Skip to content
Business logic Audit finding Intermediate

Calling Position._marketSell function compares fill_amt that includes fee to min_fill_amount that does not include fee

The Position._marketSell function passes a minimum fill amount that excludes the fee to RubiconMarket.sellAllAmount, which compares it against a fill amount that includes the fee. This makes the slippage check ineffective, so a trade could fill at a worse price than the user intended.

rbserver Follow with volodya

Originally disclosed on Code4rena

Submitted by rbserver, also found by volodya.

Calling the following Position._marketSell function calls rubiconMarket.sellAllAmount(ERC20(_asset), _payAmount, ERC20(_quote), _minFill), where _minFill does not include _fee.

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
        );
    }

Calling the following RubiconMarket.sellAllAmount function then executes require(fill_amt >= min_fill_amount, "min_fill_amount isn't filled"). In contrast to min_fill_amount, which is the Position._marketSell function’s _minFill that does not include _fee, fill_amt used in this require statement includes the fee. This means that fill_amt is very likely to be bigger than min_fill_amount, which makes this require statement and the corresponding slippage control not effective. In fact, as shown by the POC below, the fill_amt with the fee deducted that is set by calling calcAmountAfterFee(fill_amt) can equal min_fill_amount, which also proves that the fill_amt, which includes the fee, would be larger than min_fill_amount that does not include fee, and improperly comparing these two in the require statement would only result in an ineffective slippage control.

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

    function sellAllAmount(
        ERC20 pay_gem,
        uint256 pay_amt,
        ERC20 buy_gem,
        uint256 min_fill_amount
    ) external returns (uint256 fill_amt) {
        require(!locked);

        uint256 offerId;
        while (pay_amt > 0) {
            //while there is amount to sell
            offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair
            require(offerId != 0, "0 offerId"); //Fails if there are not more offers

            // There is a chance that pay_amt is smaller than 1 wei of the other token
            if (
                mul(pay_amt, 1 ether) <
                wdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)
            ) {
                break; //We consider that all amount is sold
            }
            if (pay_amt >= offers[offerId].buy_amt) {
                //If amount to sell is higher or equal than current offer amount to buy
                fill_amt = add(fill_amt, offers[offerId].pay_amt); //Add amount bought to acumulator
                pay_amt = sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to sell
                take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer
            } else {
                // if lower
                uint256 baux = rmul(
                    mul(pay_amt, 10 ** 9),
                    rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)
                ) / 10 ** 9;
                fill_amt = add(fill_amt, baux); //Add amount bought to acumulator
                take(bytes32(offerId), uint128(baux)); //We take the portion of the offer that we need
                pay_amt = 0; //All amount is sold
            }
        }
        require(fill_amt >= min_fill_amount, "min_fill_amount isn't filled");
        fill_amt = calcAmountAfterFee(fill_amt);
    }

Proof of Concept

First, please update the Position._marketSell function as follows to divide by 100_000 for the POC purpose. This is for fixing the bug mentioned in the report titled “Calling Position._marketBuy and Position._marketSell functions that calculate _fee by dividing by 10000 can cause incorrect calculations”.

    function _marketSell(
        address _asset,
        address _quote,
        uint256 _minFill
    ) internal {
        uint256 _feeBPS = rubiconMarket.getFeeBPS();

        /** @audit divide by 100_000 for POC purpose */
        // uint256 _fee = _minFill.mul(_feeBPS).div(10000);
        uint256 _fee = _minFill.mul(_feeBPS).div(100_000);
        /** */

        uint256 _payAmount = rubiconMarket.getPayAmount(
            ERC20(_asset),
            ERC20(_quote),
            _minFill.add(_fee)
        );
        uint256 _assetBalance = IERC20(_asset).balanceOf(address(this));

        /** @audit divide by 100_000 for POC purpose */
        /// @dev recalculate fee in _asset form
        // _fee = _payAmount.mul(_feeBPS).div(10000);
        _fee = _payAmount.mul(_feeBPS).div(100_000);
        /** */

        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
        );
    }

Second, please update the RubiconMarket.sellAllAmount function as follows to log min_fill_amount, the fill_amt that includes fee, and the fill_amt with the fee deducted for the POC purpose.

    function sellAllAmount(
        ERC20 pay_gem,
        uint256 pay_amt,
        ERC20 buy_gem,
        uint256 min_fill_amount
    ) external returns (uint256 fill_amt) {
        require(!locked);

        uint256 offerId;
        while (pay_amt > 0) {
            //while there is amount to sell
            offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair
            require(offerId != 0, "0 offerId"); //Fails if there are not more offers

            // There is a chance that pay_amt is smaller than 1 wei of the other token
            if (
                mul(pay_amt, 1 ether) <
                wdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)
            ) {
                break; //We consider that all amount is sold
            }
            if (pay_amt >= offers[offerId].buy_amt) {
                //If amount to sell is higher or equal than current offer amount to buy
                fill_amt = add(fill_amt, offers[offerId].pay_amt); //Add amount bought to acumulator
                pay_amt = sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to sell
                take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer
            } else {
                // if lower
                uint256 baux = rmul(
                    mul(pay_amt, 10 ** 9),
                    rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)
                ) / 10 ** 9;
                fill_amt = add(fill_amt, baux); //Add amount bought to acumulator
                take(bytes32(offerId), uint128(baux)); //We take the portion of the offer that we need
                pay_amt = 0; //All amount is sold
            }
        }

        /** @audit console.log min_fill_amount for POC purpose */
        console.log("min_fill_amount:");
        console.log(min_fill_amount);
        console.log("");
        /** */

        /** @audit console.log fill_amt for POC purpose */
        console.log("fill_amt that includes fee:");
        console.log(fill_amt);
        console.log("");

        console.log("Is the fill_amt, which includes fee, bigger than min_fill_amount that does not include fee?");
        console.log(fill_amt > min_fill_amount);
        console.log("");
        /** */

        require(fill_amt >= min_fill_amount, "min_fill_amount isn't filled");
        fill_amt = calcAmountAfterFee(fill_amt);

        /** @audit console.log fill_amt with fee deducted for POC purpose */
        console.log("fill_amt with fee deducted:");
        console.log(fill_amt);
        console.log("");

        console.log("Does the fill_amt with fee deducted equal min_fill_amount that does not include fee?");
        console.log(fill_amt == min_fill_amount);
        console.log("");
        /** */
    }

Third, please add the following Calling Position._marketSell function compares fill_amt that includes fee to min_fill_amount that does not include fee test in the Long positions describe block in test\hardhat-tests\leverage-wrapper.ts. This test will pass to print the logs below for demonstrating the described scenario:

      it.only("Calling Position._marketSell function compares fill_amt that includes fee to min_fill_amount that does not include fee", async function () {
        const { owner, testCoin, testStableCoin, Position, rubiconMarket } =
          await loadFixture(deployPoolsUtilityFixture);

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

        await rubiconMarket.functions["offer(uint256,address,uint256,address)"](
          parseUnits("1300", 6),
          testStableCoin.address,
          parseUnits("1000"),
          testCoin.address,
          { from: owner.address }
        );

        // Call Position.closePosition function, which further calls Position._marketSell function.
        // console.logs in RubiconMarket.sellAllAmount function show that
        //   the fill_amt, which includes fee, is bigger than min_fill_amount that does not include fee and
        //   the fill_amt with fee deducted equals min_fill_amount input that does not include fee.
        await Position.connect(owner).closePosition(1);
      });
min_fill_amount:
5625001

fill_amt that includes fee:
5625057

Is the fill_amt, which includes fee, bigger than min_fill_amount that does not include fee?
true

fill_amt with fee deducted:
5625001

Does the fill_amt with fee deducted equal min_fill_amount that does not include fee?
true

Tools Used

VSCode

Recommended Mitigation Steps

The Position._marketSell function can be updated to call rubiconMarket.sellAllAmount(ERC20(_asset), _payAmount, ERC20(_quote), _minFill.add(_fee)) instead of rubiconMarket.sellAllAmount(ERC20(_asset), _payAmount, ERC20(_quote), _minFill).

HickupHH3 (judge) commented:

It’s unclear to me whether min_fill_amt should be inclusive or exclusive of fees because the sellAllAmount() function itself is buggy with regards to fee accounting: the fill_amt fails to account for fees because the offer isn’t entirely filled because of fee inclusivity, so it’s an inflated value.

The fee is also charged on the pay_amt, not sure if incrementing it in the min_fill_amt entirely mitigates the issue.


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 the minimum fill amount passed to sellAllAmount excludes the fee, while the fill amount it is compared against includes the fee, so the comparison is inconsistent.

Impact

The slippage control is ineffective, so a trade could execute at a worse price than the user's minimum, though the judge noted uncertainty about whether the proposed fix fully mitigates the issue.

What the attacker needed

A leveraged position exists; user calls closePosition

The fix

The Position._marketSell function should be updated to pass _minFill.add(_fee) to sellAllAmount instead of _minFill.

How it was found

  1. Update Position._marketSell to divide the fee by 100_000 for the proof of concept.
  2. Update RubiconMarket.sellAllAmount to log min_fill_amount, the fill_amt including fee, and the fill_amt with fee deducted.
  3. Add a test in the Long positions describe block that calls buyAllAmountWithLeverage, creates an offer, then calls closePosition.
  4. Run the test and observe the logs showing fill_amt including fee is larger than min_fill_amount, and fill_amt with fee deducted equals min_fill_amount.

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 sell something on a trading platform, you can set a minimum amount you are willing to receive. Here, the platform checks your minimum against a number that already has a fee added, so the check almost always passes even if you actually receive less than you wanted. This means you could get a worse deal than you asked for.

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.

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

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.