Skip to content
Business logic Audit finding Advanced

The sorting logic is not strict enough

The auction finalisation sorted bids by a rounded price ratio, so two bids with slightly different true ratios could be treated as equal. The seller could then be forced to accept a lower total quote amount than a better bid would have provided.

hansfriese Follow

Originally disclosed on Code4rena

Submitted by hansfriese

When the seller finalizes his auction, all bids are sorted according to the quotePerBase and it’s calculated using the FixedPointMathLib.mulDivDown().

And the earliest bid will be used first for the same quotePerBase but this ratio is not strict enough so that the worse bid might be filled than the better one.

As a result, the seller might receive fewer quote token than he wants.

Proof of Concept

This is the test to show the scenario.

    function testAuditWrongSorting() public {
        // this test will show that it is possible the seller can not claim the best bid because of the inaccurate comparison in finalization
        uint128 K = 1<<64;
        baseToSell = K + 2;
        uint256 aid = seller.createAuction(
            baseToSell, reserveQuotePerBase, minimumBidQuote, startTime, endTime, unlockTime, unlockEnd, cliffPercent
        );

        bidder1.setAuctionId(aid);
        bidder1.bidOnAuctionWithSalt(K+1, K, "Worse bidder");
        bidder2.setAuctionId(aid);
        bidder2.bidOnAuctionWithSalt(K+2, K+1, "Better bidder"); // This is the better bid because (K+1)/(K+2) > K/(K+1)

        vm.warp(endTime);

        uint256[] memory bidIndices = new uint[](2);
        bidIndices[0] = 1; // the seller is smart enough to choose the correct order to (1, 0)
        bidIndices[1] = 0;

        vm.expectRevert(ISizeSealed.InvalidSorting.selector);
        seller.finalize(bidIndices, K+2, K+1); // this reverts because of #273

        // next the seller is forced to call the finalize with parameter K+1, K preferring the first bidder
        bidIndices[0] = 0;
        bidIndices[1] = 1;
        seller.finalize(bidIndices, K+1, K);

        // at this point the seller gets K quote tokens while he could get K+1 quote tokens with the better bidder
        assertEq(quoteToken.balanceOf(address(seller)), K);
    }

This is the output of the test.

    Running 1 test for src/test/SizeSealed.t.sol:SizeSealedTest
    [PASS] testAuditWrongSorting() (gas: 984991)
    Test result: ok. 1 passed; 0 failed; finished in 7.22ms

When it calculates the quotePerBase, they are same each other with (base, quote) = (K+1, K) and (K+2, K+1) when K = 1<<64.

So the seller can receive K+1 of the quote token but he got K.

I think K is realistic enough with the 18 decimals token because K is around 18 * 1e18.

Tools Used

Foundry

Recommended Mitigation Steps

As we can see from the test, it’s not strict enough to compare bidders using quotePerBase.

We can compare them by multiplying them like below.

$\frac {quote1}{base1} >= \frac{quote2}{base2} <=> quote1 * base2 >= quote2 * base1$

So we can add 2 elements to FinalizeData struct and modify this comparison like below.

    struct FinalizeData {
        uint256 reserveQuotePerBase;
        uint128 totalBaseAmount;
        uint128 filledBase;
        uint256 previousQuotePerBase;
        uint256 previousIndex;
        uint128 previousQuote; //++++++++++++
        uint128 previousBase; //+++++++++++
    }
    uint256 quotePerBase = FixedPointMathLib.mulDivDown(b.quoteAmount, type(uint128).max, baseAmount);
    if (quotePerBase >= data.previousQuotePerBase) {
        // If last bid was the same price, make sure we filled the earliest bid first
        if (quotePerBase == data.previousQuotePerBase) {
            uint256 currentMult = uint256(b.quoteAmount) * data.previousBase; //mult for current bid
            uint256 previousMult = uint256(data.previousQuote) * baseAmount; //mult for the previous bid

            if (currentMult > previousMult) { // current bid is better
                revert InvalidSorting();
            }

            if (currentMult == previousMult && data.previousIndex > bidIndex) revert InvalidSorting();
        } else {
            revert InvalidSorting();
        }
    }

    ...

    data.previousBase = baseAmount;
    data.previousQuote = b.quoteAmount;

0xean (judge) commented:

hmmm… I think the summary is loss of precision leads to small difference in sorting. Will leave open for sponsor review, but may be QA without showing a larger impact

RagePit (SIZE) confirmed and commented:

very nice find, although its only a small loss in precision the possibility of unfair sorting should be addressed

Trust (warden) commented:

With 1e18 points of precision, the difference between the theoretically correct calculation and the actual calculation is basically non existent. Therefore, impact is purely theoretical, as a competitive bidder could by the same logic over-bid by a tiny amount in the corrected calculation as well. Also, it is worth remembering that quote1 & quote2 are unknown until revealed, when it’s too late to over-bid.

hansfriese (warden) commented:

The definition of a better bid is the seller can earn more quote tokens (even if it’s 1 wei) by using the bidder. As we can see from the test, the seller can receive more amount of quote tokens if he uses the worse bidder. It means the sorting method using 1e18 is not good enough. If we implement the suggested comparison method(quote1 * base2 > quote2 * base1), it’s impossible to receive more funds by using the worse bidder because the comparison is strict. This issue has no relation to the over-bid and just shows the incorrect sorting logic.

Trust (warden) commented:

Yeah Hans you are very much correct in that sorting logic can theoretically be incorrect. I’m talking about the impact, not the root cause. Don’t you agree that the difference in calculation and the fact quote is unknown makes impact completely nullified?

Regardless it’s a well a spotted sneaky bug.

hansfriese (warden) commented:

I think we can’t say it’s 100% impossible to have the above situation although the bidders place a bid without knowing others.

It says about the Med risk like below in the document.

2 - Med: Assets not at direct risk, but the function of the protocol or its availability could be impacted, or leak value with a hypothetical attack path with stated assumptions, but external requirements.

I think my test case would be a possible assumption.

I feel I am defending my issue too much. I won’t reply anymore and will follow the judge’s decision.

Thanks for your feedback.

0xean (judge) commented:

Thanks for the comments and fact based discussion which is always welcomed, going to move forward with a M here.


The original report as published on Code4rena, by hansfriese. 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 sorting compared rounded quote-per-base values instead of cross-multiplying the raw quote and base amounts, so bids with different true ratios could compare as equal.

Impact

The seller could receive a slightly smaller amount of quote tokens than the best bid would have paid; the loss is small and depends on specific bid values.

What the attacker needed

Two bids with nearly equal price ratios; auction reaches finalisation

The fix

The comparison should cross-multiply the raw quote and base amounts (quote1 * base2 vs quote2 * base1) instead of comparing rounded ratios.

How it was found

  1. Create an auction with a base amount slightly above a power of two.
  2. Place a worse bid and a better bid whose rounded ratios are equal.
  3. Advance time to the auction end.
  4. Try to finalise with the better bid first; it reverts with InvalidSorting.
  5. Finalise with the worse bid first; the seller receives the lower quote 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.

In an auction, bids are ranked by price. Here the price was calculated with rounding, so two bids that were actually slightly different looked identical. The seller could end up with less money than if the better bid had been chosen.

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 hansfriese

View all

65 more disclosed reports, best first.

More from Size

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.