Executive Summary & Direct Answer

To test Balancer-style stable-pool rounding risk, model the exact pool math and scaling factors used by the target deployment, then fuzz sequences of swaps and compare its results with an independent, higher-precision reference. Assert that rounding error remains within a derived budget and that repeated batch operations cannot create value or materially distort the invariant. The simplified _upscaleArray example below is a test target—not verified production Balancer source—and is not sufficient to reproduce a specific historical exploit without the matching contracts and transaction inputs.

The key is to test sequences, not just individual swaps: repeated truncation can accumulate, while an invariant that merely checks each operation’s local result may miss harmful drift. Treat any claimed “8–9 wei” trigger or per-operation loss as a hypothesis to verify against the relevant deployed code and pool state.

Scope and reproduction target

The source account describes a Balancer V2 ComposableStablePool attack detected on November 3, 2025. It attributes the issue to precision loss in stable-pool calculations, including scaling balances with downward rounding and executing many swaps within a batch. It also describes funds accumulating in Vault internal balances before a later withdrawal.

For an engineering test, separate three claims that are easy to conflate:

  1. Arithmetic behavior: what the deployed scaling and invariant functions actually round, and where.
  2. Sequence behavior: whether repeated swaps can accumulate a meaningful invariant or pricing deviation.
  3. Economic extraction: whether a particular sequence can obtain more value than it contributes, considering fees, limits, pool configuration, and Vault accounting.

A unit test of mulDown establishes only the first claim. A Foundry invariant test can explore the second. Reproducing the reported theft requires the vulnerable pool implementation, matching token scaling and amplification parameters, exact swap limits, and a fork or faithful Vault harness. Do not treat the simplified source excerpt as Balancer’s complete production implementation.

This guide focuses on building that sequence-level test harness. It does not assert a particular advisory identifier: the provided source context gives no CVE or Balancer issue ID to preserve.

Environment and baseline specifications

Use Solidity ^0.8.24, Foundry (forge and anvil), and a fork pinned to a specific block when testing deployed contracts. Record the pool ID, token addresses, scaling factors, amplification parameter, Vault address, Balancer code revision, and fork block in the test fixture. If the pool implementation is behind a proxy or uses linked libraries, record those addresses and deployed bytecode hashes too.

Example foundry.toml:

[profile.default]
solc_version = "0.8.24"
evm_version = "cancun"
optimizer = true
optimizer_runs = 200
fuzz = { runs = 1000 }
invariant = { runs = 500, depth = 100 }

[profile.reference]
solc_version = "0.8.24"
evm_version = "cancun"
optimizer = true
optimizer_runs = 200

The compiler and EVM settings make the test repeatable; they do not prove the on-chain bytecode matches the tested source. For a real incident reproduction, pin the fork and source revision rather than using a floating block number or a current library checkout.

The vulnerable shape: truncation inside repeated operations

The supplied excerpt reduces scaling to a downward-rounded multiplication:

function upscaleDown(uint256 amount, uint256 factor)
    internal
    pure
    returns (uint256)
{
    return amount * factor / 1e18;
}

Integer division discards the remainder. In isolation, the discarded amount is less than one unit of the scaled result. But that bound does not automatically establish that a whole swap or batch is safe: subsequent calculations, conversions back to raw units, and state updates can introduce further rounding. Whether losses compound, cancel, or stay bounded depends on the full call path.

A dangerous testing shortcut is to assert only that this function’s output is close to a real-number product. Instead, exercise the pool’s actual sequence of operations and compare its results to a separately implemented reference. Avoid reusing the production helper in the reference implementation; shared code can make both sides share the same defect.

A focused arithmetic property

The following test illustrates a local bound for a single floor-scaled multiplication. It is deliberately not a substitute for testing the StableSwap invariant or batch swaps.

contract ScalingTest is Test {
    uint256 constant ONE = 1e18;

    function testFuzz_floorErrorIsLessThanOneScaledUnit(
        uint128 rawAmount,
        uint128 factor
    ) public pure {
        uint256 amount = uint256(rawAmount);
        uint256 scale = uint256(factor);

        // Keep multiplication in range for this test.
        vm.assume(scale == 0 || amount <= type(uint256).max / scale);

        uint256 product = amount * scale;
        uint256 down = product / ONE;
        uint256 remainder = product % ONE;

        assertEq(down * ONE + remainder, product);
        assertLt(remainder, ONE);
    }
}

This proves a division identity, not economic safety. A production differential test should compare the actual pool output and post-swap invariant with an independently written reference using wider intermediate precision, or with a trusted off-chain implementation. Document the reference’s rounding rules and validate it against known vectors before relying on it.

Production implementation: model the batch, not an isolated swap

Use a Foundry handler to generate valid sequences against a pinned pool fixture. Keep actions constrained enough that fuzz failures represent meaningful pool operations—not malformed inputs that revert before reaching the rounding path. The handler should perform the real swap or batch-swap call and record, at minimum:

  • Starting and ending token balances and BPT supply.
  • Input, output, fee, and swap limit for every step.
  • The pool invariant before and after each step, computed by both implementations.
  • Cumulative difference between production math and the independent reference.
  • Vault internal balances if the target flow uses them.

A minimal invariant shape is:

function invariant_referenceDriftWithinDerivedBudget() public view {
    assertLe(handler.maxObservedDrift(), handler.roundingBudget());
}

function invariant_noValueCreatedBySequence() public view {
    assertLe(handler.referenceValueAfter(), handler.referenceValueBefore());
}

These assertions are intentionally project-specific interfaces: connect them to the pinned pool and a reference implementation rather than filling them with an invented invariant formula. Derive roundingBudget() from the number of rounding operations, token scales, and the exact rounding direction at each boundary. A blanket tolerance such as “one wei per swap” is unsafe unless the implementation’s complete conversion path proves that bound.

For the reported pattern, generate sequences that move balances toward small residual amounts, execute repeated swaps against the same pool state, and then attempt the relevant BPT mint, trade, or redemption. Include both a single batchSwap and equivalent separate transactions. The comparison can reveal whether atomic sequencing changes the result because intermediate state persists within a batch.

Differential verification and counterexample triage

A useful test suite has three layers:

  1. Known-answer tests: Verify the reference and pool agree on ordinary swaps, token scaling boundaries, and documented edge cases.
  2. Fuzz tests: Explore balances, amounts, and operation sequences while enforcing valid swap limits.
  3. Invariant tests: Check the cumulative drift and economic properties across many handler actions.

Run the suite with reproducible settings:

forge test --match-path test/StablePoolRounding.t.sol -vvv
forge test --match-contract StablePoolInvariantTest \
  --invariant-runs 500 --invariant-depth 100 -vvv
forge test --match-contract StablePoolInvariantTest \
  --fuzz-runs 5000 -vvv

For a fork reproduction, pin the block in configuration or the test setup and run the same test against the deployed Vault and pool. Preserve failing seeds and minimized counterexamples. Foundry’s sequence minimization is particularly useful: a 65-operation failure may reduce to a shorter sequence that exposes the essential rounding boundary.

Inspect compiler output when inline assembly or optimizer-sensitive math is involved:

solc --version
solc --ir-optimized --optimize --optimize-runs 200 \
  --evm-version cancun src/PoolMath.sol

Compare optimized IR and test results across the project’s supported compiler profiles. A compiler-profile difference is a signal to investigate, not evidence that one result is correct. The central differential is between the deployed implementation and independent reference math under identical inputs—not between two compiler builds alone.

What the mitigation should prove

Do not “fix” a failing invariant by blindly rounding every operation up. Rounding direction is part of the pool’s economic rules: changing it can transfer value to a trader, LP, or protocol. A production mitigation should be based on the complete math and prove that:

  • Each operation follows the intended conservative rounding direction.
  • Conversion between raw and scaled balances cannot bypass the error budget.
  • A batch cannot use intermediate state to produce an invalid BPT price or extract value beyond the specified fee and slippage rules.
  • The invariant remains valid after token balance changes, including tiny residual balances.
  • Any pause, cap, or rejection condition behaves safely for existing pools and does not introduce an unbounded processing path.

Where pool math has unavoidable rounding, bound the cumulative error and reject or constrain inputs when the bound could affect solvency or pricing. Verify the chosen limits against the deployed token scales and pool parameters. Tests for fee-on-transfer assets are a separate accounting concern; see Preventing ERC-20 Fee-On-Transfer Accounting Bugs in Solidity. If a reproduction depends on time-based configuration or an oracle, test those assumptions independently rather than attributing their effects to rounding; see Preventing Timestamp Manipulation in Solidity Contracts.

Quantitative trade-offs

Test approachWhat it establishesTypical cost or limitation
Unit test of one scaling operationLocal truncation and remainder boundsCannot detect cumulative swap or invariant drift
Fuzzed swap testInput-sensitive behavior for individual operationsUsually misses long adversarial sequences
Handler-based invariant testSequence behavior across state transitionsRuntime grows with runs and sequence depth; requires a valid handler
Pinned fork differential testBehavior against deployed contracts and stateRPC and setup dependence; results are block-specific
Off-chain high-precision referenceIndependent numerical comparisonReference must be validated and match protocol rounding semantics

No fixed gas number is meaningful without a specific pool, compiler settings, and transaction sequence. Track test runtime and counterexample depth in CI, and measure on-chain gas separately with the exact deployed path.

Production pitfalls and edge cases

Tiny values are not automatically exploitable. A small raw balance can become zero after scaling, but the impact depends on its token’s scaling factor, the invariant implementation, and how the result is used. Assert behavior at values around every rounding boundary, including zero, one raw unit, and values immediately below and above a scale quotient boundary.

Do not confuse accounting with transfers. Balancer V2’s Vault separates token custody from pool accounting and supports internal balances. A test that checks only ERC-20 balances can miss a changed internal claim; one that checks only internal balances can miss later withdrawal behavior. If reproducing that architecture, assert both ledgers and the final recipient’s token balances.

Fees affect the differential. Compare like with like: include the exact fee path in both the pool call and the reference model. A test that omits fees may report apparent extraction or drift that disappears under the deployed rules.

A passing bounded campaign is not a proof. Fuzzing explores selected inputs; it does not establish correctness for every amount or sequence. Combine property tests with code review of rounding directions and explicit boundary vectors. For a real incident, also compare the pinned deployed bytecode and transaction trace with the source revision.

Frequently Asked Questions (FAQ)

Can a Foundry invariant test reproduce the reported Balancer exploit exactly?

Only if the test uses the affected pool implementation, matching configuration and state, and a reproducing action sequence. The simplified _upscaleArray excerpt alone is not enough to establish the exact exploit path or reproduce reported losses.

Does Solidity floor division make every small stable-pool swap unsafe?

No. Floor division discards a remainder, but the risk depends on how often rounding occurs, how intermediate values feed the invariant, and whether later operations can turn the deviation into extractable value. Test the full sequence against independent reference math.

How should I test a Balancer V2 ComposableStablePool on Foundry?

Pin the fork block and pool configuration, call the real Vault and pool path through a stateful handler, and assert cumulative drift and economic invariants against a separately validated reference. Include internal-balance accounting if the tested flow uses it.

Learn more with useful resources