Compound Liquidation Bot Development

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1 servicesAll 1306 services
Compound Liquidation Bot Development
Complex
~1-2 weeks
FAQ
Blockchain Development Services
Blockchain Development Stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1214
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_logo-advance_0.png
    B2B Advance company logo design
    561
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    823

Development of Compound Liquidation Bot

On Compound v3 (Comet), during sharp market movement—ETH drops 15% in an hour—hundreds of positions simultaneously cross the liquidation threshold. The first liquidator to call absorb claims discounted collateral assets. The second gets nothing. This is a competitive MEV arena where milliseconds count: Compound liquidations are caught by MEV bots with direct builder connections and custom Rust implementations. Building a bot that works in this environment is non-trivial.

Liquidation Mechanics in Compound v3

Compound v3 differs fundamentally from v2 in liquidation model. In v2, there was liquidateBorrow—liquidator repays borrower's debt and receives collateral with bonus (8-15%). In v3 (Comet), a two-step model exists:

Step 1: absorb. Any address can call absorb(address absorber, address[] calldata accounts) for insolvent positions. Comet takes collateral onto its balance, clears debt, and absorber receives a reward from protocol reserves.

Step 2: buyCollateral. After absorb, collateral is available for purchase via buyCollateral(address asset, uint minAmount, uint baseAmount, address recipient) at below-market price—discount determined by storeFrontPriceFactor (usually 90-95% of Chainlink oracle price).

Key: profit on v3 liquidation comes from arbitrage between Comet purchase price and market price. This means bots must atomically: call buyCollateral, sell received asset on DEX, return base token. Flash loan from Aave or Uniswap v3 to finance buyCollateral is the standard pattern.

Identifying Insolvent Positions

A position is insolvent when borrowing capacity falls below debt. Compound v3 provides isLiquidatable(address account) returns (bool) and getBorrowableOf(address account, address asset, uint amount) returns (uint). Polling each of hundreds of thousands via eth_call is impractical.

Efficient approach: event-based monitoring. Listen to Supply, Withdraw, Transfer events from Comet, update local position copies. When collateral price changes (Chainlink AnswerUpdated event), recalculate health factor for positions with this collateral. Data structure: sorted set in Redis by health factor, allowing O(log n) lookup of near-liquidation positions.

Bot Architecture

Position Monitoring

Two levels: The Graph subgraph for historical data and initial load, WebSocket subscription to events via ethers.js provider.on or viem watchContractEvent for real-time. Subgraph updates with 1-3 block delay—sufficient for competitive liquidations; bots must be faster when price moves.

Chainlink price feeds via AggregatorV3Interface with updatedAt staleness check. If oracle hasn't updated beyond heartbeat period, don't use price or liquidate. Compound v3 has staleness protection itself, but bots must verify independently.

Smart Contract Liquidator

Atomic liquidation via flash loan:

contract CompoundLiquidator {
    function liquidate(
        address comet,
        address[] calldata accounts,
        address collateralAsset,
        uint baseAmount,
        address flashLoanPool  // Uniswap v3 pool
    ) external {
        // 1. Flash loan base token from Uniswap v3
        // 2. absorb(address(this), accounts)
        // 3. buyCollateral(collateralAsset, minOut, baseAmount, address(this))
        // 4. Swap collateral -> base token via DEX
        // 5. Repay flash loan + fee
        // 6. Profit goes to msg.sender or treasury
    }
}

Critical detail: absorb and buyCollateral are two separate calls. Another bot can buy collateral between them. Either verify available collateral before purchase (quoteCollateral) or accept rare reverts.

Gas Optimization and MEV

Compound liquidations on Ethereum mainnet are a competitive MEV arena. Key factors:

Factor Naive Approach Optimized
Detection Polling every 12 sec WebSocket + event-based
Submission Public mempool Flashbots bundle
Gas price Fixed Dynamic (80th percentile + boost)
Execution EOA transaction Liquidator contract (1 tx)

For Arbitrum: sequencer is centralized, MEV competition lower, but FCFS (first-come-first-served) model means latency to sequencer endpoint matters. Keep a node in same datacenter as Arbitrum sequencer.

Profitability Filter

Not every liquidatable position is profitable. Before sending, calculate:

profit = buyCollateralValue * (1 - storeFrontPriceFactor) - flashLoanFee - gasCost - swapSlippage

If profit < threshold (usually $50-100 accounting for risk), skip. Otherwise bots burn gas on unprofitable liquidations during high-fee periods.

Work Process

Compound v3 Architecture Analysis (2-3 days). Study ABI, test calls on Goerli/Sepolia, set up fork environment via Foundry anvil.

Monitoring System (1 week). Event listener, Redis for position states, health factor calculator accounting for all collateral types.

Smart Contract Liquidator (1 week). Development, unit tests in Foundry, fork-tests with real mainnet positions.

Integration and Dry-Run (3-5 days). Run in simulation mode—bot finds positions, calculates profit, but doesn't send transactions. Verify calculation accuracy.

Deployment and Monitoring (2-3 days). Deploy contract, launch bot, set up error and anomaly alerts.

Timeline Estimates

Basic bot for Compound v3 on one chain: 2.5-3 weeks. Multi-protocol bot (Compound + Aave + Euler) with MEV optimization: 6-8 weeks. Implementation for Arbitrum/Base adds 1 week per chain.

Common Mistakes

Ignoring cooldown after absorb. Compound v3 enforces internal limits on absorb frequency per account—frequent calls may revert. Need retry logic with backoff.

Incorrect minAmount calculation. buyCollateral takes minAmount collateral. Set too strictly—transaction reverts on minor oracle move. Too loosely—opens to sandwich. Dynamic calculation based on current oracle price with 1-2% buffer is correct.

Not checking protocol reserves. absorb only works if protocol has sufficient reserves for liquidator reward. Empty reserves cause revert. Check getReserves() before sending.