> ## Documentation Index
> Fetch the complete documentation index at: https://docs.phylax.systems/llms.txt
> Use this file to discover all available pages before exploring further.

# Balancer V2 Rate Manipulation Exploit

> $120m+ lost due to rate manipulation caused by rounding error accumulation

## What Happened

In November 2025, an attacker systematically manipulated exchange rates in Balancer V2 stable pools by exploiting accumulated rounding errors in the stable pool invariant calculation.

Through a crafted sequence of 84 alternating batch swaps, the attacker biased the pool's invariant (D) downward by maintaining balances near rounding boundaries.
This caused the BPT (Balancer Pool Token) price to change significantly. One pool changed from \~1.027e18 to \~20.189e18 (approximately 20x change).
The attacker then extracted value through internal balance withdrawals in a subsequent transaction.

> [!WARNING]
>
> This conceptual assertion limits rate changes. Test legitimate operations in a non-production environment before deployment. The example 3x threshold may need adjustment.

## The Invariant

In Balancer V2 stable pools, the rate represents the price of BPT relative to underlying assets:

```text theme={null}
rate = D / totalSupply
```

Where:

* `D` is the stable pool invariant (computed from token balances)
* `totalSupply` is the circulating supply of BPT

**Normal behavior:** During legitimate swaps, rates change minimally (typically \< 10%) due to:

* Trading fees
* Slight imbalances from large trades
* Natural price discovery

**Exploit behavior:** The attacker's manipulation caused rates to change by 20x in a single `batchSwap` call, which should never happen for any legitimate operation.

## How the Exploit Worked

The exploit consisted of two transactions:

### Transaction 1: Rate Manipulation

The attacker executed a single `batchSwap` with 84 swap steps in alternating patterns. These swaps manipulated balances to specific boundaries where `StableMath._calculateInvariant()` accumulated maximum down-rounding bias, causing the invariant D to be underestimated and reducing BPT price.

**Observable Effect:**

* osETH/WETH-BPT pool rate: approximately 1.027e18 to 20.189e18 (\~19.7x change)
* wstETH/WETH-BPT pool rate: approximately 1.051e18 to 3.887e18 (\~3.7x change)

### Transaction 2: Value Extraction

The attacker withdrew accumulated internal balances via `manageUserBalance(WITHDRAW_INTERNAL)`.

## Root Cause (Technical Detail)

Balancer V2's `StableMath._calculateInvariant()` uses repeated down-rounding operations on scaled balances:

```solidity theme={null}
// Simplified invariant calculation
D_P = Math.divDown(Math.mul(D_P, invariant), Math.mul(balances[j], numTokens));
invariant = Math.divDown(...);  // Multiple divDown operations compound precision loss
```

Under specific conditions:

* Mixed token decimals amplify precision loss
* Balances maintained near rounding boundaries maximize bias
* Repeated operations in a long `batchSwap` sequence compound the error
* The computed invariant D becomes progressively underestimated

The attacker's math helper contract (0x679b3) searched for inputs that would push denominators toward zero without triggering reverts.

## Assertion Pattern

The assertion bounds the rate change within a `batchSwap` call.

### Example Assertion

```solidity theme={null}
import {AssertionSpec} from "credible-std/SpecRecorder.sol";

contract BatchSwapDeltaAssertion is Assertion {
    constructor() {
        registerAssertionSpec(AssertionSpec.Reshiram);
    }

    uint256 constant MAX_RATE_CHANGE_MULTIPLIER = 3e18; // 3.0x
    uint256 constant MIN_RATE_CHANGE_MULTIPLIER = 33e16; // 0.33x

    function assertionBatchSwapRateManipulation() external {
        address vault = ph.getAssertionAdopter();
        PhEvm.CallInputs[] memory batchSwapCalls = ph.getAllCallInputs(
            vault,
            IVault.batchSwap.selector
        );

        for (uint256 i = 0; i < batchSwapCalls.length; i++) {
            // Decode swap parameters to get affected pools
            (, IVault.BatchSwapStep[] memory swaps, , , , ) = abi.decode(
                callInput.input,
                (IVault.SwapKind, IVault.BatchSwapStep[], IAsset[],
                 IVault.FundManagement, int256[], uint256)
            );

            bytes32[] memory uniquePoolIds = _getUniquePoolIds(swaps);

            for (uint256 j = 0; j < uniquePoolIds.length; j++) {
                (address poolAddress, ) = IVault(vault).getPool(uniquePoolIds[j]);

                // Check rate before and after the swap
                PhEvm.ForkId memory preCallFork = PhEvm.ForkId({forkType: 2, callIndex: callInput.id});
                uint256 preRate = IRateProvider(poolAddress).getRate();

                PhEvm.ForkId memory postCallFork = PhEvm.ForkId({forkType: 3, callIndex: callInput.id});
                uint256 postRate = IRateProvider(poolAddress).getRate();

                uint256 rateChangeMultiplier = (postRate * 1e18) / preRate;

                // Revert if rate changed by more than 3x
                require(
                    rateChangeMultiplier <= MAX_RATE_CHANGE_MULTIPLIER &&
                    rateChangeMultiplier >= MIN_RATE_CHANGE_MULTIPLIER,
                    "BatchSwap: Extreme pool rate manipulation detected"
                );
            }
        }
    }
}
```

### Why This Works

The observed 20x rate change exceeds the example 3x threshold. The check measures the effect without identifying the rounding-error mechanism.

### Threshold Selection

We chose **3x (300%)** as the threshold based on the following analysis:

**Normal rate change behavior:**

* Single swaps: Cause \< 10% rate changes due to swap fees (1.05x-1.10x maximum)
* Proportional joins/exits: Maintain rate constant (1.0x - no change)
* Imbalanced joins/exits: Similar to swaps, \< 10% rate change maximum
* Multiple operations in a batch: Could accumulate to \~1.5-2.5x in extreme cases with many maximum-sized operations

**Exploit behavior:**

* The actual exploit showed 20x rate change (far exceeding any legitimate scenario)

**Safety margin:**

* 3x provides a 1.2x-2x buffer above the most extreme legitimate batch swap scenarios
* Significantly below the 20x change observed in the exploit

**Potential edge cases:**

* Rate provider updates: If a pool uses yield-bearing tokens with rate providers, legitimate rates should change gradually over time. A 3x change in a single transaction would indicate either oracle manipulation or a severe underlying issue (slashing event, de-pegging) that warrants investigation.
* Amplification changes: Limited to 2x per day by protocol, causing minimal per-transaction rate impact

**Trade-off:** The 3x threshold is aggressive enough to catch exploitation attempts while providing margin for legitimate operations. Teams can tune the threshold upward for protocols whose normal transaction patterns need more room, though this would reduce sensitivity to smaller manipulation attempts.

We did not identify legitimate operations above the 3x threshold in this analysis. Test for exceptions before production use.

## Review the release backtest

Create a release with `pcl apply` and [review its backtest](https://docs.phylax.systems/credible/backtesting.md). Keep a regression test for the exploit because older transactions can fall outside the platform's rolling window.

## Key Takeaways

The policy rejects rate changes beyond its threshold, regardless of their cause. Changes within that threshold remain outside this check.

## References

* **Post-Mortem Analysis:** [Coinspect - Balancer Rate Manipulation Exploit](https://www.coinspect.com/blog/balancer-rate-manipulation-exploit/)
* **Exploit Transaction (Mainnet):** [0x3e173ab0ba9183efa8a42caa783bdb5ec75daffcc8505cc1302009d11daf1ccf](https://etherscan.io/tx/0x3e173ab0ba9183efa8a42caa783bdb5ec75daffcc8505cc1302009d11daf1ccf)
* **Extraction Transaction:** [0xd155207261712c35fa3d472ed1e51bfcd816e616dd4f517fa5959836f5b48569](https://etherscan.io/tx/0xd155207261712c35fa3d472ed1e51bfcd816e616dd4f517fa5959836f5b48569)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.