@morpho-org/morpho-sdk 9.8.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/MIGRATION-v9-to-v10.md +114 -0
- package/README.md +109 -13
- 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.d.ts +3 -4
- package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +3 -2
- package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -1
- package/lib/cjs/actions/midnight/cancelAndMake.js +2 -1
- package/lib/cjs/actions/midnight/cancelOffers.d.ts +54 -0
- package/lib/cjs/actions/midnight/cancelOffers.js +108 -0
- package/lib/cjs/actions/midnight/index.d.ts +1 -0
- package/lib/cjs/actions/midnight/index.js +1 -0
- package/lib/cjs/actions/midnight/supplyCollateralBatch.js +4 -2
- package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
- package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +3 -2
- package/lib/cjs/actions/midnight/takeBorrow.d.ts +1 -1
- package/lib/cjs/actions/midnight/takeBorrow.js +3 -2
- package/lib/cjs/actions/midnight/takeLend.d.ts +1 -1
- package/lib/cjs/actions/midnight/takeLend.js +3 -2
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +3 -2
- package/lib/cjs/actions/midnight/takeWithdraw.d.ts +1 -1
- package/lib/cjs/actions/midnight/takeWithdraw.js +3 -2
- package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +4 -2
- package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
- package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
- package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
- package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +3 -3
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +5 -13
- package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
- package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
- 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/entities/blue/blue.d.ts +34 -28
- package/lib/cjs/entities/blue/blue.js +107 -77
- package/lib/cjs/entities/midnight/deadline.d.ts +2 -2
- package/lib/cjs/entities/midnight/deadline.js +4 -3
- package/lib/cjs/entities/midnight/midnight.d.ts +49 -51
- package/lib/cjs/entities/midnight/midnight.js +158 -138
- package/lib/cjs/entities/midnight/publication.d.ts +2 -0
- package/lib/cjs/entities/midnight/publication.js +193 -138
- package/lib/cjs/entities/midnight/types.d.ts +4 -4
- package/lib/cjs/entities/requirements/assertContractCode.js +4 -2
- package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
- package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +24 -28
- package/lib/cjs/entities/requirements/getErc2612Permit.js +10 -5
- package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -4
- package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
- 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.d.ts +12 -12
- package/lib/cjs/entities/vaultV1/vaultV1.js +90 -194
- 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 +16 -16
- package/lib/cjs/entities/vaultV2/vaultV2.js +94 -385
- package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +14 -0
- package/lib/cjs/entities/vaultV2BlueReallocationData.js +1599 -883
- package/lib/cjs/errors.d.ts +1 -1
- package/lib/cjs/errors.js +2 -1
- package/lib/cjs/helpers/deadShares.js +83 -47
- package/lib/cjs/helpers/encodeMidnightCalldata.js +4 -2
- package/lib/cjs/helpers/metadata.d.ts +14 -2
- package/lib/cjs/helpers/metadata.js +49 -8
- package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +44 -27
- package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +11 -2
- package/lib/cjs/helpers/utilization.js +10 -5
- package/lib/cjs/helpers/validate.js +88 -67
- 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 +177 -104
- package/lib/cjs/helpers/validatePositiveInput.js +2 -1
- package/lib/cjs/helpers/validateTakeableOffers.js +2 -1
- package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +40 -22
- package/lib/cjs/index.d.ts +2 -2
- package/lib/cjs/index.js +10 -1
- 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 +77 -24
- 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 +45 -19
- 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 +18 -33
- package/lib/cjs/transactionPlan/vaultv2/deposit.js +19 -143
- 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 +18 -29
- package/lib/cjs/transactionPlan/vaultv2/withdraw.js +21 -126
- 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.d.ts +26 -2
- package/lib/cjs/types/action.js +17 -9
- package/lib/cjs/types/error.d.ts +8 -1
- package/lib/cjs/types/error.js +21 -6
- package/lib/cjs/types/metadata.d.ts +12 -2
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.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.d.ts +3 -4
- package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +3 -2
- package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -1
- package/lib/esm/actions/midnight/cancelAndMake.js +2 -1
- package/lib/esm/actions/midnight/cancelOffers.d.ts +54 -0
- package/lib/esm/actions/midnight/cancelOffers.js +104 -0
- package/lib/esm/actions/midnight/index.d.ts +1 -0
- package/lib/esm/actions/midnight/index.js +1 -0
- package/lib/esm/actions/midnight/supplyCollateralBatch.js +4 -2
- package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
- package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +3 -2
- package/lib/esm/actions/midnight/takeBorrow.d.ts +1 -1
- package/lib/esm/actions/midnight/takeBorrow.js +3 -2
- package/lib/esm/actions/midnight/takeLend.d.ts +1 -1
- package/lib/esm/actions/midnight/takeLend.js +3 -2
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +3 -2
- package/lib/esm/actions/midnight/takeWithdraw.d.ts +1 -1
- package/lib/esm/actions/midnight/takeWithdraw.js +3 -2
- package/lib/esm/actions/midnight/withdrawCollateralBatch.js +4 -2
- package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
- package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
- package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
- package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
- package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
- package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +3 -3
- package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
- package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +7 -15
- package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
- package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
- 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/entities/blue/blue.d.ts +34 -28
- package/lib/esm/entities/blue/blue.js +107 -77
- package/lib/esm/entities/midnight/deadline.d.ts +2 -2
- package/lib/esm/entities/midnight/deadline.js +4 -3
- package/lib/esm/entities/midnight/midnight.d.ts +49 -51
- package/lib/esm/entities/midnight/midnight.js +159 -139
- package/lib/esm/entities/midnight/publication.d.ts +2 -0
- package/lib/esm/entities/midnight/publication.js +193 -138
- package/lib/esm/entities/midnight/types.d.ts +4 -4
- package/lib/esm/entities/requirements/assertContractCode.js +4 -2
- package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
- package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +25 -29
- package/lib/esm/entities/requirements/getErc2612Permit.js +10 -5
- package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -4
- package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
- 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.d.ts +12 -12
- package/lib/esm/entities/vaultV1/vaultV1.js +96 -200
- 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 +16 -16
- package/lib/esm/entities/vaultV2/vaultV2.js +102 -393
- package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +14 -0
- package/lib/esm/entities/vaultV2BlueReallocationData.js +1599 -883
- package/lib/esm/errors.d.ts +1 -1
- package/lib/esm/errors.js +1 -1
- package/lib/esm/helpers/deadShares.js +83 -47
- package/lib/esm/helpers/encodeMidnightCalldata.js +4 -2
- package/lib/esm/helpers/metadata.d.ts +14 -2
- package/lib/esm/helpers/metadata.js +48 -8
- package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +44 -27
- package/lib/esm/helpers/previewVaultV2InKindRedeem.js +11 -2
- package/lib/esm/helpers/utilization.js +10 -5
- package/lib/esm/helpers/validate.js +88 -67
- 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 +176 -103
- package/lib/esm/helpers/validatePositiveInput.js +2 -1
- package/lib/esm/helpers/validateTakeableOffers.js +2 -1
- package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +40 -22
- package/lib/esm/index.d.ts +2 -2
- package/lib/esm/index.js +1 -1
- 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 +73 -20
- 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 +45 -19
- 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 +18 -33
- package/lib/esm/transactionPlan/vaultv2/deposit.js +21 -144
- 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 +18 -29
- package/lib/esm/transactionPlan/vaultv2/withdraw.js +23 -127
- 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.d.ts +26 -2
- package/lib/esm/types/action.js +17 -9
- package/lib/esm/types/error.d.ts +8 -1
- package/lib/esm/types/error.js +21 -6
- package/lib/esm/types/metadata.d.ts +12 -2
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/package.json +15 -14
|
@@ -17,8 +17,9 @@ const createCapReserveState = (markets) => ({
|
|
|
17
17
|
});
|
|
18
18
|
const cloneCapReserveState = (state) => {
|
|
19
19
|
const touchedPairs = new Map();
|
|
20
|
-
for (const [vault, pairs] of state.touchedPairs)
|
|
20
|
+
for (const [vault, pairs] of state.touchedPairs) {
|
|
21
21
|
touchedPairs.set(vault, new Map(pairs));
|
|
22
|
+
}
|
|
22
23
|
return {
|
|
23
24
|
initialMarkets: { ...state.initialMarkets },
|
|
24
25
|
marketAccruals: new Map(state.marketAccruals),
|
|
@@ -40,8 +41,9 @@ const createSimulationContext = () => ({
|
|
|
40
41
|
* @internal
|
|
41
42
|
*/
|
|
42
43
|
const findAddressKey = (record, address) => {
|
|
43
|
-
if (Object.hasOwn(record, address))
|
|
44
|
+
if (Object.hasOwn(record, address)) {
|
|
44
45
|
return address;
|
|
46
|
+
}
|
|
45
47
|
return Object.keys(record).find((key) => (0, viem_1.isAddressEqual)(key, address));
|
|
46
48
|
};
|
|
47
49
|
/**
|
|
@@ -57,22 +59,25 @@ const findAddressKey = (record, address) => {
|
|
|
57
59
|
const getAdapterIds = (cache, adapter, market) => {
|
|
58
60
|
const key = `${adapter.address}:${market.id}`;
|
|
59
61
|
const cached = cache.get(key);
|
|
60
|
-
if (cached != null)
|
|
62
|
+
if (cached != null) {
|
|
61
63
|
return cached;
|
|
64
|
+
}
|
|
62
65
|
const ids = adapter.ids(market.params);
|
|
63
66
|
cache.set(key, ids);
|
|
64
67
|
return ids;
|
|
65
68
|
};
|
|
66
69
|
const resolveMaxPenalty = (value) => {
|
|
67
70
|
const penalty = value ?? constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY;
|
|
68
|
-
if (penalty < 0n)
|
|
71
|
+
if (penalty < 0n) {
|
|
69
72
|
throw new index_js_1.NegativeInputError("maxPenalty", penalty);
|
|
70
|
-
|
|
73
|
+
}
|
|
74
|
+
if (penalty > constant_js_1.MAX_REALLOCATION_PENALTY) {
|
|
71
75
|
throw new index_js_1.InputExceedsMaxError({
|
|
72
76
|
field: "maxPenalty",
|
|
73
77
|
value: penalty,
|
|
74
78
|
max: constant_js_1.MAX_REALLOCATION_PENALTY,
|
|
75
79
|
});
|
|
80
|
+
}
|
|
76
81
|
return penalty;
|
|
77
82
|
};
|
|
78
83
|
const getCanonicalMarket = (markets, market) => (markets[market.id] ??= new blue_sdk_1.Market({ ...market }));
|
|
@@ -95,7 +100,7 @@ const cloneAdapter = (adapter, markets) => {
|
|
|
95
100
|
parentVault: adapter.parentVault,
|
|
96
101
|
skimRecipient: adapter.skimRecipient,
|
|
97
102
|
};
|
|
98
|
-
if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2)
|
|
103
|
+
if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2) {
|
|
99
104
|
return new blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2({
|
|
100
105
|
...base,
|
|
101
106
|
marketIds: [...adapter.marketIds],
|
|
@@ -105,14 +110,17 @@ const cloneAdapter = (adapter, markets) => {
|
|
|
105
110
|
// V2 adapters can retain the canonical instance directly, so every
|
|
106
111
|
// adapter observes the same global Morpho market state.
|
|
107
112
|
adapter.markets.map((market) => getCanonicalMarket(markets, market)));
|
|
108
|
-
|
|
113
|
+
}
|
|
114
|
+
if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter) {
|
|
109
115
|
return new blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter({ ...base, marketParamsList: [...adapter.marketParamsList] }, adapter.positions.map((position) => clonePosition(position, markets)));
|
|
110
|
-
|
|
116
|
+
}
|
|
117
|
+
if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter) {
|
|
111
118
|
return new blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter({
|
|
112
119
|
...base,
|
|
113
120
|
morphoVaultV1: adapter.morphoVaultV1,
|
|
114
121
|
parentAllocation: adapter.parentAllocation,
|
|
115
122
|
}, cloneAccrualVault(adapter.accrualVaultV1, markets), adapter.shares);
|
|
123
|
+
}
|
|
116
124
|
throw new blue_sdk_1.UnsupportedVaultV2AdapterError(adapter.address);
|
|
117
125
|
};
|
|
118
126
|
const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
|
|
@@ -120,13 +128,14 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
|
|
|
120
128
|
adapterKeysToClone.has(adapter.address.toLowerCase())
|
|
121
129
|
? cloneAdapter(adapter, markets)
|
|
122
130
|
: adapter);
|
|
123
|
-
const
|
|
131
|
+
const accrualLiquidityAdapter = vault.accrualLiquidityAdapter;
|
|
132
|
+
const liquidityAdapter = accrualLiquidityAdapter == null
|
|
124
133
|
? undefined
|
|
125
|
-
: (adapters.find((adapter) => (0, viem_1.isAddressEqual)(adapter.address,
|
|
134
|
+
: (adapters.find((adapter) => (0, viem_1.isAddressEqual)(adapter.address, accrualLiquidityAdapter.address)) ??
|
|
126
135
|
(adapterKeysToClone == null ||
|
|
127
|
-
adapterKeysToClone.has(
|
|
128
|
-
? cloneAdapter(
|
|
129
|
-
:
|
|
136
|
+
adapterKeysToClone.has(accrualLiquidityAdapter.address.toLowerCase())
|
|
137
|
+
? cloneAdapter(accrualLiquidityAdapter, markets)
|
|
138
|
+
: accrualLiquidityAdapter));
|
|
130
139
|
return new blue_sdk_1.AccrualVaultV2({
|
|
131
140
|
...vault,
|
|
132
141
|
liquidityAllocations: vault.liquidityAllocations?.map((allocation) => ({
|
|
@@ -227,31 +236,11 @@ class VaultV2BlueReallocationData {
|
|
|
227
236
|
this.marketPublicAllocatorConfigs = input.marketPublicAllocatorConfigs;
|
|
228
237
|
}
|
|
229
238
|
else {
|
|
230
|
-
const
|
|
231
|
-
this.publicAllocatorConfigs = publicAllocatorConfigs;
|
|
232
|
-
|
|
233
|
-
this.
|
|
234
|
-
|
|
235
|
-
this.marketPublicAllocatorConfigs = marketPublicAllocatorConfigs;
|
|
236
|
-
for (const [vault, config] of Object.entries(input.publicAllocatorConfigs ?? {})) {
|
|
237
|
-
publicAllocatorConfigs[vault] =
|
|
238
|
-
config == null
|
|
239
|
-
? undefined
|
|
240
|
-
: new blue_sdk_1.VaultV2BluePublicAllocatorConfig(config);
|
|
241
|
-
}
|
|
242
|
-
for (const [vault, adapters] of Object.entries(input.activeAdapters ?? {})) {
|
|
243
|
-
activeAdapters[vault] =
|
|
244
|
-
adapters == null ? undefined : new Set(adapters);
|
|
245
|
-
}
|
|
246
|
-
for (const [vault, configs] of Object.entries(input.marketPublicAllocatorConfigs ?? {})) {
|
|
247
|
-
marketPublicAllocatorConfigs[vault] = {};
|
|
248
|
-
for (const [id, config] of Object.entries(configs ?? {})) {
|
|
249
|
-
marketPublicAllocatorConfigs[vault][id] =
|
|
250
|
-
config == null
|
|
251
|
-
? undefined
|
|
252
|
-
: new blue_sdk_1.VaultV2BlueMarketPublicAllocatorConfig(config);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
239
|
+
const configurations = cloneAllocatorConfigurations(input);
|
|
240
|
+
this.publicAllocatorConfigs = configurations.publicAllocatorConfigs;
|
|
241
|
+
this.activeAdapters = configurations.activeAdapters;
|
|
242
|
+
this.marketPublicAllocatorConfigs =
|
|
243
|
+
configurations.marketPublicAllocatorConfigs;
|
|
255
244
|
}
|
|
256
245
|
for (const [marketId, market] of Object.entries(input.markets ?? {})) {
|
|
257
246
|
this.mutableMarkets[marketId] =
|
|
@@ -267,14 +256,20 @@ class VaultV2BlueReallocationData {
|
|
|
267
256
|
: cloneVault(vault, { markets: this.mutableMarkets });
|
|
268
257
|
this.mutableVaults[address] = clonedVault;
|
|
269
258
|
}
|
|
259
|
+
// Populate the instance's allocation snapshots after cloning vault views.
|
|
260
|
+
this.copyAllocationSnapshots(input, isClone);
|
|
261
|
+
}
|
|
262
|
+
/** Copies allocation entries, retaining the clone path's shallow-copy semantics. @internal */
|
|
263
|
+
copyAllocationSnapshots(input, isClone) {
|
|
270
264
|
for (const [vault, allocations] of Object.entries(input.allocations ?? {})) {
|
|
271
265
|
if (isClone) {
|
|
272
266
|
this.mutableAllocations[vault] = { ...allocations };
|
|
273
267
|
continue;
|
|
274
268
|
}
|
|
275
|
-
|
|
269
|
+
const clonedAllocations = {};
|
|
270
|
+
this.mutableAllocations[vault] = clonedAllocations;
|
|
276
271
|
for (const [id, allocation] of Object.entries(allocations ?? {})) {
|
|
277
|
-
|
|
272
|
+
clonedAllocations[id] =
|
|
278
273
|
allocation == null ? undefined : { ...allocation };
|
|
279
274
|
}
|
|
280
275
|
}
|
|
@@ -338,8 +333,9 @@ class VaultV2BlueReallocationData {
|
|
|
338
333
|
*/
|
|
339
334
|
getMarket(marketId) {
|
|
340
335
|
const market = this.mutableMarkets[marketId];
|
|
341
|
-
if (market == null)
|
|
336
|
+
if (market == null) {
|
|
342
337
|
throw new index_js_1.UnknownReallocationMarketError(marketId);
|
|
338
|
+
}
|
|
343
339
|
return market;
|
|
344
340
|
}
|
|
345
341
|
/**
|
|
@@ -376,8 +372,9 @@ class VaultV2BlueReallocationData {
|
|
|
376
372
|
getMutableVault(vault) {
|
|
377
373
|
const key = findAddressKey(this.mutableVaults, vault);
|
|
378
374
|
const data = key == null ? undefined : this.mutableVaults[key];
|
|
379
|
-
if (data == null)
|
|
375
|
+
if (data == null) {
|
|
380
376
|
throw new index_js_1.UnknownReallocationVaultError(vault);
|
|
377
|
+
}
|
|
381
378
|
return data;
|
|
382
379
|
}
|
|
383
380
|
/**
|
|
@@ -416,8 +413,9 @@ class VaultV2BlueReallocationData {
|
|
|
416
413
|
getAllocation(vault, id) {
|
|
417
414
|
const key = findAddressKey(this.allocations, vault);
|
|
418
415
|
const allocation = key == null ? undefined : this.allocations[key]?.[id];
|
|
419
|
-
if (allocation == null)
|
|
416
|
+
if (allocation == null) {
|
|
420
417
|
throw new index_js_1.UnknownReallocationAllocationError(vault, id);
|
|
418
|
+
}
|
|
421
419
|
return allocation;
|
|
422
420
|
}
|
|
423
421
|
/**
|
|
@@ -451,8 +449,9 @@ class VaultV2BlueReallocationData {
|
|
|
451
449
|
*/
|
|
452
450
|
getPublicAllocatorConfig(vault) {
|
|
453
451
|
const config = this.getOptionalPublicAllocatorConfig(vault);
|
|
454
|
-
if (config == null)
|
|
452
|
+
if (config == null) {
|
|
455
453
|
throw new index_js_1.UnknownReallocationPublicAllocatorConfigError(vault);
|
|
454
|
+
}
|
|
456
455
|
return config;
|
|
457
456
|
}
|
|
458
457
|
/**
|
|
@@ -464,8 +463,9 @@ class VaultV2BlueReallocationData {
|
|
|
464
463
|
*/
|
|
465
464
|
getOptionalPublicAllocatorConfig(vault) {
|
|
466
465
|
const key = findAddressKey(this.publicAllocatorConfigs, vault);
|
|
467
|
-
if (key == null)
|
|
466
|
+
if (key == null) {
|
|
468
467
|
throw new index_js_1.UnknownReallocationPublicAllocatorConfigError(vault);
|
|
468
|
+
}
|
|
469
469
|
return this.publicAllocatorConfigs[key];
|
|
470
470
|
}
|
|
471
471
|
/**
|
|
@@ -498,8 +498,9 @@ class VaultV2BlueReallocationData {
|
|
|
498
498
|
getActiveAdapters(vault) {
|
|
499
499
|
const key = findAddressKey(this.activeAdapters, vault);
|
|
500
500
|
const adapters = key == null ? undefined : this.activeAdapters[key];
|
|
501
|
-
if (adapters == null)
|
|
501
|
+
if (adapters == null) {
|
|
502
502
|
throw new index_js_1.UnknownReallocationActiveAdaptersError(vault);
|
|
503
|
+
}
|
|
503
504
|
return adapters;
|
|
504
505
|
}
|
|
505
506
|
/**
|
|
@@ -543,8 +544,9 @@ class VaultV2BlueReallocationData {
|
|
|
543
544
|
const config = key == null
|
|
544
545
|
? undefined
|
|
545
546
|
: this.marketPublicAllocatorConfigs[key]?.[adapterMarketCapId];
|
|
546
|
-
if (config == null)
|
|
547
|
+
if (config == null) {
|
|
547
548
|
throw new index_js_1.UnknownReallocationMarketPublicAllocatorConfigError(vault, adapterMarketCapId);
|
|
549
|
+
}
|
|
548
550
|
return config;
|
|
549
551
|
}
|
|
550
552
|
/**
|
|
@@ -583,8 +585,9 @@ class VaultV2BlueReallocationData {
|
|
|
583
585
|
getMutableAdapter(vault, adapter) {
|
|
584
586
|
const data = this.getMutableVault(vault).accrualAdapters.find((candidate) => candidate instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2 &&
|
|
585
587
|
(0, viem_1.isAddressEqual)(candidate.address, adapter));
|
|
586
|
-
if (data == null)
|
|
588
|
+
if (data == null) {
|
|
587
589
|
throw new index_js_1.UnknownReallocationAdapterError(vault, adapter);
|
|
590
|
+
}
|
|
588
591
|
return data;
|
|
589
592
|
}
|
|
590
593
|
/**
|
|
@@ -710,8 +713,9 @@ class VaultV2BlueReallocationData {
|
|
|
710
713
|
* ```
|
|
711
714
|
*/
|
|
712
715
|
computeVaultV2BlueReallocations(marketId, options = {}) {
|
|
713
|
-
if (options.enabled === false)
|
|
716
|
+
if (options.enabled === false) {
|
|
714
717
|
return { reallocations: [], data: this };
|
|
718
|
+
}
|
|
715
719
|
const maxWithdrawalUtilization = (0, utilization_js_1.resolveMaxWithdrawalUtilization)(options.maxWithdrawalUtilization);
|
|
716
720
|
const maxPenalty = resolveMaxPenalty(options.maxPenalty);
|
|
717
721
|
const capAccrualBuffer = (0, utilization_js_1.resolveCapAccrualBuffer)(options.capAccrualBuffer);
|
|
@@ -730,16 +734,63 @@ class VaultV2BlueReallocationData {
|
|
|
730
734
|
return { reallocations, data };
|
|
731
735
|
}
|
|
732
736
|
const { amount, type } = operation;
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
const
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
if (
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
737
|
+
const feeAssets = resolveOperationFeeAssets(operation);
|
|
738
|
+
const { normalizedOptions, market, hasExplicitBlueBalance, blueBalance } = this.resolveOperationSnapshot({ marketId, options, resolvedOptions });
|
|
739
|
+
const { newTotalBorrowAssets, newTotalSupplyAssets } = getOperationMarketTotals({ market, marketId, type, amount, feeAssets });
|
|
740
|
+
const requiredAssets = blue_sdk_1.MathLib.wDivUp(newTotalBorrowAssets, constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION) -
|
|
741
|
+
newTotalSupplyAssets;
|
|
742
|
+
if (blue_sdk_1.MarketUtils.getUtilization({
|
|
743
|
+
totalSupplyAssets: newTotalSupplyAssets,
|
|
744
|
+
totalBorrowAssets: newTotalBorrowAssets,
|
|
745
|
+
}) <= constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION ||
|
|
746
|
+
requiredAssets <= 0n) {
|
|
747
|
+
const data = this.clone();
|
|
748
|
+
data.setMarkets([market]);
|
|
749
|
+
return { reallocations: [], data };
|
|
750
|
+
}
|
|
751
|
+
const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
|
|
752
|
+
? newTotalBorrowAssets - newTotalSupplyAssets
|
|
742
753
|
: 0n;
|
|
754
|
+
const penaltyTiers = [
|
|
755
|
+
0n,
|
|
756
|
+
...new Set(Object.values(this.publicAllocatorConfigs).flatMap((config) => config != null && config.penalty > 0n && config.penalty <= maxPenalty
|
|
757
|
+
? [config.penalty]
|
|
758
|
+
: [])),
|
|
759
|
+
].sort((0, morpho_ts_1.bigIntComparator)((tier) => tier));
|
|
760
|
+
const plan = (maxAssets, { headroom, usePhysicalBalance = false, }) => planVaultOperation({
|
|
761
|
+
maxAssets,
|
|
762
|
+
headroom,
|
|
763
|
+
usePhysicalBalance,
|
|
764
|
+
absoluteShortfall,
|
|
765
|
+
penaltyTiers,
|
|
766
|
+
type,
|
|
767
|
+
maxWithdrawalUtilization,
|
|
768
|
+
amount,
|
|
769
|
+
feeAssets,
|
|
770
|
+
blueBalance,
|
|
771
|
+
capAccrualBuffer,
|
|
772
|
+
normalizedOptions,
|
|
773
|
+
hasExplicitBlueBalance,
|
|
774
|
+
marketId,
|
|
775
|
+
initialData: this,
|
|
776
|
+
initialMarkets: this.mutableMarkets,
|
|
777
|
+
runUtilizationPass: (data, args) => data.computeVaultV2BlueReallocationsAtUtilizationInPlace(args),
|
|
778
|
+
});
|
|
779
|
+
return selectOperationPlan({
|
|
780
|
+
plan,
|
|
781
|
+
requiredAssets,
|
|
782
|
+
allocatorCapHeadroom,
|
|
783
|
+
absoluteShortfall,
|
|
784
|
+
hasExplicitBlueBalance,
|
|
785
|
+
marketId,
|
|
786
|
+
type,
|
|
787
|
+
amount,
|
|
788
|
+
blueBalance,
|
|
789
|
+
feeAssets,
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
/** Resolves the operation's accrued market and shared-Blue liquidity snapshot. @internal */
|
|
793
|
+
resolveOperationSnapshot({ marketId, options, resolvedOptions, }) {
|
|
743
794
|
const timestamp = options.timestamp == null
|
|
744
795
|
? this.getLatestSnapshotTimestamp()
|
|
745
796
|
: BigInt(options.timestamp);
|
|
@@ -762,370 +813,10 @@ class VaultV2BlueReallocationData {
|
|
|
762
813
|
? total +
|
|
763
814
|
blue_sdk_1.MathLib.zeroFloorSub(snapshotMarket.totalSupplyAssets, snapshotMarket.totalBorrowAssets)
|
|
764
815
|
: total, 0n);
|
|
765
|
-
|
|
766
|
-
const penaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
|
|
767
|
-
if (penaltyAssets === 0n)
|
|
768
|
-
return 0n;
|
|
769
|
-
let shortfall = blue_sdk_1.MathLib.zeroFloorSub(penaltyAssets, blueBalance);
|
|
770
|
-
let balance = blue_sdk_1.MathLib.zeroFloorSub(blueBalance, penaltyAssets);
|
|
771
|
-
for (const { from, assets } of reallocations) {
|
|
772
|
-
if (from.type === "idle")
|
|
773
|
-
balance += assets;
|
|
774
|
-
else
|
|
775
|
-
shortfall = blue_sdk_1.MathLib.max(shortfall, blue_sdk_1.MathLib.zeroFloorSub(assets, balance));
|
|
776
|
-
}
|
|
777
|
-
return shortfall;
|
|
778
|
-
};
|
|
779
|
-
if (type === "withdraw" && amount > market.totalSupplyAssets) {
|
|
780
|
-
throw new index_js_1.ReallocationWithdrawExceedsMarketSupplyError({
|
|
781
|
-
marketId,
|
|
782
|
-
withdrawAmount: amount,
|
|
783
|
-
totalSupplyAssets: market.totalSupplyAssets,
|
|
784
|
-
});
|
|
785
|
-
}
|
|
786
|
-
const newTotalBorrowAssets = type === "borrow"
|
|
787
|
-
? market.totalBorrowAssets + amount
|
|
788
|
-
: type === "refinance"
|
|
789
|
-
? market.totalBorrowAssets + amount + feeAssets
|
|
790
|
-
: market.totalBorrowAssets;
|
|
791
|
-
const newTotalSupplyAssets = type === "withdraw"
|
|
792
|
-
? market.totalSupplyAssets - amount
|
|
793
|
-
: market.totalSupplyAssets;
|
|
794
|
-
const requiredAssets = blue_sdk_1.MathLib.wDivUp(newTotalBorrowAssets, constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION) -
|
|
795
|
-
newTotalSupplyAssets;
|
|
796
|
-
if (blue_sdk_1.MarketUtils.getUtilization({
|
|
797
|
-
totalSupplyAssets: newTotalSupplyAssets,
|
|
798
|
-
totalBorrowAssets: newTotalBorrowAssets,
|
|
799
|
-
}) <= constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION ||
|
|
800
|
-
requiredAssets <= 0n) {
|
|
801
|
-
const data = this.clone();
|
|
802
|
-
data.setMarkets([market]);
|
|
803
|
-
return { reallocations: [], data };
|
|
804
|
-
}
|
|
805
|
-
const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
|
|
806
|
-
? newTotalBorrowAssets - newTotalSupplyAssets
|
|
807
|
-
: 0n;
|
|
808
|
-
const penaltyTiers = [
|
|
809
|
-
0n,
|
|
810
|
-
...new Set(Object.values(this.publicAllocatorConfigs).flatMap((config) => config != null && config.penalty > 0n && config.penalty <= maxPenalty
|
|
811
|
-
? [config.penalty]
|
|
812
|
-
: [])),
|
|
813
|
-
].sort((0, morpho_ts_1.bigIntComparator)((tier) => tier));
|
|
814
|
-
const plan = (maxAssets, { headroom, usePhysicalBalance = false, }) => {
|
|
815
|
-
let reserves = createCapReserveState(this.mutableMarkets);
|
|
816
|
-
const reallocations = [];
|
|
817
|
-
let data = this.clone();
|
|
818
|
-
let context = createSimulationContext();
|
|
819
|
-
let remainingShortfall = absoluteShortfall;
|
|
820
|
-
let accountingShortfall = absoluteShortfall;
|
|
821
|
-
let allocatorCapBoundTargets = new Set();
|
|
822
|
-
let idleBoundVaults = new Set();
|
|
823
|
-
for (const penalty of penaltyTiers) {
|
|
824
|
-
if (type === "refinance" && penalty === blue_sdk_1.MathLib.WAD)
|
|
825
|
-
continue;
|
|
826
|
-
let isFriendlyPass = true;
|
|
827
|
-
let triedFullCapacityAttempt = false;
|
|
828
|
-
for (const utilization of [maxWithdrawalUtilization, blue_sdk_1.MathLib.WAD]) {
|
|
829
|
-
const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
|
|
830
|
-
isFriendlyPass = false;
|
|
831
|
-
if (remainingShortfall === 0n && !isFreeFriendlyPass)
|
|
832
|
-
continue;
|
|
833
|
-
let passMaxAssets = type === "refinance" && penalty > 0n
|
|
834
|
-
? blue_sdk_1.MathLib.mulDivUp(remainingShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - penalty)
|
|
835
|
-
: isFreeFriendlyPass
|
|
836
|
-
? maxAssets
|
|
837
|
-
: remainingShortfall;
|
|
838
|
-
if (usePhysicalBalance && penalty > 0n) {
|
|
839
|
-
const penaltyMultiplier = type === "refinance" ? 2n : 1n;
|
|
840
|
-
const physicalPenalty = penaltyMultiplier * penalty;
|
|
841
|
-
if (physicalPenalty < blue_sdk_1.MathLib.WAD) {
|
|
842
|
-
const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
|
|
843
|
-
// Idle must fund both the operation and its penalty flash loan.
|
|
844
|
-
const physicalShortfall = blue_sdk_1.MathLib.zeroFloorSub(amount +
|
|
845
|
-
feeAssets +
|
|
846
|
-
penaltyMultiplier *
|
|
847
|
-
(0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations), blueBalance + idleAssets);
|
|
848
|
-
passMaxAssets = blue_sdk_1.MathLib.max(passMaxAssets, blue_sdk_1.MathLib.mulDivUp(physicalShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - physicalPenalty));
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
const retryPaidPass = penalty > 0n;
|
|
852
|
-
let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
|
|
853
|
-
let tryFullCapacityAttempt = false;
|
|
854
|
-
let isFullCapacityRetryPath = false;
|
|
855
|
-
const beforePassRemainingShortfall = remainingShortfall;
|
|
856
|
-
const beforePassAccountingShortfall = accountingShortfall;
|
|
857
|
-
// Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
|
|
858
|
-
const passStart = retryPaidPass
|
|
859
|
-
? {
|
|
860
|
-
data: data.clone(),
|
|
861
|
-
context,
|
|
862
|
-
reserves: cloneCapReserveState(reserves),
|
|
863
|
-
reallocationCount: reallocations.length,
|
|
864
|
-
}
|
|
865
|
-
: undefined;
|
|
866
|
-
let previousPassReallocatedAssets = 0n;
|
|
867
|
-
let previousPhysicalShortfall;
|
|
868
|
-
let hi;
|
|
869
|
-
let bestAttempt;
|
|
870
|
-
while (true) {
|
|
871
|
-
const isFullCapacityAttempt = tryFullCapacityAttempt;
|
|
872
|
-
tryFullCapacityAttempt = false;
|
|
873
|
-
if (passStart != null) {
|
|
874
|
-
data = passStart.data.clone();
|
|
875
|
-
context = passStart.context;
|
|
876
|
-
reserves = cloneCapReserveState(passStart.reserves);
|
|
877
|
-
reallocations.length = passStart.reallocationCount;
|
|
878
|
-
}
|
|
879
|
-
const pass = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
|
|
880
|
-
context,
|
|
881
|
-
reserves,
|
|
882
|
-
marketId,
|
|
883
|
-
maxWithdrawalUtilization: utilization,
|
|
884
|
-
maxAssets: isFullCapacityAttempt ? undefined : passMaxAssets,
|
|
885
|
-
capAccrualBuffer,
|
|
886
|
-
allocatorCapHeadroom: headroom,
|
|
887
|
-
penalty,
|
|
888
|
-
options: normalizedOptions,
|
|
889
|
-
});
|
|
890
|
-
reallocations.push(...pass.reallocations);
|
|
891
|
-
data = pass.data;
|
|
892
|
-
context = pass.context;
|
|
893
|
-
if (isFreeFriendlyPass) {
|
|
894
|
-
allocatorCapBoundTargets = pass.allocatorCapBoundTargets;
|
|
895
|
-
idleBoundVaults = pass.idleBoundVaults;
|
|
896
|
-
}
|
|
897
|
-
const currentMarket = data.getMarket(marketId);
|
|
898
|
-
const penaltyAssets = type === "refinance"
|
|
899
|
-
? (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations)
|
|
900
|
-
: 0n;
|
|
901
|
-
const borrow = type === "borrow"
|
|
902
|
-
? currentMarket.totalBorrowAssets + amount
|
|
903
|
-
: type === "refinance"
|
|
904
|
-
? currentMarket.totalBorrowAssets +
|
|
905
|
-
amount +
|
|
906
|
-
feeAssets +
|
|
907
|
-
penaltyAssets
|
|
908
|
-
: currentMarket.totalBorrowAssets;
|
|
909
|
-
const supply = type === "withdraw"
|
|
910
|
-
? currentMarket.totalSupplyAssets - amount
|
|
911
|
-
: currentMarket.totalSupplyAssets;
|
|
912
|
-
accountingShortfall = borrow > supply ? borrow - supply : 0n;
|
|
913
|
-
const penaltyForPhysicalShortfall = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
|
|
914
|
-
const idleAssetsForPhysicalShortfall = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
|
|
915
|
-
const physicalShortfall = penaltyForPhysicalShortfall === 0n
|
|
916
|
-
? 0n
|
|
917
|
-
: blue_sdk_1.MathLib.zeroFloorSub((type === "refinance"
|
|
918
|
-
? amount + feeAssets + penaltyForPhysicalShortfall
|
|
919
|
-
: amount) + penaltyForPhysicalShortfall, blueBalance + idleAssetsForPhysicalShortfall);
|
|
920
|
-
remainingShortfall = blue_sdk_1.MathLib.max(accountingShortfall, physicalShortfall);
|
|
921
|
-
const attemptTransferShortfall = hasExplicitBlueBalance && isFullCapacityRetryPath
|
|
922
|
-
? getTransferShortfall(reallocations)
|
|
923
|
-
: 0n;
|
|
924
|
-
const attemptCoversShortfall = remainingShortfall === 0n;
|
|
925
|
-
const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
|
|
926
|
-
if (passStart == null)
|
|
927
|
-
break;
|
|
928
|
-
if (isFullCapacityAttempt)
|
|
929
|
-
passMaxAssets = passReallocatedAssets;
|
|
930
|
-
const improvesAccounting = accountingShortfall < beforePassAccountingShortfall;
|
|
931
|
-
const attemptPriority = hasExplicitBlueBalance
|
|
932
|
-
? [0n, remainingShortfall, 0n, passReallocatedAssets]
|
|
933
|
-
: [
|
|
934
|
-
improvesAccounting ? 0n : 1n,
|
|
935
|
-
improvesAccounting ? accountingShortfall : 0n,
|
|
936
|
-
remainingShortfall,
|
|
937
|
-
passReallocatedAssets,
|
|
938
|
-
];
|
|
939
|
-
const previousBestAttempt = bestAttempt;
|
|
940
|
-
let isBetterAttempt = previousBestAttempt == null;
|
|
941
|
-
if (previousBestAttempt != null) {
|
|
942
|
-
const firstDifference = attemptPriority.findIndex((priority, index) => priority !== previousBestAttempt.priority[index]);
|
|
943
|
-
isBetterAttempt =
|
|
944
|
-
firstDifference !== -1 &&
|
|
945
|
-
attemptPriority[firstDifference] <
|
|
946
|
-
previousBestAttempt.priority[firstDifference];
|
|
947
|
-
}
|
|
948
|
-
if (isBetterAttempt &&
|
|
949
|
-
(!isFullCapacityRetryPath ||
|
|
950
|
-
(attemptCoversShortfall && attemptTransferShortfall === 0n)))
|
|
951
|
-
bestAttempt = {
|
|
952
|
-
data,
|
|
953
|
-
context,
|
|
954
|
-
reserves: cloneCapReserveState(reserves),
|
|
955
|
-
reallocations: pass.reallocations,
|
|
956
|
-
remainingShortfall,
|
|
957
|
-
accountingShortfall,
|
|
958
|
-
passReallocatedAssets,
|
|
959
|
-
priority: attemptPriority,
|
|
960
|
-
};
|
|
961
|
-
if (attemptCoversShortfall)
|
|
962
|
-
hi = hi == null ? passMaxAssets : blue_sdk_1.MathLib.min(hi, passMaxAssets);
|
|
963
|
-
else
|
|
964
|
-
lo = blue_sdk_1.MathLib.max(lo, passMaxAssets);
|
|
965
|
-
if (hi != null) {
|
|
966
|
-
if (hi - lo <= 1n)
|
|
967
|
-
break;
|
|
968
|
-
passMaxAssets = (lo + hi) / 2n;
|
|
969
|
-
continue;
|
|
970
|
-
}
|
|
971
|
-
if (isFullCapacityAttempt && !attemptCoversShortfall)
|
|
972
|
-
break;
|
|
973
|
-
if (accountingShortfall === 0n &&
|
|
974
|
-
previousPhysicalShortfall != null &&
|
|
975
|
-
physicalShortfall >= previousPhysicalShortfall) {
|
|
976
|
-
if (!triedFullCapacityAttempt &&
|
|
977
|
-
passReallocatedAssets === passMaxAssets) {
|
|
978
|
-
triedFullCapacityAttempt = true;
|
|
979
|
-
tryFullCapacityAttempt = true;
|
|
980
|
-
isFullCapacityRetryPath = true;
|
|
981
|
-
continue;
|
|
982
|
-
}
|
|
983
|
-
break;
|
|
984
|
-
}
|
|
985
|
-
previousPhysicalShortfall = physicalShortfall;
|
|
986
|
-
if (passReallocatedAssets <= previousPassReallocatedAssets ||
|
|
987
|
-
penalty === blue_sdk_1.MathLib.WAD)
|
|
988
|
-
break;
|
|
989
|
-
previousPassReallocatedAssets = passReallocatedAssets;
|
|
990
|
-
passMaxAssets += blue_sdk_1.MathLib.mulDivUp(remainingShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - penalty);
|
|
991
|
-
}
|
|
992
|
-
if (passStart != null) {
|
|
993
|
-
const improved = bestAttempt != null &&
|
|
994
|
-
(hasExplicitBlueBalance
|
|
995
|
-
? bestAttempt.remainingShortfall < beforePassRemainingShortfall
|
|
996
|
-
: bestAttempt.accountingShortfall <
|
|
997
|
-
beforePassAccountingShortfall ||
|
|
998
|
-
bestAttempt.remainingShortfall <
|
|
999
|
-
beforePassRemainingShortfall);
|
|
1000
|
-
if (improved && bestAttempt != null) {
|
|
1001
|
-
data = bestAttempt.data;
|
|
1002
|
-
context = bestAttempt.context;
|
|
1003
|
-
reserves = cloneCapReserveState(bestAttempt.reserves);
|
|
1004
|
-
reallocations.length = passStart.reallocationCount;
|
|
1005
|
-
reallocations.push(...bestAttempt.reallocations);
|
|
1006
|
-
remainingShortfall = bestAttempt.remainingShortfall;
|
|
1007
|
-
accountingShortfall = bestAttempt.accountingShortfall;
|
|
1008
|
-
}
|
|
1009
|
-
else {
|
|
1010
|
-
data = passStart.data;
|
|
1011
|
-
context = passStart.context;
|
|
1012
|
-
reserves = cloneCapReserveState(passStart.reserves);
|
|
1013
|
-
reallocations.length = passStart.reallocationCount;
|
|
1014
|
-
remainingShortfall = beforePassRemainingShortfall;
|
|
1015
|
-
accountingShortfall = beforePassAccountingShortfall;
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
let reallocatedAssets = 0n;
|
|
1021
|
-
let unboundAssets = 0n;
|
|
1022
|
-
for (const { vault, from, to, assets } of reallocations) {
|
|
1023
|
-
reallocatedAssets += assets;
|
|
1024
|
-
const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
|
|
1025
|
-
if (!allocatorCapBoundTargets.has(key) &&
|
|
1026
|
-
!(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
|
|
1027
|
-
unboundAssets += assets;
|
|
1028
|
-
}
|
|
1029
|
-
const penaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
|
|
1030
|
-
const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
|
|
1031
|
-
const physicalShortfall = penaltyAssets === 0n
|
|
1032
|
-
? 0n
|
|
1033
|
-
: blue_sdk_1.MathLib.zeroFloorSub((type === "refinance"
|
|
1034
|
-
? amount + feeAssets + penaltyAssets
|
|
1035
|
-
: amount) + penaltyAssets, blueBalance + idleAssets);
|
|
1036
|
-
const transferShortfall = getTransferShortfall(reallocations);
|
|
1037
|
-
const coversAccountingShortfall = type === "refinance"
|
|
1038
|
-
? reallocatedAssets >= absoluteShortfall + penaltyAssets
|
|
1039
|
-
: reallocatedAssets >= absoluteShortfall;
|
|
1040
|
-
return {
|
|
1041
|
-
maxAssets,
|
|
1042
|
-
headroom,
|
|
1043
|
-
reallocations,
|
|
1044
|
-
data,
|
|
1045
|
-
liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
|
|
1046
|
-
reallocatedAssets,
|
|
1047
|
-
unboundAssets,
|
|
1048
|
-
physicalShortfall,
|
|
1049
|
-
coversShortfall: coversAccountingShortfall &&
|
|
1050
|
-
(type === "refinance" || penaltyAssets <= amount) &&
|
|
1051
|
-
(!hasExplicitBlueBalance ||
|
|
1052
|
-
(physicalShortfall === 0n && transferShortfall === 0n)),
|
|
1053
|
-
};
|
|
1054
|
-
};
|
|
1055
|
-
// A leg that fills an allocator cap, or idle legs that together take
|
|
1056
|
-
// (nearly) all of a source vault's starting idle, revert once another
|
|
1057
|
-
// allocation lands first. A bound plan therefore moves only the operation's
|
|
1058
|
-
// shortfall, or what unbound legs moved.
|
|
1059
|
-
const target = plan(requiredAssets, { headroom: allocatorCapHeadroom });
|
|
1060
|
-
let selected = target;
|
|
1061
|
-
if (allocatorCapHeadroom > 0n && target.liquidityBound) {
|
|
1062
|
-
selected = plan(absoluteShortfall > target.unboundAssets
|
|
1063
|
-
? absoluteShortfall
|
|
1064
|
-
: target.unboundAssets, { headroom: allocatorCapHeadroom });
|
|
1065
|
-
// Shared-cap fitting is not monotonic in the budget.
|
|
1066
|
-
if (!selected.coversShortfall && target.coversShortfall)
|
|
1067
|
-
selected = target;
|
|
1068
|
-
}
|
|
1069
|
-
let available = blue_sdk_1.MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
|
|
1070
|
-
// Without headroom, `target` already is the full-cap plan toward the target.
|
|
1071
|
-
const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
|
|
1072
|
-
for (const maxAssets of fullCapBudgets) {
|
|
1073
|
-
if (selected.coversShortfall)
|
|
1074
|
-
break;
|
|
1075
|
-
selected = plan(maxAssets, { headroom: 0n });
|
|
1076
|
-
if (selected.reallocatedAssets > available)
|
|
1077
|
-
available = selected.reallocatedAssets;
|
|
1078
|
-
}
|
|
1079
|
-
if (!selected.coversShortfall) {
|
|
1080
|
-
const selectedTransferShortfall = hasExplicitBlueBalance
|
|
1081
|
-
? getTransferShortfall(selected.reallocations)
|
|
1082
|
-
: 0n;
|
|
1083
|
-
const selectedPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations);
|
|
1084
|
-
if (type !== "refinance" &&
|
|
1085
|
-
selectedPenaltyAssets > amount &&
|
|
1086
|
-
selected.reallocatedAssets >= absoluteShortfall &&
|
|
1087
|
-
(!hasExplicitBlueBalance ||
|
|
1088
|
-
(selected.physicalShortfall === 0n &&
|
|
1089
|
-
selectedTransferShortfall === 0n)))
|
|
1090
|
-
throw new index_js_1.InputExceedsMaxError({
|
|
1091
|
-
field: "reallocationPenaltyAssets",
|
|
1092
|
-
value: selectedPenaltyAssets,
|
|
1093
|
-
max: amount,
|
|
1094
|
-
});
|
|
1095
|
-
throw new index_js_1.InsufficientSharedLiquidityError({
|
|
1096
|
-
marketId,
|
|
1097
|
-
shortfall: blue_sdk_1.MathLib.max(absoluteShortfall +
|
|
1098
|
-
(type === "refinance"
|
|
1099
|
-
? (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations)
|
|
1100
|
-
: 0n), selected.reallocatedAssets +
|
|
1101
|
-
(hasExplicitBlueBalance
|
|
1102
|
-
? blue_sdk_1.MathLib.max(selected.physicalShortfall, selectedTransferShortfall)
|
|
1103
|
-
: 0n)),
|
|
1104
|
-
available,
|
|
1105
|
-
});
|
|
1106
|
-
}
|
|
1107
|
-
const selectedPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations);
|
|
1108
|
-
if (hasExplicitBlueBalance &&
|
|
1109
|
-
selectedPenaltyAssets > 1n &&
|
|
1110
|
-
blueBalance <
|
|
1111
|
-
amount +
|
|
1112
|
-
feeAssets +
|
|
1113
|
-
(type === "refinance" ? 2n : 1n) * selectedPenaltyAssets) {
|
|
1114
|
-
// Amount feasibility is not monotonic: retain the original plan unless
|
|
1115
|
-
// the physical-balance seed finds a fully funded, strictly cheaper one.
|
|
1116
|
-
const alternative = plan(selected.maxAssets, {
|
|
1117
|
-
headroom: selected.headroom,
|
|
1118
|
-
usePhysicalBalance: true,
|
|
1119
|
-
});
|
|
1120
|
-
if (alternative.coversShortfall &&
|
|
1121
|
-
(0, common_js_1.getBlueBundlesV1PenaltyAssets)(alternative.reallocations) <
|
|
1122
|
-
(0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations))
|
|
1123
|
-
selected = alternative;
|
|
1124
|
-
}
|
|
1125
|
-
return { reallocations: selected.reallocations, data: selected.data };
|
|
816
|
+
return { normalizedOptions, market, hasExplicitBlueBalance, blueBalance };
|
|
1126
817
|
}
|
|
1127
818
|
computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
|
|
1128
|
-
if (options.enabled === false)
|
|
819
|
+
if (options.enabled === false) {
|
|
1129
820
|
return {
|
|
1130
821
|
reallocations: [],
|
|
1131
822
|
data: this,
|
|
@@ -1133,6 +824,7 @@ class VaultV2BlueReallocationData {
|
|
|
1133
824
|
allocatorCapBoundTargets: new Set(),
|
|
1134
825
|
idleBoundVaults: new Set(),
|
|
1135
826
|
};
|
|
827
|
+
}
|
|
1136
828
|
this.getMarket(marketId);
|
|
1137
829
|
const timestamp = options.timestamp == null
|
|
1138
830
|
? this.getLatestSnapshotTimestamp()
|
|
@@ -1154,298 +846,45 @@ class VaultV2BlueReallocationData {
|
|
|
1154
846
|
const idleBoundVaults = new Set();
|
|
1155
847
|
const initialIdleAssets = new Map();
|
|
1156
848
|
const idleTakenAssets = new Map();
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
|
|
1164
|
-
if (touched != null)
|
|
1165
|
-
return touched;
|
|
1166
|
-
const shares = adapter.supplyShares[market.id] ?? 0n;
|
|
1167
|
-
return {
|
|
1168
|
-
key,
|
|
1169
|
-
ids: getAdapterIds(adapterIdsCache, adapter, market),
|
|
1170
|
-
reserve: (reserveState) => {
|
|
1171
|
-
let reserve = reserveState.reserveByPairKey.get(key);
|
|
1172
|
-
if (reserve == null) {
|
|
1173
|
-
let accruals = reserveState.marketAccruals.get(market.id);
|
|
1174
|
-
if (accruals == null) {
|
|
1175
|
-
const initialMarket = reserveState.initialMarkets[market.id];
|
|
1176
|
-
if (initialMarket == null)
|
|
1177
|
-
throw new index_js_1.UnknownReallocationMarketError(market.id);
|
|
1178
|
-
accruals = [
|
|
1179
|
-
initialMarket.accrueInterest(timestamp),
|
|
1180
|
-
initialMarket.accrueInterest(timestamp + capAccrualBuffer),
|
|
1181
|
-
];
|
|
1182
|
-
reserveState.marketAccruals.set(market.id, accruals);
|
|
1183
|
-
}
|
|
1184
|
-
const [atTimestamp, projected] = accruals;
|
|
1185
|
-
reserve = blue_sdk_1.MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
|
|
1186
|
-
reserveState.reserveByPairKey.set(key, reserve);
|
|
1187
|
-
}
|
|
1188
|
-
return reserve;
|
|
1189
|
-
},
|
|
1190
|
-
};
|
|
1191
|
-
};
|
|
1192
|
-
// biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
|
|
1193
|
-
const capReserve = (vault, id, candidatePairs) => {
|
|
1194
|
-
let reserve = 0n;
|
|
1195
|
-
const seen = new Set();
|
|
1196
|
-
for (const pair of [
|
|
1197
|
-
...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
|
|
1198
|
-
...candidatePairs,
|
|
1199
|
-
]) {
|
|
1200
|
-
if (seen.has(pair.key) || !pair.ids.includes(id))
|
|
1201
|
-
continue;
|
|
1202
|
-
seen.add(pair.key);
|
|
1203
|
-
reserve += pair.reserve(reserves);
|
|
1204
|
-
}
|
|
1205
|
-
return reserve;
|
|
1206
|
-
};
|
|
849
|
+
const { getPair, capReserve } = createCapReserveResolvers({
|
|
850
|
+
reserves,
|
|
851
|
+
adapterIdsCache,
|
|
852
|
+
timestamp,
|
|
853
|
+
capAccrualBuffer,
|
|
854
|
+
});
|
|
1207
855
|
while (remainingAssets == null || remainingAssets > 0n) {
|
|
1208
856
|
const candidates = vaults
|
|
1209
857
|
.map((vaultAddress) => {
|
|
1210
|
-
const
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
:
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
activeAdaptersCache
|
|
1234
|
-
}
|
|
1235
|
-
const targetSupplyHeadroom = blue_sdk_1.MathLib.zeroFloorSub(blue_sdk_1.MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
|
|
1236
|
-
const minimumSupply = targetMarket.supply(1n, 0n);
|
|
1237
|
-
const rawCandidates = [];
|
|
1238
|
-
// Missing nested allocator state means the snapshot is incomplete, so
|
|
1239
|
-
// typed getter errors below must propagate. Only explicit zero caps or
|
|
1240
|
-
// disabled permissions make an adapter ineligible.
|
|
1241
|
-
for (const adapter of vault.accrualAdapters) {
|
|
1242
|
-
if (!(adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2))
|
|
1243
|
-
continue;
|
|
1244
|
-
if (!(0, viem_1.isAddressEqual)(adapter.parentVault, vaultAddress))
|
|
1245
|
-
continue;
|
|
1246
|
-
if (!(0, viem_1.isAddressEqual)(targetMarket.params.loanToken, vault.asset) ||
|
|
1247
|
-
!(0, viem_1.isAddressEqual)(targetMarket.params.irm, adapter.adaptiveCurveIrm))
|
|
1248
|
-
continue;
|
|
1249
|
-
const targetPair = getPair(vaultAddress, adapter, targetMarket);
|
|
1250
|
-
const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
|
|
1251
|
-
const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
|
|
1252
|
-
if (!(0, viem_1.isAddressEqual)(marketPublicAllocatorConfig.vault, vaultAddress) ||
|
|
1253
|
-
!(0, viem_1.isAddressEqual)(marketPublicAllocatorConfig.adapter, adapter.address) ||
|
|
1254
|
-
!activeAdapters.has(adapter.address.toLowerCase()))
|
|
1255
|
-
continue;
|
|
1256
|
-
const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
|
|
1257
|
-
const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
|
|
1258
|
-
const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
|
|
1259
|
-
const targetAllocations = [
|
|
1260
|
-
adapterCapAllocation,
|
|
1261
|
-
collateralCapAllocation,
|
|
1262
|
-
adapterMarketCapAllocation,
|
|
1263
|
-
];
|
|
1264
|
-
if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n))
|
|
1265
|
-
continue;
|
|
1266
|
-
const adapterShares = adapter.supplyShares[marketId] ?? 0n;
|
|
1267
|
-
const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
|
|
1268
|
-
const untracked = blue_sdk_1.MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
|
|
1269
|
-
const allocatorHeadroom = blue_sdk_1.MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
|
|
1270
|
-
untracked +
|
|
1271
|
-
targetPair.reserve(reserves)), blue_sdk_1.MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
|
|
1272
|
-
const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
|
|
1273
|
-
const minimumAllocationChange = blue_sdk_1.MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
|
|
1274
|
-
const blockedTargetIds = targetAllocations
|
|
1275
|
-
.filter(({ allocation, absoluteCap, relativeCap, id }) => {
|
|
1276
|
-
const nextAllocation = allocation +
|
|
1277
|
-
capReserve(vaultAddress, id, [targetPair]) +
|
|
1278
|
-
minimumAllocationChange;
|
|
1279
|
-
return (nextAllocation > absoluteCap ||
|
|
1280
|
-
(relativeCap === 0n && nextAllocation > 0n));
|
|
1281
|
-
})
|
|
1282
|
-
.map(({ id }) => id);
|
|
1283
|
-
// MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
|
|
1284
|
-
if (targetSupplyHeadroom === 0n ||
|
|
1285
|
-
allocatorHeadroom === 0n ||
|
|
1286
|
-
minimumSupply.shares < minimumSupply.assets ||
|
|
1287
|
-
minimumSupply.market.totalSupplyShares > blue_sdk_1.MathLib.MAX_UINT_128 ||
|
|
1288
|
-
blockedTargetIds.includes(adapterMarketCapId))
|
|
1289
|
-
continue;
|
|
1290
|
-
if (publicAllocatorConfig.canPullFromIdle &&
|
|
1291
|
-
availableIdleAssets > 0n &&
|
|
1292
|
-
blockedTargetIds.length === 0) {
|
|
1293
|
-
const assets = blue_sdk_1.MathLib.min(blue_sdk_1.MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
|
|
1294
|
-
if (assets > 0n) {
|
|
1295
|
-
rawCandidates.push({
|
|
1296
|
-
reallocation: {
|
|
1297
|
-
vault: vaultAddress,
|
|
1298
|
-
from: { type: "idle" },
|
|
1299
|
-
to: { adapter: adapter.address },
|
|
1300
|
-
assets,
|
|
1301
|
-
penalty: publicAllocatorConfig.penalty,
|
|
1302
|
-
},
|
|
1303
|
-
targetPair,
|
|
1304
|
-
allocatorHeadroom,
|
|
1305
|
-
});
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
for (const sourceAdapter of vault.accrualAdapters) {
|
|
1309
|
-
if (!(sourceAdapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2))
|
|
1310
|
-
continue;
|
|
1311
|
-
if (!(0, viem_1.isAddressEqual)(sourceAdapter.parentVault, vaultAddress))
|
|
1312
|
-
continue;
|
|
1313
|
-
if (!activeAdapters.has(sourceAdapter.address.toLowerCase()))
|
|
1314
|
-
continue;
|
|
1315
|
-
for (const sourceMarketReference of sourceAdapter.markets) {
|
|
1316
|
-
const sourceMarket = data.getMarket(sourceMarketReference.id);
|
|
1317
|
-
if (!(0, viem_1.isAddressEqual)(sourceMarket.params.loanToken, vault.asset) ||
|
|
1318
|
-
!(0, viem_1.isAddressEqual)(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm))
|
|
1319
|
-
continue;
|
|
1320
|
-
if (sourceMarket.id.toLowerCase() === normalizedMarketId)
|
|
1321
|
-
continue;
|
|
1322
|
-
const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
|
|
1323
|
-
const [, , sourceAdapterMarketCapId] = sourceIds;
|
|
1324
|
-
const sourceConfig = data.getMarketPublicAllocatorConfig(vaultAddress, sourceAdapterMarketCapId);
|
|
1325
|
-
if (!(0, viem_1.isAddressEqual)(sourceConfig.vault, vaultAddress) ||
|
|
1326
|
-
!(0, viem_1.isAddressEqual)(sourceConfig.adapter, sourceAdapter.address) ||
|
|
1327
|
-
!sourceConfig.canPullFromMarket)
|
|
1328
|
-
continue;
|
|
1329
|
-
const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
|
|
1330
|
-
if (sourceAllocations.some(({ allocation }) => allocation === 0n))
|
|
1331
|
-
continue;
|
|
1332
|
-
const sourceSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
|
|
1333
|
-
if (sourceSupplyShares === 0n)
|
|
1334
|
-
continue;
|
|
1335
|
-
// A withdrawal can create target headroom only for shared cap IDs.
|
|
1336
|
-
if (blockedTargetIds.some((id) => !sourceIds.includes(id)))
|
|
1337
|
-
continue;
|
|
1338
|
-
const sourcePair = getPair(vaultAddress, sourceAdapter, sourceMarket);
|
|
1339
|
-
const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
|
|
1340
|
-
data.setMarkets([accruedSourceMarket]);
|
|
1341
|
-
const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
|
|
1342
|
-
const assets = blue_sdk_1.MathLib.min(blue_sdk_1.MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, accruedSourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
|
|
1343
|
-
if (assets <= 0n)
|
|
1344
|
-
continue;
|
|
1345
|
-
rawCandidates.push({
|
|
1346
|
-
reallocation: {
|
|
1347
|
-
vault: vaultAddress,
|
|
1348
|
-
from: {
|
|
1349
|
-
type: "market",
|
|
1350
|
-
adapter: sourceAdapter.address,
|
|
1351
|
-
marketParams: sourceMarket.params,
|
|
1352
|
-
},
|
|
1353
|
-
to: { adapter: adapter.address },
|
|
1354
|
-
assets,
|
|
1355
|
-
penalty: publicAllocatorConfig.penalty,
|
|
1356
|
-
},
|
|
1357
|
-
targetPair,
|
|
1358
|
-
sourcePair,
|
|
1359
|
-
allocatorHeadroom,
|
|
1360
|
-
});
|
|
1361
|
-
}
|
|
1362
|
-
}
|
|
1363
|
-
}
|
|
1364
|
-
const capCompatibleCandidates = [];
|
|
1365
|
-
for (const { reallocation, targetPair, sourcePair, allocatorHeadroom, } of rawCandidates) {
|
|
1366
|
-
let lower = 0n;
|
|
1367
|
-
let upper = reallocation.assets;
|
|
1368
|
-
const targetIds = targetPair.ids;
|
|
1369
|
-
const sourceIds = new Set(sourcePair?.ids ?? []);
|
|
1370
|
-
const reserveById = new Map();
|
|
1371
|
-
for (const id of targetIds)
|
|
1372
|
-
reserveById.set(id, capReserve(reallocation.vault, id, sourcePair == null ? [targetPair] : [targetPair, sourcePair]));
|
|
1373
|
-
const probeReallocation = (assets) => {
|
|
1374
|
-
if (targetMarket.totalSupplyShares +
|
|
1375
|
-
targetMarket.toSupplyShares(assets, "Down") >
|
|
1376
|
-
blue_sdk_1.MathLib.MAX_UINT_128)
|
|
1377
|
-
return;
|
|
1378
|
-
const postTransition = (0, morpho_ts_1._try)(() => data.applyPublicReallocation({
|
|
1379
|
-
context: simulationContext,
|
|
1380
|
-
reallocation: { ...reallocation, assets },
|
|
1381
|
-
targetMarketId: marketId,
|
|
1382
|
-
timestamp: targetMarket.lastUpdate,
|
|
1383
|
-
adapterIdsCache,
|
|
1384
|
-
probe: true,
|
|
1385
|
-
}), index_js_1.ReallocationAllocationUnderflowError, index_js_1.ReallocationAdapterSupplySharesUnderflowError);
|
|
1386
|
-
if (postTransition == null)
|
|
1387
|
-
return;
|
|
1388
|
-
// Vault V2 checks relative caps against the transient firstTotalAssets,
|
|
1389
|
-
// which stays fixed after the vault's first allocation in a transaction.
|
|
1390
|
-
const { firstTotalAssets } = postTransition;
|
|
1391
|
-
let withinUpperBounds = true;
|
|
1392
|
-
let withinAllCaps = true;
|
|
1393
|
-
for (const id of targetIds) {
|
|
1394
|
-
const allocation = postTransition.data.getAllocation(reallocation.vault, id);
|
|
1395
|
-
const capacity = blue_sdk_1.VaultV2Utils.allocationHeadroom({ ...allocation, allocation: 0n }, firstTotalAssets).value;
|
|
1396
|
-
// The reserve covers interest accrued before inclusion by every
|
|
1397
|
-
// position the plan touched on this cap id, as booked onchain.
|
|
1398
|
-
const withinCap = allocation.absoluteCap > 0n &&
|
|
1399
|
-
allocation.allocation + (reserveById.get(id) ?? 0n) <=
|
|
1400
|
-
capacity;
|
|
1401
|
-
if (!withinCap) {
|
|
1402
|
-
withinAllCaps = false;
|
|
1403
|
-
if (!sourceIds.has(id))
|
|
1404
|
-
withinUpperBounds = false;
|
|
1405
|
-
}
|
|
1406
|
-
}
|
|
1407
|
-
return { withinAllCaps, withinUpperBounds };
|
|
1408
|
-
};
|
|
1409
|
-
// Non-shared target IDs impose monotonic upper bounds. Shared IDs
|
|
1410
|
-
// can impose lower bounds and non-monotonic rounding constraints,
|
|
1411
|
-
// so validate them after selecting the non-shared maximum.
|
|
1412
|
-
let probeUpper = true;
|
|
1413
|
-
while (lower < upper) {
|
|
1414
|
-
const assets = probeUpper ? upper : (lower + upper + 1n) / 2n;
|
|
1415
|
-
probeUpper = false;
|
|
1416
|
-
if (probeReallocation(assets)?.withinUpperBounds === true)
|
|
1417
|
-
lower = assets;
|
|
1418
|
-
else
|
|
1419
|
-
upper = assets - 1n;
|
|
1420
|
-
}
|
|
1421
|
-
let selectedAssets = blue_sdk_1.MathLib.min(lower, remainingAssets ?? reallocation.assets);
|
|
1422
|
-
let probe = selectedAssets > 0n
|
|
1423
|
-
? probeReallocation(selectedAssets)
|
|
1424
|
-
: undefined;
|
|
1425
|
-
if (remainingAssets != null && probe?.withinAllCaps !== true) {
|
|
1426
|
-
// Bound the base-unit scan; expose a caller ceiling if wider searches become necessary.
|
|
1427
|
-
const searchUpper = blue_sdk_1.MathLib.min(lower, selectedAssets + MAX_SHARED_CAP_SEARCH_STEPS);
|
|
1428
|
-
while (selectedAssets > 0n &&
|
|
1429
|
-
selectedAssets < searchUpper &&
|
|
1430
|
-
probe?.withinAllCaps !== true) {
|
|
1431
|
-
selectedAssets += 1n;
|
|
1432
|
-
probe = probeReallocation(selectedAssets);
|
|
1433
|
-
}
|
|
1434
|
-
}
|
|
1435
|
-
if (selectedAssets > 0n && probe?.withinAllCaps === true)
|
|
1436
|
-
capCompatibleCandidates.push({
|
|
1437
|
-
reallocation: { ...reallocation, assets: selectedAssets },
|
|
1438
|
-
targetPair,
|
|
1439
|
-
sourcePair,
|
|
1440
|
-
allocatorHeadroom,
|
|
1441
|
-
});
|
|
1442
|
-
}
|
|
1443
|
-
return capCompatibleCandidates.sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"))[0];
|
|
858
|
+
const params = {
|
|
859
|
+
vaultAddress,
|
|
860
|
+
data,
|
|
861
|
+
marketId,
|
|
862
|
+
penalty,
|
|
863
|
+
options,
|
|
864
|
+
simulationContext,
|
|
865
|
+
normalizedMarketId,
|
|
866
|
+
adapterIdsCache,
|
|
867
|
+
getPair,
|
|
868
|
+
capReserve,
|
|
869
|
+
reserves,
|
|
870
|
+
allocatorCapHeadroom,
|
|
871
|
+
timestamp,
|
|
872
|
+
maxWithdrawalUtilization,
|
|
873
|
+
remainingAssets,
|
|
874
|
+
getOptionalPublicAllocatorConfig: data.getOptionalPublicAllocatorConfig.bind(data),
|
|
875
|
+
setMarkets: data.setMarkets.bind(data),
|
|
876
|
+
applyPublicReallocation: data.applyPublicReallocation.bind(data),
|
|
877
|
+
};
|
|
878
|
+
return planCachedVaultCandidate({
|
|
879
|
+
...params,
|
|
880
|
+
initialIdleAssets,
|
|
881
|
+
activeAdaptersCache,
|
|
882
|
+
});
|
|
1444
883
|
})
|
|
1445
884
|
.filter((candidate) => candidate != null)
|
|
1446
885
|
.sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"));
|
|
1447
886
|
const largest = candidates[0];
|
|
1448
|
-
if (largest == null)
|
|
887
|
+
if (largest == null) {
|
|
1449
888
|
return {
|
|
1450
889
|
reallocations,
|
|
1451
890
|
data,
|
|
@@ -1453,31 +892,20 @@ class VaultV2BlueReallocationData {
|
|
|
1453
892
|
allocatorCapBoundTargets,
|
|
1454
893
|
idleBoundVaults,
|
|
1455
894
|
};
|
|
1456
|
-
const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
|
|
1457
|
-
if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
|
|
1458
|
-
// BluePublicAllocator caps are per vault and target adapter.
|
|
1459
|
-
allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
|
|
1460
|
-
if (acceptedReallocation.from.type === "idle") {
|
|
1461
|
-
const vaultKey = acceptedReallocation.vault.toLowerCase();
|
|
1462
|
-
const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
|
|
1463
|
-
idleTakenAssets.set(vaultKey, taken);
|
|
1464
|
-
// Candidates always record this; a missing entry counts the vault as bound.
|
|
1465
|
-
const initial = initialIdleAssets.get(vaultKey) ?? 0n;
|
|
1466
|
-
if (taken >=
|
|
1467
|
-
blue_sdk_1.MathLib.zeroFloorSub(initial, blue_sdk_1.MathLib.wMulUp(initial, allocatorCapHeadroom)))
|
|
1468
|
-
idleBoundVaults.add(vaultKey);
|
|
1469
|
-
}
|
|
1470
|
-
const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
|
|
1471
|
-
let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
|
|
1472
|
-
if (touchedVaultPairs == null) {
|
|
1473
|
-
touchedVaultPairs = new Map();
|
|
1474
|
-
reserves.touchedPairs.set(touchedVaultKey, touchedVaultPairs);
|
|
1475
895
|
}
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
896
|
+
const updates = getAcceptedCandidateUpdates({
|
|
897
|
+
candidate: largest,
|
|
898
|
+
idleTakenAssets,
|
|
899
|
+
initialIdleAssets,
|
|
900
|
+
allocatorCapHeadroom,
|
|
901
|
+
reserves,
|
|
902
|
+
});
|
|
903
|
+
updates.allocatorCapBoundTargets.forEach((key) => allocatorCapBoundTargets.add(key));
|
|
904
|
+
updates.idleTakenAssets.forEach(([key, assets]) => idleTakenAssets.set(key, assets));
|
|
905
|
+
updates.idleBoundVaults.forEach((key) => idleBoundVaults.add(key));
|
|
906
|
+
updates.touchedVaultEntries.forEach(([key, pairs]) => reserves.touchedPairs.set(key, pairs));
|
|
907
|
+
updates.touchedPairEntries.forEach(([key, pair]) => updates.touchedVaultPairs.set(key, pair));
|
|
908
|
+
const { reallocation: acceptedReallocation } = largest;
|
|
1481
909
|
reallocations.push(acceptedReallocation);
|
|
1482
910
|
const transition = data.applyPublicReallocation({
|
|
1483
911
|
context: simulationContext,
|
|
@@ -1488,8 +916,9 @@ class VaultV2BlueReallocationData {
|
|
|
1488
916
|
});
|
|
1489
917
|
data = transition.data;
|
|
1490
918
|
simulationContext = transition.context;
|
|
1491
|
-
if (remainingAssets != null)
|
|
919
|
+
if (remainingAssets != null) {
|
|
1492
920
|
remainingAssets -= acceptedReallocation.assets;
|
|
921
|
+
}
|
|
1493
922
|
}
|
|
1494
923
|
return {
|
|
1495
924
|
reallocations,
|
|
@@ -1545,8 +974,9 @@ class VaultV2BlueReallocationData {
|
|
|
1545
974
|
* ```
|
|
1546
975
|
*/
|
|
1547
976
|
getPublicReallocationLiquidity(marketId, options) {
|
|
1548
|
-
if (options?.enabled === false)
|
|
977
|
+
if (options?.enabled === false) {
|
|
1549
978
|
return 0n;
|
|
979
|
+
}
|
|
1550
980
|
const capAccrualBuffer = (0, utilization_js_1.resolveCapAccrualBuffer)(options?.capAccrualBuffer);
|
|
1551
981
|
const maxPenalty = resolveMaxPenalty(options?.maxPenalty);
|
|
1552
982
|
return this.clone()
|
|
@@ -1615,8 +1045,9 @@ class VaultV2BlueReallocationData {
|
|
|
1615
1045
|
: BigInt(options.timestamp);
|
|
1616
1046
|
const market = this.getMarket(marketId).accrueInterest(timestamp);
|
|
1617
1047
|
if (options?.enabled === false ||
|
|
1618
|
-
constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION > utilization)
|
|
1048
|
+
constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION > utilization) {
|
|
1619
1049
|
return market.getBorrowToUtilization(utilization);
|
|
1050
|
+
}
|
|
1620
1051
|
const availableLiquidity = this.clone()
|
|
1621
1052
|
.computeVaultV2BlueReallocationsAtUtilizationInPlace({
|
|
1622
1053
|
context: createSimulationContext(),
|
|
@@ -1639,12 +1070,14 @@ class VaultV2BlueReallocationData {
|
|
|
1639
1070
|
getLatestSnapshotTimestamp() {
|
|
1640
1071
|
let timestamp = this.timestamp ?? 0n;
|
|
1641
1072
|
for (const market of Object.values(this.markets)) {
|
|
1642
|
-
if (market != null)
|
|
1073
|
+
if (market != null) {
|
|
1643
1074
|
timestamp = blue_sdk_1.MathLib.max(timestamp, market.lastUpdate);
|
|
1075
|
+
}
|
|
1644
1076
|
}
|
|
1645
1077
|
for (const vault of Object.values(this.vaults)) {
|
|
1646
|
-
if (vault != null)
|
|
1078
|
+
if (vault != null) {
|
|
1647
1079
|
timestamp = blue_sdk_1.MathLib.max(timestamp, vault.lastUpdate);
|
|
1080
|
+
}
|
|
1648
1081
|
}
|
|
1649
1082
|
return timestamp;
|
|
1650
1083
|
}
|
|
@@ -1654,53 +1087,14 @@ class VaultV2BlueReallocationData {
|
|
|
1654
1087
|
const sourceVault = sourceVaultKey == null ? undefined : this.mutableVaults[sourceVaultKey];
|
|
1655
1088
|
let data = this;
|
|
1656
1089
|
if (probe) {
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
probeMarkets[sourceMarket.id] = sourceMarket;
|
|
1665
|
-
adapterKeysToClone.add(reallocation.from.adapter.toLowerCase());
|
|
1666
|
-
if (sourceVault != null) {
|
|
1667
|
-
const adaptersToRefresh = new Set(sourceVault.accrualAdapters);
|
|
1668
|
-
if (sourceVault.accrualLiquidityAdapter != null)
|
|
1669
|
-
adaptersToRefresh.add(sourceVault.accrualLiquidityAdapter);
|
|
1670
|
-
for (const adapter of adaptersToRefresh) {
|
|
1671
|
-
if ((adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2 &&
|
|
1672
|
-
adapter.markets.some(({ id }) => id === sourceMarket.id)) ||
|
|
1673
|
-
(adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter &&
|
|
1674
|
-
adapter.positions.some(({ marketId }) => marketId === sourceMarket.id)) ||
|
|
1675
|
-
(adapter instanceof blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter &&
|
|
1676
|
-
adapter.accrualVaultV1.allocations.has(sourceMarket.id)))
|
|
1677
|
-
adapterKeysToClone.add(adapter.address.toLowerCase());
|
|
1678
|
-
}
|
|
1679
|
-
}
|
|
1680
|
-
for (const id of getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.from.adapter), sourceMarket))
|
|
1681
|
-
allocationIdsToClone.add(id);
|
|
1682
|
-
}
|
|
1683
|
-
data = new VaultV2BlueReallocationData({
|
|
1684
|
-
chainId: this.chainId,
|
|
1685
|
-
timestamp: this.timestamp,
|
|
1686
|
-
markets: probeMarkets,
|
|
1090
|
+
data = this.cloneReallocationProbe({
|
|
1091
|
+
reallocation,
|
|
1092
|
+
targetMarketId,
|
|
1093
|
+
adapterIdsCache,
|
|
1094
|
+
sourceVaultKey,
|
|
1095
|
+
sourceVault,
|
|
1096
|
+
sourceAllocationsKey,
|
|
1687
1097
|
});
|
|
1688
|
-
if (sourceVaultKey != null) {
|
|
1689
|
-
data.mutableVaults[sourceVaultKey] =
|
|
1690
|
-
sourceVault == null
|
|
1691
|
-
? undefined
|
|
1692
|
-
: cloneVault(sourceVault, {
|
|
1693
|
-
markets: data.mutableMarkets,
|
|
1694
|
-
adapterKeysToClone,
|
|
1695
|
-
});
|
|
1696
|
-
}
|
|
1697
|
-
if (sourceAllocationsKey != null) {
|
|
1698
|
-
const sourceAllocations = this.mutableAllocations[sourceAllocationsKey];
|
|
1699
|
-
const allocations = {};
|
|
1700
|
-
for (const id of allocationIdsToClone)
|
|
1701
|
-
allocations[id] = sourceAllocations?.[id];
|
|
1702
|
-
data.mutableAllocations[sourceAllocationsKey] = allocations;
|
|
1703
|
-
}
|
|
1704
1098
|
}
|
|
1705
1099
|
const vaultKey = findAddressKey(data.mutableVaults, reallocation.vault) ??
|
|
1706
1100
|
reallocation.vault;
|
|
@@ -1728,101 +1122,201 @@ class VaultV2BlueReallocationData {
|
|
|
1728
1122
|
};
|
|
1729
1123
|
}
|
|
1730
1124
|
if (reallocation.from.type === "market") {
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
adapter: sourceAdapter.address,
|
|
1741
|
-
marketId: sourceMarket.id,
|
|
1742
|
-
supplyShares: currentSupplyShares,
|
|
1743
|
-
withdrawnShares: withdrawal.shares,
|
|
1744
|
-
});
|
|
1745
|
-
}
|
|
1746
|
-
sourceAdapter.supplyShares[sourceMarket.id] =
|
|
1747
|
-
currentSupplyShares - withdrawal.shares;
|
|
1748
|
-
data.setMarkets([withdrawal.market]);
|
|
1749
|
-
const sourceChange = withdrawal.market.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n) -
|
|
1750
|
-
data.getAllocation(reallocation.vault, sourceAdapterMarketCapId)
|
|
1751
|
-
.allocation;
|
|
1752
|
-
for (const id of sourceIds) {
|
|
1753
|
-
const allocation = data.getAllocation(reallocation.vault, id);
|
|
1754
|
-
const nextAllocation = allocation.allocation + sourceChange;
|
|
1755
|
-
if (nextAllocation < 0n) {
|
|
1756
|
-
throw new index_js_1.ReallocationAllocationUnderflowError({
|
|
1757
|
-
vault: reallocation.vault,
|
|
1758
|
-
id,
|
|
1759
|
-
allocation: allocation.allocation,
|
|
1760
|
-
change: sourceChange,
|
|
1761
|
-
});
|
|
1762
|
-
}
|
|
1763
|
-
data.mutableAllocations[allocationsKey][id] = {
|
|
1764
|
-
...allocation,
|
|
1765
|
-
allocation: nextAllocation,
|
|
1766
|
-
};
|
|
1767
|
-
}
|
|
1768
|
-
vault.assetBalance += reallocation.assets;
|
|
1125
|
+
// Book the source withdrawal and cap deltas before supplying the target.
|
|
1126
|
+
data.withdrawReallocationSource({
|
|
1127
|
+
reallocation,
|
|
1128
|
+
source: reallocation.from,
|
|
1129
|
+
timestamp,
|
|
1130
|
+
adapterIdsCache,
|
|
1131
|
+
allocationsKey,
|
|
1132
|
+
vault,
|
|
1133
|
+
});
|
|
1769
1134
|
}
|
|
1135
|
+
// Idle allocations also credit the instance's explicit Blue liquidity balance.
|
|
1770
1136
|
if (reallocation.from.type === "idle") {
|
|
1771
|
-
|
|
1772
|
-
if (blueBalanceKey != null &&
|
|
1773
|
-
data.mutableBlueBalances[blueBalanceKey] != null)
|
|
1774
|
-
data.mutableBlueBalances[blueBalanceKey] += reallocation.assets;
|
|
1137
|
+
data.creditIdleReallocationBalance(reallocation, targetMarket);
|
|
1775
1138
|
}
|
|
1776
1139
|
if (firstTotalAssets == null) {
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
else {
|
|
1788
|
-
vault = vault.accrueInterest(timestamp).vault;
|
|
1789
|
-
}
|
|
1790
|
-
data.mutableVaults[vaultKey] = vault;
|
|
1791
|
-
firstTotalAssets = vault._totalAssets;
|
|
1792
|
-
nextContext = {
|
|
1793
|
-
...nextContext,
|
|
1794
|
-
firstTotalAssets: {
|
|
1795
|
-
...nextContext.firstTotalAssets,
|
|
1796
|
-
[firstTotalAssetsKey]: firstTotalAssets,
|
|
1797
|
-
},
|
|
1798
|
-
};
|
|
1140
|
+
const firstAllocation = data.accrueReallocationFirstAllocation({
|
|
1141
|
+
vault,
|
|
1142
|
+
vaultKey,
|
|
1143
|
+
timestamp,
|
|
1144
|
+
context: nextContext,
|
|
1145
|
+
firstTotalAssetsKey,
|
|
1146
|
+
});
|
|
1147
|
+
vault = firstAllocation.vault;
|
|
1148
|
+
firstTotalAssets = firstAllocation.firstTotalAssets;
|
|
1149
|
+
nextContext = firstAllocation.context;
|
|
1799
1150
|
}
|
|
1800
|
-
|
|
1151
|
+
// Book the target shares and cap deltas in the working state.
|
|
1152
|
+
data.supplyReallocationTarget({
|
|
1153
|
+
reallocation,
|
|
1154
|
+
adapterIdsCache,
|
|
1155
|
+
targetMarket,
|
|
1156
|
+
timestamp,
|
|
1157
|
+
probe,
|
|
1158
|
+
allocationsKey,
|
|
1159
|
+
});
|
|
1160
|
+
vault.assetBalance -= reallocation.assets;
|
|
1161
|
+
return { data, context: nextContext, firstTotalAssets };
|
|
1162
|
+
}
|
|
1163
|
+
/** Supplies the target position and books its rounded allocation changes. @internal */
|
|
1164
|
+
supplyReallocationTarget({ reallocation, adapterIdsCache, targetMarket, timestamp, probe, allocationsKey, }) {
|
|
1165
|
+
const targetAdapter = this.getMutableAdapter(reallocation.vault, reallocation.to.adapter);
|
|
1801
1166
|
const targetIds = getAdapterIds(adapterIdsCache, targetAdapter, targetMarket);
|
|
1802
1167
|
const [, , targetAdapterMarketCapId] = targetIds;
|
|
1803
|
-
const currentTargetMarket =
|
|
1804
|
-
const oldTargetAllocation =
|
|
1168
|
+
const currentTargetMarket = this.getMarket(targetMarket.id);
|
|
1169
|
+
const oldTargetAllocation = this.getAllocation(reallocation.vault, targetAdapterMarketCapId).allocation;
|
|
1805
1170
|
const supply = currentTargetMarket.supply(reallocation.assets, 0n, timestamp);
|
|
1806
1171
|
const targetSupplyShares = (targetAdapter.supplyShares[targetMarket.id] ?? 0n) + supply.shares;
|
|
1807
1172
|
targetAdapter.supplyShares[targetMarket.id] = targetSupplyShares;
|
|
1808
|
-
if (!targetAdapter.marketIds.includes(targetMarket.id))
|
|
1173
|
+
if (!targetAdapter.marketIds.includes(targetMarket.id)) {
|
|
1809
1174
|
targetAdapter.marketIds.push(targetMarket.id);
|
|
1810
|
-
|
|
1175
|
+
}
|
|
1176
|
+
if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id)) {
|
|
1811
1177
|
targetAdapter.markets.push(supply.market);
|
|
1812
|
-
|
|
1178
|
+
}
|
|
1179
|
+
this.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
|
|
1813
1180
|
const simulatedChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
|
|
1814
1181
|
// The adapter's rounded expected-assets delta can differ by one wei at inclusion,
|
|
1815
1182
|
// so cap tracking assumes each accepted leg adds at least its requested assets.
|
|
1816
1183
|
const targetChange = blue_sdk_1.MathLib.max(simulatedChange, reallocation.assets);
|
|
1817
1184
|
for (const id of targetIds) {
|
|
1818
|
-
const allocation =
|
|
1819
|
-
|
|
1185
|
+
const allocation = this.getAllocation(reallocation.vault, id);
|
|
1186
|
+
const allocations = this.mutableAllocations[allocationsKey];
|
|
1187
|
+
if (allocations == null) {
|
|
1188
|
+
throw new index_js_1.UnknownReallocationAllocationError(reallocation.vault, id);
|
|
1189
|
+
}
|
|
1190
|
+
allocations[id] = {
|
|
1820
1191
|
...allocation,
|
|
1821
1192
|
allocation: allocation.allocation + targetChange,
|
|
1822
1193
|
};
|
|
1823
1194
|
}
|
|
1824
|
-
|
|
1825
|
-
|
|
1195
|
+
}
|
|
1196
|
+
/** Credits shared Blue liquidity when an idle allocation enters the target market. @internal */
|
|
1197
|
+
creditIdleReallocationBalance(reallocation, targetMarket) {
|
|
1198
|
+
const blueBalanceKey = findAddressKey(this.mutableBlueBalances, targetMarket.params.loanToken);
|
|
1199
|
+
if (blueBalanceKey == null) {
|
|
1200
|
+
return;
|
|
1201
|
+
}
|
|
1202
|
+
const blueBalance = this.mutableBlueBalances[blueBalanceKey];
|
|
1203
|
+
if (blueBalance != null) {
|
|
1204
|
+
this.mutableBlueBalances[blueBalanceKey] =
|
|
1205
|
+
blueBalance + reallocation.assets;
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
/** Builds the isolated markets, adapter views and caps used by a transition probe. @internal */
|
|
1209
|
+
cloneReallocationProbe({ reallocation, targetMarketId, adapterIdsCache, sourceVaultKey, sourceVault, sourceAllocationsKey, }) {
|
|
1210
|
+
const probeMarkets = {
|
|
1211
|
+
[targetMarketId]: this.getMarket(targetMarketId),
|
|
1212
|
+
};
|
|
1213
|
+
const adapterKeysToClone = new Set([
|
|
1214
|
+
reallocation.to.adapter.toLowerCase(),
|
|
1215
|
+
]);
|
|
1216
|
+
const allocationIdsToClone = new Set(getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.to.adapter), this.getMarket(targetMarketId)));
|
|
1217
|
+
if (reallocation.from.type === "market") {
|
|
1218
|
+
const sourceMarket = this.getMarket(reallocation.from.marketParams.id);
|
|
1219
|
+
probeMarkets[sourceMarket.id] = sourceMarket;
|
|
1220
|
+
adapterKeysToClone.add(reallocation.from.adapter.toLowerCase());
|
|
1221
|
+
for (const key of getDependentProbeAdapterKeys(sourceVault, sourceMarket.id)) {
|
|
1222
|
+
adapterKeysToClone.add(key);
|
|
1223
|
+
}
|
|
1224
|
+
for (const id of getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.from.adapter), sourceMarket)) {
|
|
1225
|
+
allocationIdsToClone.add(id);
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
const data = new VaultV2BlueReallocationData({
|
|
1229
|
+
chainId: this.chainId,
|
|
1230
|
+
timestamp: this.timestamp,
|
|
1231
|
+
markets: probeMarkets,
|
|
1232
|
+
});
|
|
1233
|
+
if (sourceVaultKey != null) {
|
|
1234
|
+
data.mutableVaults[sourceVaultKey] =
|
|
1235
|
+
sourceVault == null
|
|
1236
|
+
? undefined
|
|
1237
|
+
: cloneVault(sourceVault, {
|
|
1238
|
+
markets: data.mutableMarkets,
|
|
1239
|
+
adapterKeysToClone,
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
if (sourceAllocationsKey != null) {
|
|
1243
|
+
const sourceAllocations = this.mutableAllocations[sourceAllocationsKey];
|
|
1244
|
+
const allocations = {};
|
|
1245
|
+
for (const id of allocationIdsToClone) {
|
|
1246
|
+
allocations[id] = sourceAllocations?.[id];
|
|
1247
|
+
}
|
|
1248
|
+
data.mutableAllocations[sourceAllocationsKey] = allocations;
|
|
1249
|
+
}
|
|
1250
|
+
return data;
|
|
1251
|
+
}
|
|
1252
|
+
/** Withdraws the source market position and books its cap changes before target supply. @internal */
|
|
1253
|
+
withdrawReallocationSource({ reallocation, source, timestamp, adapterIdsCache, allocationsKey, vault, }) {
|
|
1254
|
+
const sourceAdapter = this.getMutableAdapter(reallocation.vault, source.adapter);
|
|
1255
|
+
const sourceMarket = this.getMarket(source.marketParams.id);
|
|
1256
|
+
const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
|
|
1257
|
+
const [, , sourceAdapterMarketCapId] = sourceIds;
|
|
1258
|
+
const currentSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
|
|
1259
|
+
const withdrawal = sourceMarket.withdraw(reallocation.assets, 0n, timestamp);
|
|
1260
|
+
if (withdrawal.shares > currentSupplyShares) {
|
|
1261
|
+
throw new index_js_1.ReallocationAdapterSupplySharesUnderflowError({
|
|
1262
|
+
vault: reallocation.vault,
|
|
1263
|
+
adapter: sourceAdapter.address,
|
|
1264
|
+
marketId: sourceMarket.id,
|
|
1265
|
+
supplyShares: currentSupplyShares,
|
|
1266
|
+
withdrawnShares: withdrawal.shares,
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
sourceAdapter.supplyShares[sourceMarket.id] =
|
|
1270
|
+
currentSupplyShares - withdrawal.shares;
|
|
1271
|
+
this.setMarkets([withdrawal.market]);
|
|
1272
|
+
const sourceChange = withdrawal.market.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n) -
|
|
1273
|
+
this.getAllocation(reallocation.vault, sourceAdapterMarketCapId)
|
|
1274
|
+
.allocation;
|
|
1275
|
+
for (const id of sourceIds) {
|
|
1276
|
+
const allocation = this.getAllocation(reallocation.vault, id);
|
|
1277
|
+
const nextAllocation = allocation.allocation + sourceChange;
|
|
1278
|
+
if (nextAllocation < 0n) {
|
|
1279
|
+
throw new index_js_1.ReallocationAllocationUnderflowError({
|
|
1280
|
+
vault: reallocation.vault,
|
|
1281
|
+
id,
|
|
1282
|
+
allocation: allocation.allocation,
|
|
1283
|
+
change: sourceChange,
|
|
1284
|
+
});
|
|
1285
|
+
}
|
|
1286
|
+
const allocations = this.mutableAllocations[allocationsKey];
|
|
1287
|
+
allocations[id] = {
|
|
1288
|
+
...allocation,
|
|
1289
|
+
allocation: nextAllocation,
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
vault.assetBalance += reallocation.assets;
|
|
1293
|
+
}
|
|
1294
|
+
/** Books the vault's first-allocation denominator once per simulated transaction. @internal */
|
|
1295
|
+
accrueReallocationFirstAllocation({ vault: initialVault, vaultKey, timestamp, context, firstTotalAssetsKey, }) {
|
|
1296
|
+
let vault = initialVault;
|
|
1297
|
+
// Vault V2's transient firstTotalAssets tracks the first allocation in a
|
|
1298
|
+
// transaction independently from elapsed time. Later allocations must not
|
|
1299
|
+
// recompute the denominator, even if their simulated balances have changed.
|
|
1300
|
+
if (timestamp === vault.lastUpdate) {
|
|
1301
|
+
// AccrualVaultV2 skips zero-elapsed accruals, but the contract's first
|
|
1302
|
+
// touch still reads real adapter assets. With zero elapsed time, its
|
|
1303
|
+
// growth clamp leaves only existing losses to recognize.
|
|
1304
|
+
const realAssets = vault.accrualAdapters.reduce((assets, adapter) => assets + adapter.realAssets(timestamp), vault.assetBalance);
|
|
1305
|
+
vault._totalAssets = blue_sdk_1.MathLib.min(realAssets, vault._totalAssets);
|
|
1306
|
+
}
|
|
1307
|
+
else {
|
|
1308
|
+
vault = vault.accrueInterest(timestamp).vault;
|
|
1309
|
+
}
|
|
1310
|
+
this.mutableVaults[vaultKey] = vault;
|
|
1311
|
+
const firstTotalAssets = vault._totalAssets;
|
|
1312
|
+
const nextContext = {
|
|
1313
|
+
...context,
|
|
1314
|
+
firstTotalAssets: {
|
|
1315
|
+
...context.firstTotalAssets,
|
|
1316
|
+
[firstTotalAssetsKey]: firstTotalAssets,
|
|
1317
|
+
},
|
|
1318
|
+
};
|
|
1319
|
+
return { vault, firstTotalAssets, context: nextContext };
|
|
1826
1320
|
}
|
|
1827
1321
|
/** Updates canonical markets in bulk and refreshes only dependent adapter views. */
|
|
1828
1322
|
setMarkets(markets, adaptersToRefresh) {
|
|
@@ -1831,43 +1325,1265 @@ class VaultV2BlueReallocationData {
|
|
|
1831
1325
|
this.mutableMarkets[market.id] = market;
|
|
1832
1326
|
changedMarketIds.add(market.id);
|
|
1833
1327
|
}
|
|
1834
|
-
if (changedMarketIds.size === 0)
|
|
1328
|
+
if (changedMarketIds.size === 0) {
|
|
1835
1329
|
return;
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
adapters.add(adapter);
|
|
1846
|
-
if (vault.accrualLiquidityAdapter != null)
|
|
1847
|
-
adapters.add(vault.accrualLiquidityAdapter);
|
|
1330
|
+
}
|
|
1331
|
+
const adapters = collectAdaptersToRefresh(this.mutableVaults, adaptersToRefresh);
|
|
1332
|
+
for (const adapter of adapters) {
|
|
1333
|
+
const update = refreshAdapterMarkets(adapter, {
|
|
1334
|
+
markets: this.mutableMarkets,
|
|
1335
|
+
changedMarketIds,
|
|
1336
|
+
});
|
|
1337
|
+
if (update != null) {
|
|
1338
|
+
Object.assign(adapter, update);
|
|
1848
1339
|
}
|
|
1849
1340
|
}
|
|
1850
|
-
|
|
1851
|
-
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
exports.VaultV2BlueReallocationData = VaultV2BlueReallocationData;
|
|
1344
|
+
/** Collects the adapters whose views may depend on changed canonical markets. @internal */
|
|
1345
|
+
function collectAdaptersToRefresh(vaults, adaptersToRefresh) {
|
|
1346
|
+
const adapters = new Set();
|
|
1347
|
+
if (adaptersToRefresh == null) {
|
|
1348
|
+
// A Morpho market is global state shared by every vault position. Legacy
|
|
1349
|
+
// AccrualPosition constructors copy their Market, so rebuild those adapter
|
|
1350
|
+
// views as well as repointing V2 adapters whenever the canonical state moves.
|
|
1351
|
+
for (const vault of Object.values(vaults)) {
|
|
1352
|
+
if (vault == null) {
|
|
1353
|
+
continue;
|
|
1354
|
+
}
|
|
1355
|
+
for (const adapter of vault.accrualAdapters) {
|
|
1852
1356
|
adapters.add(adapter);
|
|
1357
|
+
}
|
|
1358
|
+
if (vault.accrualLiquidityAdapter != null) {
|
|
1359
|
+
adapters.add(vault.accrualLiquidityAdapter);
|
|
1360
|
+
}
|
|
1853
1361
|
}
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1362
|
+
}
|
|
1363
|
+
else {
|
|
1364
|
+
for (const adapter of adaptersToRefresh) {
|
|
1365
|
+
adapters.add(adapter);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
return adapters;
|
|
1369
|
+
}
|
|
1370
|
+
/** Computes one adapter's dependent market views after a canonical state change. @internal */
|
|
1371
|
+
function refreshAdapterMarkets(adapter, { markets, changedMarketIds, }) {
|
|
1372
|
+
if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2) {
|
|
1373
|
+
if (!adapter.markets.some(({ id }) => changedMarketIds.has(id))) {
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
return {
|
|
1377
|
+
markets: adapter.markets.map((adapterMarket) => getCanonicalMarket(markets, adapterMarket)),
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter) {
|
|
1381
|
+
if (!adapter.positions.some(({ marketId }) => changedMarketIds.has(marketId))) {
|
|
1382
|
+
return;
|
|
1383
|
+
}
|
|
1384
|
+
return {
|
|
1385
|
+
positions: adapter.positions.map((position) => clonePosition(position, markets)),
|
|
1386
|
+
};
|
|
1387
|
+
}
|
|
1388
|
+
if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter) {
|
|
1389
|
+
if (![...adapter.accrualVaultV1.allocations.keys()].some((marketId) => changedMarketIds.has(marketId))) {
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
return {
|
|
1393
|
+
accrualVaultV1: cloneAccrualVault(adapter.accrualVaultV1, markets),
|
|
1394
|
+
};
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
/** Clones allocator authorization records without sharing caller-owned iterables. @internal */
|
|
1398
|
+
function cloneAllocatorConfigurations(input) {
|
|
1399
|
+
const publicAllocatorConfigs = {};
|
|
1400
|
+
const activeAdapters = {};
|
|
1401
|
+
const marketPublicAllocatorConfigs = {};
|
|
1402
|
+
for (const [vault, config] of Object.entries(input.publicAllocatorConfigs ?? {})) {
|
|
1403
|
+
publicAllocatorConfigs[vault] =
|
|
1404
|
+
config == null ? undefined : new blue_sdk_1.VaultV2BluePublicAllocatorConfig(config);
|
|
1405
|
+
}
|
|
1406
|
+
for (const [vault, adapters] of Object.entries(input.activeAdapters ?? {})) {
|
|
1407
|
+
activeAdapters[vault] = adapters == null ? undefined : new Set(adapters);
|
|
1408
|
+
}
|
|
1409
|
+
for (const [vault, configs] of Object.entries(input.marketPublicAllocatorConfigs ?? {})) {
|
|
1410
|
+
marketPublicAllocatorConfigs[vault] =
|
|
1411
|
+
cloneMarketAllocatorConfigurations(configs);
|
|
1412
|
+
}
|
|
1413
|
+
return {
|
|
1414
|
+
publicAllocatorConfigs,
|
|
1415
|
+
activeAdapters,
|
|
1416
|
+
marketPublicAllocatorConfigs,
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
/** Clones one vault's adapter-market allocator configurations. @internal */
|
|
1420
|
+
function cloneMarketAllocatorConfigurations(configs) {
|
|
1421
|
+
const cloned = {};
|
|
1422
|
+
for (const [id, config] of Object.entries(configs ?? {})) {
|
|
1423
|
+
cloned[id] =
|
|
1424
|
+
config == null
|
|
1425
|
+
? undefined
|
|
1426
|
+
: new blue_sdk_1.VaultV2BlueMarketPublicAllocatorConfig(config);
|
|
1427
|
+
}
|
|
1428
|
+
return cloned;
|
|
1429
|
+
}
|
|
1430
|
+
/** Finds adapter views that a source-market transition must isolate for probing. @internal */
|
|
1431
|
+
function getDependentProbeAdapterKeys(sourceVault, sourceMarketId) {
|
|
1432
|
+
const keys = new Set();
|
|
1433
|
+
if (sourceVault == null) {
|
|
1434
|
+
return keys;
|
|
1435
|
+
}
|
|
1436
|
+
const adapters = new Set(sourceVault.accrualAdapters);
|
|
1437
|
+
if (sourceVault.accrualLiquidityAdapter != null) {
|
|
1438
|
+
adapters.add(sourceVault.accrualLiquidityAdapter);
|
|
1439
|
+
}
|
|
1440
|
+
for (const adapter of adapters) {
|
|
1441
|
+
if (adapterReferencesMarket(adapter, sourceMarketId)) {
|
|
1442
|
+
keys.add(adapter.address.toLowerCase());
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
return keys;
|
|
1446
|
+
}
|
|
1447
|
+
/** Tests whether an adapter view depends on one canonical Blue market. @internal */
|
|
1448
|
+
function adapterReferencesMarket(adapter, marketId) {
|
|
1449
|
+
return ((adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2 &&
|
|
1450
|
+
adapter.markets.some(({ id }) => id === marketId)) ||
|
|
1451
|
+
(adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter &&
|
|
1452
|
+
adapter.positions.some((position) => position.marketId === marketId)) ||
|
|
1453
|
+
(adapter instanceof blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter &&
|
|
1454
|
+
adapter.accrualVaultV1.allocations.has(marketId)));
|
|
1455
|
+
}
|
|
1456
|
+
/** Computes the accepted leg's liquidity bounds and shared cap reserve entries. @internal */
|
|
1457
|
+
function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, initialIdleAssets, allocatorCapHeadroom, reserves, }) {
|
|
1458
|
+
const allocatorCapBoundTargets = [];
|
|
1459
|
+
const idleBoundVaults = [];
|
|
1460
|
+
const idleTakenEntries = [];
|
|
1461
|
+
const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
|
|
1462
|
+
if (acceptedReallocation.assets >= acceptedAllocatorHeadroom) {
|
|
1463
|
+
// BluePublicAllocator caps are per vault and target adapter.
|
|
1464
|
+
allocatorCapBoundTargets.push(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
|
|
1465
|
+
}
|
|
1466
|
+
if (acceptedReallocation.from.type === "idle") {
|
|
1467
|
+
const vaultKey = acceptedReallocation.vault.toLowerCase();
|
|
1468
|
+
const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
|
|
1469
|
+
idleTakenEntries.push([vaultKey, taken]);
|
|
1470
|
+
// Candidates always record this; a missing entry counts the vault as bound.
|
|
1471
|
+
const initial = initialIdleAssets.get(vaultKey) ?? 0n;
|
|
1472
|
+
if (taken >=
|
|
1473
|
+
blue_sdk_1.MathLib.zeroFloorSub(initial, blue_sdk_1.MathLib.wMulUp(initial, allocatorCapHeadroom))) {
|
|
1474
|
+
idleBoundVaults.push(vaultKey);
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
|
|
1478
|
+
const existingPairs = reserves.touchedPairs.get(touchedVaultKey);
|
|
1479
|
+
const touchedVaultPairs = existingPairs ?? new Map();
|
|
1480
|
+
const touchedVaultEntries = existingPairs == null
|
|
1481
|
+
? [[touchedVaultKey, touchedVaultPairs]]
|
|
1482
|
+
: [];
|
|
1483
|
+
const touchedPairEntries = [];
|
|
1484
|
+
if (!touchedVaultPairs.has(acceptedTargetPair.key)) {
|
|
1485
|
+
touchedPairEntries.push([acceptedTargetPair.key, acceptedTargetPair]);
|
|
1486
|
+
}
|
|
1487
|
+
if (acceptedSourcePair != null &&
|
|
1488
|
+
!touchedVaultPairs.has(acceptedSourcePair.key) &&
|
|
1489
|
+
acceptedSourcePair.key !== acceptedTargetPair.key) {
|
|
1490
|
+
touchedPairEntries.push([acceptedSourcePair.key, acceptedSourcePair]);
|
|
1491
|
+
}
|
|
1492
|
+
return {
|
|
1493
|
+
allocatorCapBoundTargets,
|
|
1494
|
+
idleTakenAssets: idleTakenEntries,
|
|
1495
|
+
idleBoundVaults,
|
|
1496
|
+
touchedVaultPairs,
|
|
1497
|
+
touchedVaultEntries,
|
|
1498
|
+
touchedPairEntries,
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Creates cap-reserve readers over the shared in-place planning caches.
|
|
1503
|
+
* Returned readers populate reserve caches as in the utilization pass.
|
|
1504
|
+
* @internal
|
|
1505
|
+
*/
|
|
1506
|
+
function createCapReserveResolvers({ reserves, adapterIdsCache, timestamp, capAccrualBuffer, }) {
|
|
1507
|
+
// Onchain, market interest is booked once at transaction start, on pre-plan
|
|
1508
|
+
// positions at pre-plan rates, and stays on touched positions' cap ids.
|
|
1509
|
+
// This reserve state is shared across every planner pass and leg of the plan.
|
|
1510
|
+
// biome-ignore lint/complexity/useMaxParams: a pair is identified by its vault, adapter, and market.
|
|
1511
|
+
const getPair = (vault, adapter, market) => {
|
|
1512
|
+
const key = `${vault}:${adapter.address}:${market.id}`.toLowerCase();
|
|
1513
|
+
const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
|
|
1514
|
+
if (touched != null) {
|
|
1515
|
+
return touched;
|
|
1516
|
+
}
|
|
1517
|
+
const shares = adapter.supplyShares[market.id] ?? 0n;
|
|
1518
|
+
return {
|
|
1519
|
+
key,
|
|
1520
|
+
ids: getAdapterIds(adapterIdsCache, adapter, market),
|
|
1521
|
+
reserve: (reserveState) => {
|
|
1522
|
+
let reserve = reserveState.reserveByPairKey.get(key);
|
|
1523
|
+
if (reserve == null) {
|
|
1524
|
+
let accruals = reserveState.marketAccruals.get(market.id);
|
|
1525
|
+
if (accruals == null) {
|
|
1526
|
+
const initialMarket = reserveState.initialMarkets[market.id];
|
|
1527
|
+
if (initialMarket == null) {
|
|
1528
|
+
throw new index_js_1.UnknownReallocationMarketError(market.id);
|
|
1529
|
+
}
|
|
1530
|
+
accruals = [
|
|
1531
|
+
initialMarket.accrueInterest(timestamp),
|
|
1532
|
+
initialMarket.accrueInterest(timestamp + capAccrualBuffer),
|
|
1533
|
+
];
|
|
1534
|
+
reserveState.marketAccruals.set(market.id, accruals);
|
|
1535
|
+
}
|
|
1536
|
+
const [atTimestamp, projected] = accruals;
|
|
1537
|
+
reserve = blue_sdk_1.MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
|
|
1538
|
+
reserveState.reserveByPairKey.set(key, reserve);
|
|
1539
|
+
}
|
|
1540
|
+
return reserve;
|
|
1541
|
+
},
|
|
1542
|
+
};
|
|
1543
|
+
};
|
|
1544
|
+
// biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
|
|
1545
|
+
const capReserve = (vault, id, candidatePairs) => {
|
|
1546
|
+
let reserve = 0n;
|
|
1547
|
+
const seen = new Set();
|
|
1548
|
+
for (const pair of [
|
|
1549
|
+
...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
|
|
1550
|
+
...candidatePairs,
|
|
1551
|
+
]) {
|
|
1552
|
+
if (seen.has(pair.key) || !pair.ids.includes(id)) {
|
|
1553
|
+
continue;
|
|
1859
1554
|
}
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1555
|
+
seen.add(pair.key);
|
|
1556
|
+
reserve += pair.reserve(reserves);
|
|
1557
|
+
}
|
|
1558
|
+
return reserve;
|
|
1559
|
+
};
|
|
1560
|
+
return { getPair, capReserve };
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* Plans one vault candidate, caching its initial idle assets and active adapters in place.
|
|
1564
|
+
* @internal
|
|
1565
|
+
*/
|
|
1566
|
+
function planCachedVaultCandidate(params) {
|
|
1567
|
+
const { vaultAddress, data, initialIdleAssets, activeAdaptersCache } = params;
|
|
1568
|
+
const idleState = resolveVaultCandidateIdleState(params);
|
|
1569
|
+
if (idleState == null) {
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
const { availableIdleAssets } = idleState;
|
|
1573
|
+
const vaultAddressKey = vaultAddress.toLowerCase();
|
|
1574
|
+
if (!initialIdleAssets.has(vaultAddressKey)) {
|
|
1575
|
+
initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
|
|
1576
|
+
}
|
|
1577
|
+
let activeAdapters = activeAdaptersCache.get(vaultAddress);
|
|
1578
|
+
if (activeAdapters == null) {
|
|
1579
|
+
activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
|
|
1580
|
+
activeAdaptersCache.set(vaultAddress, activeAdapters);
|
|
1581
|
+
}
|
|
1582
|
+
return planVaultCandidate({
|
|
1583
|
+
...params,
|
|
1584
|
+
...idleState,
|
|
1585
|
+
activeAdapters,
|
|
1586
|
+
});
|
|
1587
|
+
}
|
|
1588
|
+
/** Resolves an eligible vault's idle balance before initializing candidate caches. @internal */
|
|
1589
|
+
function resolveVaultCandidateIdleState(params) {
|
|
1590
|
+
const { vaultAddress, data, marketId, penalty, options, simulationContext, getOptionalPublicAllocatorConfig, } = params;
|
|
1591
|
+
const targetMarket = data.getMarket(marketId);
|
|
1592
|
+
const publicAllocatorConfig = getOptionalPublicAllocatorConfig(vaultAddress);
|
|
1593
|
+
if (publicAllocatorConfig == null) {
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
const vault = data.getVault(vaultAddress);
|
|
1597
|
+
if (!(0, viem_1.isAddressEqual)(publicAllocatorConfig.vault, vaultAddress) ||
|
|
1598
|
+
publicAllocatorConfig.penalty >
|
|
1599
|
+
(options.maxPenalty ?? constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY)) {
|
|
1600
|
+
return;
|
|
1601
|
+
}
|
|
1602
|
+
if (penalty != null && publicAllocatorConfig.penalty !== penalty) {
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
|
|
1606
|
+
const donatedPenaltyAssets = donatedPenaltyAssetsKey == null
|
|
1607
|
+
? 0n
|
|
1608
|
+
: simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey];
|
|
1609
|
+
if (donatedPenaltyAssets == null) {
|
|
1610
|
+
throw new blue_sdk_1.UnknownDataError(`Missing donated penalty assets for "${vaultAddress}".`);
|
|
1611
|
+
}
|
|
1612
|
+
// Exclude rounded penalty dust from idle candidates so one donation
|
|
1613
|
+
// cannot replenish liquidity for another same-plan reallocation.
|
|
1614
|
+
const availableIdleAssets = blue_sdk_1.MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssets);
|
|
1615
|
+
return { vault, targetMarket, publicAllocatorConfig, availableIdleAssets };
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* Plans the highest-asset cap-compatible candidate for one configured vault.
|
|
1619
|
+
* Candidate planning updates shared working data/reserves in place; do not reuse a prior state.
|
|
1620
|
+
* @internal
|
|
1621
|
+
*/
|
|
1622
|
+
function planVaultCandidate(params) {
|
|
1623
|
+
const { vault, targetMarket, publicAllocatorConfig, availableIdleAssets, activeAdapters, } = params;
|
|
1624
|
+
const targetSupplyHeadroom = blue_sdk_1.MathLib.zeroFloorSub(blue_sdk_1.MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
|
|
1625
|
+
if (targetSupplyHeadroom === 0n ||
|
|
1626
|
+
targetMarket.toSupplyShares(1n, "Down") >
|
|
1627
|
+
blue_sdk_1.MathLib.zeroFloorSub(blue_sdk_1.MathLib.MAX_UINT_128, targetMarket.totalSupplyShares)) {
|
|
1628
|
+
return;
|
|
1629
|
+
}
|
|
1630
|
+
const minimumSupply = targetMarket.supply(1n, 0n);
|
|
1631
|
+
const rawCandidates = [];
|
|
1632
|
+
// Missing nested allocator state means the snapshot is incomplete, so
|
|
1633
|
+
// typed getter errors below must propagate. Only explicit zero caps or
|
|
1634
|
+
// disabled permissions make an adapter ineligible.
|
|
1635
|
+
for (const adapter of vault.accrualAdapters) {
|
|
1636
|
+
rawCandidates.push(...planTargetAdapterCandidates({
|
|
1637
|
+
...params,
|
|
1638
|
+
vault,
|
|
1639
|
+
targetMarket,
|
|
1640
|
+
publicAllocatorConfig,
|
|
1641
|
+
availableIdleAssets,
|
|
1642
|
+
activeAdapters,
|
|
1643
|
+
targetSupplyHeadroom,
|
|
1644
|
+
minimumSupply,
|
|
1645
|
+
adapter,
|
|
1646
|
+
}));
|
|
1647
|
+
}
|
|
1648
|
+
const capCompatibleCandidates = [];
|
|
1649
|
+
for (const candidate of rawCandidates) {
|
|
1650
|
+
const compatible = fitCandidateCaps({
|
|
1651
|
+
...params,
|
|
1652
|
+
...candidate,
|
|
1653
|
+
targetMarket,
|
|
1654
|
+
});
|
|
1655
|
+
if (compatible != null) {
|
|
1656
|
+
capCompatibleCandidates.push(compatible);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
return capCompatibleCandidates.sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"))[0];
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* Builds idle and market-source candidates for one eligible target adapter.
|
|
1663
|
+
* Updates shared working data/reserves through candidate steps; do not reuse a prior state.
|
|
1664
|
+
* @internal
|
|
1665
|
+
*/
|
|
1666
|
+
function planTargetAdapterCandidates(params) {
|
|
1667
|
+
const { vaultAddress, data, marketId, adapterIdsCache, getPair, capReserve, reserves, allocatorCapHeadroom, vault, targetMarket, activeAdapters, minimumSupply, adapter, } = params;
|
|
1668
|
+
const rawCandidates = [];
|
|
1669
|
+
if (!(adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2)) {
|
|
1670
|
+
return [];
|
|
1671
|
+
}
|
|
1672
|
+
if (!(0, viem_1.isAddressEqual)(adapter.parentVault, vaultAddress)) {
|
|
1673
|
+
return [];
|
|
1674
|
+
}
|
|
1675
|
+
if (!(0, viem_1.isAddressEqual)(targetMarket.params.loanToken, vault.asset) ||
|
|
1676
|
+
!(0, viem_1.isAddressEqual)(targetMarket.params.irm, adapter.adaptiveCurveIrm)) {
|
|
1677
|
+
return [];
|
|
1678
|
+
}
|
|
1679
|
+
const targetPair = getPair(vaultAddress, adapter, targetMarket);
|
|
1680
|
+
const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
|
|
1681
|
+
const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
|
|
1682
|
+
if (!(0, viem_1.isAddressEqual)(marketPublicAllocatorConfig.vault, vaultAddress) ||
|
|
1683
|
+
!(0, viem_1.isAddressEqual)(marketPublicAllocatorConfig.adapter, adapter.address) ||
|
|
1684
|
+
!activeAdapters.has(adapter.address.toLowerCase())) {
|
|
1685
|
+
return [];
|
|
1686
|
+
}
|
|
1687
|
+
const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
|
|
1688
|
+
const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
|
|
1689
|
+
const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
|
|
1690
|
+
const targetAllocations = [
|
|
1691
|
+
adapterCapAllocation,
|
|
1692
|
+
collateralCapAllocation,
|
|
1693
|
+
adapterMarketCapAllocation,
|
|
1694
|
+
];
|
|
1695
|
+
if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n)) {
|
|
1696
|
+
return [];
|
|
1697
|
+
}
|
|
1698
|
+
const adapterShares = adapter.supplyShares[marketId] ?? 0n;
|
|
1699
|
+
const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
|
|
1700
|
+
const untracked = blue_sdk_1.MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
|
|
1701
|
+
const allocatorHeadroom = blue_sdk_1.MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
|
|
1702
|
+
untracked +
|
|
1703
|
+
targetPair.reserve(reserves)), blue_sdk_1.MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
|
|
1704
|
+
const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
|
|
1705
|
+
const minimumAllocationChange = blue_sdk_1.MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
|
|
1706
|
+
const blockedTargetIds = targetAllocations
|
|
1707
|
+
.filter(({ allocation, absoluteCap, relativeCap, id }) => {
|
|
1708
|
+
const nextAllocation = allocation +
|
|
1709
|
+
capReserve(vaultAddress, id, [targetPair]) +
|
|
1710
|
+
minimumAllocationChange;
|
|
1711
|
+
return (nextAllocation > absoluteCap ||
|
|
1712
|
+
(relativeCap === 0n && nextAllocation > 0n));
|
|
1713
|
+
})
|
|
1714
|
+
.map(({ id }) => id);
|
|
1715
|
+
// MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
|
|
1716
|
+
if (allocatorHeadroom === 0n ||
|
|
1717
|
+
minimumSupply.shares < minimumSupply.assets ||
|
|
1718
|
+
blockedTargetIds.includes(adapterMarketCapId)) {
|
|
1719
|
+
return [];
|
|
1720
|
+
}
|
|
1721
|
+
const sourceParams = {
|
|
1722
|
+
...params,
|
|
1723
|
+
adapter,
|
|
1724
|
+
targetPair,
|
|
1725
|
+
allocatorHeadroom,
|
|
1726
|
+
blockedTargetIds,
|
|
1727
|
+
};
|
|
1728
|
+
const idleCandidate = planIdleCandidate(sourceParams);
|
|
1729
|
+
if (idleCandidate != null) {
|
|
1730
|
+
rawCandidates.push(idleCandidate);
|
|
1731
|
+
}
|
|
1732
|
+
rawCandidates.push(...planSourceAdapterCandidates(sourceParams));
|
|
1733
|
+
return rawCandidates;
|
|
1734
|
+
}
|
|
1735
|
+
/** Builds a vault-idle leg when permissions and target caps allow it. @internal */
|
|
1736
|
+
function planIdleCandidate(params) {
|
|
1737
|
+
const { vaultAddress, adapter, publicAllocatorConfig, availableIdleAssets, blockedTargetIds, targetSupplyHeadroom, allocatorHeadroom, targetPair, } = params;
|
|
1738
|
+
if (publicAllocatorConfig.canPullFromIdle &&
|
|
1739
|
+
availableIdleAssets > 0n &&
|
|
1740
|
+
blockedTargetIds.length === 0) {
|
|
1741
|
+
const assets = blue_sdk_1.MathLib.min(blue_sdk_1.MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
|
|
1742
|
+
if (assets > 0n) {
|
|
1743
|
+
return {
|
|
1744
|
+
reallocation: {
|
|
1745
|
+
vault: vaultAddress,
|
|
1746
|
+
from: { type: "idle" },
|
|
1747
|
+
to: { adapter: adapter.address },
|
|
1748
|
+
assets,
|
|
1749
|
+
penalty: publicAllocatorConfig.penalty,
|
|
1750
|
+
},
|
|
1751
|
+
targetPair,
|
|
1752
|
+
allocatorHeadroom,
|
|
1753
|
+
};
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
/**
|
|
1758
|
+
* Walks authorized source adapters in snapshot order for one target position.
|
|
1759
|
+
* Source steps update the shared working data in place; do not reuse a prior state.
|
|
1760
|
+
* @internal
|
|
1761
|
+
*/
|
|
1762
|
+
function planSourceAdapterCandidates(params) {
|
|
1763
|
+
const { vault, vaultAddress, activeAdapters } = params;
|
|
1764
|
+
const candidates = [];
|
|
1765
|
+
for (const sourceAdapter of vault.accrualAdapters) {
|
|
1766
|
+
if (!(sourceAdapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2)) {
|
|
1767
|
+
continue;
|
|
1768
|
+
}
|
|
1769
|
+
if (!(0, viem_1.isAddressEqual)(sourceAdapter.parentVault, vaultAddress)) {
|
|
1770
|
+
continue;
|
|
1771
|
+
}
|
|
1772
|
+
if (!activeAdapters.has(sourceAdapter.address.toLowerCase())) {
|
|
1773
|
+
continue;
|
|
1774
|
+
}
|
|
1775
|
+
for (const sourceMarketReference of sourceAdapter.markets) {
|
|
1776
|
+
const candidate = planSourceMarketCandidate({
|
|
1777
|
+
...params,
|
|
1778
|
+
sourceAdapter,
|
|
1779
|
+
sourceMarketReference,
|
|
1780
|
+
});
|
|
1781
|
+
if (candidate != null) {
|
|
1782
|
+
candidates.push(candidate);
|
|
1864
1783
|
}
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
return candidates;
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Plans a source-market withdrawal, accruing the same working market state.
|
|
1790
|
+
* Updates the working data clone in place via setMarkets; the caller retains that same
|
|
1791
|
+
* object, even when no candidate is returned. Do not reuse a prior state after this step.
|
|
1792
|
+
* @internal
|
|
1793
|
+
*/
|
|
1794
|
+
function planSourceMarketCandidate(params) {
|
|
1795
|
+
const { data, vault, vaultAddress, sourceAdapter, sourceMarketReference, normalizedMarketId, adapterIdsCache, blockedTargetIds, getPair, timestamp, setMarkets, targetSupplyHeadroom, allocatorHeadroom, maxWithdrawalUtilization, adapter, publicAllocatorConfig, targetPair, } = params;
|
|
1796
|
+
const sourceMarket = data.getMarket(sourceMarketReference.id);
|
|
1797
|
+
if (!(0, viem_1.isAddressEqual)(sourceMarket.params.loanToken, vault.asset) ||
|
|
1798
|
+
!(0, viem_1.isAddressEqual)(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm)) {
|
|
1799
|
+
return;
|
|
1800
|
+
}
|
|
1801
|
+
if (sourceMarket.id.toLowerCase() === normalizedMarketId) {
|
|
1802
|
+
return;
|
|
1803
|
+
}
|
|
1804
|
+
const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
|
|
1805
|
+
const [, , sourceAdapterMarketCapId] = sourceIds;
|
|
1806
|
+
const sourceConfig = data.getMarketPublicAllocatorConfig(vaultAddress, sourceAdapterMarketCapId);
|
|
1807
|
+
if (!(0, viem_1.isAddressEqual)(sourceConfig.vault, vaultAddress) ||
|
|
1808
|
+
!(0, viem_1.isAddressEqual)(sourceConfig.adapter, sourceAdapter.address) ||
|
|
1809
|
+
!sourceConfig.canPullFromMarket) {
|
|
1810
|
+
return;
|
|
1811
|
+
}
|
|
1812
|
+
const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
|
|
1813
|
+
if (sourceAllocations.some(({ allocation }) => allocation === 0n)) {
|
|
1814
|
+
return;
|
|
1815
|
+
}
|
|
1816
|
+
const sourceSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
|
|
1817
|
+
if (sourceSupplyShares === 0n) {
|
|
1818
|
+
return;
|
|
1819
|
+
}
|
|
1820
|
+
// A withdrawal can create target headroom only for shared cap IDs.
|
|
1821
|
+
if (blockedTargetIds.some((id) => !sourceIds.includes(id))) {
|
|
1822
|
+
return;
|
|
1823
|
+
}
|
|
1824
|
+
const sourcePair = getPair(vaultAddress, sourceAdapter, sourceMarket);
|
|
1825
|
+
const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
|
|
1826
|
+
setMarkets([accruedSourceMarket]);
|
|
1827
|
+
const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
|
|
1828
|
+
const assets = blue_sdk_1.MathLib.min(blue_sdk_1.MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, accruedSourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
|
|
1829
|
+
if (assets <= 0n) {
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
return {
|
|
1833
|
+
reallocation: {
|
|
1834
|
+
vault: vaultAddress,
|
|
1835
|
+
from: {
|
|
1836
|
+
type: "market",
|
|
1837
|
+
adapter: sourceAdapter.address,
|
|
1838
|
+
marketParams: sourceMarket.params,
|
|
1839
|
+
},
|
|
1840
|
+
to: { adapter: adapter.address },
|
|
1841
|
+
assets,
|
|
1842
|
+
penalty: publicAllocatorConfig.penalty,
|
|
1843
|
+
},
|
|
1844
|
+
targetPair,
|
|
1845
|
+
sourcePair,
|
|
1846
|
+
allocatorHeadroom,
|
|
1847
|
+
};
|
|
1848
|
+
}
|
|
1849
|
+
/**
|
|
1850
|
+
* Fits a raw candidate to non-shared upper bounds and shared-cap rounding.
|
|
1851
|
+
* Cap reserve reads populate shared working reserve caches; do not reuse a prior state.
|
|
1852
|
+
* @internal
|
|
1853
|
+
*/
|
|
1854
|
+
function fitCandidateCaps(params) {
|
|
1855
|
+
const { reallocation, targetPair, sourcePair, allocatorHeadroom, capReserve, remainingAssets, } = params;
|
|
1856
|
+
const targetIds = targetPair.ids;
|
|
1857
|
+
const sourceIds = new Set(sourcePair?.ids ?? []);
|
|
1858
|
+
const reserveById = new Map();
|
|
1859
|
+
for (const id of targetIds) {
|
|
1860
|
+
reserveById.set(id, capReserve(reallocation.vault, id, sourcePair == null ? [targetPair] : [targetPair, sourcePair]));
|
|
1861
|
+
}
|
|
1862
|
+
const probeParams = { ...params, targetIds, sourceIds, reserveById };
|
|
1863
|
+
// Non-shared target IDs impose monotonic upper bounds. Shared IDs
|
|
1864
|
+
// can impose lower bounds and non-monotonic rounding constraints,
|
|
1865
|
+
// so validate them after selecting the non-shared maximum.
|
|
1866
|
+
const lower = findCandidateUpperBound(probeParams);
|
|
1867
|
+
let selectedAssets = blue_sdk_1.MathLib.min(lower, remainingAssets ?? reallocation.assets);
|
|
1868
|
+
let probe = selectedAssets > 0n
|
|
1869
|
+
? probeCandidateReallocation({ ...probeParams, assets: selectedAssets })
|
|
1870
|
+
: undefined;
|
|
1871
|
+
if (remainingAssets != null && probe?.withinAllCaps !== true) {
|
|
1872
|
+
// Bound the base-unit scan; expose a caller ceiling if wider searches become necessary.
|
|
1873
|
+
const searchUpper = blue_sdk_1.MathLib.min(lower, selectedAssets + MAX_SHARED_CAP_SEARCH_STEPS);
|
|
1874
|
+
while (selectedAssets > 0n &&
|
|
1875
|
+
selectedAssets < searchUpper &&
|
|
1876
|
+
probe?.withinAllCaps !== true) {
|
|
1877
|
+
selectedAssets += 1n;
|
|
1878
|
+
probe = probeCandidateReallocation({
|
|
1879
|
+
...probeParams,
|
|
1880
|
+
assets: selectedAssets,
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
if (selectedAssets > 0n && probe?.withinAllCaps === true) {
|
|
1885
|
+
return {
|
|
1886
|
+
reallocation: { ...reallocation, assets: selectedAssets },
|
|
1887
|
+
targetPair,
|
|
1888
|
+
sourcePair,
|
|
1889
|
+
allocatorHeadroom,
|
|
1890
|
+
};
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
/** Simulates one candidate amount and tests its reserved target-cap headroom. @internal */
|
|
1894
|
+
function probeCandidateReallocation(params) {
|
|
1895
|
+
const { assets, targetMarket, applyPublicReallocation, simulationContext, reallocation, marketId, adapterIdsCache, targetIds, sourceIds, reserveById, } = params;
|
|
1896
|
+
if (targetMarket.totalSupplyShares +
|
|
1897
|
+
targetMarket.toSupplyShares(assets, "Down") >
|
|
1898
|
+
blue_sdk_1.MathLib.MAX_UINT_128) {
|
|
1899
|
+
return;
|
|
1900
|
+
}
|
|
1901
|
+
const postTransition = (0, morpho_ts_1._try)(() => applyPublicReallocation({
|
|
1902
|
+
context: simulationContext,
|
|
1903
|
+
reallocation: { ...reallocation, assets },
|
|
1904
|
+
targetMarketId: marketId,
|
|
1905
|
+
timestamp: targetMarket.lastUpdate,
|
|
1906
|
+
adapterIdsCache,
|
|
1907
|
+
probe: true,
|
|
1908
|
+
}), index_js_1.ReallocationAllocationUnderflowError, index_js_1.ReallocationAdapterSupplySharesUnderflowError);
|
|
1909
|
+
if (postTransition == null) {
|
|
1910
|
+
return;
|
|
1911
|
+
}
|
|
1912
|
+
// Vault V2 checks relative caps against the transient firstTotalAssets,
|
|
1913
|
+
// which stays fixed after the vault's first allocation in a transaction.
|
|
1914
|
+
const { firstTotalAssets } = postTransition;
|
|
1915
|
+
let withinUpperBounds = true;
|
|
1916
|
+
let withinAllCaps = true;
|
|
1917
|
+
for (const id of targetIds) {
|
|
1918
|
+
const allocation = postTransition.data.getAllocation(reallocation.vault, id);
|
|
1919
|
+
const capacity = blue_sdk_1.VaultV2Utils.allocationHeadroom({ ...allocation, allocation: 0n }, firstTotalAssets).value;
|
|
1920
|
+
// The reserve covers interest accrued before inclusion by every
|
|
1921
|
+
// position the plan touched on this cap id, as booked onchain.
|
|
1922
|
+
const withinCap = allocation.absoluteCap > 0n &&
|
|
1923
|
+
allocation.allocation + (reserveById.get(id) ?? 0n) <= capacity;
|
|
1924
|
+
if (!withinCap) {
|
|
1925
|
+
withinAllCaps = false;
|
|
1926
|
+
if (!sourceIds.has(id)) {
|
|
1927
|
+
withinUpperBounds = false;
|
|
1869
1928
|
}
|
|
1870
1929
|
}
|
|
1871
1930
|
}
|
|
1931
|
+
return { withinAllCaps, withinUpperBounds };
|
|
1932
|
+
}
|
|
1933
|
+
/** Bisects the monotonic non-shared target-cap upper bound. @internal */
|
|
1934
|
+
function findCandidateUpperBound(probeParams) {
|
|
1935
|
+
let lower = 0n;
|
|
1936
|
+
let upper = probeParams.reallocation.assets;
|
|
1937
|
+
let probeUpper = true;
|
|
1938
|
+
while (lower < upper) {
|
|
1939
|
+
const assets = probeUpper ? upper : (lower + upper + 1n) / 2n;
|
|
1940
|
+
probeUpper = false;
|
|
1941
|
+
if (probeCandidateReallocation({ ...probeParams, assets })
|
|
1942
|
+
?.withinUpperBounds === true) {
|
|
1943
|
+
lower = assets;
|
|
1944
|
+
}
|
|
1945
|
+
else {
|
|
1946
|
+
upper = assets - 1n;
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
return lower;
|
|
1950
|
+
}
|
|
1951
|
+
/** Tracks shared-Blue transfer funding in the reallocation's execution order. @internal */
|
|
1952
|
+
function getReallocationTransferShortfall(reallocations, blueBalance) {
|
|
1953
|
+
const penaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
|
|
1954
|
+
if (penaltyAssets === 0n) {
|
|
1955
|
+
return 0n;
|
|
1956
|
+
}
|
|
1957
|
+
let shortfall = blue_sdk_1.MathLib.zeroFloorSub(penaltyAssets, blueBalance);
|
|
1958
|
+
let balance = blue_sdk_1.MathLib.zeroFloorSub(blueBalance, penaltyAssets);
|
|
1959
|
+
for (const { from, assets } of reallocations) {
|
|
1960
|
+
if (from.type === "idle") {
|
|
1961
|
+
balance += assets;
|
|
1962
|
+
}
|
|
1963
|
+
else {
|
|
1964
|
+
shortfall = blue_sdk_1.MathLib.max(shortfall, blue_sdk_1.MathLib.zeroFloorSub(assets, balance));
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
return shortfall;
|
|
1968
|
+
}
|
|
1969
|
+
/** Plans one operation budget across penalty tiers and utilization passes. @internal */
|
|
1970
|
+
function planVaultOperation(params) {
|
|
1971
|
+
const { initialMarkets, initialData, absoluteShortfall, penaltyTiers, type } = params;
|
|
1972
|
+
const reserves = createCapReserveState(initialMarkets);
|
|
1973
|
+
const reallocations = [];
|
|
1974
|
+
const data = initialData.clone();
|
|
1975
|
+
const context = createSimulationContext();
|
|
1976
|
+
const remainingShortfall = absoluteShortfall;
|
|
1977
|
+
const accountingShortfall = absoluteShortfall;
|
|
1978
|
+
const allocatorCapBoundTargets = new Set();
|
|
1979
|
+
const idleBoundVaults = new Set();
|
|
1980
|
+
let state = {
|
|
1981
|
+
reserves,
|
|
1982
|
+
reallocations,
|
|
1983
|
+
data,
|
|
1984
|
+
context,
|
|
1985
|
+
remainingShortfall,
|
|
1986
|
+
accountingShortfall,
|
|
1987
|
+
allocatorCapBoundTargets,
|
|
1988
|
+
idleBoundVaults,
|
|
1989
|
+
};
|
|
1990
|
+
for (const penalty of penaltyTiers) {
|
|
1991
|
+
if (type === "refinance" && penalty === blue_sdk_1.MathLib.WAD) {
|
|
1992
|
+
continue;
|
|
1993
|
+
}
|
|
1994
|
+
state = planOperationPenaltyTier({ ...params, penalty, state });
|
|
1995
|
+
}
|
|
1996
|
+
return summarizeOperationPlan({ ...params, state });
|
|
1997
|
+
}
|
|
1998
|
+
/**
|
|
1999
|
+
* Runs friendly then full-utilization passes at one allocator penalty.
|
|
2000
|
+
* Passes update working data/reserves in place, which the returned state may share.
|
|
2001
|
+
* Do not reuse a prior state after this step.
|
|
2002
|
+
* @internal
|
|
2003
|
+
*/
|
|
2004
|
+
function planOperationPenaltyTier(params) {
|
|
2005
|
+
const { penalty, maxWithdrawalUtilization } = params;
|
|
2006
|
+
let state = params.state;
|
|
2007
|
+
let isFriendlyPass = true;
|
|
2008
|
+
let triedFullCapacityAttempt = false;
|
|
2009
|
+
for (const utilization of [maxWithdrawalUtilization, blue_sdk_1.MathLib.WAD]) {
|
|
2010
|
+
const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
|
|
2011
|
+
isFriendlyPass = false;
|
|
2012
|
+
if (state.remainingShortfall === 0n && !isFreeFriendlyPass) {
|
|
2013
|
+
continue;
|
|
2014
|
+
}
|
|
2015
|
+
const result = planOperationUtilizationPass({
|
|
2016
|
+
...params,
|
|
2017
|
+
state,
|
|
2018
|
+
utilization,
|
|
2019
|
+
penalty,
|
|
2020
|
+
isFreeFriendlyPass,
|
|
2021
|
+
triedFullCapacityAttempt,
|
|
2022
|
+
});
|
|
2023
|
+
state = result.state;
|
|
2024
|
+
triedFullCapacityAttempt = result.triedFullCapacityAttempt;
|
|
2025
|
+
}
|
|
2026
|
+
return state;
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* Executes and, for paid passes, retries one utilization budget.
|
|
2030
|
+
* Updates working data/reserves in place; the returned state may share those objects
|
|
2031
|
+
* rather than an isolated snapshot. Do not reuse a prior state after this step.
|
|
2032
|
+
* @internal
|
|
2033
|
+
*/
|
|
2034
|
+
function planOperationUtilizationPass(params) {
|
|
2035
|
+
const { penalty } = params;
|
|
2036
|
+
let state = {
|
|
2037
|
+
...params.state,
|
|
2038
|
+
reallocations: [...params.state.reallocations],
|
|
2039
|
+
};
|
|
2040
|
+
let triedFullCapacityAttempt = params.triedFullCapacityAttempt;
|
|
2041
|
+
let passMaxAssets = getOperationPassBudget(params);
|
|
2042
|
+
const retryPaidPass = penalty > 0n;
|
|
2043
|
+
let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
|
|
2044
|
+
let tryFullCapacityAttempt = false;
|
|
2045
|
+
let isFullCapacityRetryPath = false;
|
|
2046
|
+
const beforePassRemainingShortfall = state.remainingShortfall;
|
|
2047
|
+
const beforePassAccountingShortfall = state.accountingShortfall;
|
|
2048
|
+
// Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
|
|
2049
|
+
const passStart = retryPaidPass
|
|
2050
|
+
? {
|
|
2051
|
+
data: state.data.clone(),
|
|
2052
|
+
context: state.context,
|
|
2053
|
+
reserves: cloneCapReserveState(state.reserves),
|
|
2054
|
+
reallocationCount: state.reallocations.length,
|
|
2055
|
+
}
|
|
2056
|
+
: undefined;
|
|
2057
|
+
let previousPassReallocatedAssets = 0n;
|
|
2058
|
+
let previousPhysicalShortfall;
|
|
2059
|
+
let hi;
|
|
2060
|
+
let bestAttempt;
|
|
2061
|
+
while (true) {
|
|
2062
|
+
const isFullCapacityAttempt = tryFullCapacityAttempt;
|
|
2063
|
+
tryFullCapacityAttempt = false;
|
|
2064
|
+
if (passStart != null) {
|
|
2065
|
+
state = restoreOperationPassStart({ state, passStart });
|
|
2066
|
+
}
|
|
2067
|
+
const attempt = executeOperationAttempt({
|
|
2068
|
+
...params,
|
|
2069
|
+
state,
|
|
2070
|
+
isFullCapacityAttempt,
|
|
2071
|
+
passMaxAssets,
|
|
2072
|
+
isFullCapacityRetryPath,
|
|
2073
|
+
});
|
|
2074
|
+
state = attempt.state;
|
|
2075
|
+
const { pass, physicalShortfall, attemptTransferShortfall, attemptCoversShortfall, passReallocatedAssets, } = attempt;
|
|
2076
|
+
if (passStart == null) {
|
|
2077
|
+
break;
|
|
2078
|
+
}
|
|
2079
|
+
if (isFullCapacityAttempt) {
|
|
2080
|
+
passMaxAssets = passReallocatedAssets;
|
|
2081
|
+
}
|
|
2082
|
+
bestAttempt = chooseOperationBestAttempt({
|
|
2083
|
+
...params,
|
|
2084
|
+
state,
|
|
2085
|
+
bestAttempt,
|
|
2086
|
+
beforePassAccountingShortfall,
|
|
2087
|
+
isFullCapacityRetryPath,
|
|
2088
|
+
attemptCoversShortfall,
|
|
2089
|
+
attemptTransferShortfall,
|
|
2090
|
+
passReallocatedAssets,
|
|
2091
|
+
passReallocations: pass.reallocations,
|
|
2092
|
+
});
|
|
2093
|
+
const next = advanceOperationPassSearch({
|
|
2094
|
+
lo,
|
|
2095
|
+
hi,
|
|
2096
|
+
passMaxAssets,
|
|
2097
|
+
triedFullCapacityAttempt,
|
|
2098
|
+
tryFullCapacityAttempt,
|
|
2099
|
+
isFullCapacityRetryPath,
|
|
2100
|
+
previousPhysicalShortfall,
|
|
2101
|
+
previousPassReallocatedAssets,
|
|
2102
|
+
isFullCapacityAttempt,
|
|
2103
|
+
attemptCoversShortfall,
|
|
2104
|
+
accountingShortfall: state.accountingShortfall,
|
|
2105
|
+
physicalShortfall,
|
|
2106
|
+
passReallocatedAssets,
|
|
2107
|
+
remainingShortfall: state.remainingShortfall,
|
|
2108
|
+
penalty,
|
|
2109
|
+
});
|
|
2110
|
+
if (next.type === "break") {
|
|
2111
|
+
break;
|
|
2112
|
+
}
|
|
2113
|
+
({
|
|
2114
|
+
lo,
|
|
2115
|
+
hi,
|
|
2116
|
+
passMaxAssets,
|
|
2117
|
+
triedFullCapacityAttempt,
|
|
2118
|
+
tryFullCapacityAttempt,
|
|
2119
|
+
isFullCapacityRetryPath,
|
|
2120
|
+
previousPhysicalShortfall,
|
|
2121
|
+
previousPassReallocatedAssets,
|
|
2122
|
+
} = next);
|
|
2123
|
+
}
|
|
2124
|
+
const finalState = finishOperationPass({
|
|
2125
|
+
...params,
|
|
2126
|
+
state,
|
|
2127
|
+
passStart,
|
|
2128
|
+
bestAttempt,
|
|
2129
|
+
beforePassRemainingShortfall,
|
|
2130
|
+
beforePassAccountingShortfall,
|
|
2131
|
+
});
|
|
2132
|
+
return {
|
|
2133
|
+
state: finalState,
|
|
2134
|
+
triedFullCapacityAttempt,
|
|
2135
|
+
};
|
|
2136
|
+
}
|
|
2137
|
+
/**
|
|
2138
|
+
* Restores working data and reserves and truncates the shared reallocation array in place.
|
|
2139
|
+
* Other attempt results remain available to the retry search.
|
|
2140
|
+
* @internal
|
|
2141
|
+
*/
|
|
2142
|
+
function restoreOperationPassStart({ state, passStart, }) {
|
|
2143
|
+
const data = passStart.data.clone();
|
|
2144
|
+
const context = passStart.context;
|
|
2145
|
+
const reserves = cloneCapReserveState(passStart.reserves);
|
|
2146
|
+
state.reallocations.length = passStart.reallocationCount;
|
|
2147
|
+
return { ...state, data, context, reserves };
|
|
2148
|
+
}
|
|
2149
|
+
/** Summarizes liquidity-bound legs and the accounting and physical funding result. @internal */
|
|
2150
|
+
function summarizeOperationPlan(params) {
|
|
2151
|
+
const { maxAssets, headroom, type, amount, feeAssets, blueBalance, absoluteShortfall, hasExplicitBlueBalance, } = params;
|
|
2152
|
+
const { reallocations, data, allocatorCapBoundTargets, idleBoundVaults } = params.state;
|
|
2153
|
+
let reallocatedAssets = 0n;
|
|
2154
|
+
let unboundAssets = 0n;
|
|
2155
|
+
for (const { vault, from, to, assets } of reallocations) {
|
|
2156
|
+
reallocatedAssets += assets;
|
|
2157
|
+
const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
|
|
2158
|
+
if (!allocatorCapBoundTargets.has(key) &&
|
|
2159
|
+
!(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase()))) {
|
|
2160
|
+
unboundAssets += assets;
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
const penaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
|
|
2164
|
+
const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
|
|
2165
|
+
const physicalShortfall = penaltyAssets === 0n
|
|
2166
|
+
? 0n
|
|
2167
|
+
: blue_sdk_1.MathLib.zeroFloorSub((type === "refinance" ? amount + feeAssets + penaltyAssets : amount) +
|
|
2168
|
+
penaltyAssets, blueBalance + idleAssets);
|
|
2169
|
+
const transferShortfall = getReallocationTransferShortfall(reallocations, blueBalance);
|
|
2170
|
+
const coversAccountingShortfall = type === "refinance"
|
|
2171
|
+
? reallocatedAssets >= absoluteShortfall + penaltyAssets
|
|
2172
|
+
: reallocatedAssets >= absoluteShortfall;
|
|
2173
|
+
return {
|
|
2174
|
+
maxAssets,
|
|
2175
|
+
headroom,
|
|
2176
|
+
reallocations,
|
|
2177
|
+
data,
|
|
2178
|
+
liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
|
|
2179
|
+
reallocatedAssets,
|
|
2180
|
+
unboundAssets,
|
|
2181
|
+
physicalShortfall,
|
|
2182
|
+
coversShortfall: coversAccountingShortfall &&
|
|
2183
|
+
(type === "refinance" || penaltyAssets <= amount) &&
|
|
2184
|
+
(!hasExplicitBlueBalance ||
|
|
2185
|
+
(physicalShortfall === 0n && transferShortfall === 0n)),
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
/** Sizes a pass for its accounting gap and optional physical penalty funding. @internal */
|
|
2189
|
+
function getOperationPassBudget(params) {
|
|
2190
|
+
const { type, penalty, isFreeFriendlyPass, maxAssets, usePhysicalBalance, amount, feeAssets, blueBalance, } = params;
|
|
2191
|
+
const { remainingShortfall, reallocations } = params.state;
|
|
2192
|
+
let passMaxAssets = remainingShortfall;
|
|
2193
|
+
if (type === "refinance" && penalty > 0n) {
|
|
2194
|
+
passMaxAssets = blue_sdk_1.MathLib.mulDivUp(remainingShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - penalty);
|
|
2195
|
+
}
|
|
2196
|
+
else if (isFreeFriendlyPass) {
|
|
2197
|
+
passMaxAssets = maxAssets;
|
|
2198
|
+
}
|
|
2199
|
+
if (usePhysicalBalance && penalty > 0n) {
|
|
2200
|
+
const penaltyMultiplier = type === "refinance" ? 2n : 1n;
|
|
2201
|
+
const physicalPenalty = penaltyMultiplier * penalty;
|
|
2202
|
+
if (physicalPenalty < blue_sdk_1.MathLib.WAD) {
|
|
2203
|
+
const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
|
|
2204
|
+
// Idle must fund both the operation and its penalty flash loan.
|
|
2205
|
+
const physicalShortfall = blue_sdk_1.MathLib.zeroFloorSub(amount +
|
|
2206
|
+
feeAssets +
|
|
2207
|
+
penaltyMultiplier * (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations), blueBalance + idleAssets);
|
|
2208
|
+
passMaxAssets = blue_sdk_1.MathLib.max(passMaxAssets, blue_sdk_1.MathLib.mulDivUp(physicalShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - physicalPenalty));
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
return passMaxAssets;
|
|
2212
|
+
}
|
|
2213
|
+
/**
|
|
2214
|
+
* Executes one pass attempt and returns its updated state and funding gaps.
|
|
2215
|
+
* Updates working data/reserves in place via runUtilizationPass; the returned state
|
|
2216
|
+
* shares those objects. Callers must not reuse a prior state after this step.
|
|
2217
|
+
* @internal
|
|
2218
|
+
*/
|
|
2219
|
+
function executeOperationAttempt(params) {
|
|
2220
|
+
const { type, amount, feeAssets, blueBalance, capAccrualBuffer, normalizedOptions, hasExplicitBlueBalance, marketId, headroom, utilization, penalty, isFreeFriendlyPass, runUtilizationPass, isFullCapacityAttempt, passMaxAssets, isFullCapacityRetryPath, } = params;
|
|
2221
|
+
let { reserves, data, context, remainingShortfall, accountingShortfall, allocatorCapBoundTargets, idleBoundVaults, } = params.state;
|
|
2222
|
+
const reallocations = [...params.state.reallocations];
|
|
2223
|
+
const pass = runUtilizationPass(data, {
|
|
2224
|
+
context,
|
|
2225
|
+
reserves,
|
|
2226
|
+
marketId,
|
|
2227
|
+
maxWithdrawalUtilization: utilization,
|
|
2228
|
+
maxAssets: isFullCapacityAttempt ? undefined : passMaxAssets,
|
|
2229
|
+
capAccrualBuffer,
|
|
2230
|
+
allocatorCapHeadroom: headroom,
|
|
2231
|
+
penalty,
|
|
2232
|
+
options: normalizedOptions,
|
|
2233
|
+
});
|
|
2234
|
+
reallocations.push(...pass.reallocations);
|
|
2235
|
+
data = pass.data;
|
|
2236
|
+
context = pass.context;
|
|
2237
|
+
if (isFreeFriendlyPass) {
|
|
2238
|
+
allocatorCapBoundTargets = pass.allocatorCapBoundTargets;
|
|
2239
|
+
idleBoundVaults = pass.idleBoundVaults;
|
|
2240
|
+
}
|
|
2241
|
+
const currentMarket = data.getMarket(marketId);
|
|
2242
|
+
const penaltyAssets = type === "refinance" ? (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations) : 0n;
|
|
2243
|
+
let borrow;
|
|
2244
|
+
switch (type) {
|
|
2245
|
+
case "borrow":
|
|
2246
|
+
borrow = currentMarket.totalBorrowAssets + amount;
|
|
2247
|
+
break;
|
|
2248
|
+
case "refinance":
|
|
2249
|
+
borrow =
|
|
2250
|
+
currentMarket.totalBorrowAssets + amount + feeAssets + penaltyAssets;
|
|
2251
|
+
break;
|
|
2252
|
+
default:
|
|
2253
|
+
borrow = currentMarket.totalBorrowAssets;
|
|
2254
|
+
}
|
|
2255
|
+
const supply = type === "withdraw"
|
|
2256
|
+
? currentMarket.totalSupplyAssets - amount
|
|
2257
|
+
: currentMarket.totalSupplyAssets;
|
|
2258
|
+
accountingShortfall = borrow > supply ? borrow - supply : 0n;
|
|
2259
|
+
const penaltyForPhysicalShortfall = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
|
|
2260
|
+
const idleAssetsForPhysicalShortfall = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
|
|
2261
|
+
const physicalShortfall = penaltyForPhysicalShortfall === 0n
|
|
2262
|
+
? 0n
|
|
2263
|
+
: blue_sdk_1.MathLib.zeroFloorSub((type === "refinance"
|
|
2264
|
+
? amount + feeAssets + penaltyForPhysicalShortfall
|
|
2265
|
+
: amount) + penaltyForPhysicalShortfall, blueBalance + idleAssetsForPhysicalShortfall);
|
|
2266
|
+
remainingShortfall = blue_sdk_1.MathLib.max(accountingShortfall, physicalShortfall);
|
|
2267
|
+
const attemptTransferShortfall = hasExplicitBlueBalance && isFullCapacityRetryPath
|
|
2268
|
+
? getReallocationTransferShortfall(reallocations, blueBalance)
|
|
2269
|
+
: 0n;
|
|
2270
|
+
const attemptCoversShortfall = remainingShortfall === 0n;
|
|
2271
|
+
const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
|
|
2272
|
+
return {
|
|
2273
|
+
state: {
|
|
2274
|
+
reserves,
|
|
2275
|
+
reallocations,
|
|
2276
|
+
data,
|
|
2277
|
+
context,
|
|
2278
|
+
remainingShortfall,
|
|
2279
|
+
accountingShortfall,
|
|
2280
|
+
allocatorCapBoundTargets,
|
|
2281
|
+
idleBoundVaults,
|
|
2282
|
+
},
|
|
2283
|
+
pass,
|
|
2284
|
+
physicalShortfall,
|
|
2285
|
+
attemptTransferShortfall,
|
|
2286
|
+
attemptCoversShortfall,
|
|
2287
|
+
passReallocatedAssets,
|
|
2288
|
+
};
|
|
2289
|
+
}
|
|
2290
|
+
/** Retains the best feasible paid-pass attempt with the original priority ordering. @internal */
|
|
2291
|
+
function chooseOperationBestAttempt(params) {
|
|
2292
|
+
const { hasExplicitBlueBalance, bestAttempt, beforePassAccountingShortfall, isFullCapacityRetryPath, attemptCoversShortfall, attemptTransferShortfall, passReallocatedAssets, passReallocations, } = params;
|
|
2293
|
+
const { data, context, reserves, remainingShortfall, accountingShortfall } = params.state;
|
|
2294
|
+
const improvesAccounting = accountingShortfall < beforePassAccountingShortfall;
|
|
2295
|
+
const attemptPriority = hasExplicitBlueBalance
|
|
2296
|
+
? [0n, remainingShortfall, 0n, passReallocatedAssets]
|
|
2297
|
+
: [
|
|
2298
|
+
improvesAccounting ? 0n : 1n,
|
|
2299
|
+
improvesAccounting ? accountingShortfall : 0n,
|
|
2300
|
+
remainingShortfall,
|
|
2301
|
+
passReallocatedAssets,
|
|
2302
|
+
];
|
|
2303
|
+
const previousBestAttempt = bestAttempt;
|
|
2304
|
+
let isBetterAttempt = previousBestAttempt == null;
|
|
2305
|
+
if (previousBestAttempt != null) {
|
|
2306
|
+
const firstDifference = attemptPriority.findIndex((candidatePriority, index) => candidatePriority !== previousBestAttempt.priority[index]);
|
|
2307
|
+
const priority = attemptPriority[firstDifference];
|
|
2308
|
+
const previousPriority = previousBestAttempt.priority[firstDifference];
|
|
2309
|
+
isBetterAttempt =
|
|
2310
|
+
priority != null &&
|
|
2311
|
+
previousPriority != null &&
|
|
2312
|
+
priority < previousPriority;
|
|
2313
|
+
}
|
|
2314
|
+
if (isBetterAttempt &&
|
|
2315
|
+
(!isFullCapacityRetryPath ||
|
|
2316
|
+
(attemptCoversShortfall && attemptTransferShortfall === 0n))) {
|
|
2317
|
+
return {
|
|
2318
|
+
data,
|
|
2319
|
+
context,
|
|
2320
|
+
reserves: cloneCapReserveState(reserves),
|
|
2321
|
+
reallocations: passReallocations,
|
|
2322
|
+
remainingShortfall,
|
|
2323
|
+
accountingShortfall,
|
|
2324
|
+
passReallocatedAssets,
|
|
2325
|
+
priority: attemptPriority,
|
|
2326
|
+
};
|
|
2327
|
+
}
|
|
2328
|
+
return bestAttempt;
|
|
2329
|
+
}
|
|
2330
|
+
/** Advances bisection or grossed-up retries, stopping on stalled physical funding. @internal */
|
|
2331
|
+
function advanceOperationPassSearch(params) {
|
|
2332
|
+
let { lo, hi, passMaxAssets, triedFullCapacityAttempt, tryFullCapacityAttempt, isFullCapacityRetryPath, previousPhysicalShortfall, previousPassReallocatedAssets, } = params;
|
|
2333
|
+
const { isFullCapacityAttempt, attemptCoversShortfall, accountingShortfall, physicalShortfall, passReallocatedAssets, remainingShortfall, penalty, } = params;
|
|
2334
|
+
({ lo, hi } = updateOperationSearchBracket({
|
|
2335
|
+
lo,
|
|
2336
|
+
hi,
|
|
2337
|
+
passMaxAssets,
|
|
2338
|
+
attemptCoversShortfall,
|
|
2339
|
+
}));
|
|
2340
|
+
if (hi != null) {
|
|
2341
|
+
if (hi - lo <= 1n) {
|
|
2342
|
+
return { type: "break" };
|
|
2343
|
+
}
|
|
2344
|
+
passMaxAssets = (lo + hi) / 2n;
|
|
2345
|
+
return {
|
|
2346
|
+
type: "continue",
|
|
2347
|
+
lo,
|
|
2348
|
+
hi,
|
|
2349
|
+
passMaxAssets,
|
|
2350
|
+
triedFullCapacityAttempt,
|
|
2351
|
+
tryFullCapacityAttempt,
|
|
2352
|
+
isFullCapacityRetryPath,
|
|
2353
|
+
previousPhysicalShortfall,
|
|
2354
|
+
previousPassReallocatedAssets,
|
|
2355
|
+
};
|
|
2356
|
+
}
|
|
2357
|
+
if (isFullCapacityAttempt && !attemptCoversShortfall) {
|
|
2358
|
+
return { type: "break" };
|
|
2359
|
+
}
|
|
2360
|
+
if (accountingShortfall === 0n &&
|
|
2361
|
+
previousPhysicalShortfall != null &&
|
|
2362
|
+
physicalShortfall >= previousPhysicalShortfall) {
|
|
2363
|
+
if (!triedFullCapacityAttempt && passReallocatedAssets === passMaxAssets) {
|
|
2364
|
+
triedFullCapacityAttempt = true;
|
|
2365
|
+
tryFullCapacityAttempt = true;
|
|
2366
|
+
isFullCapacityRetryPath = true;
|
|
2367
|
+
return {
|
|
2368
|
+
type: "continue",
|
|
2369
|
+
lo,
|
|
2370
|
+
hi,
|
|
2371
|
+
passMaxAssets,
|
|
2372
|
+
triedFullCapacityAttempt,
|
|
2373
|
+
tryFullCapacityAttempt,
|
|
2374
|
+
isFullCapacityRetryPath,
|
|
2375
|
+
previousPhysicalShortfall,
|
|
2376
|
+
previousPassReallocatedAssets,
|
|
2377
|
+
};
|
|
2378
|
+
}
|
|
2379
|
+
return { type: "break" };
|
|
2380
|
+
}
|
|
2381
|
+
previousPhysicalShortfall = physicalShortfall;
|
|
2382
|
+
if (passReallocatedAssets <= previousPassReallocatedAssets ||
|
|
2383
|
+
penalty === blue_sdk_1.MathLib.WAD) {
|
|
2384
|
+
return { type: "break" };
|
|
2385
|
+
}
|
|
2386
|
+
previousPassReallocatedAssets = passReallocatedAssets;
|
|
2387
|
+
passMaxAssets += blue_sdk_1.MathLib.mulDivUp(remainingShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - penalty);
|
|
2388
|
+
return {
|
|
2389
|
+
type: "continue",
|
|
2390
|
+
lo,
|
|
2391
|
+
hi,
|
|
2392
|
+
passMaxAssets,
|
|
2393
|
+
triedFullCapacityAttempt,
|
|
2394
|
+
tryFullCapacityAttempt,
|
|
2395
|
+
isFullCapacityRetryPath,
|
|
2396
|
+
previousPhysicalShortfall,
|
|
2397
|
+
previousPassReallocatedAssets,
|
|
2398
|
+
};
|
|
2399
|
+
}
|
|
2400
|
+
/**
|
|
2401
|
+
* Commits the best improving paid attempt or restores the pre-pass checkpoint.
|
|
2402
|
+
* Returns working data by reference and may retain shared reserves; this does not
|
|
2403
|
+
* isolate earlier in-place updates. Do not reuse a prior state for further planning.
|
|
2404
|
+
* @internal
|
|
2405
|
+
*/
|
|
2406
|
+
function finishOperationPass(params) {
|
|
2407
|
+
const { passStart, bestAttempt, beforePassRemainingShortfall, beforePassAccountingShortfall, hasExplicitBlueBalance, } = params;
|
|
2408
|
+
let { reserves, data, context, remainingShortfall, accountingShortfall } = params.state;
|
|
2409
|
+
const { allocatorCapBoundTargets, idleBoundVaults } = params.state;
|
|
2410
|
+
const reallocations = [...params.state.reallocations];
|
|
2411
|
+
if (passStart != null) {
|
|
2412
|
+
const improved = bestAttempt != null &&
|
|
2413
|
+
(hasExplicitBlueBalance
|
|
2414
|
+
? bestAttempt.remainingShortfall < beforePassRemainingShortfall
|
|
2415
|
+
: bestAttempt.accountingShortfall < beforePassAccountingShortfall ||
|
|
2416
|
+
bestAttempt.remainingShortfall < beforePassRemainingShortfall);
|
|
2417
|
+
if (improved && bestAttempt != null) {
|
|
2418
|
+
data = bestAttempt.data;
|
|
2419
|
+
context = bestAttempt.context;
|
|
2420
|
+
reserves = cloneCapReserveState(bestAttempt.reserves);
|
|
2421
|
+
reallocations.length = passStart.reallocationCount;
|
|
2422
|
+
reallocations.push(...bestAttempt.reallocations);
|
|
2423
|
+
remainingShortfall = bestAttempt.remainingShortfall;
|
|
2424
|
+
accountingShortfall = bestAttempt.accountingShortfall;
|
|
2425
|
+
}
|
|
2426
|
+
else {
|
|
2427
|
+
data = passStart.data;
|
|
2428
|
+
context = passStart.context;
|
|
2429
|
+
reserves = cloneCapReserveState(passStart.reserves);
|
|
2430
|
+
reallocations.length = passStart.reallocationCount;
|
|
2431
|
+
remainingShortfall = beforePassRemainingShortfall;
|
|
2432
|
+
accountingShortfall = beforePassAccountingShortfall;
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
return {
|
|
2436
|
+
reserves,
|
|
2437
|
+
reallocations,
|
|
2438
|
+
data,
|
|
2439
|
+
context,
|
|
2440
|
+
remainingShortfall,
|
|
2441
|
+
accountingShortfall,
|
|
2442
|
+
allocatorCapBoundTargets,
|
|
2443
|
+
idleBoundVaults,
|
|
2444
|
+
};
|
|
2445
|
+
}
|
|
2446
|
+
/** Tightens a paid-pass bisection bracket from the attempt's coverage result. @internal */
|
|
2447
|
+
function updateOperationSearchBracket(params) {
|
|
2448
|
+
let { lo, hi } = params;
|
|
2449
|
+
const { passMaxAssets, attemptCoversShortfall } = params;
|
|
2450
|
+
if (attemptCoversShortfall) {
|
|
2451
|
+
hi = hi == null ? passMaxAssets : blue_sdk_1.MathLib.min(hi, passMaxAssets);
|
|
2452
|
+
}
|
|
2453
|
+
else {
|
|
2454
|
+
lo = blue_sdk_1.MathLib.max(lo, passMaxAssets);
|
|
2455
|
+
}
|
|
2456
|
+
return { lo, hi };
|
|
2457
|
+
}
|
|
2458
|
+
/** Validates the operation amount and fee before reading its snapshot. @internal */
|
|
2459
|
+
function resolveOperationFeeAssets(operation) {
|
|
2460
|
+
const { amount } = operation;
|
|
2461
|
+
if (amount <= 0n) {
|
|
2462
|
+
throw new index_js_1.NonPositiveInputError("amount", amount);
|
|
2463
|
+
}
|
|
2464
|
+
const referralFeePct = operation.type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
|
|
2465
|
+
if (referralFeePct < 0n) {
|
|
2466
|
+
throw new index_js_1.NegativeInputError("referralFeePct", referralFeePct);
|
|
2467
|
+
}
|
|
2468
|
+
if (referralFeePct >= blue_sdk_1.MathLib.WAD) {
|
|
2469
|
+
throw new index_js_1.ReferralFeePctExceededError(referralFeePct);
|
|
2470
|
+
}
|
|
2471
|
+
const feeAssets = operation.type === "refinance"
|
|
2472
|
+
? (0, common_js_1.getBlueBundlesV1ReferralFeeAssets)(amount, referralFeePct)
|
|
2473
|
+
: 0n;
|
|
2474
|
+
return feeAssets;
|
|
2475
|
+
}
|
|
2476
|
+
/** Computes post-operation accounting totals, rejecting withdrawals above supply. @internal */
|
|
2477
|
+
function getOperationMarketTotals({ market, marketId, type, amount, feeAssets, }) {
|
|
2478
|
+
if (type === "withdraw" && amount > market.totalSupplyAssets) {
|
|
2479
|
+
throw new index_js_1.ReallocationWithdrawExceedsMarketSupplyError({
|
|
2480
|
+
marketId,
|
|
2481
|
+
withdrawAmount: amount,
|
|
2482
|
+
totalSupplyAssets: market.totalSupplyAssets,
|
|
2483
|
+
});
|
|
2484
|
+
}
|
|
2485
|
+
let newTotalBorrowAssets = market.totalBorrowAssets;
|
|
2486
|
+
if (type === "borrow") {
|
|
2487
|
+
newTotalBorrowAssets += amount;
|
|
2488
|
+
}
|
|
2489
|
+
if (type === "refinance") {
|
|
2490
|
+
newTotalBorrowAssets += amount + feeAssets;
|
|
2491
|
+
}
|
|
2492
|
+
const newTotalSupplyAssets = type === "withdraw"
|
|
2493
|
+
? market.totalSupplyAssets - amount
|
|
2494
|
+
: market.totalSupplyAssets;
|
|
2495
|
+
return { newTotalBorrowAssets, newTotalSupplyAssets };
|
|
2496
|
+
}
|
|
2497
|
+
/** Chooses a headroom or full-cap budget before testing physical-balance alternatives. @internal */
|
|
2498
|
+
function selectOperationPlan(params) {
|
|
2499
|
+
const { plan, requiredAssets, allocatorCapHeadroom, absoluteShortfall } = params;
|
|
2500
|
+
// A leg that fills an allocator cap, or idle legs that together take
|
|
2501
|
+
// (nearly) all of a source vault's starting idle, revert once another
|
|
2502
|
+
// allocation lands first. A bound plan therefore moves only the operation's
|
|
2503
|
+
// shortfall, or what unbound legs moved.
|
|
2504
|
+
const target = plan(requiredAssets, { headroom: allocatorCapHeadroom });
|
|
2505
|
+
let selected = target;
|
|
2506
|
+
if (allocatorCapHeadroom > 0n && target.liquidityBound) {
|
|
2507
|
+
selected = plan(absoluteShortfall > target.unboundAssets
|
|
2508
|
+
? absoluteShortfall
|
|
2509
|
+
: target.unboundAssets, { headroom: allocatorCapHeadroom });
|
|
2510
|
+
// Shared-cap fitting is not monotonic in the budget.
|
|
2511
|
+
if (!selected.coversShortfall && target.coversShortfall) {
|
|
2512
|
+
selected = target;
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
let available = blue_sdk_1.MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
|
|
2516
|
+
// Without headroom, `target` already is the full-cap plan toward the target.
|
|
2517
|
+
const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
|
|
2518
|
+
for (const maxAssets of fullCapBudgets) {
|
|
2519
|
+
if (selected.coversShortfall) {
|
|
2520
|
+
break;
|
|
2521
|
+
}
|
|
2522
|
+
selected = plan(maxAssets, { headroom: 0n });
|
|
2523
|
+
if (selected.reallocatedAssets > available) {
|
|
2524
|
+
available = selected.reallocatedAssets;
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
// Reject unfunded plans before comparing optional physical-balance alternatives.
|
|
2528
|
+
assertSelectedOperationFunding({ ...params, selected, available });
|
|
2529
|
+
const funded = choosePhysicalBalancePlan({ ...params, selected });
|
|
2530
|
+
return { reallocations: funded.reallocations, data: funded.data };
|
|
2531
|
+
}
|
|
2532
|
+
/** Preserves penalty-specific error precedence when selected liquidity cannot fund the operation. @internal */
|
|
2533
|
+
function assertSelectedOperationFunding(params) {
|
|
2534
|
+
const { selected, available, hasExplicitBlueBalance, blueBalance, type, amount, absoluteShortfall, marketId, } = params;
|
|
2535
|
+
if (selected.coversShortfall) {
|
|
2536
|
+
return;
|
|
2537
|
+
}
|
|
2538
|
+
const selectedTransferShortfall = hasExplicitBlueBalance
|
|
2539
|
+
? getReallocationTransferShortfall(selected.reallocations, blueBalance)
|
|
2540
|
+
: 0n;
|
|
2541
|
+
const selectedPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations);
|
|
2542
|
+
if (type !== "refinance" &&
|
|
2543
|
+
selectedPenaltyAssets > amount &&
|
|
2544
|
+
selected.reallocatedAssets >= absoluteShortfall &&
|
|
2545
|
+
(!hasExplicitBlueBalance ||
|
|
2546
|
+
(selected.physicalShortfall === 0n && selectedTransferShortfall === 0n))) {
|
|
2547
|
+
throw new index_js_1.InputExceedsMaxError({
|
|
2548
|
+
field: "reallocationPenaltyAssets",
|
|
2549
|
+
value: selectedPenaltyAssets,
|
|
2550
|
+
max: amount,
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
throw new index_js_1.InsufficientSharedLiquidityError({
|
|
2554
|
+
marketId,
|
|
2555
|
+
shortfall: blue_sdk_1.MathLib.max(absoluteShortfall +
|
|
2556
|
+
(type === "refinance"
|
|
2557
|
+
? (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations)
|
|
2558
|
+
: 0n), selected.reallocatedAssets +
|
|
2559
|
+
(hasExplicitBlueBalance
|
|
2560
|
+
? blue_sdk_1.MathLib.max(selected.physicalShortfall, selectedTransferShortfall)
|
|
2561
|
+
: 0n)),
|
|
2562
|
+
available,
|
|
2563
|
+
});
|
|
2564
|
+
}
|
|
2565
|
+
/** Retains the selected plan unless a physical-balance seed is funded and strictly cheaper. @internal */
|
|
2566
|
+
function choosePhysicalBalancePlan(params) {
|
|
2567
|
+
const { hasExplicitBlueBalance, blueBalance, amount, feeAssets, type, plan } = params;
|
|
2568
|
+
let { selected } = params;
|
|
2569
|
+
const selectedPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations);
|
|
2570
|
+
if (hasExplicitBlueBalance &&
|
|
2571
|
+
selectedPenaltyAssets > 1n &&
|
|
2572
|
+
blueBalance <
|
|
2573
|
+
amount +
|
|
2574
|
+
feeAssets +
|
|
2575
|
+
(type === "refinance" ? 2n : 1n) * selectedPenaltyAssets) {
|
|
2576
|
+
// Amount feasibility is not monotonic: retain the original plan unless
|
|
2577
|
+
// the physical-balance seed finds a fully funded, strictly cheaper one.
|
|
2578
|
+
const alternative = plan(selected.maxAssets, {
|
|
2579
|
+
headroom: selected.headroom,
|
|
2580
|
+
usePhysicalBalance: true,
|
|
2581
|
+
});
|
|
2582
|
+
if (alternative.coversShortfall &&
|
|
2583
|
+
(0, common_js_1.getBlueBundlesV1PenaltyAssets)(alternative.reallocations) <
|
|
2584
|
+
(0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations)) {
|
|
2585
|
+
selected = alternative;
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
return selected;
|
|
1872
2589
|
}
|
|
1873
|
-
exports.VaultV2BlueReallocationData = VaultV2BlueReallocationData;
|