Balancer
A rounding error in Balancer's ERC4626LinearPools allowed an attacker to repeatedly swap 1 wei of wrapped token for 1 wei of underlying token, extracting value because the wrapped token is worth more. Combined with flash swaps and zero fees when balanced, an attacker could drain all value from Boosted Pools.
medium.com
Published on medium.com
Immunefi
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Balancer is a decentralised automated market maker (AMM) built as a flexible building block for programmable liquidity. It separates the AMM curve logic and maths from the core swapping functionality, so it can incorporate any number of swap curves and pool types. Users swap between ERC20 tokens, liquidity providers (LPs) add liquidity to earn fees, arbitragers exploit price differences between pools, and BAL holders can lock tokens into veBAL to take part in governance.
The feature at the centre of this report is the Boosted Pool, which is built on Linear Pools. Balancer's V2 vaults try to increase capital efficiency by putting idle tokens to work: asset managers allocate a portion of idle tokens to yield farming strategies while the pool still behaves as if it holds the full balance, so swappers see minimal price impact and LPs earn yield on the managed tokens.
Linear Pools let an asset and its yield-bearing wrapped counterpart trade at a fixed exchange rate, either calculated or obtained through queries. They are initialised with a large portion of newly minted Balancer Pool Tokens (BPT), and swapping in or out for BPT counts the same as a join or exit for an LP. Linear Pools use Linear Maths to simplify exchanges between assets and their wrapped counterparts, and they implement a fee/reward system: swaps that imbalance the pool pay a higher fee, but swaps that keep the balance inside a target window pay zero fees. Because BPT are themselves ERC20 tokens, Linear Pools can be nested inside other pools, and a swapper can batch swap through the outer pool into the inner one via BPT.
Boosted Pools contain Linear Pools as their assets. The example given is the bb-a-USD Composable Stable Pool, which swaps USDC, USDT and DAI while sending liquidity to Aave. It is composed of three Linear Pools, bb-a-USDC, bb-a-USDT and bb-a-DAI, each swapping a stablecoin with its yield-generating token. Combined into the Boosted Aave USD pool, it can swap between any yield-generating token (aUSDC, aUSDT, aDAI) and the equivalent value of any underlying base asset (USDC, USDT, DAI).

Setup
On 11 August 2023 the whitehat GothicShanon89238 submitted a critical vulnerability to Balancer through Immunefi. The submission described a rounding error in ERC4626LinearPools combined with flashSwap. At the time of submission, all value in Boosted Pools, 20% of Balancer's $1 billion TVL, could be drained by the attack.
The proof of concept targets Balancer's bb-a-DAI Linear Pool. The full version lives in the Immunefi bugfix review repository at https://github.com/immunefi-team/bugfix-reviews-pocs/tree/main/src/Balancer/rounding-error-aug2023. The PoC consists of BalancerPoC.sol and AttackContract.sol.
Finding it
The reported issue is in the 1:1 swapping mechanism between the underlying token and the wrapped token in ERC4626LinearPools. When a user exchanges 1 wei of the wrapped token, the pool deducts only 1 wei from the underlying token. Since the wrapped token is worth more than the underlying asset, each such swap extracts value from the pool.
On its own this looks minor: gas and swap fees would normally stop an attacker from profiting. Three conditions aligned to make Linear Pools critically affected:
- Linear Pools allow flash swaps. These work like flash loans: an arbitrager who finds a price discrepancy can profit from a balancing swap without holding any initial capital. The functionality is enabled through batch swaps that settle at the end.
- Linear Pools charge no fees when balanced. An attacker can perform as many swaps as they like for free, as long as the balance between tokens stays inside the target window.
- Linear Pools are initialised with a very large balance of BPT, so an attacker can borrow an essentially unlimited amount of BPT to execute the attack.
Exploitation
The three conditions combine into an attack that would have allowed an attacker to drain all value in Boosted Pools:
- Execute a flash swap in a Linear Pool using BPT to trade for the main and wrapped tokens, significantly reducing the total supply of each to near 0.
- Perform multiple swaps with GivenOut between the underlying and wrapped, taking advantage of the rounding error to decrease the total balance without affecting the supply. The rate is calculated as
rate = balance/supply, so this drops the rate below 1. - Repay the flash swapped BPT by trading the underlying token at a lower rate than when it was borrowed.
The PoC demonstrates a simplified version of this against the bb-a-DAI Linear Pool. By executing the swapDecrease function multiple times, the test results in the theft of 320,891 DAI in a single transaction with no starting capital required.
Step 1: Install Foundry
Install the Foundry framework from https://github.com/foundry-rs/foundry
Step 2: Clone the repository
git clone https://github.com/immunefi-team/bugfix-reviews-pocs.git
This fetches the Immunefi bugfix review repository containing the PoC sources.
Step 3: Run the PoC
forge test -vvv — match-path ./test/Balancer/rounding-error-aug2023/BalancerPoC.sol

Root cause
The mistake is a rounding error in the 1:1 exchange between the underlying token and the wrapped token in ERC4626LinearPools: exchanging 1 wei of the wrapped token deducts only 1 wei of the underlying token, even though the wrapped token is worth more. Because the rate is balance/supply, repeatedly swapping with GivenOut reduces the balance without reducing the supply, pushing the rate below 1.
Three conditions aligned to make this exploitable. Gas and swap fees would normally make the value extraction unprofitable, but Linear Pools charge no fees while balanced, so the swaps are free. The absence of initial capital is not a barrier because flash swaps, enabled through batch swaps that settle at the end, let the attacker borrow BPT. And the large BPT balance with which Linear Pools are initialised gives the attacker essentially unlimited BPT to borrow.
Impact
At the time of submission, all value in Boosted Pools could be drained by the attack, which was 20% of Balancer's $1 billion TVL. The simplified PoC shows 320,891 DAI stolen in a single transaction with no starting capital required. The bug could have resulted in the drain of funds from composable vaults.
Fix
Balancer took measures to remediate the bug after receiving the report, and both Balancer and the whitehat collaborated on the mitigation. V5 Composable Stable Pools were paused and put into recovery mode, so swaps were disabled but users could still withdraw funds. Linear Pools could not be paused by Balancer, but the majority used upgradeable wrapper tokens whose code could be replaced to block swaps while still allowing direct unwrapping.
The total TVL at risk before mitigation was $242 million, reduced to $40 million after quick action from the Balancer team. For pools without a recovery mode or with incompatible wrappers, LPs were notified and urged to exit immediately, and 95% of all LPs withdrew without being affected. The vast majority of funds at risk were withdrawn within 48 hours. Balancer disclosed the vulnerability and provided a UI for streamlined withdrawals.
Balancer paid the whitehat 1,000,000 USDC, the highest bounty Balancer has awarded.
- Other
ERC4626-style Linear Pools. Try the same 1 wei wrapped-token exchange against any pool that pairs an asset with a yield-bearing wrapper. A positive result is that the underlying balance falls by less than the value of the wrapped token received, so the pool'sbalance/supplyrate drifts below 1. - Pools with zero-fee windows. Look for pools that charge no fee while the balance stays inside a target range. A positive result is that repeated GivenOut swaps can be executed at no cost while keeping the pool inside that window.
- Flash swap plus batch settlement. Check whether a pool permits flash swaps through batch swaps that settle at the end. A positive result is that you can borrow a large BPT position, manipulate the rate, and repay at the lower rate within one transaction.
- Nested pools. Test whether a Linear Pool nested inside an outer pool can be reached through BPT batch swaps. A positive result is that a swap through the outer pool moves the inner pool's balance and rate.
- Reentrancy assumptions. Since joins and exits can be executed as swaps of BPT, test whether batch swaps bypass reentrancy protections on a target. A positive result is state changing mid-swap in a way the protection was meant to prevent.
- Upgradeable wrappers. For pools that cannot be paused, check whether the wrapper token is upgradeable. A positive result is that swap functions can be blocked while direct unwrapping remains available, which is the mitigation Balancer used.
What happened, in plain words
In August 2023, a security researcher who goes by the handle GothicShanon89238 found a serious flaw in Balancer, a piece of software that lets people trade digital tokens with each other. The researcher reported it through Immunefi, a platform where people who find bugs are paid for reporting them instead of exploiting them. Balancer paid that researcher 1,000,000 USDC, which is a digital token designed to be worth one US dollar each, so roughly one million dollars. It is the highest reward Balancer has ever paid.
The flaw was small in itself: a rounding mistake in the way one kind of pool exchanged two tokens that should be worth the same. On its own, that mistake would have been too small to profit from, because the fees charged for each trade would have eaten any gain. But three other features of the system lined up with it, and together they let an attacker take money out of the pools without putting any money in first. At the time, all the money in the affected pools, which was 20% of the roughly one billion dollars Balancer held, could have been drained.
Balancer reacted quickly. It paused some pools, replaced the code of some tokens, told the people who had put money in to take it out, and most of the money at risk was withdrawn within 48 hours. The amount at risk fell from $242 million to $40 million after the first actions, and 95% of the people who had deposited funds got out without losing anything.
This article walks through what Balancer is, what the affected feature does, how the bug worked, how the researcher proved it with a small program, and how it was fixed. Every technical word is explained the first time it appears, and there is a glossary at the end.
What Balancer is
Balancer is what people in this world call an automated market maker, or AMM. To understand that, start with the ordinary idea of a currency exchange at an airport. You walk up to a counter, and the counter has a pile of euros and a pile of dollars. You hand over dollars and get euros, and the price depends on how much of each currency the counter is holding. Nobody is negotiating with you; the counter itself is the market.
An AMM is the same idea, but run by a computer program instead of a person behind a counter. The piles of currency are called pools, and each pool holds two or more kinds of digital token. Anyone can trade against a pool, and the price is worked out by a mathematical formula rather than by a trader shouting numbers. Balancer is one such program, and it was built to be flexible: it separates the maths that decides prices from the machinery that actually moves tokens, so new kinds of pool can be added without rewriting the core.
A few roles exist around a pool:
- Swappers trade one token for another.
- Liquidity providers, or LPs, put their tokens into the pool so that others have something to trade against. In return they earn a share of the fees charged on trades. Think of them as the people who stock the airport exchange counter with currency.
- Arbitragers watch for price differences between pools and trade to take advantage of them. Their trading is what tends to pull prices back in line.
- BAL holders hold Balancer's own token, BAL, and can lock it into a system called veBAL to take part in governance, meaning they get a say in how the project is run.
A token here is just a digital unit recorded on a blockchain, a shared ledger that many computers keep in sync. ERC20 is the common standard that says how such tokens behave, so when you read ERC20 token, it simply means a token that follows that standard.
Putting idle money to work
Balancer's second version of its core contract, called a vault, tried to be more efficient with money. In a normal pool, a large share of the tokens just sits there, never used for a trade, existing only to make trades cheaper for users. Balancer introduced asset managers: programs that take a portion of those idle tokens and put them into other places where they earn interest, a practice called yield farming. The pool still behaves as if it holds the full amount, so swappers see the same low price impact, meaning their trade moves the price less. Meanwhile the LPs earn extra yield on the tokens that are out earning interest. The comparison is a shop that lends some of its stock to a neighbour overnight and gets it back in the morning with a little extra, while still advertising the full stock to customers.
Linear Pools
A Linear Pool is a specific kind of pool where a token and its yield-bearing wrapped version trade at a fixed exchange rate. The wrapped version is a receipt token: you give the pool a token, and it gives you back a wrapper that represents the same value plus whatever interest it earns. The rate between the two can be calculated or looked up through a query, which is just a request for information.
Linear Pools are set up with a large amount of a token called a Balancer Pool Token, or BPT. BPT is itself a token that represents a share of the pool: if you hold BPT, you own a slice of everything in that pool. Because BPT is an ERC20 token like any other, it can be traded. Swapping in or out for BPT is treated exactly the same as an LP joining or leaving the pool.
Linear Pools use what the report calls Linear Maths, a set of formulas that simplify exchanging a token for its wrapped counterpart. They also have a fee and reward system. If a swap pushes the pool away from its target balance, it pays a higher fee. If the swap keeps the balance inside a certain window, there is no fee at all. The point is to reward arbitragers for keeping the two sides of the pool in the right proportion, automating a job that would otherwise need a person.
Pools inside pools
Because BPT is a token, a Linear Pool's BPT can itself be placed inside another pool. This is called nesting. Nesting lets a swapper trade through the outer pool into the inner one by passing BPT along, so someone can effectively trade their BPT for one of the tokens held deep inside the nested pool. Composability, the ability to snap pieces together like building blocks, is the whole point: a higher-level pool can reuse everything the pool underneath it does.
Boosted Pools
A Boosted Pool is built on top of Linear Pools: its assets are themselves Linear Pools. Because each Linear Pool automatically forwards idle tokens to an outside protocol that pays interest, swappers get deep liquidity and LPs get yield. And because everything is built on the same BPT foundation, a user can swap a yield-bearing token directly for an underlying token inside a Linear Pool.
The report's example is the bb-a-USD Composable Stable Pool. It lets people swap USDC, USDT and DAI, three tokens each designed to be worth one US dollar, while sending the idle liquidity to Aave, a lending protocol. The bb-a-USD pool is made of three Linear Pools: bb-a-USDC, bb-a-USDT and bb-a-DAI. Each of those swaps a stablecoin for its yield-generating version (aUSDC, aUSDT, aDAI). Combined into the Boosted Aave USD pool, the whole thing can swap between any of the yield-generating tokens and the equivalent value of any of the underlying base assets.

Finding the bug
The reported issue is in the 1:1 swapping mechanism between the underlying token and the wrapped token in ERC4626LinearPools. ERC4626 is a standard for these wrapper tokens, so an ERC4626 Linear Pool is a Linear Pool that uses that standard. The 1:1 mechanism is supposed to exchange one unit of the underlying token for one unit of the wrapped token, because the wrapper is meant to represent the same value.
The smallest unit a token can be divided into is called a wei. When a user exchanges 1 wei of the wrapped token, the pool deducts only 1 wei from the underlying token. That sounds correct, but the wrapped token is worth more than the underlying asset, because it has been earning interest. So each such swap takes out more value than it puts in, and the pool slowly loses value.
On its own this looks minor. Every trade on a blockchain costs a small fee called gas, paid to the computers that process it, and pools normally charge a swap fee on top. Those costs would usually be larger than the tiny gain from a rounding error, so an attacker would lose money trying. But three conditions lined up to make Linear Pools critically affected:
- Linear Pools allow flash swaps. A flash swap works like a flash loan: you borrow something and repay it within the same transaction, a single indivisible step on the blockchain. If you cannot repay, the whole thing is undone as if it never happened. This lets an arbitrager who spots a price discrepancy profit from a balancing swap without holding any starting capital. The feature is enabled through batch swaps that settle at the end, meaning several swaps are grouped together and the final balances are only checked once at the end.
- Linear Pools charge no fees when balanced. As long as the balance between the two tokens stays inside the target window, an attacker can perform as many swaps as they like for free.
- Linear Pools start with a very large balance of BPT. That means an attacker can borrow an essentially unlimited amount of BPT to run the attack.
How the attack worked
Those three conditions combine into an attack that would have allowed an attacker to drain all the value in Boosted Pools. The report describes it in three steps:
- Execute a flash swap in a Linear Pool using BPT to trade for the main and wrapped tokens, significantly reducing the total supply of each to near 0.
- Perform multiple swaps with GivenOut between the underlying and wrapped, taking advantage of the rounding error to decrease the total balance without affecting the supply. The rate is calculated as
rate = balance/supply, so this drops the rate below 1. - Repay the flash swapped BPT by trading the underlying token at a lower rate than when it was borrowed.
In plain words: the attacker first borrows a huge amount of the pool's own share token, BPT, in a way that must be repaid by the end of the same transaction. That borrowing shrinks the pool's recorded supply of tokens almost to nothing. Then the attacker repeatedly swaps the wrapped token for the underlying token, each time exploiting the rounding error so that the pool's balance falls without its supply falling. Since the exchange rate is balance divided by supply, pushing the balance down while the supply stays the same pushes the rate below 1. Finally the attacker repays the borrowed BPT, but now at the lower rate, so they owe less than they borrowed. The difference is profit taken from the pool.
Proving it with a proof of concept
A proof of concept, or PoC, is a small program that demonstrates a bug really works, rather than just describing it. This one targets Balancer's bb-a-DAI Linear Pool and is written for Foundry, a toolkit for writing and running tests against blockchain code on your own computer. The full version lives in the Immunefi bugfix review repository at https://github.com/immunefi-team/bugfix-reviews-pocs/tree/main/src/Balancer/rounding-error-aug2023. The PoC consists of two files, BalancerPoC.sol and AttackContract.sol.
By executing the swapDecrease function multiple times, the test shows a simplified version of the attack stealing 320,891 DAI in a single transaction, with no starting capital required.
Step 1: Install Foundry
Install the Foundry framework from https://github.com/foundry-rs/foundry
This line is not a command to type; it is an instruction telling you where to get Foundry. You would follow the installation instructions at that address.
Step 2: Clone the repository
git clone https://github.com/immunefi-team/bugfix-reviews-pocs.git
git is a tool for downloading and tracking versions of code. clone means make a local copy of a repository, which is a folder of code hosted online. The address after it points to the Immunefi bugfix review repository, which contains the PoC source files. Running this downloads the whole folder to your computer so you can read and run it.
Step 3: Run the PoC
forge test -vvv — match-path ./test/Balancer/rounding-error-aug2023/BalancerPoC.sol
The match-path filter restricts execution to the file BalancerPoC.sol inside the Balancer rounding-error directory, so only that one test runs instead of everything in the repository.

The root cause
The mistake is a rounding error in the 1:1 exchange between the underlying token and the wrapped token in ERC4626LinearPools: exchanging 1 wei of the wrapped token deducts only 1 wei of the underlying token, even though the wrapped token is worth more. Because the rate is balance/supply, repeatedly swapping with GivenOut reduces the balance without reducing the supply, pushing the rate below 1. GivenOut is simply the direction of the swap: the user says exactly how much they want to receive, and the pool works out how much it must take in.
The existing defences did not stop this. Gas and swap fees would normally make the value extraction unprofitable, but Linear Pools charge no fees while balanced, so the swaps are free. The absence of starting capital is not a barrier because flash swaps, enabled through batch swaps that settle at the end, let the attacker borrow BPT. And the large BPT balance with which Linear Pools are initialised gives the attacker essentially unlimited BPT to borrow. Batch swaps can also bypass reentrancy protections, since joins and exits can be executed as swaps of BPT. Reentrancy protection is a guard that stops a contract being called again while it is still in the middle of running; if joins and exits can be disguised as swaps, that guard can be sidestepped.
What the impact would have been
At the time of submission, all value in Boosted Pools could be drained by the attack, which was 20% of Balancer's $1 billion TVL. TVL stands for total value locked, the total amount of money sitting in the protocol. The simplified PoC shows 320,891 DAI stolen in a single transaction with no starting capital required. The bug could have resulted in the drain of funds from composable vaults, meaning the shared contracts that hold the pools' assets.
How it was fixed
Balancer took measures to remediate the bug after receiving the report, and both Balancer and the whitehat collaborated on the mitigation. V5 Composable Stable Pools were paused and put into recovery mode, so swaps were disabled but users could still withdraw funds. Recovery mode is a safe state: the pool stops accepting trades but still lets people take their money out. Linear Pools could not be paused by Balancer, but the majority used upgradeable wrapper tokens whose code could be replaced to block swaps while still allowing direct unwrapping. Upgradeable means the code behind the token can be swapped for new code, which is how the team could change behaviour without moving anyone's funds.
The total TVL at risk before mitigation was $242 million, reduced to $40 million after quick action from the Balancer team. For pools without a recovery mode or with incompatible wrappers, LPs were notified and urged to exit immediately, and 95% of all LPs withdrew without being affected. The vast majority of funds at risk were withdrawn within 48 hours. Balancer disclosed the vulnerability and provided a UI for streamlined withdrawals, a user interface, meaning a web page with buttons, so people could pull their money out without needing to write any code.
Balancer paid the whitehat 1,000,000 USDC, the highest bounty Balancer has awarded. A bounty is the reward a project pays for a responsibly reported bug.
If you want to hunt for the same kind of mistake elsewhere, these are the angles the report suggests, each with what a positive result looks like:
- Other
ERC4626-style Linear Pools. Try the same 1 wei wrapped-token exchange against any pool that pairs an asset with a yield-bearing wrapper. A positive result is that the underlying balance falls by less than the value of the wrapped token received, so the pool'sbalance/supplyrate drifts below 1. - Pools with zero-fee windows. Look for pools that charge no fee while the balance stays inside a target range. A positive result is that repeated GivenOut swaps can be executed at no cost while keeping the pool inside that window.
- Flash swap plus batch settlement. Check whether a pool permits flash swaps through batch swaps that settle at the end. A positive result is that you can borrow a large BPT position, manipulate the rate, and repay at the lower rate within one transaction.
- Nested pools. Test whether a Linear Pool nested inside an outer pool can be reached through BPT batch swaps. A positive result is that a swap through the outer pool moves the inner pool's balance and rate.
- Reentrancy assumptions. Since joins and exits can be executed as swaps of BPT, test whether batch swaps bypass reentrancy protections on a target. A positive result is state changing mid-swap in a way the protection was meant to prevent.
- Upgradeable wrappers. For pools that cannot be paused, check whether the wrapper token is upgradeable. A positive result is that swap functions can be blocked while direct unwrapping remains available, which is the mitigation Balancer used.
Glossary
- AMM (automated market maker): a program that lets people trade tokens against a pool using a formula instead of a human market maker.
- Arbitrager: someone who trades to profit from price differences between markets.
- Asset manager: in Balancer, a program that puts idle pool tokens into yield-earning strategies.
- BAL: Balancer's own governance token.
- Balance: the amount of a token a pool currently holds.
- Batch swap: several swaps grouped together and settled at the end.
- Blockchain: a shared ledger kept in sync by many computers.
- Boosted Pool: a pool whose assets are themselves Linear Pools.
- Bounty: a reward paid for responsibly reporting a bug.
- BPT (Balancer Pool Token): a token representing a share of a Balancer pool.
- Composability: the ability to combine pieces of software like building blocks.
- DAI, USDC, USDT: tokens each designed to be worth one US dollar.
- ERC20: the common standard for tokens on Ethereum-style blockchains.
- ERC4626: a standard for wrapper tokens that represent a yield-bearing position.
- Flash loan / flash swap: borrowing and repaying within a single transaction, undone entirely if repayment fails.
- Foundry: a toolkit for writing and running tests against blockchain code locally.
- Gas: a small fee paid to process a transaction.
- GivenOut: a swap direction where the user specifies how much they want to receive.
- Governance: the process by which token holders decide how a project is run.
- Linear Maths: the formulas Linear Pools use to exchange a token for its wrapped counterpart.
- Linear Pool: a pool that trades a token and its yield-bearing wrapper at a fixed rate.
- Liquidity: the tokens available in a pool for trading.
- Liquidity provider (LP): someone who deposits tokens into a pool to earn fees.
- Nesting: placing one pool's token inside another pool.
- Pool: a collection of tokens that people trade against.
- Price impact: how much a trade moves the price.
- Proof of concept (PoC): a small program that demonstrates a bug really works.
- Query: a request for information.
- Rate: here, balance divided by supply.
- Recovery mode: a safe state where swaps are disabled but withdrawals still work.
- Reentrancy protection: a guard that stops a contract being re-entered while it is still running.
- Repository: a folder of code hosted online, tracked by git.
- Stablecoin: a token designed to hold a steady value, usually one US dollar.
- Supply: the total number of a pool's share tokens in existence.
- Swap: exchanging one token for another.
- Swapper: someone who performs a swap.
- Token: a digital unit recorded on a blockchain.
- Transaction: a single indivisible action on the blockchain.
- TVL (total value locked): the total amount of money sitting in a protocol.
- UI (user interface): a web page with buttons that lets people use software without coding.
- Upgradeable: code that can be replaced with new code.
- Vault: Balancer's core contract that holds pool assets.
- veBAL: a locked form of BAL that carries governance power.
- Wei: the smallest unit a token can be divided into.
- Whitehat: a security researcher who reports bugs responsibly instead of exploiting them.
- Wrapped token: a receipt token representing an underlying token plus its earned yield.
- Yield farming: putting tokens into protocols to earn interest.