UNPKG

tensaikit

Version:

An autonomous DeFi AI Agent Kit on Katana enabling AI agents to plan and execute on-chain financial operations.

50 lines (49 loc) 2.3 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchSwapQuote = void 0; const decimal_js_1 = __importDefault(require("decimal.js")); const errors_1 = require("../../../common/errors"); const utils_1 = require("../../../common/utils"); const utlis_1 = require("../utlis"); const fetchTokenMetadata_1 = require("./fetchTokenMetadata"); /** * Fetches a swap quote from the SushiSwap API for a given token pair and amount. * * This function converts the input amount to base units using the token's decimals, * builds the required query parameters, and then fetches a quote with slippage consideration. * * @param chainId - The chain ID representing the target blockchain network. * @param args - An object containing swap parameters: * - tokenIn: The address of the input token. * - tokenOut: The address of the output token. * - maxSlippage: The maximum allowed slippage percentage (e.g., 0.5 for 0.5%). * - amount: The input amount in human-readable units (e.g., 1.5 ETH). * * @returns A promise resolving to the swap quote data. * @throws Throws a formatted error if token metadata fetch or quote API call fails. */ const fetchSwapQuote = async (chainId, args) => { try { const tokenMetadata = await (0, fetchTokenMetadata_1.fetchTokenMetadata)(chainId, args.tokenIn); if (!tokenMetadata?.decimals) { throw (0, errors_1.createError)("Failed to fetch token decimals", errors_1.ErrorCode.TOKEN_METADATA_ERROR); } const amountInBaseUnits = new decimal_js_1.default(args.amount) .mul(new decimal_js_1.default(10).pow(tokenMetadata.decimals)) .toFixed(0); const params = new URLSearchParams({ tokenIn: args.tokenIn, tokenOut: args.tokenOut, amount: amountInBaseUnits, maxSlippage: args.maxSlippage.toString(), }); return await (0, utils_1.fetchFromApi)(`${utlis_1.SUSHI_QUOTE_ENDPOINT}/${chainId}?${params}`); } catch (error) { throw (0, errors_1.handleError)("Failed to fetch swap quote", error); } }; exports.fetchSwapQuote = fetchSwapQuote;