@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,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
+ };
@@ -97,31 +97,31 @@ export const midnightSupplyCollateralTakeBorrow = (params) => encodeMidnightSupp
97
97
  const parsedSupplyCollateralTakeBorrow = Symbol();
98
98
  /** Parses the static SupplyCollateralTakeBorrow constraints in the standalone builder's existing order. @internal */
99
99
  export const parseMidnightSupplyCollateralTakeBorrow = (params) => {
100
+ const { market, target, takeableOffers } = params;
100
101
  // Reject markets from another chain deployment before checking offers against them.
101
- validateMidnightMarket({ market: params.market, chainId: params.chainId });
102
+ validateMidnightMarket({ market, chainId: params.chainId });
102
103
  if (params.collateralSupplies.length === 0) {
103
104
  throw new EmptyMidnightCollateralSuppliesError();
104
105
  }
105
106
  // Validation only; retain main's canonical per-entry and per-index collateral checks.
106
107
  validateMidnightCollateralSupplies({
107
- market: params.market,
108
+ market,
108
109
  field: "collateralSupplies",
109
110
  supplies: params.collateralSupplies,
110
111
  });
111
112
  const marketId = validateTakeableOffers({
112
- market: params.market,
113
- takeableOffers: params.takeableOffers,
113
+ market,
114
+ takeableOffers,
114
115
  expectedBuy: true,
115
116
  });
116
- validateMidnightTakeableOfferBounds(params.takeableOffers);
117
+ validateMidnightTakeableOfferBounds(takeableOffers);
117
118
  // Rejects receivers that would strand the borrowed assets in a contract.
118
119
  validateMidnightReceiver({
119
120
  chainId: params.chainId,
120
- market: params.market,
121
+ market,
121
122
  field: "receiver",
122
123
  receiver: params.receiver,
123
124
  });
124
- const { target } = params;
125
125
  switch (target.type) {
126
126
  case "assets": {
127
127
  // Validation only; rejects non-positive amounts.
@@ -161,7 +161,7 @@ export const parseMidnightSupplyCollateralTakeBorrow = (params) => {
161
161
  // Rejects fee recipients that would strand the fee in a contract.
162
162
  validateMidnightReceiver({
163
163
  chainId: params.chainId,
164
- market: params.market,
164
+ market,
165
165
  field: "referralFeeRecipient",
166
166
  receiver: referralFeeRecipient,
167
167
  });
@@ -169,15 +169,20 @@ export const parseMidnightSupplyCollateralTakeBorrow = (params) => {
169
169
  const collateralSupplies = params.collateralSupplies.map(({ collateralIndex, assets }) => ({
170
170
  collateralIndex,
171
171
  assets,
172
- token: MarketUtils.getCollateralByIndex(params.market, collateralIndex)
173
- .token,
172
+ token: MarketUtils.getCollateralByIndex(market, collateralIndex).token,
174
173
  }));
175
174
  const nativeFunding = parseMidnightNativeFunding({
176
175
  chainId: params.chainId,
177
176
  nativeAmount: params.nativeAmount,
178
177
  pulls: collateralSupplies,
179
178
  });
180
- const snapshot = snapshotMidnightTakeParams({ ...params, direction: "sell" });
179
+ const snapshot = snapshotMidnightTakeParams({
180
+ direction: "sell",
181
+ market,
182
+ target,
183
+ takeableOffers,
184
+ metadata: params.metadata,
185
+ });
181
186
  return deepFreeze({
182
187
  ...snapshot,
183
188
  chainId: params.chainId,
@@ -81,22 +81,22 @@ export const midnightTakeBorrow = (params) => encodeMidnightTakeBorrow(parseMidn
81
81
  const parsedTakeBorrow = Symbol();
82
82
  /** Parses the static TakeBorrow constraints in the standalone builder's existing order. @internal */
83
83
  export const parseMidnightTakeBorrow = (params) => {
84
+ const { market, target, takeableOffers } = params;
84
85
  // Reject markets from another chain deployment before checking offers against them.
85
- validateMidnightMarket({ market: params.market, chainId: params.chainId });
86
+ validateMidnightMarket({ market, chainId: params.chainId });
86
87
  const marketId = validateTakeableOffers({
87
- market: params.market,
88
- takeableOffers: params.takeableOffers,
88
+ market,
89
+ takeableOffers,
89
90
  expectedBuy: true,
90
91
  });
91
- validateMidnightTakeableOfferBounds(params.takeableOffers);
92
+ validateMidnightTakeableOfferBounds(takeableOffers);
92
93
  // Rejects receivers that would strand the borrowed assets in a contract.
93
94
  validateMidnightReceiver({
94
95
  chainId: params.chainId,
95
- market: params.market,
96
+ market,
96
97
  field: "receiver",
97
98
  receiver: params.receiver,
98
99
  });
99
- const { target } = params;
100
100
  switch (target.type) {
101
101
  case "assets": {
102
102
  // Validation only; rejects non-positive amounts.
@@ -136,12 +136,18 @@ export const parseMidnightTakeBorrow = (params) => {
136
136
  // Rejects fee recipients that would strand the fee in a contract.
137
137
  validateMidnightReceiver({
138
138
  chainId: params.chainId,
139
- market: params.market,
139
+ market,
140
140
  field: "referralFeeRecipient",
141
141
  receiver: referralFeeRecipient,
142
142
  });
143
143
  }
144
- const snapshot = snapshotMidnightTakeParams({ ...params, direction: "sell" });
144
+ const snapshot = snapshotMidnightTakeParams({
145
+ direction: "sell",
146
+ market,
147
+ target,
148
+ takeableOffers,
149
+ metadata: params.metadata,
150
+ });
145
151
  return deepFreeze({
146
152
  ...snapshot,
147
153
  chainId: params.chainId,
@@ -81,15 +81,15 @@ export const midnightTakeLend = (params) => encodeMidnightTakeLend(parseMidnight
81
81
  const parsedTakeLend = Symbol();
82
82
  /** Parses the static TakeLend constraints in the standalone builder's existing order. @internal */
83
83
  export const parseMidnightTakeLend = (params) => {
84
+ const { market, target, takeableOffers } = params;
84
85
  // Reject markets from another chain deployment before checking offers against them.
85
- validateMidnightMarket({ market: params.market, chainId: params.chainId });
86
+ validateMidnightMarket({ market, chainId: params.chainId });
86
87
  const marketId = validateTakeableOffers({
87
- market: params.market,
88
- takeableOffers: params.takeableOffers,
88
+ market,
89
+ takeableOffers,
89
90
  expectedBuy: false,
90
91
  });
91
- validateMidnightTakeableOfferBounds(params.takeableOffers);
92
- const { target } = params;
92
+ validateMidnightTakeableOfferBounds(takeableOffers);
93
93
  switch (target.type) {
94
94
  case "assets": {
95
95
  // Validation only; rejects non-positive amounts.
@@ -129,23 +129,29 @@ export const parseMidnightTakeLend = (params) => {
129
129
  // Rejects fee recipients that would strand the fee in a contract.
130
130
  validateMidnightReceiver({
131
131
  chainId: params.chainId,
132
- market: params.market,
132
+ market,
133
133
  field: "referralFeeRecipient",
134
134
  receiver: referralFeeRecipient,
135
135
  });
136
136
  }
137
- const market = MarketUtils.toStruct(params.market);
137
+ const marketStruct = MarketUtils.toStruct(market);
138
138
  const nativeFunding = parseMidnightNativeFunding({
139
139
  chainId: params.chainId,
140
140
  nativeAmount: params.nativeAmount,
141
141
  pulls: [
142
142
  {
143
- token: market.loanToken,
143
+ token: marketStruct.loanToken,
144
144
  assets: target.type === "assets" ? target.assets : target.maxBuyerAssets,
145
145
  },
146
146
  ],
147
147
  });
148
- const snapshot = snapshotMidnightTakeParams({ ...params, direction: "buy" });
148
+ const snapshot = snapshotMidnightTakeParams({
149
+ direction: "buy",
150
+ market,
151
+ target,
152
+ takeableOffers,
153
+ metadata: params.metadata,
154
+ });
149
155
  return deepFreeze({
150
156
  ...snapshot,
151
157
  chainId: params.chainId,