@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.
Files changed (192) hide show
  1. package/README.md +44 -1
  2. package/lib/cjs/abis.d.ts +794 -1
  3. package/lib/cjs/abis.js +815 -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/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  16. package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.js +59 -0
  17. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  18. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.js +193 -0
  19. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  20. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.js +66 -0
  21. package/lib/cjs/actions/requirements/blue/index.d.ts +3 -0
  22. package/lib/cjs/actions/requirements/blue/index.js +17 -0
  23. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  24. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
  25. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +11 -6
  26. package/lib/cjs/actions/requirements/getRequirementsApproval.js +29 -5
  27. package/lib/cjs/addresses.d.ts +1 -1
  28. package/lib/cjs/addresses.js +6 -1
  29. package/lib/cjs/blue/abis.d.ts +1 -1
  30. package/lib/cjs/blue/abis.js +5 -1
  31. package/lib/cjs/blue/addresses.d.ts +1 -1
  32. package/lib/cjs/blue/addresses.js +6 -1
  33. package/lib/cjs/blue/entities.d.ts +4 -4
  34. package/lib/cjs/blue/entities.js +3 -1
  35. package/lib/cjs/blue/errors.d.ts +2 -2
  36. package/lib/cjs/blue/errors.js +5 -1
  37. package/lib/cjs/blue/fetch.d.ts +2 -2
  38. package/lib/cjs/blue/fetch.js +3 -1
  39. package/lib/cjs/blue/utils.d.ts +1 -1
  40. package/lib/cjs/blue/utils.js +2 -1
  41. package/lib/cjs/constants.d.ts +1 -1
  42. package/lib/cjs/constants.js +6 -2
  43. package/lib/cjs/entities/blue/blue.d.ts +486 -2
  44. package/lib/cjs/entities/blue/blue.js +529 -34
  45. package/lib/cjs/entities/index.d.ts +5 -5
  46. package/lib/cjs/entities/index.js +3 -1
  47. package/lib/cjs/entities/requirements/assertContractCode.d.ts +0 -23
  48. package/lib/cjs/entities/requirements/assertContractCode.js +3 -28
  49. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +34 -8
  50. package/lib/cjs/entities/vaultV2/vaultV2.js +39 -1
  51. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +120 -2
  52. package/lib/cjs/entities/vaultV2BlueReallocationData.js +232 -4
  53. package/lib/cjs/errors.d.ts +4 -4
  54. package/lib/cjs/errors.js +7 -5
  55. package/lib/cjs/fetch.d.ts +2 -2
  56. package/lib/cjs/fetch.js +3 -1
  57. package/lib/cjs/helpers/constant.d.ts +34 -0
  58. package/lib/cjs/helpers/constant.js +35 -1
  59. package/lib/cjs/helpers/deadShares.js +3 -0
  60. package/lib/cjs/helpers/getZeroExLeverageBundle.d.ts +13 -0
  61. package/lib/cjs/helpers/getZeroExLeverageBundle.js +27 -0
  62. package/lib/cjs/helpers/index.d.ts +4 -1
  63. package/lib/cjs/helpers/index.js +28 -1
  64. package/lib/cjs/helpers/leverage/index.d.ts +1 -0
  65. package/lib/cjs/helpers/leverage/index.js +11 -0
  66. package/lib/cjs/helpers/leverage/limits.d.ts +472 -0
  67. package/lib/cjs/helpers/leverage/limits.js +715 -0
  68. package/lib/cjs/helpers/leverage/positionMarket.d.ts +17 -0
  69. package/lib/cjs/helpers/leverage/positionMarket.js +28 -0
  70. package/lib/cjs/helpers/leverage/reallocations.d.ts +159 -0
  71. package/lib/cjs/helpers/leverage/reallocations.js +276 -0
  72. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  73. package/lib/cjs/helpers/validateRequirementSpender.js +4 -0
  74. package/lib/cjs/helpers/zeroExQuote.d.ts +250 -0
  75. package/lib/cjs/helpers/zeroExQuote.js +763 -0
  76. package/lib/cjs/index.d.ts +1 -0
  77. package/lib/cjs/index.js +5 -2
  78. package/lib/cjs/midnight/errors.d.ts +2 -1
  79. package/lib/cjs/midnight/errors.js +5 -4
  80. package/lib/cjs/reads/assertContractCode.d.ts +25 -0
  81. package/lib/cjs/reads/assertContractCode.js +30 -0
  82. package/lib/cjs/reads/fetchZeroExQuote.d.ts +123 -0
  83. package/lib/cjs/reads/fetchZeroExQuote.js +330 -0
  84. package/lib/cjs/types/action.d.ts +130 -1
  85. package/lib/cjs/types/error.d.ts +59 -0
  86. package/lib/cjs/types/error.js +82 -3
  87. package/lib/cjs/types/index.d.ts +2 -0
  88. package/lib/cjs/types/index.js +2 -0
  89. package/lib/cjs/types/leverageError.d.ts +1552 -0
  90. package/lib/cjs/types/leverageError.js +1711 -0
  91. package/lib/cjs/types/zeroEx.d.ts +171 -0
  92. package/lib/cjs/types/zeroEx.js +2 -0
  93. package/lib/cjs/utils.d.ts +2 -2
  94. package/lib/cjs/utils.js +4 -2
  95. package/lib/cjs/version.d.ts +1 -1
  96. package/lib/cjs/version.js +1 -1
  97. package/lib/esm/abis.d.ts +794 -1
  98. package/lib/esm/abis.js +810 -1
  99. package/lib/esm/actions/blue/close.d.ts +169 -0
  100. package/lib/esm/actions/blue/close.js +266 -0
  101. package/lib/esm/actions/blue/common.js +3 -3
  102. package/lib/esm/actions/blue/delever.d.ts +156 -0
  103. package/lib/esm/actions/blue/delever.js +219 -0
  104. package/lib/esm/actions/blue/index.d.ts +3 -0
  105. package/lib/esm/actions/blue/index.js +3 -0
  106. package/lib/esm/actions/blue/lever.d.ts +184 -0
  107. package/lib/esm/actions/blue/lever.js +268 -0
  108. package/lib/esm/actions/blue/leverageIntent.d.ts +65 -0
  109. package/lib/esm/actions/blue/leverageIntent.js +96 -0
  110. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  111. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.js +55 -0
  112. package/lib/esm/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  113. package/lib/esm/actions/requirements/blue/getLeverageRequirements.js +189 -0
  114. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  115. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.js +62 -0
  116. package/lib/esm/actions/requirements/blue/index.d.ts +3 -0
  117. package/lib/esm/actions/requirements/blue/index.js +3 -0
  118. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  119. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
  120. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +11 -6
  121. package/lib/esm/actions/requirements/getRequirementsApproval.js +29 -5
  122. package/lib/esm/addresses.d.ts +1 -1
  123. package/lib/esm/addresses.js +1 -1
  124. package/lib/esm/blue/abis.d.ts +1 -1
  125. package/lib/esm/blue/abis.js +1 -1
  126. package/lib/esm/blue/addresses.d.ts +1 -1
  127. package/lib/esm/blue/addresses.js +1 -1
  128. package/lib/esm/blue/entities.d.ts +4 -4
  129. package/lib/esm/blue/entities.js +2 -2
  130. package/lib/esm/blue/errors.d.ts +2 -2
  131. package/lib/esm/blue/errors.js +2 -2
  132. package/lib/esm/blue/fetch.d.ts +2 -2
  133. package/lib/esm/blue/fetch.js +2 -2
  134. package/lib/esm/blue/utils.d.ts +1 -1
  135. package/lib/esm/blue/utils.js +1 -1
  136. package/lib/esm/constants.d.ts +1 -1
  137. package/lib/esm/constants.js +1 -1
  138. package/lib/esm/entities/blue/blue.d.ts +486 -2
  139. package/lib/esm/entities/blue/blue.js +501 -6
  140. package/lib/esm/entities/index.d.ts +5 -5
  141. package/lib/esm/entities/index.js +2 -2
  142. package/lib/esm/entities/requirements/assertContractCode.d.ts +0 -23
  143. package/lib/esm/entities/requirements/assertContractCode.js +1 -25
  144. package/lib/esm/entities/vaultV2/vaultV2.d.ts +34 -8
  145. package/lib/esm/entities/vaultV2/vaultV2.js +40 -2
  146. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +120 -2
  147. package/lib/esm/entities/vaultV2BlueReallocationData.js +233 -5
  148. package/lib/esm/errors.d.ts +4 -4
  149. package/lib/esm/errors.js +4 -4
  150. package/lib/esm/fetch.d.ts +2 -2
  151. package/lib/esm/fetch.js +2 -2
  152. package/lib/esm/helpers/constant.d.ts +34 -0
  153. package/lib/esm/helpers/constant.js +34 -0
  154. package/lib/esm/helpers/deadShares.js +4 -1
  155. package/lib/esm/helpers/getZeroExLeverageBundle.d.ts +13 -0
  156. package/lib/esm/helpers/getZeroExLeverageBundle.js +23 -0
  157. package/lib/esm/helpers/index.d.ts +4 -1
  158. package/lib/esm/helpers/index.js +4 -1
  159. package/lib/esm/helpers/leverage/index.d.ts +1 -0
  160. package/lib/esm/helpers/leverage/index.js +1 -0
  161. package/lib/esm/helpers/leverage/limits.d.ts +472 -0
  162. package/lib/esm/helpers/leverage/limits.js +705 -0
  163. package/lib/esm/helpers/leverage/positionMarket.d.ts +17 -0
  164. package/lib/esm/helpers/leverage/positionMarket.js +24 -0
  165. package/lib/esm/helpers/leverage/reallocations.d.ts +159 -0
  166. package/lib/esm/helpers/leverage/reallocations.js +271 -0
  167. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  168. package/lib/esm/helpers/validateRequirementSpender.js +5 -1
  169. package/lib/esm/helpers/zeroExQuote.d.ts +250 -0
  170. package/lib/esm/helpers/zeroExQuote.js +754 -0
  171. package/lib/esm/index.d.ts +1 -0
  172. package/lib/esm/index.js +1 -0
  173. package/lib/esm/midnight/errors.d.ts +2 -1
  174. package/lib/esm/midnight/errors.js +2 -1
  175. package/lib/esm/reads/assertContractCode.d.ts +25 -0
  176. package/lib/esm/reads/assertContractCode.js +26 -0
  177. package/lib/esm/reads/fetchZeroExQuote.d.ts +123 -0
  178. package/lib/esm/reads/fetchZeroExQuote.js +326 -0
  179. package/lib/esm/types/action.d.ts +130 -1
  180. package/lib/esm/types/error.d.ts +59 -0
  181. package/lib/esm/types/error.js +76 -0
  182. package/lib/esm/types/index.d.ts +2 -0
  183. package/lib/esm/types/index.js +2 -0
  184. package/lib/esm/types/leverageError.d.ts +1552 -0
  185. package/lib/esm/types/leverageError.js +1660 -0
  186. package/lib/esm/types/zeroEx.d.ts +171 -0
  187. package/lib/esm/types/zeroEx.js +1 -0
  188. package/lib/esm/utils.d.ts +2 -2
  189. package/lib/esm/utils.js +2 -2
  190. package/lib/esm/version.d.ts +1 -1
  191. package/lib/esm/version.js +1 -1
  192. package/package.json +7 -7
@@ -0,0 +1,268 @@
1
+ import { deepFreeze } from "@morpho-org/morpho-ts";
2
+ import { encodeFunctionData } from "viem";
3
+ import { zeroExLeverageBundlesV1Abi } from "../../abis.js";
4
+ import { MAX_REALLOCATION_PENALTY } from "../../helpers/constant.js";
5
+ import { computeLeverLimits, } from "../../helpers/leverage/limits.js";
6
+ import { validateLeveragePositionMarket } from "../../helpers/leverage/positionMarket.js";
7
+ import { computeLeveragePenaltyAssets, validateLeverageReallocations, } from "../../helpers/leverage/reallocations.js";
8
+ import { addTransactionMetadata } from "../../helpers/metadata.js";
9
+ import { parseBlueMarket } from "../../helpers/parse.js";
10
+ import { validateAccrualPosition, validateChainId, validateMarketParamsId, } from "../../helpers/validate.js";
11
+ import { getZeroExLeverageBundle, validateZeroExQuote, } from "../../helpers/zeroExQuote.js";
12
+ import { InvalidBigIntInputError, LeverageInsufficientLiquidityError, ZeroExQuoteRequiredError, } from "../../types/index.js";
13
+ import { parseBlueAllocations } from "./common.js";
14
+ import { validateLeverageIntentAmount, validateLeverageQuoteSlippage, validateLeverNativeAmount, validateLeverSlippage, } from "./leverageIntent.js";
15
+ /**
16
+ * Encodes a ZeroExLeverageBundlesV1 Lever: pulls `collateralAssets` and `loanAssets` from the user,
17
+ * executes the planned BluePublicAllocator reallocations, borrows `maxBorrowAssets` and buys at least
18
+ * the quote's `buyAmount` (`minCollateralToBuy`) of collateral through 0x, all in one call to the chain's
19
+ * registered bundle. The bundle also accepts a 0x SELL quote, but the SDK builds Lever from exact-output quotes only.
20
+ *
21
+ * With a positive `nativeAmount`, the transaction sends it as `value` and the bundle wraps it into the chain's
22
+ * wNative (`wrappedNative`) and transfers it to the user before the pulls, so the user's wNative approval still
23
+ * covers the whole pull. Without it, `value` is zero and `wrappedNative` the zero address.
24
+ *
25
+ * Every bound is computed, none is taken from the caller:
26
+ * - `computeLeverLimits` takes the quote's `maxSellAmount` as the swap cap (0x already applied the
27
+ * slippage, and the Settler pulls that whole amount) and derives the borrow and `maxLtv` (LLTV minus `DEFAULT_LLTV_BUFFER`, never `type(uint256).max`). It
28
+ * refuses a worst fill that fails Blue's mid-flow health check (`check: "health"`) or `maxLtv`
29
+ * (`check: "maxLtv"`), refuses a worst swap price (`maxSwapIn` per `minCollateralToBuy`) more than
30
+ * `LEVERAGE_MAX_ORACLE_DEVIATION` (15%) above the market's oracle price (a lower price is never refused), and fixes the deadline one hour
31
+ * after the data block. The price and the debt are the data block's; until the deadline only the signed `maxLtv`
32
+ * and Blue's health check guard execution. The deviation compares `maxSwapIn` alone: reallocation penalties
33
+ * (`penaltyAssets`, at most 1% each) are paid on top.
34
+ * - `penaltyAssets` is each reallocation's penalty rounded up, then summed, as the bundle checks it. A Lever
35
+ * that borrows nothing takes no reallocation, as the bundle reverts with `InconsistentBorrowInput` otherwise.
36
+ * `validateLeverageReallocations` refuses a reallocation to another market, through a route the
37
+ * allocator does not allow at the data block, above the 1% penalty ceiling, or reallocations
38
+ * that move more than the borrow. It does not check remaining caps or IRM compatibility, so pass
39
+ * only reallocations `VaultV2BlueReallocationData` planned for this borrow, as `MorphoBlue.lever`
40
+ * does.
41
+ * - `validateZeroExQuote` decodes the swap against the market's tokens, the bundle and the swap cap. It does not
42
+ * check whether the swap's Settler is 0x's official one or paused; the bundle's `maxIn` bounds the swap.
43
+ *
44
+ * Each guard's typed error surfaces unchanged and nothing is encoded when one fails. The builder is
45
+ * synchronous and pure: identical inputs give identical calldata.
46
+ *
47
+ * At most one ZeroExLeverageBundlesV1 call succeeds per transaction: bundles `3bf5314` keeps its transient initiator
48
+ * set until the transaction ends (L36, L49), so a second Lever, Delever or Close to the bundle in the same smart-account
49
+ * batch or ERC-4337 bundle reverts with `Reentrancy`. Send each one in its own transaction.
50
+ *
51
+ * @param params - Lever encoding parameters.
52
+ * @param params.market.chainId - Chain of the market and the bundle.
53
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
54
+ * @param params.args.userAddress - Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself.
55
+ * @param params.args.txOrigin - Optional sender of the outer onchain transaction (its `tx.origin`) when it is not
56
+ * `userAddress`, such as a Safe's executing owner or an ERC-4337 bundler. The quote must have been fetched with
57
+ * the same value. Defaults to `userAddress`.
58
+ * @param params.args.leverageData - One-block leverage data from `MorphoBlue.getLeverageData`.
59
+ * @param params.args.quote - Exact-output 0x quote for the collateral to buy.
60
+ * @param params.args.slippage - Caller slippage, WAD-scaled, at most 10%.
61
+ * @param params.args.collateralAssets - Collateral the user deposits.
62
+ * @param params.args.loanAssets - Loan assets the user deposits.
63
+ * @param params.args.reallocations - Planner-built reallocations toward this market.
64
+ * @param params.args.nativeAmount - Optional native token the bundle wraps into wNative before the pulls.
65
+ * @param params.metadata - Optional transaction metadata.
66
+ * @returns A deep-frozen `Readonly<Transaction<BlueLeverAction>>` calling
67
+ * `zeroExLeverageBundlesV1Lever` on the registered bundle.
68
+ * @throws {MarketIdMismatchError} when `marketParams` or the position's market tuple does not hash to its
69
+ * cached id, or the leverage data position or its market tuple is for another market.
70
+ * @throws {ChainIdMismatchError} when the leverage data was read on another chain.
71
+ * @throws {AccrualPositionUserMismatchError} when the leverage data position belongs to another user.
72
+ * @throws {InvalidBigIntInputError} when `collateralAssets`, `loanAssets`, `nativeAmount`, `slippage`,
73
+ * `quote.slippage`, or a reallocation's `assets` or `penalty` is not a bigint.
74
+ * @throws {NegativeInputError} when an intent amount, the slippage or a reallocation penalty is negative.
75
+ * @throws {InputExceedsMaxError} when an intent amount, a signed amount or the deadline exceeds `uint256`, when
76
+ * `loanAssets` exceeds the swap cap plus the penalty, when `nativeAmount` exceeds the pull of the wNative
77
+ * token, or when a reallocation exceeds its ABI bound.
78
+ * @throws {ZeroExQuoteTypeMismatchError} when the quote is not exact output.
79
+ * @throws {ZeroExQuoteRequiredError} when no quote is given.
80
+ * @throws {LeverageQuoteSlippageMismatchError} when the quote was fetched with another slippage than `slippage`.
81
+ * @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
82
+ * @throws {LeverageWorstFillLtvError} when the worst fill fails Blue's health check or `maxLtv`.
83
+ * @throws {LeverageOraclePriceDeviationError} when the quote's worst price is more than 15% above the market's
84
+ * oracle price.
85
+ * @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero.
86
+ * @throws {NonPositiveInputError} when a quote amount, a reallocation amount or the deadline is not positive.
87
+ * @throws {LeverageReallocationMarketMismatchError} when a reallocation targets another market.
88
+ * @throws {LeverageReallocationNoFlowError} when the allocator does not allow a reallocation's route.
89
+ * @throws {LeverageReallocationPenaltyAboveLimitError} when a reallocation's penalty rate exceeds 1%.
90
+ * @throws {LeverageReallocationExceedsBorrowError} when the reallocations move more than the borrow, including any
91
+ * reallocation of a Lever that borrows nothing.
92
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount` is positive and neither market token is the
93
+ * chain's wNative.
94
+ * @throws {ChainWNativeMissingError} when `nativeAmount` is positive and the chain registers no wNative.
95
+ * @throws {LeverageInsufficientLiquidityError} when the market's liquidity at the data block plus
96
+ * the reallocated assets cannot fund the borrow. Passing it does not make the Lever land: when
97
+ * `penaltyAssets` exceeds `loanAssets`, the bundle flash-loans the difference from Blue before it borrows, and
98
+ * the SDK does not check Blue's loan-token balance, so a Lever that pays a penalty can still revert onchain when
99
+ * Blue is short of cash.
100
+ * @throws {InconsistentReallocationPenaltyError} when a reallocation's penalty is not its vault's.
101
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdraws from the Lever's market.
102
+ * @throws {ReallocationLoanTokenMismatchError} when a reallocation's source uses another loan token.
103
+ * @throws {ZeroExQuoteAmountExceedsCapError} when the amount the quote's calldata lets Settler pull
104
+ * exceeds the swap cap.
105
+ * @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address; pass a valid one or omit it
106
+ * instead of fetching a new quote.
107
+ * @throws {ZeroExQuoteError} for any other quote mismatch documented on `validateZeroExQuote`.
108
+ * @throws {LeverageUnsupportedChainError} when the chain has no usable leverage bundle.
109
+ * @example
110
+ * ```ts
111
+ * import { blueLever, fetchZeroExQuote, leverageDeadline } from "@morpho-org/morpho-sdk";
112
+ *
113
+ * // leverageData = await client.morpho.blue(marketParams, chainId).getLeverageData({ userAddress });
114
+ * const quote = await fetchZeroExQuote({
115
+ * chainId,
116
+ * kind: "lever",
117
+ * marketParams,
118
+ * userAddress,
119
+ * amount: 2n * 10n ** 18n,
120
+ * slippage: 5_000_000_000_000_000n, // 0.5%, WAD-scaled (1e18 = 100%), not bps
121
+ * deadline: leverageDeadline(leverageData), // the deadline the Lever signs
122
+ * apiKey,
123
+ * });
124
+ * const tx = blueLever({
125
+ * market: { chainId, marketParams },
126
+ * args: {
127
+ * userAddress,
128
+ * leverageData,
129
+ * quote,
130
+ * slippage: 5_000_000_000_000_000n,
131
+ * collateralAssets: 10n ** 18n,
132
+ * loanAssets: 0n,
133
+ * },
134
+ * });
135
+ * // tx.to is the registered ZeroExLeverageBundlesV1; tx.action.args.maxBorrowAssets is the borrow.
136
+ * ```
137
+ */
138
+ export const blueLever = (params) => {
139
+ const { market: { chainId, marketParams }, args: { userAddress, leverageData, quote, slippage, collateralAssets, loanAssets, }, } = params;
140
+ validateMarketParamsId(marketParams);
141
+ validateChainId(leverageData.chainId, chainId);
142
+ validateAccrualPosition({
143
+ positionData: leverageData.position,
144
+ expectedMarketId: marketParams.id,
145
+ expectedUser: userAddress,
146
+ });
147
+ // The bounds come from the position's own market tuple, so it must be the expected market's.
148
+ validateLeveragePositionMarket(leverageData.position, marketParams);
149
+ // Checked before the quote's slippage, so a requote advice never names a slippage the quote fetch refuses.
150
+ validateLeverSlippage(slippage);
151
+ if (quote == null) {
152
+ throw new ZeroExQuoteRequiredError({ operation: "lever" });
153
+ }
154
+ validateLeverageQuoteSlippage({
155
+ operation: "lever",
156
+ slippage,
157
+ quoteSlippage: quote.slippage,
158
+ });
159
+ validateLeverageIntentAmount("collateralAssets", collateralAssets);
160
+ validateLeverageIntentAmount("loanAssets", loanAssets);
161
+ const bundle = getZeroExLeverageBundle(chainId);
162
+ const nativeFunding = validateLeverNativeAmount({
163
+ ...params.args,
164
+ chainId,
165
+ marketParams,
166
+ });
167
+ const requested = params.args.reallocations ?? [];
168
+ // The penalty below is computed before validateLeverageReallocations, so refuse non-bigint legs first.
169
+ for (const leg of requested) {
170
+ // Non-object and Vault V1-shaped legs are left to the shared shape check, which throws its typed error.
171
+ if (typeof leg !== "object" ||
172
+ leg === null ||
173
+ "withdrawals" in leg ||
174
+ "fee" in leg) {
175
+ continue;
176
+ }
177
+ if (typeof leg.assets !== "bigint") {
178
+ throw new InvalidBigIntInputError("reallocation.assets", leg.assets);
179
+ }
180
+ if (typeof leg.penalty !== "bigint") {
181
+ throw new InvalidBigIntInputError("reallocation.penalty", leg.penalty);
182
+ }
183
+ }
184
+ const { publicAllocations: reallocations } = parseBlueAllocations(requested, {
185
+ marketParams: parseBlueMarket(marketParams),
186
+ maxPenalty: MAX_REALLOCATION_PENALTY,
187
+ });
188
+ const limits = computeLeverLimits({
189
+ intent: { collateralAssets, loanAssets },
190
+ quote,
191
+ slippage,
192
+ leverageData,
193
+ penaltyAssets: computeLeveragePenaltyAssets(reallocations),
194
+ });
195
+ validateLeverageReallocations({
196
+ reallocations,
197
+ marketParams,
198
+ allocator: leverageData.reallocationData,
199
+ maxBorrowAssets: limits.maxBorrowAssets,
200
+ });
201
+ const reallocatedAssets = reallocations.reduce((total, { assets }) => total + assets, 0n);
202
+ const { liquidity } = leverageData.position.market;
203
+ if (liquidity + reallocatedAssets < limits.maxBorrowAssets) {
204
+ throw new LeverageInsufficientLiquidityError({
205
+ liquidity,
206
+ reallocatedAssets,
207
+ maxBorrowAssets: limits.maxBorrowAssets,
208
+ });
209
+ }
210
+ const swap = validateZeroExQuote({
211
+ quote,
212
+ kind: "lever",
213
+ chainId,
214
+ marketParams,
215
+ userAddress,
216
+ txOrigin: params.args.txOrigin,
217
+ maxSwapInput: limits.maxSwapIn,
218
+ deadline: limits.deadline,
219
+ });
220
+ const transaction = {
221
+ to: bundle,
222
+ value: nativeFunding.value,
223
+ data: encodeFunctionData({
224
+ abi: zeroExLeverageBundlesV1Abi,
225
+ functionName: "zeroExLeverageBundlesV1Lever",
226
+ args: [
227
+ marketParams,
228
+ collateralAssets,
229
+ loanAssets,
230
+ limits.minCollateralToBuy,
231
+ limits.maxBorrowAssets,
232
+ swap.swapData,
233
+ limits.maxLtv,
234
+ reallocations,
235
+ limits.penaltyAssets,
236
+ limits.deadline,
237
+ nativeFunding.wrappedNative,
238
+ ],
239
+ }),
240
+ };
241
+ return deepFreeze({
242
+ ...(params.metadata == null
243
+ ? transaction
244
+ : addTransactionMetadata(transaction, params.metadata)),
245
+ action: {
246
+ type: "blueLever",
247
+ args: {
248
+ market: marketParams.id,
249
+ onBehalf: userAddress,
250
+ collateralAssets,
251
+ loanAssets,
252
+ minCollateralToBuy: limits.minCollateralToBuy,
253
+ maxBorrowAssets: limits.maxBorrowAssets,
254
+ maxSwapIn: limits.maxSwapIn,
255
+ maxLtv: limits.maxLtv,
256
+ reallocations: reallocations.length,
257
+ penaltyAssets: limits.penaltyAssets,
258
+ settler: swap.settler,
259
+ oracleDeviation: { status: "measured", ...limits.oracleDeviation },
260
+ deadline: limits.deadline,
261
+ block: {
262
+ number: leverageData.block.number,
263
+ timestamp: leverageData.block.timestamp,
264
+ },
265
+ },
266
+ },
267
+ });
268
+ };
@@ -0,0 +1,65 @@
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
+ import { LeverageQuoteSlippageMismatchError } from "../../types/index.js";
3
+ /**
4
+ * Refuses a Lever intent amount that is not a bigint or does not fit in `uint256`, before any bigint
5
+ * arithmetic mixes it with a number.
6
+ *
7
+ * @param field - Intent field name reported in the error.
8
+ * @param value - Intent amount.
9
+ * @throws {InvalidBigIntInputError} when `value` is not a bigint.
10
+ * @throws {NegativeInputError} when `value` is negative.
11
+ * @throws {InputExceedsMaxError} when `value` exceeds `uint256`.
12
+ */
13
+ export declare const validateLeverageIntentAmount: (field: string, value: bigint) => void;
14
+ /**
15
+ * Refuses a Lever slippage that is not a bigint, is negative or exceeds the Lever's 10% limit. Callers run it
16
+ * before comparing the slippage with the quote's, so a requote advice never names a slippage the quote fetch
17
+ * refuses.
18
+ *
19
+ * @param slippage - Caller slippage, WAD-scaled.
20
+ * @throws {InvalidBigIntInputError} when `slippage` is not a bigint.
21
+ * @throws {NegativeInputError} when `slippage` is negative.
22
+ * @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds `LEVERAGE_MAX_EXECUTION_LOSS.lever`.
23
+ */
24
+ export declare const validateLeverSlippage: (slippage: bigint) => void;
25
+ /**
26
+ * Refuses a quote fetched with another slippage than the caller's. The quote's slippage is checked to be a bigint
27
+ * first, so a missing or malformed value is reported as such rather than as a slippage mismatch.
28
+ *
29
+ * @param params.operation - Leverage action the quote is for.
30
+ * @param params.slippage - Caller slippage, WAD-scaled, already validated.
31
+ * @param params.quoteSlippage - Slippage the quote was fetched with.
32
+ * @throws {InvalidBigIntInputError} when `quoteSlippage` is not a bigint (field `quote.slippage`).
33
+ * @throws {LeverageQuoteSlippageMismatchError} when `quoteSlippage` is not `slippage`.
34
+ */
35
+ export declare const validateLeverageQuoteSlippage: (params: {
36
+ readonly operation: LeverageQuoteSlippageMismatchError["operation"];
37
+ readonly slippage: bigint;
38
+ readonly quoteSlippage: bigint;
39
+ }) => void;
40
+ /**
41
+ * Validates a Lever's `nativeAmount` and returns the transaction `value` and the `wrappedNative` argument. The bundle
42
+ * wraps `nativeAmount` into the chain's wNative for the user before pulling `collateralAssets` and `loanAssets`.
43
+ *
44
+ * @param params.chainId - Chain used to resolve wNative.
45
+ * @param params.marketParams - Market whose collateral and loan tokens the Lever pulls.
46
+ * @param params.collateralAssets - Collateral pulled from the user.
47
+ * @param params.loanAssets - Loan assets pulled from the user.
48
+ * @param params.nativeAmount - Optional native token to wrap; omitted or zero sends no value.
49
+ * @returns The transaction `value` and the `wrappedNative` Lever argument (`zeroAddress` without native).
50
+ * @throws {InvalidBigIntInputError} when `nativeAmount` is given and is not a bigint.
51
+ * @throws {NegativeInputError} when `nativeAmount` is negative.
52
+ * @throws {ChainWNativeMissingError} when the chain has no wNative.
53
+ * @throws {NativeAmountOnNonWNativeAssetError} when neither market token is wNative.
54
+ * @throws {InputExceedsMaxError} when `nativeAmount` exceeds the wNative pull.
55
+ */
56
+ export declare const validateLeverNativeAmount: ({ chainId, marketParams, collateralAssets, loanAssets, nativeAmount, }: {
57
+ readonly chainId: number;
58
+ readonly marketParams: MarketParams;
59
+ readonly collateralAssets: bigint;
60
+ readonly loanAssets: bigint;
61
+ readonly nativeAmount?: bigint;
62
+ }) => {
63
+ value: bigint;
64
+ wrappedNative: import("viem").Address;
65
+ };
@@ -0,0 +1,96 @@
1
+ import { LEVERAGE_MAX_EXECUTION_LOSS } from "../../helpers/constant.js";
2
+ import { validateMidnightNativeAmount, validateUint256Field, } from "../../helpers/validate.js";
3
+ import { InvalidBigIntInputError, LeverageQuoteSlippageMismatchError, LeverageSlippageAboveLimitError, NegativeInputError, } from "../../types/index.js";
4
+ /**
5
+ * Refuses a Lever intent amount that is not a bigint or does not fit in `uint256`, before any bigint
6
+ * arithmetic mixes it with a number.
7
+ *
8
+ * @param field - Intent field name reported in the error.
9
+ * @param value - Intent amount.
10
+ * @throws {InvalidBigIntInputError} when `value` is not a bigint.
11
+ * @throws {NegativeInputError} when `value` is negative.
12
+ * @throws {InputExceedsMaxError} when `value` exceeds `uint256`.
13
+ */
14
+ export const validateLeverageIntentAmount = (field, value) => {
15
+ if (typeof value !== "bigint") {
16
+ throw new InvalidBigIntInputError(field, value);
17
+ }
18
+ validateUint256Field(field, value);
19
+ };
20
+ /**
21
+ * Refuses a Lever slippage that is not a bigint, is negative or exceeds the Lever's 10% limit. Callers run it
22
+ * before comparing the slippage with the quote's, so a requote advice never names a slippage the quote fetch
23
+ * refuses.
24
+ *
25
+ * @param slippage - Caller slippage, WAD-scaled.
26
+ * @throws {InvalidBigIntInputError} when `slippage` is not a bigint.
27
+ * @throws {NegativeInputError} when `slippage` is negative.
28
+ * @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds `LEVERAGE_MAX_EXECUTION_LOSS.lever`.
29
+ */
30
+ export const validateLeverSlippage = (slippage) => {
31
+ if (typeof slippage !== "bigint") {
32
+ throw new InvalidBigIntInputError("slippage", slippage);
33
+ }
34
+ if (slippage < 0n) {
35
+ throw new NegativeInputError("slippage", slippage);
36
+ }
37
+ if (slippage > LEVERAGE_MAX_EXECUTION_LOSS.lever) {
38
+ throw new LeverageSlippageAboveLimitError({
39
+ operation: "lever",
40
+ slippage,
41
+ max: LEVERAGE_MAX_EXECUTION_LOSS.lever,
42
+ });
43
+ }
44
+ };
45
+ /**
46
+ * Refuses a quote fetched with another slippage than the caller's. The quote's slippage is checked to be a bigint
47
+ * first, so a missing or malformed value is reported as such rather than as a slippage mismatch.
48
+ *
49
+ * @param params.operation - Leverage action the quote is for.
50
+ * @param params.slippage - Caller slippage, WAD-scaled, already validated.
51
+ * @param params.quoteSlippage - Slippage the quote was fetched with.
52
+ * @throws {InvalidBigIntInputError} when `quoteSlippage` is not a bigint (field `quote.slippage`).
53
+ * @throws {LeverageQuoteSlippageMismatchError} when `quoteSlippage` is not `slippage`.
54
+ */
55
+ export const validateLeverageQuoteSlippage = (params) => {
56
+ const { operation, slippage, quoteSlippage } = params;
57
+ if (typeof quoteSlippage !== "bigint") {
58
+ throw new InvalidBigIntInputError("quote.slippage", quoteSlippage);
59
+ }
60
+ if (quoteSlippage !== slippage) {
61
+ throw new LeverageQuoteSlippageMismatchError({
62
+ operation,
63
+ slippage,
64
+ quoteSlippage,
65
+ });
66
+ }
67
+ };
68
+ /**
69
+ * Validates a Lever's `nativeAmount` and returns the transaction `value` and the `wrappedNative` argument. The bundle
70
+ * wraps `nativeAmount` into the chain's wNative for the user before pulling `collateralAssets` and `loanAssets`.
71
+ *
72
+ * @param params.chainId - Chain used to resolve wNative.
73
+ * @param params.marketParams - Market whose collateral and loan tokens the Lever pulls.
74
+ * @param params.collateralAssets - Collateral pulled from the user.
75
+ * @param params.loanAssets - Loan assets pulled from the user.
76
+ * @param params.nativeAmount - Optional native token to wrap; omitted or zero sends no value.
77
+ * @returns The transaction `value` and the `wrappedNative` Lever argument (`zeroAddress` without native).
78
+ * @throws {InvalidBigIntInputError} when `nativeAmount` is given and is not a bigint.
79
+ * @throws {NegativeInputError} when `nativeAmount` is negative.
80
+ * @throws {ChainWNativeMissingError} when the chain has no wNative.
81
+ * @throws {NativeAmountOnNonWNativeAssetError} when neither market token is wNative.
82
+ * @throws {InputExceedsMaxError} when `nativeAmount` exceeds the wNative pull.
83
+ */
84
+ export const validateLeverNativeAmount = ({ chainId, marketParams, collateralAssets, loanAssets, nativeAmount, }) => {
85
+ if (nativeAmount !== undefined) {
86
+ validateLeverageIntentAmount("nativeAmount", nativeAmount);
87
+ }
88
+ return validateMidnightNativeAmount({
89
+ chainId,
90
+ nativeAmount,
91
+ pulls: [
92
+ { token: marketParams.collateralToken, assets: collateralAssets },
93
+ { token: marketParams.loanToken, assets: loanAssets },
94
+ ],
95
+ });
96
+ };
@@ -0,0 +1,39 @@
1
+ import { type Address } from "viem";
2
+ import type { BlueAuthorizationAction, Transaction } from "../../../types/index.js";
3
+ /**
4
+ * Encodes Morpho Blue `setAuthorization(zeroExLeverageBundlesV1, isAuthorized)` for the chain's
5
+ * registered ZeroExLeverageBundlesV1.
6
+ *
7
+ * Lever with a borrow, Delever and Close act on the sender's Blue position through the bundle, so
8
+ * Blue requires this authorization. It is global over every Blue position of the user and persists
9
+ * after the action; pass `isAuthorized: false` to revoke it. A revoke can name the `operator` to clear,
10
+ * such as a bundle the registry no longer lists or now lists at another address; a grant always names
11
+ * the registered bundle.
12
+ *
13
+ * @param params.chainId - The chain the transaction targets.
14
+ * @param params.isAuthorized - `true` to grant, `false` to revoke.
15
+ * @param params.operator - Revoke only: the address to deauthorize. Defaults to the registered bundle.
16
+ * @returns A deep-frozen `Transaction<BlueAuthorizationAction>` sent to Morpho Blue.
17
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the address registry.
18
+ * @throws {LeverageUnsupportedChainError} when the chain registers no leverage bundle and a revoke names
19
+ * no `operator`, or, for a grant only, when the bundle cannot run on the chain.
20
+ * @throws {viem.InvalidAddressError} when a revoke's `operator` is not an address.
21
+ * @example
22
+ * ```ts
23
+ * import { encodeLeverageAuthorization } from "@morpho-org/morpho-sdk";
24
+ *
25
+ * // None ships yet: register a verified zeroExLeverageBundlesV1 address with `registerCustomAddresses` first,
26
+ * // otherwise it throws `LeverageUnsupportedChainError` with `reason: "noBundle"`.
27
+ * const grant = encodeLeverageAuthorization({ chainId: 8453, isAuthorized: true });
28
+ * // grant.action.args satisfies { authorized: zeroExLeverageBundlesV1, isAuthorized: true }
29
+ * const revokeOld = encodeLeverageAuthorization({ chainId: 8453, isAuthorized: false, operator: oldBundle });
30
+ * ```
31
+ */
32
+ export declare const encodeLeverageAuthorization: (params: {
33
+ readonly chainId: number;
34
+ readonly isAuthorized: true;
35
+ } | {
36
+ readonly chainId: number;
37
+ readonly isAuthorized: false;
38
+ readonly operator?: Address;
39
+ }) => Readonly<Transaction<BlueAuthorizationAction>>;
@@ -0,0 +1,55 @@
1
+ import { getChainAddresses } from "@morpho-org/blue-sdk";
2
+ import { blueAbi } from "@morpho-org/blue-sdk-viem";
3
+ import { deepFreeze } from "@morpho-org/morpho-ts";
4
+ import { encodeFunctionData } from "viem";
5
+ import { getRegisteredZeroExLeverageBundle } from "../../../helpers/getZeroExLeverageBundle.js";
6
+ import { getZeroExLeverageBundle } from "../../../helpers/zeroExQuote.js";
7
+ /**
8
+ * Encodes Morpho Blue `setAuthorization(zeroExLeverageBundlesV1, isAuthorized)` for the chain's
9
+ * registered ZeroExLeverageBundlesV1.
10
+ *
11
+ * Lever with a borrow, Delever and Close act on the sender's Blue position through the bundle, so
12
+ * Blue requires this authorization. It is global over every Blue position of the user and persists
13
+ * after the action; pass `isAuthorized: false` to revoke it. A revoke can name the `operator` to clear,
14
+ * such as a bundle the registry no longer lists or now lists at another address; a grant always names
15
+ * the registered bundle.
16
+ *
17
+ * @param params.chainId - The chain the transaction targets.
18
+ * @param params.isAuthorized - `true` to grant, `false` to revoke.
19
+ * @param params.operator - Revoke only: the address to deauthorize. Defaults to the registered bundle.
20
+ * @returns A deep-frozen `Transaction<BlueAuthorizationAction>` sent to Morpho Blue.
21
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the address registry.
22
+ * @throws {LeverageUnsupportedChainError} when the chain registers no leverage bundle and a revoke names
23
+ * no `operator`, or, for a grant only, when the bundle cannot run on the chain.
24
+ * @throws {viem.InvalidAddressError} when a revoke's `operator` is not an address.
25
+ * @example
26
+ * ```ts
27
+ * import { encodeLeverageAuthorization } from "@morpho-org/morpho-sdk";
28
+ *
29
+ * // None ships yet: register a verified zeroExLeverageBundlesV1 address with `registerCustomAddresses` first,
30
+ * // otherwise it throws `LeverageUnsupportedChainError` with `reason: "noBundle"`.
31
+ * const grant = encodeLeverageAuthorization({ chainId: 8453, isAuthorized: true });
32
+ * // grant.action.args satisfies { authorized: zeroExLeverageBundlesV1, isAuthorized: true }
33
+ * const revokeOld = encodeLeverageAuthorization({ chainId: 8453, isAuthorized: false, operator: oldBundle });
34
+ * ```
35
+ */
36
+ export const encodeLeverageAuthorization = (params) => {
37
+ const { chainId, isAuthorized } = params;
38
+ // Only a grant needs the bundle to be usable; a revoke must still clear a delisted or replaced bundle.
39
+ const authorized = params.isAuthorized
40
+ ? getZeroExLeverageBundle(chainId)
41
+ : (params.operator ?? getRegisteredZeroExLeverageBundle(chainId));
42
+ return deepFreeze({
43
+ to: getChainAddresses(chainId).blue,
44
+ data: encodeFunctionData({
45
+ abi: blueAbi,
46
+ functionName: "setAuthorization",
47
+ args: [authorized, isAuthorized],
48
+ }),
49
+ value: 0n,
50
+ action: {
51
+ type: "blueAuthorization",
52
+ args: { authorized, isAuthorized },
53
+ },
54
+ });
55
+ };
@@ -0,0 +1,104 @@
1
+ import { type MarketParams } from "@morpho-org/blue-sdk";
2
+ import { type Address, type Client } from "viem";
3
+ import { type BlueAuthorizationAction, type ERC20ApprovalAction, type Transaction } from "../../../types/index.js";
4
+ /**
5
+ * Leverage entry point whose prerequisites to resolve. Lever carries the amounts its entry point
6
+ * pulls from the user and its borrow cap; Delever and Close pull nothing from the user.
7
+ */
8
+ export type LeverageRequirementsOperation = {
9
+ readonly type: "lever";
10
+ /** Collateral the bundle pulls from the user. */
11
+ readonly collateralAssets: bigint;
12
+ /** Loan assets the bundle pulls from the user. */
13
+ readonly loanAssets: bigint;
14
+ /**
15
+ * The built Lever's `maxBorrowAssets`: pass `tx.action.args.maxBorrowAssets` of the transaction the Lever
16
+ * builder returned, never an estimate. A borrow needs the Blue authorization, so a different value can skip
17
+ * the grant and make the Lever revert on Blue.
18
+ */
19
+ readonly maxBorrowAssets: bigint;
20
+ } | {
21
+ readonly type: "delever";
22
+ } | {
23
+ readonly type: "close";
24
+ };
25
+ /**
26
+ * Resolves the transactions a user submits before a ZeroExLeverageBundlesV1 action: ERC-20
27
+ * approvals for the tokens it pulls, then the Morpho Blue authorization when its entry point
28
+ * needs one.
29
+ *
30
+ * Reads the user's allowance for each pulled token and `Morpho.isAuthorized(user, bundle)` on the
31
+ * target chain. For the leverage bundle the SDK ships it reads no contract code: `MorphoBlue.lever`, `delever` and
32
+ * `close` check Morpho Blue's code before calling it, and the shipped bundle's code check is waived
33
+ * (`docs/EXCEPTIONS.md`). A bundle registered with `registerCustomAddresses` falls back to the default rules: its code
34
+ * is checked before any read or grant, and its approvals are exact.
35
+ *
36
+ * - **Lever** pulls `collateralAssets` of the collateral token and `loanAssets` of the loan token
37
+ * from the user; when the allowance is short, each gets an unlimited approval (`maxUint256`,
38
+ * capped per token by `MAX_TOKEN_APPROVALS`), as for the other bundles, or an approval of exactly the pulled
39
+ * amount for a bundle the SDK does not ship. It borrows on Blue only
40
+ * when `maxBorrowAssets > 0`, so only then does it need the authorization.
41
+ * - **Delever** and **Close** pull nothing from the user and always withdraw collateral on Blue,
42
+ * so they need the authorization and no approval.
43
+ *
44
+ * The allowance and authorization reads run in parallel, each at the latest block its request sees; they are not
45
+ * pinned to one block, so a block landing between them can mix two states. The result is a snapshot of those
46
+ * reads: a requirement missed that way makes the action revert, and a returned approval still calls `approve` and
47
+ * replaces the allowance, with the zero reset of an approve-once token such as USDT planned from the allowance
48
+ * read. If the allowance or the authorization may have changed before submission, resolve the requirements again.
49
+ *
50
+ * The authorization is global over the user's Blue positions and persists after the action, like
51
+ * the unlimited approvals. The bundle takes no signed authorization, so no signature requirement
52
+ * is returned.
53
+ *
54
+ * @param params.viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
55
+ * @param params.chainId - Target chain id.
56
+ * @param params.userAddress - The account that sends the leverage transaction.
57
+ * @param params.marketParams - The market's loan and collateral tokens.
58
+ * @param params.operation - The leverage entry point and, for Lever, its pulled amounts.
59
+ * @returns Deep-frozen transactions in submission order: approvals (each optionally preceded by a
60
+ * reset to zero), then the authorization grant. Empty when nothing is missing.
61
+ * @throws {InvalidLeverageOperationError} when `operation` is missing or not an object, its `type` is
62
+ * not `lever`, `delever` or `close`, a Lever amount is not a bigint, or `userAddress` or a market token is
63
+ * not an address, before any read.
64
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, a
65
+ * chain other than `params.chainId`.
66
+ * @throws {LeverageUnsupportedChainError} when the chain has no usable leverage bundle; a chain absent from the
67
+ * address registry reports `noAllowanceHolder`.
68
+ * @throws {MissingContractCodeError} when the chain's leverage bundle is not the one the SDK ships and has no code.
69
+ * @throws {NegativeInputError} when a Lever amount is negative.
70
+ * @throws {InputExceedsMaxError} when a Lever amount exceeds `uint256`; before any read,
71
+ * with `field: "amount"`, when the sum of both amounts on a market whose loan and collateral
72
+ * tokens are equal exceeds `uint256`.
73
+ * @throws {viem.BaseError} when the `eth_chainId` request or an allowance or authorization read
74
+ * fails.
75
+ * @example
76
+ * ```ts
77
+ * import { createPublicClient, http } from "viem";
78
+ * import { base } from "viem/chains";
79
+ * import { getLeverageRequirements } from "@morpho-org/morpho-sdk";
80
+ *
81
+ * const client = createPublicClient({ chain: base, transport: http() });
82
+ * // `leverTx`: the built Lever transaction; its args carry the amounts the Lever signs.
83
+ * const { collateralAssets, loanAssets, maxBorrowAssets } = leverTx.action.args;
84
+ * // None ships yet: register a verified zeroExLeverageBundlesV1 address with `registerCustomAddresses` first,
85
+ * // otherwise it throws `LeverageUnsupportedChainError` with `reason: "noBundle"`.
86
+ * const requirements = await getLeverageRequirements({
87
+ * viemClient: client,
88
+ * chainId: base.id,
89
+ * userAddress,
90
+ * marketParams,
91
+ * // Here collateralAssets is 1_000000000000000000n and loanAssets 0n.
92
+ * operation: { type: "lever", collateralAssets, loanAssets, maxBorrowAssets },
93
+ * });
94
+ * // requirements: [approve(bundle, 1_000000000000000000n), setAuthorization(bundle, true)] when both are
95
+ * // missing: a registered bundle is approved exactly the pull; the bundle morpho-ts ships gets maxUint256.
96
+ * ```
97
+ */
98
+ export declare const getLeverageRequirements: (params: {
99
+ readonly viemClient: Client;
100
+ readonly chainId: number;
101
+ readonly userAddress: Address;
102
+ readonly marketParams: Pick<MarketParams, "loanToken" | "collateralToken">;
103
+ readonly operation: LeverageRequirementsOperation;
104
+ }) => Promise<readonly Readonly<Transaction<ERC20ApprovalAction | BlueAuthorizationAction>>[]>;