Skip to content
Business logic Audit finding Advanced

Incorrect TWAP calculation in BalancerPriceOracle allows price manipulation and breaks oracle guarantees

The BalancerPriceOracle contract implements an incorrect TWAP formula that accumulates the previous average price instead of the actual observed price, and recovers elapsed time by dividing cumulative price by average price. An attacker could manipulate the Balancer pool price after the minimum update period and call updatePrice with the manipulated price, corrupting the average and enabling further manipulation.

BenRai Follow with 0xDemon, Ace2 and 6 others

Originally disclosed on Code4rena

Submitted by BenRai, also found by 0xDemon, Ace2, Gakarot, jkk812812, JoshuaM33, Morraez, rage, and santipu_

autonolas-tokenomics/../contracts/oracles/BalancerPriceOracle.sol #L84-L128

The BalancerPriceOracle.updatePrice() function implements an incorrect Time-Weighted Average Price (TWAP) formula that does not properly accumulate price over time, making the oracle unreliable and susceptible to manipulation.

Finding Description

The protocol implements a price oracle that attempts to provide a Time-Weighted Average Price (TWAP) from Balancer pool prices. The updatePrice() function is responsible for updating the price snapshot and calculating the average price over time, which is then used to validate new price updates through a slippage check.

The core issue lies in the TWAP calculation formula within the updatePrice() function:

// Update cumulative price with the previous average over the elapsed time
snapshot.cumulativePrice += snapshot.averagePrice * elapsedTime;

// Update the average price to reflect the current price
uint256 averagePrice = (snapshot.cumulativePrice + (currentPrice * elapsedTime)) /
    ((snapshot.cumulativePrice / snapshot.averagePrice) + elapsedTime);

This implementation breaks the fundamental TWAP formula in multiple ways:

Issue 1: Accumulating averagePrice instead of lastPrice

The snapshot.cumulativePrice price should accumulate the actual observed price over each time period. Instead,

// Update cumulative price with the previous average over the elapsed time
snapshot.cumulativePrice += snapshot.averagePrice * elapsedTime;

the code accumulates snapshot.averagePrice, which is itself a derived average. This creates a recursive averaging effect where:

  • First update: accumulates some initial price
  • Second update: accumulates the average of the first update (not the actual price that was valid during that period)
  • Third update: accumulates an average of averages

This fundamentally breaks the TWAP property because it doesn’t weight each actual price observation by its duration.

Issue 2: Incorrect average calculation

A proper TWAP formula is:

TWAP = Σ(price_i × duration_i) / Σ(duration_i)

The implemented formula attempts to recover the total elapsed time by dividing snapshot.cumulativePrice / snapshot.averagePrice, which:

  • Loses precision through integer division
  • Assumes the relationship cumulativePrice = averagePrice × totalTime holds, which it doesn’t after the first update due to Issue 1
  • Becomes increasingly inaccurate over time as rounding errors compound

Impact

This broken TWAP implementation has severe consequences:

  1. Oracle Manipulation: The slippage check validates currentPrice against the calculated averagePrice. Since the average doesn’t reflect true time-weighted prices, an attacker can:

    • Manipulate the Balancer pool price after the minUpdateTimePeriod
    • Call updatePrice() with the manipulated price
    • The broken TWAP formula will not properly account for the manipulation duration
    • Subsequent price updates will use this corrupted average, allowing further manipulation

Recommendation

Implement a proper TWAP calculation that accumulates actual prices weighted by time. For this you can use the observation pattern similar to UniswapV3 where observations (timeStamp, priceCumulative) are saved in a circular buffer. Let a keeper call updatePrice on a regular basis to ensure continues data. Also consider implementing a TWAP time range (e.g. 15 minutes) to ensure a proper time frame for the result.

The update function and the getPrice functions could look like this:

function update() external {
    uint256 timeElapsed = block.timestamp - lastUpdateTimestamp;

    if (timeElapsed > 0) {
        // Get spot price from Balancer pool
        uint256 spotPrice = getBalancerSpotPrice();

        // Update accumulator
        priceAccumulator += spotPrice * timeElapsed;
        lastUpdateTimestamp = block.timestamp;

        // Store observation
        observations.push(Observation({
            timestamp: block.timestamp,
            priceCumulative: priceAccumulator
        }));
    }
}

function getTWAP() public view returns (uint256) {
    uint256 currentTime = block.timestamp;
    uint256 targetTime = currentTime - PERIOD;

    // Find observation closest to targetTime
    Observation memory oldObservation = findObservation(targetTime);

    uint256 priceDelta = priceAccumulator - oldObservation.priceCumulative;
    uint256 timeDelta = currentTime - oldObservation.timestamp;

    return priceDelta / timeDelta;
}

The original report as published on Code4rena, by BenRai. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the cumulative price accumulator adds the previous average price rather than the last observed spot price, and the average is computed by dividing cumulative price by average price to recover elapsed time, which is mathematically invalid after the first update.

Impact

An attacker could manipulate the Balancer pool price after the minimum update period and call updatePrice with the manipulated price, and because the broken TWAP does not properly account for manipulation duration, subsequent price updates would use the corrupted average, allowing further manipulation.

What the attacker needed

Ability to trade on the Balancer pool; wait for minUpdateTimePeriod to elapse; call updatePrice with manipulated price

The fix

The oracle should be fixed by implementing a proper TWAP that accumulates actual spot prices weighted by time, for example using a UniswapV3-style observation buffer with a defined TWAP period.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

A price oracle is a service that tells a smart contract what an asset is worth. This oracle tried to compute a time-weighted average price (TWAP), which should smooth out short-term price swings by averaging prices over time. Because the code averaged averages instead of real prices, an attacker could push the pool price around and feed a fake value into the oracle, which could then be used to misprice things.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by BenRai

View all

13 more disclosed reports, best first.

More from Olas

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.