@morpho-org/morpho-sdk 10.5.0-next.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 +793 -0
- package/lib/cjs/abis.js +811 -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/midnight/supplyCollateralTakeBorrow.js +16 -11
- package/lib/cjs/actions/midnight/takeBorrow.js +14 -8
- package/lib/cjs/actions/midnight/takeLend.js +15 -9
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
- package/lib/cjs/actions/midnight/takeWithdraw.js +14 -8
- 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/addresses.d.ts +1 -1
- package/lib/cjs/blue/addresses.js +6 -1
- package/lib/cjs/constants.d.ts +1 -1
- package/lib/cjs/constants.js +7 -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 +1 -1
- package/lib/cjs/entities/midnight/midnight.d.ts +6 -0
- package/lib/cjs/entities/midnight/midnight.js +21 -2
- package/lib/cjs/entities/requirements/assertContractCode.d.ts +0 -23
- package/lib/cjs/entities/requirements/assertContractCode.js +3 -28
- package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +117 -0
- package/lib/cjs/entities/vaultV2BlueReallocationData.js +226 -2
- package/lib/cjs/helpers/constant.d.ts +41 -0
- package/lib/cjs/helpers/constant.js +42 -1
- 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 +29 -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/validate.d.ts +14 -0
- package/lib/cjs/helpers/validate.js +25 -1
- 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/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/transactionPlan/midnight/takeBorrow.d.ts +4 -0
- package/lib/cjs/transactionPlan/midnight/takeBorrow.js +8 -2
- package/lib/cjs/types/action.d.ts +130 -1
- package/lib/cjs/types/error.d.ts +84 -0
- package/lib/cjs/types/error.js +110 -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/version.d.ts +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/esm/abis.d.ts +793 -0
- package/lib/esm/abis.js +809 -0
- 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/midnight/supplyCollateralTakeBorrow.js +16 -11
- package/lib/esm/actions/midnight/takeBorrow.js +14 -8
- package/lib/esm/actions/midnight/takeLend.js +15 -9
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
- package/lib/esm/actions/midnight/takeWithdraw.js +14 -8
- 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/addresses.d.ts +1 -1
- package/lib/esm/blue/addresses.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 +1 -1
- package/lib/esm/entities/midnight/midnight.d.ts +6 -0
- package/lib/esm/entities/midnight/midnight.js +21 -2
- package/lib/esm/entities/requirements/assertContractCode.d.ts +0 -23
- package/lib/esm/entities/requirements/assertContractCode.js +1 -25
- package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +117 -0
- package/lib/esm/entities/vaultV2BlueReallocationData.js +227 -3
- package/lib/esm/helpers/constant.d.ts +41 -0
- package/lib/esm/helpers/constant.js +41 -0
- 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/validate.d.ts +14 -0
- package/lib/esm/helpers/validate.js +25 -2
- 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/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/transactionPlan/midnight/takeBorrow.d.ts +4 -0
- package/lib/esm/transactionPlan/midnight/takeBorrow.js +9 -3
- package/lib/esm/types/action.d.ts +130 -1
- package/lib/esm/types/error.d.ts +84 -0
- package/lib/esm/types/error.js +103 -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/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1,169 @@
|
|
|
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 BlueCloseAction, type Metadata, type Transaction } from "../../types/index.js";
|
|
5
|
+
import type { ZeroExQuote } from "../../types/zeroEx.js";
|
|
6
|
+
/**
|
|
7
|
+
* One-block state a Close is built from: the fields of `getLeverageData()` the builder reads.
|
|
8
|
+
* Pass the unmodified `getLeverageData()` result; the builder trusts its position.
|
|
9
|
+
*/
|
|
10
|
+
export type BlueCloseData = LeverageLimitsData & {
|
|
11
|
+
readonly chainId: number;
|
|
12
|
+
readonly block: {
|
|
13
|
+
readonly number: bigint;
|
|
14
|
+
readonly timestamp: bigint;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
/** Parameters for {@link blueClose}. */
|
|
18
|
+
export interface BlueCloseParams {
|
|
19
|
+
/** Chain and scoped Morpho Blue market. */
|
|
20
|
+
readonly market: {
|
|
21
|
+
readonly chainId: number;
|
|
22
|
+
readonly marketParams: MarketParams;
|
|
23
|
+
};
|
|
24
|
+
/** Caller inputs of the Close. */
|
|
25
|
+
readonly args: {
|
|
26
|
+
/** Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself; its position is closed. */
|
|
27
|
+
readonly userAddress: Address;
|
|
28
|
+
/**
|
|
29
|
+
* Sender of the outer onchain transaction (its `tx.origin`) when it is not `userAddress`: the owner EOA that
|
|
30
|
+
* executes a Safe transaction, or the bundler that submits an ERC-4337 UserOperation, not the wallet's signer. The
|
|
31
|
+
* quote must have been fetched with the same `txOrigin`. Defaults to `userAddress`.
|
|
32
|
+
*/
|
|
33
|
+
readonly txOrigin?: Address;
|
|
34
|
+
/** One-block leverage data of the user's position on the market. */
|
|
35
|
+
readonly leverageData: BlueCloseData;
|
|
36
|
+
/** Exact-output 0x quote from `fetchZeroExQuote` with kind `closeKeepCollateral`. */
|
|
37
|
+
readonly quote?: ZeroExQuote;
|
|
38
|
+
/** Caller slippage, WAD-scaled, at most `LEVERAGE_MAX_EXECUTION_LOSS.close` (10%). */
|
|
39
|
+
readonly slippage: bigint;
|
|
40
|
+
};
|
|
41
|
+
/** Optional transaction metadata suffix. */
|
|
42
|
+
readonly metadata?: Metadata;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Encodes a ZeroExLeverageBundlesV1 Close: repays the user's whole debt by swapping collateral
|
|
46
|
+
* through 0x and sends what is left to the user. Pure and synchronous: it validates the quote
|
|
47
|
+
* on every build and reads no chain state.
|
|
48
|
+
*
|
|
49
|
+
* - **With debt (`keepCollateral`):** an exact-output quote buys exactly the debt plus the SDK's
|
|
50
|
+
* interest buffer (`computeCloseInterestBuffer`: debt × borrow rate × 1 hour × 4). `minLoanOut` is
|
|
51
|
+
* that buy amount, which must equal exactly the debt accrued to the data block plus the buffer, both
|
|
52
|
+
* from the same leverage data, and `maxCollateralIn`
|
|
53
|
+
* the quote's `maxSellAmount`, never above the position's collateral. Unsold collateral and unused
|
|
54
|
+
* loan token return to the user. The buffer is an estimate at the data block's borrow rate: it
|
|
55
|
+
* makes an interest-driven revert unlikely, not impossible, if the rate jumps before execution.
|
|
56
|
+
* - **No debt:** refused with `LeverageCloseWithoutDebtError`. At bundles `3bf5314` a Close without debt still
|
|
57
|
+
* withdraws the collateral and runs the swap, and AllowanceHolder reverts on empty swap calldata; withdraw the
|
|
58
|
+
* collateral with `market.withdrawCollateral` (`blueWithdrawCollateral`) instead.
|
|
59
|
+
* The check reads the leverage data's block only. If the debt is fully repaid between that block and execution,
|
|
60
|
+
* the bundle still runs the signed swap: it sells at most `maxCollateralIn` for at least `minLoanOut` and sends
|
|
61
|
+
* the loan tokens and the unsold collateral to the user, instead of returning all the collateral unsold
|
|
62
|
+
* (bundles `3bf5314` L165, L186-L188). Rebuild the Close from fresh data after any repayment.
|
|
63
|
+
*
|
|
64
|
+
* Every swap bound comes from the quote and the slippage only. A quote whose Settler slippage struct names a minimum
|
|
65
|
+
* below the signed `minLoanOut` (the quote's `buyAmount`), even by one unit, is refused with
|
|
66
|
+
* `ZeroExQuoteMinAmountOutMismatchError`: fetch a new quote. An all-zero slippage struct is the one
|
|
67
|
+
* exception, accepted because the bundle enforces `minLoanOut` onchain. Close signs no `maxLtv`:
|
|
68
|
+
* the contract has none for it. The deadline is the leverage data timestamp plus one hour.
|
|
69
|
+
*
|
|
70
|
+
* When a Close is refused, exit without a swap through the existing Blue methods: `repay` or
|
|
71
|
+
* `supplyCollateral` reduce risk, and `repayWithdrawCollateral` leaves the position.
|
|
72
|
+
*
|
|
73
|
+
* At most one ZeroExLeverageBundlesV1 call succeeds per transaction: bundles `3bf5314` keeps its transient initiator
|
|
74
|
+
* set until the transaction ends (L36, L49), so a second Lever, Delever or Close to the bundle in the same smart-account
|
|
75
|
+
* batch or ERC-4337 bundle reverts with `Reentrancy`. Send each one in its own transaction.
|
|
76
|
+
*
|
|
77
|
+
* @param params - Close encoding parameters.
|
|
78
|
+
* @param params.market.chainId - Chain of the market.
|
|
79
|
+
* @param params.market.marketParams - Scoped Morpho Blue market parameters.
|
|
80
|
+
* @param params.args.userAddress - Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself; its position is closed.
|
|
81
|
+
* @param params.args.txOrigin - Optional sender of the outer onchain transaction (its `tx.origin`) when it is not
|
|
82
|
+
* `userAddress`, such as a Safe's executing owner or an ERC-4337 bundler. The quote must have been fetched with
|
|
83
|
+
* the same value. Defaults to `userAddress`.
|
|
84
|
+
* @param params.args.leverageData - Unmodified `getLeverageData()` result for the user and market.
|
|
85
|
+
* @param params.args.quote - Exact-output 0x quote of kind `closeKeepCollateral`; required with debt.
|
|
86
|
+
* @param params.args.slippage - Caller slippage, WAD-scaled, at most 10%.
|
|
87
|
+
* @param params.metadata - Optional transaction metadata.
|
|
88
|
+
* @returns A deep-frozen `Readonly<Transaction<BlueCloseAction>>` sent to ZeroExLeverageBundlesV1,
|
|
89
|
+
* whose `action.args` records the signed bounds, the Settler and the leverage data block.
|
|
90
|
+
* @throws {MarketIdMismatchError} when `marketParams` or the position's market tuple does not hash to its
|
|
91
|
+
* cached id, or the leverage data position or its market tuple is for another market.
|
|
92
|
+
* @throws {AccrualPositionUserMismatchError} when the leverage data position belongs to another user.
|
|
93
|
+
* @throws {ChainIdMismatchError} when the leverage data was read on another chain.
|
|
94
|
+
* @throws {LeverageUnsupportedChainError} when the chain has no usable leverage bundle.
|
|
95
|
+
* @throws {LeverageCloseEmptyPositionError} when the position has neither debt nor collateral. There is no
|
|
96
|
+
* fallback transaction for it: tell the user there is nothing to close.
|
|
97
|
+
* @throws {LeverageCloseWithoutDebtError} when the position has collateral but no debt; withdraw the collateral with
|
|
98
|
+
* `market.withdrawCollateral` (`blueWithdrawCollateral`) instead.
|
|
99
|
+
* @throws {ZeroExQuoteRequiredError} when the position has debt and no quote is given.
|
|
100
|
+
* @throws {ZeroExQuoteTypeMismatchError} when the quote is not an exact-output quote.
|
|
101
|
+
* @throws {LeverageQuoteSlippageMismatchError} when the quote was fetched with another slippage than `slippage`.
|
|
102
|
+
* @throws {LeverageCloseInputExceedsCollateralError} when `maxCollateralIn` exceeds the collateral.
|
|
103
|
+
* @throws {LeverageCloseBuyAboveDebtError} when the quote buys more than the debt plus the interest
|
|
104
|
+
* buffer.
|
|
105
|
+
* @throws {LeverageCloseFloorBelowDebtPlusBufferError} when `minLoanOut` is below the debt plus the interest
|
|
106
|
+
* buffer.
|
|
107
|
+
* @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
|
|
108
|
+
* @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero. Exit without a
|
|
109
|
+
* swap instead.
|
|
110
|
+
* @throws {InputExceedsMaxError} when `minLoanOut` or the deadline exceeds `uint256`.
|
|
111
|
+
* @throws {InvalidBigIntInputError} when `slippage`, `quote.slippage` or `leverageData.block.timestamp` is missing or not
|
|
112
|
+
* a bigint, or when the position has debt and `leverageData.borrowRate` is missing or not a bigint.
|
|
113
|
+
* @throws {NegativeInputError} when `slippage` is negative, or when the position has debt and `leverageData.borrowRate` is
|
|
114
|
+
* negative.
|
|
115
|
+
* @throws {NonPositiveInputError} when a quote amount or the deadline is not positive.
|
|
116
|
+
* @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address; pass a valid one or omit it
|
|
117
|
+
* instead of fetching a new quote.
|
|
118
|
+
* @throws {ZeroExQuoteError} for any other quote or calldata mismatch `validateZeroExQuote` refuses.
|
|
119
|
+
* @example
|
|
120
|
+
* ```ts
|
|
121
|
+
* import { createPublicClient, http } from "viem";
|
|
122
|
+
* import { base } from "viem/chains";
|
|
123
|
+
* import {
|
|
124
|
+
* blueClose,
|
|
125
|
+
* computeCloseInterestBuffer,
|
|
126
|
+
* fetchZeroExQuote,
|
|
127
|
+
* leverageDeadline,
|
|
128
|
+
* morphoViemExtension,
|
|
129
|
+
* } from "@morpho-org/morpho-sdk";
|
|
130
|
+
* import { isBlueZeroExLeverageChain } from "@morpho-org/morpho-sdk/addresses";
|
|
131
|
+
*
|
|
132
|
+
* // Close needs a ZeroExLeverageBundlesV1 registered on the chain; without one the leverage data read
|
|
133
|
+
* // throws LeverageUnsupportedChainError.
|
|
134
|
+
* if (!isBlueZeroExLeverageChain(base.id)) throw new Error("No leverage bundle is registered on Base yet.");
|
|
135
|
+
* const client = createPublicClient({ chain: base, transport: http() }).extend(morphoViemExtension());
|
|
136
|
+
* const leverageData = await client.morpho
|
|
137
|
+
* .blue(marketParams, base.id)
|
|
138
|
+
* .getLeverageData({ userAddress });
|
|
139
|
+
* const slippage = 5_000_000_000_000_000n; // 0.5%, WAD-scaled (1e18 = 100%), not bps
|
|
140
|
+
* // A position without debt (no borrow shares) has no Close: withdraw its collateral with blueWithdrawCollateral
|
|
141
|
+
* // instead. Check it before fetching a quote, whose amount would be zero.
|
|
142
|
+
* if (leverageData.position.borrowShares === 0n) {
|
|
143
|
+
* throw new Error("No debt: withdraw the collateral with blueWithdrawCollateral instead of a Close.");
|
|
144
|
+
* }
|
|
145
|
+
* // The debt accrued to the data block, as the builder computes it.
|
|
146
|
+
* const { borrowAssets } = leverageData.position.accrueInterest(leverageData.block.timestamp);
|
|
147
|
+
* const quote = await fetchZeroExQuote({
|
|
148
|
+
* chainId: base.id,
|
|
149
|
+
* kind: "closeKeepCollateral",
|
|
150
|
+
* marketParams,
|
|
151
|
+
* userAddress,
|
|
152
|
+
* amount: borrowAssets + computeCloseInterestBuffer(leverageData),
|
|
153
|
+
* slippage,
|
|
154
|
+
* deadline: leverageDeadline(leverageData), // the deadline the Close signs
|
|
155
|
+
* apiKey,
|
|
156
|
+
* });
|
|
157
|
+
* const tx = blueClose({
|
|
158
|
+
* market: { chainId: base.id, marketParams },
|
|
159
|
+
* args: {
|
|
160
|
+
* userAddress,
|
|
161
|
+
* leverageData,
|
|
162
|
+
* quote,
|
|
163
|
+
* slippage,
|
|
164
|
+
* },
|
|
165
|
+
* });
|
|
166
|
+
* // tx.action.args.mode is "keepCollateral": the Close swaps collateral to repay the debt.
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
export declare const blueClose: (params: BlueCloseParams) => Readonly<Transaction<BlueCloseAction>>;
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.blueClose = void 0;
|
|
4
|
+
const morpho_ts_1 = require("@morpho-org/morpho-ts");
|
|
5
|
+
const viem_1 = require("viem");
|
|
6
|
+
const abis_js_1 = require("../../abis.js");
|
|
7
|
+
const constant_js_1 = require("../../helpers/constant.js");
|
|
8
|
+
const limits_js_1 = require("../../helpers/leverage/limits.js");
|
|
9
|
+
const positionMarket_js_1 = require("../../helpers/leverage/positionMarket.js");
|
|
10
|
+
const metadata_js_1 = require("../../helpers/metadata.js");
|
|
11
|
+
const validate_js_1 = require("../../helpers/validate.js");
|
|
12
|
+
const zeroExQuote_js_1 = require("../../helpers/zeroExQuote.js");
|
|
13
|
+
const index_js_1 = require("../../types/index.js");
|
|
14
|
+
const leverageIntent_js_1 = require("./leverageIntent.js");
|
|
15
|
+
const swapBounds = ({ params, debt, quote, }) => {
|
|
16
|
+
const { chainId, marketParams } = params.market;
|
|
17
|
+
const { userAddress, leverageData, slippage } = params.args;
|
|
18
|
+
const interestBuffer = (0, limits_js_1.computeCloseInterestBuffer)(leverageData);
|
|
19
|
+
const limits = (0, limits_js_1.computeCloseLimits)({
|
|
20
|
+
quote,
|
|
21
|
+
slippage,
|
|
22
|
+
leverageData,
|
|
23
|
+
});
|
|
24
|
+
if (limits.minLoanOut > debt + interestBuffer) {
|
|
25
|
+
throw new index_js_1.LeverageCloseBuyAboveDebtError({
|
|
26
|
+
buyAmount: limits.minLoanOut,
|
|
27
|
+
debt,
|
|
28
|
+
interestBuffer,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
const swap = (0, zeroExQuote_js_1.validateZeroExQuote)({
|
|
32
|
+
quote,
|
|
33
|
+
kind: "closeKeepCollateral",
|
|
34
|
+
chainId,
|
|
35
|
+
marketParams,
|
|
36
|
+
userAddress,
|
|
37
|
+
txOrigin: params.args.txOrigin,
|
|
38
|
+
maxSwapInput: limits.maxCollateralIn,
|
|
39
|
+
deadline: limits.deadline,
|
|
40
|
+
});
|
|
41
|
+
return {
|
|
42
|
+
mode: "keepCollateral",
|
|
43
|
+
maxCollateralIn: limits.maxCollateralIn,
|
|
44
|
+
minLoanOut: limits.minLoanOut,
|
|
45
|
+
swapData: swap.swapData,
|
|
46
|
+
settler: swap.settler,
|
|
47
|
+
oracleDeviation: { status: "measured", ...limits.oracleDeviation },
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Encodes a ZeroExLeverageBundlesV1 Close: repays the user's whole debt by swapping collateral
|
|
52
|
+
* through 0x and sends what is left to the user. Pure and synchronous: it validates the quote
|
|
53
|
+
* on every build and reads no chain state.
|
|
54
|
+
*
|
|
55
|
+
* - **With debt (`keepCollateral`):** an exact-output quote buys exactly the debt plus the SDK's
|
|
56
|
+
* interest buffer (`computeCloseInterestBuffer`: debt × borrow rate × 1 hour × 4). `minLoanOut` is
|
|
57
|
+
* that buy amount, which must equal exactly the debt accrued to the data block plus the buffer, both
|
|
58
|
+
* from the same leverage data, and `maxCollateralIn`
|
|
59
|
+
* the quote's `maxSellAmount`, never above the position's collateral. Unsold collateral and unused
|
|
60
|
+
* loan token return to the user. The buffer is an estimate at the data block's borrow rate: it
|
|
61
|
+
* makes an interest-driven revert unlikely, not impossible, if the rate jumps before execution.
|
|
62
|
+
* - **No debt:** refused with `LeverageCloseWithoutDebtError`. At bundles `3bf5314` a Close without debt still
|
|
63
|
+
* withdraws the collateral and runs the swap, and AllowanceHolder reverts on empty swap calldata; withdraw the
|
|
64
|
+
* collateral with `market.withdrawCollateral` (`blueWithdrawCollateral`) instead.
|
|
65
|
+
* The check reads the leverage data's block only. If the debt is fully repaid between that block and execution,
|
|
66
|
+
* the bundle still runs the signed swap: it sells at most `maxCollateralIn` for at least `minLoanOut` and sends
|
|
67
|
+
* the loan tokens and the unsold collateral to the user, instead of returning all the collateral unsold
|
|
68
|
+
* (bundles `3bf5314` L165, L186-L188). Rebuild the Close from fresh data after any repayment.
|
|
69
|
+
*
|
|
70
|
+
* Every swap bound comes from the quote and the slippage only. A quote whose Settler slippage struct names a minimum
|
|
71
|
+
* below the signed `minLoanOut` (the quote's `buyAmount`), even by one unit, is refused with
|
|
72
|
+
* `ZeroExQuoteMinAmountOutMismatchError`: fetch a new quote. An all-zero slippage struct is the one
|
|
73
|
+
* exception, accepted because the bundle enforces `minLoanOut` onchain. Close signs no `maxLtv`:
|
|
74
|
+
* the contract has none for it. The deadline is the leverage data timestamp plus one hour.
|
|
75
|
+
*
|
|
76
|
+
* When a Close is refused, exit without a swap through the existing Blue methods: `repay` or
|
|
77
|
+
* `supplyCollateral` reduce risk, and `repayWithdrawCollateral` leaves the position.
|
|
78
|
+
*
|
|
79
|
+
* At most one ZeroExLeverageBundlesV1 call succeeds per transaction: bundles `3bf5314` keeps its transient initiator
|
|
80
|
+
* set until the transaction ends (L36, L49), so a second Lever, Delever or Close to the bundle in the same smart-account
|
|
81
|
+
* batch or ERC-4337 bundle reverts with `Reentrancy`. Send each one in its own transaction.
|
|
82
|
+
*
|
|
83
|
+
* @param params - Close encoding parameters.
|
|
84
|
+
* @param params.market.chainId - Chain of the market.
|
|
85
|
+
* @param params.market.marketParams - Scoped Morpho Blue market parameters.
|
|
86
|
+
* @param params.args.userAddress - Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself; its position is closed.
|
|
87
|
+
* @param params.args.txOrigin - Optional sender of the outer onchain transaction (its `tx.origin`) when it is not
|
|
88
|
+
* `userAddress`, such as a Safe's executing owner or an ERC-4337 bundler. The quote must have been fetched with
|
|
89
|
+
* the same value. Defaults to `userAddress`.
|
|
90
|
+
* @param params.args.leverageData - Unmodified `getLeverageData()` result for the user and market.
|
|
91
|
+
* @param params.args.quote - Exact-output 0x quote of kind `closeKeepCollateral`; required with debt.
|
|
92
|
+
* @param params.args.slippage - Caller slippage, WAD-scaled, at most 10%.
|
|
93
|
+
* @param params.metadata - Optional transaction metadata.
|
|
94
|
+
* @returns A deep-frozen `Readonly<Transaction<BlueCloseAction>>` sent to ZeroExLeverageBundlesV1,
|
|
95
|
+
* whose `action.args` records the signed bounds, the Settler and the leverage data block.
|
|
96
|
+
* @throws {MarketIdMismatchError} when `marketParams` or the position's market tuple does not hash to its
|
|
97
|
+
* cached id, or the leverage data position or its market tuple is for another market.
|
|
98
|
+
* @throws {AccrualPositionUserMismatchError} when the leverage data position belongs to another user.
|
|
99
|
+
* @throws {ChainIdMismatchError} when the leverage data was read on another chain.
|
|
100
|
+
* @throws {LeverageUnsupportedChainError} when the chain has no usable leverage bundle.
|
|
101
|
+
* @throws {LeverageCloseEmptyPositionError} when the position has neither debt nor collateral. There is no
|
|
102
|
+
* fallback transaction for it: tell the user there is nothing to close.
|
|
103
|
+
* @throws {LeverageCloseWithoutDebtError} when the position has collateral but no debt; withdraw the collateral with
|
|
104
|
+
* `market.withdrawCollateral` (`blueWithdrawCollateral`) instead.
|
|
105
|
+
* @throws {ZeroExQuoteRequiredError} when the position has debt and no quote is given.
|
|
106
|
+
* @throws {ZeroExQuoteTypeMismatchError} when the quote is not an exact-output quote.
|
|
107
|
+
* @throws {LeverageQuoteSlippageMismatchError} when the quote was fetched with another slippage than `slippage`.
|
|
108
|
+
* @throws {LeverageCloseInputExceedsCollateralError} when `maxCollateralIn` exceeds the collateral.
|
|
109
|
+
* @throws {LeverageCloseBuyAboveDebtError} when the quote buys more than the debt plus the interest
|
|
110
|
+
* buffer.
|
|
111
|
+
* @throws {LeverageCloseFloorBelowDebtPlusBufferError} when `minLoanOut` is below the debt plus the interest
|
|
112
|
+
* buffer.
|
|
113
|
+
* @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
|
|
114
|
+
* @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero. Exit without a
|
|
115
|
+
* swap instead.
|
|
116
|
+
* @throws {InputExceedsMaxError} when `minLoanOut` or the deadline exceeds `uint256`.
|
|
117
|
+
* @throws {InvalidBigIntInputError} when `slippage`, `quote.slippage` or `leverageData.block.timestamp` is missing or not
|
|
118
|
+
* a bigint, or when the position has debt and `leverageData.borrowRate` is missing or not a bigint.
|
|
119
|
+
* @throws {NegativeInputError} when `slippage` is negative, or when the position has debt and `leverageData.borrowRate` is
|
|
120
|
+
* negative.
|
|
121
|
+
* @throws {NonPositiveInputError} when a quote amount or the deadline is not positive.
|
|
122
|
+
* @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address; pass a valid one or omit it
|
|
123
|
+
* instead of fetching a new quote.
|
|
124
|
+
* @throws {ZeroExQuoteError} for any other quote or calldata mismatch `validateZeroExQuote` refuses.
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* import { createPublicClient, http } from "viem";
|
|
128
|
+
* import { base } from "viem/chains";
|
|
129
|
+
* import {
|
|
130
|
+
* blueClose,
|
|
131
|
+
* computeCloseInterestBuffer,
|
|
132
|
+
* fetchZeroExQuote,
|
|
133
|
+
* leverageDeadline,
|
|
134
|
+
* morphoViemExtension,
|
|
135
|
+
* } from "@morpho-org/morpho-sdk";
|
|
136
|
+
* import { isBlueZeroExLeverageChain } from "@morpho-org/morpho-sdk/addresses";
|
|
137
|
+
*
|
|
138
|
+
* // Close needs a ZeroExLeverageBundlesV1 registered on the chain; without one the leverage data read
|
|
139
|
+
* // throws LeverageUnsupportedChainError.
|
|
140
|
+
* if (!isBlueZeroExLeverageChain(base.id)) throw new Error("No leverage bundle is registered on Base yet.");
|
|
141
|
+
* const client = createPublicClient({ chain: base, transport: http() }).extend(morphoViemExtension());
|
|
142
|
+
* const leverageData = await client.morpho
|
|
143
|
+
* .blue(marketParams, base.id)
|
|
144
|
+
* .getLeverageData({ userAddress });
|
|
145
|
+
* const slippage = 5_000_000_000_000_000n; // 0.5%, WAD-scaled (1e18 = 100%), not bps
|
|
146
|
+
* // A position without debt (no borrow shares) has no Close: withdraw its collateral with blueWithdrawCollateral
|
|
147
|
+
* // instead. Check it before fetching a quote, whose amount would be zero.
|
|
148
|
+
* if (leverageData.position.borrowShares === 0n) {
|
|
149
|
+
* throw new Error("No debt: withdraw the collateral with blueWithdrawCollateral instead of a Close.");
|
|
150
|
+
* }
|
|
151
|
+
* // The debt accrued to the data block, as the builder computes it.
|
|
152
|
+
* const { borrowAssets } = leverageData.position.accrueInterest(leverageData.block.timestamp);
|
|
153
|
+
* const quote = await fetchZeroExQuote({
|
|
154
|
+
* chainId: base.id,
|
|
155
|
+
* kind: "closeKeepCollateral",
|
|
156
|
+
* marketParams,
|
|
157
|
+
* userAddress,
|
|
158
|
+
* amount: borrowAssets + computeCloseInterestBuffer(leverageData),
|
|
159
|
+
* slippage,
|
|
160
|
+
* deadline: leverageDeadline(leverageData), // the deadline the Close signs
|
|
161
|
+
* apiKey,
|
|
162
|
+
* });
|
|
163
|
+
* const tx = blueClose({
|
|
164
|
+
* market: { chainId: base.id, marketParams },
|
|
165
|
+
* args: {
|
|
166
|
+
* userAddress,
|
|
167
|
+
* leverageData,
|
|
168
|
+
* quote,
|
|
169
|
+
* slippage,
|
|
170
|
+
* },
|
|
171
|
+
* });
|
|
172
|
+
* // tx.action.args.mode is "keepCollateral": the Close swaps collateral to repay the debt.
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
const blueClose = (params) => {
|
|
176
|
+
const { chainId, marketParams } = params.market;
|
|
177
|
+
const { userAddress, leverageData, quote, slippage } = params.args;
|
|
178
|
+
(0, validate_js_1.validateMarketParamsId)(marketParams);
|
|
179
|
+
// Refused before any position check, so a malformed txOrigin fails the same way on every position.
|
|
180
|
+
(0, zeroExQuote_js_1.resolveZeroExTxOrigin)(params.args.txOrigin, userAddress);
|
|
181
|
+
if (typeof slippage !== "bigint") {
|
|
182
|
+
throw new index_js_1.InvalidBigIntInputError("slippage", slippage);
|
|
183
|
+
}
|
|
184
|
+
if (leverageData.chainId !== chainId) {
|
|
185
|
+
throw new index_js_1.ChainIdMismatchError(leverageData.chainId, chainId);
|
|
186
|
+
}
|
|
187
|
+
(0, validate_js_1.validateAccrualPosition)({
|
|
188
|
+
positionData: leverageData.position,
|
|
189
|
+
expectedMarketId: marketParams.id,
|
|
190
|
+
expectedUser: userAddress,
|
|
191
|
+
});
|
|
192
|
+
// The bounds come from the position's own market tuple, so it must be the expected market's.
|
|
193
|
+
(0, positionMarket_js_1.validateLeveragePositionMarket)(leverageData.position, marketParams);
|
|
194
|
+
const bundle = (0, zeroExQuote_js_1.getZeroExLeverageBundle)(chainId);
|
|
195
|
+
// Validates the data block timestamp before accrual, so a malformed one throws InvalidBigIntInputError.
|
|
196
|
+
const deadline = (0, limits_js_1.leverageDeadline)(leverageData);
|
|
197
|
+
const position = leverageData.position.accrueInterest(leverageData.block.timestamp);
|
|
198
|
+
if (position.borrowShares === 0n && position.collateral === 0n) {
|
|
199
|
+
throw new index_js_1.LeverageCloseEmptyPositionError({
|
|
200
|
+
marketId: marketParams.id,
|
|
201
|
+
user: userAddress,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
if (slippage < 0n) {
|
|
205
|
+
throw new index_js_1.NegativeInputError("slippage", slippage);
|
|
206
|
+
}
|
|
207
|
+
// Checked before the quote's slippage, so a requote advice never names a slippage the quote fetch refuses.
|
|
208
|
+
if (slippage > constant_js_1.LEVERAGE_MAX_EXECUTION_LOSS.close) {
|
|
209
|
+
throw new index_js_1.LeverageSlippageAboveLimitError({
|
|
210
|
+
operation: "close",
|
|
211
|
+
slippage,
|
|
212
|
+
max: constant_js_1.LEVERAGE_MAX_EXECUTION_LOSS.close,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
if (position.borrowShares === 0n) {
|
|
216
|
+
throw new index_js_1.LeverageCloseWithoutDebtError({
|
|
217
|
+
marketId: marketParams.id,
|
|
218
|
+
user: userAddress,
|
|
219
|
+
collateral: position.collateral,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
if (quote == null) {
|
|
223
|
+
throw new index_js_1.ZeroExQuoteRequiredError({ operation: "close" });
|
|
224
|
+
}
|
|
225
|
+
(0, leverageIntent_js_1.validateLeverageQuoteSlippage)({
|
|
226
|
+
operation: "close",
|
|
227
|
+
slippage,
|
|
228
|
+
quoteSlippage: quote.slippage,
|
|
229
|
+
});
|
|
230
|
+
const bounds = swapBounds({ params, debt: position.borrowAssets, quote });
|
|
231
|
+
let tx = {
|
|
232
|
+
to: bundle,
|
|
233
|
+
value: 0n,
|
|
234
|
+
data: (0, viem_1.encodeFunctionData)({
|
|
235
|
+
abi: abis_js_1.zeroExLeverageBundlesV1Abi,
|
|
236
|
+
functionName: "zeroExLeverageBundlesV1Close",
|
|
237
|
+
args: [
|
|
238
|
+
marketParams,
|
|
239
|
+
bounds.maxCollateralIn,
|
|
240
|
+
bounds.minLoanOut,
|
|
241
|
+
bounds.swapData,
|
|
242
|
+
deadline,
|
|
243
|
+
],
|
|
244
|
+
}),
|
|
245
|
+
};
|
|
246
|
+
if (params.metadata) {
|
|
247
|
+
tx = (0, metadata_js_1.addTransactionMetadata)(tx, params.metadata);
|
|
248
|
+
}
|
|
249
|
+
return (0, morpho_ts_1.deepFreeze)({
|
|
250
|
+
...tx,
|
|
251
|
+
action: {
|
|
252
|
+
type: "blueClose",
|
|
253
|
+
args: {
|
|
254
|
+
market: marketParams.id,
|
|
255
|
+
onBehalf: userAddress,
|
|
256
|
+
mode: bounds.mode,
|
|
257
|
+
maxCollateralIn: bounds.maxCollateralIn,
|
|
258
|
+
minLoanOut: bounds.minLoanOut,
|
|
259
|
+
settler: bounds.settler,
|
|
260
|
+
oracleDeviation: bounds.oracleDeviation,
|
|
261
|
+
deadline,
|
|
262
|
+
block: {
|
|
263
|
+
number: leverageData.block.number,
|
|
264
|
+
timestamp: leverageData.block.timestamp,
|
|
265
|
+
},
|
|
266
|
+
},
|
|
267
|
+
},
|
|
268
|
+
});
|
|
269
|
+
};
|
|
270
|
+
exports.blueClose = blueClose;
|
|
@@ -5,6 +5,7 @@ const blue_sdk_1 = require("@morpho-org/blue-sdk");
|
|
|
5
5
|
const morpho_ts_1 = require("@morpho-org/morpho-ts");
|
|
6
6
|
const viem_1 = require("viem");
|
|
7
7
|
const index_js_1 = require("../../helpers/index.js");
|
|
8
|
+
const reallocations_js_1 = require("../../helpers/leverage/reallocations.js");
|
|
8
9
|
const parse_js_1 = require("../../helpers/parse.js");
|
|
9
10
|
const validate_js_1 = require("../../helpers/validate.js");
|
|
10
11
|
const index_js_2 = require("../../types/index.js");
|
|
@@ -149,8 +150,7 @@ const parseBlueAllocations = (reallocations, { marketParams: targetMarketParams,
|
|
|
149
150
|
};
|
|
150
151
|
exports.parseBlueAllocations = parseBlueAllocations;
|
|
151
152
|
/** @internal */
|
|
152
|
-
const getBlueBundlesV1PenaltyAssets = (reallocations) =>
|
|
153
|
-
blue_sdk_1.VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets), 0n);
|
|
153
|
+
const getBlueBundlesV1PenaltyAssets = (reallocations) => (0, reallocations_js_1.computeLeveragePenaltyAssets)(reallocations);
|
|
154
154
|
exports.getBlueBundlesV1PenaltyAssets = getBlueBundlesV1PenaltyAssets;
|
|
155
155
|
/** @internal */
|
|
156
156
|
const getBlueBundlesV1ReferralFeeAssets = (assets, referralFeePct) => referralFeePct === 0n
|
|
@@ -0,0 +1,156 @@
|
|
|
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 BlueDeleverAction, type Metadata, type Transaction } from "../../types/index.js";
|
|
5
|
+
import type { ZeroExQuote } from "../../types/zeroEx.js";
|
|
6
|
+
/** Parameters for {@link blueDelever}. */
|
|
7
|
+
export interface BlueDeleverParams {
|
|
8
|
+
/** Market the caller expects the Delever to run on; the leverage data must match it. */
|
|
9
|
+
readonly market: {
|
|
10
|
+
readonly chainId: number;
|
|
11
|
+
readonly marketParams: MarketParams;
|
|
12
|
+
};
|
|
13
|
+
/** Delever inputs. */
|
|
14
|
+
readonly args: {
|
|
15
|
+
/**
|
|
16
|
+
* One-block leverage data of the user's position, as returned unmodified by
|
|
17
|
+
* `client.morpho.blue(marketParams, chainId).getLeverageData({ userAddress })`.
|
|
18
|
+
*/
|
|
19
|
+
readonly leverageData: LeverageLimitsData & {
|
|
20
|
+
readonly chainId: number;
|
|
21
|
+
readonly block: {
|
|
22
|
+
readonly number: bigint;
|
|
23
|
+
readonly timestamp: bigint;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
/** Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself; the bundle acts on this account's position. */
|
|
27
|
+
readonly userAddress: Address;
|
|
28
|
+
/**
|
|
29
|
+
* Sender of the outer onchain transaction (its `tx.origin`) when it is not `userAddress`: the owner EOA that
|
|
30
|
+
* executes a Safe transaction, or the bundler that submits an ERC-4337 UserOperation, not the wallet's signer. The
|
|
31
|
+
* quote must have been fetched with the same `txOrigin`. Defaults to `userAddress`.
|
|
32
|
+
*/
|
|
33
|
+
readonly txOrigin?: Address;
|
|
34
|
+
/** Exact-input 0x quote selling the collateral to sell, from `fetchZeroExQuote` with kind `delever`. */
|
|
35
|
+
readonly quote: ZeroExQuote;
|
|
36
|
+
/** Slippage passed to 0x, WAD-scaled, at most `LEVERAGE_MAX_EXECUTION_LOSS.delever` (10%). */
|
|
37
|
+
readonly slippage: bigint;
|
|
38
|
+
};
|
|
39
|
+
/** Optional transaction metadata suffix. */
|
|
40
|
+
readonly metadata?: Metadata;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Encodes a ZeroExLeverageBundlesV1 Delever ("pay back with collateral"): the bundle repays
|
|
44
|
+
* `minRepayAssets` of the user's debt, withdraws `maxCollateralToSell`, sells at most that through 0x, supplies
|
|
45
|
+
* any unsold collateral back, repays the remaining debt with any swap output above `minRepayAssets` and sends
|
|
46
|
+
* what is left above the debt to the user's wallet, then checks `maxLtv` (ZeroExLeverageBundlesV1.sol:137-156, :310-325 at bundles 3bf5314).
|
|
47
|
+
*
|
|
48
|
+
* Pure and synchronous. Every bound comes from `computeDeleverLimits` and the quote is validated
|
|
49
|
+
* again with `validateZeroExQuote`, so a guard that fails refuses instead of building:
|
|
50
|
+
*
|
|
51
|
+
* - `maxCollateralToSell` is the quote's `sellAmount` and `minRepayAssets` its `minBuyAmount` as is, refused unless
|
|
52
|
+
* positive and at least `buyAmount × (1 − slippage)`, with the slippage rounded down to whole parts per
|
|
53
|
+
* million as 0x rounds it, then the amount rounded down.
|
|
54
|
+
* A repay above the debt refuses with `RepayExceedsDebtError`: offer the no-swap `repayWithdrawCollateral`
|
|
55
|
+
* exit instead.
|
|
56
|
+
* - `maxLtv` is the position's LTV with its debt accrued to the deadline, at the data block's price,
|
|
57
|
+
* never `type(uint256).max` and never the LLTV buffer, so a position already past LLTV − 0.5% can still
|
|
58
|
+
* delever. The build refuses when the worst fill (all collateral withdrawn, only `minRepayAssets`
|
|
59
|
+
* repaid, debt accrued to the deadline) would exceed that cap or fail Blue's health check.
|
|
60
|
+
* - The deadline is the leverage data timestamp plus one hour. No reallocation is involved.
|
|
61
|
+
*
|
|
62
|
+
* The SDK does not refuse on the quoted price: `action.args.oracleDeviation` reports the worst fill's deviation from the
|
|
63
|
+
* oracle; show it and `maxCollateralToSell` before the user signs.
|
|
64
|
+
*
|
|
65
|
+
* Delever pulls no token from the user; it needs the Morpho authorization of the bundle, which
|
|
66
|
+
* `getLeverageRequirements` returns.
|
|
67
|
+
*
|
|
68
|
+
* At most one ZeroExLeverageBundlesV1 call succeeds per transaction: bundles `3bf5314` keeps its transient initiator
|
|
69
|
+
* set until the transaction ends (L36, L49), so a second Lever, Delever or Close to the bundle in the same smart-account
|
|
70
|
+
* batch or ERC-4337 bundle reverts with `Reentrancy`. Send each one in its own transaction.
|
|
71
|
+
*
|
|
72
|
+
* @param params - Delever parameters.
|
|
73
|
+
* @param params.market - Chain and market the caller expects; the leverage data must match both.
|
|
74
|
+
* @param params.args.leverageData - One-block leverage data of the user's position.
|
|
75
|
+
* @param params.args.userAddress - Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself.
|
|
76
|
+
* @param params.args.txOrigin - Optional sender of the outer onchain transaction (its `tx.origin`) when it is not
|
|
77
|
+
* `userAddress`, such as a Safe's executing owner or an ERC-4337 bundler. The quote must have been fetched with
|
|
78
|
+
* the same value. Defaults to `userAddress`.
|
|
79
|
+
* @param params.args.quote - Exact-input 0x quote for the collateral to sell.
|
|
80
|
+
* @param params.args.slippage - Caller slippage, WAD-scaled, at most 10%.
|
|
81
|
+
* @param params.metadata - Optional transaction metadata.
|
|
82
|
+
* @returns A deep-frozen `Readonly<Transaction<BlueDeleverAction>>` to the leverage bundle with zero value, whose
|
|
83
|
+
* `action.args` carries the signed bounds, the swap's Settler and the data block.
|
|
84
|
+
* @throws {MarketIdMismatchError} when `market.marketParams` or the position's market tuple does not hash to
|
|
85
|
+
* its cached id, the position's `marketId` names another market than that tuple, or the leverage data position is
|
|
86
|
+
* for another market than `market.marketParams`.
|
|
87
|
+
* @throws {ChainIdMismatchError} when the leverage data was read on another chain than `market.chainId`.
|
|
88
|
+
* @throws {AccrualPositionUserMismatchError} when the leverage data position belongs to another user.
|
|
89
|
+
* @throws {ZeroExQuoteTypeMismatchError} when the quote is not exact input.
|
|
90
|
+
* @throws {ZeroExQuoteRequiredError} when no quote is given.
|
|
91
|
+
* @throws {LeverageQuoteSlippageMismatchError} when the quote was fetched with another slippage than `slippage`.
|
|
92
|
+
* @throws {ZeroExQuoteMinBuyAmountBelowSlippageError} when the quote's `minBuyAmount` is zero or below
|
|
93
|
+
* `buyAmount × (1 − slippage)`, with the slippage rounded down to whole parts per million, then the amount
|
|
94
|
+
* rounded down.
|
|
95
|
+
* @throws {RepayExceedsDebtError} when `minRepayAssets` exceeds the debt; offer the no-swap
|
|
96
|
+
* `repayWithdrawCollateral` exit instead.
|
|
97
|
+
* @throws {RepaySharesExceedDebtError} when `minRepayAssets` would burn more shares than the position holds.
|
|
98
|
+
* @throws {WithdrawExceedsCollateralError} when `maxCollateralToSell` exceeds the position's collateral.
|
|
99
|
+
* @throws {LeverageWorstFillLtvError} when the worst fill fails Blue's health check (`check: "health"`) or
|
|
100
|
+
* would raise the LTV (`check: "maxLtv"`).
|
|
101
|
+
* @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
|
|
102
|
+
* @throws {InvalidBigIntInputError} when `slippage` or `quote.slippage` is missing or not a bigint.
|
|
103
|
+
* @throws {NegativeInputError} when `slippage` is negative.
|
|
104
|
+
* @throws {NonPositiveInputError} when `sellAmount`, `buyAmount` or the deadline is not positive.
|
|
105
|
+
* @throws {InputExceedsMaxError} when the deadline exceeds `uint256`.
|
|
106
|
+
* @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero.
|
|
107
|
+
* @throws {UnsupportedMarketIrmError} when accruing the position's debt needs an unsupported IRM.
|
|
108
|
+
* @throws {LeverageUnsupportedChainError} when the chain has no AllowanceHolder or no registered bundle.
|
|
109
|
+
* @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address; pass a valid one or omit it
|
|
110
|
+
* instead of fetching a new quote.
|
|
111
|
+
* @throws {ZeroExQuoteError} when the quote's chain, tokens, taker, txOrigin, value, target, Settler, amount,
|
|
112
|
+
* recipient or calldata does not match the Delever (see `validateZeroExQuote`).
|
|
113
|
+
* @example
|
|
114
|
+
* ```ts
|
|
115
|
+
* import { markets } from "@morpho-org/morpho-test";
|
|
116
|
+
* import { type Address, createPublicClient, http } from "viem";
|
|
117
|
+
* import { base } from "viem/chains";
|
|
118
|
+
* import {
|
|
119
|
+
* blueDelever,
|
|
120
|
+
* fetchZeroExQuote,
|
|
121
|
+
* leverageDeadline,
|
|
122
|
+
* morphoViemExtension,
|
|
123
|
+
* } from "@morpho-org/morpho-sdk";
|
|
124
|
+
* import { isBlueZeroExLeverageChain } from "@morpho-org/morpho-sdk/addresses";
|
|
125
|
+
*
|
|
126
|
+
* // Delever needs a ZeroExLeverageBundlesV1 registered on the chain; without one the leverage data read
|
|
127
|
+
* // throws LeverageUnsupportedChainError.
|
|
128
|
+
* if (!isBlueZeroExLeverageChain(8453)) throw new Error("No leverage bundle is registered on Base yet.");
|
|
129
|
+
* declare const userAddress: Address; // owner of the position to delever
|
|
130
|
+
* const marketParams = markets[base.id].usdc_eth;
|
|
131
|
+
* const client = createPublicClient({ chain: base, transport: http() });
|
|
132
|
+
* const market = client.extend(morphoViemExtension()).morpho.blue(marketParams, 8453);
|
|
133
|
+
* const leverageData = await market.getLeverageData({ userAddress });
|
|
134
|
+
* const quote = await fetchZeroExQuote({
|
|
135
|
+
* chainId: 8453,
|
|
136
|
+
* kind: "delever",
|
|
137
|
+
* marketParams,
|
|
138
|
+
* userAddress,
|
|
139
|
+
* amount: 10n ** 17n,
|
|
140
|
+
* slippage: 5_000_000_000_000_000n, // 0.5%, WAD-scaled (1e18 = 100%), not bps
|
|
141
|
+
* deadline: leverageDeadline(leverageData), // the deadline the Delever signs
|
|
142
|
+
* apiKey: process.env.ZEROEX_API_KEY!,
|
|
143
|
+
* });
|
|
144
|
+
* const tx = blueDelever({
|
|
145
|
+
* market: { chainId: 8453, marketParams },
|
|
146
|
+
* args: {
|
|
147
|
+
* leverageData,
|
|
148
|
+
* userAddress,
|
|
149
|
+
* quote,
|
|
150
|
+
* slippage: 5_000_000_000_000_000n,
|
|
151
|
+
* },
|
|
152
|
+
* });
|
|
153
|
+
* // tx satisfies Readonly<Transaction<BlueDeleverAction>>
|
|
154
|
+
* ```
|
|
155
|
+
*/
|
|
156
|
+
export declare const blueDelever: (params: BlueDeleverParams) => Readonly<Transaction<BlueDeleverAction>>;
|