How Liquidations Work in DeFi:
A Deep Dive

Author: Victor Yurov, Sergey Boogerwooger
Security researcher(s) at MixBytes
Introduction
Liquidation mechanisms are vital to the stability and solvency of decentralized finance (DeFi) protocols, especially in volatile market conditions. However, their complexity and sensitivity to various challenges—such as liquidity constraints, cascading liquidations, and cross-chain interactions—make them a critical area of focus for developers and auditors alike.

This article is divided into three parts:

  1. The first part, Understanding the Role of Liquidations in DeFi, examines the challenges protocols face, including market volatility, oracle reliability, and bad debt management.
  2. The second part, Examining Traditional and Modern Liquidation Architectures, explores traditional and modern liquidation architectures, highlighting both established approaches and innovative solutions like Curve's crvUSD and Fluid Vault.
  3. The third part, Real-World Vulnerabilities and Lessons Learned, examines both audit findings and real incidents to provide actionable insights for more secure and efficient liquidation mechanisms.

By understanding these aspects, we aim to shed light on the complexities of liquidations and how they shape the resilience of DeFi protocols.
Part 1: Understanding the Role of Liquidations in DeFi
Overview
This section explores the core challenges DeFi platforms face during liquidations. Auditors and developers who are not active traders must realize that market conditions can change abruptly due to various triggers. Recognizing these dynamics is crucial for understanding the environments in which the code being developed or audited may ultimately operate.
DeFi Security Challenges and Risks in Bear Markets
Market Liquidity

This meme highlights a common phenomenon in crypto markets: investors’ reluctance to buy during dips and their eagerness to jump in when prices are high. It reflects how market sentiment drives liquidity, with fewer participants during downturns and surging activity during bull runs. This behavior underscores the importance of understanding liquidity dynamics and sentiment cycles in crypto trading.

Insufficient liquidity occurs when the available capital in the market decreases due to factors such as declining investor confidence, mass asset withdrawals, or market-wide sell-offs. This reduction in liquidity leads to thinner order books and smaller liquidity pools, making it harder for trades to execute without significant price slippage.
As a result, price volatility increases, and the risk of cascading liquidations grows, particularly in DeFi protocols reliant on sufficient market depth to liquidate positions effectively. Additionally, lower liquidity exacerbates the impact of price manipulation and oracle inaccuracies, further destabilizing the ecosystem and potentially causing systemic failures or bad debt accumulation within the protocol.
Cascading Liquidations

This chart serves as a clear example of cascading liquidations in the crypto market, where a series of negative events triggers a sharp decline in prices. Initially, Tesla's announcement to stop BTC payments caused an initial sell-off, eroding confidence. This was followed by reports of regulatory crackdowns in China, further pressuring prices. As the price continued to fall, many leveraged positions fell below their collateralization thresholds, triggering automatic liquidations. This liquidation cascade amplified the downward momentum, causing prices to plummet even further in a short period. Such events highlight the vulnerability of highly leveraged markets and the systemic risks posed by rapid price drops.

Cascading liquidations occur when the forced sale of assets to cover under-collateralized positions triggers further price declines, leading to additional liquidations.
This process often starts during periods of high market volatility, where rapid price drops cause collateral values to fall below required thresholds. As DeFi protocols initiate liquidations to recover debt, the selling pressure exacerbates price declines, forcing more liquidations in a self-reinforcing loop. The consequences can be severe: liquidity pools may be drained, market slippage increases dramatically, and the protocol may accumulate bad debt if assets cannot be liquidated at sufficient value. This can destabilize not only the protocol in question but also the broader market, especially if multiple interconnected platforms are affected.
Oracle Reliance
Reliance on oracles introduces significant risks. Price manipulation is a primary concern, where attackers exploit low liquidity in DEXs or vulnerabilities in oracle mechanisms to distort prices, leading to improper collateral valuations and liquidations. Additionally, latency during network congestion can result in outdated price feeds, causing missed or erroneous liquidations. Dependence on a single oracle provider further increases systemic risk by creating a central point of failure. The consequences of these issues can include bad debt, protocol instability, and loss of user trust. To mitigate these risks, protocols use safeguards like time-weighted average prices (TWAP), multi-oracle redundancy, and real-time monitoring, ensuring greater resilience and reliability.
Bad Debts
Bad debt in DeFi becomes even more problematic in protocols that offer leveraged positions, where users borrow funds to amplify their exposure to assets. Leveraged trading increases the sensitivity of positions to price fluctuations, as even minor market movements can quickly render positions under-collateralized. In such systems, the speed and accuracy of liquidation processes are crucial, but delays in oracle updates or low liquidity can prevent timely liquidations, allowing debt to spiral. Furthermore, cascading liquidations are more likely in leveraged protocols due to the higher volume of liquidations triggered simultaneously in volatile conditions. This creates additional downward pressure on asset prices, accelerating the accumulation of bad debt. The higher risks in leveraged systems can destabilize not just the protocol but also interconnected platforms, especially in cross-collateralized ecosystems. To mitigate these risks, leveraged protocols often enforce stricter collateralization ratios, employ robust liquidation mechanisms, and maintain larger reserve funds to absorb unexpected losses.
Collateralization Ratios
Collateralization ratios in DeFi ensure loans are secured while balancing accessibility and risk. Higher ratios reduce the risk of under-collateralization but may deter borrowing due to high capital requirements, while lower ratios make borrowing easier but increase the likelihood of bad debt during market downturns. In volatile markets, overly optimistic ratios can lead to rapid under-collateralization and failed liquidations, especially in low-liquidity conditions. Leveraged and cross-chain protocols face heightened risks as price swings and systemic interdependencies amplify vulnerabilities. To address these challenges, many protocols use dynamic collateralization models, real-time oracle updates, and circuit breakers to adapt to market conditions, ensuring solvency and minimizing systemic risks.
High Volatility
Volatility is a defining feature of cryptocurrency markets and poses significant challenges to the security of DeFi protocols. Sharp price swings can lead to rapid changes in the value of collateral, increasing the likelihood of liquidations and, in extreme cases, causing cascading liquidations. High volatility also amplifies the risk of bad debt, particularly when liquidation mechanisms or oracles fail to respond promptly to market movements. Additionally, price manipulation becomes more feasible during volatile periods, as attackers exploit thin liquidity or delayed price updates to trigger undeserved liquidations or arbitrage opportunities. Volatility's impact extends to user behavior as well, driving panic withdrawals that can drain liquidity pools and destabilize protocols. To mitigate these risks, protocols implement measures such as conservative collateralization ratios, time-weighted average price (TWAP) oracles, and dynamic risk management frameworks that adapt to changing market conditions. These safeguards are essential for maintaining stability in the face of unpredictable market dynamics.
Gas Fee Surge and Delays in Liquidation Execution

This chart illustrates the average gas price on the Ethereum network over time, highlighting significant spikes in gas costs during periods of network congestion, such as 2017, 2020, and 2021. These surges often occur during high market activity or stress, like token launches, DeFi booms, or liquidation cascades, when transaction demand overwhelms available block space.

Delays in liquidation execution pose critical risks to the stability of DeFi protocols, especially during periods of high market volatility. When liquidations are not executed promptly, under-collateralized positions can deteriorate further as collateral values continue to drop, increasing the likelihood of bad debt. Such delays often stem from network congestion, where high gas fees and transaction bottlenecks slow down the processing of liquidation orders. Inadequate oracle updates or reliance on slow price feeds exacerbate the issue by providing outdated valuations, preventing liquidators from acting in time. The cascading effects of these delays can destabilize protocols by draining liquidity pools, amplifying systemic risks, and undermining user trust.
To address these challenges, DeFi platforms implement strategies such as prioritizing and incentivizing liquidation transactions, using faster oracle mechanisms, and introducing circuit breakers to pause liquidations during extreme conditions, ensuring the protocol's resilience even in adverse scenarios.
Conclusion of the part 1
The complexities of liquidations in DeFi cannot be overstated. High volatility, low liquidity, oracle dependencies, and execution delays can turn a well-understood environment into one that is turbulent and unpredictable. Bad debt can accumulate if liquidation mechanisms fail to adapt to rapid market changes, and leveraged positions add further vulnerabilities. Every component—from collateral ratios to oracle integrations—must be carefully tuned, resilient, and supported by robust risk management frameworks.

In the third part of this series, we will examine a real-world incident that encapsulates many of these challenges. By analyzing an actual event, we can better understand these interactions and how protocols, developers, and auditors can collaborate to enhance DeFi stability and security.
Part 2: Examining Traditional and Modern Liquidation Architectures
Overview
This part delves into the architectures of liquidation modules across various DeFi protocols. We'll discuss liquidations in different projects, their key ideas, architecture and advantages/disadvantages of different liquidation approaches in modern DeFi.
AAVE

AAVE uses a Health Factor (HF) formula to determine the collateral safety of a borrower's position. The HF is calculated as the ratio of the collateral value, adjusted by its liquidation threshold, to the borrowed value. If the HF falls below 1, the position becomes under-collateralized and eligible for liquidation. Liquidators are incentivized to participate by receiving a liquidation bonus, typically 5% to 10% of the liquidated collateral's value, depending on the asset (see this table for more details). The liquidation process is individual and partial, meaning that liquidators can repay up to 100% of the debt for a single position in exchange for the corresponding portion of collateral. This ensures that liquidations are targeted and do not require the full liquidation of a position, reducing the immediate market impact.
Advantages:
  1. Individual position liquidations target only users below the Health Factor threshold, ensuring fairness and isolating risk.
  2. Support for multiple collateral types allows users to supply a wide range of tokens, providing flexibility and accessibility.
  3. Liquidators can choose which token to repay and which collateral to claim, optimizing their profits and improving efficiency.
  4. Partial liquidation mechanisms help mitigate large market impacts by limiting the size of each liquidation.
  5. The modular and flexible approach adapts to a broad range of assets and changing market conditions.
Disadvantages:
  1. High gas costs per liquidation transaction make the process expensive, especially during network congestion. Liquidating smaller positions can be economically inefficient due to transaction costs outweighing potential rewards.
  2. Inefficient liquidation of certain positions may lead to the accumulation of bad debt if under-collateralized positions are not addressed promptly.
  3. Scalability and cost issues can arise in extreme market conditions, as price declines may outpace the liquidation process.
Gearbox
Gearbox, like AAVE, utilizes a Health Factor (HF) to monitor the collateralization of user positions, ensuring that borrowed funds remain adequately secured. However, Gearbox stands out by focusing on leveraged trading, enabling users to borrow assets to amplify their market exposure. The protocol uses HF to dynamically assess the safety of each position; if the HF falls below 1, the position becomes under-collateralized and is flagged for liquidation. Gearbox integrates multiple oracle solutions, including Chainlink and RedStone, to provide real-time and reliable price data for determining collateral and debt valuations. While Chainlink offers robust decentralization and secure on-chain updates, RedStone brings enhanced speed and cost-efficiency through its off-chain data storage model, where data is signed off-chain and submitted on-chain only when needed. This hybrid approach allows Gearbox to balance security, flexibility, and real-time accuracy, which is especially critical for managing leveraged positions.

The leverage offered by Gearbox increases the potential for higher returns but also significantly heightens the risk of bad debt. In volatile market conditions, leveraged positions can become under-collateralized rapidly if price updates from oracles are delayed or inaccurate. This can result in liquidations that fail to recover enough collateral to cover the debt, leaving the protocol with outstanding liabilities. Additionally, the increased sensitivity of leveraged positions to price movements magnifies the risk of cascading liquidations, particularly in low-liquidity markets. To mitigate these risks, Gearbox relies on strict risk parameters, real-time oracle updates from both Chainlink and RedStone, and active monitoring, but the inherent complexity of leveraged trading still presents challenges in ensuring long-term solvency and protocol stability.
crvUSD
Curve Finance Stablecoin (crvUSD) introduces a groundbreaking liquidation mechanism called LLAMMA (Lending-Liquidating AMM Algorithm), which redefines the handling of collateral during volatile market conditions. Unlike traditional CDP-based stablecoins like DAI, which rely on abrupt, discrete liquidations, LLAMMA enables soft, continuous liquidations.

This is achieved by integrating borrower collateral into a specialized AMM pool, where collateral is dynamically rebalanced between volatile assets (e.g., ETH) and the stablecoin (crvUSD). The rebalancing occurs within defined price bands using a concentrated liquidity model similar to Uniswap V3 but optimized for automated liquidation and recovery processes. When collateral prices decline, a portion is gradually converted into crvUSD, reducing exposure to volatility. This mechanism minimizes borrower losses, avoids sudden market shocks, and reduces the protocol's risk of bad debt.
LLAMMA’s efficiency is bolstered by its use of external price oracles (e.g., Uniswap TWAP, Chainlink, and Tricrypto) combined with an exponential moving average (EMA, more details about it you can find here and here) to filter volatility and manipulation risks. The system incentivizes arbitrageurs to rebalance the collateral pool when deviations occur between the oracle price P_ORACLE and the pool price P_AMM, ensuring liquidity and stability. For instance, when ETH’s price falls, P_AMM drops faster than P_ORACLE, prompting arbitrageurs to deposit crvUSD and extract undervalued ETH, thus restoring balance. This decentralized and automated liquidation process is highly effective in preventing cascading liquidations, even during extreme market events, while allowing borrowers to recover positions through repayment or collateral addition. However, the model depends on timely arbitrage, making high gas fees or oracle delays potential risks in maintaining optimal pool health.
Advantages
1. Soft Liquidation
LLAMMA's soft liquidation mechanism avoids sudden collateral losses by gradually converting collateral into crvUSD as its value declines. Hard liquidations are also available as an additional layer of protection against bad debt.

2. Minimized Market Impact
By spreading out liquidations over time, crvUSD reduces the risk of market shocks caused by the sudden selling of collateral, a common issue with Aave during large-scale liquidations.

3. Gas Efficiency Through Position Aggregation
crvUSD aggregates all borrower positions into a single collateral pool, allowing soft liquidation actions to occur on a pooled basis. This design significantly reduces gas costs compared to Aave, where each borrower’s liquidation requires a separate transaction. The aggregated approach ensures that rebalancing actions, such as selling collateral, are more efficient and cost-effective during periods of high activity.

4. Incentivized Arbitrage for Rebalancing
crvUSD leverages external arbitrageurs to maintain pool balance, reducing the protocol's reliance on predefined liquidators. This decentralized model ensures efficient collateral rebalancing, even in volatile markets.

5. Borrower-Friendly Mechanism
Borrowers retain more options in crvUSD, including self-liquidation or adding collateral during soft-liquidation mode, giving them greater control over their positions.
Disadvantages
1. Single-Collateral Restriction
crvUSD is limited to a single asset (e.g., ETH or liquid staked derivatives). This significantly reduces flexibility for borrowers who may want to use other assets, such as stablecoins, BTC, or yield-bearing tokens, as collateral.
Borrowers with diversified portfolios or assets other than ETH may find crvUSD less attractive (in comparison with traditional approach).

2. Dependence on Arbitrage Participation
crvUSD relies on external arbitrageurs to rebalance its pools. If market conditions (e.g., high gas fees or low arbitrage profitability) hinder arbitrage activity, the protocol may face delays in liquidation, increasing the risk of bad debt.
Fluid Vault T1

In Fluid Vault, the liquidation process is designed to be both cost-effective and highly efficient. Instead of harsh penalties and full collateral sell-offs, the protocol allows for partial liquidations that only bring the position back to a safe state. Debt to Collateral Ratio and Liquidation Threshold determine when a position can be liquidated. If the ratio surpasses the defined threshold, a portion of the collateral is sold off just enough to reduce the debt within safe bounds, incurring a minimal liquidation penalty—often as low as 0.1%. By contrast, most competitors levy a 5-10% penalty. Moreover, The platform’s architecture allows multiple positions to be liquidated in a single transaction with minimal additional gas costs, avoiding multiple costly operations.
Branches in Fluid Vault represent a mechanism to handle sequential liquidation events within defined ranges (ticks) where the collateral price has declined, resulting in unhealthy collateral-to-debt ratios. Each branch encompasses a set of ticks that become eligible for liquidation, enabling the protocol to systematically reduce bad debt and restore safe collateral levels without directly interacting with individual user positions. As the liquidation process moves through these ranges, branches may merge when one branch’s minimal tick level is reached. This consolidation advances the process efficiently to the next stage of liquidation. This branch-based architecture ensures that liquidations occur in a structured, controlled, and gas-efficient manner, effectively “waving” through segments of the collateral price curve while maintaining protocol stability.

One of Fluid Vault’s key innovations is its integration with DEX aggregators. This approach allows bad debt to be handled similar to a liquidity provision on a decentralized exchange. Instead of a dedicated liquidator stepping in, trades occurring through the integrated DEX infrastructure can effectively “absorb” bad debt as part of their regular operations. Consequently, liquidation doesn’t necessarily depend on a single class of participants; it can occur fluidly through standard trading activity. This eliminates the need for heavy monitoring infrastructure or expert knowledge, making the system more accessible. However, the very low liquidation penalty, while user-friendly, may reduce incentives for some traditional liquidators. Additionally, during periods of high volatility, sudden price swings can still cause unplanned and rapid liquidations, presenting an inherent limitation rather than a design flaw.

A standout feature of Fluid Vault’s liquidation mechanism is the ability to treat bad debt as an active trading opportunity rather than a separate, isolated event. By integrating bad debt into the platform’s liquidity pools, it becomes as simple to handle as executing a trade on Uniswap, Curve, or Balancer. When liquidity providers and traders interact with these pools, they effectively help to “soak up” bad debt, distributing the risk and resolution across a broad participant base. This means that no specialized infrastructure or tools are required to track and liquidate positions at risk. Anyone with basic experience in the DeFi ecosystem can become a participant in the liquidation process, further lowering the barrier to entry, increasing efficiency, and turning what traditionally would be a specialized and cumbersome process into a routine operation.
Advantages:
  1. Extremely low liquidation penalties (as low as 0.1%, compared to 5–10% in other protocols).
  2. High gas efficiency: multiple positions can be liquidated in a single transaction without a significant increase in gas costs.
  3. Integration with DEX-style mechanisms: “bad debt” can be handled similarly to active liquidity, making it simple to integrate with DEX aggregators. This can allow traders, rather than dedicated liquidators, to absorb bad debt.
  4. No need for heavy infrastructure to track individual at-risk positions; even users with basic experience can participate in liquidation.
  5. Only the required amount is liquidated to bring a position back to a safe threshold, preventing unnecessary collateral sell-offs.
  6. Consistent and automatic rebalancing of all positions through a tick-based system, without direct interaction with each user’s account.
Disadvantages
  1. Currently supports only a single type of collateral, limiting flexibility and diversification.
  2. Although liquidations are minimal, the very low penalty might reduce incentives for some traditional liquidators to participate.
  3. There is no further partial liquidation beyond restoring the position to the liquidation threshold; you cannot fine-tune liquidation amounts below that safety level.
  4. In periods of extreme volatility, rapid and unplanned liquidations may still occur despite the efficient mechanism.

More information about Fluid Vault you can find here.
Conclusion for the part 2
Each protocol—AAVE, Gearbox, crvUSD, and Fluid Vault—offers a unique approach to liquidations, balancing factors like flexibility, cost, risk, and user-friendliness. Understanding these trade-offs helps participants choose platforms that align with their priorities in a rapidly evolving DeFi landscape.
Part 3: Real-World Liquidation Related Vulnerabilities and Lessons Learned
Overview
In this part, we explore some of the most significant vulnerabilities uncovered in real-world audits of DeFi protocols. These examples highlight critical risks, such as oracle manipulation, liquidity shortfalls, and flaws in liquidation execution mechanisms. By analyzing these vulnerabilities, we aim to provide valuable insights into the pitfalls and best practices of designing robust liquidation frameworks. This section underscores the importance of continuous auditing and adaptation to safeguard DeFi platforms in an ever-changing market landscape.
MakerDAO’s “Black Thursday” Incident (March 2020)
Although it was not a traditional “bug” in the code, MakerDAO’s liquidation mechanism failed under extreme market conditions.
MakerDAO’s system allows users to create Collateralized Debt Positions (CDPs) by locking collateral (primarily ETH at the time) and borrowing the DAI stablecoin against it. If the collateral’s value falls too much relative to the borrowed DAI, the position becomes undercollateralized and is subject to liquidation to maintain the protocol’s solvency. Liquidations in MakerDAO involve an auctioning process: undercollateralized CDPs are auctioned off to bidders, who pay DAI to purchase the collateral at a discount.
What Happened on Black Thursday:
1. Market Crash:
On March 12, 2020, global markets, including crypto, experienced a massive downturn. The price of ETH dropped steeply within a very short timeframe. This meant many CDPs fell below their required collateralization threshold simultaneously.

2. Network Congestion & Oracle Delays:
Ethereum network congestion spiked as panic spread and users rushed to adjust their positions. Transaction fees soared, and many transactions were delayed. At the same time, MakerDAO relies on decentralized oracles to feed ETH price data into the system. The rapid price decline, combined with network congestion, delayed updates and made it challenging for the protocol to react promptly to the rapidly changing market conditions.

3. Liquidation Mechanism Under Stress:
Under normal circumstances, when a CDP’s collateralization ratio drops too low, the protocol triggers a liquidation and initiates an auction. Bidders can then offer DAI to buy the liquidated collateral. The design assumes competitive bidding to ensure the protocol receives enough DAI to cover the debt and return some collateral value to the original CDP owner.
  • However, during Black Thursday:The extreme volatility and congestion slowed down the entire liquidation process.
  • Oracle data took longer than expected to update, meaning that by the time the protocol recognized a CDP was undercollateralized, the actual market price of ETH had often fallen even further.

4. Zero-Bid Liquidations:
  • The most catastrophic outcome was that multiple auctions saw zero or near-zero bids. In normal conditions, liquidators compete with each other, ensuring the protocol at least recovers most of the debt owed by the CDP. Instead, a few opportunistic participants were able to walk away with ETH collateral at essentially no cost (0 DAI bids) because:There were not enough active bidders in the chaotic environment.
  • Transactions to outbid these near-zero bids either didn’t get mined in time or never arrived due to high fees and congestion.

5. Resulting Losses:
Because the protocol received almost no DAI from many of these auctions, MakerDAO ended up with a significant shortfall—essentially a large hole in its balance sheet. The protocol became undercollateralized as it could not fully cover the DAI in circulation with underlying collateral. This event forced MakerDAO to initiate an emergency shutdown plan and later hold auctions for MKR (the governance and volatility absorbing token) to recapitalize the system.
Key Lessons Learned:
The event showed that MakerDAO’s reliance on timely oracles and competitive, on-chain auctions is vulnerable in extreme conditions. If the network is too congested or the market moves too fast, the current design may fail to efficiently liquidate bad debt.

“Black Thursday” underscored that DeFi protocols are not isolated; they depend on stable network operation, accurate price feeds, and healthy market conditions. A crisis in the broader crypto market can directly translate into insolvency risks for protocols.

The MakerDAO community responded by improving their auction mechanisms, oracle feeds, and introducing circuit breakers and other fail-safes. These changes aimed to ensure that, in future stress scenarios, liquidations would proceed more smoothly and predictably.
Alpha Homora (February 2021)
Alpha Homora is a yield-leveraging protocol built on Ethereum, allowing users to borrow funds against collateral to amplify their returns in yield farming. In February 2021, the protocol suffered a major exploit resulting in roughly $37 million in losses. The vulnerability was tied to improper integration between Alpha Homora and Iron Bank (a product of C.R.E.A.M.), as well as flawed collateral calculations.
Nature of the Vulnerability:
The crux of the issue was incorrect handling of collateral and loan parameters between Alpha Homora and Iron Bank. The attacker was able to borrow funds beyond what their collateral should have allowed due to logical miscalculations in leverage and collateralization requirements. Under normal conditions, exceeding safe collateralization ratios triggers liquidations that restore system health by selling some collateral to repay debt. However, the bug enabled the attacker to circumvent these safeguards, letting them borrow more than permitted without facing liquidation.
Role of Liquidation and the Core Issue:
Properly implemented liquidation logic ensures that when positions become undercollateralized, a portion of the collateral is sold off to cover the shortfall. Alpha Homora’s vulnerability allowed the attacker to bypass liquidation triggers by confusing the system into believing the position remained adequately collateralized. As a result, the attacker extracted significant value before the discrepancy was noticed.
Lessons Learned:
This case underscored the importance of accurate collateral calculations and consistent logic across integrated protocols. When one protocol (Alpha Homora) relies on another (Iron Bank), they must ensure that liquidation conditions and loan-to-value (LTV) calculations are perfectly aligned. Any mismatch can create loopholes that attackers can exploit.

The related code with the issue described you can find here
Cream Finance (Multiple Exploits in 2021–2022)
Cream Finance, a lending and borrowing platform similar to Compound and Aave, also faced multiple attacks exploiting flaws in collateral valuation, interest calculations, price oracle dependencies, and liquidation logic.

  • Nature of Cream Finance Vulnerabilities:
Many of Cream’s vulnerabilities stemmed from incorrect assumptions or oversights in how collateral and debt were accounted for. Attackers often manipulated collateral prices or exploited flash loans to trick the protocol into believing a position was healthier than it actually was.

  • Price Manipulation and Avoiding Liquidation:
One common tactic involved artificially inflating the price of the collateral used by the attacker’s position. If the protocol relied on this inflated price, it would fail to trigger a liquidation, believing the position was still solvent. After the attacker secured their profit and the price returned to normal, the protocol was left undercollateralized, effectively absorbing the losses.

  • Logical Flaws in Debt and Interest Calculations:
Some vulnerabilities emerged from incorrect interest and debt calculations. These errors allowed borrowers to take out loans that the system deemed fully backed, but in reality, lacked sufficient collateral. Without accurate liquidation triggers, the protocol could not protect itself against these unbacked loans, resulting in bad debt.

  • Lessons Learned:
The Cream Finance exploits highlighted the need for robust price oracles, secure flash loan implementations, and consistent health factor validation. Protocols must ensure that their liquidation logic can withstand price manipulation, sudden market changes, and integration complexities. Comprehensive audits, testing of economic assumptions, and strict adherence to best practices can help mitigate these risks.
Common Takeaways
1. Correct Health Factor, Collateral and Debt Accounting:
Any discrepancies in calculating LTV ratios, collateral, debt or health factor open the door to manipulation. Attackers can borrow more than allowed, effectively bypassing liquidation triggers.

2. Reliable Oracles and Data Feeds:
Since liquidation logic relies heavily on accurate price data, tamper-resistant oracles are crucial. Delays or manipulations in price feeds can cause premature or nonexistent liquidations.

3. Complex Cross-Protocol Interactions:
When protocols integrate or rely on one another, misaligned assumptions or incorrect parameter passing can create systemic vulnerabilities. Rigorous integration tests and audits are essential.
Proper Tuning of Risk Parameters:
Well-calibrated risk parameters, such as liquidation thresholds, collateralization ratios, and penalty rates, are essential for maintaining protocol stability. Overly lenient settings may lead to bad debt accumulation, while overly strict parameters can deter user participation and increase liquidation events unnecessarily. Regular reviews and adjustments based on market conditions are necessary to strike the right balance.
Some interesting findings in audits
Curve Finance Inflation Attack and Hard liquidations
This issue has been found by MixBytes team during the audit of the Curve smart contracts. C-01 in this audit report describes an issue in the TwoWayLending protocol where a hacker can manipulate the share price and trigger hard liquidations.
Compound Self-Liquidation critical issue
This issue was found by Rich M in 2019.

The core of the bug was that if the borrower and the liquidator were the same address, the smart contract logic would fail to properly adjust the collateral balances. Instead of effectively leaving the account's collateral unchanged (subtracting and then adding the same amount), it would mistakenly increase the borrower’s collateral by the seized amount. This meant a malicious user could liquidate their own position and walk away with more collateral than they started with, effectively stealing funds from the protocol.

The original article, describing this issue is here, link to the code where the issue was found is here.
How an Attacker Can Block Liquidation
Sometimes a borrower can block the liquidation process and keep their position undercollateralized.

The C-04 in this audit report describes a problem where users can provide an unlimited number of position NFTs to their margin account, which can cause issues during liquidation. This can be exploited by users to avoid liquidation by causing an out-of-gas error. The report recommends restricting the maximum number of NFTs that can be added to a margin account to prevent this issue.
Conclusion
As DeFi matures, developers, auditors, and users must remain vigilant, continuously refine liquidation mechanisms, and embrace robust risk management and testing practices to foster a more secure, stable, and resilient financial ecosystem.
The increasing frequency of flash crashes and market turbulence in the DeFi ecosystem underscores the need for robust and adaptive protocol designs. To enhance resilience and protect both users and protocols, the following strategies should be prioritized:

1. Gas Fee-Optimized Liquidation Architecture
Enabling multiple liquidations within a single transaction minimizes gas costs and accelerates execution. This reduces the strain on the network during peak periods and ensures timely liquidation processes, preventing cascading failures.

2. Partial Liquidation Mechanisms
Introducing partial liquidations allows protocols to liquidate smaller portions of under-collateralized positions incrementally, reducing market impact and providing borrowers with opportunities to recover. This approach prevents the destabilizing effects of large-scale, sudden sell-offs.

3. Dynamic Liquidation Thresholds and Collateral Buffers
Flexible thresholds that adjust in response to market conditions, combined with additional collateral buffers, provide greater stability during volatile periods. These measures allow protocols to maintain solvency while offering borrowers more time to manage their positions.

4. Advanced Price Oracle Integration
Leveraging multiple reliable oracles and off-chain price aggregation reduces delays and costs in updating market data. Technologies like the PYTH network enable high-frequency price updates with minimal gas expenditure, ensuring protocols can react quickly to price changes without overburdening the blockchain.

By adopting these strategies, DeFi protocols can mitigate the risks associated with flash crashes, protect user assets, and maintain ecosystem stability. These recommendations not only improve operational efficiency but also build trust and confidence among users, ensuring the long-term sustainability of decentralized finance.
  • Who is MixBytes?
    MixBytes is a team of expert blockchain auditors and security researchers specializing in providing comprehensive smart contract audits and technical advisory services for EVM-compatible and Substrate-based projects. Join us on X to stay up-to-date with the latest industry trends and insights.
  • Disclaimer
    The information contained in this Website is for educational and informational purposes only and shall not be understood or construed as financial or investment advice.
Other posts