Note: When the market crashes, millions of dollars in positions become liquidatable on lending protocols. Bots that act first earn the liquidation bonus—up to 8% of the collateral. Others either miss out or have their transactions reverted due to price increases. Developing a flash loan liquidation bot for Aave v3 is a challenge of speed, precise calculation, and MEV strategy. Flash loans allow participation without capital: borrow an asset, liquidate, swap collateral to repay, and return the debt plus fee—all in one atomic transaction. Our engineers have over 7 years of blockchain development experience and have passed more than 100 smart contract audits. We guarantee stable operation and MEV protection. In this article, we dive into how Aave v3 liquidations work, design the bot architecture, and incorporate MEV protection.
How Liquidation Works on Aave v3
A position becomes liquidatable when the health factor drops below 1.0. Health factor = (collateral_value * liquidation_threshold) / debt_value. The liquidation threshold on Aave v3 is 82.5% for ETH and 75% for WBTC.
The liquidator calls liquidationCall(collateralAsset, debtAsset, user, debtToCover, receiveAToken). A maximum of 50% of the debt can be covered per transaction (close factor). In return, the liquidator receives collateral with a bonus—the liquidation bonus, which is 5% for ETH.
Profitability Check Before Sending a Transaction
profit = collateral_received * collateral_price
- debt_covered * debt_price
- flash_loan_fee (0.09% on Aave v3)
- swap_slippage
- gas_cost
If profit ≤ 0, we do not send the transaction. This sounds obvious, but without accurate off-chain calculations using current oracle prices and slippage, the bot loses money on every unprofitable liquidation by only paying gas. For example, liquidating a $10,000 position with a $50 gas fee can become unprofitable if slippage exceeds 0.5%.
Bot Architecture
Smart Contract Executor
A single contract that receives liquidation parameters and performs the atomic sequence:
-
flashLoan() from the Aave PoolAddressesProvider—borrow the debtAsset
- In the
executeOperation() callback, call liquidationCall
- Receive the
collateralAsset (or aToken)
- Swap
collateralAsset → debtAsset via Uniswap v3 or 1inch
- Return
debtAsset + fee to Aave
- The surplus—profit—is sent to the wallet
The contract should be non-upgradeable and have an onlyOwner modifier on the execution function. Upgradeability is not needed; simplicity and a minimal attack surface are key.
Off-Chain Monitoring
The source of position data. Three options:
-
getUserAccountData() via Multicall for a list of known borrowers—slow for many addresses
- The Graph subgraphs for Aave—index all positions, updated per block
- Direct event tracking: Borrow, Deposit, Repay events → local position state machine
The optimal setup: The Graph for initial state loading + WebSocket events for real-time updates. The list of positions with a health factor < 1.05 is checked at every new block.
| Method |
Speed |
Scalability |
Cost |
| Multicall |
Low |
Limited |
Free (query) |
| The Graph |
High |
High |
Paid (subgraph query) |
| Event-driven |
Medium |
Medium |
Free |
How to Protect Against MEV?
A liquidation bot lives in the MEV world. Sending a transaction to the public mempool with standard gasPrice allows searchers to front-run it: copy the calldata, resend with higher gas, and liquidate the position first.
Bundle simulation. Before sending, simulate the bundle via eth_callBundle—verify that by the time the block is mined, the position is still liquidatable and profit is positive. Sending bundles through Flashbots is three times more effective than public transactions on Ethereum mainnet in terms of liquidation speed.
Dynamic priority fee. On L2s (Arbitrum, Optimism, Base), MEV competition is lower due to the sequencer. Liquidations on Arbitrum are often profitable even without Flashbots. For example, on Arbitrum, liquidating a $50,000 position yields about $2,500 in fees with a gas cost of $5 — that's 500 times lower than Ethereum gas costs for a similar gain.
Typical Implementation Issues
Slippage when swapping large collateral. For large positions, swapping 1,000 ETH to USDC via a single Uniswap v3 pool causes significant price impact. Solution: split routing via the 1inch API or a custom multi-hop implementation across several pools. The optimal route calculation must be part of the off-chain profitability check.
Reorgs on L2s. Arbitrum and Optimism have finality lag. A transaction is confirmed on L2 but may later be reorged—rare, but it happens. For a liquidation bot, this is not critical (the position is either liquidated or not), but confirmations must be handled correctly.
Gas estimation. eth_estimateGas for a flash loan transaction can be off by 10-20%—external contracts behave differently. We add a 20% buffer to the estimate and verify that the transaction remains profitable after the buffer.
Stale health factor. Between calculating the health factor and sending the transaction, 1-2 blocks may pass. If the price rises during that time, the position is no longer liquidatable, and liquidationCall will revert. Add try/catch logic at the off-chain level and only pay gas for failed transactions.
What Is Included in the Work
- Architecture and documentation: data flow diagrams, contract and off-chain service descriptions.
- Smart contract: full Solidity code with Foundry tests.
- Off-chain monitoring: Node.js service with The Graph, Redis, and viem.
- MEV integration: Flashbots/MEV Blocker setup, simulation.
- Testing: fork tests on mainnet, soft launch on real data.
- Deployment and support: deploy to required chains, 2 weeks of post-launch support.
- Deliverables: full access to code repository, comprehensive documentation, and training session.
Chain Comparison for Liquidations
| Chain |
Average Gas Cost |
MEV Protection |
Liquidity |
| Ethereum |
$50-100 |
Flashbots |
High |
| Arbitrum |
$1-5 |
Sequencer |
High |
| Polygon |
$0.1-0.5 |
Low MEV |
Medium |
Development Process
Smart contract development (3-4 days). Solidity + Foundry. Fork tests on Ethereum/Arbitrum mainnet: simulate specific liquidatable positions from historical data, verify calculation correctness and profit.
Off-chain monitoring (4-6 days). Node.js/TypeScript, viem for on-chain interaction, The Graph SDK, WebSocket block subscriptions, Redis for position state storage.
MEV integration (2-3 days). Flashbots SDK, bundle building, pre-submission simulation.
Testnet + mainnet soft launch (3-5 days). Start with a Sepolia fork, then mainnet with minimal capital—a few real liquidations to calibrate profitability parameters.
Timeline Estimates
A basic liquidation system for one protocol (Aave v3) on one chain: 1-2 weeks. Multi-protocol (Aave + Compound + Morpho) with multi-chain support: from 3-4 weeks. Timelines depend on MEV protection requirements and the number of target protocols. The cost to build a basic bot starts at $5,000, with potential earnings of thousands per liquidation. Contact us to discuss your project and get a preliminary estimate. Our team has over 5 years of market presence, 7+ years of blockchain experience, and 50+ DeFi projects completed. Order a turnkey bot with full documentation.
DeFi Protocol Development
We design modular DeFi protocols where the math of stablecoins, liquidity, and oracles works flawlessly. Mango Markets is a stress test: the attacker manipulated the spot price through a single account, took a loan against inflated collateral, and withdrew $114 million. The oracle took the price from a single source without TWAP. Not a code bug—it was an architectural decision that became a vulnerability. Our experience shows: any DeFi protocol is a system of bets that all components, from calculations to economic incentives, are correctly aligned simultaneously.
We don't write code under the 'if it works, don't touch it' mindset. We model stress scenarios: cascading liquidations, depegs, flash loans. Only then do we build events that won't break the protocol.
Why are oracles a critical component of DeFi?
Most major DeFi hacks started with oracle manipulation. Let's break down the three layers we use in every project.
Spot price as oracle—not an option. Uniswap v2 spot price can be shifted by a flash loan in one transaction. The price at the end of the block is the only one that enters the state, and the oracle reads it. Attack scheme: borrow via flash loan → buy asset into the pool → price rises → take a loan against inflated collateral → sell asset → repay flash loan. One transaction.
TWAP as protection. Uniswap v3 observe() averages the price over a period (30 minutes). Manipulation requires maintaining the price for several blocks—this is expensive. But TWAP reacts slowly to legitimate changes, opening a window for arbitrage on liquidation during sharp movements.
Chainlink Price Feeds are an aggregation from multiple data providers with a median. Standard for lending. Problem: heartbeat 1–24 hours and deviation threshold 0.5%. If the price doesn't move, the feed may not update for a day. In volatile markets—lag.
| Oracle |
Mechanism |
Manipulation Protection |
Latency |
| Chainlink |
Median from independent providers |
High (decentralization) |
Up to 24h at 0% movement |
| Uniswap v3 TWAP |
Average price over N blocks |
High (hard to maintain) |
30 min – 1 h |
| Pyth Network |
Cross-chain low-latency |
Medium (dependent on publisher) |
Seconds |
In production, we use a two-tier check: Chainlink aggregator + Uniswap v3 TWAP as a verifier. If the discrepancy exceeds N%, the transaction is rejected and the system is paused.
How to protect a DeFi protocol from flash loan attacks?
Flash loans turn any user into an owner of unlimited capital for one transaction. Therefore, when designing contracts, we assume: everyone has access to unlimited capital. This completely changes the threat model.
Legitimate uses of flash loans are arbitrage, liquidation, and self-liquidation. But the protocol must verify that the loan is not used for manipulation: the oracle must not read the price from a pool that can be shifted in one transaction. We add checks on block.timestamp and minimum liquidity depth.
Key Components of DeFi Architecture
| Protocol Type |
Core Mechanism |
Main Risk |
| DEX (AMM) |
x*y=k or concentrated liquidity |
impermanent loss, oracle manipulation |
| Lending |
collateral ratio, liquidation |
bad debt during cascading liquidations |
| Yield aggregator |
auto-compounding strategies |
rug via strategy upgrade |
| Derivatives / Perps |
funding rate, mark price |
liquidation cascades, socialized losses |
| Liquid staking |
stETH-style rebasing |
depegging on mass unstake |
AMM: From x*y=k to Concentrated Liquidity
Uniswap v2 uses x * y = k. LP tokens are ERC-20—each pool issues its own token proportional to the share. Problem: liquidity is spread across the entire curve, most of it unused.
Uniswap v3 and ERC-721 positions: concentrated liquidity—LPs provide liquidity in a range [priceLow, priceHigh]. Capital efficiency up to 4000x for stable pairs. But ERC-721 breaks vault strategies built for ERC-20. Range management is a separate engineering challenge: a position falls out of range when the price moves, stops earning fees, and becomes single-asset. Protocols like Arrakis Finance automatically rebalance. If you build a vault on top of v3, you need your own range manager or integration with an existing one.
Slippage in v3 is calculated via sqrtPriceX96—96-bit fixed-point math. Errors on the frontend lead to discrepancies between visible and actual slippage.
Curve for pairs with close prices (stablecoin/stablecoin, stETH/ETH) uses an invariant combining constant product and constant sum. Lower slippage within the peg range. Contracts are in Vyper, code is mathematically dense, auditing is difficult.
Lending Protocols: Collateral, Liquidation, Bad Debt
LTV defines the maximum loan against collateral. Liquidation threshold is the level for liquidation. The difference is the buffer for the liquidator. Typical example: LTV 75%, liquidation threshold 80%, bonus 5%. If the price drops 20%+, the position is open for liquidation.
Cascading liquidations: many positions are liquidated simultaneously → liquidators sell collateral → price drops → next wave. LUNA/UST 2022 is a classic cascade.
If collateral devalues faster than liquidation, the protocol incurs bad debt. Aave uses a Safety Module (staked AAVE), Compound uses reserves. Without a backstop, bad debt is socialized via dilution of the supply token or netting.
Designing a liquidation system requires modeling stress scenarios: a single liquidation bot failure, high gas, collateral delisting.
Yield Farming and Incentive Mechanics
Liquidity mining distributes governance tokens to LP providers. Problem: mercenary capital—farmers come, sell tokens, leave. TVL is illusory.
Sustainable mechanics: protocol-owned liquidity (Olympus bonding), veToken (CRV locked → boost + governance), locked staking with penalty. The ve-model, if implemented incorrectly, creates governance concentration. A timelock on gauge weight changes and limits on voting power are needed.
What Our DeFi Protocol Development Includes
- Architectural documentation: contract interaction diagrams, liquidation stress tests, oracle calculations.
- Implementation in Solidity 0.8.x with OpenZeppelin 5.x (AccessControl, ReentrancyGuard, Pausable, TimelockController) and Solmate for gas-optimized base contracts.
- Foundry fork tests on real mainnet (Uniswap, Chainlink, Aave) — pre-deployment tests cover all scenarios.
- Audit: at least two independent auditors for TVL over $1M. Code4rena or Sherlock for bug bounty.
- Deployment with Gnosis Safe 3/5 multisig + timelock 48–72 hours.
- Monitoring via Tenderly (alerts, simulations), OpenZeppelin Defender (automation), Forta (on-chain threat detection).
- Post-launch support: updates, patches, upgrades via proxy.
Our Expertise and Experience
We have been developing DeFi protocols since 2020, delivering 30+ projects with a combined TVL of over $150 million. Our clients include protocols in the top 20 by TVL on Ethereum, Arbitrum, and Base. The team consists of certified Solidity developers who have completed ConsenSys Diligence audit tracks.
DeFi basic principles that we apply in practice.
Timelines
- DEX with AMM (Uniswap v2 fork): 6–10 weeks
- Lending protocol (Aave-style, single collateral): 3–5 months
- Yield aggregator with multiple strategies: 2–4 months
- Full-fledged DeFi protocol with governance: 5–8 months including audit
Cost is calculated individually—contact us for a project estimate.
Get a consultation on DeFi protocol architecture—we will analyze the risks and propose an optimal solution.