Solidity Uniswap – Optimized Swaps with swapExactTokensForTokens for Different Addresses

optimizationpythonsolidityswapsuniswap

I've already spent a hours to figuring out, how to do the following swap order across different exchanges/DEX using my own smart contract. In the image below (optimal Example), the swap is effectively performed. There is no intermediate step back to the origin smartcontract address and the token is passed directly to the next pool (but via another DEX).

Optimized Example:

Example Swap, optimized

How can this be done technically? Unfortunately I didn't manage it with swapExactTokensForTokens, at least I get an error when I want to specify address to the pool.

Here is a bad example and not optimized.
enter image description here

In this example, the swap is transferred back to the original smart contract and it do another swap from the contract. That is not efficient and of course costs gas!

I hope you can help me here?
Thank you very much

Best Answer

You don't have to use the Uniswap V2 router but instead you can directly interact with the pairs. Simply transfer the exact input amount to the pair and then call swap() on the pair passing the next pair as to.

You can use UniswapV2Library.getAmountsOut() to compute on-chain the correct amounts for arbitrarily long paths.

Check the code of swapExactTokensForTokens() to better understand how to perform these operations.

Related Topic