GetActualSupply should be used instead of total
The rewards distributor computed the expected BPT output for a Balancer pool join using the pool's totalSupply rather than its actual supply, which ignores protocol fees and unminted tokens. This made the slippage-protection figure too low, so a user's join could be sandwiched and they could receive less BPT than they should.
- Disclosed after under an hour
31335 - [SC - High] getActualSupply should be used instead of total...
Submitted on May 17th 2024 at 11:44:53 UTC by @OxAnmol for Boost | Alchemix
Report ID: #31335
Report type: Smart Contract
Report severity: High
Target: https://github.com/alchemix-finance/alchemix-v2-dao/blob/main/src/RewardsDistributor.sol
Impacts:
- Theft of unclaimed yield
Description
Brief/Intro
The rewardDistributor:_depositIntoBalancerPool uses totalSupply from the balance pool to calculate the expected BPT amount out. But the balancer docs recommend using getActualSupply instead of totalSupply.
Vulnerability Details
totalSupply function in the balancer doesn’t account for protocol fees and unminted tokens which means the totalSupply doesn't' correctly reflect the actual supply of BPT. The balancer recommends using getActualSupply to get the correct total supply of the BPT tokens.
https://docs.balancer.fi/concepts/advanced/valuing-bpt/valuing-bpt.html#getting-bpt-supply
In our case, the BPT total supply function is used to calculate the bptAmountOut
uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn(
balances,
_normalizedWeights,
amountsIn,
IERC20(address(balancerPool)).totalSupply(), //@audit should use getActualSupply
balancerPool.getSwapFeePercentage()
);
bptAmountOut here acts like a slippage protection for add liquidity and this parameter is very important for sandwich protection. If the total supply is used instead of getActualSupply then the bptAmountOut can be significantly low and this can be vulnerable to sandwich attacks resulting in the loss of BPT for a user.
Impact Details
Users can receive less BPT because of sandwich attacks resulting in the loss of unclaimed yield for the user. Please follow this and
this for further clarity in the issue.
References
https://docs.balancer.fi/concepts/advanced/valuing-bpt/valuing-bpt.html#getting-bpt-supply
##Recommedation use getActualSupply instead of totalSupply
Proof of Concept
Here I have added a new interface IBalancerPool, edited the RewardDistributor:_depositIntoBalancerPool in RewardDistributor and used getTotalSupply to get bptAmountOut2 The console log is used to show the difference between the two outputs.
interface IBalancerPool {
function getActualSupply() external view returns (uint256);
}
...SNIP..
function _depositIntoBalancerPool(
uint256 _wethAmount,
uint256 _alcxAmount,
uint256[] memory _normalizedWeights
) internal {
(, uint256[] memory balances, ) = balancerVault.getPoolTokens(balancerPoolId);
uint256[] memory amountsIn = new uint256[](2);
amountsIn[0] = _wethAmount;
amountsIn[1] = _alcxAmount;
uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn(
balances,
_normalizedWeights,
amountsIn,
IERC20(address(balancerPool)).totalSupply(),
balancerPool.getSwapFeePercentage()
);
uint256 bptAmountOut2 = WeightedMath._calcBptOutGivenExactTokensIn(
balances,
_normalizedWeights,
amountsIn,
IBalancerPool(address(balancerPool)).getActualSupply(),
balancerPool.getSwapFeePercentage()
);
if (bptAmountOut > bptAmountOut2) {
console2.log("bptAmountOut > bptAmountOut2 and diff is ", bptAmountOut - bptAmountOut2);
} else if (bptAmountOut < bptAmountOut2) {
console2.log("bptAmountOut < bptAmountOut2 and diff is ", bptAmountOut2 - bptAmountOut);
//@audit-issue this is a potential issue
} else {
console2.log("bptAmountOut == bptAmountOut2");
}
bytes memory _userData = abi.encode(
WeightedPoolUserData.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT,
amountsIn,
bptAmountOut2
);
IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({
assets: poolAssets,
maxAmountsIn: amountsIn,
userData: _userData,
fromInternalBalance: false
});
balancerVault.joinPool(balancerPoolId, address(this), address(this), request);
}
add this test in Voting.t.sol
function testGetActualSupply() public {
uint256 period = minter.activePeriod();
// Create a veALCX token and vote to trigger voter rewards
uint256 tokenId = createVeAlcx(admin, TOKEN_1, MAXTIME, false);
address bribeAddress = voter.bribes(address(sushiGauge));
createThirdPartyBribe(bribeAddress, bal, TOKEN_100K);
address[] memory pools = new address[](1);
pools[0] = sushiPoolAddress;
uint256[] memory weights = new uint256[](1);
weights[0] = 5000;
address[] memory bribes = new address[](1);
bribes[0] = address(bribeAddress);
address[][] memory tokens = new address[][](2);
tokens[0] = new address[](1);
tokens[0][0] = bal;
hevm.startPrank(admin);
veALCX.approve(beef, tokenId);
hevm.stopPrank();
hevm.startPrank(beef);
voter.vote(tokenId, pools, weights, 0);
// Move forward a week relative to period
hevm.warp(period + nextEpoch);
voter.distribute();
hevm.deal(beef, 10e18); // Sendt 10 ether to admin
// 10 ether should be enough to pair with ALCX
distributor.claim{ value: 10e18 }(tokenId, true); // Opt for compounding
hevm.stopPrank();
}
Console Outputs
Ran 1 test for src/test/Voting.t.sol:VotingTest
[PASS] testGetActualSupply() (gas: 4931022)
Logs:
bptAmountOut < bptAmountOut2 and diff is 130532624887077104
Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 142.81s (116.42s CPU time)
Ran 1 test suite in 143.73s (142.81s CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)
As we can see the bptAmountOut2 calculated using getTotalSupply is greater than bptAmountOut. The difference here might seem small but this will largely depend on the trading volume of the balancer pool.
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 code used the pool's totalSupply, which does not reflect protocol fees or unminted tokens, instead of the Balancer-recommended actual supply when computing the expected BPT output.
Impact
Users could receive less BPT through sandwich attacks, resulting in loss of unclaimed yield; the size of the gap depends on the pool's trading volume.
What the attacker needed
Victim claims rewards with compounding; attacker can sandwich the pool join
The fix
The code should use getActualSupply instead of totalSupply when calculating the expected BPT amount out.
How it was found
- Call the distributor's claim with compounding enabled so it deposits into the Balancer pool.
- Compare the BPT amount computed with totalSupply against the amount computed with getActualSupply.
- Observe that the totalSupply-based figure is lower than the actual-supply figure.
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.
When you add money to a shared pool, the contract works out in advance how many pool tokens you should get back, and that number protects you from being short-changed. Here it used a slightly wrong measure of the pool's size, so the protection was weaker than it should be. An attacker who reorders trades around yours could then take some of the value you were owed.
What is Smart contracts?
Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.