Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

Launching a Protocol with Automated Liquidations

A technical guide to implementing a secure, gas-efficient liquidation system for a lending protocol, covering incentive design, auction mechanics, keeper integration, and risk management.
Chainscore © 2026
introduction
ARCHITECTURE GUIDE

Launching a Protocol with Automated Liquidations

Automated liquidations are a critical risk management mechanism for lending protocols. This guide explains the core components and design considerations for implementing them.

Automated liquidations are a non-negotiable component of any overcollateralized lending protocol like Aave or Compound. Their primary function is to protect the protocol's solvency by automatically selling a borrower's collateral when their health factor falls below a safe threshold (typically 1.0). This process converts the undercollateralized debt position into a solvent one, ensuring lenders can be repaid. Without this mechanism, bad debt would accumulate, threatening the entire system's liquidity and user funds.

The core architecture revolves around a liquidation engine that continuously monitors positions. Key parameters you must define include the liquidation threshold (the collateral value at which liquidation triggers), the liquidation penalty (an incentive for liquidators, e.g., 5-10%), and the close factor (the maximum percentage of debt that can be liquidated in a single transaction). These are often set by governance. The engine calculates a health factor for each position: Health Factor = (Collateral Value * Liquidation Threshold) / Borrowed Value. A health factor below 1 makes the position eligible.

To execute, you need a permissionless function that liquidators can call. A standard pattern, as seen in Compound's Comptroller.sol, involves a liquidateBorrow function. It verifies the health factor, calculates the seizeable collateral amount (debt + penalty), and transfers assets. Critical design choices include allowing partial liquidations to reduce market impact and implementing a liquidation bonus to incentivize bots. The function must be gas-efficient and resistant to front-running, often using a fixed price oracle at the start of the transaction.

Integrating with secure oracles like Chainlink is paramount. Liquidations rely on accurate, real-time price feeds for both collateral and borrowed assets. You must decide on a price feed update frequency and a safety margin (oracle deviation threshold) to prevent stale price attacks. For example, if the oracle updates every hour, a position could become undercollateralized and be exploited before the next update. Using multiple data sources or a time-weighted average price (TWAP) from a DEX can enhance robustness.

Finally, consider the economic incentives. The liquidation penalty must be high enough to cover the liquidator's gas costs and profit margin, driving a competitive ecosystem of liquidation bots, but not so high it unfairly penalizes borrowers. Testing your system under extreme market volatility—simulating a 50% price drop in collateral—is essential. Tools like Gauntlet and Chaos Labs provide simulations to model capital efficiency and risk parameters before mainnet launch.

prerequisites
FOUNDATION

Prerequisites and Core Concepts

Before launching a protocol with automated liquidations, you must understand the core financial and technical components that make the system secure and functional.

An automated liquidation protocol is a non-custodial lending system where users can borrow assets by providing collateral. The core mechanism ensures the loan remains overcollateralized at all times. If the value of the collateral falls below a predefined threshold (the liquidation ratio), a portion is automatically sold to repay the debt, protecting the protocol from insolvency. This system requires a robust price oracle (like Chainlink or Pyth Network) to provide accurate, real-time asset valuations on-chain, which is the single most critical dependency for security.

Key financial parameters must be carefully calibrated. The Loan-to-Value (LTV) ratio determines the maximum amount a user can borrow against their collateral (e.g., 75% LTV means a $100 deposit allows a $75 loan). The liquidation threshold is slightly higher than the maximum LTV, triggering liquidations before the loan becomes undercollateralized. A liquidation penalty (or bonus) incentivizes external liquidators to repay the bad debt and seize the collateral at a discount, keeping the system balanced. Misconfigured parameters can lead to mass liquidations or, worse, protocol insolvency.

From a technical perspective, the smart contract architecture typically separates core logic into modules: a Collateral Manager for deposits/withdrawals, a Borrowing Engine for issuing debt, and a Liquidation Module that executes the safety mechanism. The liquidation logic itself is often permissionless, allowing any network participant to call the public liquidate() function when conditions are met. This design avoids centralized bottlenecks but requires the contract's state and pricing logic to be gas-efficient to prevent front-running or manipulation during volatile market events.

Security considerations are paramount. Beyond oracle reliability, you must guard against flash loan attacks that can manipulate collateral value within a single transaction. Implementing a health factor for each position—a numerical representation of its safety—allows for continuous risk monitoring. Furthermore, using decentralized governance (via a DAO or token vote) for parameter updates, rather than admin keys, builds trust. A time-tested codebase, like a fork of Aave or Compound's audited contracts, is a common starting point to mitigate implementation risks.

Finally, successful deployment requires integration with the broader ecosystem. Your protocol will need liquidity pools for the borrowed assets and a front-end interface. You must also consider cross-chain interoperability if targeting users on multiple networks, which may involve deploying on an L2 like Arbitrum or using a cross-chain messaging layer. Thorough testing on a testnet (and possibly a bug bounty program) is non-negotiable before mainnet launch to ensure the automated system behaves as intended under all market conditions.

key-concepts
ARCHITECTURE

Core Components of a Liquidation System

Building a secure and efficient liquidation engine requires integrating several critical subsystems. These components work together to monitor positions, calculate health, and execute liquidations.

01

Health Factor & Price Oracles

The health factor is the core risk metric, calculated as (Collateral Value * Collateral Factor) / Borrowed Value. A position becomes liquidatable when this ratio falls below 1.0.

  • Reliable price oracles (e.g., Chainlink, Pyth Network) are non-negotiable for accurate valuation.
  • Collateral factors (e.g., 80% for ETH, 65% for wBTC) determine the borrowing power of deposited assets.
  • Oracle staleness and manipulation resistance are critical for system solvency.
02

Liquidation Engine & Incentives

This is the execution layer that closes underwater positions. Key design choices include:

  • Liquidation threshold: The health factor level (e.g., 1.05) that triggers the process.
  • Liquidation bonus (discount): The incentive for liquidators, typically 5-15% of the collateral seized.
  • Close factor: The maximum percentage of a position (e.g., 50%) that can be liquidated in a single transaction to prevent market disruption.
  • The engine must be permissionless and gas-efficient to ensure timely execution.
05

Debt & Bad Debt Accounting

The system must handle scenarios where collateral value drops too quickly for any liquidation to be profitable, resulting in bad debt.

  • A safety module or protocol-owned reserve (often funded by protocol revenue) is used to recapitalize the system.
  • Some designs use a global settlement or pause mechanism as a last resort.
  • Transparent accounting of bad debt is essential for user trust and protocol governance.
incentive-design
PROTOCOL DESIGN

Designing Liquidator Incentives

A guide to structuring rewards that ensure timely, secure, and economically viable automated liquidations for lending protocols.

Automated liquidations are a critical risk management mechanism for overcollateralized lending protocols like Aave and Compound. When a borrower's collateral value falls below the required health factor, liquidators can repay a portion of the debt in exchange for the collateral at a discount. The liquidation incentive is the economic reward for this service, typically a percentage bonus on the seized collateral. Designing this incentive is a balancing act: it must be high enough to attract liquidators to cover gas costs and provide profit, but low enough to minimize the penalty on borrowers and prevent predatory behavior.

The incentive structure directly impacts protocol safety and user experience. A low incentive may lead to liquidation inefficiency, where positions become undercollateralized but no liquidator acts, putting the entire protocol at risk of bad debt. Conversely, an excessively high incentive can cause over-liquidation and user attrition. Most protocols implement a fixed discount, such as Compound's 5% or Aave V3's variable 5-15% based on asset volatility. An emerging design is the Dutch auction model, as seen in Euler and Morpho Blue, where the discount increases the longer a position remains unhealthy, dynamically balancing speed and cost.

When launching a protocol, you must calculate the minimum viable incentive. This covers the liquidator's expected costs: Gas Cost + Slippage + Risk Premium + Profit Margin. On Ethereum Mainnet, gas can be the dominant factor. For example, a complex liquidation might cost 500,000 gas. At a gas price of 50 Gwei, this is 0.025 ETH (~$75). The incentive must cover this cost on top of the debt repaid. Protocols often set a liquidation close factor (e.g., 50% of the debt) to limit exposure per transaction and a liquidation bonus (the incentive) paid in the seized collateral.

Here is a simplified representation of a core liquidation logic in a smart contract, highlighting the incentive calculation.

solidity
function liquidate(address borrower, uint256 repayAmount) external {
    // 1. Check health factor
    require(getHealthFactor(borrower) < 1e18, "Healthy position");

    // 2. Calculate the maximum allowed repayment and collateral seizure
    uint256 maxRepay = debtOf(borrower) * closeFactor / 100;
    repayAmount = min(repayAmount, maxRepay);

    // 3. Calculate collateral to seize: debt repaid + incentive bonus
    uint256 incentive = repayAmount * liquidationBonus / 100;
    uint256 collateralToSeize = repayAmount + incentive;

    // 4. Execute the swap: repay debt, seize collateral
    debtToken.transferFrom(msg.sender, address(this), repayAmount);
    collateralToken.transfer(msg.sender, collateralToSeize);
}

This shows how the bonus is added to the amount of collateral transferred to the liquidator.

Beyond the base incentive, consider incentive stacking. Protocols can offer additional rewards from a treasury or liquidity mining program to bootstrap activity during launch. However, these should be temporary. The permanent, on-chain incentive must stand alone. Also, design for MEV resistance. Frontrunning bots can extract value from public liquidation transactions. Using a Dutch auction or a sealed-bid mechanism (like in the MEV-Share ecosystem) can help democratize access and return some value to users. Monitoring tools like Chainscore are essential post-launch to track liquidation efficiency, average discount, and liquidator profitability in real-time.

Finally, parameter selection is not set-and-forget. Use governance to adjust bonuses based on network conditions and asset volatility. A stablecoin collateral pool may need a lower bonus than a volatile altcoin pool. Transparently communicate changes to users, as they affect their cost of borrowing. A well-designed system creates a reliable, competitive market for liquidation services, which is the bedrock of trust in any decentralized lending market.

ARCHITECTURE

Comparison of Liquidation Mechanisms

Key technical and economic trade-offs between common automated liquidation designs for lending protocols.

MechanismDutch AuctionFixed DiscountLiquidity Pool (AMM)

Primary Use Case

Large, illiquid positions

Standard ERC-20 collateral

Exotic or volatile collateral

Price Discovery

Dynamic over time

Instant at fixed discount

Instant via pool price

Liquidation Penalty

Starts at ~13%, decays

Fixed 5-15%

Implied via slippage

Max Gas Cost for Liquidator

High (multiple txs)

Low (single tx)

Low to Medium (single tx)

Keeper Race Intensity

High (time-based)

Extreme (gas auction)

Moderate (slippage-based)

Oracle Dependency

Critical for starting price

Critical for discount calc

Reduced (uses pool price)

Example Protocol

MakerDAO

Compound, Aave

Abracadabra (MIM)

Capital Efficiency for Liquidators

Lower (capital locked)

High

Highest (flash loans)

keeper-integration
AUTOMATED LIQUIDATIONS

Integrating with Keeper Networks

This guide explains how to launch a lending or borrowing protocol with automated liquidations using decentralized keeper networks like Chainlink Automation or Gelato.

A keeper network is a decentralized service that executes predefined smart contract functions when specific conditions are met. For a lending protocol, the most critical condition is when a user's collateral value falls below the required health factor or collateralization ratio. Instead of relying on manual monitoring or centralized bots, you can outsource this execution to a network of incentivized node operators. This ensures liquidation events are processed reliably, fairly, and in a trust-minimized manner, securing the protocol's solvency.

To integrate, your smart contract must expose a public function that any external caller can invoke to perform the liquidation check and execution. A standard pattern is a function like checkAndLiquidate(address user). Inside, the function validates the user's health factor and, if it's below the safe threshold, executes the liquidation logic—seizing collateral, repaying debt, and awarding a liquidation bonus to the keeper. The function should be permissionless but include access controls or rate-limiting to prevent spam.

You then register this function as an Upkeep on a keeper network. For Chainlink Automation, you create an Upkeep that calls your checkAndLiquidate function. You specify the trigger condition, which is typically time-based (e.g., every block or every 10 seconds). The keeper nodes will call your function at the defined interval; the on-chain logic inside the function determines if a liquidation is necessary. You fund the Upkeep with LINK (for Chainlink) or the native gas token (for Gelato) to cover execution costs and keeper rewards.

Designing efficient liquidation logic is crucial for cost-effectiveness. Since keepers pay gas for each call, you want to avoid unnecessary on-chain computations. Implement off-chain computation where possible: use a keeper network's off-chain simulation capabilities (like Gelato's canExec) to check the health factor off-chain and only submit a transaction if liquidation is required. This can drastically reduce gas costs. Additionally, consider batching multiple user checks into a single transaction to improve efficiency for protocols with many positions.

Security considerations are paramount. Your liquidation function must be resilient to reentrancy attacks and price oracle manipulation. Use checks-effects-interactions patterns and rely on decentralized oracles like Chainlink Data Feeds for accurate, tamper-resistant price data. Thoroughly test the integration on a testnet, simulating scenarios like network congestion and oracle staleness. Proper integration ensures your protocol remains solvent during market volatility while maintaining decentralization and reliability.

risk-mitigation
SYSTEMIC RISK MITIGATION

Launching a Protocol with Automated Liquidations

Automated liquidations are a critical defense mechanism for lending protocols, preventing bad debt accumulation and systemic failure. This guide explains the core concepts and implementation strategies.

In decentralized finance (DeFi), bad debt occurs when a user's collateral value falls below their loan value and the position cannot be liquidated. This creates a liability for the protocol's treasury or insurance fund. The primary tool to prevent this is an automated liquidation engine. When a user's health factor (a ratio of collateral value to borrowed value) drops below a threshold (e.g., 1.0), liquidators are incentivized to repay part or all of the debt in exchange for the collateral at a discount. This process is non-negotiable and triggered by code, not a central authority.

Designing an effective system requires careful parameter selection. Key variables include the liquidation threshold (the collateral value at which liquidation becomes possible), the liquidation penalty (the discount offered to liquidators, typically 5-15%), and the close factor (the maximum percentage of debt that can be liquidated in a single transaction). Protocols like Aave and Compound use on-chain price oracles to calculate health factors in real-time. A critical failure mode is liquidation cascades, where many positions are liquidated simultaneously, causing volatile price swings and potentially triggering more liquidations.

Smart contract implementation involves creating a liquidateBorrow or similar function. This function must verify the borrower's health factor is unhealthy, calculate the repay amount, transfer the borrowed assets from the liquidator, and transfer the discounted collateral to the liquidator. It must also update the protocol's internal accounting. Security is paramount; the function must be resistant to reentrancy attacks and ensure oracle price freshness to prevent manipulation. Here's a simplified logic check:

solidity
require(healthFactor < 1.0, "Borrower is not underwater");
uint collateralToSeize = (repayAmount * liquidationBonus) / oraclePrice;
_seizeCollateral(borrower, liquidator, collateralToSeize);

Beyond the smart contract, a robust liquidation system requires a healthy liquidator ecosystem. Protocols must ensure the liquidation incentive (the penalty) is sufficient to cover gas costs and provide profit during network congestion. Some protocols, like MakerDAO, use auction-based liquidations (collateral auctions) for larger, less liquid assets to achieve better prices. Monitoring tools are essential; protocol teams should track metrics like the percentage of at-risk positions, average liquidation size, and liquidator participation rates to adjust parameters proactively.

Systemic risk emerges when market-wide volatility overwhelms the liquidation mechanism. This can happen due to oracle failure (providing stale or incorrect prices), liquidity black holes (no liquidators available or insufficient liquidity to absorb sales), or collateral correlation (e.g., using only ETH-based assets as collateral during an ETH crash). Mitigation strategies include using multiple, decentralized oracle feeds (like Chainlink), implementing circuit breakers that pause liquidations during extreme volatility, and requiring a diverse basket of uncorrelated collateral assets.

Before launch, thorough testing is non-negotiable. This includes unit tests for the liquidation logic, forked mainnet simulations using tools like Foundry or Tenderly to test under realistic market conditions, and invariant testing to ensure the system's total liabilities never exceed its assets. A well-designed automated liquidation system is not just a feature; it is the foundational pillar that maintains the protocol's solvency and user trust during market stress.

implementation-steps
AUTOMATED LIQUIDATIONS

Step-by-Step Implementation Guide

A practical guide to implementing a secure and efficient liquidation engine for lending protocols. This covers core components from price feeds to keeper networks.

IMPLEMENTATION COMPARISON

Gas Optimization Techniques for Liquidations

Comparison of common gas optimization strategies for automated liquidation engines on EVM chains.

Optimization TechniqueBatch LiquidationsGas Token RefundsMEV-Aware ExecutionState Channel Pre-approvals

Average Gas Savings per TX

15-25%

5-10%

10-20%

40-60%

Implementation Complexity

Medium

Low

High

Very High

Requires Protocol Changes

MEV Resistance

Best For

High-volume protocols

All protocols

Competitive LTV markets

Whitelisted institutional users

Primary Risk

Failed batch reversion

Gas token price volatility

Searcher centralization

Off-chain security compromise

Example Protocol

Aave V3

EIP-1559 (legacy)

Euler Finance (historical)

dYdX StarkEx

Estimated Dev Time

2-3 weeks

1 week

1-2 months

3+ months

AUTOMATED LIQUIDATIONS

Frequently Asked Questions

Common technical questions and troubleshooting for developers implementing automated liquidation systems in DeFi protocols.

The core difference lies in who can execute liquidations and the associated economic model.

Keeper networks (like Chainlink Keepers, Gelato Network) are decentralized, permissionless networks where any node can submit a transaction to trigger a liquidation. They operate on a first-come, first-served basis, with the keeper earning a pre-defined incentive (often a gas reimbursement plus a bonus). This model promotes censorship resistance and reliability through competition.

Permissioned operator models rely on a whitelisted set of addresses, often controlled by the protocol team or DAO, to perform liquidations. This centralizes trust but can offer more predictable execution and easier coordination for complex logic. The incentive is typically a fixed fee taken from the liquidation surplus.

Choosing between them involves a trade-off between decentralization, operational overhead, and execution cost predictability.

conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have now implemented a foundational automated liquidation system. This guide covered the core components: a price feed oracle, a health factor check, and a liquidation execution contract.

The primary goal of this system is to protect protocol solvency by automatically closing undercollateralized positions. The key metric is the Health Factor (HF), calculated as (Collateral Value * Liquidation Threshold) / Borrowed Value. When HF drops below 1.0, the position becomes eligible for liquidation. Your LiquidationEngine contract listens for these events and executes the liquidation, typically by repaying a portion of the debt in exchange for the collateral at a discounted rate, enforced by a liquidationBonus.

For production deployment, several critical enhancements are necessary. Oracle robustness is paramount; consider using a decentralized oracle network like Chainlink for mainnet price feeds instead of a mock oracle. Implement circuit breakers and maximum liquidation size limits to manage risk during extreme volatility. You must also add access control (e.g., OpenZeppelin's Ownable or role-based systems) to your LiquidationEngine to prevent unauthorized calls. Finally, comprehensive event logging is essential for off-chain monitoring and analytics.

To extend this system, explore integrating with keeper networks like Chainlink Keepers or Gelato Network to automate the execution of the checkAndLiquidate function, removing the need for manual transaction submission. You could also implement more sophisticated logic, such as partial liquidations that only restore the HF to a safe threshold (e.g., 1.5) or support for flash loans to allow liquidators to perform atomic, capital-efficient transactions.

For further learning, review the code for established lending protocols. Study Aave's liquidation logic and Compound's Comptroller contract to understand their real-world implementations and security considerations. Always test your contracts extensively on a testnet (like Sepolia or Goerli) using frameworks like Foundry or Hardhat before considering a mainnet launch.

The next step is to integrate this liquidation module into a complete lending protocol. This involves building the core LendingPool for deposits and borrows, which will calculate and update each user's Health Factor on every interaction. The LiquidationEngine should be permissionlessly callable, with incentives (the liquidation bonus) ensuring the ecosystem remains solvent. Remember, in DeFi, the security of user funds is the highest priority; a robust, automated liquidation mechanism is a non-negotiable component of that security model.