0

this is from UniswapV2Pair.sol

token0 and token1 are declared:

address public token0;
address public token1; 

Then in swap function

 function swap( uint amount0Out,uint amount1Out,address to,bytes calldata data) external lock {
        require(
            amount0Out > 0 || amount1Out > 0,
            "UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT"
        );
        (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
        require(
            amount0Out < _reserve0 && amount1Out < _reserve1,
            "UniswapV2: INSUFFICIENT_LIQUIDITY"
        );

        uint balance0;
        uint balance1;
        {
            // scope for _token{0,1}, avoids stack too deep errors
            address _token0 = token0;
            address _token1 = token1;
            require(to != _token0 && to != _token1, "UniswapV2: INVALID_TO");
            if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
            if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
            if (data.length > 0)
                IUniswapV2Callee(to).uniswapV2Call(
                    msg.sender,
                    amount0Out,
                    amount1Out,
                    data
                );
            balance0 = IERC20(_token0).balanceOf(address(this));
            balance1 = IERC20(_token1).balanceOf(address(this));
        }
       ......
    }

Inside function a new scope is opened and comment says: "// scope for _token{0,1}, avoids stack too deep errors". How does it avoid stack-too-deep errors and why Uniswap needs only for "_token{0,1}"? I searched and found out that

Scoping a piece of code with { ... } has the same impact as placing that piece of code in a separate function.

Why did

1 Answer 1

1

Every function provides a little stack for each function (Stack has a maximum depth of 1024 elements and supports the word size of 256 bits). So, that means that increase in local variables will ultimately fill up the stack fast.

Providing a separate scope for _token0, and _token1 helps in that issue. Since both these variables are just being used in these few lines, they can be put in a different scope, thus getting saved from the stack too deep errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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