@morpho-org/morpho-sdk 10.5.0-next.0 → 10.6.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -1
- package/lib/cjs/abis.d.ts +793 -0
- package/lib/cjs/abis.js +811 -1
- package/lib/cjs/actions/blue/close.d.ts +169 -0
- package/lib/cjs/actions/blue/close.js +270 -0
- package/lib/cjs/actions/blue/common.js +2 -2
- package/lib/cjs/actions/blue/delever.d.ts +156 -0
- package/lib/cjs/actions/blue/delever.js +223 -0
- package/lib/cjs/actions/blue/index.d.ts +3 -0
- package/lib/cjs/actions/blue/index.js +3 -0
- package/lib/cjs/actions/blue/lever.d.ts +184 -0
- package/lib/cjs/actions/blue/lever.js +272 -0
- package/lib/cjs/actions/blue/leverageIntent.d.ts +65 -0
- package/lib/cjs/actions/blue/leverageIntent.js +103 -0
- package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +16 -11
- package/lib/cjs/actions/midnight/takeBorrow.js +14 -8
- package/lib/cjs/actions/midnight/takeLend.js +15 -9
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
- package/lib/cjs/actions/midnight/takeWithdraw.js +14 -8
- package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
- package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.js +59 -0
- package/lib/cjs/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
- package/lib/cjs/actions/requirements/blue/getLeverageRequirements.js +193 -0
- package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
- package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.js +66 -0
- package/lib/cjs/actions/requirements/blue/index.d.ts +3 -0
- package/lib/cjs/actions/requirements/blue/index.js +17 -0
- package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
- package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
- package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +11 -6
- package/lib/cjs/actions/requirements/getRequirementsApproval.js +29 -5
- package/lib/cjs/addresses.d.ts +1 -1
- package/lib/cjs/addresses.js +6 -1
- package/lib/cjs/blue/addresses.d.ts +1 -1
- package/lib/cjs/blue/addresses.js +6 -1
- package/lib/cjs/constants.d.ts +1 -1
- package/lib/cjs/constants.js +7 -2
- package/lib/cjs/entities/blue/blue.d.ts +486 -2
- package/lib/cjs/entities/blue/blue.js +529 -34
- package/lib/cjs/entities/index.d.ts +1 -1
- package/lib/cjs/entities/midnight/midnight.d.ts +6 -0
- package/lib/cjs/entities/midnight/midnight.js +21 -2
- package/lib/cjs/entities/requirements/assertContractCode.d.ts +0 -23
- package/lib/cjs/entities/requirements/assertContractCode.js +3 -28
- package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +117 -0
- package/lib/cjs/entities/vaultV2BlueReallocationData.js +226 -2
- package/lib/cjs/helpers/constant.d.ts +41 -0
- package/lib/cjs/helpers/constant.js +42 -1
- package/lib/cjs/helpers/getZeroExLeverageBundle.d.ts +13 -0
- package/lib/cjs/helpers/getZeroExLeverageBundle.js +27 -0
- package/lib/cjs/helpers/index.d.ts +4 -1
- package/lib/cjs/helpers/index.js +29 -1
- package/lib/cjs/helpers/leverage/index.d.ts +1 -0
- package/lib/cjs/helpers/leverage/index.js +11 -0
- package/lib/cjs/helpers/leverage/limits.d.ts +472 -0
- package/lib/cjs/helpers/leverage/limits.js +715 -0
- package/lib/cjs/helpers/leverage/positionMarket.d.ts +17 -0
- package/lib/cjs/helpers/leverage/positionMarket.js +28 -0
- package/lib/cjs/helpers/leverage/reallocations.d.ts +159 -0
- package/lib/cjs/helpers/leverage/reallocations.js +276 -0
- package/lib/cjs/helpers/validate.d.ts +14 -0
- package/lib/cjs/helpers/validate.js +25 -1
- package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
- package/lib/cjs/helpers/validateRequirementSpender.js +4 -0
- package/lib/cjs/helpers/zeroExQuote.d.ts +250 -0
- package/lib/cjs/helpers/zeroExQuote.js +763 -0
- package/lib/cjs/index.d.ts +1 -0
- package/lib/cjs/index.js +5 -2
- package/lib/cjs/reads/assertContractCode.d.ts +25 -0
- package/lib/cjs/reads/assertContractCode.js +30 -0
- package/lib/cjs/reads/fetchZeroExQuote.d.ts +123 -0
- package/lib/cjs/reads/fetchZeroExQuote.js +330 -0
- package/lib/cjs/transactionPlan/midnight/takeBorrow.d.ts +4 -0
- package/lib/cjs/transactionPlan/midnight/takeBorrow.js +8 -2
- package/lib/cjs/types/action.d.ts +130 -1
- package/lib/cjs/types/error.d.ts +84 -0
- package/lib/cjs/types/error.js +110 -3
- package/lib/cjs/types/index.d.ts +2 -0
- package/lib/cjs/types/index.js +2 -0
- package/lib/cjs/types/leverageError.d.ts +1552 -0
- package/lib/cjs/types/leverageError.js +1711 -0
- package/lib/cjs/types/zeroEx.d.ts +171 -0
- package/lib/cjs/types/zeroEx.js +2 -0
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/esm/abis.d.ts +793 -0
- package/lib/esm/abis.js +809 -0
- package/lib/esm/actions/blue/close.d.ts +169 -0
- package/lib/esm/actions/blue/close.js +266 -0
- package/lib/esm/actions/blue/common.js +3 -3
- package/lib/esm/actions/blue/delever.d.ts +156 -0
- package/lib/esm/actions/blue/delever.js +219 -0
- package/lib/esm/actions/blue/index.d.ts +3 -0
- package/lib/esm/actions/blue/index.js +3 -0
- package/lib/esm/actions/blue/lever.d.ts +184 -0
- package/lib/esm/actions/blue/lever.js +268 -0
- package/lib/esm/actions/blue/leverageIntent.d.ts +65 -0
- package/lib/esm/actions/blue/leverageIntent.js +96 -0
- package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +16 -11
- package/lib/esm/actions/midnight/takeBorrow.js +14 -8
- package/lib/esm/actions/midnight/takeLend.js +15 -9
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
- package/lib/esm/actions/midnight/takeWithdraw.js +14 -8
- package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
- package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.js +55 -0
- package/lib/esm/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
- package/lib/esm/actions/requirements/blue/getLeverageRequirements.js +189 -0
- package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
- package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.js +62 -0
- package/lib/esm/actions/requirements/blue/index.d.ts +3 -0
- package/lib/esm/actions/requirements/blue/index.js +3 -0
- package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
- package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
- package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +11 -6
- package/lib/esm/actions/requirements/getRequirementsApproval.js +29 -5
- package/lib/esm/addresses.d.ts +1 -1
- package/lib/esm/addresses.js +1 -1
- package/lib/esm/blue/addresses.d.ts +1 -1
- package/lib/esm/blue/addresses.js +1 -1
- package/lib/esm/constants.d.ts +1 -1
- package/lib/esm/constants.js +1 -1
- package/lib/esm/entities/blue/blue.d.ts +486 -2
- package/lib/esm/entities/blue/blue.js +501 -6
- package/lib/esm/entities/index.d.ts +1 -1
- package/lib/esm/entities/midnight/midnight.d.ts +6 -0
- package/lib/esm/entities/midnight/midnight.js +21 -2
- package/lib/esm/entities/requirements/assertContractCode.d.ts +0 -23
- package/lib/esm/entities/requirements/assertContractCode.js +1 -25
- package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +117 -0
- package/lib/esm/entities/vaultV2BlueReallocationData.js +227 -3
- package/lib/esm/helpers/constant.d.ts +41 -0
- package/lib/esm/helpers/constant.js +41 -0
- package/lib/esm/helpers/getZeroExLeverageBundle.d.ts +13 -0
- package/lib/esm/helpers/getZeroExLeverageBundle.js +23 -0
- package/lib/esm/helpers/index.d.ts +4 -1
- package/lib/esm/helpers/index.js +4 -1
- package/lib/esm/helpers/leverage/index.d.ts +1 -0
- package/lib/esm/helpers/leverage/index.js +1 -0
- package/lib/esm/helpers/leverage/limits.d.ts +472 -0
- package/lib/esm/helpers/leverage/limits.js +705 -0
- package/lib/esm/helpers/leverage/positionMarket.d.ts +17 -0
- package/lib/esm/helpers/leverage/positionMarket.js +24 -0
- package/lib/esm/helpers/leverage/reallocations.d.ts +159 -0
- package/lib/esm/helpers/leverage/reallocations.js +271 -0
- package/lib/esm/helpers/validate.d.ts +14 -0
- package/lib/esm/helpers/validate.js +25 -2
- package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
- package/lib/esm/helpers/validateRequirementSpender.js +5 -1
- package/lib/esm/helpers/zeroExQuote.d.ts +250 -0
- package/lib/esm/helpers/zeroExQuote.js +754 -0
- package/lib/esm/index.d.ts +1 -0
- package/lib/esm/index.js +1 -0
- package/lib/esm/reads/assertContractCode.d.ts +25 -0
- package/lib/esm/reads/assertContractCode.js +26 -0
- package/lib/esm/reads/fetchZeroExQuote.d.ts +123 -0
- package/lib/esm/reads/fetchZeroExQuote.js +326 -0
- package/lib/esm/transactionPlan/midnight/takeBorrow.d.ts +4 -0
- package/lib/esm/transactionPlan/midnight/takeBorrow.js +9 -3
- package/lib/esm/types/action.d.ts +130 -1
- package/lib/esm/types/error.d.ts +84 -0
- package/lib/esm/types/error.js +103 -0
- package/lib/esm/types/index.d.ts +2 -0
- package/lib/esm/types/index.js +2 -0
- package/lib/esm/types/leverageError.d.ts +1552 -0
- package/lib/esm/types/leverageError.js +1660 -0
- package/lib/esm/types/zeroEx.d.ts +171 -0
- package/lib/esm/types/zeroEx.js +1 -0
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/package.json +7 -7
package/lib/cjs/index.d.ts
CHANGED
|
@@ -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/cjs/index.js
CHANGED
|
@@ -14,14 +14,17 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.
|
|
18
|
-
exports.version = exports.ZeroAccountError = exports.validateBlueMarketSnapshot = exports.UnsupportedTransactionPlanVersionError = exports.UnsupportedTransactionPlanActionError = exports.TransactionPlanSignatureMismatchError = exports.serializeTransactionPlan = exports.prepareVaultV2Withdraw = exports.prepareVaultV2Redeem = exports.prepareVaultV2InKindRedeem = void 0;
|
|
17
|
+
exports.prepareVaultV2Deposit = exports.prepareVaultV1Withdraw = exports.prepareVaultV1Redeem = exports.prepareVaultV1MigrateToV2 = exports.prepareVaultV1InKindRedeem = exports.prepareVaultV1Deposit = exports.prepareMidnightWithdrawCollateralBatch = exports.prepareMidnightWithdrawCollateral = exports.prepareMidnightTakeWithdraw = exports.prepareMidnightTakeRepayWithdrawCollateral = exports.prepareMidnightTakeLend = exports.prepareMidnightTakeBorrow = exports.prepareMidnightSupplyCollateralWithNative = exports.prepareMidnightSupplyCollateralTakeBorrow = exports.prepareMidnightSupplyCollateralMakeBorrow = exports.prepareMidnightSupplyCollateralBatch = exports.prepareMidnightSupplyCollateral = exports.prepareMidnightSupplyBlueMakeLend = exports.prepareMidnightRepayWithdrawCollateral = exports.prepareMidnightRedeem = exports.prepareMidnightMakeWithdraw = exports.prepareMidnightMakeRepay = exports.prepareMidnightMakeLend = exports.prepareMidnightMakeBorrow = exports.prepareMidnightCancelOffers = exports.prepareBlueWithdrawCollateral = exports.prepareBlueWithdrawBuyCallback = exports.prepareBlueWithdraw = exports.prepareBlueSupplyCollateralBorrow = exports.prepareBlueSupplyCollateral = exports.prepareBlueSupply = exports.prepareBlueRepayWithdrawCollateral = exports.prepareBlueRepay = exports.prepareBlueRefinance = exports.prepareBlueBorrow = exports.parseTransactionPlan = exports.NonIntegerInputError = exports.MidnightTakeCreditInsufficientError = exports.InvalidTransactionPlanError = exports.InvalidCalldataOriginError = exports.IncompleteTransactionPlanError = exports.getPendingSignatureRequests = exports.buildTransactions = exports.buildTransaction = exports.BlueSnapshotStateMismatchError = exports.BlueSnapshotChainMismatchError = exports.applySignatures = exports.ZERO_EX_LEVERAGE_EXCLUDED_SOURCES = exports.fetchZeroExQuote = exports.validateClientChainId = void 0;
|
|
18
|
+
exports.version = exports.ZeroAccountError = exports.validateBlueMarketSnapshot = exports.UnsupportedTransactionPlanVersionError = exports.UnsupportedTransactionPlanActionError = exports.TransactionPlanSignatureMismatchError = exports.serializeTransactionPlan = exports.prepareVaultV2Withdraw = exports.prepareVaultV2Redeem = exports.prepareVaultV2InKindRedeem = exports.prepareVaultV2ForceWithdraw = exports.prepareVaultV2ForceRedeem = void 0;
|
|
19
19
|
__exportStar(require("./actions/index.js"), exports);
|
|
20
20
|
var validateClientChainId_js_1 = require("./actions/requirements/validateClientChainId.js");
|
|
21
21
|
Object.defineProperty(exports, "validateClientChainId", { enumerable: true, get: function () { return validateClientChainId_js_1.validateClientChainId; } });
|
|
22
22
|
__exportStar(require("./client/index.js"), exports);
|
|
23
23
|
__exportStar(require("./entities/requirements/index.js"), exports);
|
|
24
24
|
__exportStar(require("./helpers/index.js"), exports);
|
|
25
|
+
var fetchZeroExQuote_js_1 = require("./reads/fetchZeroExQuote.js");
|
|
26
|
+
Object.defineProperty(exports, "fetchZeroExQuote", { enumerable: true, get: function () { return fetchZeroExQuote_js_1.fetchZeroExQuote; } });
|
|
27
|
+
Object.defineProperty(exports, "ZERO_EX_LEVERAGE_EXCLUDED_SOURCES", { enumerable: true, get: function () { return fetchZeroExQuote_js_1.ZERO_EX_LEVERAGE_EXCLUDED_SOURCES; } });
|
|
25
28
|
var index_js_1 = require("./transactionPlan/index.js");
|
|
26
29
|
Object.defineProperty(exports, "applySignatures", { enumerable: true, get: function () { return index_js_1.applySignatures; } });
|
|
27
30
|
Object.defineProperty(exports, "BlueSnapshotChainMismatchError", { enumerable: true, get: function () { return index_js_1.BlueSnapshotChainMismatchError; } });
|
|
@@ -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,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertContractCode = void 0;
|
|
4
|
+
const actions_1 = require("viem/actions");
|
|
5
|
+
const index_js_1 = require("../types/index.js");
|
|
6
|
+
/**
|
|
7
|
+
* Asserts that a configured contract address holds deployed code on the client's chain.
|
|
8
|
+
*
|
|
9
|
+
* A call to a code-less address succeeds on-chain as a no-op, so entity flows check each
|
|
10
|
+
* registered target before returning requirements. The `eth_getCode` read runs at the
|
|
11
|
+
* client's default block; transport failures propagate unwrapped because they are
|
|
12
|
+
* infrastructure failures, not configuration failures.
|
|
13
|
+
*
|
|
14
|
+
* @param client - Connected viem client used for the `eth_getCode` read.
|
|
15
|
+
* @param params - Assertion parameters.
|
|
16
|
+
* @param params.address - Contract address expected to hold code.
|
|
17
|
+
* @param params.chainId - Chain id the flow targets, reported on the error.
|
|
18
|
+
* @param params.role - Registry label naming the address's role in the flow.
|
|
19
|
+
* @returns Nothing when the address holds code.
|
|
20
|
+
* @throws {MissingContractCodeError} when the address has no deployed bytecode.
|
|
21
|
+
* @throws {viem.BaseError} when the `eth_getCode` read itself fails.
|
|
22
|
+
* @internal
|
|
23
|
+
*/
|
|
24
|
+
const assertContractCode = async (client, params) => {
|
|
25
|
+
const bytecode = await (0, actions_1.getBytecode)(client, { address: params.address });
|
|
26
|
+
if (bytecode === undefined || bytecode === "0x") {
|
|
27
|
+
throw new index_js_1.MissingContractCodeError(params.address, params.chainId, params.role);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
exports.assertContractCode = assertContractCode;
|
|
@@ -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,330 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ZERO_EX_LEVERAGE_EXCLUDED_SOURCES = void 0;
|
|
4
|
+
exports.fetchZeroExQuote = fetchZeroExQuote;
|
|
5
|
+
const morpho_ts_1 = require("@morpho-org/morpho-ts");
|
|
6
|
+
const viem_1 = require("viem");
|
|
7
|
+
const validate_js_1 = require("../helpers/validate.js");
|
|
8
|
+
const zeroExQuote_js_1 = require("../helpers/zeroExQuote.js");
|
|
9
|
+
const index_js_1 = require("../types/index.js");
|
|
10
|
+
const ZERO_EX_QUOTE_URL = "https://api.0x.org/swap/allowance-holder/quote";
|
|
11
|
+
const ZERO_EX_API_VERSION = "v2";
|
|
12
|
+
/**
|
|
13
|
+
* 0x liquidity sources `fetchZeroExQuote` excludes from every leverage quote, on every chain, as the `excludedSources`
|
|
14
|
+
* request parameter. 0x (2026-12-02) confirmed that `0x_RFQ`, `Bebop`, `Swaap_V2` and `Native_V2` are its only
|
|
15
|
+
* request-for-quote or otherwise short-lived sources, and that the `deadline` parameter does not filter them: their
|
|
16
|
+
* fills carry the maker's own expiry. `Kipseli` is not on 0x's list, but recorded quotes through it carry the quote
|
|
17
|
+
* block's timestamp as a time bound that `validateZeroExQuote` refuses, so it is excluded too. `Metric_V2` is excluded
|
|
18
|
+
* on our own fork evidence: it is an oracle-fed venue whose calldata carries no time bound, and a replayed Base quote
|
|
19
|
+
* routed through it reverts with `FeedStalled()` from ten seconds after the quote. A source 0x adds later is not
|
|
20
|
+
* excluded here: `validateZeroExQuote` still refuses any signed-order fill or short time bound the calldata shows, but
|
|
21
|
+
* not a venue that, like `Metric_V2`, goes stale without one.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* import { ZERO_EX_LEVERAGE_EXCLUDED_SOURCES } from "@morpho-org/morpho-sdk";
|
|
26
|
+
*
|
|
27
|
+
* ZERO_EX_LEVERAGE_EXCLUDED_SOURCES; // "0x_RFQ,Bebop,Swaap_V2,Native_V2,Kipseli,Metric_V2"
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
exports.ZERO_EX_LEVERAGE_EXCLUDED_SOURCES = "0x_RFQ,Bebop,Swaap_V2,Native_V2,Kipseli,Metric_V2";
|
|
31
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
32
|
+
function readObject(body, field) {
|
|
33
|
+
const value = body[field];
|
|
34
|
+
if (!isObject(value)) {
|
|
35
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
36
|
+
reason: `${field} is not an object`,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
function readString(body, field) {
|
|
42
|
+
const value = body[field];
|
|
43
|
+
if (typeof value !== "string") {
|
|
44
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
45
|
+
reason: `${field} is not a string`,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
const UINT256_MAX_DIGITS = viem_1.maxUint256.toString().length;
|
|
51
|
+
function readAmount(body, field) {
|
|
52
|
+
const value = readString(body, field);
|
|
53
|
+
if (!/^\d+$/.test(value)) {
|
|
54
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
55
|
+
reason: `${field} "${value}" is not a non-negative integer string`,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (value.length > UINT256_MAX_DIGITS) {
|
|
59
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
60
|
+
reason: field + " has more than " + UINT256_MAX_DIGITS + " digits",
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
const amount = BigInt(value);
|
|
64
|
+
if (amount > viem_1.maxUint256) {
|
|
65
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
66
|
+
reason: field + " exceeds uint256",
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return amount;
|
|
70
|
+
}
|
|
71
|
+
function readAddress(body, field) {
|
|
72
|
+
const value = readString(body, field);
|
|
73
|
+
if (!(0, viem_1.isAddress)(value, { strict: false })) {
|
|
74
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
75
|
+
reason: `${field} "${value}" is not an address`,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
function readHex(body, field) {
|
|
81
|
+
const value = readString(body, field);
|
|
82
|
+
// isHex accepts an odd number of digits, which is no calldata: it must hold whole bytes.
|
|
83
|
+
if (!(0, viem_1.isHex)(value) || value.length % 2 !== 0) {
|
|
84
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
85
|
+
reason: `${field} is not hex data of whole bytes`,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
async function readBody(response) {
|
|
91
|
+
try {
|
|
92
|
+
return await response.text();
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
throw new index_js_1.ZeroExQuoteRequestError({ status: response.ok ? null : response.status, code: null }, { cause: error });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function parseJson(text) {
|
|
99
|
+
try {
|
|
100
|
+
return JSON.parse(text);
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({ reason: "body is not JSON" }, { cause: error });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Fetches the 0x allowance-holder quote for the swap of a ZeroExLeverageBundlesV1 action.
|
|
108
|
+
*
|
|
109
|
+
* The request is fixed by the action: taker and recipient the chain's leverage bundle, txOrigin the user unless
|
|
110
|
+
* `txOrigin` names the sender of the outer onchain transaction (a Safe's executing owner, an ERC-4337 bundler), `buyAmount` for
|
|
111
|
+
* Lever and the keep-collateral Close, `sellAmount` for Delever, and the caller's
|
|
112
|
+
* slippage passed to 0x (rounded down to 0x's parts-per-million) as the tolerance 0x should quote with: a nonzero
|
|
113
|
+
* slippage below one part per million (under 1e12, WAD-scaled) is sent as `slippagePpm` 0 without an error, so 0x
|
|
114
|
+
* quotes it with no tolerance. It always sends {@link ZERO_EX_LEVERAGE_EXCLUDED_SOURCES} as `excludedSources`, the
|
|
115
|
+
* sources 0x confirmed are request-for-quote or otherwise short-lived, plus Kipseli for its recorded time bound and
|
|
116
|
+
* Metric_V2 for its oracle-fed fork evidence. It sends `deadline`, which 0x writes as the deadline of the permit its
|
|
117
|
+
* Settler actions pull the sell token with, instead of its default of the quote block's timestamp plus 300 seconds,
|
|
118
|
+
* and as the router deadlines of its AMM calls. Neither request parameter is
|
|
119
|
+
* the guarantee on its own: `validateZeroExQuote` refuses a quote whose Settler actions fill a signed order or show a
|
|
120
|
+
* time bound short of `deadline`. A venue whose validity depends on an offchain keeper, with no time bound in the
|
|
121
|
+
* calldata, is kept out only by the excluded sources.
|
|
122
|
+
* The fetch
|
|
123
|
+
* never checks the response's amounts against an action bound: 0x applies that tolerance to its own minimum or
|
|
124
|
+
* sell cap, and the action's swap input cap and output floor are enforced separately.
|
|
125
|
+
* The response is parsed and checked against the request, but it stays untrusted: pass it to
|
|
126
|
+
* `validateZeroExQuote`, which the leverage builders also run. The response's `blockNumber` and `zid` are kept
|
|
127
|
+
* but never checked: the SDK sets no limit on a quote's age, and the only time bound is the leverage deadline the
|
|
128
|
+
* builders sign (the leverage data block plus one hour). This is the one network boundary of the
|
|
129
|
+
* leverage flow; the API key is only sent in the request header and never stored.
|
|
130
|
+
*
|
|
131
|
+
* @param params - Request parameters.
|
|
132
|
+
* @param params.chainId - Chain of the action.
|
|
133
|
+
* @param params.kind - Swap the action needs.
|
|
134
|
+
* @param params.marketParams - Market of the action.
|
|
135
|
+
* @param params.userAddress - Account whose position the action changes; the 0x `txOrigin` unless `txOrigin` is given.
|
|
136
|
+
* @param params.txOrigin - Sender of the outer onchain transaction (its `tx.origin`), when it is not `userAddress`:
|
|
137
|
+
* the owner EOA that executes a Safe transaction, or the bundler that submits an ERC-4337 UserOperation, not the
|
|
138
|
+
* wallet's signer. Defaults to `userAddress`; build the action with the same value.
|
|
139
|
+
* @param params.amount - Exact amount: the buy amount for exact-output swaps, the sell amount otherwise.
|
|
140
|
+
* @param params.slippage - Slippage tolerance, WAD-scaled.
|
|
141
|
+
* @param params.deadline - Permit deadline 0x writes into the quote, in seconds: the deadline the builder signs, the
|
|
142
|
+
* leverage data's block timestamp plus one hour, which `validateZeroExQuote` checks the quote against. 0x does not
|
|
143
|
+
* document this parameter. If 0x stops honoring it, `validateZeroExQuote` refuses every quote whose permit carries
|
|
144
|
+
* another deadline with `ZeroExQuoteDeadlineMismatchError`.
|
|
145
|
+
* @param params.apiKey - 0x API key, sent as the `0x-api-key` header.
|
|
146
|
+
* @param params.fetch - Fetch implementation. Defaults to the global `fetch`.
|
|
147
|
+
* @param params.signal - Optional abort signal for the request. The fetch sets no timeout of its own, so pass one,
|
|
148
|
+
* e.g. `signal: AbortSignal.timeout(10_000)`.
|
|
149
|
+
* @returns The parsed quote with its request context.
|
|
150
|
+
* @throws {LeverageUnsupportedChainError} when the chain has no AllowanceHolder at its Cancun address or no
|
|
151
|
+
* registered leverage bundle.
|
|
152
|
+
* @throws {InvalidBigIntInputError} when `amount`, `slippage` or `deadline` is missing or not a bigint.
|
|
153
|
+
* @throws {NonPositiveInputError} when `amount` or `deadline` is not positive.
|
|
154
|
+
* @throws {ZeroExInvalidTxOriginError} when `txOrigin` is given and is not a valid address.
|
|
155
|
+
* @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds `uint256`.
|
|
156
|
+
* @throws {NegativeInputError} when `slippage` is negative.
|
|
157
|
+
* @throws {ExcessiveSlippageToleranceError} when `slippage` is above `MAX_SLIPPAGE_TOLERANCE`.
|
|
158
|
+
* @throws {ZeroExExactOutputUnsupportedError} when an exact-output swap trades a native and wrapped-native pair.
|
|
159
|
+
* @throws {ZeroExUnknownSwapKindError} when `kind` is not one of the three leverage swap kinds.
|
|
160
|
+
* @throws {ZeroExQuoteRequestError} when the request fails, or 0x answers with a non-2xx status. A body that
|
|
161
|
+
* fails to download, with the failure (such as the caller's abort) as `cause`, reports `status: null` on a 2xx
|
|
162
|
+
* response and keeps the status, with `code: null`, on a non-2xx one.
|
|
163
|
+
* @throws {ZeroExQuoteNoLiquidityError} when 0x reports no liquidity.
|
|
164
|
+
* @throws {ZeroExQuoteMalformedResponseError} when the response does not have the documented shape or does not
|
|
165
|
+
* echo the requested amount.
|
|
166
|
+
* @throws {ZeroExQuoteTypeMismatchError} when 0x answers in another quote mode.
|
|
167
|
+
* @throws {ZeroExQuoteTokenMismatchError} when 0x answers for other tokens.
|
|
168
|
+
* @example
|
|
169
|
+
* ```ts
|
|
170
|
+
* import { fetchZeroExQuote } from "@morpho-org/morpho-sdk";
|
|
171
|
+
* import { isBlueZeroExLeverageChain } from "@morpho-org/morpho-sdk/addresses";
|
|
172
|
+
*
|
|
173
|
+
* declare const marketParams: { loanToken: `0x${string}`; collateralToken: `0x${string}` };
|
|
174
|
+
* declare const userAddress: `0x${string}`;
|
|
175
|
+
* // Deadline the action signs, in seconds: the leverage builders sign the leverage data's block timestamp plus one hour.
|
|
176
|
+
* declare const deadline: bigint;
|
|
177
|
+
*
|
|
178
|
+
* // Leverage needs a ZeroExLeverageBundlesV1 registered on the chain. None ships yet: register a verified
|
|
179
|
+
* // address with `registerCustomAddresses` first, or the call throws LeverageUnsupportedChainError before any request.
|
|
180
|
+
* if (!isBlueZeroExLeverageChain(8453)) throw new Error("No leverage bundle is registered on Base yet.");
|
|
181
|
+
* const quote = await fetchZeroExQuote({
|
|
182
|
+
* chainId: 8453,
|
|
183
|
+
* kind: "delever",
|
|
184
|
+
* marketParams,
|
|
185
|
+
* userAddress,
|
|
186
|
+
* amount: 10n ** 18n,
|
|
187
|
+
* slippage: 5_000_000_000_000_000n,
|
|
188
|
+
* deadline,
|
|
189
|
+
* apiKey: process.env.ZEROEX_API_KEY!,
|
|
190
|
+
* signal: AbortSignal.timeout(10_000), // the fetch sets no timeout of its own
|
|
191
|
+
* });
|
|
192
|
+
* ```
|
|
193
|
+
*/
|
|
194
|
+
async function fetchZeroExQuote(params) {
|
|
195
|
+
const { chainId, userAddress, amount, slippage, deadline } = params;
|
|
196
|
+
const taker = (0, zeroExQuote_js_1.getZeroExLeverageBundle)(chainId);
|
|
197
|
+
const txOrigin = (0, zeroExQuote_js_1.resolveZeroExTxOrigin)(params.txOrigin, userAddress);
|
|
198
|
+
if (typeof amount !== "bigint") {
|
|
199
|
+
throw new index_js_1.InvalidBigIntInputError("amount", amount);
|
|
200
|
+
}
|
|
201
|
+
if (amount <= 0n) {
|
|
202
|
+
throw new index_js_1.NonPositiveInputError("amount", amount);
|
|
203
|
+
}
|
|
204
|
+
(0, validate_js_1.validateUint256Field)("amount", amount);
|
|
205
|
+
if (typeof slippage !== "bigint") {
|
|
206
|
+
throw new index_js_1.InvalidBigIntInputError("slippage", slippage);
|
|
207
|
+
}
|
|
208
|
+
(0, validate_js_1.validateSlippageTolerance)(slippage);
|
|
209
|
+
if (typeof deadline !== "bigint") {
|
|
210
|
+
throw new index_js_1.InvalidBigIntInputError("deadline", deadline);
|
|
211
|
+
}
|
|
212
|
+
(0, validate_js_1.validateDeadline)(deadline);
|
|
213
|
+
const route = (0, zeroExQuote_js_1.getZeroExSwapRoute)(params.kind, params.marketParams);
|
|
214
|
+
(0, zeroExQuote_js_1.validateZeroExExactOutputPair)({ chainId, ...route });
|
|
215
|
+
const url = new URL(ZERO_EX_QUOTE_URL);
|
|
216
|
+
url.search = new URLSearchParams({
|
|
217
|
+
chainId: String(chainId),
|
|
218
|
+
sellToken: route.sellToken,
|
|
219
|
+
buyToken: route.buyToken,
|
|
220
|
+
[route.mode === "exactOutput" ? "buyAmount" : "sellAmount"]: String(amount),
|
|
221
|
+
taker,
|
|
222
|
+
recipient: taker,
|
|
223
|
+
txOrigin,
|
|
224
|
+
slippagePpm: String((0, zeroExQuote_js_1.toZeroExSlippagePpm)(slippage)),
|
|
225
|
+
excludedSources: exports.ZERO_EX_LEVERAGE_EXCLUDED_SOURCES,
|
|
226
|
+
deadline: String(deadline),
|
|
227
|
+
}).toString();
|
|
228
|
+
let response;
|
|
229
|
+
try {
|
|
230
|
+
response = await (params.fetch ?? fetch)(url, {
|
|
231
|
+
headers: {
|
|
232
|
+
"0x-api-key": params.apiKey,
|
|
233
|
+
"0x-version": ZERO_EX_API_VERSION,
|
|
234
|
+
},
|
|
235
|
+
redirect: "error",
|
|
236
|
+
signal: params.signal,
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
throw new index_js_1.ZeroExQuoteRequestError({ status: null, code: null }, { cause: error });
|
|
241
|
+
}
|
|
242
|
+
if (!response.ok) {
|
|
243
|
+
const text = await readBody(response);
|
|
244
|
+
const body = (0, morpho_ts_1._try)(() => parseJson(text), index_js_1.ZeroExQuoteMalformedResponseError);
|
|
245
|
+
throw new index_js_1.ZeroExQuoteRequestError({
|
|
246
|
+
status: response.status,
|
|
247
|
+
code: isObject(body) && typeof body.name === "string" ? body.name : null,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
const body = parseJson(await readBody(response));
|
|
251
|
+
if (!isObject(body)) {
|
|
252
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
253
|
+
reason: "body is not an object",
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
if (body.liquidityAvailable !== true) {
|
|
257
|
+
if (body.liquidityAvailable === false) {
|
|
258
|
+
throw new index_js_1.ZeroExQuoteNoLiquidityError(route);
|
|
259
|
+
}
|
|
260
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
261
|
+
reason: "liquidityAvailable is not a boolean",
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
const mode = readString(body, "mode");
|
|
265
|
+
if (mode !== "exact-in" && mode !== "exact-out") {
|
|
266
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
267
|
+
reason: `mode "${mode}" is neither exact-in nor exact-out`,
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
const quoteMode = mode === "exact-out" ? "exactOutput" : "exactInput";
|
|
271
|
+
if (quoteMode !== route.mode) {
|
|
272
|
+
throw new index_js_1.ZeroExQuoteTypeMismatchError({
|
|
273
|
+
expected: route.mode,
|
|
274
|
+
actual: quoteMode,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
const sellToken = readAddress(body, "sellToken");
|
|
278
|
+
const buyToken = readAddress(body, "buyToken");
|
|
279
|
+
for (const [field, actual] of [
|
|
280
|
+
["sellToken", sellToken],
|
|
281
|
+
["buyToken", buyToken],
|
|
282
|
+
]) {
|
|
283
|
+
if (!(0, viem_1.isAddressEqual)(actual, route[field])) {
|
|
284
|
+
throw new index_js_1.ZeroExQuoteTokenMismatchError({
|
|
285
|
+
field,
|
|
286
|
+
expected: route[field],
|
|
287
|
+
actual,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const amountField = route.mode === "exactOutput" ? "buyAmount" : "sellAmount";
|
|
292
|
+
const returnedAmount = readAmount(body, amountField);
|
|
293
|
+
if (returnedAmount !== amount) {
|
|
294
|
+
throw new index_js_1.ZeroExQuoteMalformedResponseError({
|
|
295
|
+
reason: `${amountField} "${returnedAmount}" differs from the requested "${amount}"`,
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
const transaction = readObject(body, "transaction");
|
|
299
|
+
const base = {
|
|
300
|
+
chainId,
|
|
301
|
+
taker,
|
|
302
|
+
txOrigin,
|
|
303
|
+
slippage,
|
|
304
|
+
sellToken,
|
|
305
|
+
buyToken,
|
|
306
|
+
blockNumber: readAmount(body, "blockNumber"),
|
|
307
|
+
zid: readString(body, "zid"),
|
|
308
|
+
transaction: {
|
|
309
|
+
to: readAddress(transaction, "to"),
|
|
310
|
+
data: readHex(transaction, "data"),
|
|
311
|
+
value: readAmount(transaction, "value"),
|
|
312
|
+
},
|
|
313
|
+
};
|
|
314
|
+
if (route.mode === "exactOutput") {
|
|
315
|
+
return {
|
|
316
|
+
...base,
|
|
317
|
+
mode: "exactOutput",
|
|
318
|
+
buyAmount: amount,
|
|
319
|
+
maxSellAmount: readAmount(body, "maxSellAmount"),
|
|
320
|
+
estimatedNetSellAmount: readAmount(body, "estimatedNetSellAmount"),
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
return {
|
|
324
|
+
...base,
|
|
325
|
+
mode: "exactInput",
|
|
326
|
+
sellAmount: amount,
|
|
327
|
+
buyAmount: readAmount(body, "buyAmount"),
|
|
328
|
+
minBuyAmount: readAmount(body, "minBuyAmount"),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
@@ -89,6 +89,8 @@ export interface MidnightTakeBorrowPlanParams extends Omit<IntentParams, "suppor
|
|
|
89
89
|
* @throws {InvalidMidnightPositionAccrualStateError} If the position's credit and fee snapshot cannot be accrued.
|
|
90
90
|
* @throws {MidnightTakeableOffersNotFillableError} If the supplied offers cannot be used.
|
|
91
91
|
* @throws {MidnightTakeTargetUnreachableError} If the supplied target and bounds cannot be met.
|
|
92
|
+
* @throws {MidnightBorrowTooCloseToMaturityError} If `now` is not past maturity and expiry is less than
|
|
93
|
+
* `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the target.
|
|
92
94
|
* @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
|
|
93
95
|
* @throws {viem.BaseError} If an `eth_chainId` request or the authorization read fails.
|
|
94
96
|
* @example
|
|
@@ -225,6 +227,8 @@ export interface MidnightSupplyCollateralTakeBorrowPlanParams extends MidnightTa
|
|
|
225
227
|
* last loss factor; fetch the market and position at the same block.
|
|
226
228
|
* @throws {InvalidMidnightPositionAccrualStateError} If the position's credit and fee snapshot cannot be accrued.
|
|
227
229
|
* @throws {MidnightTakeableOffersNotFillableError} If the supplied offers cannot be used.
|
|
230
|
+
* @throws {MidnightBorrowTooCloseToMaturityError} If `now` is not past maturity and expiry is less than
|
|
231
|
+
* `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the target.
|
|
228
232
|
* @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
|
|
229
233
|
* @throws {viem.BaseError} If an `eth_chainId` request, an allowance read or the authorization read fails.
|
|
230
234
|
* @example
|
|
@@ -92,6 +92,8 @@ const validation_js_2 = require("./validation.js");
|
|
|
92
92
|
* @throws {InvalidMidnightPositionAccrualStateError} If the position's credit and fee snapshot cannot be accrued.
|
|
93
93
|
* @throws {MidnightTakeableOffersNotFillableError} If the supplied offers cannot be used.
|
|
94
94
|
* @throws {MidnightTakeTargetUnreachableError} If the supplied target and bounds cannot be met.
|
|
95
|
+
* @throws {MidnightBorrowTooCloseToMaturityError} If `now` is not past maturity and expiry is less than
|
|
96
|
+
* `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the target.
|
|
95
97
|
* @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
|
|
96
98
|
* @throws {viem.BaseError} If an `eth_chainId` request or the authorization read fails.
|
|
97
99
|
* @example
|
|
@@ -224,6 +226,8 @@ async function prepareMidnightTakeBorrow(client, params) {
|
|
|
224
226
|
* last loss factor; fetch the market and position at the same block.
|
|
225
227
|
* @throws {InvalidMidnightPositionAccrualStateError} If the position's credit and fee snapshot cannot be accrued.
|
|
226
228
|
* @throws {MidnightTakeableOffersNotFillableError} If the supplied offers cannot be used.
|
|
229
|
+
* @throws {MidnightBorrowTooCloseToMaturityError} If `now` is not past maturity and expiry is less than
|
|
230
|
+
* `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the target.
|
|
227
231
|
* @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
|
|
228
232
|
* @throws {viem.BaseError} If an `eth_chainId` request, an allowance read or the authorization read fails.
|
|
229
233
|
* @example
|
|
@@ -363,7 +367,7 @@ async function prepareBorrow(client, { params, supply, }) {
|
|
|
363
367
|
: parsed.target.maxUnits,
|
|
364
368
|
});
|
|
365
369
|
const { credit } = new midnight_sdk_1.AccrualPosition(positionData, marketData).accrueInterest(blue_sdk_1.MathLib.max(now, positionData.lastAccrual));
|
|
366
|
-
const
|
|
370
|
+
const feasibility = {
|
|
367
371
|
side: "sell",
|
|
368
372
|
takeableOffers: parsed.takeableOffers,
|
|
369
373
|
accountAddress: account,
|
|
@@ -375,7 +379,9 @@ async function prepareBorrow(client, { params, supply, }) {
|
|
|
375
379
|
credit,
|
|
376
380
|
target: parsed.target,
|
|
377
381
|
increasesDebt: true,
|
|
378
|
-
}
|
|
382
|
+
};
|
|
383
|
+
const takeableOffers = (0, validateMidnightTakeFeasibility_js_1.validateMidnightTakeFeasibility)(feasibility);
|
|
384
|
+
(0, validate_js_1.validateMidnightBorrowMaturity)(feasibility);
|
|
379
385
|
const requirement = { chainId, account, bundle, pulls };
|
|
380
386
|
const [approvals, authorization] = await prepareBorrowRequirements(client, requirement);
|
|
381
387
|
const inputs = {
|