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