@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
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.blueDelever = void 0;
|
|
4
|
+
const viem_1 = require("viem");
|
|
5
|
+
const abis_js_1 = require("../../abis.js");
|
|
6
|
+
const constant_js_1 = require("../../helpers/constant.js");
|
|
7
|
+
const limits_js_1 = require("../../helpers/leverage/limits.js");
|
|
8
|
+
const positionMarket_js_1 = require("../../helpers/leverage/positionMarket.js");
|
|
9
|
+
const metadata_js_1 = require("../../helpers/metadata.js");
|
|
10
|
+
const validate_js_1 = require("../../helpers/validate.js");
|
|
11
|
+
const zeroExQuote_js_1 = require("../../helpers/zeroExQuote.js");
|
|
12
|
+
const index_js_1 = require("../../types/index.js");
|
|
13
|
+
const utils_js_1 = require("../../utils.js");
|
|
14
|
+
const leverageIntent_js_1 = require("./leverageIntent.js");
|
|
15
|
+
/**
|
|
16
|
+
* Encodes a ZeroExLeverageBundlesV1 Delever ("pay back with collateral"): the bundle repays
|
|
17
|
+
* `minRepayAssets` of the user's debt, withdraws `maxCollateralToSell`, sells at most that through 0x, supplies
|
|
18
|
+
* any unsold collateral back, repays the remaining debt with any swap output above `minRepayAssets` and sends
|
|
19
|
+
* what is left above the debt to the user's wallet, then checks `maxLtv` (ZeroExLeverageBundlesV1.sol:137-156, :310-325 at bundles 3bf5314).
|
|
20
|
+
*
|
|
21
|
+
* Pure and synchronous. Every bound comes from `computeDeleverLimits` and the quote is validated
|
|
22
|
+
* again with `validateZeroExQuote`, so a guard that fails refuses instead of building:
|
|
23
|
+
*
|
|
24
|
+
* - `maxCollateralToSell` is the quote's `sellAmount` and `minRepayAssets` its `minBuyAmount` as is, refused unless
|
|
25
|
+
* positive and at least `buyAmount × (1 − slippage)`, with the slippage rounded down to whole parts per
|
|
26
|
+
* million as 0x rounds it, then the amount rounded down.
|
|
27
|
+
* A repay above the debt refuses with `RepayExceedsDebtError`: offer the no-swap `repayWithdrawCollateral`
|
|
28
|
+
* exit instead.
|
|
29
|
+
* - `maxLtv` is the position's LTV with its debt accrued to the deadline, at the data block's price,
|
|
30
|
+
* never `type(uint256).max` and never the LLTV buffer, so a position already past LLTV − 0.5% can still
|
|
31
|
+
* delever. The build refuses when the worst fill (all collateral withdrawn, only `minRepayAssets`
|
|
32
|
+
* repaid, debt accrued to the deadline) would exceed that cap or fail Blue's health check.
|
|
33
|
+
* - The deadline is the leverage data timestamp plus one hour. No reallocation is involved.
|
|
34
|
+
*
|
|
35
|
+
* The SDK does not refuse on the quoted price: `action.args.oracleDeviation` reports the worst fill's deviation from the
|
|
36
|
+
* oracle; show it and `maxCollateralToSell` before the user signs.
|
|
37
|
+
*
|
|
38
|
+
* Delever pulls no token from the user; it needs the Morpho authorization of the bundle, which
|
|
39
|
+
* `getLeverageRequirements` returns.
|
|
40
|
+
*
|
|
41
|
+
* At most one ZeroExLeverageBundlesV1 call succeeds per transaction: bundles `3bf5314` keeps its transient initiator
|
|
42
|
+
* set until the transaction ends (L36, L49), so a second Lever, Delever or Close to the bundle in the same smart-account
|
|
43
|
+
* batch or ERC-4337 bundle reverts with `Reentrancy`. Send each one in its own transaction.
|
|
44
|
+
*
|
|
45
|
+
* @param params - Delever parameters.
|
|
46
|
+
* @param params.market - Chain and market the caller expects; the leverage data must match both.
|
|
47
|
+
* @param params.args.leverageData - One-block leverage data of the user's position.
|
|
48
|
+
* @param params.args.userAddress - Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself.
|
|
49
|
+
* @param params.args.txOrigin - Optional sender of the outer onchain transaction (its `tx.origin`) when it is not
|
|
50
|
+
* `userAddress`, such as a Safe's executing owner or an ERC-4337 bundler. The quote must have been fetched with
|
|
51
|
+
* the same value. Defaults to `userAddress`.
|
|
52
|
+
* @param params.args.quote - Exact-input 0x quote for the collateral to sell.
|
|
53
|
+
* @param params.args.slippage - Caller slippage, WAD-scaled, at most 10%.
|
|
54
|
+
* @param params.metadata - Optional transaction metadata.
|
|
55
|
+
* @returns A deep-frozen `Readonly<Transaction<BlueDeleverAction>>` to the leverage bundle with zero value, whose
|
|
56
|
+
* `action.args` carries the signed bounds, the swap's Settler and the data block.
|
|
57
|
+
* @throws {MarketIdMismatchError} when `market.marketParams` or the position's market tuple does not hash to
|
|
58
|
+
* its cached id, the position's `marketId` names another market than that tuple, or the leverage data position is
|
|
59
|
+
* for another market than `market.marketParams`.
|
|
60
|
+
* @throws {ChainIdMismatchError} when the leverage data was read on another chain than `market.chainId`.
|
|
61
|
+
* @throws {AccrualPositionUserMismatchError} when the leverage data position belongs to another user.
|
|
62
|
+
* @throws {ZeroExQuoteTypeMismatchError} when the quote is not exact input.
|
|
63
|
+
* @throws {ZeroExQuoteRequiredError} when no quote is given.
|
|
64
|
+
* @throws {LeverageQuoteSlippageMismatchError} when the quote was fetched with another slippage than `slippage`.
|
|
65
|
+
* @throws {ZeroExQuoteMinBuyAmountBelowSlippageError} when the quote's `minBuyAmount` is zero or below
|
|
66
|
+
* `buyAmount × (1 − slippage)`, with the slippage rounded down to whole parts per million, then the amount
|
|
67
|
+
* rounded down.
|
|
68
|
+
* @throws {RepayExceedsDebtError} when `minRepayAssets` exceeds the debt; offer the no-swap
|
|
69
|
+
* `repayWithdrawCollateral` exit instead.
|
|
70
|
+
* @throws {RepaySharesExceedDebtError} when `minRepayAssets` would burn more shares than the position holds.
|
|
71
|
+
* @throws {WithdrawExceedsCollateralError} when `maxCollateralToSell` exceeds the position's collateral.
|
|
72
|
+
* @throws {LeverageWorstFillLtvError} when the worst fill fails Blue's health check (`check: "health"`) or
|
|
73
|
+
* would raise the LTV (`check: "maxLtv"`).
|
|
74
|
+
* @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
|
|
75
|
+
* @throws {InvalidBigIntInputError} when `slippage` or `quote.slippage` is missing or not a bigint.
|
|
76
|
+
* @throws {NegativeInputError} when `slippage` is negative.
|
|
77
|
+
* @throws {NonPositiveInputError} when `sellAmount`, `buyAmount` or the deadline is not positive.
|
|
78
|
+
* @throws {InputExceedsMaxError} when the deadline exceeds `uint256`.
|
|
79
|
+
* @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero.
|
|
80
|
+
* @throws {UnsupportedMarketIrmError} when accruing the position's debt needs an unsupported IRM.
|
|
81
|
+
* @throws {LeverageUnsupportedChainError} when the chain has no AllowanceHolder or no registered bundle.
|
|
82
|
+
* @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address; pass a valid one or omit it
|
|
83
|
+
* instead of fetching a new quote.
|
|
84
|
+
* @throws {ZeroExQuoteError} when the quote's chain, tokens, taker, txOrigin, value, target, Settler, amount,
|
|
85
|
+
* recipient or calldata does not match the Delever (see `validateZeroExQuote`).
|
|
86
|
+
* @example
|
|
87
|
+
* ```ts
|
|
88
|
+
* import { markets } from "@morpho-org/morpho-test";
|
|
89
|
+
* import { type Address, createPublicClient, http } from "viem";
|
|
90
|
+
* import { base } from "viem/chains";
|
|
91
|
+
* import {
|
|
92
|
+
* blueDelever,
|
|
93
|
+
* fetchZeroExQuote,
|
|
94
|
+
* leverageDeadline,
|
|
95
|
+
* morphoViemExtension,
|
|
96
|
+
* } from "@morpho-org/morpho-sdk";
|
|
97
|
+
* import { isBlueZeroExLeverageChain } from "@morpho-org/morpho-sdk/addresses";
|
|
98
|
+
*
|
|
99
|
+
* // Delever needs a ZeroExLeverageBundlesV1 registered on the chain; without one the leverage data read
|
|
100
|
+
* // throws LeverageUnsupportedChainError.
|
|
101
|
+
* if (!isBlueZeroExLeverageChain(8453)) throw new Error("No leverage bundle is registered on Base yet.");
|
|
102
|
+
* declare const userAddress: Address; // owner of the position to delever
|
|
103
|
+
* const marketParams = markets[base.id].usdc_eth;
|
|
104
|
+
* const client = createPublicClient({ chain: base, transport: http() });
|
|
105
|
+
* const market = client.extend(morphoViemExtension()).morpho.blue(marketParams, 8453);
|
|
106
|
+
* const leverageData = await market.getLeverageData({ userAddress });
|
|
107
|
+
* const quote = await fetchZeroExQuote({
|
|
108
|
+
* chainId: 8453,
|
|
109
|
+
* kind: "delever",
|
|
110
|
+
* marketParams,
|
|
111
|
+
* userAddress,
|
|
112
|
+
* amount: 10n ** 17n,
|
|
113
|
+
* slippage: 5_000_000_000_000_000n, // 0.5%, WAD-scaled (1e18 = 100%), not bps
|
|
114
|
+
* deadline: leverageDeadline(leverageData), // the deadline the Delever signs
|
|
115
|
+
* apiKey: process.env.ZEROEX_API_KEY!,
|
|
116
|
+
* });
|
|
117
|
+
* const tx = blueDelever({
|
|
118
|
+
* market: { chainId: 8453, marketParams },
|
|
119
|
+
* args: {
|
|
120
|
+
* leverageData,
|
|
121
|
+
* userAddress,
|
|
122
|
+
* quote,
|
|
123
|
+
* slippage: 5_000_000_000_000_000n,
|
|
124
|
+
* },
|
|
125
|
+
* });
|
|
126
|
+
* // tx satisfies Readonly<Transaction<BlueDeleverAction>>
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
const blueDelever = (params) => {
|
|
130
|
+
const { market: { chainId, marketParams }, args: { leverageData, userAddress, quote, slippage }, } = params;
|
|
131
|
+
(0, validate_js_1.validateMarketParamsId)(marketParams);
|
|
132
|
+
(0, validate_js_1.validateChainId)(leverageData.chainId, chainId);
|
|
133
|
+
(0, validate_js_1.validateAccrualPosition)({
|
|
134
|
+
positionData: leverageData.position,
|
|
135
|
+
expectedMarketId: marketParams.id,
|
|
136
|
+
expectedUser: userAddress,
|
|
137
|
+
});
|
|
138
|
+
// The bounds come from the position's own market tuple, so it must be the expected market's.
|
|
139
|
+
(0, positionMarket_js_1.validateLeveragePositionMarket)(leverageData.position, marketParams);
|
|
140
|
+
if (typeof slippage !== "bigint") {
|
|
141
|
+
throw new index_js_1.InvalidBigIntInputError("slippage", slippage);
|
|
142
|
+
}
|
|
143
|
+
if (slippage < 0n) {
|
|
144
|
+
throw new index_js_1.NegativeInputError("slippage", slippage);
|
|
145
|
+
}
|
|
146
|
+
// Checked before the quote's slippage, so a requote advice never names a slippage the quote fetch refuses.
|
|
147
|
+
if (slippage > constant_js_1.LEVERAGE_MAX_EXECUTION_LOSS.delever) {
|
|
148
|
+
throw new index_js_1.LeverageSlippageAboveLimitError({
|
|
149
|
+
operation: "delever",
|
|
150
|
+
slippage,
|
|
151
|
+
max: constant_js_1.LEVERAGE_MAX_EXECUTION_LOSS.delever,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
if (quote == null) {
|
|
155
|
+
throw new index_js_1.ZeroExQuoteRequiredError({ operation: "delever" });
|
|
156
|
+
}
|
|
157
|
+
if (quote.mode !== "exactInput") {
|
|
158
|
+
throw new index_js_1.ZeroExQuoteTypeMismatchError({
|
|
159
|
+
expected: "exactInput",
|
|
160
|
+
actual: quote.mode,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
(0, leverageIntent_js_1.validateLeverageQuoteSlippage)({
|
|
164
|
+
operation: "delever",
|
|
165
|
+
slippage,
|
|
166
|
+
quoteSlippage: quote.slippage,
|
|
167
|
+
});
|
|
168
|
+
const limits = (0, limits_js_1.computeDeleverLimits)({
|
|
169
|
+
quote,
|
|
170
|
+
slippage,
|
|
171
|
+
leverageData,
|
|
172
|
+
});
|
|
173
|
+
const swap = (0, zeroExQuote_js_1.validateZeroExQuote)({
|
|
174
|
+
quote,
|
|
175
|
+
kind: "delever",
|
|
176
|
+
chainId,
|
|
177
|
+
marketParams,
|
|
178
|
+
userAddress,
|
|
179
|
+
txOrigin: params.args.txOrigin,
|
|
180
|
+
maxSwapInput: limits.maxCollateralToSell,
|
|
181
|
+
deadline: limits.deadline,
|
|
182
|
+
});
|
|
183
|
+
let transaction = {
|
|
184
|
+
to: swap.taker,
|
|
185
|
+
value: 0n,
|
|
186
|
+
data: (0, viem_1.encodeFunctionData)({
|
|
187
|
+
abi: abis_js_1.zeroExLeverageBundlesV1Abi,
|
|
188
|
+
functionName: "zeroExLeverageBundlesV1Delever",
|
|
189
|
+
args: [
|
|
190
|
+
marketParams,
|
|
191
|
+
limits.maxCollateralToSell,
|
|
192
|
+
limits.minRepayAssets,
|
|
193
|
+
swap.swapData,
|
|
194
|
+
limits.maxLtv,
|
|
195
|
+
limits.deadline,
|
|
196
|
+
],
|
|
197
|
+
}),
|
|
198
|
+
};
|
|
199
|
+
if (params.metadata != null) {
|
|
200
|
+
transaction = (0, metadata_js_1.addTransactionMetadata)(transaction, params.metadata);
|
|
201
|
+
}
|
|
202
|
+
return (0, utils_js_1.deepFreeze)({
|
|
203
|
+
...transaction,
|
|
204
|
+
action: {
|
|
205
|
+
type: "blueDelever",
|
|
206
|
+
args: {
|
|
207
|
+
market: marketParams.id,
|
|
208
|
+
onBehalf: userAddress,
|
|
209
|
+
maxCollateralToSell: limits.maxCollateralToSell,
|
|
210
|
+
minRepayAssets: limits.minRepayAssets,
|
|
211
|
+
maxLtv: limits.maxLtv,
|
|
212
|
+
deadline: limits.deadline,
|
|
213
|
+
settler: swap.settler,
|
|
214
|
+
oracleDeviation: { status: "measured", ...limits.oracleDeviation },
|
|
215
|
+
block: {
|
|
216
|
+
number: leverageData.block.number,
|
|
217
|
+
timestamp: leverageData.block.timestamp,
|
|
218
|
+
},
|
|
219
|
+
},
|
|
220
|
+
},
|
|
221
|
+
});
|
|
222
|
+
};
|
|
223
|
+
exports.blueDelever = blueDelever;
|
|
@@ -15,6 +15,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
__exportStar(require("./borrow.js"), exports);
|
|
18
|
+
__exportStar(require("./close.js"), exports);
|
|
19
|
+
__exportStar(require("./delever.js"), exports);
|
|
20
|
+
__exportStar(require("./lever.js"), exports);
|
|
18
21
|
__exportStar(require("./refinance.js"), exports);
|
|
19
22
|
__exportStar(require("./repay.js"), exports);
|
|
20
23
|
__exportStar(require("./repayWithdrawCollateral.js"), exports);
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { MarketParams } from "@morpho-org/blue-sdk";
|
|
2
|
+
import { type Address } from "viem";
|
|
3
|
+
import { type LeverageLimitsData } from "../../helpers/leverage/limits.js";
|
|
4
|
+
import { type LeverageAllocatorState } from "../../helpers/leverage/reallocations.js";
|
|
5
|
+
import { type BlueLeverAction, type Metadata, type Transaction, type VaultV2BlueReallocation, type ZeroExQuote } from "../../types/index.js";
|
|
6
|
+
/**
|
|
7
|
+
* One-block state a Lever is built from: the limits data plus the chain, the block number and the
|
|
8
|
+
* BluePublicAllocator state read at that block. `MorphoBlue.getLeverageData`
|
|
9
|
+
* returns it; pass its result unmodified.
|
|
10
|
+
*/
|
|
11
|
+
export interface BlueLeverData extends LeverageLimitsData {
|
|
12
|
+
/** Chain every field was read on. */
|
|
13
|
+
readonly chainId: number;
|
|
14
|
+
/** Block number and timestamp every field was read at. */
|
|
15
|
+
readonly block: {
|
|
16
|
+
readonly number: bigint;
|
|
17
|
+
readonly timestamp: bigint;
|
|
18
|
+
};
|
|
19
|
+
/** BluePublicAllocator state the reallocations are checked against. */
|
|
20
|
+
readonly reallocationData: LeverageAllocatorState;
|
|
21
|
+
}
|
|
22
|
+
/** Parameters for {@link blueLever}. */
|
|
23
|
+
export interface BlueLeverParams {
|
|
24
|
+
/** Chain and scoped Morpho Blue market. */
|
|
25
|
+
readonly market: {
|
|
26
|
+
readonly chainId: number;
|
|
27
|
+
readonly marketParams: MarketParams;
|
|
28
|
+
};
|
|
29
|
+
/** Lever intent and inputs. */
|
|
30
|
+
readonly args: {
|
|
31
|
+
/** Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself; its position is levered. */
|
|
32
|
+
readonly userAddress: Address;
|
|
33
|
+
/** One-block leverage data the limits are computed from. */
|
|
34
|
+
readonly leverageData: BlueLeverData;
|
|
35
|
+
/**
|
|
36
|
+
* Sender of the outer onchain transaction (its `tx.origin`) when it is not `userAddress`: the owner EOA that
|
|
37
|
+
* executes a Safe transaction, or the bundler that submits an ERC-4337 UserOperation, not the wallet's signer. The
|
|
38
|
+
* quote must have been fetched with the same `txOrigin`. Defaults to `userAddress`.
|
|
39
|
+
*/
|
|
40
|
+
readonly txOrigin?: Address;
|
|
41
|
+
/** Exact-output 0x quote buying the collateral, fetched with the bundle as taker and `txOrigin` as txOrigin. */
|
|
42
|
+
readonly quote: ZeroExQuote;
|
|
43
|
+
/** Caller slippage passed to 0x, WAD-scaled, at most 10%. */
|
|
44
|
+
readonly slippage: bigint;
|
|
45
|
+
/** Collateral pulled from the user and supplied. */
|
|
46
|
+
readonly collateralAssets: bigint;
|
|
47
|
+
/** Loan assets pulled from the user and swapped. */
|
|
48
|
+
readonly loanAssets: bigint;
|
|
49
|
+
/** Reallocations `VaultV2BlueReallocationData` planned toward this market; none by default. */
|
|
50
|
+
readonly reallocations?: readonly VaultV2BlueReallocation[];
|
|
51
|
+
/**
|
|
52
|
+
* Native token sent as the transaction `value`, which the bundle wraps into the chain's wNative and sends to
|
|
53
|
+
* `userAddress` before pulling `collateralAssets` and `loanAssets`. Only when the market's collateral or loan
|
|
54
|
+
* token is the chain's wNative, and at most that token's pull. Omitted or zero sends no value.
|
|
55
|
+
*/
|
|
56
|
+
readonly nativeAmount?: bigint;
|
|
57
|
+
};
|
|
58
|
+
/** Optional transaction metadata suffix. */
|
|
59
|
+
readonly metadata?: Metadata;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Encodes a ZeroExLeverageBundlesV1 Lever: pulls `collateralAssets` and `loanAssets` from the user,
|
|
63
|
+
* executes the planned BluePublicAllocator reallocations, borrows `maxBorrowAssets` and buys at least
|
|
64
|
+
* the quote's `buyAmount` (`minCollateralToBuy`) of collateral through 0x, all in one call to the chain's
|
|
65
|
+
* registered bundle. The bundle also accepts a 0x SELL quote, but the SDK builds Lever from exact-output quotes only.
|
|
66
|
+
*
|
|
67
|
+
* With a positive `nativeAmount`, the transaction sends it as `value` and the bundle wraps it into the chain's
|
|
68
|
+
* wNative (`wrappedNative`) and transfers it to the user before the pulls, so the user's wNative approval still
|
|
69
|
+
* covers the whole pull. Without it, `value` is zero and `wrappedNative` the zero address.
|
|
70
|
+
*
|
|
71
|
+
* Every bound is computed, none is taken from the caller:
|
|
72
|
+
* - `computeLeverLimits` takes the quote's `maxSellAmount` as the swap cap (0x already applied the
|
|
73
|
+
* slippage, and the Settler pulls that whole amount) and derives the borrow and `maxLtv` (LLTV minus `DEFAULT_LLTV_BUFFER`, never `type(uint256).max`). It
|
|
74
|
+
* refuses a worst fill that fails Blue's mid-flow health check (`check: "health"`) or `maxLtv`
|
|
75
|
+
* (`check: "maxLtv"`), refuses a worst swap price (`maxSwapIn` per `minCollateralToBuy`) more than
|
|
76
|
+
* `LEVERAGE_MAX_ORACLE_DEVIATION` (15%) above the market's oracle price (a lower price is never refused), and fixes the deadline one hour
|
|
77
|
+
* after the data block. The price and the debt are the data block's; until the deadline only the signed `maxLtv`
|
|
78
|
+
* and Blue's health check guard execution. The deviation compares `maxSwapIn` alone: reallocation penalties
|
|
79
|
+
* (`penaltyAssets`, at most 1% each) are paid on top.
|
|
80
|
+
* - `penaltyAssets` is each reallocation's penalty rounded up, then summed, as the bundle checks it. A Lever
|
|
81
|
+
* that borrows nothing takes no reallocation, as the bundle reverts with `InconsistentBorrowInput` otherwise.
|
|
82
|
+
* `validateLeverageReallocations` refuses a reallocation to another market, through a route the
|
|
83
|
+
* allocator does not allow at the data block, above the 1% penalty ceiling, or reallocations
|
|
84
|
+
* that move more than the borrow. It does not check remaining caps or IRM compatibility, so pass
|
|
85
|
+
* only reallocations `VaultV2BlueReallocationData` planned for this borrow, as `MorphoBlue.lever`
|
|
86
|
+
* does.
|
|
87
|
+
* - `validateZeroExQuote` decodes the swap against the market's tokens, the bundle and the swap cap. It does not
|
|
88
|
+
* check whether the swap's Settler is 0x's official one or paused; the bundle's `maxIn` bounds the swap.
|
|
89
|
+
*
|
|
90
|
+
* Each guard's typed error surfaces unchanged and nothing is encoded when one fails. The builder is
|
|
91
|
+
* synchronous and pure: identical inputs give identical calldata.
|
|
92
|
+
*
|
|
93
|
+
* At most one ZeroExLeverageBundlesV1 call succeeds per transaction: bundles `3bf5314` keeps its transient initiator
|
|
94
|
+
* set until the transaction ends (L36, L49), so a second Lever, Delever or Close to the bundle in the same smart-account
|
|
95
|
+
* batch or ERC-4337 bundle reverts with `Reentrancy`. Send each one in its own transaction.
|
|
96
|
+
*
|
|
97
|
+
* @param params - Lever encoding parameters.
|
|
98
|
+
* @param params.market.chainId - Chain of the market and the bundle.
|
|
99
|
+
* @param params.market.marketParams - Scoped Morpho Blue market parameters.
|
|
100
|
+
* @param params.args.userAddress - Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself.
|
|
101
|
+
* @param params.args.txOrigin - Optional sender of the outer onchain transaction (its `tx.origin`) when it is not
|
|
102
|
+
* `userAddress`, such as a Safe's executing owner or an ERC-4337 bundler. The quote must have been fetched with
|
|
103
|
+
* the same value. Defaults to `userAddress`.
|
|
104
|
+
* @param params.args.leverageData - One-block leverage data from `MorphoBlue.getLeverageData`.
|
|
105
|
+
* @param params.args.quote - Exact-output 0x quote for the collateral to buy.
|
|
106
|
+
* @param params.args.slippage - Caller slippage, WAD-scaled, at most 10%.
|
|
107
|
+
* @param params.args.collateralAssets - Collateral the user deposits.
|
|
108
|
+
* @param params.args.loanAssets - Loan assets the user deposits.
|
|
109
|
+
* @param params.args.reallocations - Planner-built reallocations toward this market.
|
|
110
|
+
* @param params.args.nativeAmount - Optional native token the bundle wraps into wNative before the pulls.
|
|
111
|
+
* @param params.metadata - Optional transaction metadata.
|
|
112
|
+
* @returns A deep-frozen `Readonly<Transaction<BlueLeverAction>>` calling
|
|
113
|
+
* `zeroExLeverageBundlesV1Lever` on the registered bundle.
|
|
114
|
+
* @throws {MarketIdMismatchError} when `marketParams` or the position's market tuple does not hash to its
|
|
115
|
+
* cached id, or the leverage data position or its market tuple is for another market.
|
|
116
|
+
* @throws {ChainIdMismatchError} when the leverage data was read on another chain.
|
|
117
|
+
* @throws {AccrualPositionUserMismatchError} when the leverage data position belongs to another user.
|
|
118
|
+
* @throws {InvalidBigIntInputError} when `collateralAssets`, `loanAssets`, `nativeAmount`, `slippage`,
|
|
119
|
+
* `quote.slippage`, or a reallocation's `assets` or `penalty` is not a bigint.
|
|
120
|
+
* @throws {NegativeInputError} when an intent amount, the slippage or a reallocation penalty is negative.
|
|
121
|
+
* @throws {InputExceedsMaxError} when an intent amount, a signed amount or the deadline exceeds `uint256`, when
|
|
122
|
+
* `loanAssets` exceeds the swap cap plus the penalty, when `nativeAmount` exceeds the pull of the wNative
|
|
123
|
+
* token, or when a reallocation exceeds its ABI bound.
|
|
124
|
+
* @throws {ZeroExQuoteTypeMismatchError} when the quote is not exact output.
|
|
125
|
+
* @throws {ZeroExQuoteRequiredError} when no quote is given.
|
|
126
|
+
* @throws {LeverageQuoteSlippageMismatchError} when the quote was fetched with another slippage than `slippage`.
|
|
127
|
+
* @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
|
|
128
|
+
* @throws {LeverageWorstFillLtvError} when the worst fill fails Blue's health check or `maxLtv`.
|
|
129
|
+
* @throws {LeverageOraclePriceDeviationError} when the quote's worst price is more than 15% above the market's
|
|
130
|
+
* oracle price.
|
|
131
|
+
* @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero.
|
|
132
|
+
* @throws {NonPositiveInputError} when a quote amount, a reallocation amount or the deadline is not positive.
|
|
133
|
+
* @throws {LeverageReallocationMarketMismatchError} when a reallocation targets another market.
|
|
134
|
+
* @throws {LeverageReallocationNoFlowError} when the allocator does not allow a reallocation's route.
|
|
135
|
+
* @throws {LeverageReallocationPenaltyAboveLimitError} when a reallocation's penalty rate exceeds 1%.
|
|
136
|
+
* @throws {LeverageReallocationExceedsBorrowError} when the reallocations move more than the borrow, including any
|
|
137
|
+
* reallocation of a Lever that borrows nothing.
|
|
138
|
+
* @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount` is positive and neither market token is the
|
|
139
|
+
* chain's wNative.
|
|
140
|
+
* @throws {ChainWNativeMissingError} when `nativeAmount` is positive and the chain registers no wNative.
|
|
141
|
+
* @throws {LeverageInsufficientLiquidityError} when the market's liquidity at the data block plus
|
|
142
|
+
* the reallocated assets cannot fund the borrow. Passing it does not make the Lever land: when
|
|
143
|
+
* `penaltyAssets` exceeds `loanAssets`, the bundle flash-loans the difference from Blue before it borrows, and
|
|
144
|
+
* the SDK does not check Blue's loan-token balance, so a Lever that pays a penalty can still revert onchain when
|
|
145
|
+
* Blue is short of cash.
|
|
146
|
+
* @throws {InconsistentReallocationPenaltyError} when a reallocation's penalty is not its vault's.
|
|
147
|
+
* @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdraws from the Lever's market.
|
|
148
|
+
* @throws {ReallocationLoanTokenMismatchError} when a reallocation's source uses another loan token.
|
|
149
|
+
* @throws {ZeroExQuoteAmountExceedsCapError} when the amount the quote's calldata lets Settler pull
|
|
150
|
+
* exceeds the swap cap.
|
|
151
|
+
* @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address; pass a valid one or omit it
|
|
152
|
+
* instead of fetching a new quote.
|
|
153
|
+
* @throws {ZeroExQuoteError} for any other quote mismatch documented on `validateZeroExQuote`.
|
|
154
|
+
* @throws {LeverageUnsupportedChainError} when the chain has no usable leverage bundle.
|
|
155
|
+
* @example
|
|
156
|
+
* ```ts
|
|
157
|
+
* import { blueLever, fetchZeroExQuote, leverageDeadline } from "@morpho-org/morpho-sdk";
|
|
158
|
+
*
|
|
159
|
+
* // leverageData = await client.morpho.blue(marketParams, chainId).getLeverageData({ userAddress });
|
|
160
|
+
* const quote = await fetchZeroExQuote({
|
|
161
|
+
* chainId,
|
|
162
|
+
* kind: "lever",
|
|
163
|
+
* marketParams,
|
|
164
|
+
* userAddress,
|
|
165
|
+
* amount: 2n * 10n ** 18n,
|
|
166
|
+
* slippage: 5_000_000_000_000_000n, // 0.5%, WAD-scaled (1e18 = 100%), not bps
|
|
167
|
+
* deadline: leverageDeadline(leverageData), // the deadline the Lever signs
|
|
168
|
+
* apiKey,
|
|
169
|
+
* });
|
|
170
|
+
* const tx = blueLever({
|
|
171
|
+
* market: { chainId, marketParams },
|
|
172
|
+
* args: {
|
|
173
|
+
* userAddress,
|
|
174
|
+
* leverageData,
|
|
175
|
+
* quote,
|
|
176
|
+
* slippage: 5_000_000_000_000_000n,
|
|
177
|
+
* collateralAssets: 10n ** 18n,
|
|
178
|
+
* loanAssets: 0n,
|
|
179
|
+
* },
|
|
180
|
+
* });
|
|
181
|
+
* // tx.to is the registered ZeroExLeverageBundlesV1; tx.action.args.maxBorrowAssets is the borrow.
|
|
182
|
+
* ```
|
|
183
|
+
*/
|
|
184
|
+
export declare const blueLever: (params: BlueLeverParams) => Readonly<Transaction<BlueLeverAction>>;
|