@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,272 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.blueLever = void 0;
4
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ const viem_1 = require("viem");
6
+ const abis_js_1 = require("../../abis.js");
7
+ const constant_js_1 = require("../../helpers/constant.js");
8
+ const limits_js_1 = require("../../helpers/leverage/limits.js");
9
+ const positionMarket_js_1 = require("../../helpers/leverage/positionMarket.js");
10
+ const reallocations_js_1 = require("../../helpers/leverage/reallocations.js");
11
+ const metadata_js_1 = require("../../helpers/metadata.js");
12
+ const parse_js_1 = require("../../helpers/parse.js");
13
+ const validate_js_1 = require("../../helpers/validate.js");
14
+ const zeroExQuote_js_1 = require("../../helpers/zeroExQuote.js");
15
+ const index_js_1 = require("../../types/index.js");
16
+ const common_js_1 = require("./common.js");
17
+ const leverageIntent_js_1 = require("./leverageIntent.js");
18
+ /**
19
+ * Encodes a ZeroExLeverageBundlesV1 Lever: pulls `collateralAssets` and `loanAssets` from the user,
20
+ * executes the planned BluePublicAllocator reallocations, borrows `maxBorrowAssets` and buys at least
21
+ * the quote's `buyAmount` (`minCollateralToBuy`) of collateral through 0x, all in one call to the chain's
22
+ * registered bundle. The bundle also accepts a 0x SELL quote, but the SDK builds Lever from exact-output quotes only.
23
+ *
24
+ * With a positive `nativeAmount`, the transaction sends it as `value` and the bundle wraps it into the chain's
25
+ * wNative (`wrappedNative`) and transfers it to the user before the pulls, so the user's wNative approval still
26
+ * covers the whole pull. Without it, `value` is zero and `wrappedNative` the zero address.
27
+ *
28
+ * Every bound is computed, none is taken from the caller:
29
+ * - `computeLeverLimits` takes the quote's `maxSellAmount` as the swap cap (0x already applied the
30
+ * slippage, and the Settler pulls that whole amount) and derives the borrow and `maxLtv` (LLTV minus `DEFAULT_LLTV_BUFFER`, never `type(uint256).max`). It
31
+ * refuses a worst fill that fails Blue's mid-flow health check (`check: "health"`) or `maxLtv`
32
+ * (`check: "maxLtv"`), refuses a worst swap price (`maxSwapIn` per `minCollateralToBuy`) more than
33
+ * `LEVERAGE_MAX_ORACLE_DEVIATION` (15%) above the market's oracle price (a lower price is never refused), and fixes the deadline one hour
34
+ * after the data block. The price and the debt are the data block's; until the deadline only the signed `maxLtv`
35
+ * and Blue's health check guard execution. The deviation compares `maxSwapIn` alone: reallocation penalties
36
+ * (`penaltyAssets`, at most 1% each) are paid on top.
37
+ * - `penaltyAssets` is each reallocation's penalty rounded up, then summed, as the bundle checks it. A Lever
38
+ * that borrows nothing takes no reallocation, as the bundle reverts with `InconsistentBorrowInput` otherwise.
39
+ * `validateLeverageReallocations` refuses a reallocation to another market, through a route the
40
+ * allocator does not allow at the data block, above the 1% penalty ceiling, or reallocations
41
+ * that move more than the borrow. It does not check remaining caps or IRM compatibility, so pass
42
+ * only reallocations `VaultV2BlueReallocationData` planned for this borrow, as `MorphoBlue.lever`
43
+ * does.
44
+ * - `validateZeroExQuote` decodes the swap against the market's tokens, the bundle and the swap cap. It does not
45
+ * check whether the swap's Settler is 0x's official one or paused; the bundle's `maxIn` bounds the swap.
46
+ *
47
+ * Each guard's typed error surfaces unchanged and nothing is encoded when one fails. The builder is
48
+ * synchronous and pure: identical inputs give identical calldata.
49
+ *
50
+ * At most one ZeroExLeverageBundlesV1 call succeeds per transaction: bundles `3bf5314` keeps its transient initiator
51
+ * set until the transaction ends (L36, L49), so a second Lever, Delever or Close to the bundle in the same smart-account
52
+ * batch or ERC-4337 bundle reverts with `Reentrancy`. Send each one in its own transaction.
53
+ *
54
+ * @param params - Lever encoding parameters.
55
+ * @param params.market.chainId - Chain of the market and the bundle.
56
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
57
+ * @param params.args.userAddress - Wallet that owns the position and calls the bundle (`msg.sender`), such as the smart account itself.
58
+ * @param params.args.txOrigin - Optional sender of the outer onchain transaction (its `tx.origin`) when it is not
59
+ * `userAddress`, such as a Safe's executing owner or an ERC-4337 bundler. The quote must have been fetched with
60
+ * the same value. Defaults to `userAddress`.
61
+ * @param params.args.leverageData - One-block leverage data from `MorphoBlue.getLeverageData`.
62
+ * @param params.args.quote - Exact-output 0x quote for the collateral to buy.
63
+ * @param params.args.slippage - Caller slippage, WAD-scaled, at most 10%.
64
+ * @param params.args.collateralAssets - Collateral the user deposits.
65
+ * @param params.args.loanAssets - Loan assets the user deposits.
66
+ * @param params.args.reallocations - Planner-built reallocations toward this market.
67
+ * @param params.args.nativeAmount - Optional native token the bundle wraps into wNative before the pulls.
68
+ * @param params.metadata - Optional transaction metadata.
69
+ * @returns A deep-frozen `Readonly<Transaction<BlueLeverAction>>` calling
70
+ * `zeroExLeverageBundlesV1Lever` on the registered bundle.
71
+ * @throws {MarketIdMismatchError} when `marketParams` or the position's market tuple does not hash to its
72
+ * cached id, or the leverage data position or its market tuple is for another market.
73
+ * @throws {ChainIdMismatchError} when the leverage data was read on another chain.
74
+ * @throws {AccrualPositionUserMismatchError} when the leverage data position belongs to another user.
75
+ * @throws {InvalidBigIntInputError} when `collateralAssets`, `loanAssets`, `nativeAmount`, `slippage`,
76
+ * `quote.slippage`, or a reallocation's `assets` or `penalty` is not a bigint.
77
+ * @throws {NegativeInputError} when an intent amount, the slippage or a reallocation penalty is negative.
78
+ * @throws {InputExceedsMaxError} when an intent amount, a signed amount or the deadline exceeds `uint256`, when
79
+ * `loanAssets` exceeds the swap cap plus the penalty, when `nativeAmount` exceeds the pull of the wNative
80
+ * token, or when a reallocation exceeds its ABI bound.
81
+ * @throws {ZeroExQuoteTypeMismatchError} when the quote is not exact output.
82
+ * @throws {ZeroExQuoteRequiredError} when no quote is given.
83
+ * @throws {LeverageQuoteSlippageMismatchError} when the quote was fetched with another slippage than `slippage`.
84
+ * @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds 10%.
85
+ * @throws {LeverageWorstFillLtvError} when the worst fill fails Blue's health check or `maxLtv`.
86
+ * @throws {LeverageOraclePriceDeviationError} when the quote's worst price is more than 15% above the market's
87
+ * oracle price.
88
+ * @throws {LeverageOraclePriceUnavailableError} when the market's oracle price is unknown or zero.
89
+ * @throws {NonPositiveInputError} when a quote amount, a reallocation amount or the deadline is not positive.
90
+ * @throws {LeverageReallocationMarketMismatchError} when a reallocation targets another market.
91
+ * @throws {LeverageReallocationNoFlowError} when the allocator does not allow a reallocation's route.
92
+ * @throws {LeverageReallocationPenaltyAboveLimitError} when a reallocation's penalty rate exceeds 1%.
93
+ * @throws {LeverageReallocationExceedsBorrowError} when the reallocations move more than the borrow, including any
94
+ * reallocation of a Lever that borrows nothing.
95
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount` is positive and neither market token is the
96
+ * chain's wNative.
97
+ * @throws {ChainWNativeMissingError} when `nativeAmount` is positive and the chain registers no wNative.
98
+ * @throws {LeverageInsufficientLiquidityError} when the market's liquidity at the data block plus
99
+ * the reallocated assets cannot fund the borrow. Passing it does not make the Lever land: when
100
+ * `penaltyAssets` exceeds `loanAssets`, the bundle flash-loans the difference from Blue before it borrows, and
101
+ * the SDK does not check Blue's loan-token balance, so a Lever that pays a penalty can still revert onchain when
102
+ * Blue is short of cash.
103
+ * @throws {InconsistentReallocationPenaltyError} when a reallocation's penalty is not its vault's.
104
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdraws from the Lever's market.
105
+ * @throws {ReallocationLoanTokenMismatchError} when a reallocation's source uses another loan token.
106
+ * @throws {ZeroExQuoteAmountExceedsCapError} when the amount the quote's calldata lets Settler pull
107
+ * exceeds the swap cap.
108
+ * @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address; pass a valid one or omit it
109
+ * instead of fetching a new quote.
110
+ * @throws {ZeroExQuoteError} for any other quote mismatch documented on `validateZeroExQuote`.
111
+ * @throws {LeverageUnsupportedChainError} when the chain has no usable leverage bundle.
112
+ * @example
113
+ * ```ts
114
+ * import { blueLever, fetchZeroExQuote, leverageDeadline } from "@morpho-org/morpho-sdk";
115
+ *
116
+ * // leverageData = await client.morpho.blue(marketParams, chainId).getLeverageData({ userAddress });
117
+ * const quote = await fetchZeroExQuote({
118
+ * chainId,
119
+ * kind: "lever",
120
+ * marketParams,
121
+ * userAddress,
122
+ * amount: 2n * 10n ** 18n,
123
+ * slippage: 5_000_000_000_000_000n, // 0.5%, WAD-scaled (1e18 = 100%), not bps
124
+ * deadline: leverageDeadline(leverageData), // the deadline the Lever signs
125
+ * apiKey,
126
+ * });
127
+ * const tx = blueLever({
128
+ * market: { chainId, marketParams },
129
+ * args: {
130
+ * userAddress,
131
+ * leverageData,
132
+ * quote,
133
+ * slippage: 5_000_000_000_000_000n,
134
+ * collateralAssets: 10n ** 18n,
135
+ * loanAssets: 0n,
136
+ * },
137
+ * });
138
+ * // tx.to is the registered ZeroExLeverageBundlesV1; tx.action.args.maxBorrowAssets is the borrow.
139
+ * ```
140
+ */
141
+ const blueLever = (params) => {
142
+ const { market: { chainId, marketParams }, args: { userAddress, leverageData, quote, slippage, collateralAssets, loanAssets, }, } = params;
143
+ (0, validate_js_1.validateMarketParamsId)(marketParams);
144
+ (0, validate_js_1.validateChainId)(leverageData.chainId, chainId);
145
+ (0, validate_js_1.validateAccrualPosition)({
146
+ positionData: leverageData.position,
147
+ expectedMarketId: marketParams.id,
148
+ expectedUser: userAddress,
149
+ });
150
+ // The bounds come from the position's own market tuple, so it must be the expected market's.
151
+ (0, positionMarket_js_1.validateLeveragePositionMarket)(leverageData.position, marketParams);
152
+ // Checked before the quote's slippage, so a requote advice never names a slippage the quote fetch refuses.
153
+ (0, leverageIntent_js_1.validateLeverSlippage)(slippage);
154
+ if (quote == null) {
155
+ throw new index_js_1.ZeroExQuoteRequiredError({ operation: "lever" });
156
+ }
157
+ (0, leverageIntent_js_1.validateLeverageQuoteSlippage)({
158
+ operation: "lever",
159
+ slippage,
160
+ quoteSlippage: quote.slippage,
161
+ });
162
+ (0, leverageIntent_js_1.validateLeverageIntentAmount)("collateralAssets", collateralAssets);
163
+ (0, leverageIntent_js_1.validateLeverageIntentAmount)("loanAssets", loanAssets);
164
+ const bundle = (0, zeroExQuote_js_1.getZeroExLeverageBundle)(chainId);
165
+ const nativeFunding = (0, leverageIntent_js_1.validateLeverNativeAmount)({
166
+ ...params.args,
167
+ chainId,
168
+ marketParams,
169
+ });
170
+ const requested = params.args.reallocations ?? [];
171
+ // The penalty below is computed before validateLeverageReallocations, so refuse non-bigint legs first.
172
+ for (const leg of requested) {
173
+ // Non-object and Vault V1-shaped legs are left to the shared shape check, which throws its typed error.
174
+ if (typeof leg !== "object" ||
175
+ leg === null ||
176
+ "withdrawals" in leg ||
177
+ "fee" in leg) {
178
+ continue;
179
+ }
180
+ if (typeof leg.assets !== "bigint") {
181
+ throw new index_js_1.InvalidBigIntInputError("reallocation.assets", leg.assets);
182
+ }
183
+ if (typeof leg.penalty !== "bigint") {
184
+ throw new index_js_1.InvalidBigIntInputError("reallocation.penalty", leg.penalty);
185
+ }
186
+ }
187
+ const { publicAllocations: reallocations } = (0, common_js_1.parseBlueAllocations)(requested, {
188
+ marketParams: (0, parse_js_1.parseBlueMarket)(marketParams),
189
+ maxPenalty: constant_js_1.MAX_REALLOCATION_PENALTY,
190
+ });
191
+ const limits = (0, limits_js_1.computeLeverLimits)({
192
+ intent: { collateralAssets, loanAssets },
193
+ quote,
194
+ slippage,
195
+ leverageData,
196
+ penaltyAssets: (0, reallocations_js_1.computeLeveragePenaltyAssets)(reallocations),
197
+ });
198
+ (0, reallocations_js_1.validateLeverageReallocations)({
199
+ reallocations,
200
+ marketParams,
201
+ allocator: leverageData.reallocationData,
202
+ maxBorrowAssets: limits.maxBorrowAssets,
203
+ });
204
+ const reallocatedAssets = reallocations.reduce((total, { assets }) => total + assets, 0n);
205
+ const { liquidity } = leverageData.position.market;
206
+ if (liquidity + reallocatedAssets < limits.maxBorrowAssets) {
207
+ throw new index_js_1.LeverageInsufficientLiquidityError({
208
+ liquidity,
209
+ reallocatedAssets,
210
+ maxBorrowAssets: limits.maxBorrowAssets,
211
+ });
212
+ }
213
+ const swap = (0, zeroExQuote_js_1.validateZeroExQuote)({
214
+ quote,
215
+ kind: "lever",
216
+ chainId,
217
+ marketParams,
218
+ userAddress,
219
+ txOrigin: params.args.txOrigin,
220
+ maxSwapInput: limits.maxSwapIn,
221
+ deadline: limits.deadline,
222
+ });
223
+ const transaction = {
224
+ to: bundle,
225
+ value: nativeFunding.value,
226
+ data: (0, viem_1.encodeFunctionData)({
227
+ abi: abis_js_1.zeroExLeverageBundlesV1Abi,
228
+ functionName: "zeroExLeverageBundlesV1Lever",
229
+ args: [
230
+ marketParams,
231
+ collateralAssets,
232
+ loanAssets,
233
+ limits.minCollateralToBuy,
234
+ limits.maxBorrowAssets,
235
+ swap.swapData,
236
+ limits.maxLtv,
237
+ reallocations,
238
+ limits.penaltyAssets,
239
+ limits.deadline,
240
+ nativeFunding.wrappedNative,
241
+ ],
242
+ }),
243
+ };
244
+ return (0, morpho_ts_1.deepFreeze)({
245
+ ...(params.metadata == null
246
+ ? transaction
247
+ : (0, metadata_js_1.addTransactionMetadata)(transaction, params.metadata)),
248
+ action: {
249
+ type: "blueLever",
250
+ args: {
251
+ market: marketParams.id,
252
+ onBehalf: userAddress,
253
+ collateralAssets,
254
+ loanAssets,
255
+ minCollateralToBuy: limits.minCollateralToBuy,
256
+ maxBorrowAssets: limits.maxBorrowAssets,
257
+ maxSwapIn: limits.maxSwapIn,
258
+ maxLtv: limits.maxLtv,
259
+ reallocations: reallocations.length,
260
+ penaltyAssets: limits.penaltyAssets,
261
+ settler: swap.settler,
262
+ oracleDeviation: { status: "measured", ...limits.oracleDeviation },
263
+ deadline: limits.deadline,
264
+ block: {
265
+ number: leverageData.block.number,
266
+ timestamp: leverageData.block.timestamp,
267
+ },
268
+ },
269
+ },
270
+ });
271
+ };
272
+ exports.blueLever = blueLever;
@@ -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,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateLeverNativeAmount = exports.validateLeverageQuoteSlippage = exports.validateLeverSlippage = exports.validateLeverageIntentAmount = void 0;
4
+ const constant_js_1 = require("../../helpers/constant.js");
5
+ const validate_js_1 = require("../../helpers/validate.js");
6
+ const index_js_1 = require("../../types/index.js");
7
+ /**
8
+ * Refuses a Lever intent amount that is not a bigint or does not fit in `uint256`, before any bigint
9
+ * arithmetic mixes it with a number.
10
+ *
11
+ * @param field - Intent field name reported in the error.
12
+ * @param value - Intent amount.
13
+ * @throws {InvalidBigIntInputError} when `value` is not a bigint.
14
+ * @throws {NegativeInputError} when `value` is negative.
15
+ * @throws {InputExceedsMaxError} when `value` exceeds `uint256`.
16
+ */
17
+ const validateLeverageIntentAmount = (field, value) => {
18
+ if (typeof value !== "bigint") {
19
+ throw new index_js_1.InvalidBigIntInputError(field, value);
20
+ }
21
+ (0, validate_js_1.validateUint256Field)(field, value);
22
+ };
23
+ exports.validateLeverageIntentAmount = validateLeverageIntentAmount;
24
+ /**
25
+ * Refuses a Lever slippage that is not a bigint, is negative or exceeds the Lever's 10% limit. Callers run it
26
+ * before comparing the slippage with the quote's, so a requote advice never names a slippage the quote fetch
27
+ * refuses.
28
+ *
29
+ * @param slippage - Caller slippage, WAD-scaled.
30
+ * @throws {InvalidBigIntInputError} when `slippage` is not a bigint.
31
+ * @throws {NegativeInputError} when `slippage` is negative.
32
+ * @throws {LeverageSlippageAboveLimitError} when `slippage` exceeds `LEVERAGE_MAX_EXECUTION_LOSS.lever`.
33
+ */
34
+ const validateLeverSlippage = (slippage) => {
35
+ if (typeof slippage !== "bigint") {
36
+ throw new index_js_1.InvalidBigIntInputError("slippage", slippage);
37
+ }
38
+ if (slippage < 0n) {
39
+ throw new index_js_1.NegativeInputError("slippage", slippage);
40
+ }
41
+ if (slippage > constant_js_1.LEVERAGE_MAX_EXECUTION_LOSS.lever) {
42
+ throw new index_js_1.LeverageSlippageAboveLimitError({
43
+ operation: "lever",
44
+ slippage,
45
+ max: constant_js_1.LEVERAGE_MAX_EXECUTION_LOSS.lever,
46
+ });
47
+ }
48
+ };
49
+ exports.validateLeverSlippage = validateLeverSlippage;
50
+ /**
51
+ * Refuses a quote fetched with another slippage than the caller's. The quote's slippage is checked to be a bigint
52
+ * first, so a missing or malformed value is reported as such rather than as a slippage mismatch.
53
+ *
54
+ * @param params.operation - Leverage action the quote is for.
55
+ * @param params.slippage - Caller slippage, WAD-scaled, already validated.
56
+ * @param params.quoteSlippage - Slippage the quote was fetched with.
57
+ * @throws {InvalidBigIntInputError} when `quoteSlippage` is not a bigint (field `quote.slippage`).
58
+ * @throws {LeverageQuoteSlippageMismatchError} when `quoteSlippage` is not `slippage`.
59
+ */
60
+ const validateLeverageQuoteSlippage = (params) => {
61
+ const { operation, slippage, quoteSlippage } = params;
62
+ if (typeof quoteSlippage !== "bigint") {
63
+ throw new index_js_1.InvalidBigIntInputError("quote.slippage", quoteSlippage);
64
+ }
65
+ if (quoteSlippage !== slippage) {
66
+ throw new index_js_1.LeverageQuoteSlippageMismatchError({
67
+ operation,
68
+ slippage,
69
+ quoteSlippage,
70
+ });
71
+ }
72
+ };
73
+ exports.validateLeverageQuoteSlippage = validateLeverageQuoteSlippage;
74
+ /**
75
+ * Validates a Lever's `nativeAmount` and returns the transaction `value` and the `wrappedNative` argument. The bundle
76
+ * wraps `nativeAmount` into the chain's wNative for the user before pulling `collateralAssets` and `loanAssets`.
77
+ *
78
+ * @param params.chainId - Chain used to resolve wNative.
79
+ * @param params.marketParams - Market whose collateral and loan tokens the Lever pulls.
80
+ * @param params.collateralAssets - Collateral pulled from the user.
81
+ * @param params.loanAssets - Loan assets pulled from the user.
82
+ * @param params.nativeAmount - Optional native token to wrap; omitted or zero sends no value.
83
+ * @returns The transaction `value` and the `wrappedNative` Lever argument (`zeroAddress` without native).
84
+ * @throws {InvalidBigIntInputError} when `nativeAmount` is given and is not a bigint.
85
+ * @throws {NegativeInputError} when `nativeAmount` is negative.
86
+ * @throws {ChainWNativeMissingError} when the chain has no wNative.
87
+ * @throws {NativeAmountOnNonWNativeAssetError} when neither market token is wNative.
88
+ * @throws {InputExceedsMaxError} when `nativeAmount` exceeds the wNative pull.
89
+ */
90
+ const validateLeverNativeAmount = ({ chainId, marketParams, collateralAssets, loanAssets, nativeAmount, }) => {
91
+ if (nativeAmount !== undefined) {
92
+ (0, exports.validateLeverageIntentAmount)("nativeAmount", nativeAmount);
93
+ }
94
+ return (0, validate_js_1.validateMidnightNativeAmount)({
95
+ chainId,
96
+ nativeAmount,
97
+ pulls: [
98
+ { token: marketParams.collateralToken, assets: collateralAssets },
99
+ { token: marketParams.loanToken, assets: loanAssets },
100
+ ],
101
+ });
102
+ };
103
+ exports.validateLeverNativeAmount = validateLeverNativeAmount;
@@ -101,31 +101,31 @@ exports.midnightSupplyCollateralTakeBorrow = midnightSupplyCollateralTakeBorrow;
101
101
  const parsedSupplyCollateralTakeBorrow = Symbol();
102
102
  /** Parses the static SupplyCollateralTakeBorrow constraints in the standalone builder's existing order. @internal */
103
103
  const parseMidnightSupplyCollateralTakeBorrow = (params) => {
104
+ const { market, target, takeableOffers } = params;
104
105
  // Reject markets from another chain deployment before checking offers against them.
105
- (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market: params.market, chainId: params.chainId });
106
+ (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market, chainId: params.chainId });
106
107
  if (params.collateralSupplies.length === 0) {
107
108
  throw new index_js_1.EmptyMidnightCollateralSuppliesError();
108
109
  }
109
110
  // Validation only; retain main's canonical per-entry and per-index collateral checks.
110
111
  (0, validateMidnightCollateralSupplies_js_1.validateMidnightCollateralSupplies)({
111
- market: params.market,
112
+ market,
112
113
  field: "collateralSupplies",
113
114
  supplies: params.collateralSupplies,
114
115
  });
115
116
  const marketId = (0, validateTakeableOffers_js_1.validateTakeableOffers)({
116
- market: params.market,
117
- takeableOffers: params.takeableOffers,
117
+ market,
118
+ takeableOffers,
118
119
  expectedBuy: true,
119
120
  });
120
- (0, validateMidnightBounds_js_1.validateMidnightTakeableOfferBounds)(params.takeableOffers);
121
+ (0, validateMidnightBounds_js_1.validateMidnightTakeableOfferBounds)(takeableOffers);
121
122
  // Rejects receivers that would strand the borrowed assets in a contract.
122
123
  (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
123
124
  chainId: params.chainId,
124
- market: params.market,
125
+ market,
125
126
  field: "receiver",
126
127
  receiver: params.receiver,
127
128
  });
128
- const { target } = params;
129
129
  switch (target.type) {
130
130
  case "assets": {
131
131
  // Validation only; rejects non-positive amounts.
@@ -165,7 +165,7 @@ const parseMidnightSupplyCollateralTakeBorrow = (params) => {
165
165
  // Rejects fee recipients that would strand the fee in a contract.
166
166
  (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
167
167
  chainId: params.chainId,
168
- market: params.market,
168
+ market,
169
169
  field: "referralFeeRecipient",
170
170
  receiver: referralFeeRecipient,
171
171
  });
@@ -173,15 +173,20 @@ const parseMidnightSupplyCollateralTakeBorrow = (params) => {
173
173
  const collateralSupplies = params.collateralSupplies.map(({ collateralIndex, assets }) => ({
174
174
  collateralIndex,
175
175
  assets,
176
- token: midnight_sdk_1.MarketUtils.getCollateralByIndex(params.market, collateralIndex)
177
- .token,
176
+ token: midnight_sdk_1.MarketUtils.getCollateralByIndex(market, collateralIndex).token,
178
177
  }));
179
178
  const nativeFunding = (0, parseMidnight_js_1.parseMidnightNativeFunding)({
180
179
  chainId: params.chainId,
181
180
  nativeAmount: params.nativeAmount,
182
181
  pulls: collateralSupplies,
183
182
  });
184
- const snapshot = (0, parse_js_2.snapshotMidnightTakeParams)({ ...params, direction: "sell" });
183
+ const snapshot = (0, parse_js_2.snapshotMidnightTakeParams)({
184
+ direction: "sell",
185
+ market,
186
+ target,
187
+ takeableOffers,
188
+ metadata: params.metadata,
189
+ });
185
190
  return (0, morpho_ts_1.deepFreeze)({
186
191
  ...snapshot,
187
192
  chainId: params.chainId,
@@ -85,22 +85,22 @@ exports.midnightTakeBorrow = midnightTakeBorrow;
85
85
  const parsedTakeBorrow = Symbol();
86
86
  /** Parses the static TakeBorrow constraints in the standalone builder's existing order. @internal */
87
87
  const parseMidnightTakeBorrow = (params) => {
88
+ const { market, target, takeableOffers } = params;
88
89
  // Reject markets from another chain deployment before checking offers against them.
89
- (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market: params.market, chainId: params.chainId });
90
+ (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market, chainId: params.chainId });
90
91
  const marketId = (0, validateTakeableOffers_js_1.validateTakeableOffers)({
91
- market: params.market,
92
- takeableOffers: params.takeableOffers,
92
+ market,
93
+ takeableOffers,
93
94
  expectedBuy: true,
94
95
  });
95
- (0, validateMidnightBounds_js_1.validateMidnightTakeableOfferBounds)(params.takeableOffers);
96
+ (0, validateMidnightBounds_js_1.validateMidnightTakeableOfferBounds)(takeableOffers);
96
97
  // Rejects receivers that would strand the borrowed assets in a contract.
97
98
  (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
98
99
  chainId: params.chainId,
99
- market: params.market,
100
+ market,
100
101
  field: "receiver",
101
102
  receiver: params.receiver,
102
103
  });
103
- const { target } = params;
104
104
  switch (target.type) {
105
105
  case "assets": {
106
106
  // Validation only; rejects non-positive amounts.
@@ -140,12 +140,18 @@ const parseMidnightTakeBorrow = (params) => {
140
140
  // Rejects fee recipients that would strand the fee in a contract.
141
141
  (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
142
142
  chainId: params.chainId,
143
- market: params.market,
143
+ market,
144
144
  field: "referralFeeRecipient",
145
145
  receiver: referralFeeRecipient,
146
146
  });
147
147
  }
148
- const snapshot = (0, parse_js_2.snapshotMidnightTakeParams)({ ...params, direction: "sell" });
148
+ const snapshot = (0, parse_js_2.snapshotMidnightTakeParams)({
149
+ direction: "sell",
150
+ market,
151
+ target,
152
+ takeableOffers,
153
+ metadata: params.metadata,
154
+ });
149
155
  return (0, morpho_ts_1.deepFreeze)({
150
156
  ...snapshot,
151
157
  chainId: params.chainId,
@@ -85,15 +85,15 @@ exports.midnightTakeLend = midnightTakeLend;
85
85
  const parsedTakeLend = Symbol();
86
86
  /** Parses the static TakeLend constraints in the standalone builder's existing order. @internal */
87
87
  const parseMidnightTakeLend = (params) => {
88
+ const { market, target, takeableOffers } = params;
88
89
  // Reject markets from another chain deployment before checking offers against them.
89
- (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market: params.market, chainId: params.chainId });
90
+ (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market, chainId: params.chainId });
90
91
  const marketId = (0, validateTakeableOffers_js_1.validateTakeableOffers)({
91
- market: params.market,
92
- takeableOffers: params.takeableOffers,
92
+ market,
93
+ takeableOffers,
93
94
  expectedBuy: false,
94
95
  });
95
- (0, validateMidnightBounds_js_1.validateMidnightTakeableOfferBounds)(params.takeableOffers);
96
- const { target } = params;
96
+ (0, validateMidnightBounds_js_1.validateMidnightTakeableOfferBounds)(takeableOffers);
97
97
  switch (target.type) {
98
98
  case "assets": {
99
99
  // Validation only; rejects non-positive amounts.
@@ -133,23 +133,29 @@ const parseMidnightTakeLend = (params) => {
133
133
  // Rejects fee recipients that would strand the fee in a contract.
134
134
  (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
135
135
  chainId: params.chainId,
136
- market: params.market,
136
+ market,
137
137
  field: "referralFeeRecipient",
138
138
  receiver: referralFeeRecipient,
139
139
  });
140
140
  }
141
- const market = midnight_sdk_1.MarketUtils.toStruct(params.market);
141
+ const marketStruct = midnight_sdk_1.MarketUtils.toStruct(market);
142
142
  const nativeFunding = (0, parseMidnight_js_1.parseMidnightNativeFunding)({
143
143
  chainId: params.chainId,
144
144
  nativeAmount: params.nativeAmount,
145
145
  pulls: [
146
146
  {
147
- token: market.loanToken,
147
+ token: marketStruct.loanToken,
148
148
  assets: target.type === "assets" ? target.assets : target.maxBuyerAssets,
149
149
  },
150
150
  ],
151
151
  });
152
- const snapshot = (0, parse_js_2.snapshotMidnightTakeParams)({ ...params, direction: "buy" });
152
+ const snapshot = (0, parse_js_2.snapshotMidnightTakeParams)({
153
+ direction: "buy",
154
+ market,
155
+ target,
156
+ takeableOffers,
157
+ metadata: params.metadata,
158
+ });
153
159
  return (0, morpho_ts_1.deepFreeze)({
154
160
  ...snapshot,
155
161
  chainId: params.chainId,