Skip to content
Smart contracts Audit finding Intermediate

Reward accounting is incorrect in BathBuddy contract

The BathBuddy contract calculates rewards based on the BathToken's total supply and account balances, but it does not update its reward accounting when those balances change through mint, burn, or transfer. An attacker could transfer tokens just before claiming rewards to receive the full reward amount, while the previous holder receives nothing.

adriro Follow with R2, cducrest and 48 others

Originally disclosed on Code4rena

Submitted by adriro, also found by R2, cducrest, zhuXKET, dec3ntraliz3d, 0xTheC0der, AlexCzm, markus_ether, 0xTheC0der, immeas, teddav, immeas, kutugu, nirlin, joestakey, kaden, John, nirlin, Emmanuel, 0Kage, shalaamum, Toshii, Delvir0, rbserver, 141345, 141345, 0xDING99YA, 0xDING99YA, ast3ros, Lirios, sces60107, jasonxiale, mrpathfindr, SaeedAlipoor01988, KingNFT, Ace-30, sinarette, carrotsmuggler, carrotsmuggler, Lilyjjo, Lilyjjo, lopotras, ktg, Banditx0x, yellowBirdy, dontonka, RedTiger, Banditx0x, bytes032, cccz, bytes032, mjmoonwalker, cccz, chaduke, SpicyMeatball, bytes032, nobody2018, T1MOH, Juntao, 0xStalin, J4de, Dug, ljmanini, 0xmichalis, rvierdiiev, Fanz, rvierdiiev and 117l11.

The BathBuddy contracts implements rewards for liquidity providers (holders of BathToken). The contract is modeled after the famous Synthetix staking contract, with some tweaks to support rewards for multiple tokens at the same time.

The implementation overall is correct; however, there is a critical difference with the Synthetix contract that is ignored in the BathBuddy contract. In the Synthetix implementation, the main actions related to rewards accounting are the stake and withdraw actions. These trigger the updateReward modifier to ensure correct reward accounting. Staked tokens cannot be transferred, as these are held in the staking contract. In the BathBuddy implementation, things are very different as there is no staking. Rewards are intended to be distributed directly to holders of the BathToken without any need of staking the tokens in the contract. This means that, as there is no “staking” action in the BathBuddy implementation (i.e. depositing funds in the contract), rewards fail to be correctly accounted whenever BathToken are minted, burned or transferred between different accounts.

These are two critical places in the code where the BathBuddy contract uses the state from the BathToken, but fails to be triggered whenever the state in the BathToken is modified. The first is rewardPerToken, which calculates the amount of rewards that should correspond to one unit of the BathToken token. This is logically dependent on the total supply of the token (lines 124 and 133):

https://github.com/code-423n4/2023-04-rubicon/blob/main/contracts/periphery/BathBuddy.sol#L121-L135

121:     function rewardPerToken(address token) public view returns (uint256) {
122:         require(friendshipStarted, "I have not started a bathToken friendship");
123:
124:         if (IERC20(myBathTokenBuddy).totalSupply() == 0) {
125:             return rewardsPerTokensStored[token];
126:         }
127:         return
128:             rewardsPerTokensStored[token].add(
129:                 lastTimeRewardApplicable(token)
130:                     .sub(lastUpdateTime[token])
131:                     .mul(rewardRates[token])
132:                     .mul(1e18)
133:                     .div(IERC20(myBathTokenBuddy).totalSupply())
134:             );
135:     }

The other place is in the earned function which uses the BathToken balanceOf function of an account (lines 146-147):

https://github.com/code-423n4/2023-04-rubicon/blob/main/contracts/periphery/BathBuddy.sol#L139-L161

139:     function earned(
140:         address account,
141:         address token
142:     ) public view override returns (uint256) {
143:         require(friendshipStarted, "I have not started a bathToken friendship");
144:
145:         return
146:             IERC20(myBathTokenBuddy) // Care with this?
147:                 .balanceOf(account)
148:                 .mul(
149:                     rewardPerToken(token).sub(
150:                         userRewardsPerTokenPaid[token][account]
151:                     )
152:                 )
153:                 .div(1e18)
154:                 .add(tokenRewards[token][account]);
155:     }
156:
157:     function getRewardForDuration(
158:         address token
159:     ) external view returns (uint256) {
160:         return rewardRates[token].mul(rewardsDuration[token]);
161:     }

Since the whole BathBuddy contract is dependent on the total supply and account balance state of the paired BathToken contract, the following actions in the token should update the rewards state in BathBuddy:

  • mint and burn, as these modify the total supply of the token and the balances of the account whose tokens are minted or burned.
  • transfer and transferFrom, as these modify the balances of the sender and recipient accounts.

As the BathBuddy updateReward modifier fails to be triggered when the mentioned state in the BathToken is modified, reward accounting will be incorrect for many different scenarios. We’ll explore one of these in the next section.

Proof of Concept

In the following test, we demonstrate one of the possible scenarios where reward accounting is broken. This is a simple case in which rewards fail to be updated when a token transfer is executed. Alice has 1e18 BathTokens, at the middle of the rewards duration period she sends all her tokens to Bob. The expected outcome should be that Alice would earn half of the rewards, as she held the tokens for the half of the duration period. But when the duration period has ended, we call getReward for both Alice and Bob and we can see that Alice got nothing and Bob earned 100% of the rewards.

Note: the snippet shows only the relevant code for the test. Full test file can be found here.

function test_BathBuddy_IncorrectRewardAccounting() public {
    // Setup rewards
    uint256 startTime = block.timestamp;
    uint256 duration = 10_000 seconds;
    vm.prank(bathBuddyOwner);
    bathBuddy.setRewardsDuration(duration, address(rewardToken));

    uint256 rewardAmount = 100 ether;
    rewardToken.mint(address(bathBuddy), rewardAmount);
    vm.prank(bathBuddyOwner);
    bathBuddy.notifyRewardAmount(rewardAmount, rewardToken);

    // Mint bathTokens to Alice
    uint256 bathTokenAmount = 1 ether;
    bathToken.mint(alice, bathTokenAmount);

    // Simulate half of the duration time passes
    vm.warp(startTime + duration / 2);

    // Alice transfers tokens for Bob at middle of the period
    vm.prank(alice);
    bathToken.transfer(bob, bathTokenAmount);

    // Simulate complete duration time passes
    vm.warp(startTime + duration);

    // Trigger getRewards for Alice
    vm.prank(bathBuddyHouse);
    bathBuddy.getReward(rewardToken, alice);

    // Trigger getRewards for Bob
    vm.prank(bathBuddyHouse);
    bathBuddy.getReward(rewardToken, bob);

    // Alice gets nothings and Bob gets the full rewards, even though Alice held the tokens for half the duration time
    assertEq(rewardToken.balanceOf(alice), 0);
    assertEq(rewardToken.balanceOf(bob), rewardAmount);
}

Recommendation

There are two recommended paths here. The easy path would be to just add the stake and withdraw functions to the BathBuddy contract similar to how the original StakingRewards contract works on Synthetix. However, this may change the original intention of the protocol as rewards won’t be earned just by holding BathTokens, they will need to be staked (rewards will only be distributed to stakers).

The other path, and a bit more complex, would be to modify the BathToken contract (the cToken) so that burn, mint and transfer actions trigger the update on the paired BathBuddy contract.

daoio (Rubicon) confirmed

HickupHH3 (judge) commented:

This write-up encapsulates the issues arising from forking the staking contract, but doing away with the staking portion through the usage of balanceOf() and totalSupply().

  • No initialisation of userRewardsPerTokenPaid
  • Doesn’t account for holding duration

0xepley (warden) commented:

I think that in the duplicate, two categories of issues have been merged into one.

So the two separate problems that have been merged into one are:

  1. Difference of implementation from synthetix, where there is no modifier on stake and withdraw. Hence, the calculation is flawed, leading to being able to claim the reward for whole duration by minting at the last moment, reducing others’ rewards.
  2. Second, is the ability to transfer the token and claim (again and again, etc) until the contract is drained.

Both are different issues and require different solutions.

Just for example, two marked duplicates are: #1074 and #1168. Each explain separate issues of uneven distribution and draining.

HickupHH3 (judge) commented:

(2) is enabled by (1).

The removal of staking & withdrawing (1) also led to the removal of initialisation of the rewardsPerToken, which allows you to do (2).


The original report as published on Code4rena, by adriro. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

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 reward accounting is not updated when the underlying BathToken's total supply or balances change, because the contract removed the staking mechanism that would normally trigger updates.

Impact

A user could transfer tokens to another account just before claiming rewards to receive the full reward amount, while the original holder receives nothing, potentially draining rewards from other users.

What the attacker needed

A BathToken holder; ability to transfer tokens; rewards are active

The fix

The contract should be modified so that mint, burn, and transfer actions in the BathToken trigger an update of the reward accounting in the paired BathBuddy contract, or staking and withdrawal functions should be added.

How it was found

  1. Set up rewards with a duration and notify the reward amount.
  2. Mint BathTokens to Alice.
  3. Simulate half of the duration time passing.
  4. Alice transfers all her tokens to Bob.
  5. Simulate the full duration time passing.
  6. Call getReward for Alice and Bob; Alice gets nothing and Bob gets the full reward.

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.

This is a smart contract that gives rewards to people who hold a special token. The contract checks how many tokens you have to decide your reward, but it doesn't update its records when tokens move between people. So someone can move tokens to a new address right before rewards are paid and collect rewards that were earned by someone else.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by adriro

View all

57 more disclosed reports, best first.

More from Rubicon v2

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.