@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,715 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.computeCloseInterestBuffer = exports.computeCloseLimits = exports.computeDeleverLimits = exports.computeLeverLimits = exports.computeLeverageOracleDeviation = exports.validateLeverageInputs = exports.leverageDeadline = void 0;
|
|
4
|
+
const blue_sdk_1 = require("@morpho-org/blue-sdk");
|
|
5
|
+
const index_js_1 = require("../../types/index.js");
|
|
6
|
+
const constant_js_1 = require("../constant.js");
|
|
7
|
+
const validate_js_1 = require("../validate.js");
|
|
8
|
+
const zeroExQuote_js_1 = require("../zeroExQuote.js");
|
|
9
|
+
const quoteSellCap = (quote) => quote.mode === "exactOutput" ? quote.maxSellAmount : quote.sellAmount;
|
|
10
|
+
// A JavaScript caller can pass any type; refuse a non-bigint before any bigint arithmetic.
|
|
11
|
+
function assertBigInt(field, value) {
|
|
12
|
+
if (typeof value !== "bigint") {
|
|
13
|
+
throw new index_js_1.InvalidBigIntInputError(field, value);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const valueDown = (collateral, price) => blue_sdk_1.MathLib.mulDivDown(collateral, price, blue_sdk_1.ORACLE_PRICE_SCALE);
|
|
17
|
+
const ltvOf = (borrowed, collateralValue) => collateralValue === 0n
|
|
18
|
+
? blue_sdk_1.MathLib.MAX_UINT_256
|
|
19
|
+
: blue_sdk_1.MathLib.wDivUp(borrowed, collateralValue);
|
|
20
|
+
/**
|
|
21
|
+
* Returns the deadline of a leverage action: the data block's timestamp plus
|
|
22
|
+
* `LEVERAGE_DEADLINE_WINDOW` (1 hour). The caller cannot set it. It is the `deadline` to pass to
|
|
23
|
+
* `fetchZeroExQuote` and `validateZeroExQuote`, so the quote's Settler permit carries the deadline the action signs.
|
|
24
|
+
*
|
|
25
|
+
* @param leverageData - One-block leverage data.
|
|
26
|
+
* @returns Deadline in Unix seconds.
|
|
27
|
+
* @throws {InvalidBigIntInputError} when the data block timestamp is not a bigint.
|
|
28
|
+
* @throws {NonPositiveInputError} when the deadline is zero or negative.
|
|
29
|
+
* @throws {InputExceedsMaxError} when the deadline exceeds `uint256`.
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* import { leverageDeadline } from "@morpho-org/morpho-sdk";
|
|
33
|
+
*
|
|
34
|
+
* // `leverageData`: the funded WETH/USDC position of the `LeverageLimitsData` example.
|
|
35
|
+
* const deadline = leverageDeadline(leverageData);
|
|
36
|
+
* // leverageData.block.timestamp === 1_700_000_000n
|
|
37
|
+
* // deadline === 1_700_003_600n
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
const leverageDeadline = (leverageData) => {
|
|
41
|
+
// A hand-built leverage data can carry a string timestamp, which `+` would concatenate.
|
|
42
|
+
assertBigInt("leverageData.block.timestamp", leverageData.block.timestamp);
|
|
43
|
+
const deadline = leverageData.block.timestamp + constant_js_1.LEVERAGE_DEADLINE_WINDOW;
|
|
44
|
+
(0, validate_js_1.validateDeadline)(deadline);
|
|
45
|
+
return deadline;
|
|
46
|
+
};
|
|
47
|
+
exports.leverageDeadline = leverageDeadline;
|
|
48
|
+
/**
|
|
49
|
+
* Validates the caller inputs shared by every leverage action and returns the position accrued to
|
|
50
|
+
* the data block. Slippage must be between zero and the action's
|
|
51
|
+
* `LEVERAGE_MAX_EXECUTION_LOSS`, and the quote must fix the side the action requires with positive
|
|
52
|
+
* amounts.
|
|
53
|
+
*
|
|
54
|
+
* @param params - Shared leverage inputs.
|
|
55
|
+
* @param params.operation - Leverage action.
|
|
56
|
+
* @param params.quote - Quote amounts.
|
|
57
|
+
* @param params.slippage - Caller slippage, WAD-scaled.
|
|
58
|
+
* @param params.leverageData - One-block leverage data.
|
|
59
|
+
* @returns The leverage data position accrued to the data block's timestamp.
|
|
60
|
+
* @throws {InvalidBigIntInputError} when `slippage`, `quote.buyAmount`, the quote's sell amount
|
|
61
|
+
* (`sellAmount`, or `maxSellAmount` for exact output), an exact-input quote's `minBuyAmount` or the data
|
|
62
|
+
* block timestamp is missing or not a bigint.
|
|
63
|
+
* @throws {InvalidLeverageOperationError} when `operation` is missing or not `lever`, `delever` or `close`.
|
|
64
|
+
* @throws {NegativeInputError} when `slippage` is negative.
|
|
65
|
+
* @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds the action's limit.
|
|
66
|
+
* @throws {NonPositiveInputError} when the quote's sell amount or `buyAmount` is not positive.
|
|
67
|
+
* @throws {ZeroExQuoteMinBuyAmountBelowSlippageError} when an exact-input quote's `minBuyAmount` is zero or below
|
|
68
|
+
* `buyAmount × (1 − slippage)`, the slippage rounded down to whole parts per million.
|
|
69
|
+
* @throws {ZeroExQuoteRequiredError} when the quote is missing.
|
|
70
|
+
* @throws {ZeroExQuoteTypeMismatchError} when the quote fixes the wrong side.
|
|
71
|
+
* @throws {UnsupportedMarketIrmError} when accruing the position's debt needs an unsupported IRM.
|
|
72
|
+
* @throws {BlueErrors.TotalOverflow} when accruing the market's interest overflows.
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* import { validateLeverageInputs } from "@morpho-org/morpho-sdk";
|
|
76
|
+
*
|
|
77
|
+
* // `leverageData`: the funded WETH/USDC position of the `LeverageLimitsData` example.
|
|
78
|
+
* const accrued = validateLeverageInputs({
|
|
79
|
+
* operation: "delever",
|
|
80
|
+
* quote: {
|
|
81
|
+
* mode: "exactInput",
|
|
82
|
+
* sellAmount: 10n ** 19n,
|
|
83
|
+
* buyAmount: 29_970_000_000n,
|
|
84
|
+
* minBuyAmount: 29_820_150_000n,
|
|
85
|
+
* },
|
|
86
|
+
* slippage: 5_000_000_000_000_000n,
|
|
87
|
+
* leverageData,
|
|
88
|
+
* });
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
const validateLeverageInputs = (params) => {
|
|
92
|
+
const { operation, quote, slippage, leverageData } = params;
|
|
93
|
+
// A JavaScript caller can pass numbers or omit fields; refuse them before any bigint arithmetic.
|
|
94
|
+
assertBigInt("slippage", slippage);
|
|
95
|
+
assertBigInt("leverageData.block.timestamp", leverageData.block.timestamp);
|
|
96
|
+
if (typeof operation !== "string" ||
|
|
97
|
+
!Object.hasOwn(constant_js_1.LEVERAGE_MAX_EXECUTION_LOSS, operation)) {
|
|
98
|
+
throw new index_js_1.InvalidLeverageOperationError("operation", operation);
|
|
99
|
+
}
|
|
100
|
+
if (quote == null) {
|
|
101
|
+
throw new index_js_1.ZeroExQuoteRequiredError({ operation });
|
|
102
|
+
}
|
|
103
|
+
if (slippage < 0n) {
|
|
104
|
+
throw new index_js_1.NegativeInputError("slippage", slippage);
|
|
105
|
+
}
|
|
106
|
+
const max = constant_js_1.LEVERAGE_MAX_EXECUTION_LOSS[operation];
|
|
107
|
+
if (slippage > max) {
|
|
108
|
+
throw new index_js_1.LeverageSlippageAboveLimitError({ operation, slippage, max });
|
|
109
|
+
}
|
|
110
|
+
const expectedQuoteType = operation === "delever" ? "exactInput" : "exactOutput";
|
|
111
|
+
if (quote.mode !== expectedQuoteType) {
|
|
112
|
+
throw new index_js_1.ZeroExQuoteTypeMismatchError({
|
|
113
|
+
expected: expectedQuoteType,
|
|
114
|
+
actual: quote.mode,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
const sellCapField = quote.mode === "exactOutput" ? "quote.maxSellAmount" : "quote.sellAmount";
|
|
118
|
+
const sellCap = quoteSellCap(quote);
|
|
119
|
+
assertBigInt(sellCapField, sellCap);
|
|
120
|
+
assertBigInt("quote.buyAmount", quote.buyAmount);
|
|
121
|
+
if (sellCap <= 0n) {
|
|
122
|
+
throw new index_js_1.NonPositiveInputError(sellCapField, sellCap);
|
|
123
|
+
}
|
|
124
|
+
if (quote.buyAmount <= 0n) {
|
|
125
|
+
throw new index_js_1.NonPositiveInputError("quote.buyAmount", quote.buyAmount);
|
|
126
|
+
}
|
|
127
|
+
if (quote.mode === "exactInput") {
|
|
128
|
+
assertBigInt("quote.minBuyAmount", quote.minBuyAmount);
|
|
129
|
+
// 0x rounds its floor down from the whole-ppm slippage it was sent, so the same bound accepts its quotes.
|
|
130
|
+
const slippageFloor = blue_sdk_1.MathLib.mulDivDown(quote.buyAmount, zeroExQuote_js_1.ZERO_EX_SLIPPAGE_PPM - (0, zeroExQuote_js_1.toZeroExSlippagePpm)(slippage), zeroExQuote_js_1.ZERO_EX_SLIPPAGE_PPM);
|
|
131
|
+
if (quote.minBuyAmount <= 0n || quote.minBuyAmount < slippageFloor) {
|
|
132
|
+
throw new index_js_1.ZeroExQuoteMinBuyAmountBelowSlippageError({
|
|
133
|
+
buyAmount: quote.buyAmount,
|
|
134
|
+
minBuyAmount: quote.minBuyAmount,
|
|
135
|
+
slippage,
|
|
136
|
+
slippageFloor,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return leverageData.position.accrueInterest(leverageData.block.timestamp);
|
|
141
|
+
};
|
|
142
|
+
exports.validateLeverageInputs = validateLeverageInputs;
|
|
143
|
+
const marketPrice = (position, operation) => {
|
|
144
|
+
const { price } = position.market;
|
|
145
|
+
// A hand-built position can carry a string price, which `<= 0n` lets through and bigint arithmetic rejects.
|
|
146
|
+
if (price != null && typeof price !== "bigint") {
|
|
147
|
+
throw new index_js_1.InvalidBigIntInputError("leverageData.position.market.price", price);
|
|
148
|
+
}
|
|
149
|
+
if (price == null || price <= 0n) {
|
|
150
|
+
throw new index_js_1.LeverageOraclePriceUnavailableError({
|
|
151
|
+
operation,
|
|
152
|
+
marketId: position.marketId,
|
|
153
|
+
price: price ?? undefined,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
return price;
|
|
157
|
+
};
|
|
158
|
+
/**
|
|
159
|
+
* Computes how far a leverage action's worst signed execution price is from the market's oracle price, relative to
|
|
160
|
+
* the oracle value of the collateral traded, WAD-scaled and signed so that a positive value costs the user.
|
|
161
|
+
*
|
|
162
|
+
* - Lever buys `minCollateralToBuy` for at most `maxSwapIn`: `(maxSwapIn × SCALE − minCollateralToBuy × price) /
|
|
163
|
+
* (minCollateralToBuy × price)`, positive when it pays more than the oracle value.
|
|
164
|
+
* - Delever sells `maxCollateralToSell` for at least `minRepayAssets`, and Close sells at most `maxCollateralIn` for at
|
|
165
|
+
* least `minLoanOut`: `(collateral × price − loan × SCALE) / (collateral × price)`, positive when the worst fill
|
|
166
|
+
* returns less than the oracle value.
|
|
167
|
+
*
|
|
168
|
+
* `SCALE` is `ORACLE_PRICE_SCALE` (1e36): a Morpho oracle price is loan-token units per collateral-token unit, so
|
|
169
|
+
* token decimals need no adjustment. The result is rounded up (towards the unfavourable side), so for any whole WAD
|
|
170
|
+
* bound `max`, `deviation > max` exactly when the unrounded deviation exceeds it. Pure: reads nothing on chain.
|
|
171
|
+
* Lever refuses a deviation above `LEVERAGE_MAX_ORACLE_DEVIATION` (15%); Delever and Close return it in their
|
|
172
|
+
* limits and never refuse on it, so an app can warn or ask for confirmation at its own thresholds.
|
|
173
|
+
*
|
|
174
|
+
* @param params - The action, its signed swap bounds and the oracle price.
|
|
175
|
+
* @param params.operation - `"lever"`, `"delever"` or `"close"`.
|
|
176
|
+
* @param params.limits - Signed swap bounds, such as the action's limits or its `action.args`.
|
|
177
|
+
* @param params.oraclePrice - Market oracle price, scaled by `ORACLE_PRICE_SCALE`.
|
|
178
|
+
* @returns The worst price (rounded down), the oracle price and the deviation, WAD-scaled and rounded up:
|
|
179
|
+
* `150_000_000_000_000_000n` is 15% worse than the oracle, a negative value better.
|
|
180
|
+
* @throws {InvalidBigIntInputError} when `oraclePrice` or a bound is missing or not a bigint.
|
|
181
|
+
* @throws {NonPositiveInputError} when `oraclePrice` or the collateral bound is not positive.
|
|
182
|
+
* @throws {NegativeInputError} when the loan-token bound is negative.
|
|
183
|
+
* @throws {InvalidLeverageOperationError} when `operation` is not `lever`, `delever` or `close`.
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* import { computeLeverageOracleDeviation } from "@morpho-org/morpho-sdk";
|
|
187
|
+
*
|
|
188
|
+
* // Selling 10 WETH (18 decimals) for at least 27,000 USDC (6 decimals) with the oracle at 3,000 USDC per WETH.
|
|
189
|
+
* const { deviation } = computeLeverageOracleDeviation({
|
|
190
|
+
* operation: "delever",
|
|
191
|
+
* limits: { maxCollateralToSell: 10n * 10n ** 18n, minRepayAssets: 27_000n * 10n ** 6n },
|
|
192
|
+
* oraclePrice: 3_000n * 10n ** 24n,
|
|
193
|
+
* });
|
|
194
|
+
* // deviation === 100_000_000_000_000_000n: the worst fill is 10% below the oracle value
|
|
195
|
+
* ```
|
|
196
|
+
*/
|
|
197
|
+
const computeLeverageOracleDeviation = (params) => {
|
|
198
|
+
const { oraclePrice } = params;
|
|
199
|
+
// A JavaScript caller can pass any tag; refuse it with a typed error.
|
|
200
|
+
const operation = params.operation;
|
|
201
|
+
const [collateralField, loanField, buysCollateral] = (() => {
|
|
202
|
+
switch (operation) {
|
|
203
|
+
case "lever":
|
|
204
|
+
return ["minCollateralToBuy", "maxSwapIn", true];
|
|
205
|
+
case "delever":
|
|
206
|
+
return ["maxCollateralToSell", "minRepayAssets", false];
|
|
207
|
+
case "close":
|
|
208
|
+
return ["maxCollateralIn", "minLoanOut", false];
|
|
209
|
+
default:
|
|
210
|
+
throw new index_js_1.InvalidLeverageOperationError("operation", operation);
|
|
211
|
+
}
|
|
212
|
+
})();
|
|
213
|
+
const limits = (params.limits ?? {});
|
|
214
|
+
const collateral = limits[collateralField];
|
|
215
|
+
const loan = limits[loanField];
|
|
216
|
+
assertBigInt("oraclePrice", oraclePrice);
|
|
217
|
+
assertBigInt(`limits.${collateralField}`, collateral);
|
|
218
|
+
assertBigInt(`limits.${loanField}`, loan);
|
|
219
|
+
if (oraclePrice <= 0n) {
|
|
220
|
+
throw new index_js_1.NonPositiveInputError("oraclePrice", oraclePrice);
|
|
221
|
+
}
|
|
222
|
+
if (collateral <= 0n) {
|
|
223
|
+
throw new index_js_1.NonPositiveInputError(`limits.${collateralField}`, collateral);
|
|
224
|
+
}
|
|
225
|
+
if (loan < 0n) {
|
|
226
|
+
throw new index_js_1.NegativeInputError(`limits.${loanField}`, loan);
|
|
227
|
+
}
|
|
228
|
+
const oracleValue = collateral * oraclePrice;
|
|
229
|
+
const quoteValue = loan * blue_sdk_1.ORACLE_PRICE_SCALE;
|
|
230
|
+
const excess = buysCollateral
|
|
231
|
+
? quoteValue - oracleValue
|
|
232
|
+
: oracleValue - quoteValue;
|
|
233
|
+
return {
|
|
234
|
+
worstPrice: blue_sdk_1.MathLib.mulDivDown(loan, blue_sdk_1.ORACLE_PRICE_SCALE, collateral),
|
|
235
|
+
oraclePrice,
|
|
236
|
+
deviation: excess >= 0n
|
|
237
|
+
? blue_sdk_1.MathLib.mulDivUp(excess, blue_sdk_1.MathLib.WAD, oracleValue)
|
|
238
|
+
: -blue_sdk_1.MathLib.mulDivDown(-excess, blue_sdk_1.MathLib.WAD, oracleValue),
|
|
239
|
+
};
|
|
240
|
+
};
|
|
241
|
+
exports.computeLeverageOracleDeviation = computeLeverageOracleDeviation;
|
|
242
|
+
// Only a price above the oracle costs the user; a price below it is never refused. Rounded up, so exactly 15% passes.
|
|
243
|
+
const validateLeverOraclePrice = (params) => {
|
|
244
|
+
const result = (0, exports.computeLeverageOracleDeviation)({
|
|
245
|
+
operation: "lever",
|
|
246
|
+
limits: params,
|
|
247
|
+
oraclePrice: params.price,
|
|
248
|
+
});
|
|
249
|
+
if (result.deviation <= constant_js_1.LEVERAGE_MAX_ORACLE_DEVIATION) {
|
|
250
|
+
return result;
|
|
251
|
+
}
|
|
252
|
+
throw new index_js_1.LeverageOraclePriceDeviationError({
|
|
253
|
+
quotePrice: result.worstPrice,
|
|
254
|
+
oraclePrice: result.oraclePrice,
|
|
255
|
+
deviation: result.deviation,
|
|
256
|
+
max: constant_js_1.LEVERAGE_MAX_ORACLE_DEVIATION,
|
|
257
|
+
});
|
|
258
|
+
};
|
|
259
|
+
const validateWorstFillLtv = (params) => {
|
|
260
|
+
const collateralValue = valueDown(params.collateral, params.price);
|
|
261
|
+
if (params.borrowed <= blue_sdk_1.MathLib.wMulDown(collateralValue, params.maxLtv)) {
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
throw new index_js_1.LeverageWorstFillLtvError({
|
|
265
|
+
operation: params.operation,
|
|
266
|
+
check: params.check,
|
|
267
|
+
ltv: ltvOf(params.borrowed, collateralValue),
|
|
268
|
+
maxLtv: params.maxLtv,
|
|
269
|
+
});
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* Computes the signed limits of a Lever from an exact-output 0x quote.
|
|
273
|
+
*
|
|
274
|
+
* - `minCollateralToBuy` is the quote's `buyAmount`; the swap input cap `maxSwapIn` is the quote's
|
|
275
|
+
* `maxSellAmount`, which already carries the caller's slippage: the bundle approves exactly
|
|
276
|
+
* `maxSwapIn` and the Settler pulls the whole `maxSellAmount` before refunding, so a smaller cap
|
|
277
|
+
* would revert. No oracle enters a bound.
|
|
278
|
+
* - The worst swap price, `maxSwapIn` per `minCollateralToBuy` scaled by `ORACLE_PRICE_SCALE`, must be at most
|
|
279
|
+
* `LEVERAGE_MAX_ORACLE_DEVIATION` (15%) above the market's oracle price at the data block; exactly 15% is
|
|
280
|
+
* accepted, and a price below the oracle, which favours the user, is never refused. The comparison is exact (cross-multiplied, no rounding). It refuses the Lever and changes no
|
|
281
|
+
* signed bound. The price and the debt are the data block's; until the deadline only the signed `maxLtv` and
|
|
282
|
+
* Blue's health check guard execution. The deviation compares `maxSwapIn` alone: reallocation penalties
|
|
283
|
+
* (`penaltyAssets`, at most 1% each) are paid on top.
|
|
284
|
+
* - `maxBorrowAssets = maxSwapIn + penaltyAssets − loanAssets`, so the contract's swap cap
|
|
285
|
+
* `loanAssets + maxBorrowAssets − penaltyAssets` equals the quote cap.
|
|
286
|
+
* - `maxLtv` is the LLTV minus `DEFAULT_LLTV_BUFFER`, never `type(uint256).max`. The worst fill is
|
|
287
|
+
* the full `maxBorrowAssets` borrowed with exactly `minCollateralToBuy` received, which is also the
|
|
288
|
+
* state Blue's health check sees mid-flow, before any surplus repays debt. It is checked with the
|
|
289
|
+
* contract's rounding (debt rounded up against collateral value, the bound rounded down), first
|
|
290
|
+
* against the LLTV (Blue's health check, `check: "health"`, also when `maxLtv` fails too, because
|
|
291
|
+
* the contract hits that check first), then against `maxLtv` (`check: "maxLtv"`). The debt is the position's
|
|
292
|
+
* debt at the data block; interest accrued before execution is not checked. `DEFAULT_LLTV_BUFFER` leaves room
|
|
293
|
+
* for it under the LLTV only: a worst fill at the signed `maxLtv` has none, so whether interest fits under
|
|
294
|
+
* `maxLtv` depends on the position and the fill, and a Lever that exceeds it reverts onchain.
|
|
295
|
+
* - The deadline is the leverage data timestamp plus `LEVERAGE_DEADLINE_WINDOW`.
|
|
296
|
+
*
|
|
297
|
+
* @param params - Lever inputs.
|
|
298
|
+
* @param params.intent - Collateral and loan assets the user deposits.
|
|
299
|
+
* @param params.quote - Exact-output quote amounts; `buyAmount` is the collateral to buy.
|
|
300
|
+
* @param params.slippage - Slippage the caller passed to 0x, WAD-scaled, at most 10%.
|
|
301
|
+
* @param params.leverageData - One-block leverage data.
|
|
302
|
+
* @param params.penaltyAssets - Total public-allocator penalty of the action's reallocations, summed
|
|
303
|
+
* per entry as the contract does (zero without reallocations).
|
|
304
|
+
* @returns The Lever's signed limits.
|
|
305
|
+
* @throws {InvalidBigIntInputError} when `slippage`, an intent amount, `penaltyAssets`, `quote.buyAmount`,
|
|
306
|
+
* `quote.maxSellAmount` or the data block timestamp is not a bigint.
|
|
307
|
+
* @throws {NegativeInputError} when an intent amount, `penaltyAssets` or `slippage` is negative.
|
|
308
|
+
* @throws {InputExceedsMaxError} when `loanAssets` exceeds `maxSwapIn + penaltyAssets`, which would
|
|
309
|
+
* lift the signed swap cap above the quote cap, or when an intent amount, `penaltyAssets`, a signed amount or
|
|
310
|
+
* the deadline exceeds the uint256 range.
|
|
311
|
+
* @throws {LeverageWorstFillLtvError} with `check: "health"` when the worst fill fails Blue's mid-flow
|
|
312
|
+
* health check at the LLTV, or `check: "maxLtv"` when it passes that check but exceeds `maxLtv`.
|
|
313
|
+
* @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
|
|
314
|
+
* @throws {ZeroExQuoteRequiredError} when the quote is missing.
|
|
315
|
+
* @throws {ZeroExQuoteTypeMismatchError} when the quote is not exact output.
|
|
316
|
+
* @throws {UnsupportedMarketIrmError} when accruing the position's debt needs an unsupported IRM.
|
|
317
|
+
* @throws {BlueErrors.TotalOverflow} when accruing the market's interest overflows.
|
|
318
|
+
* @throws {NonPositiveInputError} when a quote amount or the deadline is not positive.
|
|
319
|
+
* @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero; a present price
|
|
320
|
+
* that is not a bigint throws `InvalidBigIntInputError`.
|
|
321
|
+
* @throws {LeverageOraclePriceDeviationError} when the worst swap price is more than
|
|
322
|
+
* `LEVERAGE_MAX_ORACLE_DEVIATION` (15%) above the oracle price.
|
|
323
|
+
* @example
|
|
324
|
+
* ```ts
|
|
325
|
+
* import { computeLeverLimits } from "@morpho-org/morpho-sdk";
|
|
326
|
+
*
|
|
327
|
+
* // `leverageData`: the funded WETH/USDC position of the `LeverageLimitsData` example.
|
|
328
|
+
* const limits = computeLeverLimits({
|
|
329
|
+
* intent: { collateralAssets: 10n ** 19n, loanAssets: 0n },
|
|
330
|
+
* quote: { mode: "exactOutput", maxSellAmount: 60_360_300_000n, buyAmount: 2n * 10n ** 19n },
|
|
331
|
+
* slippage: 5_000_000_000_000_000n,
|
|
332
|
+
* leverageData,
|
|
333
|
+
* penaltyAssets: 0n,
|
|
334
|
+
* });
|
|
335
|
+
* // limits.maxBorrowAssets === 60_360_300_000n: the 30 WETH position grows to 60 WETH
|
|
336
|
+
* ```
|
|
337
|
+
*/
|
|
338
|
+
const computeLeverLimits = (params) => {
|
|
339
|
+
const { intent, quote, penaltyAssets } = params;
|
|
340
|
+
const position = (0, exports.validateLeverageInputs)({
|
|
341
|
+
...params,
|
|
342
|
+
operation: "lever",
|
|
343
|
+
});
|
|
344
|
+
for (const [field, value] of [
|
|
345
|
+
["intent.collateralAssets", intent.collateralAssets],
|
|
346
|
+
["intent.loanAssets", intent.loanAssets],
|
|
347
|
+
["penaltyAssets", penaltyAssets],
|
|
348
|
+
]) {
|
|
349
|
+
assertBigInt(field, value);
|
|
350
|
+
}
|
|
351
|
+
if (intent.collateralAssets < 0n) {
|
|
352
|
+
throw new index_js_1.NegativeInputError("intent.collateralAssets", intent.collateralAssets);
|
|
353
|
+
}
|
|
354
|
+
if (intent.loanAssets < 0n) {
|
|
355
|
+
throw new index_js_1.NegativeInputError("intent.loanAssets", intent.loanAssets);
|
|
356
|
+
}
|
|
357
|
+
if (penaltyAssets < 0n) {
|
|
358
|
+
throw new index_js_1.NegativeInputError("penaltyAssets", penaltyAssets);
|
|
359
|
+
}
|
|
360
|
+
(0, validate_js_1.validateUint256Field)("intent.collateralAssets", intent.collateralAssets);
|
|
361
|
+
(0, validate_js_1.validateUint256Field)("intent.loanAssets", intent.loanAssets);
|
|
362
|
+
(0, validate_js_1.validateUint256Field)("penaltyAssets", penaltyAssets);
|
|
363
|
+
const minCollateralToBuy = quote.buyAmount;
|
|
364
|
+
const maxSwapIn = quoteSellCap(quote);
|
|
365
|
+
const spendable = maxSwapIn + penaltyAssets;
|
|
366
|
+
if (intent.loanAssets > spendable) {
|
|
367
|
+
throw new index_js_1.InputExceedsMaxError({
|
|
368
|
+
field: "intent.loanAssets",
|
|
369
|
+
value: intent.loanAssets,
|
|
370
|
+
max: spendable,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
const maxBorrowAssets = spendable - intent.loanAssets;
|
|
374
|
+
(0, validate_js_1.validateUint256Field)("minCollateralToBuy", minCollateralToBuy);
|
|
375
|
+
(0, validate_js_1.validateUint256Field)("maxSwapIn", maxSwapIn);
|
|
376
|
+
(0, validate_js_1.validateUint256Field)("maxBorrowAssets", maxBorrowAssets);
|
|
377
|
+
const { market } = position;
|
|
378
|
+
const price = marketPrice(position, "lever");
|
|
379
|
+
const maxLtv = blue_sdk_1.MathLib.zeroFloorSub(market.params.lltv, constant_js_1.DEFAULT_LLTV_BUFFER);
|
|
380
|
+
const borrowShares = blue_sdk_1.MarketUtils.toBorrowShares(maxBorrowAssets, market, "Up");
|
|
381
|
+
const borrowed = blue_sdk_1.MarketUtils.toBorrowAssets(position.borrowShares + borrowShares, {
|
|
382
|
+
totalBorrowAssets: market.totalBorrowAssets + maxBorrowAssets,
|
|
383
|
+
totalBorrowShares: market.totalBorrowShares + borrowShares,
|
|
384
|
+
}, "Up");
|
|
385
|
+
const collateral = position.collateral + intent.collateralAssets + minCollateralToBuy;
|
|
386
|
+
validateWorstFillLtv({
|
|
387
|
+
operation: "lever",
|
|
388
|
+
check: "health",
|
|
389
|
+
borrowed,
|
|
390
|
+
collateral,
|
|
391
|
+
price,
|
|
392
|
+
maxLtv: market.params.lltv,
|
|
393
|
+
});
|
|
394
|
+
validateWorstFillLtv({
|
|
395
|
+
operation: "lever",
|
|
396
|
+
check: "maxLtv",
|
|
397
|
+
borrowed,
|
|
398
|
+
collateral,
|
|
399
|
+
price,
|
|
400
|
+
maxLtv,
|
|
401
|
+
});
|
|
402
|
+
const oracleDeviation = validateLeverOraclePrice({
|
|
403
|
+
maxSwapIn,
|
|
404
|
+
minCollateralToBuy,
|
|
405
|
+
price,
|
|
406
|
+
});
|
|
407
|
+
return {
|
|
408
|
+
minCollateralToBuy,
|
|
409
|
+
maxBorrowAssets,
|
|
410
|
+
maxSwapIn,
|
|
411
|
+
penaltyAssets,
|
|
412
|
+
maxLtv,
|
|
413
|
+
deadline: (0, exports.leverageDeadline)(params.leverageData),
|
|
414
|
+
oracleDeviation,
|
|
415
|
+
};
|
|
416
|
+
};
|
|
417
|
+
exports.computeLeverLimits = computeLeverLimits;
|
|
418
|
+
/**
|
|
419
|
+
* Computes the signed limits of a Delever (pay back with collateral) from an exact-input 0x quote
|
|
420
|
+
* and the caller's slippage.
|
|
421
|
+
*
|
|
422
|
+
* - `maxCollateralToSell` is the quote's `sellAmount`; `minRepayAssets` is the quote's `minBuyAmount` as is, so
|
|
423
|
+
* 0x's floor is the one source of truth and a fill at it passes the bundle's output check. It must be positive
|
|
424
|
+
* and at least `buyAmount × (1 − slippage)`. That bound uses the whole-ppm slippage sent to 0x, which rounds the
|
|
425
|
+
* caller's slippage down and so raises the bound in the user's favour, and rounds the amount down as 0x does,
|
|
426
|
+
* so every quote 0x builds for that slippage passes and one unit less is refused. No oracle enters a bound.
|
|
427
|
+
* - `maxLtv` is the position's LTV with its debt accrued to the deadline, at the data block's
|
|
428
|
+
* oracle price (rounded up, as Blue's `getLtv`): the LTV of doing nothing until the deadline. A
|
|
429
|
+
* position already past the LLTV buffer can still delever. The accrual is a projection from the leverage data
|
|
430
|
+
* block's market and IRM state, run once from the market's stored last update as Blue accrues it, so a
|
|
431
|
+
* fetched position must be passed unaccrued: interest that follows it does not make a small Delever revert, but a rate
|
|
432
|
+
* that rises before execution can. The worst fill withdraws all of
|
|
433
|
+
* `maxCollateralToSell` and repays only `minRepayAssets` of the debt accrued to the deadline, the latest
|
|
434
|
+
* and costliest moment the contract can run; Blue checks health on that state before any surplus
|
|
435
|
+
* is repaid, and the contract checks `maxLtv` after it. Refuses when it fails either, so a Delever
|
|
436
|
+
* never ends above the LTV projected from the data block. That cap is fixed when the Delever is built: an
|
|
437
|
+
* oracle price rise or new debt before inclusion can let a poor fill raise the live LTV and still pass it.
|
|
438
|
+
*
|
|
439
|
+
* @param params - Delever inputs.
|
|
440
|
+
* @param params.quote - Exact-input quote amounts; `sellAmount` is the collateral to sell.
|
|
441
|
+
* @param params.slippage - Caller slippage, WAD-scaled, at most 10%.
|
|
442
|
+
* @param params.leverageData - One-block leverage data.
|
|
443
|
+
* @returns The Delever's signed limits.
|
|
444
|
+
* @throws {ZeroExQuoteMinBuyAmountBelowSlippageError} when `quote.minBuyAmount` is zero or below
|
|
445
|
+
* `buyAmount × (1 − slippage)`, the slippage rounded down to whole parts per million: the quote allows more
|
|
446
|
+
* slippage than the caller's. Fetch a new quote with the caller's slippage.
|
|
447
|
+
* @throws {RepayExceedsDebtError} when `minRepayAssets` exceeds the debt; use Close instead.
|
|
448
|
+
* @throws {RepaySharesExceedDebtError} when `minRepayAssets`, repaid by assets as the contract
|
|
449
|
+
* does, would burn more borrow shares than the position holds; use Close instead.
|
|
450
|
+
* @throws {WithdrawExceedsCollateralError} when `maxCollateralToSell` exceeds the position's collateral.
|
|
451
|
+
* @throws {LeverageWorstFillLtvError} when the worst fill fails Blue's health check or `maxLtv`, or
|
|
452
|
+
* when the collateral is worth zero at the market price, which would make `maxLtv` unlimited.
|
|
453
|
+
* @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
|
|
454
|
+
* @throws {ZeroExQuoteRequiredError} when the quote is missing.
|
|
455
|
+
* @throws {ZeroExQuoteTypeMismatchError} when the quote is not exact input.
|
|
456
|
+
* @throws {UnsupportedMarketIrmError} when accruing the position's debt needs an unsupported IRM.
|
|
457
|
+
* @throws {BlueErrors.TotalOverflow} when accruing the market's interest overflows.
|
|
458
|
+
* @throws {InvalidBigIntInputError} when `slippage`, `quote.buyAmount`, `quote.minBuyAmount`, the quote's sell amount
|
|
459
|
+
* or the data block timestamp is not a bigint.
|
|
460
|
+
* @throws {NegativeInputError} when `slippage` is negative.
|
|
461
|
+
* @throws {NonPositiveInputError} when `quote.sellAmount`, `quote.buyAmount` or the deadline is not positive.
|
|
462
|
+
* @throws {InputExceedsMaxError} when the deadline exceeds the uint256 range.
|
|
463
|
+
* @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero; a present price
|
|
464
|
+
* that is not a bigint throws `InvalidBigIntInputError`.
|
|
465
|
+
* @example
|
|
466
|
+
* ```ts
|
|
467
|
+
* import { computeDeleverLimits } from "@morpho-org/morpho-sdk";
|
|
468
|
+
*
|
|
469
|
+
* // `leverageData`: the funded WETH/USDC position of the `LeverageLimitsData` example.
|
|
470
|
+
* const limits = computeDeleverLimits({
|
|
471
|
+
* quote: {
|
|
472
|
+
* mode: "exactInput",
|
|
473
|
+
* sellAmount: 10n ** 19n,
|
|
474
|
+
* buyAmount: 29_970_000_000n,
|
|
475
|
+
* minBuyAmount: 29_820_150_000n,
|
|
476
|
+
* },
|
|
477
|
+
* slippage: 5_000_000_000_000_000n,
|
|
478
|
+
* leverageData,
|
|
479
|
+
* });
|
|
480
|
+
* // limits.minRepayAssets === 29_820_150_000n
|
|
481
|
+
* ```
|
|
482
|
+
*/
|
|
483
|
+
const computeDeleverLimits = (params) => {
|
|
484
|
+
const { quote } = params;
|
|
485
|
+
const position = (0, exports.validateLeverageInputs)({
|
|
486
|
+
...params,
|
|
487
|
+
operation: "delever",
|
|
488
|
+
});
|
|
489
|
+
const { market } = position;
|
|
490
|
+
const maxCollateralToSell = quoteSellCap(quote);
|
|
491
|
+
/* v8 ignore next: validateLeverageInputs refuses a Delever quote that is not exact input; this narrows the type. */
|
|
492
|
+
if (quote.mode !== "exactInput") {
|
|
493
|
+
throw new index_js_1.ZeroExQuoteTypeMismatchError({
|
|
494
|
+
expected: "exactInput",
|
|
495
|
+
actual: quote.mode,
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
const minRepayAssets = quote.minBuyAmount;
|
|
499
|
+
const debt = position.borrowAssets;
|
|
500
|
+
if (minRepayAssets > debt) {
|
|
501
|
+
throw new index_js_1.RepayExceedsDebtError({
|
|
502
|
+
repayAmount: minRepayAssets,
|
|
503
|
+
debt,
|
|
504
|
+
market: market.id,
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
if (maxCollateralToSell > position.collateral) {
|
|
508
|
+
throw new index_js_1.WithdrawExceedsCollateralError({
|
|
509
|
+
withdrawAmount: maxCollateralToSell,
|
|
510
|
+
available: position.collateral,
|
|
511
|
+
market: market.id,
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
const price = marketPrice(position, "delever");
|
|
515
|
+
const collateralValue = valueDown(position.collateral, price);
|
|
516
|
+
if (collateralValue === 0n) {
|
|
517
|
+
throw new index_js_1.LeverageWorstFillLtvError({
|
|
518
|
+
operation: "delever",
|
|
519
|
+
check: "maxLtv",
|
|
520
|
+
ltv: blue_sdk_1.MathLib.MAX_UINT_256,
|
|
521
|
+
maxLtv: market.params.lltv,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
// Interest accrued until the deadline only raises the LTV of doing nothing, so signing it keeps the
|
|
525
|
+
// guarantee while a small Delever no longer reverts on interest that follows the projection. Blue
|
|
526
|
+
// accrues once from its stored last update, so the projection does too: accruing the data-block
|
|
527
|
+
// position again rounds each step down and can sign a cap below the debt Blue reaches.
|
|
528
|
+
const deadline = (0, exports.leverageDeadline)(params.leverageData);
|
|
529
|
+
const atDeadline = params.leverageData.position.accrueInterest(deadline);
|
|
530
|
+
const maxLtv = blue_sdk_1.MathLib.wDivUp(atDeadline.borrowAssets, collateralValue);
|
|
531
|
+
const repaidShares = blue_sdk_1.MarketUtils.toBorrowShares(minRepayAssets, market, "Down");
|
|
532
|
+
if (repaidShares > position.borrowShares) {
|
|
533
|
+
throw new index_js_1.RepaySharesExceedDebtError({
|
|
534
|
+
repayShares: repaidShares,
|
|
535
|
+
borrowShares: position.borrowShares,
|
|
536
|
+
market: market.id,
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
// The contract can run up to the deadline, where the debt is highest, so the worst fill is checked there.
|
|
540
|
+
const repaidSharesAtDeadline = blue_sdk_1.MarketUtils.toBorrowShares(minRepayAssets, atDeadline.market, "Down");
|
|
541
|
+
const borrowed = blue_sdk_1.MarketUtils.toBorrowAssets(atDeadline.borrowShares - repaidSharesAtDeadline, {
|
|
542
|
+
totalBorrowAssets: atDeadline.market.totalBorrowAssets - minRepayAssets,
|
|
543
|
+
totalBorrowShares: atDeadline.market.totalBorrowShares - repaidSharesAtDeadline,
|
|
544
|
+
}, "Up");
|
|
545
|
+
const collateral = position.collateral - maxCollateralToSell;
|
|
546
|
+
validateWorstFillLtv({
|
|
547
|
+
operation: "delever",
|
|
548
|
+
check: "health",
|
|
549
|
+
borrowed,
|
|
550
|
+
collateral,
|
|
551
|
+
price,
|
|
552
|
+
maxLtv: market.params.lltv,
|
|
553
|
+
});
|
|
554
|
+
validateWorstFillLtv({
|
|
555
|
+
operation: "delever",
|
|
556
|
+
check: "maxLtv",
|
|
557
|
+
borrowed,
|
|
558
|
+
collateral,
|
|
559
|
+
price,
|
|
560
|
+
maxLtv,
|
|
561
|
+
});
|
|
562
|
+
return {
|
|
563
|
+
maxCollateralToSell,
|
|
564
|
+
minRepayAssets,
|
|
565
|
+
maxLtv,
|
|
566
|
+
deadline,
|
|
567
|
+
oracleDeviation: (0, exports.computeLeverageOracleDeviation)({
|
|
568
|
+
operation: "delever",
|
|
569
|
+
limits: { maxCollateralToSell, minRepayAssets },
|
|
570
|
+
oraclePrice: price,
|
|
571
|
+
}),
|
|
572
|
+
};
|
|
573
|
+
};
|
|
574
|
+
exports.computeDeleverLimits = computeDeleverLimits;
|
|
575
|
+
/**
|
|
576
|
+
* Computes the signed limits of a Close with debt, from an exact-output 0x quote and the caller's
|
|
577
|
+
* slippage. The Close keeps the collateral it does not sell.
|
|
578
|
+
*
|
|
579
|
+
* - `minLoanOut` is the quote's `buyAmount` and `maxCollateralIn` its `maxSellAmount`, which
|
|
580
|
+
* already carries the caller's slippage and must not exceed the position's collateral (the
|
|
581
|
+
* contract does not cap it). Unsold collateral returns to the wallet.
|
|
582
|
+
* - `minLoanOut` must cover the debt at the data block plus `computeCloseInterestBuffer` (at
|
|
583
|
+
* least 1 wei), as headroom for the interest that accrues before execution. It is not a minimum returned to the
|
|
584
|
+
* user: `maxCollateralIn` can be the whole collateral, so a fill at the floor can sell all of it, repay the debt
|
|
585
|
+
* and return nothing. The buffer is an estimate at the
|
|
586
|
+
* data block's borrow rate: it reduces interest-driven reverts of a fill at the floor but does not
|
|
587
|
+
* rule them out if the rate jumps before execution. The debt is never used as the floor.
|
|
588
|
+
* - Close has no `maxLtv`.
|
|
589
|
+
* - This helper only checks that `minLoanOut` covers at least the debt plus the buffer. `blueClose` accepts only that
|
|
590
|
+
* exact size and refuses a larger `buyAmount` with `LeverageCloseBuyAboveDebtError`, so a caller that uses this
|
|
591
|
+
* helper directly must enforce the exact size itself.
|
|
592
|
+
*
|
|
593
|
+
* A Close without debt has no limits: this function refuses it, and `blueClose` refuses it earlier with
|
|
594
|
+
* `LeverageCloseWithoutDebtError`.
|
|
595
|
+
*
|
|
596
|
+
* @param params - Close inputs.
|
|
597
|
+
* @param params.quote - Exact-output quote amounts.
|
|
598
|
+
* @param params.slippage - Caller slippage, WAD-scaled, at most 10%.
|
|
599
|
+
* @param params.leverageData - One-block leverage data.
|
|
600
|
+
* @returns The Close's signed limits.
|
|
601
|
+
* @throws {NonPositiveInputError} when the position has no debt, or a quote amount or the deadline is not positive.
|
|
602
|
+
* @throws {LeverageCloseInputExceedsCollateralError} when `maxCollateralIn` exceeds the collateral.
|
|
603
|
+
* @throws {LeverageCloseFloorBelowDebtPlusBufferError} when `minLoanOut` is below the debt plus the interest buffer.
|
|
604
|
+
* @throws {InputExceedsMaxError} when `minLoanOut` or the deadline exceeds the uint256 range.
|
|
605
|
+
* @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
|
|
606
|
+
* @throws {ZeroExQuoteRequiredError} when the quote is missing.
|
|
607
|
+
* @throws {ZeroExQuoteTypeMismatchError} when the quote is not an exact-output quote.
|
|
608
|
+
* @throws {UnsupportedMarketIrmError} when accruing the position's debt needs an unsupported IRM.
|
|
609
|
+
* @throws {BlueErrors.TotalOverflow} when accruing the market's interest overflows.
|
|
610
|
+
* @throws {InvalidBigIntInputError} when `slippage`, `quote.buyAmount`, the quote's sell amount or the data
|
|
611
|
+
* block timestamp is not a bigint, or when the position has debt and `leverageData.borrowRate` is not a bigint.
|
|
612
|
+
* @throws {NegativeInputError} when `slippage` is negative, or when the position has debt and `leverageData.borrowRate` is
|
|
613
|
+
* negative.
|
|
614
|
+
* @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero; a present price
|
|
615
|
+
* that is not a bigint throws `InvalidBigIntInputError`.
|
|
616
|
+
* @example
|
|
617
|
+
* ```ts
|
|
618
|
+
* import { computeCloseInterestBuffer, computeCloseLimits } from "@morpho-org/morpho-sdk";
|
|
619
|
+
*
|
|
620
|
+
* // `leverageData`: the funded WETH/USDC position of the `LeverageLimitsData` example.
|
|
621
|
+
* // Size the exact-output quote from the same snapshot: the debt at the data block plus the interest buffer.
|
|
622
|
+
* const buyAmount =
|
|
623
|
+
* leverageData.position.accrueInterest(leverageData.block.timestamp).borrowAssets +
|
|
624
|
+
* computeCloseInterestBuffer(leverageData);
|
|
625
|
+
* const limits = computeCloseLimits({
|
|
626
|
+
* quote: { mode: "exactOutput", maxSellAmount: 205n * 10n ** 17n, buyAmount },
|
|
627
|
+
* slippage: 5_000_000_000_000_000n,
|
|
628
|
+
* leverageData,
|
|
629
|
+
* });
|
|
630
|
+
* // limits.minLoanOut === buyAmount: exactly the debt plus the buffer, the only size blueClose accepts
|
|
631
|
+
* ```
|
|
632
|
+
*/
|
|
633
|
+
const computeCloseLimits = (params) => {
|
|
634
|
+
const { quote } = params;
|
|
635
|
+
const position = (0, exports.validateLeverageInputs)({
|
|
636
|
+
...params,
|
|
637
|
+
operation: "close",
|
|
638
|
+
});
|
|
639
|
+
const debt = position.borrowAssets;
|
|
640
|
+
if (debt <= 0n) {
|
|
641
|
+
throw new index_js_1.NonPositiveInputError("leverageData.position.borrowAssets", debt);
|
|
642
|
+
}
|
|
643
|
+
const maxCollateralIn = quoteSellCap(quote);
|
|
644
|
+
const minLoanOut = quote.buyAmount;
|
|
645
|
+
if (maxCollateralIn > position.collateral) {
|
|
646
|
+
throw new index_js_1.LeverageCloseInputExceedsCollateralError({
|
|
647
|
+
cap: maxCollateralIn,
|
|
648
|
+
collateral: position.collateral,
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
(0, validate_js_1.validateUint256Field)("minLoanOut", minLoanOut);
|
|
652
|
+
// The floor covers the estimated interest until the deadline, so a fill at the floor rarely falls short.
|
|
653
|
+
const interestBuffer = (0, exports.computeCloseInterestBuffer)(params.leverageData);
|
|
654
|
+
if (minLoanOut < debt + interestBuffer) {
|
|
655
|
+
throw new index_js_1.LeverageCloseFloorBelowDebtPlusBufferError({
|
|
656
|
+
floor: minLoanOut,
|
|
657
|
+
debt,
|
|
658
|
+
interestBuffer,
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
return {
|
|
662
|
+
maxCollateralIn,
|
|
663
|
+
minLoanOut,
|
|
664
|
+
deadline: (0, exports.leverageDeadline)(params.leverageData),
|
|
665
|
+
oracleDeviation: (0, exports.computeLeverageOracleDeviation)({
|
|
666
|
+
operation: "close",
|
|
667
|
+
limits: { maxCollateralIn, minLoanOut },
|
|
668
|
+
oraclePrice: marketPrice(position, "close"),
|
|
669
|
+
}),
|
|
670
|
+
};
|
|
671
|
+
};
|
|
672
|
+
exports.computeCloseLimits = computeCloseLimits;
|
|
673
|
+
/**
|
|
674
|
+
* Computes the interest buffer a Close floor must cover above the debt; a keep-collateral Close adds it to the debt when it asks 0x for an
|
|
675
|
+
* exact output: `debt × borrowRate × LEVERAGE_DEADLINE_WINDOW × LEVERAGE_CLOSE_INTEREST_BUFFER_FACTOR`,
|
|
676
|
+
* rounded up and at least 1 wei when there is debt, so `debt + buffer` always passes the floor
|
|
677
|
+
* check of `computeCloseLimits` (a zero-rate market included), with the debt and the market's
|
|
678
|
+
* per-second borrow rate at the data block. Not a
|
|
679
|
+
* safety value: the contract returns any excess to the user as loan token, and a shortfall only
|
|
680
|
+
* makes Blue's repay pull revert.
|
|
681
|
+
*
|
|
682
|
+
* @param leverageData - One-block leverage data.
|
|
683
|
+
* @returns Interest buffer in loan-token assets.
|
|
684
|
+
* @throws {InvalidBigIntInputError} when `leverageData.block.timestamp` is missing or not a bigint, or when the position
|
|
685
|
+
* has debt and `leverageData.borrowRate` is missing or not a bigint.
|
|
686
|
+
* @throws {NegativeInputError} when the position has debt and `leverageData.borrowRate` is negative.
|
|
687
|
+
* @throws {UnsupportedMarketIrmError} when accruing a debt needs an unsupported IRM.
|
|
688
|
+
* @throws {BlueErrors.TotalOverflow} when accruing the market's interest overflows.
|
|
689
|
+
* @example
|
|
690
|
+
* ```ts
|
|
691
|
+
* import { computeCloseInterestBuffer } from "@morpho-org/morpho-sdk";
|
|
692
|
+
*
|
|
693
|
+
* // `leverageData`: the funded WETH/USDC position of the `LeverageLimitsData` example.
|
|
694
|
+
* const buffer = computeCloseInterestBuffer(leverageData);
|
|
695
|
+
* const buyAmount =
|
|
696
|
+
* leverageData.position.accrueInterest(leverageData.block.timestamp).borrowAssets + buffer;
|
|
697
|
+
* ```
|
|
698
|
+
*/
|
|
699
|
+
const computeCloseInterestBuffer = (leverageData) => {
|
|
700
|
+
// Blue accrues to the market's lastUpdate when the timestamp is missing, which would undersize the buffer.
|
|
701
|
+
assertBigInt("leverageData.block.timestamp", leverageData.block.timestamp);
|
|
702
|
+
const position = leverageData.position.accrueInterest(leverageData.block.timestamp);
|
|
703
|
+
if (position.borrowAssets === 0n) {
|
|
704
|
+
return 0n;
|
|
705
|
+
}
|
|
706
|
+
assertBigInt("leverageData.borrowRate", leverageData.borrowRate);
|
|
707
|
+
if (leverageData.borrowRate < 0n) {
|
|
708
|
+
throw new index_js_1.NegativeInputError("leverageData.borrowRate", leverageData.borrowRate);
|
|
709
|
+
}
|
|
710
|
+
const buffer = blue_sdk_1.MathLib.mulDivUp(position.borrowAssets, leverageData.borrowRate *
|
|
711
|
+
constant_js_1.LEVERAGE_DEADLINE_WINDOW *
|
|
712
|
+
constant_js_1.LEVERAGE_CLOSE_INTEREST_BUFFER_FACTOR, blue_sdk_1.MathLib.WAD);
|
|
713
|
+
return buffer > 0n ? buffer : 1n;
|
|
714
|
+
};
|
|
715
|
+
exports.computeCloseInterestBuffer = computeCloseInterestBuffer;
|