What are liquidation logic bugs?

Liquidation logic bugs are errors in the code that decides when a loan can be liquidated, how much a liquidator repays and how much collateral they take. They let liquidators seize healthy positions, let unhealthy ones linger until the loss grows, or leave debt that no collateral covers on the books as if someone will repay it. Compute health one way everywhere, cap each liquidation by what the position holds, and write off what can't be covered.

Last updated . 6 minute read. By the QuillAudits Team.

What goes wrong in liquidation code?

  • Health computed differently in different places. Borrowing checks one price or rounding and liquidation checks another, so a position can be liquidatable the moment it opens, or never.
  • Interest not accrued first. A health check on debt that hasn't accrued for a week treats an unhealthy position as healthy.
  • Seizing more than the position holds. Repaid debt times one plus the bonus, divided by the price, can exceed an underwater position's collateral, and the call reverts or takes collateral that belongs to someone else.
  • A bonus that makes positions worse. Below a certain point each liquidation leaves the position less healthy than before, as the next section shows.
  • Liquidations that can't happen. A paused market, a token transfer that reverts, a callback the borrower controls, or a position too small to be worth the gas can all stop liquidators.
  • Bad debt that never shows. Debt with no collateral behind it stays on the books, and lenders who withdraw first are paid in full out of what the last ones are owed.
  • Wrong prices for a moment. Liquidating on a stale or manipulated price seizes healthy positions, which the page on oracle price manipulation covers for moved prices.

What does vulnerable code look like?

Vulnerable: no cap on what is seized, no close factor and no handling of bad debt (illustrative, not audited code) UncappedLiquidations.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

interface IOracle {
    function price() external view returns (uint256); // collateral in stablecoin, 18 decimals
}

contract UncappedLiquidations {
    IOracle public immutable oracle;
    uint256 public constant LIQ_THRESHOLD = 80; // percent of collateral value that may be borrowed
    uint256 public constant BONUS = 10; // percent extra collateral paid to the liquidator
    mapping(address => uint256) public collateral; // collateral tokens, 18 decimals
    mapping(address => uint256) public debt; // stablecoin, 18 decimals

    constructor(IOracle oracle_) {
        oracle = oracle_;
    }

    function isHealthy(address user) public view returns (bool) {
        return debt[user] * 100 <= collateral[user] * oracle.price() / 1e18 * LIQ_THRESHOLD;
    }

    function liquidate(address user, uint256 repayAmount) external {
        require(!isHealthy(user), "position is healthy");
        uint256 seize = repayAmount * (100 + BONUS) / 100 * 1e18 / oracle.price();
        debt[user] -= repayAmount;
        // When the collateral is worth less than the debt plus the bonus, repaying the
        // whole debt makes seize larger than what the user has, and this line reverts.
        // Liquidators have to guess a smaller amount, and when the collateral runs
        // out, the rest of the debt stays on the books with nothing behind it.
        collateral[user] -= seize;
        collateral[msg.sender] += seize;
        // ... pull `repayAmount` stablecoins from msg.sender
    }
}

Take a position with 100 collateral tokens and 80 of debt, with the collateral priced at 0.8. It is liquidatable. A liquidator who repays the whole 80 asks for 110 tokens, the user has 100, and the call reverts. A repayment of 40 works and takes 55 tokens, which leaves 45 tokens worth 36 against 40 of debt: the position is worse after the liquidation than before it. A Foundry test of this contract shows both.

When does a liquidation bonus make a position worse?

A liquidation repays some debt and takes collateral worth that amount times one plus the bonus. It improves the ratio of collateral to debt only while the collateral is worth more than the debt times one plus the bonus. Below that line, every liquidation leaves the position less healthy than it was, and repeated liquidations drain the collateral to zero with debt left over.

With a liquidation threshold of 80% and a 10% bonus, a position that has just crossed the threshold holds collateral worth 1.25 times its debt, above the 1.1 line, so liquidating it helps. A sharp drop that skips past the threshold can leave positions below 1.1 before anyone acts, which is why the fixed contract caps what is seized and writes off the rest.

How do you fix it?

Fixed: a close factor, a cap on what is seized, and bad debt written off (illustrative, not audited code) CappedLiquidations.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

interface IOracle {
    function price() external view returns (uint256); // collateral in stablecoin, 18 decimals
}

contract CappedLiquidations {
    IOracle public immutable oracle;
    uint256 public constant LIQ_THRESHOLD = 80;
    uint256 public constant BONUS = 10;
    uint256 public constant CLOSE_FACTOR = 50; // most of the debt one call may repay, in percent
    mapping(address => uint256) public collateral;
    mapping(address => uint256) public debt;
    uint256 public badDebt; // debt no collateral covers, kept visible for lenders

    constructor(IOracle oracle_) {
        oracle = oracle_;
    }

    // Borrow, withdraw and liquidate must all use this one function, with the same price.
    function isHealthy(address user) public view returns (bool) {
        return debt[user] * 100 <= collateral[user] * oracle.price() / 1e18 * LIQ_THRESHOLD;
    }

    function liquidate(address user, uint256 repayAmount) external {
        require(!isHealthy(user), "position is healthy");
        uint256 p = oracle.price();
        uint256 maxRepay = debt[user] * CLOSE_FACTOR / 100;
        if (repayAmount > maxRepay) repayAmount = maxRepay;
        uint256 seize = repayAmount * (100 + BONUS) * 1e18 / (100 * p);
        if (seize > collateral[user]) {
            // Underwater: the liquidator takes everything and repays only what it is worth.
            seize = collateral[user];
            repayAmount = seize * p * 100 / ((100 + BONUS) * 1e18);
        }
        require(repayAmount > 0 && seize > 0, "nothing to liquidate");
        debt[user] -= repayAmount;
        collateral[user] -= seize;
        collateral[msg.sender] += seize;
        if (collateral[user] == 0 && debt[user] > 0) {
            // Write off what is left instead of leaving a loan nobody will ever repay.
            badDebt += debt[user];
            debt[user] = 0;
        }
        // ... pull `repayAmount` stablecoins from msg.sender
    }
}
  • Cap what is seized. When the repayment plus the bonus is worth more than the collateral, the liquidator takes all of it and repays only what it is worth, so the call never reverts on an underwater position.
  • Limit each call with a close factor. Repaying at most half the debt per call spreads a large liquidation over several liquidators and several prices.
  • Write off bad debt. When the collateral is gone and debt remains, the fixed contract moves it to badDebt, where the protocol can cover it from reserves or share it among lenders, instead of carrying a loan nobody will repay.
  • Use one health function. isHealthy is the only place health is computed, and borrowing, withdrawing and liquidating must all call it with the same price.
  • Round against the liquidator. The example keeps its math short, but production code should round the repaid amount up and the seized amount down, so rounding never pays more than the bonus.
  • Accrue interest before every check, which the example leaves out, and keep liquidations open when the protocol pauses anything else.

In the same test, the fixed contract liquidated the position at a price of 0.5 in two calls. The first repaid 40 and took 88 tokens. The second found 12 tokens left, took them, and wrote off about 34.5 of debt.

How has liquidation logic been exploited?

Protocol Euler Finance
Date 13 March 2023
Chain Ethereum
Loss about $197M
What happened Euler's eIP-14 upgrade added donateToReserves, which let an account hand collateral to the protocol's reserves without the health check a withdrawal runs (Omniscia). The attacker borrowed its way into a large position, donated enough collateral to leave that account with bad debt, then liquidated it from a second contract at Euler's maximum discount of 20% and kept the difference. Bloomberg reported a loss of about $197M on the day, and Euler's own account of the recovery gives the same figure.
Sources Euler Labs, Omniscia, Bloomberg

Two liquidation lessons come out of it. Every function that can lower an account's health needs the same health check as a withdrawal, or anyone can manufacture the deeply insolvent position that a liquidation discount pays out on. And once a position has no collateral buffer left, the discount comes out of what lenders are owed, which is why the cap and the write-off in the fixed contract matter.

What should a reviewer check?

  • Is health computed by one function that borrowing, withdrawing, moving collateral and liquidating all use?
  • Is interest accrued before every health check?
  • Can the seized amount ever exceed the position's collateral, and what happens then?
  • Given the threshold and the bonus, does a liquidation improve the position at every health level the protocol can reach?
  • What happens to debt left after all collateral is seized: written off, covered from reserves, or left on the books?
  • Can anything block a liquidation: a pause, a reverting token transfer, a callback the borrower controls, a minimum size?
  • Are small positions still worth liquidating after gas, and if not, is there a minimum borrow size?
  • Which price does liquidation use, how fresh must it be, and is there a grace period after an outage?
  • Do fuzz tests drop the price sharply and check that liquidating an unhealthy position never reverts and that bad debt is recorded when collateral runs out?

How does QuillShield check for liquidation logic bugs?

Liquidation bugs come from parts that disagree: the health check in one contract, the price adapter in another, the interest model in a third. Put the markets, the oracle adapters, the interest rate model and the liquidation logic in scope together. QuillShield runs a full audit of a Solidity codebase in a Foundry project. It builds a security graph of the code and lists the invariants the code must keep.

Before an audit you can add context such as the whitepaper, trust assumptions, privileged roles and previous audit reports, so include your risk parameters: thresholds, bonuses, close factors and who can change them. A separate reviewer agent tries to disprove every finding before you see it, and each finding that holds up comes with the exact lines, the impact, a recommended fix and, on full audits, a proof of concept.

It then checks every pull request on GitHub or GitLab.com against that graph. A new collateral type or a changed bonus is a small diff that changes the math above. Run a full audit. New accounts get $50 in credit, good for up to half of an order. For a launch you can also request a manual audit from QuillAudits.

FAQ

What is a close factor?

The largest share of a position's debt that one liquidation call can repay. It stops one liquidator from taking a whole position at one price and spreads large liquidations over time.

Why do liquidations fail during crashes?

Positions fall past the point where liquidating them pays or even helps, prices move faster than keepers act, and code that reverts when the seized amount exceeds the collateral stops exactly the liquidations that matter most.

What is bad debt in a lending protocol?

Debt with no collateral left behind it. If the protocol doesn't write it off or cover it, lenders who withdraw first are paid in full and the last ones can't withdraw.

Should borrowers be able to liquidate themselves?

It depends on where the bonus comes from. A bonus paid out of the borrower's own healthy collateral gains them nothing, but on an insolvent position the discount is paid by lenders. In the Euler exploit, the attacker liquidated its own insolvent account from a second contract at the maximum discount.

Sources

QuillShield is building the security layer between AI and money, so you can keep shipping between audits.

Sign-up is free, and new accounts get $50 in credit, good for up to half of an order.

  1. 1Sign up and import a repo
  2. 2See the exact price before anything is charged
  3. 3Approve it, and the audit starts