function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
    require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
    (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
    require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');

In this function we are sorting the tokens and why we are comparing the data type address

function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {//ex[usdt,weth,usdc]
    for (uint i; i < path.length - 1; i++) {
        (address input, address output) = (path[i], path[i + 1]);//(input-->usdt,output-->weth)
        (address token0,) = UniswapV2Library.sortTokens(input, output);
        IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));//getting the pair address for selecteed pair
        uint amountInput;
        uint amountOutput;
        //reserve0 is the amount of token0 we have in the pair contract(liquidity pool)balance of usdt in the pair contract
        //reserve1 is the amount of token1 we have i the pair contract(liquidity pool)balance of weth in the pair contract
        { // scope to avoid stack too deep errors
        (uint reserve0, uint reserve1,) = pair.getReserves();//get the amounts of token0 and token1
        (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);//reserves of input tokens and output tokens
        amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);//our input amount
        //-->we need to take 2% of amount input
        amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);//maximum amount of output token you will get (cutting the percentage)
        //we will get the output amount as 98% estimated
        (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
        address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
        pair.swap(amount0Out, amount1Out, to, new bytes(0));

If the tokens weren't sorted, it would result in a distinct pair address for each sort order:

  • Tokens: [A,B] -> Pair address: X
  • Tokens: [B,A] -> Pair address: Y

By sorting the tokens first, the address of any given pair is pre-determined, and can be computed without any on-chain lookups (using CREATE2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.