hypesdk
Version:
A powerful SDK for interacting with the Hype blockchain, featuring advanced routing and token swap capabilities
71 lines (70 loc) • 2.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRoute = getRoute;
const utils_1 = require("../utils");
/**
* Get the optimal route for a token swap
* @param tokenA Input token address
* @param tokenB Output token address
* @param amountIn Input amount (human readable)
* @returns Route response from the API
*/
async function getRoute(tokenA, tokenB, amountIn) {
const normalizedAmount = (0, utils_1.normalizeAmount)(amountIn);
console.log("Requesting route from API...");
console.log("Token A:", tokenA);
console.log("Token B:", tokenB);
console.log("Amount In:", normalizedAmount);
const url = `https://api.liqd.ag/route?tokenA=${tokenA}&tokenB=${tokenB}&amountIn=${normalizedAmount}&multiHop=true`;
console.log("API URL:", url);
try {
const apiResponse = await fetch(url);
console.log("API Response Status:", apiResponse.status);
if (!apiResponse.ok) {
throw new Error(`API request failed with status ${apiResponse.status}: ${apiResponse.statusText}`);
}
const data = (await apiResponse.json());
console.log("\nAPI Response Data:", JSON.stringify(data, null, 2));
if (!data.success) {
throw new Error(`API returned error: ${JSON.stringify(data)}`);
}
if (!data.data?.bestPath) {
throw new Error("No route found. API response: " + JSON.stringify(data));
}
// Construct the path array from the hop information
const hops = data.data.bestPath.hop;
const path = [];
// Add the first token
if (hops.length > 0) {
path.push(hops[0].tokenIn);
}
// Add all intermediate and final tokens
hops.forEach((hop) => {
path.push(hop.tokenOut);
});
// Create the modified response with the path array
const routeResponse = {
success: data.success,
data: {
bestPath: {
path,
estimatedAmountOut: data.data.bestPath.amountOut,
amountIn: data.data.tokenInfo.amountIn,
priceImpact: "0%", // Calculate this if needed
hop: data.data.bestPath.hop,
tokenInfo: {
tokenIn: data.data.tokenInfo.tokenIn,
tokenOut: data.data.tokenInfo.tokenOut,
},
},
},
};
return routeResponse;
}
catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to fetch route: ${error.message}`);
}
throw error;
}
}