Executive Summary & Direct Answer

When a liquidity pool caches virtual balances to save gas, its cached state must remain consistent with its LP-token supply and actual asset balances. A dangerous edge case occurs when the final LP tokens are burned: rounding can leave nonzero cached balances even though supply is zero. If the next deposit treats zero supply as proof of a pristine pool, stale values can influence LP-token minting and enable catastrophic over-minting.

Prevent this class of exploit by making the zero-supply transition explicit. Clear or rebuild every cached virtual balance when the pool becomes empty, define how residual assets are handled, and calculate first-deposit shares from current assets—not from cached state left by earlier liquidity cycles. Then test repeated deposit, withdrawal, and re-deposit sequences as a stateful invariant.

The failure mode: zero supply does not mean zero cached state

A weighted StableSwap pool may compute a virtual balance for each asset from its actual balance and an exchange rate:

virtualBalance[i] = actualBalance[i] * rate[i] / RATE_PRECISION

Those values can be cached in storage—for example, in a packed array named packed_vbs—to avoid repeatedly querying rate providers and recomputing the pool’s invariant.

The optimization is safe only if cached balances are kept synchronized with the pool’s other accounting. In the yETH incident described by Check Point Research, the critical mismatch was between supply and packed_vbs: after all LP tokens were burned, rounding left residual cached values, but the values were not reset. A later deposit entered the “first deposit” path because supply was zero, then used state that did not represent that deposit.

The core invariant is not merely “supply is zero when the pool is empty.” It is:

Whenever the pool enters its zero-supply state, every state variable used to price or mint the next initial shares must be either reset or recomputed from the current assets.

If a first-deposit calculation consumes stale cached balances, it can calculate shares from phantom value instead of the value actually deposited. The resulting supply may be vastly out of proportion to the deposit.

Environment and baseline

The examples use Solidity ^0.8.24 with the Cancun EVM target, Foundry, and no required third-party library. The cache is represented as uint256[] for clarity; a production pool may pack values into narrower fields, as long as it validates packing bounds and applies the same reset rules to every field.

The snippets are accounting sketches, not a drop-in implementation of a particular StableSwap invariant. A production pool must use its audited invariant and rate-provider conventions. Pin the compiler and EVM target in foundry.toml so tests and deployed bytecode use a reproducible baseline:

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

Naive pattern: burn supply, retain cache

The vulnerable design often has two apparently reasonable paths:

function removeLiquidity(uint256 shares) external {
    uint256 oldSupply = totalSupply;
    // Calculate and transfer proportional amounts.
    _burn(msg.sender, shares);

    // Decrement cached virtual balances proportionally.
    // Integer rounding can leave nonzero values.
    _decreasePackedVirtualBalances(shares, oldSupply);

    // Missing: clear or reconcile the cache when totalSupply == 0.
}

function addLiquidity(uint256[] calldata amounts) external returns (uint256 minted) {
    if (totalSupply == 0) {
        // Incorrect assumption: zero supply means pristine cache.
        minted = _initialSharesFromCachedValues(amounts, packed_vbs);
    } else {
        minted = _sharesFromInvariantChange(amounts, packed_vbs);
    }

    _updateBalancesAndCache(amounts);
    _mint(msg.sender, minted);
}

The root cause is a state-transition bug, not simply a rounding bug. Proportional subtraction can round down, so cached values need not reach zero when the last shares are burned. Meanwhile, totalSupply == 0 records token supply, not the history or validity of packed_vbs. The condition is therefore insufficient evidence that cached state is safe to use.

The incident illustrates why “first deposit” must mean initialize from current pool state, not “take the branch associated with zero supply and trust whatever storage contains.” Dust assets, accrued fees, rate changes, or a prior full withdrawal can all make those states differ.

Production fix: make the empty-pool transition explicit

A robust implementation handles the final burn as a distinct state transition. It either requires all underlying balances to be zero, or applies a documented dust policy; it then clears every cache field that can affect future pricing. On the next initial deposit, it computes virtual balances from the post-deposit balances and current rates.

uint256[] private packed_vbs;
uint256 public totalSupply;

function _afterFinalBurn() internal {
    // Called only after the final LP tokens have been burned.
    // The policy must be explicit: reject residual assets, sweep them,
    // or account for them through a separately defined mechanism.
    for (uint256 i; i < packed_vbs.length; ++i) {
        packed_vbs[i] = 0;
    }

    emit PoolCacheReset();
}

function _mintInitialLiquidity(
    uint256[] memory actualBalancesAfterDeposit
) internal returns (uint256 shares) {
    uint256 n = packed_vbs.length;
    require(actualBalancesAfterDeposit.length == n, "length");

    uint256[] memory freshVbs = new uint256[](n);
    for (uint256 i; i < n; ++i) {
        uint256 rate = _currentRate(i);
        freshVbs[i] = actualBalancesAfterDeposit[i] * rate / RATE_PRECISION;
    }

    shares = _initialSharesFromFreshBalances(freshVbs);
    require(shares != 0, "zero shares");

    for (uint256 i; i < n; ++i) {
        packed_vbs[i] = freshVbs[i];
    }

    _mint(msg.sender, shares);
}

The important ordering is: establish actual post-deposit balances, obtain rates according to the protocol’s rate policy, compute fresh virtual balances, calculate initial shares from those fresh values, write the cache, and mint. Do not read stale cache values to determine initial shares.

The final-burn path must also ensure it runs against the post-burn supply. For example:

_burn(owner, shares);

if (totalSupply == 0) {
    _enforceEmptyPoolAssetPolicy();
    _clearAllPricingCaches();
}

If the pool permits residual underlying assets while supply is zero, simply clearing the cache does not define who owns those assets or how a future depositor is treated. Either reject a final withdrawal that leaves unowned assets, sweep or segregate dust under an explicit rule, or include those assets in initialization under a documented ownership model. Never silently give a new depositor the value of old assets—or let stale cache entries make a tiny deposit appear valuable.

A version/generation marker can help detect uninitialized cache state, but it is not a substitute for correct initialization. If using one, increment it atomically on reset, associate cached entries with that generation, and ensure every read rejects entries from an older generation.

State and math checks that matter

A pool should keep the following relationships true after every successful state-changing operation:

  1. totalSupply == 0 implies cached pricing state is cleared or explicitly marked invalid.
  2. If totalSupply > 0, each cached virtual balance corresponds to the pool’s actual balance and the rate snapshot or rate semantics used by the invariant.
  3. The first mint after zero supply depends only on the defined initial-deposit inputs—not on prior cache contents.
  4. A failed rate query, overflow, invalid packed value, or failed token transfer reverts the whole transition; the cache must not be partially updated.

For rebasing or rate-bearing assets, “corresponds” needs careful definition. If rates can change independently between pool operations, cached values may intentionally represent a snapshot. The pool must specify whether it refreshes rates before each operation, bounds rate changes, or uses another invariant-compatible policy. Resetting the cache fixes stale state after depletion; it does not by itself solve stale or manipulable rate-provider data.

Trade-offs: cleanup versus recomputation

The reset path touches storage, but it is exceptional: it runs only when the last LP share is burned. The table compares the main choices by concrete work and security property; exact gas depends on compiler output, packing, and storage slot transitions.

ApproachWork at final burn / first depositCache reads for initial mintSecurity property
Leave cache unchanged0 reset writesUp to N stale readsUnsafe: old state can affect initial pricing
Clear all N entries at final burnN zeroing writes0 stale-cache readsSafe if residual-asset policy is also enforced
Recompute N entries on first deposit0 reset writes; N rate computations and writes at initialization0 stale-cache reads if implementation avoids themSafe when recomputation uses current, validated assets and rates
Generation-tag cache entriesO(N) generation checks or metadata handling, implementation-dependentNo valid old-generation readsSafe only if all reads enforce generation validity

N is the number of pool assets. A loop over a fixed, bounded asset count is usually acceptable on this exceptional path; if the pool supports a large or unbounded number of assets, bound it at construction and account for the worst-case gas. Clearing storage may receive a refund under applicable EVM rules, but refunds are capped and should not be treated as a guaranteed reimbursement. Recomputing rates can cost more than clearing slots, especially when rate providers are external contracts.

Differential and stateful verification

A unit test that checks only one deposit and one withdrawal can miss residual state accumulated across multiple cycles. Use a stateful test that repeatedly adds liquidity, removes partial amounts, removes the final shares, and deposits again. Assert both state invariants and the relationship between deposited value and minted shares.

Example Foundry checks should include:

function invariant_zeroSupplyHasNoCachedValue() public view {
    if (pool.totalSupply() == 0) {
        for (uint256 i; i < pool.assetCount(); ++i) {
            assertEq(pool.virtualBalance(i), 0);
        }
    }
}

That assertion assumes the chosen design clears all cache entries at zero supply; adapt it if the implementation uses an explicit invalid-generation marker. Also test that a first deposit’s minted amount is invariant to prior deposit/withdrawal history when the current balances and rates are identical.

Run targeted fuzzing and profile comparisons:

forge test --match-contract VirtualBalanceCacheTest --fuzz-runs 10000
forge test --match-test testRepeatedFullExitThenDustDeposit -vvvv
forge test --gas-report

For compiler-output review, inspect optimized IR and compare it with the configured production profile:

solc --version
solc --optimize --via-ir --ir-optimized src/Pool.sol
forge test --profile default

The IR command is useful for checking whether a reset loop or packed-field update compiles as expected; it is not a security proof. Keep the compiler version, optimizer settings, and evm_version fixed when comparing gas or behavior. Add a differential test that runs identical operation sequences against a simple reference model which recomputes virtual balances from actual balances on every operation. The production cache and reference model should agree after every transition, particularly after the final burn and subsequent initial mint.

For broader accounting context, distinguish stale-cache failures from token-transfer mismatches covered by Preventing ERC-20 Fee-On-Transfer Accounting Bugs in Solidity. If a deposit path uses signed authorization, also ensure its authorization cannot be reused across pool states or chains; see Preventing Signature Replay Attacks in Solidity.

Production pitfalls

  • Partial final exits: The reset must happen only when the actual LP supply reaches zero, not merely when a withdrawal is close to the total supply.
  • Burn rounding: Verify whether share burns, asset transfers, and cache decrements round in compatible directions. Do not assume proportional arithmetic reaches exactly zero.
  • Residual assets: Define ownership and treatment for every underlying token, including assets below a transfer or accounting threshold.
  • Packed fields: Clear the packed storage word or every packed subfield. Resetting one decoded value while leaving another pricing field intact is still stale state.
  • Reentrant token calls: If tokens or rate providers are untrusted or callback-capable, preserve a consistent state across external interactions. Update and validate accounting in an order appropriate to the pool’s reentrancy design.
  • Rates and precision: Check multiplication bounds, rate precision, and any minimum or maximum rate assumptions. Solidity 0.8 checked arithmetic reverts on overflow, but it does not make an economically incorrect formula safe.
  • Events and monitoring: Emit a reset or empty-pool transition event if it helps monitoring, but treat storage invariants—not off-chain event interpretation—as the security boundary.

Frequently Asked Questions (FAQ)

Why is totalSupply == 0 not enough to identify a fresh pool?

Supply tracks outstanding LP tokens, not every cached accounting value. A full withdrawal can leave residual values because proportional arithmetic rounds, so a zero-supply branch must clear or recompute pricing state before using it.

Can clearing packed_vbs alone prevent a repeat of the yETH exploit?

It prevents stale cache entries from influencing a later initial mint only if every relevant cached field is cleared and the next deposit computes shares from fresh, validated inputs. The protocol must also define how any residual underlying assets are handled when supply reaches zero.

Should a pool recompute virtual balances on every operation instead of caching them?

Recomputation reduces the risk of cache drift but may require additional rate-provider calls and gas for every operation. Caching can be safe if all state transitions update it consistently, the final-burn path invalidates it, and stateful tests compare it against a recomputing reference model.

Learn more with useful resources