DEV Community

Cover image for [UniswapV2] SwapRouter by @Dialectic
MOYED
MOYED

Posted on

[UniswapV2] SwapRouter by @Dialectic

Source

https://github.com/dialecticch/router


Overview

Simple router to exchange tokens for best price for any UniswapV2 like AMM. This contract can only be used for exchanges that uses the code of Uniswapv2 .


SwapRouterMock

swap

Returns SwapRouter.swap function.


swap in SwapRouter library

Parameters

  • swaps is the candidates of exchanges that we can choose.
  • path is the array of token address which we will use for swap.
  • amount is the amount of token we want to sell.
  • slippage is the max slippage in basis points.

  1. Find the best profitable exchange and the corresponding amountOut for given amount by using dataForBestExchange function.

    (UniswapV2 swap, uint256 amountOut) = dataForBestExchange(swaps, path, amount);
    
  2. Approve swap (exchange we choose) to use path[0] (input token for swap) for amount .

    ERC20(path[0]).approve(address(swap), amount);
    
  3. Swap the token using swapExactTokensForTokens function from the exchange address. out is the real amount of output token we receive.

    uint256[] memory amountsOut = swap.swapExactTokensForTokens(
        amount,
        (amountOut * (1000 - slippage)) / 1000,
        path,
        address(this),
        block.timestamp + 180
        );
    
    uint256 out = amountsOut[amountsOut.length - 1];
    

dataForBestExchange

Returns the best exchange and the corresponding output value.

For given swap, we calculate the biggest out value by using amountOutFor function.

for (uint256 i = 0; i < length; i++) {
            uint256 out = amountOutFor(swaps[i], path, amount);
            if (out > bestAmount) {
                bestExchange = swaps[i];
                bestAmount = out;
            }
        }
Enter fullscreen mode Exit fullscreen mode

amountOutFor

Use getAmountsOut function to calculate the optimal output value from given amountIn and path.

try exchange.getAmountsOut(amountIn, path) returns (uint256[] memory amountsOut) {
    return amountsOut[amountsOut.length - 1];
} catch {
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)