pragma solidity >=0.4.16 <0.9.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';

// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
    using FixedPoint for *;

    // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
    function currentBlockTimestamp() internal view returns (uint32) {
        return uint32(block.timestamp % 2 ** 32);

    // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
    function currentCumulativePrices(
        address pair
    ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
        blockTimestamp = currentBlockTimestamp();
        price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
        price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();

        // if time has elapsed since the last update on the pair, mock the accumulated price values
        (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
        if (blockTimestampLast != blockTimestamp) {
            // subtraction overflow is desired
            uint32 timeElapsed = blockTimestamp - blockTimestampLast;
            // addition overflow is desired
            // counterfactual
            price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
            // counterfactual
            price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
  • Since contracts are executed in the EVM it would be better if they don't depend on time zones. Why do you need timezone in your contract?
    – Ismael
    Jan 5 at 14:58
  • 1
    I just realized the EVM block timestamp is produced based on the Epoch/Unix timestamp, thus the value is rendered as UTC. UTC provides the standard and the GMT serves as the timezone since there is no difference between the two. You are right since EVM timestamps are in UTC.Eg. Fri Jan 07 2022 02:10:03 GMT+0800 (China Standard Time).Epoch could be 1641492603, same on EVM. The UTC used by EVM and the practical use of GMT as timezones in applications makes it confusing but I realized they are the same. I will stick to the EVM's.Link explained here: epochconverter.com/timestamp-list
    – Peeman
    Jan 6 at 18:16


Your Answer

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

Browse other questions tagged or ask your own question.