Line data Source code
1 : // SPDX-License-Identifier: MIT 2 : 3 : pragma solidity ^0.6.12; 4 : pragma experimental ABIEncoderV2; 5 : 6 : // Local imports 7 : 8 : import { IUniswapV2Pair } from "../interfaces/IUniswapV2Pair.sol"; 9 : 10 : import { FixedPoint } from "./FixedPoint.sol"; 11 : 12 : library UniswapV2OracleLibrary { 13 : using FixedPoint for *; 14 : 15 : // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 16 : // 1] 17 : function currentBlockTimestamp() internal view returns (uint32) { 18 85 : return uint32(block.timestamp % 2 ** 32); 19 : } 20 : 21 : // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. 22 : function currentCumulativePrices(address pair) 23 : internal 24 : view 25 : returns (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) 26 : { 27 8 : blockTimestamp = currentBlockTimestamp(); 28 8 : price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); 29 8 : price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); 30 : 31 : // if time has elapsed since the last update on the pair, mock the accumulated price values 32 8 : (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); 33 8 : if (blockTimestampLast != blockTimestamp) { 34 : // subtraction overflow is desired 35 5 : uint32 timeElapsed = blockTimestamp - blockTimestampLast; 36 : // addition overflow is desired 37 : // counterfactual 38 5 : price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; 39 : // counterfactual 40 5 : price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; 41 : } 42 : } 43 : }