Skip to content
Business logic Audit finding Intermediate

It is nearly impossble for Liquidators to use liquidatePosition() to fully pay off a non bad-debt position

The liquidatePosition function requires the liquidator's repayAmount multiplied by the liquidation penalty to exactly equal the position's total debt, which increases every second. Because a transaction cannot be timed to the exact second, liquidators cannot fully repay a non-bad-debt position, leaving residual debt that may become bad debt.

pkqs90 Follow with Evo

Originally disclosed on Code4rena

Submitted by pkqs90, also found by Evo

First, we need to know how liquidation of a non bad-debt position works. The liquidator passes the amount repayAmount, pays a penalty, and buys the position collateral at a discount price.

The issue here is after deducting the penalty, the repayAmount must be exactly equal to the amount of debt at the current second in order to completely pay off the debt. Aligning with the code, this means the repayAmount * liquidationPenalty must be equal to calcTotalDebt(debtData). If it is larger, the liquidation would fail due to integer underflow in calcDecrease().

However, since the result of calcTotalDebt(debtData) is increasing as time passes, and the transaction cannot pinpoint which second it is executed, the liquidator cannot know the amount of calcTotalDebt(debtData).

This means it is nearly impossible for liquidators to fully pay off the non bad-debt position, which is unexpected.

    function liquidatePosition(address owner, uint256 repayAmount) external whenNotPaused {
        // validate params
        if (owner == address(0) || repayAmount == 0) revert CDPVault__liquidatePosition_invalidParameters();

        // load configs
        VaultConfig memory config = vaultConfig;
        LiquidationConfig memory liqConfig_ = liquidationConfig;

        // load liquidated position
        Position memory position = positions[owner];
        DebtData memory debtData = _calcDebt(position);

        // load price and calculate discounted price
        uint256 spotPrice_ = spotPrice();
        uint256 discountedPrice = wmul(spotPrice_, liqConfig_.liquidationDiscount);
        if (spotPrice_ == 0) revert CDPVault__liquidatePosition_invalidSpotPrice();
        // Ensure that there's no bad debt
        if (calcTotalDebt(debtData) > wmul(position.collateral, spotPrice_)) revert CDPVault__BadDebt();

        // compute collateral to take, debt to repay and penalty to pay
        uint256 takeCollateral = wdiv(repayAmount, discountedPrice);
        uint256 deltaDebt = wmul(repayAmount, liqConfig_.liquidationPenalty);
        uint256 penalty = wmul(repayAmount, WAD - liqConfig_.liquidationPenalty);
        if (takeCollateral > position.collateral) revert CDPVault__tooHighRepayAmount();

        // verify that the position is indeed unsafe
        if (_isCollateralized(calcTotalDebt(debtData), wmul(position.collateral, spotPrice_), config.liquidationRatio))
            revert CDPVault__liquidatePosition_notUnsafe();

        // transfer the repay amount from the liquidator to the vault
        poolUnderlying.safeTransferFrom(msg.sender, address(pool), repayAmount - penalty);

        uint256 newDebt;
        uint256 profit;
        uint256 maxRepayment = calcTotalDebt(debtData);
        uint256 newCumulativeIndex;
>       if (deltaDebt == maxRepayment) {
            newDebt = 0;
            newCumulativeIndex = debtData.cumulativeIndexNow;
            profit = debtData.accruedInterest;
            position.cumulativeQuotaInterest = 0;
        } else {
            // @auditnote: If deltaDebt > maxRepayment, the following code would underflow and revert.
>           (newDebt, newCumulativeIndex, profit, position.cumulativeQuotaInterest) = calcDecrease(
                deltaDebt, // delta debt
                debtData.debt,
                debtData.cumulativeIndexNow, // current cumulative base interest index in Ray
                debtData.cumulativeIndexLastUpdate,
                debtData.cumulativeQuotaInterest
            );
        }
        position.cumulativeQuotaIndexLU = debtData.cumulativeQuotaIndexNow;
        // update liquidated position
        position = _modifyPosition(owner, position, newDebt, newCumulativeIndex, -toInt256(takeCollateral), totalDebt);

        pool.repayCreditAccount(debtData.debt - newDebt, profit, 0); // U:[CM-11]
        // transfer the collateral amount from the vault to the liquidator
        token.safeTransfer(msg.sender, takeCollateral);

        // Mint the penalty from the vault to the treasury
        poolUnderlying.safeTransferFrom(msg.sender, address(pool), penalty);
        IPoolV3Loop(address(pool)).mintProfit(penalty);

        if (debtData.debt - newDebt != 0) {
            IPoolV3(pool).updateQuotaRevenue(_calcQuotaRevenueChange(-int(debtData.debt - newDebt))); // U:[PQK-15]
        }
    }

Recommended Mitigation Steps

Add a check where if deltaDebt > maxRepayment, set the deltaDebt to maxRepayment, and reverse calculate the repayAmount by maxRepayment / liquidationPenalty.

0xtj24 (LoopFi) disputed and commented:

Liquidator can estimate the exact debt with:

  /// @notice Returns the total debt of a position
    /// @param position Address of the position
    /// @return totalDebt Total debt of the position [wad]
    function virtualDebt(address position) external view returns (uint256) {
        return calcTotalDebt(_calcDebt(positions[position]));
    }

and thus repaying the exact position’s debt.

Koolex (judge) increased severity to High and commented:

However, since the result of calcTotalDebt(debtData) is increasing as time passes, and the transaction cannot pinpoint which second it is executed, the liquidator cannot know the amount of calcTotalDebt(debtData).

While Liquidator can estimate the exact debt with virtualDebt, there is a time window between the transaction sent and processed, during this, the debt could increase. Over time, bad debt will accumulate.

0xAlix2 (warden) commented:

While Liquidator can estimate the exact debt with virtualDebt, there is a time window between the transaction sent and processed, during this, the debt could increase. Over time, bad debt will accumulate.

@Koolex - I agree with this; however, this could be considered a user error. Since a user could simply call liquidatePosition(position, virtualDebt(position)), the mentioned scenario won’t happen, and everything will work as expected.

Hence, I believe this is a valid low.

pkqs90 (warden) commented:

@0xAlix2 - The point is due to the nature of blockchain, there is a time window between initiation of a transaction and execution of transaction. The initiation of a transaction most likely happen through a frontend request, and not by some blockchain code.

Koolex (judge) commented:

Thank you for the feedback. No mitigation on the front-end could mitigate this. Any suggested mitigation can protect is on-chain. Stays as-is.


The original report as published on Code4rena, by pkqs90. 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 contract requires an exact equality between the penalty-adjusted repayment and the continuously increasing total debt, with no tolerance or clamping for small overpayments.

Impact

Liquidators cannot fully repay non-bad-debt positions, so residual debt remains and may accumulate into bad debt over time.

What the attacker needed

Position is unsafe but not bad debt; liquidator sends a transaction

The fix

The code should clamp deltaDebt to maxRepayment when it exceeds it and recalculate repayAmount as maxRepayment divided by the liquidation penalty.

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 a lending system, a liquidator repays a borrower's debt to close an unsafe position. This code only clears the debt if the repayment amount exactly matches the debt at the moment the transaction runs, but the debt grows every second. Since the liquidator cannot predict the exact second, the repayment is almost always slightly off, so the position is never fully closed.

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 pkqs90

View all

25 more disclosed reports, best first.

More from LoopFi

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.