Users will lose rewards when buying new tokens if they already own some tokens
When a user buys additional tokens of a share they already hold, the buy function updates their reward checkpoint after splitting the new fee, so their existing tokens never earn a share of that fee. The buyer permanently loses the reward they should have received on their old holdings, while other holders gain slightly more.
Weipeng Jiang Follow with d3e4, immeas and 15 others
Originally disclosed on Code4rena
Submitted by Krace, also found by d3e4, immeas, 0xAadi, mojito_auditor, PENGUN, Yanchuan, D1r3Wolf, ether_sky, tnquanghuy0512, AS, leegh, lanrebayode77, bin2chen, 0xpiken, glcanvas, SpicyMeatball, and rvierdiiev
When users purchase new tokens, the old tokens they already own do not receive the fees from this purchase, resulting in a loss of funds for the users.
Proof of Concept
According to the explanation by the sponsor (Roman), when users buy new tokens, the recently purchased token is not eligible for a fee. However, the “old shares” that users already own should be eligible.
Roman:
Hey, just a design decision, the idea behind it is that the user does not own the new shares yet when he buys, so he should not get any fees for it. Whereas he still owns it when he sells (it is basically the last sale).
Krace:
So the new shares should not get fee. If the user owns some “old shares”, is it eligible for a fee when the user buying?
Roman:
Yes, in that case, these shares are in the “owner pool” at the time of purchase and should be eligible
However, the buy function will completely disregard the rewards associated with the buyer’s “old shares” for these fees.
Let’s analyze the buy function:
- Step 1: It retrieves the rewards for the buyer before the purchase. These rewards are not linked to the purchase because they use the old token amounts, and the fees from this purchase are not factored in.
- Step 2: It splits the fees for this purchase.
_splitFeesincreases the value ofshareHolderRewardsPerTokenScaledbased on the fees from this purchase. - Step 3: It updates the
rewardsLastClaimedValueof the buyer to the latestshareHolderRewardsPerTokenScaled, which was increased in_splitFeesjust now.
The question arises: the fees from this purchase are not rewarded to the buyer’s old tokens between Step 2 and Step 3, yet the buyer’s rewardsLastClaimedValue is updated to the newest value. This results in the permanent loss of these rewards for the buyer.
function buy(uint256 _id, uint256 _amount) external {
require(shareData[_id].creator != msg.sender, "Creator cannot buy");
(uint256 price, uint256 fee) = getBuyPrice(_id, _amount); // Reverts for non-existing ID
SafeERC20.safeTransferFrom(token, msg.sender, address(this), price + fee);
// The reward calculation has to use the old rewards value (pre fee-split) to not include the fees of this buy
// The rewardsLastClaimedValue then needs to be updated with the new value such that the user cannot claim fees of this buy
//@audit it will get the rewards first
uint256 rewardsSinceLastClaim = _getRewardsSinceLastClaim(_id);
// Split the fee among holder, creator and platform
//@audit then split the fees of this buying
_splitFees(_id, fee, shareData[_id].tokensInCirculation);
//@audit and update sender's rewardsLastClaimedValue to the newest one, which is updated by `splitFees`
rewardsLastClaimedValue[_id][msg.sender] = shareData[_id].shareHolderRewardsPerTokenScaled;
shareData[_id].tokenCount += _amount;
shareData[_id].tokensInCirculation += _amount;
tokensByAddress[_id][msg.sender] += _amount;
if (rewardsSinceLastClaim > 0) {
SafeERC20.safeTransfer(token, msg.sender, rewardsSinceLastClaim);
}
emit SharesBought(_id, msg.sender, _amount, price, fee);
}
function _splitFees(
uint256 _id,
uint256 _fee,
uint256 _tokenCount
) internal {
uint256 shareHolderFee = (_fee * HOLDER_CUT_BPS) / 10_000;
uint256 shareCreatorFee = (_fee * CREATOR_CUT_BPS) / 10_000;
uint256 platformFee = _fee - shareHolderFee - shareCreatorFee;
shareData[_id].shareCreatorPool += shareCreatorFee;
if (_tokenCount > 0) {
//@audit shareHolderRewardsPerTokenScaled will be increased if tokenCount>0
shareData[_id].shareHolderRewardsPerTokenScaled += (shareHolderFee * 1e18) / _tokenCount;
} else {
// If there are no tokens in circulation, the fee goes to the platform
platformFee += shareHolderFee;
}
platformPool += platformFee;
}
Test
The following POC shows the case mentioned. Add it to 1155tech-contracts/src/Market.t.sol and run it with forge test --match-test testBuyNoReward -vv.
function testBuyNoReward() public {
// Bob create share with id 1
market.changeBondingCurveAllowed(address(bondingCurve), true);
market.restrictShareCreation(false);
vm.prank(bob);
market.createNewShare("Test Share", address(bondingCurve), "metadataURI");
assertEq(market.shareIDs("Test Share"), 1);
token.transfer(alice, 1e17);
// alice buy 1 token in share1 ==> token1
vm.startPrank(alice);
uint256 aliceBalanceBefore = token.balanceOf(alice);
token.approve(address(market), 1e18);
console.log(" alice balance ", aliceBalanceBefore);
market.buy(1, 1);
uint256 aliceBalanceAfter = token.balanceOf(alice);
console.log(" alice balance after buy ", aliceBalanceAfter);
console.log(" alice cost after buy ", aliceBalanceBefore - aliceBalanceAfter);
// alice buy another 1 token in share1 ==> token2
market.buy(1,1);
uint256 aliceBalanceAfterSecondBuy = token.balanceOf(alice);
console.log(" alice balance after second buy ", aliceBalanceAfterSecondBuy);
// alice get no reward for her token1
console.log(" alice cost after second buy ", aliceBalanceAfter - aliceBalanceAfterSecondBuy);
vm.stopPrank();
}
The result is shown below; Alice gets no rewards for token1:
[PASS] testBuyNoReward() (gas: 443199)
Logs:
alice balance 100000000000000000
alice balance after buy 98900000000000000
alice cost after buy 1100000000000000
alice balance after second buy 96700000000000000
alice cost after second buy 2200000000000000
After my suggested patch, Alice can get the rewards for token1: 2200000000000000 - 2134000000000000 = 66000000000000.
[PASS] testBuyNoReward() (gas: 447144)
Logs:
alice balance 100000000000000000
alice balance after buy 98900000000000000
alice cost after buy 1100000000000000
alice balance after second buy 96766000000000000
alice cost after second buy 2134000000000000
Tools Used
Foundry
Recommended Mitigation Steps
Split the fees before getting the rewards in buy:
diff --git a/1155tech-contracts/src/Market.sol b/1155tech-contracts/src/Market.sol
index 59c5c96..85d91a5 100644
--- a/1155tech-contracts/src/Market.sol
+++ b/1155tech-contracts/src/Market.sol
@@ -151,11 +151,11 @@ contract Market is ERC1155, Ownable2Step {
require(shareData[_id].creator != msg.sender, "Creator cannot buy");
(uint256 price, uint256 fee) = getBuyPrice(_id, _amount); // Reverts for non-existing ID
SafeERC20.safeTransferFrom(token, msg.sender, address(this), price + fee);
+ // Split the fee among holder, creator and platform
+ _splitFees(_id, fee, shareData[_id].tokensInCirculation);
// The reward calculation has to use the old rewards value (pre fee-split) to not include the fees of this buy
// The rewardsLastClaimedValue then needs to be updated with the new value such that the user cannot claim fees of this buy
uint256 rewardsSinceLastClaim = _getRewardsSinceLastClaim(_id);
- // Split the fee among holder, creator and platform
- _splitFees(_id, fee, shareData[_id].tokensInCirculation);
rewardsLastClaimedValue[_id][msg.sender] = shareData[_id].shareHolderRewardsPerTokenScaled;
shareData[_id].tokenCount += _amount;
Assessed type
Context
OpenCoreCH (Canto) confirmed, but disagreed with severity and commented:
These fees are not lost, the impact is just that for this particular
buys; the other users get more rewards and the user that buys less (but the same also applies for other users, so it might even cancel out for long-term holders). So I think high is definitely over-inflated for that.However, I agree that the current logic is a bit weird, but changing it such that they just receive rewards for the other shares would also be a bit weird (would incentivize to split up a buy into multiple ones). We discussed this internally and will change the logic such that users always receive fees for their
buys, no matter if it is the first or subsequent ones.
0xTheC0der (judge) decreased severity to Medium
Fixed.
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
The buy function splits the fee (raising the per-token reward accumulator) before reading the buyer's pending rewards, then sets the buyer's checkpoint to the post-split value, discarding the reward their existing tokens earned from that fee.
Impact
The buyer loses the fee reward on their existing tokens for that purchase; the sponsor notes the funds are not destroyed but go to other holders, so the loss is small and may even out for long-term holders.
What the attacker needed
A share already exists; buyer already holds tokens of that share; buyer makes a further purchase
The fix
The order was changed so fees are split before the buyer's pending rewards are read, and the sponsor states it was fixed.
How it was found
- Create a share and give a buyer some tokens so they already hold a position.
- Have the buyer purchase one token of that share.
- Have the same buyer purchase another token of the same share.
- Observe that the buyer receives no reward for the tokens held during the second purchase.
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.
A share contract pays holders a cut of every trading fee, tracked by a running total per token. When you buy more, the code first records what you are owed, then adds the new fee to the running total, then marks you as already paid up to the new total. That last step skips the fee you just generated, so your earlier tokens miss out on it.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.