@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,754 @@
1
+ import { getChainAddresses, isZeroExLeverageChain, MathLib, NATIVE_ADDRESS, ZERO_EX_ALLOWANCE_HOLDER_ADDRESS, ZERO_EX_ALLOWANCE_HOLDER_CHAIN_IDS, } from "@morpho-org/morpho-ts";
2
+ import { decodeFunctionData, hexToBigInt, isAddress, isAddressEqual, size, sliceHex, toFunctionSelector, zeroAddress, } from "viem";
3
+ import { zeroExAllowanceHolderAbi, zeroExSettlerAbi, zeroExSettlerBasicAbi, zeroExSettlerOtherEntryPointsAbi, zeroExSettlerSelectAbi, } from "../abis.js";
4
+ import { InvalidBigIntInputError, LeverageUnsupportedChainError, NonPositiveInputError, ZeroExExactOutputUnsupportedError, ZeroExInvalidTxOriginError, ZeroExQuoteAmountExceedsCapError, ZeroExQuoteChainMismatchError, ZeroExQuoteDeadlineMismatchError, ZeroExQuoteMalformedCalldataError, ZeroExQuoteMinAmountOutMismatchError, ZeroExQuoteNonZeroValueError, ZeroExQuoteRecipientMismatchError, ZeroExQuoteSellAmountMismatchError, ZeroExQuoteShortTimeBoundError, ZeroExQuoteSignedOrderActionError, ZeroExQuoteTakerMismatchError, ZeroExQuoteTargetMismatchError, ZeroExQuoteTokenMismatchError, ZeroExQuoteTxOriginMismatchError, ZeroExQuoteTypeMismatchError, ZeroExQuoteUndecodableCalldataError, ZeroExQuoteUnsupportedActionError, ZeroExSettlerOperatorTargetMismatchError, ZeroExUnknownSwapKindError, } from "../types/index.js";
5
+ import { LEVERAGE_DEADLINE_WINDOW } from "./constant.js";
6
+ import { validateDeadline, validateUint256Field } from "./validate.js";
7
+ /**
8
+ * Parts per million: the unit of the 0x `slippagePpm` parameter.
9
+ *
10
+ * @internal
11
+ */
12
+ export const ZERO_EX_SLIPPAGE_PPM = 1000000n;
13
+ /**
14
+ * Converts a WAD-scaled slippage to the whole parts per million 0x applies, rounded down as the
15
+ * `slippagePpm` request parameter carries it.
16
+ *
17
+ * @internal
18
+ * @param slippage - Caller slippage, WAD-scaled.
19
+ * @returns The slippage 0x applies, in parts per million.
20
+ * @example
21
+ * ```ts
22
+ * toZeroExSlippagePpm(5_000_000_000_000_000n); // 5_000n
23
+ * ```
24
+ */
25
+ export const toZeroExSlippagePpm = (slippage) => (slippage * ZERO_EX_SLIPPAGE_PPM) / MathLib.WAD;
26
+ /**
27
+ * Returns the tokens and quote mode of the 0x swap a ZeroExLeverageBundlesV1 action needs on a market.
28
+ *
29
+ * Lever buys exactly the collateral with loan tokens (exact output). Delever and Close sell collateral for
30
+ * loan tokens: Delever sells an exact amount (exact input), while Close buys exactly the debt plus its
31
+ * buffer (exact output).
32
+ *
33
+ * @see https://github.com/morpho-org/bundles/blob/3bf53141455051f8fc7a85cd00cc15bd89459238/src/leverage/ZeroExLeverageBundlesV1.sol#L60
34
+ * @see https://github.com/morpho-org/bundles/blob/3bf53141455051f8fc7a85cd00cc15bd89459238/src/leverage/ZeroExLeverageBundlesV1.sol#L128
35
+ * @see https://github.com/morpho-org/bundles/blob/3bf53141455051f8fc7a85cd00cc15bd89459238/src/leverage/ZeroExLeverageBundlesV1.sol#L159-L161
36
+ * @param kind - Swap the action needs.
37
+ * @param marketParams - Market whose tokens the swap trades.
38
+ * @returns The quote mode and the sell and buy tokens.
39
+ * @throws {ZeroExUnknownSwapKindError} when `kind` is not one of the three leverage swap kinds.
40
+ * @example
41
+ * ```ts
42
+ * import { getZeroExSwapRoute } from "@morpho-org/morpho-sdk";
43
+ *
44
+ * declare const marketParams: { loanToken: `0x${string}`; collateralToken: `0x${string}` };
45
+ * const route = getZeroExSwapRoute("lever", marketParams);
46
+ * // { mode: "exactOutput", sellToken: marketParams.loanToken, buyToken: marketParams.collateralToken }
47
+ * ```
48
+ */
49
+ export function getZeroExSwapRoute(kind, marketParams) {
50
+ switch (kind) {
51
+ case "lever":
52
+ return {
53
+ mode: "exactOutput",
54
+ sellToken: marketParams.loanToken,
55
+ buyToken: marketParams.collateralToken,
56
+ };
57
+ case "closeKeepCollateral":
58
+ return {
59
+ mode: "exactOutput",
60
+ sellToken: marketParams.collateralToken,
61
+ buyToken: marketParams.loanToken,
62
+ };
63
+ case "delever":
64
+ return {
65
+ mode: "exactInput",
66
+ sellToken: marketParams.collateralToken,
67
+ buyToken: marketParams.loanToken,
68
+ };
69
+ default:
70
+ throw new ZeroExUnknownSwapKindError({ kind });
71
+ }
72
+ }
73
+ /**
74
+ * Returns the ZeroExLeverageBundlesV1 address registered for a chain where AllowanceHolder sits at its Cancun
75
+ * address.
76
+ *
77
+ * @internal
78
+ * @param chainId - Chain of the action.
79
+ * @returns The leverage bundle address.
80
+ * @throws {LeverageUnsupportedChainError} when AllowanceHolder is not at its Cancun address on the chain, or no
81
+ * bundle is registered there, including a bundle registered as the zero address.
82
+ */
83
+ export function getZeroExLeverageBundle(chainId) {
84
+ if (!ZERO_EX_ALLOWANCE_HOLDER_CHAIN_IDS.has(chainId)) {
85
+ throw new LeverageUnsupportedChainError({
86
+ chainId,
87
+ reason: "noAllowanceHolder",
88
+ });
89
+ }
90
+ const bundle = getChainAddresses(chainId).bundles?.zeroExLeverageBundlesV1;
91
+ if (bundle == null || !isZeroExLeverageChain(chainId)) {
92
+ throw new LeverageUnsupportedChainError({ chainId, reason: "noBundle" });
93
+ }
94
+ return bundle;
95
+ }
96
+ /**
97
+ * Refuses an exact-output swap between the chain's native token and its wrapped-native token, which 0x does not
98
+ * support.
99
+ *
100
+ * @internal
101
+ * @param params - Swap details.
102
+ * @param params.chainId - Chain of the swap.
103
+ * @param params.mode - Quote mode.
104
+ * @param params.sellToken - Token the swap sells.
105
+ * @param params.buyToken - Token the swap buys.
106
+ * @throws {ZeroExExactOutputUnsupportedError} when the mode is exact output and the tokens are the native and
107
+ * the wrapped-native token, in either order.
108
+ */
109
+ export function validateZeroExExactOutputPair(params) {
110
+ const { chainId, mode, sellToken, buyToken } = params;
111
+ if (mode !== "exactOutput") {
112
+ return;
113
+ }
114
+ const wNative = getChainAddresses(chainId).wNative;
115
+ if (wNative == null) {
116
+ return;
117
+ }
118
+ const isNativeOrWrapped = (token) => isAddressEqual(token, NATIVE_ADDRESS) || isAddressEqual(token, wNative);
119
+ if (isNativeOrWrapped(sellToken) &&
120
+ isNativeOrWrapped(buyToken) &&
121
+ !isAddressEqual(sellToken, buyToken)) {
122
+ throw new ZeroExExactOutputUnsupportedError({ sellToken, buyToken });
123
+ }
124
+ }
125
+ function tryDecodeAllowanceHolderExec(data) {
126
+ try {
127
+ return decodeFunctionData({ abi: zeroExAllowanceHolderAbi, data }).args;
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ }
133
+ /**
134
+ * Returns the transaction origin of a leverage action: `txOrigin` when given, else the user. Only the 0x request
135
+ * and its echo use it; the taker, recipient, position owner and authorization stay the bundle and the user.
136
+ *
137
+ * @internal
138
+ * @param txOrigin - Optional sender of the outer onchain transaction, such as a Safe's executing owner or an ERC-4337 bundler.
139
+ * @param userAddress - Account whose position the action changes.
140
+ * @returns The transaction origin.
141
+ * @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address.
142
+ */
143
+ export function resolveZeroExTxOrigin(txOrigin, userAddress) {
144
+ if (txOrigin === undefined) {
145
+ return userAddress;
146
+ }
147
+ if (typeof txOrigin !== "string" || !isAddress(txOrigin, { strict: false })) {
148
+ throw new ZeroExInvalidTxOriginError(txOrigin);
149
+ }
150
+ return txOrigin;
151
+ }
152
+ // Settler actions of the deployed Settlers, classed by what leverage accepts, as their Solidity signatures from
153
+ // ISettlerActions.sol at 0x-settler 243fb92; the older METATXN_* revisions and DODOV1 come from that file at
154
+ // 0x-settler 0d82cbc, 3af5605, 53b9603, 82b0c9f, a629bc4, c40b5cc. The selectors are derived from these signatures. `permit` pulls the sell
155
+ // token with the taker's permit, whose deadline is ABI word 4; `signedOrder` fills a maker's signed order; `timeCheck`
156
+ // reverts past its word 0; `opaqueCall` calls a venue with data Settler does not read; `select` holds candidate action
157
+ // lists; `amm` swaps through a pool with no time field (HANJI passes `expires = max`, Hanji.sol:77).
158
+ const SETTLER_ACTIONS = Object.fromEntries([
159
+ [
160
+ "permit",
161
+ "TRANSFER_FROM(address,((address,uint256),uint256,uint256),bytes)",
162
+ ],
163
+ [
164
+ "permit",
165
+ "UNISWAPV3_VIP(address,((address,uint256),uint256,uint256),bytes,bytes,uint256)",
166
+ ],
167
+ [
168
+ "permit",
169
+ "UNISWAPV4_VIP(address,((address,uint256),uint256,uint256),uint8,bool,uint256,uint256,bytes,bytes,uint256)",
170
+ ],
171
+ [
172
+ "permit",
173
+ "BALANCERV3_VIP(address,((address,uint256),uint256,uint256),bool,uint256,uint256,bytes,bytes,uint256)",
174
+ ],
175
+ [
176
+ "permit",
177
+ "PANCAKE_INFINITY_VIP(address,((address,uint256),uint256,uint256),uint8,bool,uint256,uint256,bytes,bytes,uint256)",
178
+ ],
179
+ [
180
+ "permit",
181
+ "CURVE_TRICRYPTO_VIP(address,((address,uint256),uint256,uint256),uint80,bytes,uint256)",
182
+ ],
183
+ [
184
+ "permit",
185
+ "EKUBOV3_VIP(address,((address,uint256),uint256,uint256),bool,uint256,uint256,bytes,bytes,uint256)",
186
+ ],
187
+ [
188
+ "signedOrder",
189
+ "RFQ(address,((address,uint256),uint256,uint256),address,bytes,address,uint256)",
190
+ ],
191
+ [
192
+ "signedOrder",
193
+ "RFQ_VIP(address,((address,uint256),uint256,uint256),((address,uint256),uint256,uint256),address,bytes,bytes)",
194
+ ],
195
+ [
196
+ "signedOrder",
197
+ "BEBOP(address,address,(uint256,address,uint256,address,uint256,uint256,uint256),(bytes,uint256),uint256)",
198
+ ],
199
+ [
200
+ "signedOrder",
201
+ "METATXN_TRANSFER_FROM(address,((address,uint256),uint256,uint256))",
202
+ ],
203
+ [
204
+ "signedOrder",
205
+ "METATXN_RFQ_VIP(address,((address,uint256),uint256,uint256),((address,uint256),uint256,uint256),address,bytes)",
206
+ ],
207
+ [
208
+ "signedOrder",
209
+ "METATXN_RFQ_VIP(address,((address,uint256),uint256,uint256),address,bytes,((address,uint256),uint256,uint256))",
210
+ ],
211
+ [
212
+ "signedOrder",
213
+ "METATXN_UNISWAPV4_VIP(address,((address,uint256),uint256,uint256),bool,uint256,uint256,bytes,uint256)",
214
+ ],
215
+ [
216
+ "signedOrder",
217
+ "METATXN_UNISWAPV4_VIP(address,bool,uint256,uint256,bytes,((address,uint256),uint256,uint256),uint256)",
218
+ ],
219
+ [
220
+ "signedOrder",
221
+ "METATXN_UNISWAPV4_VIP(address,((address,uint256),uint256,uint256),uint8,bool,uint256,uint256,bytes,uint256)",
222
+ ],
223
+ [
224
+ "signedOrder",
225
+ "METATXN_BALANCERV3_VIP(address,((address,uint256),uint256,uint256),bool,uint256,uint256,bytes,uint256)",
226
+ ],
227
+ [
228
+ "signedOrder",
229
+ "METATXN_BALANCERV3_VIP(address,bool,uint256,uint256,bytes,((address,uint256),uint256,uint256),uint256)",
230
+ ],
231
+ [
232
+ "signedOrder",
233
+ "METATXN_PANCAKE_INFINITY_VIP(address,((address,uint256),uint256,uint256),bool,uint256,uint256,bytes,uint256)",
234
+ ],
235
+ [
236
+ "signedOrder",
237
+ "METATXN_PANCAKE_INFINITY_VIP(address,bool,uint256,uint256,bytes,((address,uint256),uint256,uint256),uint256)",
238
+ ],
239
+ [
240
+ "signedOrder",
241
+ "METATXN_PANCAKE_INFINITY_VIP(address,((address,uint256),uint256,uint256),uint8,bool,uint256,uint256,bytes,uint256)",
242
+ ],
243
+ [
244
+ "signedOrder",
245
+ "METATXN_UNISWAPV3_VIP(address,((address,uint256),uint256,uint256),bytes,uint256)",
246
+ ],
247
+ [
248
+ "signedOrder",
249
+ "METATXN_UNISWAPV3_VIP(address,bytes,((address,uint256),uint256,uint256),uint256)",
250
+ ],
251
+ [
252
+ "signedOrder",
253
+ "METATXN_CURVE_TRICRYPTO_VIP(address,((address,uint256),uint256,uint256),uint80,uint256)",
254
+ ],
255
+ [
256
+ "signedOrder",
257
+ "METATXN_CURVE_TRICRYPTO_VIP(address,uint80,((address,uint256),uint256,uint256),uint256)",
258
+ ],
259
+ [
260
+ "signedOrder",
261
+ "METATXN_EKUBOV3_VIP(address,((address,uint256),uint256,uint256),bool,uint256,uint256,bytes,uint256)",
262
+ ],
263
+ [
264
+ "signedOrder",
265
+ "METATXN_EKUBOV3_VIP(address,bool,uint256,uint256,bytes,((address,uint256),uint256,uint256),uint256)",
266
+ ],
267
+ [
268
+ "signedOrder",
269
+ "METATXN_MAVERICKV2_VIP(address,bytes32,bool,((address,uint256),uint256,uint256),int32,uint256)",
270
+ ],
271
+ [
272
+ "signedOrder",
273
+ "METATXN_MAVERICKV2_VIP(address,((address,uint256),uint256,uint256),bytes32,bool,int32,uint256)",
274
+ ],
275
+ [
276
+ "signedOrder",
277
+ "METATXN_MAVERICKV2_VIP(address,bytes32,bool,((address,uint256),uint256,uint256),uint256)",
278
+ ],
279
+ [
280
+ "signedOrder",
281
+ "METATXN_EKUBO_VIP(address,bool,uint256,uint256,bytes,((address,uint256),uint256,uint256),uint256)",
282
+ ],
283
+ [
284
+ "signedOrder",
285
+ "METATXN_EKUBO_VIP(address,((address,uint256),uint256,uint256),bool,uint256,uint256,bytes,uint256)",
286
+ ],
287
+ [
288
+ "signedOrder",
289
+ "METATXN_TSUNAMI_VIP(address,((address,uint256),uint256,uint256),bool,uint256,uint256,bytes,uint256)",
290
+ ],
291
+ ["timeCheck", "NATIVE_CHECK(uint256,uint256)"],
292
+ ["timeCheck", "ATTEST(uint256,bytes32,bytes32)"],
293
+ ["opaqueCall", "BASIC(address,uint256,address,uint256,bytes)"],
294
+ ["opaqueCall", "BASIC_PUSH(address,uint256,address,uint256,bytes)"],
295
+ ["select", "SELECT(uint256,address,uint256[],bytes[][])"],
296
+ ["amm", "UNISWAPV2(address,address,uint256,address,uint24,uint256)"],
297
+ ["amm", "UNISWAPV3(address,uint256,bytes,uint256)"],
298
+ [
299
+ "amm",
300
+ "UNISWAPV4(address,address,uint256,uint8,bool,uint256,uint256,bytes,uint256)",
301
+ ],
302
+ [
303
+ "amm",
304
+ "BALANCERV3(address,address,uint256,bool,uint256,uint256,bytes,uint256)",
305
+ ],
306
+ [
307
+ "amm",
308
+ "PANCAKE_INFINITY(address,address,uint256,uint8,bool,uint256,uint256,bytes,uint256)",
309
+ ],
310
+ [
311
+ "amm",
312
+ "EKUBO(address,address,uint256,bool,uint256,uint256,bytes,uint256)",
313
+ ],
314
+ [
315
+ "amm",
316
+ "EKUBOV3(address,address,uint256,bool,uint256,uint256,bytes,uint256)",
317
+ ],
318
+ ["amm", "MAVERICKV2(address,address,uint256,address,bool,int32,uint256)"],
319
+ ["amm", "VELODROME(address,uint256,address,uint24,uint256)"],
320
+ ["amm", "DODOV1(address,uint256,address,bool,uint256)"],
321
+ ["amm", "DODOV2(address,address,uint256,address,bool,uint256)"],
322
+ ["amm", "MAKERPSM(address,uint256,bool,uint256,address,address)"],
323
+ ["amm", "FLUXPOOL(address,uint256,bytes32,bool,uint256)"],
324
+ [
325
+ "amm",
326
+ "HANJI(address,uint256,address,uint256,uint256,bool,uint256,uint256)",
327
+ ],
328
+ ["amm", "DEEPSTATE(address,uint256,address,uint256,int32,uint256)"],
329
+ ["amm", "POSITIVE_SLIPPAGE(address,address,uint256,uint256,uint256)"],
330
+ ["amm", "CHECK_SLIPPAGE(bool)"],
331
+ ].map(([kind, signature]) => [
332
+ toFunctionSelector(signature),
333
+ [kind, signature.slice(0, signature.indexOf("("))],
334
+ ]));
335
+ // SELECT levels walked: real routes nest one level, so a deeper SELECT refuses instead of going unchecked.
336
+ const SETTLER_SELECT_MAX_DEPTH = 3;
337
+ // How far before the deadline an opaque call's word still reads as a time bound: the deadline window plus one day,
338
+ // which covers the expiry of any quote fetched within the day before the leverage data block.
339
+ const SETTLER_TIME_BOUND_LOOKBACK = LEVERAGE_DEADLINE_WINDOW + 86400n;
340
+ // Reads ABI word `word` of a Settler action's arguments, refusing an action too short to hold it.
341
+ function readSettlerWord(data, { word, action }) {
342
+ if (size(data) < 4 + (word + 1) * 32) {
343
+ throw new ZeroExQuoteMalformedCalldataError({
344
+ reason: `Settler ${action} action is too short to hold its deadline`,
345
+ });
346
+ }
347
+ return hexToBigInt(sliceHex(data, 4 + word * 32, 4 + (word + 1) * 32));
348
+ }
349
+ // Refuses an opaque call whose data, after its selector, holds a word in the time-bound window below the deadline:
350
+ // 0x writes router deadlines equal to the deadline, so a shorter one may be a venue's own expiry; the word is refused
351
+ // as one, since nothing tells whether it is a deadline.
352
+ function assertNoShortTimeBound(data, { action, path, deadline, }) {
353
+ let call;
354
+ try {
355
+ [, , , , call] = decodeFunctionData({
356
+ abi: zeroExSettlerBasicAbi,
357
+ data,
358
+ }).args;
359
+ }
360
+ catch (cause) {
361
+ throw new ZeroExQuoteMalformedCalldataError({ reason: `Settler ${action} does not decode` }, { cause });
362
+ }
363
+ for (let offset = 4; offset + 32 <= size(call); offset += 32) {
364
+ const value = hexToBigInt(sliceHex(call, offset, offset + 32));
365
+ if (value >= deadline - SETTLER_TIME_BOUND_LOOKBACK && value < deadline) {
366
+ throw new ZeroExQuoteShortTimeBoundError({
367
+ path,
368
+ word: (offset - 4) / 32,
369
+ value,
370
+ deadline,
371
+ });
372
+ }
373
+ }
374
+ }
375
+ // Returns the candidate action lists of a SELECT action, refusing one that does not decode or nests too deep.
376
+ function readSettlerSelectCandidates(data, depth) {
377
+ let candidates;
378
+ try {
379
+ [, , , candidates] = decodeFunctionData({
380
+ abi: zeroExSettlerSelectAbi,
381
+ data,
382
+ }).args;
383
+ }
384
+ catch (cause) {
385
+ throw new ZeroExQuoteMalformedCalldataError({ reason: "Settler SELECT does not decode" }, { cause });
386
+ }
387
+ if (depth === SETTLER_SELECT_MAX_DEPTH) {
388
+ throw new ZeroExQuoteMalformedCalldataError({
389
+ reason: `Settler SELECT nested deeper than ${SETTLER_SELECT_MAX_DEPTH} levels`,
390
+ });
391
+ }
392
+ return candidates;
393
+ }
394
+ // Walks Settler's `execute` actions and every SELECT candidate, accepting only AMM actions, the permit of the first
395
+ // top-level action when it carries `deadline`, a top-level NATIVE_CHECK or ATTEST reaching `deadline`, and opaque
396
+ // calls with no shorter time bound. Settler runs a permit (VIP) action only at index 0 (Settler.sol:173-178), and
397
+ // reverts past the permit deadline (Permit2Payment.sol:484), NATIVE_CHECK's deadline (Settler.sol:44-52) and
398
+ // ATTEST's (Attest.sol:73), all at 0x-settler 243fb92.
399
+ function assertSettlerActions(actions, { deadline, depth, path, }) {
400
+ for (const [index, data] of actions.entries()) {
401
+ const at = `${path}[${index}]`;
402
+ const selector = data.slice(0, 10).toLowerCase();
403
+ const entry = SETTLER_ACTIONS[selector];
404
+ if (entry === undefined) {
405
+ throw new ZeroExQuoteUnsupportedActionError({ selector, path: at });
406
+ }
407
+ const [kind, action] = entry;
408
+ if (kind === "amm") {
409
+ continue;
410
+ }
411
+ if (kind === "signedOrder") {
412
+ throw new ZeroExQuoteSignedOrderActionError({ action, path: at });
413
+ }
414
+ if (kind === "opaqueCall") {
415
+ assertNoShortTimeBound(data, { action, path: at, deadline });
416
+ continue;
417
+ }
418
+ if (kind === "select") {
419
+ for (const [candidate, candidateActions] of readSettlerSelectCandidates(data, depth).entries()) {
420
+ assertSettlerActions(candidateActions, {
421
+ deadline,
422
+ depth: depth + 1,
423
+ path: `${at}.candidates[${candidate}]`,
424
+ });
425
+ }
426
+ continue;
427
+ }
428
+ if (depth > 0 || (kind === "permit" && index > 0)) {
429
+ throw new ZeroExQuoteUnsupportedActionError({ selector, path: at });
430
+ }
431
+ const actual = readSettlerWord(data, {
432
+ word: kind === "permit" ? 4 : 0,
433
+ action,
434
+ });
435
+ if (kind === "permit" ? actual !== deadline : actual < deadline) {
436
+ throw new ZeroExQuoteDeadlineMismatchError({
437
+ expected: deadline,
438
+ actual,
439
+ action,
440
+ });
441
+ }
442
+ }
443
+ }
444
+ // Returns the quote's output floor and sell amount (`maxSellAmount` for an exact output), refusing a quote that lacks
445
+ // either before any calldata is decoded, so a swap whose calldata does not decode still carries both.
446
+ function readZeroExQuoteAmounts(quote) {
447
+ if (typeof quote.buyAmount !== "bigint") {
448
+ throw new InvalidBigIntInputError("quote.buyAmount", quote.buyAmount);
449
+ }
450
+ const exactOutput = quote.mode === "exactOutput";
451
+ const quotedMinAmountOut = exactOutput ? quote.buyAmount : quote.minBuyAmount;
452
+ if (typeof quotedMinAmountOut !== "bigint") {
453
+ throw new InvalidBigIntInputError("quote.minBuyAmount", quotedMinAmountOut);
454
+ }
455
+ const quotedSellAmount = exactOutput ? quote.maxSellAmount : quote.sellAmount;
456
+ if (typeof quotedSellAmount !== "bigint") {
457
+ throw new InvalidBigIntInputError(exactOutput ? "quote.maxSellAmount" : "quote.sellAmount", quotedSellAmount);
458
+ }
459
+ return { quotedMinAmountOut, quotedSellAmount };
460
+ }
461
+ // Refuses a malformed swap input cap or deadline before any quote field is read.
462
+ function validateZeroExSwapBounds(maxSwapInput, deadline) {
463
+ if (typeof maxSwapInput !== "bigint") {
464
+ throw new InvalidBigIntInputError("maxSwapInput", maxSwapInput);
465
+ }
466
+ if (maxSwapInput <= 0n) {
467
+ throw new NonPositiveInputError("maxSwapInput", maxSwapInput);
468
+ }
469
+ validateUint256Field("maxSwapInput", maxSwapInput);
470
+ if (typeof deadline !== "bigint") {
471
+ throw new InvalidBigIntInputError("deadline", deadline);
472
+ }
473
+ validateDeadline(deadline);
474
+ }
475
+ function tryDecodeSettlerExecute(data) {
476
+ try {
477
+ return decodeFunctionData({ abi: zeroExSettlerAbi, data }).args;
478
+ }
479
+ catch {
480
+ // Falls through to the other entry points.
481
+ }
482
+ let functionName;
483
+ try {
484
+ ({ functionName } = decodeFunctionData({
485
+ abi: zeroExSettlerOtherEntryPointsAbi,
486
+ data,
487
+ }));
488
+ }
489
+ catch {
490
+ return undefined;
491
+ }
492
+ throw new ZeroExQuoteMalformedCalldataError({
493
+ reason: `Settler entry point is ${functionName}, not execute`,
494
+ });
495
+ }
496
+ /**
497
+ * Validates a 0x quote for a ZeroExLeverageBundlesV1 action and returns it as a {@link ValidatedZeroExSwap}.
498
+ *
499
+ * The bundle runs `swapData` through AllowanceHolder unchecked and only measures its own balance changes
500
+ * (ZeroExLeverageBundlesV1.sol:385-408), so this is the SDK's check of the calldata. It is strict on the envelope:
501
+ * the quote's chain, mode and tokens, its taker and txOrigin, no native value, and a call to AllowanceHolder. Every
502
+ * calldata layer must decode, whichever leverage bundle takes the quote: a layer that does not refuses with
503
+ * `ZeroExQuoteUndecodableCalldataError`, and a decoded layer that does not match refuses the swap.
504
+ * - AllowanceHolder layer: the `exec` call's operator and target are the same Settler, pulling the sell token, at most
505
+ * the action's swap input cap and exactly the quote's sell amount (`maxSellAmount` for an exact output).
506
+ * - Settler layer: the `exec` data is Settler's taker-submitted `execute`, whose slippage pays the bundle in the buy
507
+ * token with a minimum output at least the quote's floor. Another recognized entry point (`executeWithPermit` or
508
+ * `executeMetaTxn`) refuses.
509
+ * - Settler actions: every action, and every action of every `SELECT` candidate down to three levels, is classed by
510
+ * its selector, and anything not classed refuses. AMM actions pass. A signed-order fill (`RFQ`, `RFQ_VIP`, `BEBOP`,
511
+ * any `METATXN_*`) refuses at any depth, since its maker's expiry can come before the leverage deadline. The permit
512
+ * action (`TRANSFER_FROM` and the `*_VIP` actions) may only be the first top-level action, where Settler runs it,
513
+ * and its deadline must equal `deadline`. `NATIVE_CHECK` and `ATTEST` may only be top-level, with a deadline of at
514
+ * least `deadline`. An opaque `BASIC` or `BASIC_PUSH` call refuses when any 32-byte word of its data reads as a
515
+ * time bound in the hour and day before `deadline`; one equal to `deadline` is how 0x writes router deadlines. The
516
+ * scan cannot tell a deadline from another value, so an ordinary amount in that window refuses too; a new quote
517
+ * clears it only when its calldata differs, so a fixed value such as the caller's amount needs another amount, a
518
+ * later retry or a no-swap exit. A
519
+ * `SELECT` that does not decode, or nests more than three levels deep, refuses.
520
+ * So every time bound the calldata shows reaches `deadline`, whichever sources 0x routes through; this is the
521
+ * backstop for a short-lived source 0x adds after `ZERO_EX_LEVERAGE_EXCLUDED_SOURCES`. A venue whose validity depends
522
+ * on an offchain keeper, with no time bound in the calldata, is kept out only by the sources `fetchZeroExQuote`
523
+ * excludes. In every case the bundle's onchain bounds (`spent <= maxIn`, `received >= minOut`)
524
+ * still bind what the swap does inside Settler. A slippage struct that is all zero, which 0x sends for some
525
+ * single-pool routes, is accepted: Settler then checks no output, and the bundle's `received >= minOut` check
526
+ * protects the swap. The leverage limits compare the swap's worst price with the market oracle: a Lever refuses past
527
+ * the bound, while a Delever or a Close only reports the deviation. Whether that Settler is 0x's official one, and
528
+ * whether 0x paused it, is not checked here; the bundle's bounds limit what the swap can lose.
529
+ *
530
+ * The quote's `chainId`, `taker` and `txOrigin` are also checked against the action's chain, the leverage
531
+ * bundle and the action's `txOrigin` (`userAddress` by default), but these are request-context checks: `fetchZeroExQuote` fills them from its own request,
532
+ * so they show what was asked for, not whom 0x built the calldata for. The quote's `blockNumber` is not checked
533
+ * either: a quote has no age limit here beyond the leverage deadline the builders sign. Pure and synchronous:
534
+ * builders call it again on every build.
535
+ *
536
+ * @param params - Validation parameters.
537
+ * @param params.quote - Quote returned by `fetchZeroExQuote`.
538
+ * @param params.kind - Swap the action needs.
539
+ * @param params.chainId - Chain of the action.
540
+ * @param params.marketParams - Market of the action.
541
+ * @param params.userAddress - Account whose position the action changes (`msg.sender`).
542
+ * @param params.txOrigin - Transaction origin the quote must have been requested for, when it differs from the user,
543
+ * such as a Safe's executing owner or an ERC-4337 bundler sending the outer transaction. Defaults to `userAddress`.
544
+ * @param params.maxSwapInput - Largest amount of the sell token the action lets the swap spend: the swap input
545
+ * cap the transaction enforces: `maxIn` of the bundle's swap, as the builder signs it. When that cap comes from
546
+ * the quote, such as an exact-output quote's `maxSellAmount`, validation only proves that the calldata stays within
547
+ * the signed limit; deciding whether the quoted price is acceptable stays with the caller.
548
+ * @param params.deadline - Deadline the action signs, in seconds: for the leverage builders, the leverage data's
549
+ * block timestamp plus one hour. Fetch the quote with the same `deadline`: the permit must carry it, and every other
550
+ * time bound the Settler actions show must reach it.
551
+ * @returns The quote with its swap calldata, its Settler, its swap input and its Settler minimum output.
552
+ * @throws {LeverageUnsupportedChainError} when the chain has no AllowanceHolder at its Cancun address or no
553
+ * registered leverage bundle.
554
+ * @throws {ZeroExQuoteChainMismatchError} when the quote is for another chain.
555
+ * @throws {ZeroExQuoteTypeMismatchError} when the quote mode is not the one the action requires.
556
+ * @throws {ZeroExQuoteTokenMismatchError} when the quote, the AllowanceHolder token or Settler's buy token is
557
+ * not the action's sell or buy token.
558
+ * @throws {ZeroExExactOutputUnsupportedError} when an exact-output action swaps a native and wrapped-native pair.
559
+ * @throws {ZeroExQuoteTakerMismatchError} when the quote's taker is not the leverage bundle.
560
+ * @throws {ZeroExQuoteTxOriginMismatchError} when the quote's txOrigin is not `txOrigin`, or the user by default.
561
+ * @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address.
562
+ * @throws {ZeroExQuoteNonZeroValueError} when the quote sends native value.
563
+ * @throws {ZeroExQuoteTargetMismatchError} when the quote does not call AllowanceHolder.
564
+ * @throws {ZeroExUnknownSwapKindError} when `kind` is not one of the three leverage swap kinds.
565
+ * @throws {InvalidBigIntInputError} when `maxSwapInput`, the quote's `buyAmount`, its floor (`minBuyAmount` for an
566
+ * exact input, `buyAmount` for an exact output) or its sell amount (`sellAmount` for an exact input, `maxSellAmount` for an
567
+ * exact output) is missing or not a bigint, before any calldata is decoded.
568
+ * @throws {NonPositiveInputError} when `maxSwapInput` is not positive.
569
+ * @throws {InputExceedsMaxError} when `maxSwapInput` exceeds `uint256`.
570
+ * @throws {InvalidBigIntInputError} when `deadline` is missing or not a bigint.
571
+ * @throws {NonPositiveInputError} when `deadline` is not positive.
572
+ * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256`.
573
+ * @throws {ZeroExSettlerOperatorTargetMismatchError} when the AllowanceHolder target is not the operator.
574
+ * @throws {ZeroExQuoteAmountExceedsCapError} when AllowanceHolder may pull more than `maxSwapInput`.
575
+ * @throws {ZeroExQuoteSellAmountMismatchError} when AllowanceHolder pulls another amount than the quote's sell
576
+ * amount.
577
+ * @throws {ZeroExQuoteMalformedCalldataError} when the Settler layer decodes as an entry point other than `execute`,
578
+ * a permit, `NATIVE_CHECK` or `ATTEST` action is too short to hold its deadline, a `BASIC` or `BASIC_PUSH` action
579
+ * does not decode, or a `SELECT` action does not decode or nests deeper than three levels.
580
+ * @throws {ZeroExQuoteUndecodableCalldataError} when the AllowanceHolder or Settler layer does not decode.
581
+ * @throws {ZeroExQuoteSignedOrderActionError} when a Settler action, or one in a `SELECT` candidate, fills a signed
582
+ * order (`RFQ`, `RFQ_VIP`, `BEBOP` or any `METATXN_*` action).
583
+ * @throws {ZeroExQuoteUnsupportedActionError} when a Settler action is not one the SDK classes, or stands where it may
584
+ * not: a permit action other than the first top-level one, or a `NATIVE_CHECK` or `ATTEST` in a `SELECT` candidate.
585
+ * @throws {ZeroExQuoteShortTimeBoundError} when a `BASIC` or `BASIC_PUSH` call holds a word that looks like a deadline
586
+ * before `deadline`.
587
+ * @throws {ZeroExQuoteDeadlineMismatchError} when the permit deadline is not `deadline`, or a `NATIVE_CHECK` or
588
+ * `ATTEST` deadline is below it.
589
+ * @throws {ZeroExQuoteRecipientMismatchError} when the Settler slippage pays anyone but the leverage bundle.
590
+ * @throws {ZeroExQuoteMinAmountOutMismatchError} when the Settler slippage's minimum output is zero or below the
591
+ * quote's floor (`minBuyAmount` for an exact input, `buyAmount` for an exact output).
592
+ * @example
593
+ * ```ts
594
+ * import { fetchZeroExQuote, validateZeroExQuote } from "@morpho-org/morpho-sdk";
595
+ * import { isBlueZeroExLeverageChain } from "@morpho-org/morpho-sdk/addresses";
596
+ *
597
+ * declare const marketParams: { loanToken: `0x${string}`; collateralToken: `0x${string}` };
598
+ * declare const userAddress: `0x${string}`;
599
+ * // Swap input cap the transaction enforces: the bundle's `maxIn`, as the builder signs it. The leverage builders
600
+ * // derive it from the action's limits (a Lever's `maxSwapIn`, a Delever's `maxCollateralToSell`, a Close's
601
+ * // `maxCollateralIn`); a direct caller must bound it on its own, not copy it from the quote.
602
+ * declare const maxSwapInput: bigint;
603
+ * // Deadline the action signs, in seconds: the leverage builders sign the leverage data's block timestamp plus one hour.
604
+ * declare const deadline: bigint;
605
+ *
606
+ * // Leverage needs a ZeroExLeverageBundlesV1 registered on the chain. None ships yet: register a verified
607
+ * // address with `registerCustomAddresses` first, or the call throws LeverageUnsupportedChainError before any request.
608
+ * if (!isBlueZeroExLeverageChain(8453)) throw new Error("No leverage bundle is registered on Base yet.");
609
+ * const quote = await fetchZeroExQuote({
610
+ * chainId: 8453,
611
+ * kind: "lever",
612
+ * marketParams,
613
+ * userAddress,
614
+ * amount: 10n ** 18n,
615
+ * slippage: 5_000_000_000_000_000n,
616
+ * deadline,
617
+ * apiKey: process.env.ZEROEX_API_KEY!,
618
+ * });
619
+ * const swap = validateZeroExQuote({
620
+ * quote,
621
+ * kind: "lever",
622
+ * chainId: 8453,
623
+ * marketParams,
624
+ * userAddress,
625
+ * maxSwapInput,
626
+ * deadline,
627
+ * });
628
+ * ```
629
+ */
630
+ export function validateZeroExQuote(params) {
631
+ const { quote, chainId, userAddress, maxSwapInput, deadline } = params;
632
+ const bundle = getZeroExLeverageBundle(chainId);
633
+ const txOrigin = resolveZeroExTxOrigin(params.txOrigin, userAddress);
634
+ validateZeroExSwapBounds(maxSwapInput, deadline);
635
+ if (quote.chainId !== chainId) {
636
+ throw new ZeroExQuoteChainMismatchError({
637
+ expected: chainId,
638
+ actual: quote.chainId,
639
+ });
640
+ }
641
+ const route = getZeroExSwapRoute(params.kind, params.marketParams);
642
+ if (quote.mode !== route.mode) {
643
+ throw new ZeroExQuoteTypeMismatchError({
644
+ expected: route.mode,
645
+ actual: quote.mode,
646
+ });
647
+ }
648
+ if (!isAddressEqual(quote.sellToken, route.sellToken)) {
649
+ throw new ZeroExQuoteTokenMismatchError({
650
+ field: "sellToken",
651
+ expected: route.sellToken,
652
+ actual: quote.sellToken,
653
+ });
654
+ }
655
+ if (!isAddressEqual(quote.buyToken, route.buyToken)) {
656
+ throw new ZeroExQuoteTokenMismatchError({
657
+ field: "buyToken",
658
+ expected: route.buyToken,
659
+ actual: quote.buyToken,
660
+ });
661
+ }
662
+ validateZeroExExactOutputPair({ chainId, ...route });
663
+ if (!isAddressEqual(quote.taker, bundle)) {
664
+ throw new ZeroExQuoteTakerMismatchError({
665
+ expected: bundle,
666
+ actual: quote.taker,
667
+ });
668
+ }
669
+ if (!isAddressEqual(quote.txOrigin, txOrigin)) {
670
+ throw new ZeroExQuoteTxOriginMismatchError({
671
+ expected: txOrigin,
672
+ actual: quote.txOrigin,
673
+ });
674
+ }
675
+ if (quote.transaction.value !== 0n) {
676
+ throw new ZeroExQuoteNonZeroValueError(quote.transaction.value);
677
+ }
678
+ if (!isAddressEqual(quote.transaction.to, ZERO_EX_ALLOWANCE_HOLDER_ADDRESS)) {
679
+ throw new ZeroExQuoteTargetMismatchError({
680
+ expected: ZERO_EX_ALLOWANCE_HOLDER_ADDRESS,
681
+ actual: quote.transaction.to,
682
+ });
683
+ }
684
+ // Checked before decoding, so a quote without a floor or a sell amount is refused whether or not it decodes.
685
+ const { quotedMinAmountOut, quotedSellAmount } = readZeroExQuoteAmounts(quote);
686
+ const exec = tryDecodeAllowanceHolderExec(quote.transaction.data);
687
+ if (exec === undefined) {
688
+ throw new ZeroExQuoteUndecodableCalldataError({
689
+ layer: "allowanceHolder",
690
+ bundle,
691
+ });
692
+ }
693
+ const [operator, token, amount, target, settlerData] = exec;
694
+ if (!isAddressEqual(target, operator)) {
695
+ throw new ZeroExSettlerOperatorTargetMismatchError({ operator, target });
696
+ }
697
+ if (!isAddressEqual(token, route.sellToken)) {
698
+ throw new ZeroExQuoteTokenMismatchError({
699
+ field: "sellToken",
700
+ expected: route.sellToken,
701
+ actual: token,
702
+ });
703
+ }
704
+ if (amount > maxSwapInput) {
705
+ throw new ZeroExQuoteAmountExceedsCapError({ amount, cap: maxSwapInput });
706
+ }
707
+ if (amount !== quotedSellAmount) {
708
+ throw new ZeroExQuoteSellAmountMismatchError({
709
+ expected: quotedSellAmount,
710
+ actual: amount,
711
+ });
712
+ }
713
+ const execute = tryDecodeSettlerExecute(settlerData);
714
+ if (execute === undefined) {
715
+ throw new ZeroExQuoteUndecodableCalldataError({
716
+ layer: "settler",
717
+ bundle,
718
+ });
719
+ }
720
+ const [{ recipient, buyToken, minAmountOut }, actions] = execute;
721
+ assertSettlerActions(actions, { deadline, depth: 0, path: "" });
722
+ const validated = {
723
+ ...quote,
724
+ settler: operator,
725
+ swapData: quote.transaction.data,
726
+ swapInput: amount,
727
+ settlerMinAmountOut: minAmountOut,
728
+ };
729
+ if (isAddressEqual(recipient, zeroAddress) &&
730
+ isAddressEqual(buyToken, zeroAddress) &&
731
+ minAmountOut === 0n) {
732
+ return validated;
733
+ }
734
+ if (!isAddressEqual(recipient, bundle)) {
735
+ throw new ZeroExQuoteRecipientMismatchError({
736
+ expected: bundle,
737
+ actual: recipient,
738
+ });
739
+ }
740
+ if (!isAddressEqual(buyToken, route.buyToken)) {
741
+ throw new ZeroExQuoteTokenMismatchError({
742
+ field: "buyToken",
743
+ expected: route.buyToken,
744
+ actual: buyToken,
745
+ });
746
+ }
747
+ if (minAmountOut === 0n || minAmountOut < quotedMinAmountOut) {
748
+ throw new ZeroExQuoteMinAmountOutMismatchError({
749
+ expected: quotedMinAmountOut,
750
+ actual: minAmountOut,
751
+ });
752
+ }
753
+ return validated;
754
+ }