Uniswap / v3-periphery

🦄 🦄 🦄 Peripheral smart contracts for interacting with Uniswap v3
https://uniswap.org
GNU General Public License v2.0
1.16k stars 1.08k forks source link

Swap path for two tokens #315

Open CodeCook-dev opened 1 year ago

CodeCook-dev commented 1 year ago

Hi there,

I want to estimate an exact output amount for a swap of multi pools by using V3 Quoter. quoteExactInputSingle is just for a single pool, so I tried to use a quoteExactInput, but it needs a path for two tokens to swap them each other. But how can I get the path for two tokens?

Please help me in this.

Thanks

Haripandey21 commented 1 year ago

To use the quoteExactInput function in Uniswap V3, you will need to specify the token path for the two tokens you want to swap. The token path refers to the sequence of pools that must be hopped through to complete the trade.

To get the token path, you can use the Uniswap V3 Router's exactInput function to get the best output amount for the desired input amount for each token in the path. You can then use the output token from the first pool as the input token for the next pool in the path, and repeat this process until you reach the final output token.

Once you have the token path, you can use the quoteExactInput function to estimate the exact output amount for the swap.

Here's an example of how to get the token path for swapping two tokens:

const tokenA = '0x...'; // Address of first token
const tokenB = '0x...'; // Address of second token
const amountIn = web3.utils.toHex(100); // Input amount in wei

const route = await uniswapRouter.exactInput({
  path: [tokenA, tokenB],
  amountIn: amountIn,
  deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from now
  sqrtPriceLimitX96: 0,
});

const path = route.route.path.map(p => p.toLowerCase());

In this example, uniswapRouter is an instance of the Uniswap V3 Router contract. exactInput is used to execute a trade and returns a SwapRouter.ExactInputSingleResult object that contains the token path and output amount.

Once we have the path, we can use it in the quoteExactInput function to estimate the exact output amount for the swap. For example:

const result = await uniswapQuoter.quoteExactInput({
  path: path,
  amountIn: amountIn,
  deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from now
});

console.log(result);