Skip to content
Business logic Audit finding Intermediate

Users may incur an unexpected fragmentation fee in the compensate() call

The compensate() function lacks a minimum-amount parameter, so a borrower may pay an unexpected fragmentation fee if another transaction changes the credit position before their call executes. A malicious user could front-run to cause this fee.

mt030d Follow with pkqs90

Originally disclosed on Code4rena

Submitted by mt030d, also found by pkqs90

https://github.com/code-423n4/2024-06-size/blob/8850e25fb088898e9cf86f9be1c401ad155bea86/src/libraries/actions/Compensate.sol#L116 https://github.com/code-423n4/2024-06-size/blob/8850e25fb088898e9cf86f9be1c401ad155bea86/src/libraries/actions/Compensate.sol#L136 https://github.com/code-423n4/2024-06-size/blob/8850e25fb088898e9cf86f9be1c401ad155bea86/src/libraries/actions/Compensate.sol#L146-L155

Impact

The CompensateParams struct lacks a field indicating the minimum amount the user is willing to compensate in the compensate() call. Consequently, users might pay an unexpected fragmentation fee during the compensate() call.

In scenarios where a borrower has a credit position that can be used to compensate the debt (creditPositionToCompensateId), they could search the market for a credit position (creditPositionWithDebtToRepayId) that relates to the debt and has the same credit amount as creditPositionToCompensateId. This way, in the compensate() call, the borrower would not fragment the creditPositionToCompensateId and avoid paying the fragmentation fee.

However, unexpectedly to the borrower, they might still pay the fragmentation fee if the compensate() transaction is executed after a buyCreditMarket() or sellCreditMarket() transaction that decreases the credit in creditPositionWithDebtToRepayId.

            uint256 amountToCompensate = Math.min(params.amount, creditPositionWithDebtToRepay.credit);
            uint256 exiterCreditRemaining = creditPositionToCompensate.credit - amountToCompensate;
            if (exiterCreditRemaining > 0) {
                // charge the fragmentation fee in collateral tokens, capped by the user balance
                uint256 fragmentationFeeInCollateral = Math.min(
                    state.debtTokenAmountToCollateralTokenAmount(state.feeConfig.fragmentationFee),
                    state.data.collateralToken.balanceOf(msg.sender)
                );
                state.data.collateralToken.transferFrom(
                    msg.sender, state.feeConfig.feeRecipient, fragmentationFeeInCollateral
                );
            }

In this case, the amountToCompensate will be less than the credit in creditPositionToCompensateId, and the user will have to pay an unforeseen fragmentation fee.

This situation can occur in normal user flows. Moreover, a malicious user could exploit this vulnerability and front-running a borrower’s compensate() transaction to cause the borrower to pay an unforeseen fragmentation fee.

Proof of Concept

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import {NonTransferrableToken} from "@src/token/NonTransferrableToken.sol";
import {CREDIT_POSITION_ID_START} from "@src/libraries/LoanLibrary.sol";
import {DataView} from "@src/SizeView.sol";
import {BaseTest} from "@test/BaseTest.sol";
import {console} from "forge-std/console.sol";

contract PoC is BaseTest {
    NonTransferrableToken collateralToken;

    function setUp() public override {
        super.setUp();
        _labels();

        DataView memory dataView = size.data();
        collateralToken = dataView.collateralToken;
        vm.label(address(collateralToken), "szWETH");

        _deposit(alice, weth, 100e18);
        _deposit(alice, usdc, 100e6);
        _deposit(bob, weth, 100e18);
        _deposit(bob, usdc, 100e6);
        _deposit(candy, weth, 100e18);
        _deposit(candy, usdc, 100e6);
        _deposit(james, weth, 100e18);
        _deposit(james, usdc, 100e6);
    }

    function test_it() public {

        _sellCreditLimit(alice, 0.03e18, 365 days);
        _buyCreditMarket(bob, alice, 100e6, 365 days, false);

        (, uint256 creditPositionCount) = size.getPositionsCount();
        uint256 creditPositionWithDebtToRepayId = CREDIT_POSITION_ID_START + creditPositionCount - 1;

        _sellCreditLimit(candy, 0.04e18, 365 days);
        _buyCreditMarket(alice, candy, 100e6, 365 days, false);
        (, creditPositionCount) = size.getPositionsCount();
        uint256 creditPositionToCompensateId = CREDIT_POSITION_ID_START + creditPositionCount - 1;

        uint256 snapshot = vm.snapshot();
        {
            uint256 beforeBalance = collateralToken.balanceOf(alice);
            _compensate(alice, creditPositionWithDebtToRepayId, creditPositionToCompensateId);
            uint256 afterBalance = collateralToken.balanceOf(alice);
            console.log("Scenario 1: borrower's expected compensate call");
            console.log("  fragmentation fee: %s", beforeBalance - afterBalance);
        }

        vm.revertTo(snapshot);
        _sellCreditLimit(bob, 0.04e18, 365 days);
        _buyCreditMarket(james, creditPositionWithDebtToRepayId, 50e6, false);
        {
            uint256 beforeBalance = collateralToken.balanceOf(alice);
            _compensate(alice, creditPositionWithDebtToRepayId, creditPositionToCompensateId);
            uint256 afterBalance = collateralToken.balanceOf(alice);
            console.log("Scenario 2: unexpected - a buyCreditMarket call executed before the compensate call");
            console.log("  fragmentation fee: %s", beforeBalance - afterBalance);
        }
    }
}

Run the above code with command forge test --mc PoC -vv, the result is as follows:

    Logs:
      Scenario 1: borrower's expected compensate call
        fragmentation fee: 0
      Scenario 2: unexpected - a buyCreditMarket call executed before the compensate call
        fragmentation fee: 3739715781600599

As show by the PoC, by the time the compensate transaction is executed in scenario 2, the credit in creditPositionWithDebtToRepayId has decreased due to an earlier buyCreditMaket transaction. As a result, the borrower pays an unforeseen fragmentation fee.

Tools Used

Foundry

Recommended Mitigation Steps

Allow the user to input a minAmount parameter in the compensate() function to specify the minimum amount they are willing to use. Then, handle this parameter within the compensate() function.

aviggiano (Size) acknowledged and commented:

Additional feedback from the team:

I think this is technically valid since, although frontrunning can happen, we can implement measures in the protocol to prevent users from being unexpectedly charged fees. For example, setting slippage protection. compensate could have a parameter allowing the user to specify “revert if a fee is charged”.

Yes, it is another instance of having a proper Anti-MEV system because the same “issue” is true on the other side, meaning somebody trying to buy a credit that gets compensated entirely before his buyCreditMarket() can be executed but on buy and sell we already Anti-MEV params. That’s kind of minor since no attack that benefits anybody, but the protocol, can be run here so up to you.

I think the potential issue of users paying for fees unexpectedly is not as important as the UX problem of operations failing because of the order they are applied to the orderbook, as we are aware. So adding a new parameter to the function doesn’t hurt but doesn’t solve the problem either.

hansfriese (judge) commented:

Will keep as Medium since it might occur during normal interactions.


The original report as published on Code4rena, by mt030d. 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 compensate() function does not allow the user to specify a minimum amount or a condition to revert if a fragmentation fee is charged, so the fee can be triggered by changes to the credit position before execution.

Impact

Users may pay an unexpected fragmentation fee, and a malicious user could front-run a borrower's compensate() transaction to cause this fee.

What the attacker needed

Borrower has a credit position to compensate; another transaction changes the debt credit position; attacker can front-run the compensate() call

The fix

The compensate() function should be modified to accept a minimum amount parameter, allowing the user to specify the minimum compensation amount and revert if a fee would be charged.

How it was found

  1. Alice has a credit position to compensate and finds a matching debt credit position with the same credit amount.
  2. Before Alice's compensate() call, Bob executes a buyCreditMarket() that reduces the credit in the debt credit position.
  3. Alice's compensate() call then compensates less than the full credit of her position, leaving a remainder.
  4. Because a remainder exists, the contract charges a fragmentation fee in collateral tokens.

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 call compensate(), the system checks if the credit position you're compensating has more credit than the amount you're compensating. If it does, it charges a fragmentation fee. Because there's no way to say 'don't charge me more than X', someone else's transaction can change the credit amount first, causing you to pay this fee unexpectedly.

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 mt030d

View all

1 more disclosed report, 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.