@morpho-org/morpho-sdk 10.5.0 → 10.6.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -1
- package/lib/cjs/abis.d.ts +794 -1
- package/lib/cjs/abis.js +815 -1
- package/lib/cjs/actions/blue/close.d.ts +169 -0
- package/lib/cjs/actions/blue/close.js +270 -0
- package/lib/cjs/actions/blue/common.js +2 -2
- package/lib/cjs/actions/blue/delever.d.ts +156 -0
- package/lib/cjs/actions/blue/delever.js +223 -0
- package/lib/cjs/actions/blue/index.d.ts +3 -0
- package/lib/cjs/actions/blue/index.js +3 -0
- package/lib/cjs/actions/blue/lever.d.ts +184 -0
- package/lib/cjs/actions/blue/lever.js +272 -0
- package/lib/cjs/actions/blue/leverageIntent.d.ts +65 -0
- package/lib/cjs/actions/blue/leverageIntent.js +103 -0
- package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
- package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.js +59 -0
- package/lib/cjs/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
- package/lib/cjs/actions/requirements/blue/getLeverageRequirements.js +193 -0
- package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
- package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.js +66 -0
- package/lib/cjs/actions/requirements/blue/index.d.ts +3 -0
- package/lib/cjs/actions/requirements/blue/index.js +17 -0
- package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
- package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
- package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +11 -6
- package/lib/cjs/actions/requirements/getRequirementsApproval.js +29 -5
- package/lib/cjs/addresses.d.ts +1 -1
- package/lib/cjs/addresses.js +6 -1
- package/lib/cjs/blue/abis.d.ts +1 -1
- package/lib/cjs/blue/abis.js +5 -1
- package/lib/cjs/blue/addresses.d.ts +1 -1
- package/lib/cjs/blue/addresses.js +6 -1
- package/lib/cjs/blue/entities.d.ts +4 -4
- package/lib/cjs/blue/entities.js +3 -1
- package/lib/cjs/blue/errors.d.ts +2 -2
- package/lib/cjs/blue/errors.js +5 -1
- package/lib/cjs/blue/fetch.d.ts +2 -2
- package/lib/cjs/blue/fetch.js +3 -1
- package/lib/cjs/blue/utils.d.ts +1 -1
- package/lib/cjs/blue/utils.js +2 -1
- package/lib/cjs/constants.d.ts +1 -1
- package/lib/cjs/constants.js +6 -2
- package/lib/cjs/entities/blue/blue.d.ts +486 -2
- package/lib/cjs/entities/blue/blue.js +529 -34
- package/lib/cjs/entities/index.d.ts +5 -5
- package/lib/cjs/entities/index.js +3 -1
- package/lib/cjs/entities/requirements/assertContractCode.d.ts +0 -23
- package/lib/cjs/entities/requirements/assertContractCode.js +3 -28
- package/lib/cjs/entities/vaultV2/vaultV2.d.ts +34 -8
- package/lib/cjs/entities/vaultV2/vaultV2.js +39 -1
- package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +120 -2
- package/lib/cjs/entities/vaultV2BlueReallocationData.js +232 -4
- package/lib/cjs/errors.d.ts +4 -4
- package/lib/cjs/errors.js +7 -5
- package/lib/cjs/fetch.d.ts +2 -2
- package/lib/cjs/fetch.js +3 -1
- package/lib/cjs/helpers/constant.d.ts +34 -0
- package/lib/cjs/helpers/constant.js +35 -1
- package/lib/cjs/helpers/deadShares.js +3 -0
- package/lib/cjs/helpers/getZeroExLeverageBundle.d.ts +13 -0
- package/lib/cjs/helpers/getZeroExLeverageBundle.js +27 -0
- package/lib/cjs/helpers/index.d.ts +4 -1
- package/lib/cjs/helpers/index.js +28 -1
- package/lib/cjs/helpers/leverage/index.d.ts +1 -0
- package/lib/cjs/helpers/leverage/index.js +11 -0
- package/lib/cjs/helpers/leverage/limits.d.ts +472 -0
- package/lib/cjs/helpers/leverage/limits.js +715 -0
- package/lib/cjs/helpers/leverage/positionMarket.d.ts +17 -0
- package/lib/cjs/helpers/leverage/positionMarket.js +28 -0
- package/lib/cjs/helpers/leverage/reallocations.d.ts +159 -0
- package/lib/cjs/helpers/leverage/reallocations.js +276 -0
- package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
- package/lib/cjs/helpers/validateRequirementSpender.js +4 -0
- package/lib/cjs/helpers/zeroExQuote.d.ts +250 -0
- package/lib/cjs/helpers/zeroExQuote.js +763 -0
- package/lib/cjs/index.d.ts +1 -0
- package/lib/cjs/index.js +5 -2
- package/lib/cjs/midnight/errors.d.ts +2 -1
- package/lib/cjs/midnight/errors.js +5 -4
- package/lib/cjs/reads/assertContractCode.d.ts +25 -0
- package/lib/cjs/reads/assertContractCode.js +30 -0
- package/lib/cjs/reads/fetchZeroExQuote.d.ts +123 -0
- package/lib/cjs/reads/fetchZeroExQuote.js +330 -0
- package/lib/cjs/types/action.d.ts +130 -1
- package/lib/cjs/types/error.d.ts +59 -0
- package/lib/cjs/types/error.js +82 -3
- package/lib/cjs/types/index.d.ts +2 -0
- package/lib/cjs/types/index.js +2 -0
- package/lib/cjs/types/leverageError.d.ts +1552 -0
- package/lib/cjs/types/leverageError.js +1711 -0
- package/lib/cjs/types/zeroEx.d.ts +171 -0
- package/lib/cjs/types/zeroEx.js +2 -0
- package/lib/cjs/utils.d.ts +2 -2
- package/lib/cjs/utils.js +4 -2
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/esm/abis.d.ts +794 -1
- package/lib/esm/abis.js +810 -1
- package/lib/esm/actions/blue/close.d.ts +169 -0
- package/lib/esm/actions/blue/close.js +266 -0
- package/lib/esm/actions/blue/common.js +3 -3
- package/lib/esm/actions/blue/delever.d.ts +156 -0
- package/lib/esm/actions/blue/delever.js +219 -0
- package/lib/esm/actions/blue/index.d.ts +3 -0
- package/lib/esm/actions/blue/index.js +3 -0
- package/lib/esm/actions/blue/lever.d.ts +184 -0
- package/lib/esm/actions/blue/lever.js +268 -0
- package/lib/esm/actions/blue/leverageIntent.d.ts +65 -0
- package/lib/esm/actions/blue/leverageIntent.js +96 -0
- package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
- package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.js +55 -0
- package/lib/esm/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
- package/lib/esm/actions/requirements/blue/getLeverageRequirements.js +189 -0
- package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
- package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.js +62 -0
- package/lib/esm/actions/requirements/blue/index.d.ts +3 -0
- package/lib/esm/actions/requirements/blue/index.js +3 -0
- package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
- package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
- package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +11 -6
- package/lib/esm/actions/requirements/getRequirementsApproval.js +29 -5
- package/lib/esm/addresses.d.ts +1 -1
- package/lib/esm/addresses.js +1 -1
- package/lib/esm/blue/abis.d.ts +1 -1
- package/lib/esm/blue/abis.js +1 -1
- package/lib/esm/blue/addresses.d.ts +1 -1
- package/lib/esm/blue/addresses.js +1 -1
- package/lib/esm/blue/entities.d.ts +4 -4
- package/lib/esm/blue/entities.js +2 -2
- package/lib/esm/blue/errors.d.ts +2 -2
- package/lib/esm/blue/errors.js +2 -2
- package/lib/esm/blue/fetch.d.ts +2 -2
- package/lib/esm/blue/fetch.js +2 -2
- package/lib/esm/blue/utils.d.ts +1 -1
- package/lib/esm/blue/utils.js +1 -1
- package/lib/esm/constants.d.ts +1 -1
- package/lib/esm/constants.js +1 -1
- package/lib/esm/entities/blue/blue.d.ts +486 -2
- package/lib/esm/entities/blue/blue.js +501 -6
- package/lib/esm/entities/index.d.ts +5 -5
- package/lib/esm/entities/index.js +2 -2
- package/lib/esm/entities/requirements/assertContractCode.d.ts +0 -23
- package/lib/esm/entities/requirements/assertContractCode.js +1 -25
- package/lib/esm/entities/vaultV2/vaultV2.d.ts +34 -8
- package/lib/esm/entities/vaultV2/vaultV2.js +40 -2
- package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +120 -2
- package/lib/esm/entities/vaultV2BlueReallocationData.js +233 -5
- package/lib/esm/errors.d.ts +4 -4
- package/lib/esm/errors.js +4 -4
- package/lib/esm/fetch.d.ts +2 -2
- package/lib/esm/fetch.js +2 -2
- package/lib/esm/helpers/constant.d.ts +34 -0
- package/lib/esm/helpers/constant.js +34 -0
- package/lib/esm/helpers/deadShares.js +4 -1
- package/lib/esm/helpers/getZeroExLeverageBundle.d.ts +13 -0
- package/lib/esm/helpers/getZeroExLeverageBundle.js +23 -0
- package/lib/esm/helpers/index.d.ts +4 -1
- package/lib/esm/helpers/index.js +4 -1
- package/lib/esm/helpers/leverage/index.d.ts +1 -0
- package/lib/esm/helpers/leverage/index.js +1 -0
- package/lib/esm/helpers/leverage/limits.d.ts +472 -0
- package/lib/esm/helpers/leverage/limits.js +705 -0
- package/lib/esm/helpers/leverage/positionMarket.d.ts +17 -0
- package/lib/esm/helpers/leverage/positionMarket.js +24 -0
- package/lib/esm/helpers/leverage/reallocations.d.ts +159 -0
- package/lib/esm/helpers/leverage/reallocations.js +271 -0
- package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
- package/lib/esm/helpers/validateRequirementSpender.js +5 -1
- package/lib/esm/helpers/zeroExQuote.d.ts +250 -0
- package/lib/esm/helpers/zeroExQuote.js +754 -0
- package/lib/esm/index.d.ts +1 -0
- package/lib/esm/index.js +1 -0
- package/lib/esm/midnight/errors.d.ts +2 -1
- package/lib/esm/midnight/errors.js +2 -1
- package/lib/esm/reads/assertContractCode.d.ts +25 -0
- package/lib/esm/reads/assertContractCode.js +26 -0
- package/lib/esm/reads/fetchZeroExQuote.d.ts +123 -0
- package/lib/esm/reads/fetchZeroExQuote.js +326 -0
- package/lib/esm/types/action.d.ts +130 -1
- package/lib/esm/types/error.d.ts +59 -0
- package/lib/esm/types/error.js +76 -0
- package/lib/esm/types/index.d.ts +2 -0
- package/lib/esm/types/index.js +2 -0
- package/lib/esm/types/leverageError.d.ts +1552 -0
- package/lib/esm/types/leverageError.js +1660 -0
- package/lib/esm/types/zeroEx.d.ts +171 -0
- package/lib/esm/types/zeroEx.js +1 -0
- package/lib/esm/utils.d.ts +2 -2
- package/lib/esm/utils.js +2 -2
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/package.json +7 -7
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { MarketParams, MathLib, } from "@morpho-org/blue-sdk";
|
|
1
|
+
import { MarketParams, MathLib, UnknownMarketParamsError, } from "@morpho-org/blue-sdk";
|
|
2
2
|
import { fetchAccrualPosition, fetchAccrualVaultV2, fetchMarket, fetchVaultV2BluePublicAllocatorData, } from "@morpho-org/blue-sdk-viem";
|
|
3
|
-
import { deepFreeze, getChainAddress, getChainAddresses, Time, } from "@morpho-org/morpho-ts";
|
|
3
|
+
import { _try, deepFreeze, getChainAddress, getChainAddresses, isZeroExLeverageChain, Time, ZERO_EX_ALLOWANCE_HOLDER_ADDRESS, ZERO_EX_ALLOWANCE_HOLDER_CHAIN_IDS, } from "@morpho-org/morpho-ts";
|
|
4
4
|
import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
|
|
5
|
-
import { readContract } from "viem/actions";
|
|
5
|
+
import { getBlock, getCode, readContract } from "viem/actions";
|
|
6
6
|
import { blueAbi, midnightBlueBuyCallbackAbi, midnightBlueBuyCallbackFactoryAbi, } from "../../abis.js";
|
|
7
|
-
import { getBlueBundlesV1ReferralFeeAssets, parseBlueAllocations, parseBlueBundlesV1Common, selectBlueBundlesV1RequirementSignatures, } from "../../actions/blue/common.js";
|
|
7
|
+
import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1ReferralFeeAssets, parseBlueAllocations, parseBlueBundlesV1Common, selectBlueBundlesV1RequirementSignatures, } from "../../actions/blue/common.js";
|
|
8
|
+
import { validateLeverageIntentAmount, validateLeverageQuoteSlippage, validateLeverSlippage, } from "../../actions/blue/leverageIntent.js";
|
|
8
9
|
import { buildBlueRefinance, parseBlueRefinanceMarkets, } from "../../actions/blue/refinance.internal.js";
|
|
9
10
|
import { validateBlueRefinanceQuote } from "../../actions/blue/refinanceValidation.js";
|
|
10
11
|
import { buildBlueRepayWithdrawCollateral, parseBlueRepayCap, parseBlueRepayCoverage, parseBlueRepayMode, } from "../../actions/blue/repayWithdrawCollateral.internal.js";
|
|
@@ -12,18 +13,229 @@ import { buildBlueSupply, } from "../../actions/blue/supply.internal.js";
|
|
|
12
13
|
import { buildBlueSupplyCollateralBorrow, parseBlueSupplyCollateralBorrowAllocations, parseBlueSupplyCollateralBorrowMode, } from "../../actions/blue/supplyCollateralBorrow.internal.js";
|
|
13
14
|
import { buildBlueWithdraw, parseBlueWithdrawMode, parseBlueWithdrawPenalty, } from "../../actions/blue/withdraw.internal.js";
|
|
14
15
|
import { buildBlueWithdrawBuyCallback, } from "../../actions/blue/withdrawBuyCallback.internal.js";
|
|
16
|
+
import { blueClose, blueDelever, blueLever, getLeverageRequirements, } from "../../actions/index.js";
|
|
15
17
|
import { getParsedBlueAuthorizationRequirement, parseBlueAuthorizationRequirement, } from "../../actions/requirements/blue/getBlueAuthorizationRequirement.js";
|
|
16
18
|
import { createChainCheck, } from "../../actions/requirements/chainCheck.js";
|
|
19
|
+
import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
|
|
17
20
|
import { getBlueBundlesV1QuoteTimestamp } from "../../helpers/getBlueBundlesV1QuoteTimestamp.js";
|
|
18
|
-
import { DEFAULT_LLTV_BUFFER, validateAccrualPosition, validateChainId, validatePositionHealth, validatePositionHealthAfterWithdraw, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
|
|
21
|
+
import { computeLeverLimits, DEFAULT_LLTV_BUFFER, LEVERAGE_MAX_REALLOCATION_PENALTY, validateAccrualPosition, validateChainId, validatePositionHealth, validatePositionHealthAfterWithdraw, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
|
|
22
|
+
import { leverageDeadline } from "../../helpers/leverage/limits.js";
|
|
23
|
+
import { validateLeveragePositionMarket } from "../../helpers/leverage/positionMarket.js";
|
|
19
24
|
import { resolveTransactionMetadata } from "../../helpers/metadata.js";
|
|
20
25
|
import { parseBlueMarket, parseNativeFunding, parseNonnegative, parseUint256, parseUint256Max, } from "../../helpers/parse.js";
|
|
21
26
|
import { quoteBlueRepay } from "../../helpers/quoteBlueRepay.js";
|
|
22
|
-
import {
|
|
27
|
+
import { resolveAllocatorCapHeadroom, resolveCapAccrualBuffer, resolveMaxWithdrawalUtilization, } from "../../helpers/utilization.js";
|
|
28
|
+
import { BlueBuyCallbackOwnerMismatchError, BlueBuyCallbackUnauthorizedError, EmptyBlueSupplyPositionError, ExpiredDeadlineError, ExpiredLeverageDeadlineError, InputExceedsMaxError, InsufficientBlueLiquidityError, InsufficientSharedLiquidityError, InvalidBigIntInputError, LeverageReallocationExceedsBorrowError, LeverageReallocationOutsideCapsError, LeverageUnsupportedChainError, MarketIdMismatchError, MissingAccrualPositionError, NegativeInputError, NonPositiveInputError, NotBlueBuyCallbackError, ZeroExQuoteRequiredError, } from "../../types/index.js";
|
|
23
29
|
import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
|
|
24
30
|
import { getParsedBundlesTokenRequirements, parseGetBundlesTokenRequirements, } from "../requirements/getBundlesTokenRequirements.js";
|
|
25
31
|
import { validateNativeRequirements } from "../requirements/validateNativeRequirements.js";
|
|
26
32
|
import { VaultV2BlueReallocationData } from "../vaultV2BlueReallocationData.js";
|
|
33
|
+
/**
|
|
34
|
+
* Planning rounds of a Lever. A padded plan usually settles in the first round; when the vaults can
|
|
35
|
+
* fund only the unpadded borrow, each round closes the gap to the self-covering borrow at least
|
|
36
|
+
* a hundredfold (the penalty rate is at most 1%), so 32 rounds settle any `uint256` borrow.
|
|
37
|
+
*/
|
|
38
|
+
const LEVER_REALLOCATION_PLAN_ROUNDS = 32;
|
|
39
|
+
/**
|
|
40
|
+
* Keeps the leading legs of a plan until they move `budget` assets, trimming the last kept leg. The
|
|
41
|
+
* planner sizes its free legs toward a 90% utilization target and can move more than the borrow,
|
|
42
|
+
* which the leverage guard refuses; every plan covers the borrow's shortfall, which never exceeds
|
|
43
|
+
* the borrow, so the trimmed plan still covers it, and its later, penalized legs shrink first.
|
|
44
|
+
*/
|
|
45
|
+
const capLeverReallocations = (reallocations, budget) => {
|
|
46
|
+
const capped = [];
|
|
47
|
+
let remaining = budget;
|
|
48
|
+
for (const reallocation of reallocations) {
|
|
49
|
+
if (remaining === 0n) {
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
const assets = MathLib.min(reallocation.assets, remaining);
|
|
53
|
+
capped.push(assets === reallocation.assets
|
|
54
|
+
? reallocation
|
|
55
|
+
: { ...reallocation, assets });
|
|
56
|
+
remaining -= assets;
|
|
57
|
+
}
|
|
58
|
+
return capped;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Trims a planned Lever to the borrow the market's liquidity leaves uncovered.
|
|
62
|
+
*/
|
|
63
|
+
const trimLeverReallocations = ({ planned, borrow, liquidity, }) => capLeverReallocations(planned, MathLib.zeroFloorSub(borrow, liquidity));
|
|
64
|
+
/**
|
|
65
|
+
* Base units below the bisected amount that a cap-breaking Lever leg scans for a smaller accepted amount,
|
|
66
|
+
* the window the planner gives its own shared-cap search.
|
|
67
|
+
*/
|
|
68
|
+
const LEVER_CAP_SEARCH_STEPS = 1024n;
|
|
69
|
+
/**
|
|
70
|
+
* Checks a trimmed Lever plan against the vaults' caps by replaying it at the data block. A leg
|
|
71
|
+
* trimmed below the amount the planner chose can break a shared relative cap that a larger move
|
|
72
|
+
* meets, because the larger move donates a larger penalty and lifts the cap. Each leg that breaks a
|
|
73
|
+
* cap is raised to an amount that keeps it and every earlier leg within the caps: its planned amount
|
|
74
|
+
* must, a bisection between the trimmed and planned amounts narrows it to an accepted amount, and a scan of
|
|
75
|
+
* the `LEVER_CAP_SEARCH_STEPS` amounts below that one takes the smallest the replay accepts, since share
|
|
76
|
+
* rounding can make a cap accept an amount below one it refuses. The raised plan must still move no more
|
|
77
|
+
* than the borrow it needs.
|
|
78
|
+
*
|
|
79
|
+
* @throws {LeverageReallocationOutsideCapsError} when a leg breaks a cap even at its planned amount.
|
|
80
|
+
* @throws {LeverageReallocationExceedsBorrowError} when the raised plan moves more than the borrow it needs.
|
|
81
|
+
*/
|
|
82
|
+
const fitLeverReallocationCaps = ({ planned, trimmed, getBorrow, findOutsideCaps, findFittingAssets, }) => {
|
|
83
|
+
let legs = trimmed;
|
|
84
|
+
for (let outside = findOutsideCaps(legs); outside != null; outside = findOutsideCaps(legs)) {
|
|
85
|
+
const broken = outside;
|
|
86
|
+
const index = legs.indexOf(broken);
|
|
87
|
+
const earlier = legs.slice(0, index);
|
|
88
|
+
const fits = (amounts) => findFittingAssets({
|
|
89
|
+
reallocations: earlier,
|
|
90
|
+
reallocation: broken,
|
|
91
|
+
amounts,
|
|
92
|
+
});
|
|
93
|
+
/* v8 ignore next: every leg keeps its planned leg's from and to objects, so the lookup always matches. */
|
|
94
|
+
const plannedAssets = planned.find(({ from, to }) => from === broken.from && to === broken.to)
|
|
95
|
+
?.assets ?? broken.assets;
|
|
96
|
+
if (plannedAssets <= broken.assets || fits([plannedAssets]) == null) {
|
|
97
|
+
throw new LeverageReallocationOutsideCapsError({
|
|
98
|
+
vault: broken.vault,
|
|
99
|
+
assets: broken.assets,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
let low = broken.assets;
|
|
103
|
+
let high = plannedAssets;
|
|
104
|
+
while (high - low > 1n) {
|
|
105
|
+
const middle = (low + high) / 2n;
|
|
106
|
+
if (fits([middle]) == null) {
|
|
107
|
+
low = middle;
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
high = middle;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
// Share rounding can make a shared cap accept an amount below one it refuses, so the bisection
|
|
114
|
+
// may skip a smaller fit: scan the window below its result upward, in one replay of the earlier legs.
|
|
115
|
+
const scanFrom = MathLib.max(broken.assets + 1n, high - LEVER_CAP_SEARCH_STEPS);
|
|
116
|
+
const window = function* () {
|
|
117
|
+
for (let assets = scanFrom; assets < high; assets++) {
|
|
118
|
+
yield assets;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
const assets = fits(window()) ?? high;
|
|
122
|
+
legs = legs.map((leg, i) => (i === index ? { ...leg, assets } : leg));
|
|
123
|
+
}
|
|
124
|
+
const total = legs.reduce((sum, { assets }) => sum + assets, 0n);
|
|
125
|
+
const maxBorrowAssets = getBorrow(legs);
|
|
126
|
+
if (total > maxBorrowAssets) {
|
|
127
|
+
throw new LeverageReallocationExceedsBorrowError({
|
|
128
|
+
total,
|
|
129
|
+
maxBorrowAssets,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
return legs;
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* Plans the Vault V2 BluePublicAllocator reallocations of a Lever with `VaultV2BlueReallocationData`.
|
|
136
|
+
* The borrow is the penalty-free borrow plus the plan's own penalty. A market whose liquidity covers
|
|
137
|
+
* the penalty-free borrow needs no reallocation. Otherwise each plan is sized for the borrow plus its
|
|
138
|
+
* penalty tail at the `maxPenalty` ceiling, or for the unpadded borrow when the vaults cannot fund
|
|
139
|
+
* that, then trimmed to the part of the borrow the market's liquidity leaves uncovered: trimming
|
|
140
|
+
* lowers the penalty and so the borrow, until the two agree. A plan that needs more than it was sized for is replanned,
|
|
141
|
+
* at most 32 rounds; `blueLever` refuses a last plan that leaves the market short of the borrow and
|
|
142
|
+
* reruns the price and LTV checks on the final plan. The trimmed plan is replayed against the vaults'
|
|
143
|
+
* caps first: a trimmed leg that breaks one is raised toward its planned amount, to the smallest
|
|
144
|
+
* amount the replay accepts.
|
|
145
|
+
*/
|
|
146
|
+
const planLeverReallocations = ({ marketParams, leverageData, options, limits, }) => {
|
|
147
|
+
if (options?.enabled === false ||
|
|
148
|
+
Object.keys(leverageData.reallocationData.vaults).length === 0) {
|
|
149
|
+
return [];
|
|
150
|
+
}
|
|
151
|
+
const maxPenalty = MathLib.min(options?.maxPenalty ?? LEVERAGE_MAX_REALLOCATION_PENALTY, LEVERAGE_MAX_REALLOCATION_PENALTY);
|
|
152
|
+
// Every round replans with the same allowlist, so a one-shot iterable is read once.
|
|
153
|
+
const reallocatableVaults = options?.reallocatableVaults == null
|
|
154
|
+
? undefined
|
|
155
|
+
: [...options.reallocatableVaults];
|
|
156
|
+
// The price and LTV checks only tighten as the penalty grows, so they run once here on the
|
|
157
|
+
// penalty-free borrow; `blueLever` reruns them on the final plan. Sizing below is arithmetic: the
|
|
158
|
+
// borrow is the penalty-free borrow plus the plan's penalty.
|
|
159
|
+
const borrowWithoutPenalty = computeLeverLimits({
|
|
160
|
+
...limits,
|
|
161
|
+
penaltyAssets: 0n,
|
|
162
|
+
}).maxBorrowAssets;
|
|
163
|
+
const getBorrow = (legs) => borrowWithoutPenalty + getBlueBundlesV1PenaltyAssets(legs);
|
|
164
|
+
const { liquidity } = leverageData.position.market;
|
|
165
|
+
const fit = (planned, trimmed) => fitLeverReallocationCaps({
|
|
166
|
+
planned,
|
|
167
|
+
trimmed,
|
|
168
|
+
getBorrow,
|
|
169
|
+
findOutsideCaps: (legs) => leverageData.reallocationData.findVaultV2BlueReallocationOutsideCaps({
|
|
170
|
+
marketId: marketParams.id,
|
|
171
|
+
reallocations: legs,
|
|
172
|
+
timestamp: leverageData.block.timestamp,
|
|
173
|
+
capAccrualBuffer: options?.capAccrualBuffer,
|
|
174
|
+
}),
|
|
175
|
+
findFittingAssets: (search) => leverageData.reallocationData.findVaultV2BlueReallocationFittingAssets({
|
|
176
|
+
...search,
|
|
177
|
+
marketId: marketParams.id,
|
|
178
|
+
timestamp: leverageData.block.timestamp,
|
|
179
|
+
capAccrualBuffer: options?.capAccrualBuffer,
|
|
180
|
+
}),
|
|
181
|
+
});
|
|
182
|
+
const trim = (planned, borrow) => trimLeverReallocations({
|
|
183
|
+
planned,
|
|
184
|
+
borrow,
|
|
185
|
+
liquidity,
|
|
186
|
+
});
|
|
187
|
+
const plan = (data) => {
|
|
188
|
+
if (borrowWithoutPenalty <= liquidity) {
|
|
189
|
+
return [];
|
|
190
|
+
}
|
|
191
|
+
const planBorrow = (amount) => data.computeVaultV2BlueReallocations(marketParams.id, {
|
|
192
|
+
...options,
|
|
193
|
+
reallocatableVaults,
|
|
194
|
+
timestamp: leverageData.block.timestamp,
|
|
195
|
+
maxPenalty,
|
|
196
|
+
operation: { type: "borrow", amount },
|
|
197
|
+
}).reallocations;
|
|
198
|
+
// Each plan is first sized for the borrow plus its whole penalty tail at the `maxPenalty`
|
|
199
|
+
// ceiling, then trimmed back down; when the vaults cannot fund that padding, the unpadded
|
|
200
|
+
// borrow is planned instead.
|
|
201
|
+
const pad = (borrow, tail) => borrow + MathLib.mulDivUp(tail, maxPenalty, MathLib.WAD - maxPenalty);
|
|
202
|
+
let unpadded = borrowWithoutPenalty;
|
|
203
|
+
let target = pad(borrowWithoutPenalty, borrowWithoutPenalty);
|
|
204
|
+
let planned = [];
|
|
205
|
+
let reallocations = [];
|
|
206
|
+
for (let round = 0; round < LEVER_REALLOCATION_PLAN_ROUNDS; round++) {
|
|
207
|
+
const padded = _try(() => planBorrow(target), InsufficientSharedLiquidityError);
|
|
208
|
+
const sizedFor = padded === undefined ? unpadded : target;
|
|
209
|
+
planned = padded ?? planBorrow(unpadded);
|
|
210
|
+
// The plan is trimmed for the borrow it was sized for. A smaller borrow lowers the penalty, so
|
|
211
|
+
// the borrow it needs falls until the plan, trimmed for that borrow, needs exactly that borrow.
|
|
212
|
+
let borrow = sizedFor;
|
|
213
|
+
reallocations = trim(planned, borrow);
|
|
214
|
+
let needed = getBorrow(reallocations);
|
|
215
|
+
while (needed < borrow) {
|
|
216
|
+
borrow = needed;
|
|
217
|
+
reallocations = trim(planned, borrow);
|
|
218
|
+
needed = getBorrow(reallocations);
|
|
219
|
+
}
|
|
220
|
+
if (needed === borrow) {
|
|
221
|
+
return fit(planned, reallocations);
|
|
222
|
+
}
|
|
223
|
+
unpadded = needed;
|
|
224
|
+
target = pad(needed, needed - sizedFor);
|
|
225
|
+
}
|
|
226
|
+
return fit(planned, reallocations);
|
|
227
|
+
};
|
|
228
|
+
// Lever plans ignore Blue's loan-token balance by choice, so the planner's flash-loan funding check never
|
|
229
|
+
// refuses a Lever. ZeroExLeverageBundlesV1 still flash-loans `penaltyAssets - loanAssets` from Blue when the
|
|
230
|
+
// penalty exceeds the deposit, so a Lever that pays a penalty can revert onchain when Blue is short of cash.
|
|
231
|
+
const { reallocationData } = leverageData;
|
|
232
|
+
return plan(Object.values(reallocationData.blueBalances).every((balance) => balance == null)
|
|
233
|
+
? reallocationData
|
|
234
|
+
: new VaultV2BlueReallocationData({
|
|
235
|
+
...reallocationData,
|
|
236
|
+
blueBalances: {},
|
|
237
|
+
}));
|
|
238
|
+
};
|
|
27
239
|
/** Binds a viem client to a Morpho Blue market's action builders. */
|
|
28
240
|
export class MorphoBlue {
|
|
29
241
|
client;
|
|
@@ -45,11 +257,30 @@ export class MorphoBlue {
|
|
|
45
257
|
this.chainId = chainId;
|
|
46
258
|
this.parsedMarket = parseBlueMarket(marketParams);
|
|
47
259
|
}
|
|
260
|
+
validateLeverageNow(now) {
|
|
261
|
+
if (now === undefined) {
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (typeof now !== "bigint") {
|
|
265
|
+
throw new InvalidBigIntInputError("now", now);
|
|
266
|
+
}
|
|
267
|
+
if (now < 0n) {
|
|
268
|
+
throw new NegativeInputError("now", now);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
elapsedLeverageNow(now, createdAt) {
|
|
272
|
+
return now === undefined ? undefined : now + Time.timestamp() - createdAt;
|
|
273
|
+
}
|
|
48
274
|
validateDeadline(deadline, now = Time.timestamp()) {
|
|
49
275
|
if (deadline <= now) {
|
|
50
276
|
throw new ExpiredDeadlineError(deadline, now);
|
|
51
277
|
}
|
|
52
278
|
}
|
|
279
|
+
validateLeverageDeadline(deadline, now = Time.timestamp()) {
|
|
280
|
+
if (deadline <= now) {
|
|
281
|
+
throw new ExpiredLeverageDeadlineError(deadline, now);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
53
284
|
validateWriteCommon(params, now) {
|
|
54
285
|
// Reject cross-chain inputs before continuing.
|
|
55
286
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
@@ -143,6 +374,270 @@ export class MorphoBlue {
|
|
|
143
374
|
deployless: this.client.options.supportDeployless,
|
|
144
375
|
});
|
|
145
376
|
}
|
|
377
|
+
/** {@inheritDoc BlueActions.getLeverageData} */
|
|
378
|
+
async getLeverageData({ userAddress, vaultAddresses = [], blockNumber, }) {
|
|
379
|
+
if (!isZeroExLeverageChain(this.chainId)) {
|
|
380
|
+
throw new LeverageUnsupportedChainError({
|
|
381
|
+
chainId: this.chainId,
|
|
382
|
+
reason: ZERO_EX_ALLOWANCE_HOLDER_CHAIN_IDS.has(this.chainId)
|
|
383
|
+
? "noBundle"
|
|
384
|
+
: "noAllowanceHolder",
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
await validateClientChainId(this.client.viemClient, this.chainId);
|
|
388
|
+
// Read the caller's iterable once, before any parallel read starts, so an iterator that throws leaves
|
|
389
|
+
// no read without a handler. A repeated vault, in any casing, is read once; a malformed entry is kept for the
|
|
390
|
+
// reallocation read to refuse with its typed error.
|
|
391
|
+
const seenVaults = new Set();
|
|
392
|
+
const vaults = [...vaultAddresses].filter((vault) => {
|
|
393
|
+
const key = typeof vault === "string" ? vault.toLowerCase() : vault;
|
|
394
|
+
if (seenVaults.has(key)) {
|
|
395
|
+
return false;
|
|
396
|
+
}
|
|
397
|
+
seenVaults.add(key);
|
|
398
|
+
return true;
|
|
399
|
+
});
|
|
400
|
+
const client = this.client.viemClient;
|
|
401
|
+
const { number, timestamp } = await getBlock(client, blockNumber == null ? {} : { blockNumber });
|
|
402
|
+
const block = { number, timestamp };
|
|
403
|
+
const allowanceHolderCode = await getCode(client, {
|
|
404
|
+
address: ZERO_EX_ALLOWANCE_HOLDER_ADDRESS,
|
|
405
|
+
blockNumber: block.number,
|
|
406
|
+
});
|
|
407
|
+
if (allowanceHolderCode == null || allowanceHolderCode === "0x") {
|
|
408
|
+
throw new LeverageUnsupportedChainError({
|
|
409
|
+
chainId: this.chainId,
|
|
410
|
+
reason: "noAllowanceHolder",
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
const [snapshotRead, reallocationRead] = await Promise.allSettled([
|
|
414
|
+
fetchAccrualPosition(userAddress, this.parsedMarket.id, client, {
|
|
415
|
+
blockNumber: block.number,
|
|
416
|
+
deployless: this.client.options.supportDeployless,
|
|
417
|
+
}),
|
|
418
|
+
this.getVaultV2BlueReallocationData({
|
|
419
|
+
vaultAddresses: vaults,
|
|
420
|
+
block,
|
|
421
|
+
}),
|
|
422
|
+
]);
|
|
423
|
+
if (snapshotRead.status === "rejected") {
|
|
424
|
+
throw snapshotRead.reason;
|
|
425
|
+
}
|
|
426
|
+
const snapshot = snapshotRead.value;
|
|
427
|
+
// Morpho returns an all-zero, never-updated market for an id with no market at the block. Its id is the
|
|
428
|
+
// zero tuple's, which matches only an entity built from the zero tuple, so the last update is checked too.
|
|
429
|
+
// Checked before the sibling reads' errors, which such a market can also cause.
|
|
430
|
+
if (snapshot.market.id !== this.parsedMarket.id ||
|
|
431
|
+
snapshot.market.lastUpdate === 0n) {
|
|
432
|
+
throw new UnknownMarketParamsError(this.parsedMarket.id);
|
|
433
|
+
}
|
|
434
|
+
if (reallocationRead.status === "rejected") {
|
|
435
|
+
throw reallocationRead.reason;
|
|
436
|
+
}
|
|
437
|
+
const reallocationData = reallocationRead.value;
|
|
438
|
+
return {
|
|
439
|
+
chainId: this.chainId,
|
|
440
|
+
block,
|
|
441
|
+
bundle: getChainAddress(this.chainId, "bundles.zeroExLeverageBundlesV1"),
|
|
442
|
+
market: snapshot.market,
|
|
443
|
+
// Left as stored: Blue accrues once from its last update, and the leverage limits do the same.
|
|
444
|
+
position: snapshot,
|
|
445
|
+
borrowRate: snapshot.market
|
|
446
|
+
.accrueInterest(block.timestamp)
|
|
447
|
+
.getEndBorrowRate(block.timestamp),
|
|
448
|
+
reallocationData,
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
/** {@inheritDoc BlueActions.lever} */
|
|
452
|
+
lever({ userAddress, txOrigin, leverageData, quote, slippage, collateralAssets, loanAssets, nativeAmount, reallocationOptions, now, }) {
|
|
453
|
+
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
454
|
+
validateChainId(leverageData.chainId, this.chainId);
|
|
455
|
+
this.validateLeverageNow(now);
|
|
456
|
+
const createdAt = Time.timestamp();
|
|
457
|
+
// Expired leverage data fails here first, so the caller is told to read a new one.
|
|
458
|
+
this.validateLeverageDeadline(leverageDeadline(leverageData), now);
|
|
459
|
+
// The planner computes limits from the snapshot before `blueLever`, so the snapshot's market and
|
|
460
|
+
// user and the intent are checked first to throw the same typed error with planning on or off.
|
|
461
|
+
validateAccrualPosition({
|
|
462
|
+
positionData: leverageData.position,
|
|
463
|
+
expectedMarketId: this.parsedMarket.id,
|
|
464
|
+
expectedUser: userAddress,
|
|
465
|
+
});
|
|
466
|
+
// Built from the snapshot, never the caller's object, which the caller can mutate after construction.
|
|
467
|
+
const marketParams = new MarketParams(this.parsedMarket);
|
|
468
|
+
validateLeveragePositionMarket(leverageData.position, marketParams);
|
|
469
|
+
validateLeverageIntentAmount("collateralAssets", collateralAssets);
|
|
470
|
+
validateLeverageIntentAmount("loanAssets", loanAssets);
|
|
471
|
+
// Checked before the quote's slippage, so a requote advice never names a slippage the quote fetch refuses.
|
|
472
|
+
validateLeverSlippage(slippage);
|
|
473
|
+
if (quote == null) {
|
|
474
|
+
throw new ZeroExQuoteRequiredError({ operation: "lever" });
|
|
475
|
+
}
|
|
476
|
+
validateLeverageQuoteSlippage({
|
|
477
|
+
operation: "lever",
|
|
478
|
+
slippage,
|
|
479
|
+
quoteSlippage: quote.slippage,
|
|
480
|
+
});
|
|
481
|
+
const maxPenalty = reallocationOptions?.maxPenalty;
|
|
482
|
+
if (maxPenalty !== undefined && typeof maxPenalty !== "bigint") {
|
|
483
|
+
throw new InvalidBigIntInputError("reallocationOptions.maxPenalty", maxPenalty);
|
|
484
|
+
}
|
|
485
|
+
// Refused here so a bad setting fails on a liquid market too, where planning returns early.
|
|
486
|
+
if (maxPenalty !== undefined && maxPenalty < 0n) {
|
|
487
|
+
throw new NegativeInputError("reallocationOptions.maxPenalty", maxPenalty);
|
|
488
|
+
}
|
|
489
|
+
const { capAccrualBuffer, allocatorCapHeadroom, maxWithdrawalUtilization } = reallocationOptions ?? {};
|
|
490
|
+
for (const [field, value] of [
|
|
491
|
+
["reallocationOptions.allocatorCapHeadroom", allocatorCapHeadroom],
|
|
492
|
+
[
|
|
493
|
+
"reallocationOptions.maxWithdrawalUtilization",
|
|
494
|
+
maxWithdrawalUtilization,
|
|
495
|
+
],
|
|
496
|
+
]) {
|
|
497
|
+
if (value !== undefined && typeof value !== "bigint") {
|
|
498
|
+
throw new InvalidBigIntInputError(field, value);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
if (capAccrualBuffer != null) {
|
|
502
|
+
try {
|
|
503
|
+
BigInt(capAccrualBuffer);
|
|
504
|
+
}
|
|
505
|
+
catch {
|
|
506
|
+
throw new InvalidBigIntInputError("reallocationOptions.capAccrualBuffer", capAccrualBuffer);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
resolveCapAccrualBuffer(reallocationOptions?.capAccrualBuffer);
|
|
510
|
+
resolveAllocatorCapHeadroom(reallocationOptions?.allocatorCapHeadroom);
|
|
511
|
+
resolveMaxWithdrawalUtilization(reallocationOptions?.maxWithdrawalUtilization);
|
|
512
|
+
const reallocations = planLeverReallocations({
|
|
513
|
+
marketParams,
|
|
514
|
+
leverageData,
|
|
515
|
+
options: reallocationOptions,
|
|
516
|
+
limits: {
|
|
517
|
+
intent: { collateralAssets, loanAssets },
|
|
518
|
+
quote,
|
|
519
|
+
slippage,
|
|
520
|
+
leverageData,
|
|
521
|
+
},
|
|
522
|
+
});
|
|
523
|
+
const transaction = blueLever({
|
|
524
|
+
market: { chainId: this.chainId, marketParams },
|
|
525
|
+
args: {
|
|
526
|
+
userAddress,
|
|
527
|
+
txOrigin,
|
|
528
|
+
leverageData,
|
|
529
|
+
quote,
|
|
530
|
+
slippage,
|
|
531
|
+
collateralAssets,
|
|
532
|
+
loanAssets,
|
|
533
|
+
reallocations,
|
|
534
|
+
nativeAmount,
|
|
535
|
+
},
|
|
536
|
+
metadata: resolveTransactionMetadata(this.client.options.metadata, now),
|
|
537
|
+
});
|
|
538
|
+
const { maxBorrowAssets, deadline } = transaction.action.args;
|
|
539
|
+
return {
|
|
540
|
+
getRequirements: async () => {
|
|
541
|
+
this.validateLeverageDeadline(deadline, this.elapsedLeverageNow(now, createdAt));
|
|
542
|
+
// Morpho Blue keeps its code check. A shipped leverage bundle's check is waived (docs/EXCEPTIONS.md); a bundle
|
|
543
|
+
// registered with registerCustomAddresses has its code checked in getLeverageRequirements.
|
|
544
|
+
await assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, [{ role: "blue", address: getChainAddress(this.chainId, "blue") }]);
|
|
545
|
+
return getLeverageRequirements({
|
|
546
|
+
viemClient: this.client.viemClient,
|
|
547
|
+
chainId: this.chainId,
|
|
548
|
+
userAddress,
|
|
549
|
+
marketParams: this.parsedMarket,
|
|
550
|
+
operation: {
|
|
551
|
+
type: "lever",
|
|
552
|
+
collateralAssets,
|
|
553
|
+
loanAssets,
|
|
554
|
+
maxBorrowAssets,
|
|
555
|
+
},
|
|
556
|
+
});
|
|
557
|
+
},
|
|
558
|
+
buildTx: () => transaction,
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
/** {@inheritDoc BlueActions.delever} */
|
|
562
|
+
delever(params) {
|
|
563
|
+
const { userAddress, leverageData, now } = params;
|
|
564
|
+
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
565
|
+
validateChainId(leverageData.chainId, this.chainId);
|
|
566
|
+
if (leverageData.market.id !== this.parsedMarket.id) {
|
|
567
|
+
throw new MarketIdMismatchError(leverageData.market.id, this.parsedMarket.id);
|
|
568
|
+
}
|
|
569
|
+
this.validateLeverageNow(now);
|
|
570
|
+
const createdAt = Time.timestamp();
|
|
571
|
+
// Expired leverage data fails here first, so the caller is told to read a new one.
|
|
572
|
+
this.validateLeverageDeadline(leverageDeadline(leverageData), now);
|
|
573
|
+
const tx = blueDelever({
|
|
574
|
+
market: {
|
|
575
|
+
chainId: this.chainId,
|
|
576
|
+
// Built from the snapshot, never the caller's object, which the caller can mutate after construction.
|
|
577
|
+
marketParams: new MarketParams(this.parsedMarket),
|
|
578
|
+
},
|
|
579
|
+
args: {
|
|
580
|
+
leverageData,
|
|
581
|
+
userAddress,
|
|
582
|
+
txOrigin: params.txOrigin,
|
|
583
|
+
quote: params.quote,
|
|
584
|
+
slippage: params.slippage,
|
|
585
|
+
},
|
|
586
|
+
metadata: resolveTransactionMetadata(this.client.options.metadata, now),
|
|
587
|
+
});
|
|
588
|
+
const { deadline } = tx.action.args;
|
|
589
|
+
return {
|
|
590
|
+
getRequirements: async () => {
|
|
591
|
+
this.validateLeverageDeadline(deadline, this.elapsedLeverageNow(now, createdAt));
|
|
592
|
+
// Morpho Blue keeps its code check. A shipped leverage bundle's check is waived (docs/EXCEPTIONS.md); a bundle
|
|
593
|
+
// registered with registerCustomAddresses has its code checked in getLeverageRequirements.
|
|
594
|
+
await assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, [{ role: "blue", address: getChainAddress(this.chainId, "blue") }]);
|
|
595
|
+
return getLeverageRequirements({
|
|
596
|
+
viemClient: this.client.viemClient,
|
|
597
|
+
chainId: this.chainId,
|
|
598
|
+
userAddress,
|
|
599
|
+
marketParams: this.parsedMarket,
|
|
600
|
+
operation: { type: "delever" },
|
|
601
|
+
});
|
|
602
|
+
},
|
|
603
|
+
buildTx: () => tx,
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
/** {@inheritDoc BlueActions.close} */
|
|
607
|
+
close(params) {
|
|
608
|
+
const { userAddress, leverageData, now } = params;
|
|
609
|
+
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
610
|
+
this.validateLeverageNow(now);
|
|
611
|
+
const createdAt = Time.timestamp();
|
|
612
|
+
// Expired leverage data fails here first, so the caller is told to read a new one.
|
|
613
|
+
this.validateLeverageDeadline(leverageDeadline(leverageData), now);
|
|
614
|
+
const tx = blueClose({
|
|
615
|
+
market: {
|
|
616
|
+
chainId: this.chainId,
|
|
617
|
+
// Built from the snapshot, never the caller's object, which the caller can mutate after construction.
|
|
618
|
+
marketParams: new MarketParams(this.parsedMarket),
|
|
619
|
+
},
|
|
620
|
+
args: params,
|
|
621
|
+
metadata: resolveTransactionMetadata(this.client.options.metadata, now),
|
|
622
|
+
});
|
|
623
|
+
const { deadline } = tx.action.args;
|
|
624
|
+
return {
|
|
625
|
+
getRequirements: async () => {
|
|
626
|
+
this.validateLeverageDeadline(deadline, this.elapsedLeverageNow(now, createdAt));
|
|
627
|
+
// Morpho Blue keeps its code check. A shipped leverage bundle's check is waived (docs/EXCEPTIONS.md); a bundle
|
|
628
|
+
// registered with registerCustomAddresses has its code checked in getLeverageRequirements.
|
|
629
|
+
await assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, [{ role: "blue", address: getChainAddress(this.chainId, "blue") }]);
|
|
630
|
+
return getLeverageRequirements({
|
|
631
|
+
viemClient: this.client.viemClient,
|
|
632
|
+
chainId: this.chainId,
|
|
633
|
+
userAddress,
|
|
634
|
+
marketParams: this.parsedMarket,
|
|
635
|
+
operation: { type: "close" },
|
|
636
|
+
});
|
|
637
|
+
},
|
|
638
|
+
buildTx: () => tx,
|
|
639
|
+
};
|
|
640
|
+
}
|
|
146
641
|
supply(params) {
|
|
147
642
|
return this.supplyPrepared(this.parseSupplyParams(params));
|
|
148
643
|
}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
export type { IAccrualPosition as IBlueAccrualPosition, IAccrualVault, IAccrualVaultV2, IAccrualVaultV2Adapter, IAccrualVaultV2MorphoMarketV1Adapter, IAccrualVaultV2MorphoMarketV1AdapterV2, IAccrualVaultV2MorphoVaultV1Adapter, IAssetBalances, IEip5267Domain, IHolding, IMarket as IBlueMarket, IMarketParams as IBlueMarketParams, IPosition as IBluePosition,
|
|
1
|
+
export type { IAccrualPosition as IBlueAccrualPosition, IAccrualVault, IAccrualVaultV2, IAccrualVaultV2Adapter, IAccrualVaultV2MidnightAdapter, IAccrualVaultV2MorphoMarketV1Adapter, IAccrualVaultV2MorphoMarketV1AdapterV2, IAccrualVaultV2MorphoVaultV1Adapter, IAssetBalances, IEip5267Domain, IHolding, IMarket as IBlueMarket, IMarketParams as IBlueMarketParams, IPosition as IBluePosition,
|
|
2
2
|
/** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
|
|
3
3
|
IPreLiquidationParams as IBluePreLiquidationParams,
|
|
4
4
|
/** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
|
|
5
|
-
IPreLiquidationPosition as IBluePreLiquidationPosition, IToken, IVault, IVaultConfig, IVaultMarketAllocation, IVaultMarketConfig, IVaultToken, IVaultUser, IVaultV2, IVaultV2Adapter, IVaultV2Allocation, IVaultV2BlueMarketPublicAllocatorConfig, IVaultV2BluePublicAllocatorConfig, IVaultV2MorphoMarketV1Adapter, IVaultV2MorphoMarketV1AdapterV2, IVaultV2MorphoVaultV1Adapter, PeripheralBalance, PeripheralBalanceType, } from "@morpho-org/blue-sdk";
|
|
6
|
-
export { AccrualPosition as BlueAccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market as BlueMarket, MarketParams as BlueMarketParams, Position as BluePosition,
|
|
5
|
+
IPreLiquidationPosition as IBluePreLiquidationPosition, IToken, IVault, IVaultConfig, IVaultMarketAllocation, IVaultMarketConfig, IVaultToken, IVaultUser, IVaultV2, IVaultV2Adapter, IVaultV2Allocation, IVaultV2BlueMarketPublicAllocatorConfig, IVaultV2BluePublicAllocatorConfig, IVaultV2MidnightAdapter, IVaultV2MidnightAdapterAccrualMarket, IVaultV2MidnightAdapterCollateralParams, IVaultV2MidnightAdapterMarket, IVaultV2MidnightAdapterMarketData, IVaultV2MidnightAdapterMarketState, IVaultV2MidnightAdapterMidnightMarket, IVaultV2MidnightAdapterPosition, IVaultV2MorphoMarketV1Adapter, IVaultV2MorphoMarketV1AdapterV2, IVaultV2MorphoVaultV1Adapter, PeripheralBalance, PeripheralBalanceType, VaultV2MidnightAdapterAccrualMarket, VaultV2MidnightAdapterMarketData, } from "@morpho-org/blue-sdk";
|
|
6
|
+
export { AccrualPosition as BlueAccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MidnightAdapter, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market as BlueMarket, MarketParams as BlueMarketParams, Position as BluePosition,
|
|
7
7
|
/** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
|
|
8
8
|
PreLiquidationParams as BluePreLiquidationParams,
|
|
9
9
|
/** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
|
|
10
|
-
PreLiquidationPosition as BluePreLiquidationPosition, Token, User as BlueUser, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
|
|
10
|
+
PreLiquidationPosition as BluePreLiquidationPosition, Token, User as BlueUser, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2MidnightAdapter, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
|
|
11
11
|
export type { AnyTree as MidnightAnyTree, AnyTreeSnapshot as MidnightAnyTreeSnapshot, BuildOfferParams as MidnightBuildOfferParams, CollateralParams as MidnightCollateralParams, EcrecoverTreeCreateRequest as MidnightEcrecoverTreeCreateRequest, GroupInput as MidnightGroupInput, IAccrualPosition as IMidnightAccrualPosition, ICollateralParams as IMidnightCollateralParams, IGroup as IMidnightGroup, IMarket as IMidnightMarket, IMarketParams as IMidnightMarketParams, IOffer as IMidnightOffer, IPosition as IMidnightPosition, MarketInput as MidnightMarketInput, OfferStruct as MidnightOfferStruct, PriceRatifierV1TreeCreateRequest as MidnightPriceRatifierV1TreeCreateRequest, RateRatifierV1TreeCreateRequest as MidnightRateRatifierV1TreeCreateRequest, RatifierKind as MidnightRatifierKind, RatifierTreeInput as MidnightRatifierTreeInput, RatifierTypes as MidnightRatifierTypes, SetterTreeCreateRequest as MidnightSetterTreeCreateRequest, SettlementFeeCbps as MidnightSettlementFeeCbps, TreeCreateParams as MidnightTreeCreateParams, TreeCreateRequest as MidnightTreeCreateRequest, TreeData as MidnightTreeData, TreeDescriptor as MidnightTreeDescriptor, TreeEntry as MidnightTreeEntry, TreeInput as MidnightTreeInput, TreeLike as MidnightTreeLike, TreeMempoolValidateParams as MidnightTreeMempoolValidateParams, TreeMempoolValidateRatification as MidnightTreeMempoolValidateRatification, TreeProof as MidnightTreeProof, TreeSnapshot as MidnightTreeSnapshot, TypedRatifierTreeInput as MidnightTypedRatifierTreeInput, TypedTreeMempoolValidateParams as MidnightTypedTreeMempoolValidateParams, } from "@morpho-org/midnight-sdk";
|
|
12
12
|
export { AccrualPosition as MidnightAccrualPosition, Group as MidnightGroup, Market as MidnightMarket, MarketParams as MidnightMarketParams, Offer as MidnightOffer, Position as MidnightPosition, Tree as MidnightTree, } from "@morpho-org/midnight-sdk";
|
|
13
|
-
export type { BlueActions, BlueTokenRequirementsParams, } from "./blue/index.js";
|
|
13
|
+
export type { BlueActions, BlueLeverageData, BlueTokenRequirementsParams, } from "./blue/index.js";
|
|
14
14
|
export { MorphoBlue } from "./blue/index.js";
|
|
15
15
|
export type { GetOffersDataParams as MidnightGetOffersDataParams, GetPositionDataParams as MidnightGetPositionDataParams, MakeLendParams as MidnightMakeLendParams, MakeOffersOutput as MidnightMakeOffersOutput, MakeOffersParams as MidnightMakeOffersParams, MarketActionParams as MidnightMarketActionParams, MidnightMakerTreeInput, MidnightPositionHealthParams, OffersData as MidnightOffersData, OfferValidationParams as MidnightOfferValidationParams, RedeemParams as MidnightRedeemParams, RepayWithdrawCollateralParams as MidnightRepayWithdrawCollateralParams, SupplyBlueMakeLendParams as MidnightSupplyBlueMakeLendParams, SupplyCollateralBatchParams as MidnightSupplyCollateralBatchParams, SupplyCollateralMakeBorrowParams as MidnightSupplyCollateralMakeBorrowParams, SupplyCollateralParams as MidnightSupplyCollateralParams, SupplyCollateralTakeBorrowParams as MidnightSupplyCollateralTakeBorrowParams, TakeBorrowParams as MidnightTakeBorrowParams, TakeLendParams as MidnightTakeLendParams, TakeRepayWithdrawCollateralParams as MidnightTakeRepayWithdrawCollateralParams, TakeWithdrawParams as MidnightTakeWithdrawParams, WithdrawCollateralBatchParams as MidnightWithdrawCollateralBatchParams, WithdrawCollateralParams as MidnightWithdrawCollateralParams, } from "./midnight/index.js";
|
|
16
16
|
export { type MidnightActionOutput, type MidnightActions, type MidnightRequirementsParams, MorphoMidnight, } from "./midnight/index.js";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { AccrualPosition as BlueAccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market as BlueMarket, MarketParams as BlueMarketParams, Position as BluePosition,
|
|
1
|
+
export { AccrualPosition as BlueAccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MidnightAdapter, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market as BlueMarket, MarketParams as BlueMarketParams, Position as BluePosition,
|
|
2
2
|
/** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
|
|
3
3
|
PreLiquidationParams as BluePreLiquidationParams,
|
|
4
4
|
/** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
|
|
5
|
-
PreLiquidationPosition as BluePreLiquidationPosition, Token, User as BlueUser, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
|
|
5
|
+
PreLiquidationPosition as BluePreLiquidationPosition, Token, User as BlueUser, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2MidnightAdapter, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
|
|
6
6
|
export { AccrualPosition as MidnightAccrualPosition, Group as MidnightGroup, Market as MidnightMarket, MarketParams as MidnightMarketParams, Offer as MidnightOffer, Position as MidnightPosition, Tree as MidnightTree, } from "@morpho-org/midnight-sdk";
|
|
7
7
|
export { MorphoBlue } from "./blue/index.js";
|
|
8
8
|
export { MorphoMidnight, } from "./midnight/index.js";
|
|
@@ -1,29 +1,6 @@
|
|
|
1
1
|
import type { AddressLabel } from "@morpho-org/morpho-ts";
|
|
2
2
|
import type { Address, Client } from "viem";
|
|
3
3
|
import { type ChainCheck } from "../../actions/requirements/chainCheck.js";
|
|
4
|
-
/**
|
|
5
|
-
* Asserts that a configured contract address holds deployed code on the client's chain.
|
|
6
|
-
*
|
|
7
|
-
* A call to a code-less address succeeds on-chain as a no-op, so entity flows check each
|
|
8
|
-
* registered target before returning requirements. The `eth_getCode` read runs at the
|
|
9
|
-
* client's default block; transport failures propagate unwrapped because they are
|
|
10
|
-
* infrastructure failures, not configuration failures.
|
|
11
|
-
*
|
|
12
|
-
* @param client - Connected viem client used for the `eth_getCode` read.
|
|
13
|
-
* @param params - Assertion parameters.
|
|
14
|
-
* @param params.address - Contract address expected to hold code.
|
|
15
|
-
* @param params.chainId - Chain id the flow targets, reported on the error.
|
|
16
|
-
* @param params.role - Registry label naming the address's role in the flow.
|
|
17
|
-
* @returns Nothing when the address holds code.
|
|
18
|
-
* @throws {MissingContractCodeError} when the address has no deployed bytecode.
|
|
19
|
-
* @throws {viem.BaseError} when the `eth_getCode` read itself fails.
|
|
20
|
-
* @internal
|
|
21
|
-
*/
|
|
22
|
-
export declare const assertContractCode: (client: Client, params: {
|
|
23
|
-
readonly address: Address;
|
|
24
|
-
readonly chainId: number;
|
|
25
|
-
readonly role: AddressLabel;
|
|
26
|
-
}) => Promise<void>;
|
|
27
4
|
/**
|
|
28
5
|
* Asserts that each distinct target in a flow's write-surface list holds code.
|
|
29
6
|
*
|
|
@@ -1,30 +1,6 @@
|
|
|
1
|
-
import { getBytecode } from "viem/actions";
|
|
2
1
|
import { createChainCheck, } from "../../actions/requirements/chainCheck.js";
|
|
2
|
+
import { assertContractCode } from "../../reads/assertContractCode.js";
|
|
3
3
|
import { ChainIdMismatchError, MissingContractCodeError, } from "../../types/index.js";
|
|
4
|
-
/**
|
|
5
|
-
* Asserts that a configured contract address holds deployed code on the client's chain.
|
|
6
|
-
*
|
|
7
|
-
* A call to a code-less address succeeds on-chain as a no-op, so entity flows check each
|
|
8
|
-
* registered target before returning requirements. The `eth_getCode` read runs at the
|
|
9
|
-
* client's default block; transport failures propagate unwrapped because they are
|
|
10
|
-
* infrastructure failures, not configuration failures.
|
|
11
|
-
*
|
|
12
|
-
* @param client - Connected viem client used for the `eth_getCode` read.
|
|
13
|
-
* @param params - Assertion parameters.
|
|
14
|
-
* @param params.address - Contract address expected to hold code.
|
|
15
|
-
* @param params.chainId - Chain id the flow targets, reported on the error.
|
|
16
|
-
* @param params.role - Registry label naming the address's role in the flow.
|
|
17
|
-
* @returns Nothing when the address holds code.
|
|
18
|
-
* @throws {MissingContractCodeError} when the address has no deployed bytecode.
|
|
19
|
-
* @throws {viem.BaseError} when the `eth_getCode` read itself fails.
|
|
20
|
-
* @internal
|
|
21
|
-
*/
|
|
22
|
-
export const assertContractCode = async (client, params) => {
|
|
23
|
-
const bytecode = await getBytecode(client, { address: params.address });
|
|
24
|
-
if (bytecode === undefined || bytecode === "0x") {
|
|
25
|
-
throw new MissingContractCodeError(params.address, params.chainId, params.role);
|
|
26
|
-
}
|
|
27
|
-
};
|
|
28
4
|
/**
|
|
29
5
|
* Asserts that each distinct target in a flow's write-surface list holds code.
|
|
30
6
|
*
|