@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
@@ -4,6 +4,7 @@ export * from "./client/index.js";
4
4
  export type { SupplyCollateralWithNativeParams } from "./entities/midnight/types.js";
5
5
  export * from "./entities/requirements/index.js";
6
6
  export * from "./helpers/index.js";
7
+ export { fetchZeroExQuote, ZERO_EX_LEVERAGE_EXCLUDED_SOURCES, } from "./reads/fetchZeroExQuote.js";
7
8
  export type { Action, BlueBorrowPlanParams, BlueMarketSnapshot, BluePositionSnapshot, BlueRefinancePlanParams, BlueRepayPlanParams, BlueRepayWithdrawCollateralPlanParams, BlueSupplyCollateralBorrowPlanParams, BlueSupplyCollateralPlanParams, BlueSupplyPlanParams, BlueWithdrawBuyCallbackPlanParams, BlueWithdrawCollateralPlanParams, BlueWithdrawPlanParams, Funding, IntentParams, MidnightCancelOffersPlanParams, MidnightMakeBorrowPlanParams, MidnightMakeLendPlanParams, MidnightMakeRepayPlanParams, MidnightMakerPublicationPlanParams, MidnightMakeWithdrawPlanParams, MidnightRedeemPlanParams, MidnightRepayWithdrawCollateralPlanParams, MidnightSupplyBlueMakeLendPlanParams, MidnightSupplyCollateralBatchPlanParams, MidnightSupplyCollateralMakeBorrowPlanParams, MidnightSupplyCollateralPlanParams, MidnightSupplyCollateralTakeBorrowPlanParams, MidnightSupplyCollateralWithNativePlanParams, MidnightTakeBorrowPlanParams, MidnightTakeLendPlanParams, MidnightTakeRepayWithdrawCollateralPlanParams, MidnightTakeWithdrawPlanParams, MidnightWithdrawCollateralBatchPlanParams, MidnightWithdrawCollateralPlanParams, ReferralFee, SignatureRequest, Step, TransactionPlan, VaultV1DepositPlanParams, VaultV1InKindRedeemPlanParams, VaultV1MigrateToV2PlanParams, VaultV1RedeemPlanParams, VaultV1WithdrawPlanParams, VaultV2DepositPlanParams, VaultV2ForceRedeemPlanParams, VaultV2ForceWithdrawPlanParams, VaultV2InKindRedeemPlanParams, VaultV2RedeemPlanParams, VaultV2WithdrawPlanParams, } from "./transactionPlan/index.js";
8
9
  export { applySignatures, BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, MidnightTakeCreditInsufficientError, NonIntegerInputError, parseTransactionPlan, prepareBlueBorrow, prepareBlueRefinance, prepareBlueRepay, prepareBlueRepayWithdrawCollateral, prepareBlueSupply, prepareBlueSupplyCollateral, prepareBlueSupplyCollateralBorrow, prepareBlueWithdraw, prepareBlueWithdrawBuyCallback, prepareBlueWithdrawCollateral, prepareMidnightCancelOffers, prepareMidnightMakeBorrow, prepareMidnightMakeLend, prepareMidnightMakeRepay, prepareMidnightMakeWithdraw, prepareMidnightRedeem, prepareMidnightRepayWithdrawCollateral, prepareMidnightSupplyBlueMakeLend, prepareMidnightSupplyCollateral, prepareMidnightSupplyCollateralBatch, prepareMidnightSupplyCollateralMakeBorrow, prepareMidnightSupplyCollateralTakeBorrow, prepareMidnightSupplyCollateralWithNative, prepareMidnightTakeBorrow, prepareMidnightTakeLend, prepareMidnightTakeRepayWithdrawCollateral, prepareMidnightTakeWithdraw, prepareMidnightWithdrawCollateral, prepareMidnightWithdrawCollateralBatch, prepareVaultV1Deposit, prepareVaultV1InKindRedeem, prepareVaultV1MigrateToV2, prepareVaultV1Redeem, prepareVaultV1Withdraw, prepareVaultV2Deposit, prepareVaultV2ForceRedeem, prepareVaultV2ForceWithdraw, prepareVaultV2InKindRedeem, prepareVaultV2Redeem, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, validateBlueMarketSnapshot, ZeroAccountError, } from "./transactionPlan/index.js";
9
10
  export * from "./types/index.js";
package/lib/esm/index.js CHANGED
@@ -3,6 +3,7 @@ export { validateClientChainId } from "./actions/requirements/validateClientChai
3
3
  export * from "./client/index.js";
4
4
  export * from "./entities/requirements/index.js";
5
5
  export * from "./helpers/index.js";
6
+ export { fetchZeroExQuote, ZERO_EX_LEVERAGE_EXCLUDED_SOURCES, } from "./reads/fetchZeroExQuote.js";
6
7
  export { applySignatures, BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, MidnightTakeCreditInsufficientError, NonIntegerInputError, parseTransactionPlan, prepareBlueBorrow, prepareBlueRefinance, prepareBlueRepay, prepareBlueRepayWithdrawCollateral, prepareBlueSupply, prepareBlueSupplyCollateral, prepareBlueSupplyCollateralBorrow, prepareBlueWithdraw, prepareBlueWithdrawBuyCallback, prepareBlueWithdrawCollateral, prepareMidnightCancelOffers, prepareMidnightMakeBorrow, prepareMidnightMakeLend, prepareMidnightMakeRepay, prepareMidnightMakeWithdraw, prepareMidnightRedeem, prepareMidnightRepayWithdrawCollateral, prepareMidnightSupplyBlueMakeLend, prepareMidnightSupplyCollateral, prepareMidnightSupplyCollateralBatch, prepareMidnightSupplyCollateralMakeBorrow, prepareMidnightSupplyCollateralTakeBorrow, prepareMidnightSupplyCollateralWithNative, prepareMidnightTakeBorrow, prepareMidnightTakeLend, prepareMidnightTakeRepayWithdrawCollateral, prepareMidnightTakeWithdraw, prepareMidnightWithdrawCollateral, prepareMidnightWithdrawCollateralBatch, prepareVaultV1Deposit, prepareVaultV1InKindRedeem, prepareVaultV1MigrateToV2, prepareVaultV1Redeem, prepareVaultV1Withdraw, prepareVaultV2Deposit, prepareVaultV2ForceRedeem, prepareVaultV2ForceWithdraw, prepareVaultV2InKindRedeem, prepareVaultV2Redeem, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, validateBlueMarketSnapshot, ZeroAccountError, } from "./transactionPlan/index.js";
7
8
  export * from "./types/index.js";
8
9
  export { version } from "./version.js";
@@ -1 +1,2 @@
1
- export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
1
+ export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
2
+ export { InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, } from "@morpho-org/morpho-ts";
@@ -1 +1,2 @@
1
- export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
1
+ export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
2
+ export { InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, } from "@morpho-org/morpho-ts";
@@ -0,0 +1,25 @@
1
+ import type { AddressLabel } from "@morpho-org/morpho-ts";
2
+ import type { Address, Client } from "viem";
3
+ /**
4
+ * Asserts that a configured contract address holds deployed code on the client's chain.
5
+ *
6
+ * A call to a code-less address succeeds on-chain as a no-op, so entity flows check each
7
+ * registered target before returning requirements. The `eth_getCode` read runs at the
8
+ * client's default block; transport failures propagate unwrapped because they are
9
+ * infrastructure failures, not configuration failures.
10
+ *
11
+ * @param client - Connected viem client used for the `eth_getCode` read.
12
+ * @param params - Assertion parameters.
13
+ * @param params.address - Contract address expected to hold code.
14
+ * @param params.chainId - Chain id the flow targets, reported on the error.
15
+ * @param params.role - Registry label naming the address's role in the flow.
16
+ * @returns Nothing when the address holds code.
17
+ * @throws {MissingContractCodeError} when the address has no deployed bytecode.
18
+ * @throws {viem.BaseError} when the `eth_getCode` read itself fails.
19
+ * @internal
20
+ */
21
+ export declare const assertContractCode: (client: Client, params: {
22
+ readonly address: Address;
23
+ readonly chainId: number;
24
+ readonly role: AddressLabel;
25
+ }) => Promise<void>;
@@ -0,0 +1,26 @@
1
+ import { getBytecode } from "viem/actions";
2
+ import { MissingContractCodeError } from "../types/index.js";
3
+ /**
4
+ * Asserts that a configured contract address holds deployed code on the client's chain.
5
+ *
6
+ * A call to a code-less address succeeds on-chain as a no-op, so entity flows check each
7
+ * registered target before returning requirements. The `eth_getCode` read runs at the
8
+ * client's default block; transport failures propagate unwrapped because they are
9
+ * infrastructure failures, not configuration failures.
10
+ *
11
+ * @param client - Connected viem client used for the `eth_getCode` read.
12
+ * @param params - Assertion parameters.
13
+ * @param params.address - Contract address expected to hold code.
14
+ * @param params.chainId - Chain id the flow targets, reported on the error.
15
+ * @param params.role - Registry label naming the address's role in the flow.
16
+ * @returns Nothing when the address holds code.
17
+ * @throws {MissingContractCodeError} when the address has no deployed bytecode.
18
+ * @throws {viem.BaseError} when the `eth_getCode` read itself fails.
19
+ * @internal
20
+ */
21
+ export const assertContractCode = async (client, params) => {
22
+ const bytecode = await getBytecode(client, { address: params.address });
23
+ if (bytecode === undefined || bytecode === "0x") {
24
+ throw new MissingContractCodeError(params.address, params.chainId, params.role);
25
+ }
26
+ };
@@ -0,0 +1,123 @@
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
+ import { type Address } from "viem";
3
+ import type { ZeroExLeverageSwapKind, ZeroExQuote } from "../types/zeroEx.js";
4
+ /**
5
+ * 0x liquidity sources `fetchZeroExQuote` excludes from every leverage quote, on every chain, as the `excludedSources`
6
+ * request parameter. 0x (2026-12-02) confirmed that `0x_RFQ`, `Bebop`, `Swaap_V2` and `Native_V2` are its only
7
+ * request-for-quote or otherwise short-lived sources, and that the `deadline` parameter does not filter them: their
8
+ * fills carry the maker's own expiry. `Kipseli` is not on 0x's list, but recorded quotes through it carry the quote
9
+ * block's timestamp as a time bound that `validateZeroExQuote` refuses, so it is excluded too. `Metric_V2` is excluded
10
+ * on our own fork evidence: it is an oracle-fed venue whose calldata carries no time bound, and a replayed Base quote
11
+ * routed through it reverts with `FeedStalled()` from ten seconds after the quote. A source 0x adds later is not
12
+ * excluded here: `validateZeroExQuote` still refuses any signed-order fill or short time bound the calldata shows, but
13
+ * not a venue that, like `Metric_V2`, goes stale without one.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { ZERO_EX_LEVERAGE_EXCLUDED_SOURCES } from "@morpho-org/morpho-sdk";
18
+ *
19
+ * ZERO_EX_LEVERAGE_EXCLUDED_SOURCES; // "0x_RFQ,Bebop,Swaap_V2,Native_V2,Kipseli,Metric_V2"
20
+ * ```
21
+ */
22
+ export declare const ZERO_EX_LEVERAGE_EXCLUDED_SOURCES = "0x_RFQ,Bebop,Swaap_V2,Native_V2,Kipseli,Metric_V2";
23
+ /**
24
+ * Fetches the 0x allowance-holder quote for the swap of a ZeroExLeverageBundlesV1 action.
25
+ *
26
+ * The request is fixed by the action: taker and recipient the chain's leverage bundle, txOrigin the user unless
27
+ * `txOrigin` names the sender of the outer onchain transaction (a Safe's executing owner, an ERC-4337 bundler), `buyAmount` for
28
+ * Lever and the keep-collateral Close, `sellAmount` for Delever, and the caller's
29
+ * slippage passed to 0x (rounded down to 0x's parts-per-million) as the tolerance 0x should quote with: a nonzero
30
+ * slippage below one part per million (under 1e12, WAD-scaled) is sent as `slippagePpm` 0 without an error, so 0x
31
+ * quotes it with no tolerance. It always sends {@link ZERO_EX_LEVERAGE_EXCLUDED_SOURCES} as `excludedSources`, the
32
+ * sources 0x confirmed are request-for-quote or otherwise short-lived, plus Kipseli for its recorded time bound and
33
+ * Metric_V2 for its oracle-fed fork evidence. It sends `deadline`, which 0x writes as the deadline of the permit its
34
+ * Settler actions pull the sell token with, instead of its default of the quote block's timestamp plus 300 seconds,
35
+ * and as the router deadlines of its AMM calls. Neither request parameter is
36
+ * the guarantee on its own: `validateZeroExQuote` refuses a quote whose Settler actions fill a signed order or show a
37
+ * time bound short of `deadline`. A venue whose validity depends on an offchain keeper, with no time bound in the
38
+ * calldata, is kept out only by the excluded sources.
39
+ * The fetch
40
+ * never checks the response's amounts against an action bound: 0x applies that tolerance to its own minimum or
41
+ * sell cap, and the action's swap input cap and output floor are enforced separately.
42
+ * The response is parsed and checked against the request, but it stays untrusted: pass it to
43
+ * `validateZeroExQuote`, which the leverage builders also run. The response's `blockNumber` and `zid` are kept
44
+ * but never checked: the SDK sets no limit on a quote's age, and the only time bound is the leverage deadline the
45
+ * builders sign (the leverage data block plus one hour). This is the one network boundary of the
46
+ * leverage flow; the API key is only sent in the request header and never stored.
47
+ *
48
+ * @param params - Request parameters.
49
+ * @param params.chainId - Chain of the action.
50
+ * @param params.kind - Swap the action needs.
51
+ * @param params.marketParams - Market of the action.
52
+ * @param params.userAddress - Account whose position the action changes; the 0x `txOrigin` unless `txOrigin` is given.
53
+ * @param params.txOrigin - Sender of the outer onchain transaction (its `tx.origin`), when it is not `userAddress`:
54
+ * the owner EOA that executes a Safe transaction, or the bundler that submits an ERC-4337 UserOperation, not the
55
+ * wallet's signer. Defaults to `userAddress`; build the action with the same value.
56
+ * @param params.amount - Exact amount: the buy amount for exact-output swaps, the sell amount otherwise.
57
+ * @param params.slippage - Slippage tolerance, WAD-scaled.
58
+ * @param params.deadline - Permit deadline 0x writes into the quote, in seconds: the deadline the builder signs, the
59
+ * leverage data's block timestamp plus one hour, which `validateZeroExQuote` checks the quote against. 0x does not
60
+ * document this parameter. If 0x stops honoring it, `validateZeroExQuote` refuses every quote whose permit carries
61
+ * another deadline with `ZeroExQuoteDeadlineMismatchError`.
62
+ * @param params.apiKey - 0x API key, sent as the `0x-api-key` header.
63
+ * @param params.fetch - Fetch implementation. Defaults to the global `fetch`.
64
+ * @param params.signal - Optional abort signal for the request. The fetch sets no timeout of its own, so pass one,
65
+ * e.g. `signal: AbortSignal.timeout(10_000)`.
66
+ * @returns The parsed quote with its request context.
67
+ * @throws {LeverageUnsupportedChainError} when the chain has no AllowanceHolder at its Cancun address or no
68
+ * registered leverage bundle.
69
+ * @throws {InvalidBigIntInputError} when `amount`, `slippage` or `deadline` is missing or not a bigint.
70
+ * @throws {NonPositiveInputError} when `amount` or `deadline` is not positive.
71
+ * @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address.
72
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds `uint256`.
73
+ * @throws {NegativeInputError} when `slippage` is negative.
74
+ * @throws {ExcessiveSlippageToleranceError} when `slippage` is above `MAX_SLIPPAGE_TOLERANCE`.
75
+ * @throws {ZeroExExactOutputUnsupportedError} when an exact-output swap trades a native and wrapped-native pair.
76
+ * @throws {ZeroExUnknownSwapKindError} when `kind` is not one of the three leverage swap kinds.
77
+ * @throws {ZeroExQuoteRequestError} when the request fails, or 0x answers with a non-2xx status. A body that
78
+ * fails to download, with the failure (such as the caller's abort) as `cause`, reports `status: null` on a 2xx
79
+ * response and keeps the status, with `code: null`, on a non-2xx one.
80
+ * @throws {ZeroExQuoteNoLiquidityError} when 0x reports no liquidity.
81
+ * @throws {ZeroExQuoteMalformedResponseError} when the response does not have the documented shape or does not
82
+ * echo the requested amount.
83
+ * @throws {ZeroExQuoteTypeMismatchError} when 0x answers in another quote mode.
84
+ * @throws {ZeroExQuoteTokenMismatchError} when 0x answers for other tokens.
85
+ * @example
86
+ * ```ts
87
+ * import { fetchZeroExQuote } from "@morpho-org/morpho-sdk";
88
+ * import { isBlueZeroExLeverageChain } from "@morpho-org/morpho-sdk/addresses";
89
+ *
90
+ * declare const marketParams: { loanToken: `0x${string}`; collateralToken: `0x${string}` };
91
+ * declare const userAddress: `0x${string}`;
92
+ * // Deadline the action signs, in seconds: the leverage builders sign the leverage data's block timestamp plus one hour.
93
+ * declare const deadline: bigint;
94
+ *
95
+ * // Leverage needs a ZeroExLeverageBundlesV1 registered on the chain. None ships yet: register a verified
96
+ * // address with `registerCustomAddresses` first, or the call throws LeverageUnsupportedChainError before any request.
97
+ * if (!isBlueZeroExLeverageChain(8453)) throw new Error("No leverage bundle is registered on Base yet.");
98
+ * const quote = await fetchZeroExQuote({
99
+ * chainId: 8453,
100
+ * kind: "delever",
101
+ * marketParams,
102
+ * userAddress,
103
+ * amount: 10n ** 18n,
104
+ * slippage: 5_000_000_000_000_000n,
105
+ * deadline,
106
+ * apiKey: process.env.ZEROEX_API_KEY!,
107
+ * signal: AbortSignal.timeout(10_000), // the fetch sets no timeout of its own
108
+ * });
109
+ * ```
110
+ */
111
+ export declare function fetchZeroExQuote(params: {
112
+ readonly chainId: number;
113
+ readonly kind: ZeroExLeverageSwapKind;
114
+ readonly marketParams: Pick<MarketParams, "loanToken" | "collateralToken">;
115
+ readonly userAddress: Address;
116
+ readonly txOrigin?: Address;
117
+ readonly amount: bigint;
118
+ readonly slippage: bigint;
119
+ readonly deadline: bigint;
120
+ readonly apiKey: string;
121
+ readonly fetch?: typeof fetch;
122
+ readonly signal?: AbortSignal;
123
+ }): Promise<ZeroExQuote>;
@@ -0,0 +1,326 @@
1
+ import { _try } from "@morpho-org/morpho-ts";
2
+ import { isAddress, isAddressEqual, isHex, maxUint256, } from "viem";
3
+ import { validateDeadline, validateSlippageTolerance, validateUint256Field, } from "../helpers/validate.js";
4
+ import { getZeroExLeverageBundle, getZeroExSwapRoute, resolveZeroExTxOrigin, toZeroExSlippagePpm, validateZeroExExactOutputPair, } from "../helpers/zeroExQuote.js";
5
+ import { InvalidBigIntInputError, NonPositiveInputError, ZeroExQuoteMalformedResponseError, ZeroExQuoteNoLiquidityError, ZeroExQuoteRequestError, ZeroExQuoteTokenMismatchError, ZeroExQuoteTypeMismatchError, } from "../types/index.js";
6
+ const ZERO_EX_QUOTE_URL = "https://api.0x.org/swap/allowance-holder/quote";
7
+ const ZERO_EX_API_VERSION = "v2";
8
+ /**
9
+ * 0x liquidity sources `fetchZeroExQuote` excludes from every leverage quote, on every chain, as the `excludedSources`
10
+ * request parameter. 0x (2026-12-02) confirmed that `0x_RFQ`, `Bebop`, `Swaap_V2` and `Native_V2` are its only
11
+ * request-for-quote or otherwise short-lived sources, and that the `deadline` parameter does not filter them: their
12
+ * fills carry the maker's own expiry. `Kipseli` is not on 0x's list, but recorded quotes through it carry the quote
13
+ * block's timestamp as a time bound that `validateZeroExQuote` refuses, so it is excluded too. `Metric_V2` is excluded
14
+ * on our own fork evidence: it is an oracle-fed venue whose calldata carries no time bound, and a replayed Base quote
15
+ * routed through it reverts with `FeedStalled()` from ten seconds after the quote. A source 0x adds later is not
16
+ * excluded here: `validateZeroExQuote` still refuses any signed-order fill or short time bound the calldata shows, but
17
+ * not a venue that, like `Metric_V2`, goes stale without one.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { ZERO_EX_LEVERAGE_EXCLUDED_SOURCES } from "@morpho-org/morpho-sdk";
22
+ *
23
+ * ZERO_EX_LEVERAGE_EXCLUDED_SOURCES; // "0x_RFQ,Bebop,Swaap_V2,Native_V2,Kipseli,Metric_V2"
24
+ * ```
25
+ */
26
+ export const ZERO_EX_LEVERAGE_EXCLUDED_SOURCES = "0x_RFQ,Bebop,Swaap_V2,Native_V2,Kipseli,Metric_V2";
27
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
28
+ function readObject(body, field) {
29
+ const value = body[field];
30
+ if (!isObject(value)) {
31
+ throw new ZeroExQuoteMalformedResponseError({
32
+ reason: `${field} is not an object`,
33
+ });
34
+ }
35
+ return value;
36
+ }
37
+ function readString(body, field) {
38
+ const value = body[field];
39
+ if (typeof value !== "string") {
40
+ throw new ZeroExQuoteMalformedResponseError({
41
+ reason: `${field} is not a string`,
42
+ });
43
+ }
44
+ return value;
45
+ }
46
+ const UINT256_MAX_DIGITS = maxUint256.toString().length;
47
+ function readAmount(body, field) {
48
+ const value = readString(body, field);
49
+ if (!/^\d+$/.test(value)) {
50
+ throw new ZeroExQuoteMalformedResponseError({
51
+ reason: `${field} "${value}" is not a non-negative integer string`,
52
+ });
53
+ }
54
+ if (value.length > UINT256_MAX_DIGITS) {
55
+ throw new ZeroExQuoteMalformedResponseError({
56
+ reason: field + " has more than " + UINT256_MAX_DIGITS + " digits",
57
+ });
58
+ }
59
+ const amount = BigInt(value);
60
+ if (amount > maxUint256) {
61
+ throw new ZeroExQuoteMalformedResponseError({
62
+ reason: field + " exceeds uint256",
63
+ });
64
+ }
65
+ return amount;
66
+ }
67
+ function readAddress(body, field) {
68
+ const value = readString(body, field);
69
+ if (!isAddress(value, { strict: false })) {
70
+ throw new ZeroExQuoteMalformedResponseError({
71
+ reason: `${field} "${value}" is not an address`,
72
+ });
73
+ }
74
+ return value;
75
+ }
76
+ function readHex(body, field) {
77
+ const value = readString(body, field);
78
+ // isHex accepts an odd number of digits, which is no calldata: it must hold whole bytes.
79
+ if (!isHex(value) || value.length % 2 !== 0) {
80
+ throw new ZeroExQuoteMalformedResponseError({
81
+ reason: `${field} is not hex data of whole bytes`,
82
+ });
83
+ }
84
+ return value;
85
+ }
86
+ async function readBody(response) {
87
+ try {
88
+ return await response.text();
89
+ }
90
+ catch (error) {
91
+ throw new ZeroExQuoteRequestError({ status: response.ok ? null : response.status, code: null }, { cause: error });
92
+ }
93
+ }
94
+ function parseJson(text) {
95
+ try {
96
+ return JSON.parse(text);
97
+ }
98
+ catch (error) {
99
+ throw new ZeroExQuoteMalformedResponseError({ reason: "body is not JSON" }, { cause: error });
100
+ }
101
+ }
102
+ /**
103
+ * Fetches the 0x allowance-holder quote for the swap of a ZeroExLeverageBundlesV1 action.
104
+ *
105
+ * The request is fixed by the action: taker and recipient the chain's leverage bundle, txOrigin the user unless
106
+ * `txOrigin` names the sender of the outer onchain transaction (a Safe's executing owner, an ERC-4337 bundler), `buyAmount` for
107
+ * Lever and the keep-collateral Close, `sellAmount` for Delever, and the caller's
108
+ * slippage passed to 0x (rounded down to 0x's parts-per-million) as the tolerance 0x should quote with: a nonzero
109
+ * slippage below one part per million (under 1e12, WAD-scaled) is sent as `slippagePpm` 0 without an error, so 0x
110
+ * quotes it with no tolerance. It always sends {@link ZERO_EX_LEVERAGE_EXCLUDED_SOURCES} as `excludedSources`, the
111
+ * sources 0x confirmed are request-for-quote or otherwise short-lived, plus Kipseli for its recorded time bound and
112
+ * Metric_V2 for its oracle-fed fork evidence. It sends `deadline`, which 0x writes as the deadline of the permit its
113
+ * Settler actions pull the sell token with, instead of its default of the quote block's timestamp plus 300 seconds,
114
+ * and as the router deadlines of its AMM calls. Neither request parameter is
115
+ * the guarantee on its own: `validateZeroExQuote` refuses a quote whose Settler actions fill a signed order or show a
116
+ * time bound short of `deadline`. A venue whose validity depends on an offchain keeper, with no time bound in the
117
+ * calldata, is kept out only by the excluded sources.
118
+ * The fetch
119
+ * never checks the response's amounts against an action bound: 0x applies that tolerance to its own minimum or
120
+ * sell cap, and the action's swap input cap and output floor are enforced separately.
121
+ * The response is parsed and checked against the request, but it stays untrusted: pass it to
122
+ * `validateZeroExQuote`, which the leverage builders also run. The response's `blockNumber` and `zid` are kept
123
+ * but never checked: the SDK sets no limit on a quote's age, and the only time bound is the leverage deadline the
124
+ * builders sign (the leverage data block plus one hour). This is the one network boundary of the
125
+ * leverage flow; the API key is only sent in the request header and never stored.
126
+ *
127
+ * @param params - Request parameters.
128
+ * @param params.chainId - Chain of the action.
129
+ * @param params.kind - Swap the action needs.
130
+ * @param params.marketParams - Market of the action.
131
+ * @param params.userAddress - Account whose position the action changes; the 0x `txOrigin` unless `txOrigin` is given.
132
+ * @param params.txOrigin - Sender of the outer onchain transaction (its `tx.origin`), when it is not `userAddress`:
133
+ * the owner EOA that executes a Safe transaction, or the bundler that submits an ERC-4337 UserOperation, not the
134
+ * wallet's signer. Defaults to `userAddress`; build the action with the same value.
135
+ * @param params.amount - Exact amount: the buy amount for exact-output swaps, the sell amount otherwise.
136
+ * @param params.slippage - Slippage tolerance, WAD-scaled.
137
+ * @param params.deadline - Permit deadline 0x writes into the quote, in seconds: the deadline the builder signs, the
138
+ * leverage data's block timestamp plus one hour, which `validateZeroExQuote` checks the quote against. 0x does not
139
+ * document this parameter. If 0x stops honoring it, `validateZeroExQuote` refuses every quote whose permit carries
140
+ * another deadline with `ZeroExQuoteDeadlineMismatchError`.
141
+ * @param params.apiKey - 0x API key, sent as the `0x-api-key` header.
142
+ * @param params.fetch - Fetch implementation. Defaults to the global `fetch`.
143
+ * @param params.signal - Optional abort signal for the request. The fetch sets no timeout of its own, so pass one,
144
+ * e.g. `signal: AbortSignal.timeout(10_000)`.
145
+ * @returns The parsed quote with its request context.
146
+ * @throws {LeverageUnsupportedChainError} when the chain has no AllowanceHolder at its Cancun address or no
147
+ * registered leverage bundle.
148
+ * @throws {InvalidBigIntInputError} when `amount`, `slippage` or `deadline` is missing or not a bigint.
149
+ * @throws {NonPositiveInputError} when `amount` or `deadline` is not positive.
150
+ * @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address.
151
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds `uint256`.
152
+ * @throws {NegativeInputError} when `slippage` is negative.
153
+ * @throws {ExcessiveSlippageToleranceError} when `slippage` is above `MAX_SLIPPAGE_TOLERANCE`.
154
+ * @throws {ZeroExExactOutputUnsupportedError} when an exact-output swap trades a native and wrapped-native pair.
155
+ * @throws {ZeroExUnknownSwapKindError} when `kind` is not one of the three leverage swap kinds.
156
+ * @throws {ZeroExQuoteRequestError} when the request fails, or 0x answers with a non-2xx status. A body that
157
+ * fails to download, with the failure (such as the caller's abort) as `cause`, reports `status: null` on a 2xx
158
+ * response and keeps the status, with `code: null`, on a non-2xx one.
159
+ * @throws {ZeroExQuoteNoLiquidityError} when 0x reports no liquidity.
160
+ * @throws {ZeroExQuoteMalformedResponseError} when the response does not have the documented shape or does not
161
+ * echo the requested amount.
162
+ * @throws {ZeroExQuoteTypeMismatchError} when 0x answers in another quote mode.
163
+ * @throws {ZeroExQuoteTokenMismatchError} when 0x answers for other tokens.
164
+ * @example
165
+ * ```ts
166
+ * import { fetchZeroExQuote } from "@morpho-org/morpho-sdk";
167
+ * import { isBlueZeroExLeverageChain } from "@morpho-org/morpho-sdk/addresses";
168
+ *
169
+ * declare const marketParams: { loanToken: `0x${string}`; collateralToken: `0x${string}` };
170
+ * declare const userAddress: `0x${string}`;
171
+ * // Deadline the action signs, in seconds: the leverage builders sign the leverage data's block timestamp plus one hour.
172
+ * declare const deadline: bigint;
173
+ *
174
+ * // Leverage needs a ZeroExLeverageBundlesV1 registered on the chain. None ships yet: register a verified
175
+ * // address with `registerCustomAddresses` first, or the call throws LeverageUnsupportedChainError before any request.
176
+ * if (!isBlueZeroExLeverageChain(8453)) throw new Error("No leverage bundle is registered on Base yet.");
177
+ * const quote = await fetchZeroExQuote({
178
+ * chainId: 8453,
179
+ * kind: "delever",
180
+ * marketParams,
181
+ * userAddress,
182
+ * amount: 10n ** 18n,
183
+ * slippage: 5_000_000_000_000_000n,
184
+ * deadline,
185
+ * apiKey: process.env.ZEROEX_API_KEY!,
186
+ * signal: AbortSignal.timeout(10_000), // the fetch sets no timeout of its own
187
+ * });
188
+ * ```
189
+ */
190
+ export async function fetchZeroExQuote(params) {
191
+ const { chainId, userAddress, amount, slippage, deadline } = params;
192
+ const taker = getZeroExLeverageBundle(chainId);
193
+ const txOrigin = resolveZeroExTxOrigin(params.txOrigin, userAddress);
194
+ if (typeof amount !== "bigint") {
195
+ throw new InvalidBigIntInputError("amount", amount);
196
+ }
197
+ if (amount <= 0n) {
198
+ throw new NonPositiveInputError("amount", amount);
199
+ }
200
+ validateUint256Field("amount", amount);
201
+ if (typeof slippage !== "bigint") {
202
+ throw new InvalidBigIntInputError("slippage", slippage);
203
+ }
204
+ validateSlippageTolerance(slippage);
205
+ if (typeof deadline !== "bigint") {
206
+ throw new InvalidBigIntInputError("deadline", deadline);
207
+ }
208
+ validateDeadline(deadline);
209
+ const route = getZeroExSwapRoute(params.kind, params.marketParams);
210
+ validateZeroExExactOutputPair({ chainId, ...route });
211
+ const url = new URL(ZERO_EX_QUOTE_URL);
212
+ url.search = new URLSearchParams({
213
+ chainId: String(chainId),
214
+ sellToken: route.sellToken,
215
+ buyToken: route.buyToken,
216
+ [route.mode === "exactOutput" ? "buyAmount" : "sellAmount"]: String(amount),
217
+ taker,
218
+ recipient: taker,
219
+ txOrigin,
220
+ slippagePpm: String(toZeroExSlippagePpm(slippage)),
221
+ excludedSources: ZERO_EX_LEVERAGE_EXCLUDED_SOURCES,
222
+ deadline: String(deadline),
223
+ }).toString();
224
+ let response;
225
+ try {
226
+ response = await (params.fetch ?? fetch)(url, {
227
+ headers: {
228
+ "0x-api-key": params.apiKey,
229
+ "0x-version": ZERO_EX_API_VERSION,
230
+ },
231
+ redirect: "error",
232
+ signal: params.signal,
233
+ });
234
+ }
235
+ catch (error) {
236
+ throw new ZeroExQuoteRequestError({ status: null, code: null }, { cause: error });
237
+ }
238
+ if (!response.ok) {
239
+ const text = await readBody(response);
240
+ const body = _try(() => parseJson(text), ZeroExQuoteMalformedResponseError);
241
+ throw new ZeroExQuoteRequestError({
242
+ status: response.status,
243
+ code: isObject(body) && typeof body.name === "string" ? body.name : null,
244
+ });
245
+ }
246
+ const body = parseJson(await readBody(response));
247
+ if (!isObject(body)) {
248
+ throw new ZeroExQuoteMalformedResponseError({
249
+ reason: "body is not an object",
250
+ });
251
+ }
252
+ if (body.liquidityAvailable !== true) {
253
+ if (body.liquidityAvailable === false) {
254
+ throw new ZeroExQuoteNoLiquidityError(route);
255
+ }
256
+ throw new ZeroExQuoteMalformedResponseError({
257
+ reason: "liquidityAvailable is not a boolean",
258
+ });
259
+ }
260
+ const mode = readString(body, "mode");
261
+ if (mode !== "exact-in" && mode !== "exact-out") {
262
+ throw new ZeroExQuoteMalformedResponseError({
263
+ reason: `mode "${mode}" is neither exact-in nor exact-out`,
264
+ });
265
+ }
266
+ const quoteMode = mode === "exact-out" ? "exactOutput" : "exactInput";
267
+ if (quoteMode !== route.mode) {
268
+ throw new ZeroExQuoteTypeMismatchError({
269
+ expected: route.mode,
270
+ actual: quoteMode,
271
+ });
272
+ }
273
+ const sellToken = readAddress(body, "sellToken");
274
+ const buyToken = readAddress(body, "buyToken");
275
+ for (const [field, actual] of [
276
+ ["sellToken", sellToken],
277
+ ["buyToken", buyToken],
278
+ ]) {
279
+ if (!isAddressEqual(actual, route[field])) {
280
+ throw new ZeroExQuoteTokenMismatchError({
281
+ field,
282
+ expected: route[field],
283
+ actual,
284
+ });
285
+ }
286
+ }
287
+ const amountField = route.mode === "exactOutput" ? "buyAmount" : "sellAmount";
288
+ const returnedAmount = readAmount(body, amountField);
289
+ if (returnedAmount !== amount) {
290
+ throw new ZeroExQuoteMalformedResponseError({
291
+ reason: `${amountField} "${returnedAmount}" differs from the requested "${amount}"`,
292
+ });
293
+ }
294
+ const transaction = readObject(body, "transaction");
295
+ const base = {
296
+ chainId,
297
+ taker,
298
+ txOrigin,
299
+ slippage,
300
+ sellToken,
301
+ buyToken,
302
+ blockNumber: readAmount(body, "blockNumber"),
303
+ zid: readString(body, "zid"),
304
+ transaction: {
305
+ to: readAddress(transaction, "to"),
306
+ data: readHex(transaction, "data"),
307
+ value: readAmount(transaction, "value"),
308
+ },
309
+ };
310
+ if (route.mode === "exactOutput") {
311
+ return {
312
+ ...base,
313
+ mode: "exactOutput",
314
+ buyAmount: amount,
315
+ maxSellAmount: readAmount(body, "maxSellAmount"),
316
+ estimatedNetSellAmount: readAmount(body, "estimatedNetSellAmount"),
317
+ };
318
+ }
319
+ return {
320
+ ...base,
321
+ mode: "exactInput",
322
+ sellAmount: amount,
323
+ buyAmount: readAmount(body, "buyAmount"),
324
+ minBuyAmount: readAmount(body, "minBuyAmount"),
325
+ };
326
+ }