Skip to content
Audit finding Intermediate

Calling Position._marketBuy and Position._marketSell functions that calculate _fee by dividing by 10000 can cause incorrect calculations

The Position contract's _marketBuy and _marketSell functions calculate fees by dividing by 10000, while the RubiconMarket.buy function uses 100000 as the denominator. This mismatch causes users to receive fewer tokens than they are entitled to when using functions like buyAllAmountWithLeverage.

rbserver Follow with zhuXKET, Josiah and 38 others

Originally disclosed on Code4rena

Submitted by rbserver, also found by zhuXKET, Josiah, Aymen0909, immeas, immeas, teddav, joestakey, Ruhum, cducrest, markus_ether, markus_ether, Nyx, dec3ntraliz3d, Viktor_Cortess, 141345, Toshii, 0xDING99YA, sashik_eth, Madalad, peanuts, AlexCzm, R2, 0xfusion, SpicyMeatball, sinarette, cccz, xmxanuel, said, T1MOH, RaymondFam, MalfurionWhitehat, ljmanini, volodya, 3agle, sces60107, anodaram, ckksec, 0xnev, dacian and volodya.

Calling the following Position._marketBuy function executes uint256 _fee = _maxFill.mul(rubiconMarket.getFeeBPS()).div(10000), and calling the Position._marketSell function below executes uint256 _fee = _minFill.mul(_feeBPS).div(10000) and _fee = _payAmount.mul(_feeBPS).div(10000); in these _fee calculations, 10000 is used as the denominator.

https://github.com/code-423n4/2023-04-rubicon/blob/main/contracts/utilities/poolsUtility/Position.sol#L454-L473

    function _marketBuy(
        address _asset,
        address _quote,
        uint256 _maxFill
    ) internal {
        uint256 _fee = _maxFill.mul(rubiconMarket.getFeeBPS()).div(10000);
        uint256 _buyAmount = rubiconMarket.getBuyAmount(
            ERC20(_asset),
            ERC20(_quote),
            _maxFill.sub(_fee)
        );
        IERC20(_quote).approve(address(rubiconMarket), _maxFill);

        rubiconMarket.buyAllAmount(
            ERC20(_asset),
            _buyAmount,
            ERC20(_quote),
            _maxFill
        );
    }

https://github.com/code-423n4/2023-04-rubicon/blob/main/contracts/utilities/poolsUtility/Position.sol#L475-L511

    function _marketSell(
        address _asset,
        address _quote,
        uint256 _minFill
    ) internal {
        uint256 _feeBPS = rubiconMarket.getFeeBPS();
        uint256 _fee = _minFill.mul(_feeBPS).div(10000);
        uint256 _payAmount = rubiconMarket.getPayAmount(
            ERC20(_asset),
            ERC20(_quote),
            _minFill.add(_fee)
        );
        uint256 _assetBalance = IERC20(_asset).balanceOf(address(this));

        /// @dev recalculate fee in _asset form
        _fee = _payAmount.mul(_feeBPS).div(10000);

        if (_assetBalance < _payAmount) {
            IERC20(_asset).transferFrom(
                msg.sender,
                address(this),
                _payAmount.sub(_assetBalance).add(_fee)
            );
        }

        IERC20(_asset).approve(
            address(rubiconMarket),
            IERC20(_asset).balanceOf(address(this))
        );

        rubiconMarket.sellAllAmount(
            ERC20(_asset),
            _payAmount,
            ERC20(_quote),
            _minFill
        );
    }

When calling the Position._marketBuy and Position._marketSell functions, the following RubiconMarket.buy function will be eventually called. Calling the RubiconMarket.buy function executes uint256 fee = mul(spend, feeBPS) / 100_000, where 100_000, which is not 10000, is the denominator.

https://github.com/code-423n4/2023-04-rubicon/blob/main/contracts/RubiconMarket.sol#L314-L448

    function buy(
        uint256 id,
        uint256 quantity
    ) public virtual can_buy(id) synchronized returns (bool) {
        OfferInfo memory _offer = offers[id];
        uint256 spend = mul(quantity, _offer.buy_amt) / _offer.pay_amt;

        require(uint128(spend) == spend, "spend is not an int");
        require(uint128(quantity) == quantity, "quantity is not an int");

        ///@dev For backwards semantic compatibility.
        if (
            quantity == 0 ||
            spend == 0 ||
            quantity > _offer.pay_amt ||
            spend > _offer.buy_amt
        ) {
            return false;
        }

        offers[id].pay_amt = sub(_offer.pay_amt, quantity);
        offers[id].buy_amt = sub(_offer.buy_amt, spend);

        /// @dev Fee logic added on taker trades
        uint256 fee = mul(spend, feeBPS) / 100_000;
        require(
            _offer.buy_gem.transferFrom(msg.sender, feeTo, fee),
            "Insufficient funds to cover fee"
        );
        ...
    }

Because the Position._marketBuy and Position._marketSell functions calculate _fee through dividing by 10000 but the RubiconMarket.buy function calculates fee through dividing by 100_000, _fee and fee are different. This can cause incorrect calculations when calling the Position contract’s functions that eventually call the Position._marketBuy or Position._marketSell function, and users can lose tokens that they are entitled to, as a result. For example, when calling the Position.buyAllAmountWithLeverage function, the user should receive more asset tokens when the Position._marketBuy function calculates _fee through dividing by 100_000 than when the Position._marketBuy function calculates _fee through dividing by 10000. Thus, since the Position._marketBuy function currently calculates _fee through dividing by 10000, the user loses some asset tokens that they are entitled to.

Proof of Concept

First, please add the following changes of quote and asset tokens when Position._marketBuy function calculates _fee through dividing by 10000 test in the Long positions describe block in test\hardhat-tests\leverage-wrapper.ts. This test will pass to show the number of asset tokens received by the user who calls the Position.buyAllAmountWithLeverage function when the Position._marketBuy function calculates _fee through dividing by 10000.

      it.only("changes of quote and asset tokens when Position._marketBuy function calculates _fee through dividing by 10000", async function () {
        const { owner, testCoin, testStableCoin, Position} =
          await loadFixture(deployPoolsUtilityFixture);

        // testCoin is quote token when calling Position.buyAllAmountWithLeverage function
        const ownerTestCoinBalanceBefore = await testCoin.balanceOf(owner.address);

        // testStableCoin is asset token when calling Position.buyAllAmountWithLeverage function
        const ownerTestStableCoinBefore = await testStableCoin.balanceOf(owner.address);

        // owner calls Position.buyAllAmountWithLeverage function
        await Position.connect(owner).buyAllAmountWithLeverage(
          testCoin.address,
          testStableCoin.address,
          TEST_AMOUNT,
          x1_25
        );

        // owner sends 25000000000000000000 quote tokens
        const ownerTestCoinBalanceAfter = await testCoin.balanceOf(owner.address);
        expect(ownerTestCoinBalanceAfter.sub(ownerTestCoinBalanceBefore)).to.equal(-25000000000000000000n);

        // owner receives 5624437 asset tokens
        const ownerTestStableCoinAfter = await testStableCoin.balanceOf(owner.address);
        expect(ownerTestStableCoinAfter.sub(ownerTestStableCoinBefore)).to.equal(5624437);
      });

Second, please update the Position._marketBuy function, as follows, to divide by 100_000 for the POC purpose.

    function _marketBuy(
        address _asset,
        address _quote,
        uint256 _maxFill
    ) internal {
        /** @audit divide by 100_000 for POC purpose */
        // uint256 _fee = _maxFill.mul(rubiconMarket.getFeeBPS()).div(10000);
        uint256 _fee = _maxFill.mul(rubiconMarket.getFeeBPS()).div(100_000);
        /** */

        uint256 _buyAmount = rubiconMarket.getBuyAmount(
            ERC20(_asset),
            ERC20(_quote),
            _maxFill.sub(_fee)
        );
        IERC20(_quote).approve(address(rubiconMarket), _maxFill);

        rubiconMarket.buyAllAmount(
            ERC20(_asset),
            _buyAmount,
            ERC20(_quote),
            _maxFill
        );
    }

Third, please add the following changes of quote and asset tokens when Position._marketBuy function calculates _fee through dividing by 100_000 test in the Long positions describe block in test\hardhat-tests\leverage-wrapper.ts. This test will pass to show the number of asset tokens received by the user who calls the Position.buyAllAmountWithLeverage function when the Position._marketBuy function calculates _fee through dividing by 100_000. This test also demonstrates that the user should receive more asset tokens when the Position._marketBuy function calculates _fee through dividing by 100_000 than when the Position._marketBuy function calculates _fee through dividing by 10000.

      it.only("changes of quote and asset tokens when Position._marketBuy function calculates _fee through dividing by 100_000", async function () {
        const { owner, testCoin, testStableCoin, Position} =
          await loadFixture(deployPoolsUtilityFixture);

        // testCoin is quote token when calling Position.buyAllAmountWithLeverage function
        const ownerTestCoinBalanceBefore = await testCoin.balanceOf(owner.address);

        // testStableCoin is asset token when calling Position.buyAllAmountWithLeverage function
        const ownerTestStableCoinBefore = await testStableCoin.balanceOf(owner.address);

        // owner calls Position.buyAllAmountWithLeverage function
        await Position.connect(owner).buyAllAmountWithLeverage(
          testCoin.address,
          testStableCoin.address,
          TEST_AMOUNT,
          x1_25
        );

        // owner still sends 25000000000000000000 quote tokens
        const ownerTestCoinBalanceAfter = await testCoin.balanceOf(owner.address);
        expect(ownerTestCoinBalanceAfter.sub(ownerTestCoinBalanceBefore)).to.equal(-25000000000000000000n);

        // yet, owner receives 5624943 asset tokens
        const ownerTestStableCoinAfter = await testStableCoin.balanceOf(owner.address);
        expect(ownerTestStableCoinAfter.sub(ownerTestStableCoinBefore)).to.equal(5624943);

        // owner receives more asset tokens in this situation than when Position._marketBuy function calculates _fee through dividing by 10000
        expect(5624943).to.be.gt(5624437);
      });

Tools Used

VSCode

Recommended Mitigation Steps

The Position._marketBuy and Position._marketSell functions can be updated to divide by 100_000, instead of 10000, when calculating _fee.

bghughes (Rubicon) confirmed via duplicate issue #1025

HickupHH3 (judge) decreased severity to Medium


The original report as published on Code4rena, by rbserver. 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 a copy-paste or oversight where the fee denominator was set to 10000 instead of 100000 to match the market contract.

Impact

Users could lose a small amount of tokens they are entitled to when using functions that rely on these fee calculations.

What the attacker needed

User calls a Position function that uses _marketBuy or…

The fix

The Position._marketBuy and Position._marketSell functions should be updated to divide by 100_000 instead of 10000 when calculating _fee.

How it was found

  1. Add a test to the Long positions describe block in leverage-wrapper.ts that calls buyAllAmountWithLeverage and records token balances.
  2. Run the test to observe the asset tokens received when _fee is calculated with denominator 10000.
  3. Update the _marketBuy function to divide by 100000 for proof-of-concept.
  4. Add another test that calls buyAllAmountWithLeverage and records balances.
  5. Run the test to observe the asset tokens received when _fee is calculated with denominator 100000.
  6. Compare the results to show the user receives more tokens with the corrected denominator.

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.

In smart contracts, fees are often calculated as a percentage using a denominator like 10000 (meaning 1/100th of a percent). Here, two parts of the same system use different denominators (10000 vs 100000), so the fee amounts don't match. As a result, users get slightly less of the asset they are buying than they should.

More by rbserver

View all

51 more disclosed reports, best first.

More from Rubicon v2

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.