Uniswap / v2-core

🦄 🦄 Core smart contracts of Uniswap V2
https://uniswap.org/docs
GNU General Public License v3.0
2.97k stars 3.18k forks source link

uint32 blockTimestamp = uint32(block.timestamp % 2**32); --- Why Do This? #96

Closed mudgen closed 4 years ago

mudgen commented 4 years ago

In UniswapV2Pair.sol there is this code:

    function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
        require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
        uint32 blockTimestamp = uint32(block.timestamp % 2**32);
        uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
        if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
            // * never overflows, and + overflow is desired
            price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
            price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
        }
        reserve0 = uint112(balance0);
        reserve1 = uint112(balance1);
        blockTimestampLast = blockTimestamp;
        emit Sync(reserve0, reserve1);
    }

Why do you do this: uint32 blockTimestamp = uint32(block.timestamp % 2**32); ?

Because uint32(block.timestamp) == uint32(block.timestamp % 2**32)

Doing block.timestamp % 2**32 does not change the value, so why do it?

moodysalem commented 4 years ago

Pretty sure this is just an oversight, given the two are exactly equivalent. Not sure if it makes a difference in terms of gas--may be optimized out.