Stuck rewards in FeeSplitter contract
The FeeSplitter contract accumulates rewards per token using integer division, which leaves a remainder that no user can ever claim. As a result, a growing amount of ETH becomes permanently stuck in the contract with each buy or sell.
hals Follow with ether_sky, visualbits and 2 others
Originally disclosed on Code4rena
Submitted by hals, also found by ether_sky, visualbits, m4ttm, and btk
Curves protocol incentivize users to buy subjects and hold it for a prolonged time to receive high rewards, and the claimable rewards amount entitled for each user is calculated based on the user subject balance times the difference between the subject cumulativeFeePerToken and the user’s userFeeOffset of that subject, where the user’s userFeeOffset is updated whenever he buys or sells that specific subject:
```javascript
function onBalanceChange(address token, address account) public onlyManager {
TokenData storage data = tokensData[token];
data.userFeeOffset[account] = data.cumulativeFeePerToken;
if (balanceOf(token, account) > 0) userTokens[account].push(token);
}
```
The cumulativeFeePerToken is updated by an increment of msg.value / PRECISION, where msg.value represents the holdersFee amount that is deducted from each selling/purchase price of each subject token, and this value is accumulated to be claimed later by that subject holders (via FeeSplitter.addFees function):
```javascript
function addFees(address token) public payable onlyManager {
uint256 totalSupply_ = totalSupply(token);
if (totalSupply_ == 0) revert NoTokenHolders();
TokenData storage data = tokensData[token];
//@audit-issue : the more the totalSupply increases the more stuck rewards (division loss)
data.cumulativeFeePerToken += (msg.value * PRECISION) / totalSupply_;
}
```
But there’s an issue with this implementation:
- There will be always a locked amount in the contract equals to the latest subject’s
cumulativeFeePerToken, and this amount will be stuck and not utilized as there’s no way to withdraw them from the splitter contract (no withdraw function to rescue any stuck funds in excess of the contracts’s needs). - These stuck accrued rewards will never be fully claimed as well and will be increasing with each purchase or selling of that subject, because users will be able to claim rewards based on their subject balance times the difference between the subject
cumulativeFeePerTokenand the user’suserFeeOffsetof that subject only.
This issue is presented in the PoC section below, where all subject holders claim their rewards while there’s still a stuck amount of that subject rewards in the contract.
Proof of Concept
function addFees(address token) public payable onlyManager {
uint256 totalSupply_ = totalSupply(token);
if (totalSupply_ == 0) revert NoTokenHolders();
TokenData storage data = tokensData[token];
data.cumulativeFeePerToken += (msg.value * PRECISION) / totalSupply_;
}
Foundry PoC:
-
Test Setup: Foundry is used to write a PoC that illustrates this vulnerability, in order to setup Foundry testing environment in a project that uses hardhat, follow these steps/run the following commands in the project main directory:
- yarn add —dev @nomicfoundation/hardhat-foundry
- in
hardhat.config.tsfile , import:import "@nomicfoundation/hardhat-foundry"; - npx hardhat init-foundry
-
Add this
FeeSplitterTest.t.soltest file in the following directory2024-01-curves/test/FeeSplitterTest.t.sol:
```
├── 2024-01-curves
│ ├── test
│ ├──FeeSplitterTest.t.sol
```
```javascript
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
import {Test, console2} from "forge-std/Test.sol";
import {Curves} from "../contracts/Curves.sol";
import {CurvesERC20Factory} from "../contracts/CurvesERC20Factory.sol";
import {FeeSplitter} from "../contracts/FeeSplitter.sol";
import {CurvesERC20} from "../contracts/CurvesERC20.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract FeeSplitterTest is Test {
Curves public curves;
CurvesERC20Factory public factory;
FeeSplitter public feeSplitter;
//fees:
uint256 i_protocolFee = 5e16; // 5%
uint256 i_subjectFee = 5e16; // 5%
uint256 i_referralFee = 0; // 0%
uint256 i_holdersFee = 5e16; // 5%
//fee destination:
address protocolFeeDestination = makeAddr("protocolFeeDestination");
//subjects addresses:
address subjectOne = makeAddr("subjectOne");
//subject tokens addresses:
address subjectOneToken;
function setUp() public {
//1. deploy required contracts:
feeSplitter = new FeeSplitter();
factory = new CurvesERC20Factory();
curves = new Curves(address(factory), address(feeSplitter));
feeSplitter.setCurves(curves);
//2. set fees:
curves.setMaxFeePercent(i_protocolFee + i_subjectFee + i_holdersFee);
curves.setProtocolFeePercent(i_protocolFee, protocolFeeDestination);
curves.setExternalFeePercent(i_subjectFee, i_referralFee, i_holdersFee);
//3.add a subject token:
vm.startPrank(subjectOne);
curves.buyCurvesTokenWithName(subjectOne, 1, "subjectOne", curves.DEFAULT_SYMBOL());
subjectOneToken = curves.symbolToSubject("CURVES1");
vm.stopPrank();
}
function testSetUp() public {
// test fee setup:
(uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holdersFee, ) = curves.getFees(1 ether);
assertGt(protocolFee, 0);
assertGt(subjectFee, 0);
assertEq(referralFee, 0);
assertGt(holdersFee, 0);
// test if subject token is created:
assertFalse(subjectOneToken == address(0));
}
//! forge test --mt testDrainFeeSplitter
function testDrainFeeSplitter() public {
uint256 numberOfBuyers = 100;
address[] memory buyers = new address[](numberOfBuyers);
uint256 boughtAmount = 200; // each one of the buyers will buy 200 subject tokens
//1. 100 users buy subjectOne token:
for (uint256 i; i < numberOfBuyers; ++i) {
buyers[i] = makeAddr(string(Strings.toString(i)));
uint256 buyerBalanceBefore = curves.curvesTokenBalance(subjectOne, buyers[i]);
assert(buyerBalanceBefore == 0);
uint256 price = curves.getBuyPriceAfterFee(subjectOne, boughtAmount + i);
vm.deal(buyers[i], price);
vm.startPrank(buyers[i]);
curves.buyCurvesToken{value: price}(subjectOne, boughtAmount + i);
vm.stopPrank();
uint256 buyerBalanceAfter = curves.curvesTokenBalance(subjectOne, buyers[i]);
assert(buyerBalanceAfter == boughtAmount + i);
}
uint256 feeSplitterBalanceBeforeClaims = address(feeSplitter).balance;
// 2. now these users will claim their rewards from the splitter contract:
uint256 totalClaimableByUsers;
for (uint256 i; i < numberOfBuyers; ++i) {
uint256 buyerETHBalanceBefore = buyers[i].balance;
assert(buyerETHBalanceBefore == 0);
uint256 claimedFeesByBuyer = feeSplitter.getClaimableFees(subjectOne, buyers[i]);
vm.startPrank(buyers[i]);
feeSplitter.claimFees(subjectOne);
vm.stopPrank();
uint256 buyerETHBalanceAfter = buyers[i].balance;
assertGt(buyerETHBalanceAfter, buyerETHBalanceBefore);
assert(buyerETHBalanceAfter == claimedFeesByBuyer);
totalClaimableByUsers += claimedFeesByBuyer;
}
//3. As can be noticed: the splitter balance is larger than the claimable rewards which will result in the difference being stuck in the contract:
uint256 feeSplitterBalanceAfterClaims = address(feeSplitter).balance;
assertGt(totalClaimableByUsers - feeSplitterBalanceAfterClaims, 0); // stucke balance
assert(feeSplitterBalanceBeforeClaims - totalClaimableByUsers == feeSplitterBalanceAfterClaims);
console2.log("totalClaimableByUsers (# of ETH): ", totalClaimableByUsers / 1e18);
console2.log("--------------------------------------------------");
console2.log("stuck rewards in the splitter contract (# of ETH): ", feeSplitterBalanceAfterClaims / 1e18);
//4. to prove it more, another purchase is made, and the buyer claimed his rewards while the stuck amount is increased:
address lastBuyer = makeAddr("lastBuyer");
uint256 price = curves.getBuyPriceAfterFee(subjectOne, boughtAmount);
//---------- buying subjectOne tokens:
vm.deal(lastBuyer, price);
vm.startPrank(lastBuyer);
curves.buyCurvesToken{value: price}(subjectOne, boughtAmount);
//---------- lastBuyer claims his rewards:
feeSplitter.claimFees(subjectOne);
vm.stopPrank();
//-----
console2.log("--------------------------------------------------");
console2.log(
"stuck rewards in the splitter contract after the lastBuyer claimed his rewards (# of ETH): ",
address(feeSplitter).balance / 1e18
);
}
}
```
-
Explained scenario:
- The assumption made is that buyers will claim their rewards based on the same bought balance without manipulating it with direct transfers, otherwise another vulnerability is introduced (check issue under the title : “Any subject holder can drain the
FeeSplittercontract funds”). - 100 buyer purchase a specific amount of subjectOne token.
- Then all buyers claim their rewards from the splitter contract.
- There’s a stuck amount of subject rewards that will never be utilized, and this amount equals to the latest
cumulativeFeePerTokenof that subject. - To illustrate this more; another buyer (lastBuyer) buys subjectOne tokens and claim his rewards, and as can be noticed: more rewards stuck in the contract.
- The assumption made is that buyers will claim their rewards based on the same bought balance without manipulating it with direct transfers, otherwise another vulnerability is introduced (check issue under the title : “Any subject holder can drain the
-
Test result:
$ forge test --mt testDrainFeeSplitter -vvv Running 1 test for test/FeeSplitterTest.t.sol:FeeSplitterTest [PASS] testDrainFeeSplitter() (gas: 24258455) Logs: totalClaimableByUsers (# of ETH): 16178590 -------------------------------------------------- stuck rewards in the splitter contract (# of ETH): 963 -------------------------------------------------- stuck rewards in the splitter contract after the lastBuyer claimed his rewards (# of ETH): 390051 Test result: ok. 1 passed; 0 failed; 0 skipped; finished in 52.28ms Ran 1 test suites: 1 tests passed, 0 failed, 0 skipped (1 total tests)
Tools Used
Foundry
Recommended Mitigation Steps
Implement a mechanism to utilize these stuck rewards or withdraw them; or modify the current rewarding mechanism to prevent any stuck rewards in the future.
andresaiello (Curves) acknowledged
Note: For full discussion, see here.
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 integer division in the fee-per-token calculation truncates the result, leaving a remainder that is never distributed or recoverable.
Impact
A growing amount of ETH becomes permanently locked in the FeeSplitter contract, reducing the rewards available to users and locking funds indefinitely.
What the attacker needed
Users buy and sell subject tokens; holders fee is enabled
The fix
The contract should be modified to prevent stuck rewards, for example by tracking remainders or providing a withdrawal mechanism for excess funds.
How it was found
- Deploy the contracts and set fees including a holders fee.
- Have 100 buyers each purchase a different amount of subject tokens.
- Each buyer claims their rewards from the FeeSplitter.
- Observe that the contract balance exceeds the total claimed rewards.
- Have another buyer purchase tokens and claim rewards, increasing the stuck amount.
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 fees are added to a reward pool, the contract divides the total fee by the number of tokens. Because Solidity only handles whole numbers, any remainder is lost. Over time, these lost remainders add up to a significant amount of ETH that nobody can withdraw.