Skip to content
Business logic Audit finding Intermediate

In CDPVault::liquidatePositionBadDebt() , the calculation of loss is incorrect

The bad-debt liquidation function calculates the protocol's loss as total debt (principal plus accrued interest) minus the amount repaid by the liquidator, rather than principal minus repayment. This overstates the loss, causing the protocol to burn more treasury shares than necessary, which can lead to insufficient shares and incorrect accounting.

lian886 Follow with lanrebayode77, crypticdefense and 2 others

Originally disclosed on Code4rena

Submitted by lian886, also found by lanrebayode77, crypticdefense, 0xpiken, and hash

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/CDPVault.sol#L579

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/CDPVault.sol#L735

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/CDPVault.sol#L509

Impact

The incorrect calculation affects the protocol’s profit assessment, resulting in potential losses for users, particularly in the interest portion.

Proof of Concept

    function liquidatePositionBadDebt(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);
        uint256 spotPrice_ = spotPrice();
        if (spotPrice_ == 0) revert CDPVault__liquidatePosition_invalidSpotPrice();
        // verify that the position is indeed unsafe
        if (_isCollateralized(calcTotalDebt(debtData), wmul(position.collateral, spotPrice_), config.liquidationRatio))
            revert CDPVault__liquidatePosition_notUnsafe();

        // load price and calculate discounted price
        uint256 discountedPrice = wmul(spotPrice_, liqConfig_.liquidationDiscount);
        // Ensure that the debt is greater than the collateral at discounted price
        if (calcTotalDebt(debtData) <= wmul(position.collateral, discountedPrice)) revert CDPVault__noBadDebt();
        // compute collateral to take, debt to repay
        uint256 takeCollateral = wdiv(repayAmount, discountedPrice);
        if (takeCollateral < position.collateral) revert CDPVault__repayAmountNotEnough();

        // account for bad debt
        takeCollateral = position.collateral;
        repayAmount = wmul(takeCollateral, discountedPrice);
    @>>    uint256 loss = calcTotalDebt(debtData) - repayAmount;

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

        position.cumulativeQuotaInterest = 0;
        position.cumulativeQuotaIndexLU = debtData.cumulativeQuotaIndexNow;
        // update liquidated position
        position = _modifyPosition(
            owner,
            position,
            0,
            debtData.cumulativeIndexNow,
            -toInt256(takeCollateral),
            totalDebt
        );

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

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

In the liquidatePositionBadDebt function, the calculation of the loss is done by subtracting the repaid portion of the debt from the total debt.

    function calcTotalDebt(DebtData memory debtData) internal pure returns (uint256) {
@>>        return debtData.debt + debtData.accruedInterest; //+ debtData.accruedFees;
    }

Through the calcTotalDebt() function, we know that the total debt includes both the principal debt and the interest accrued on the debt. In this CDPVault, the interest accrued on the debt is treated as profit. For example, in the liquidatePosition function, profit is calculated as debtData.accruedInterest, and this profit is treated as interest revenue in other functions as well.

   function liquidatePosition(address owner, uint256 repayAmount) external whenNotPaused {
        //skip ........
        uint256 newDebt;
        uint256 profit;
        uint256 maxRepayment = calcTotalDebt(debtData);
        uint256 newCumulativeIndex;
        if (deltaDebt == maxRepayment) {
            newDebt = 0;
            newCumulativeIndex = debtData.cumulativeIndexNow;
@>>            profit = debtData.accruedInterest;
            position.cumulativeQuotaInterest = 0;
        }

        //skip ........
    }

Therefore, the loss should only account for the loss of the principal amount. In the liquidatePositionBadDebt function, if repayAmount > debtData.debt, there would actually be a small profit (repayAmount - debtData.debt) instead of a loss. The calculation for the loss should be debtData.debt - repayAmount to correctly reflect the loss of the principal portion.

Recommended Mitigation Steps

Modify the relevant formula for calculating the loss.

Assessed type

Math

0xtj24 (LoopFi) confirmed

Koolex (judge) decreased severity to Medium and commented:

Looks valid. However, this is based on the assumption that loss of revenue is not a loss. Requesting from the Warden to provide further input to support this assumption. only in PJQA please.

crypticdefense (warden) commented:

@Koolex, I would like to provide further info as requested (my issue #394 is a duplicate).

The assumption that the accruedInterest is not a loss is based off how the protocol itself will burn treasury shares to make up for the loss when there is bad debt. Think about it like this, the accruedInterest is the profit the protocol will receive from lending, and if there is bad debt accumulated, that means the accruedInterest has not been paid.

Then, when someone liquidates the bad debt position, they can liquidate it for a discount. Since they are paying at a discount, the full debt cannot be repaid, so the protocol will proceed to cover the rest of the amount of debt by burning treasury shares. The loss calculation is as follows: position debt + accruedInterest - repayAmount, where repayAmount is the amount paid by the liquidator. However, the protocol never lost accruedInterest amount, that is just potential profit from lending that was never received.

Even if there exists a case where some of the accruedInterest was paid by the borrower, that is still profit that the protocol is burning. It should only burn the amount of shares equivalent to the debt owed, because that represents the loss. Profit accumulated is not a loss.

So the protocol will proceed to burn loss amount of treasury shares. It is burning extra treasury shares here because it includes accruedInterest, causing a range of issues such as DoS due to insufficient shares and incorrect accounting.

Koolex (judge) commented:

Thank you for the additional clarification. The issue stays as-is.


The original report as published on Code4rena, by lian886. 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 loss calculation subtracts the repayment from total debt including accrued interest, instead of from principal debt only.

Impact

The protocol burns excess treasury shares, which could cause a denial of service if shares are insufficient and leads to incorrect accounting.

What the attacker needed

A position with bad debt; a liquidator repays the bad debt

The fix

The loss formula should be changed to subtract the repayment from the principal debt only, not from total debt including interest.

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 protocol, a borrower owes the original loan (principal) plus interest. When a loan goes bad, a liquidator pays part of what is owed at a discount, and the protocol writes off the rest as a loss. The code wrongly counts unpaid interest as part of that loss, even though interest was only potential profit, so the protocol destroys too many of its own shares to cover it.

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 lian886

View all

3 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.