Uniswap - Find route or path between 2 tokens for swap or exchange when direct pool does not exists

61 Views Asked by At

I am trying to write a code for swaps and exchanges between 2 tokens. Let's say if direct pool or path does not exists and the route is via some intermediary token or maybe via 3-4 hops,I need to see the full route of what token paths are involved and the fee and amountOut.

I tried Fetcher and Trade from @uniswap/sdk. Even bestTradeExactIn() works for direct pool, I tried to trade between mantle and usdc... got error: Error: call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="getReserves()", data="0x", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.7.0)

But the same code works DAI and USDC.

This is my below code async function findBestTradePath() { const chainId = ChainId.MAINNET;

let token1 = config.tokens.dai
let token2 = config.tokens.usdc

// Fetch token data
const tokenA = await Fetcher.fetchTokenData(chainId, token1.address, customHttpProvider, token1.symbol, token1.name);
const tokenB = await Fetcher.fetchTokenData(chainId, token2.address, customHttpProvider, token2.symbol, token2.symbol);


// Try to find the best trade path
try {
    const directPoolExists = await checkDirectPoolExists(tokenA, tokenB);
    console.log("directPoolExists: ", directPoolExists);

    if (directPoolExists) {
        console.log('Direct pool exists. Proceeding with direct trade.');
        const pairAB = await Fetcher.fetchPairData(tokenA, tokenB, customHttpProvider);
        const tradeAB = new Trade(pairAB, new TokenAmount(tokenA, amountIn.toString()), TradeType.EXACT_INPUT);
        console.log('Direct Trade:', tradeAB);
    } else {
        console.log('No direct pool exists. Finding the optimal trade path.');
        const weth = WETH[CHAIN_ID];

        const pairAB = await Fetcher.fetchPairData(tokenA, tokenB, customHttpProvider);
        const pairBA = await Fetcher.fetchPairData(tokenB, tokenA, customHttpProvider);

        // Ensure pair objects are valid before proceeding
        if (!pairAB || !pairBA) {
            console.log('Invalid pair objects.');
            return null;
        }


        const trade = await Trade.bestTradeExactIn([pairAB, pairBA], new TokenAmount(tokenA, '1000000000000000000'), tokenB, {
            maxHops: 8,
            maxNumResults: 1,
        });
       
    }
} catch (error) {
    console.log('Error finding trade path.');
    console.error(error);
    return null;
}

}

If anyone can help here, would be really appreciated. Thank you in advance.

0

There are 0 best solutions below