How to use UniswapV2 as Sliding Window Price Oracle

Hi, I am trying to use uniswap as a price oracle, uniswap docs already have an example for a Sliding Window Oracle, but I am a little confused about somethings, I would appreciate it if someone can clear my confusions.

The oracle uses a sliding window means it stores the multiple observations across a predefined window size, below is the example contract from uniswap.

The consult method which is used to read the price, calculates the price by taking an average of the first price from the observation window and the current price, it does not consider the other observation points, why? shouldn’t it just use all observations like if there is the granularity of 10 then there would be 10 observations for a certain window, it should consider all observations and calculate the average right? Am I missing something here? or I have to do it myself?

// returns the amount out corresponding to the amount in for a given token using the moving average over the time
// range [now - [windowSize, windowSize - periodSize * 2], now]
// update must have been called for the bucket corresponding to timestamp `now - windowSize`
function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) {
    address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut);
    Observation storage firstObservation = getFirstObservationInWindow(pair);

    uint timeElapsed = block.timestamp - firstObservation.timestamp;
    require(timeElapsed <= windowSize, 'SlidingWindowOracle: MISSING_HISTORICAL_OBSERVATION');
    // should never happen.
    require(timeElapsed >= windowSize - periodSize * 2, 'SlidingWindowOracle: UNEXPECTED_TIME_ELAPSED');

    (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
    (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut);

    if (token0 == tokenIn) {
        return computeAmountOut(firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn);
    } else {
        return computeAmountOut(firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn);
1 Like

Hi @Abdul_Rafay,

Sorry, this isn’t something that I can help with.

If you don’t get an answer here, you may want to try asking in the Uniswap community: Discord link on the Community menu: