PangolinOracleLibrary.sol
1 pragma solidity >=0.5.0; 2 3 import '@pangolindex/exchange-contracts/contracts/pangolin-core/interfaces/IPangolinPair.sol'; 4 import '@pangolindex/exchange-contracts/contracts/pangolin-lib/libraries/FixedPoint.sol'; 5 6 7 // library with helper methods for oracles that are concerned with computing average prices 8 library PangolinOracleLibrary { 9 using FixedPoint for *; 10 11 // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] 12 function currentBlockTimestamp() internal view returns (uint32) { 13 return uint32(block.timestamp % 2 ** 32); 14 } 15 16 // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. 17 function currentCumulativePrices( 18 address pair 19 ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { 20 blockTimestamp = currentBlockTimestamp(); 21 price0Cumulative = IPangolinPair(pair).price0CumulativeLast(); 22 price1Cumulative = IPangolinPair(pair).price1CumulativeLast(); 23 24 // if time has elapsed since the last update on the pair, mock the accumulated price values 25 (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IPangolinPair(pair).getReserves(); 26 if (blockTimestampLast != blockTimestamp) { 27 // subtraction overflow is desired 28 uint32 timeElapsed = blockTimestamp - blockTimestampLast; 29 // addition overflow is desired 30 // counterfactual 31 price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; 32 // counterfactual 33 price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; 34 } 35 } 36 }