ChainScore Labs
All Guides

The Role of Keepers and Bots in DeFi

LABS

The Role of Keepers and Bots in DeFi

An examination of the automated agents that power decentralized finance protocols, from liquidations to arbitrage.
Chainscore © 2025

Core Automated Agents in DeFi

An overview of the automated entities that perform critical, time-sensitive tasks to maintain the health, efficiency, and security of decentralized finance protocols without human intervention.

Liquidation Bots

Liquidation Bots are automated agents that monitor lending protocols for undercollateralized positions. They execute liquidations to protect the protocol from bad debt, ensuring system solvency.

  • Monitor loan-to-value ratios in real-time on platforms like Aave and Compound.
  • Execute profitable liquidations by repaying the borrowed assets and seizing the collateral, often earning a bonus.
  • Maintain protocol health by preventing systemic risk, which directly protects user deposits and maintains stable interest rates.

Arbitrage Bots

Arbitrage Bots exploit price discrepancies for the same asset across different decentralized exchanges (DEXs) or between centralized and decentralized venues.

  • Identify price differences across pools on Uniswap, SushiSwap, and centralized exchanges.
  • Execute instant trades to buy low on one venue and sell high on another, profiting from the spread.
  • Enforce price efficiency across the DeFi ecosystem, which helps stabilize asset prices and reduces slippage for all traders.

Keeper Networks (e.g., Chainlink Keepers)

Keeper Networks are decentralized services that provide reliable, trust-minimized automation for smart contracts that require external execution to perform key functions.

  • Automate contract upkeep for tasks like harvesting yield, rebalancing portfolios, or triggering limit orders.
  • Use decentralized node operators to ensure uptime and censorship resistance, unlike a single bot.
  • Enable advanced DeFi products like yield optimizers (Yearn) and auto-compounding vaults, which would be impractical to run manually.

MEV (Maximal Extractable Value) Bots

MEV Bots are sophisticated agents that search for and extract value by influencing the order, inclusion, or exclusion of transactions within a block.

  • Perform complex strategies like front-running, back-running, and sandwich attacks on pending user transactions.
  • Utilize private transaction pools and advanced algorithms to gain a competitive edge in block production.
  • Represent a double-edged sword: while they can provide liquidity and efficient price discovery, they also pose risks of network congestion and unfair user exploitation.

Automated Market Makers (AMM) Bots

AMM Bots are specialized agents that provide liquidity to automated market maker pools, dynamically managing their capital to maximize fees and minimize impermanent loss.

  • Deposit and rebalance liquidity across different price ranges (concentrated liquidity on Uniswap V3).
  • Optimize fee earnings by algorithmically adjusting positions based on market volatility and trading volume.
  • Are essential for deep liquidity in DEXs, which lowers trading costs and slippage, making DeFi markets more efficient for all participants.

How a Keeper Network Operates

A detailed breakdown of the automated processes and key actors that maintain and execute critical functions within Decentralized Finance protocols.

1

Monitoring and Trigger Detection

Keepers and bots continuously scan the blockchain for specific conditions that require an on-chain action.

Detailed Instructions

Keeper bots operate by constantly listening to blockchain events and querying smart contract states. They are programmed to identify precise trigger conditions, such as a loan's collateral ratio falling below a liquidation threshold (e.g., 110% for a MakerDAO Vault) or a limit order price being met on a DEX. This involves subscribing to events via a node provider like Infura or Alchemy and parsing transaction mempools.

  • Sub-step 1: Subscribe to Events: Connect to an Ethereum node via WebSocket and listen for specific event logs (e.g., LogNote for MakerDAO actions).
  • Sub-step 2: Poll Contract State: Regularly call view functions on target contracts to check key values, such as getCollateralRatio(address vault).
  • Sub-step 3: Calculate Profitability: Before acting, the bot estimates gas costs and potential rewards to ensure the transaction is economically viable, a process known as Maximal Extractable Value (MEV).

Tip: Use a service like Tenderly to simulate transactions off-chain first to verify gas estimates and success conditions without spending real ETH.

2

Transaction Construction and Simulation

Once a trigger is detected, the keeper constructs, simulates, and signs the necessary transaction.

Detailed Instructions

After identifying a profitable opportunity, the keeper bot must build a transaction that will execute the desired on-chain function. This involves encoding the correct function call with the right parameters. For a liquidation on Aave, this would be calling liquidationCall() with the specific collateral asset, debt asset, user address, and debt to cover. The transaction is then simulated in a local environment to ensure it will succeed and be profitable.

  • Sub-step 1: Encode Calldata: Use a library like ethers.js to encode the function call. For example: const data = contract.interface.encodeFunctionData('liquidationCall', [collateralAsset, debtAsset, user, debtToCover, false]);
  • Sub-step 2: Estimate Gas: Call eth_estimateGas on the constructed transaction to get a gas estimate, adding a buffer (e.g., 20%) for safety.
  • Sub-step 3: Set Gas Price: Query an oracle like ETH Gas Station or use a dynamic fee estimator (EIP-1559) to set a competitive maxFeePerGas and maxPriorityFeePerGas.

Tip: Always simulate with a forked mainnet using Hardhat or Ganache to catch unexpected reverts and avoid wasting gas on failed transactions.

3

Transaction Submission and Race Execution

The signed transaction is broadcast to the network, often in a competitive environment with other keepers.

Detailed Instructions

This is the most critical and competitive phase. Multiple keepers may have identified the same opportunity, leading to a gas auction where bots compete by submitting transactions with increasingly higher gas prices to get their transaction mined first. The keeper must manage its private key securely and broadcast the transaction via a reliable connection to multiple nodes or a service like Flashbots to avoid front-running.

  • Sub-step 1: Sign Transaction: Securely sign the raw transaction using the keeper's private key. Never expose this key in client-side code.
  • Sub-step 2: Choose Broadcast Method: For standard execution, send via eth_sendRawTransaction. For MEV-sensitive actions, use a private transaction relay like Flashbots to submit a bundle directly to miners/validators.
  • Sub-step 3: Monitor Inclusion: Track the transaction hash. If it's stuck, the keeper may need to replace-by-fee (RBF) by resubmitting with a higher gas price.

Tip: For time-sensitive actions like liquidations, consider using a Keeper Network like Chainlink Keepers or Gelato, which handle the infrastructure, reliability, and gas cost management for you.

4

Post-Execution Verification and Reward Collection

After the transaction is mined, the keeper verifies the outcome and claims any earned rewards or fees.

Detailed Instructions

A successful on-chain execution is not the final step. The keeper must verify that the transaction achieved its intended state change and then collect its incentive. This reward is often a percentage of the liquidated collateral or a fixed fee paid by the protocol. The keeper's software must listen for the completion event and may need to call a separate function to claim accrued rewards from a reward distributor contract.

  • Sub-step 1: Confirm State Change: Query the relevant contract after the block is confirmed to ensure the action was successful (e.g., the user's debt is now zero).
  • Sub-step 2: Claim Rewards: If rewards are not sent automatically, call the claim function. For example, on a keeper network registry: await keeperRegistry.claimRewards(keeperAddress);
  • Sub-step 3: Reconcile and Report: Update internal accounting logs, subtract gas costs from the gross reward to calculate net profit, and alert the operator of the result.

Tip: Automate reward claiming to a regular schedule to avoid leaving funds idle in smart contracts, but be mindful of gas costs for the claim transaction itself.

Comparing DeFi Automation Agents

Comparison of the roles, capabilities, and operational models of Keepers and Bots in Decentralized Finance.

Agent TypePrimary RoleExecution TriggerCost ModelExample Protocol

Keeper (e.g., Chainlink)

Maintain protocol health & execute predefined functions

Time-based or condition-based off-chain monitoring

Gas reimbursement + premium (bounty)

MakerDAO (Liquidations)

Arbitrage Bot

Capture price differences across DEXs

Real-time on-chain price feed discrepancies

Gas costs + profit share model

Various DEXs (Uniswap, SushiSwap)

Liquidation Bot

Liquidate undercollateralized positions

Health factor falls below threshold

Gas costs + liquidation bonus

Aave, Compound

MEV Searcher Bot

Extract value by reordering transactions

Mempool transaction analysis

Gas auction (priority fee) + profit

Ethereum block builders

Yield Farming Bot

Automate deposit/withdraw to optimize yields

APR/APY changes across pools

Gas costs + performance fee

Yearn Finance, Beefy Finance

Limit Order Bot

Execute trades at specified price points

Market price reaches target level

Gas costs + possible service fee

1inch Limit Orders, Gelato

Rebalancing Bot

Maintain target portfolio allocations

Deviation from target allocation percentage

Subscription fee + gas costs

TokenSets, DeFi Saver

Building and Interacting with Keepers

Getting Started with Keepers

A keeper is an automated bot or script that performs predefined tasks on a blockchain when specific conditions are met. In DeFi, they are essential for maintaining protocol health by executing functions that are too costly, time-sensitive, or repetitive for users to do manually. Think of them as the automated maintenance crew of the decentralized world.

Key Responsibilities

  • Liquidation: When a loan on a lending protocol like Aave becomes undercollateralized, a keeper automatically liquidates the position to protect the protocol's solvency.
  • Rebalancing: In automated market maker (AMM) pools like Uniswap, keepers help rebalance liquidity or arbitrage price differences across exchanges.
  • Triggering Updates: They call functions to update oracle prices (e.g., from Chainlink) or execute limit orders on DEX aggregators like 1inch.

Real-World Example

When using a yield aggregator like Yearn Finance, keepers automatically harvest rewards, compound them, and reallocate funds to the most profitable strategies, saving users significant time and gas fees.

Essential Keeper Infrastructure

An overview of the automated agents and bots that perform critical, time-sensitive tasks to maintain the health, efficiency, and security of decentralized finance protocols.

Liquidation Bots

Liquidation Bots are automated programs that monitor undercollateralized loans and execute liquidations to protect lending protocols. They ensure the solvency of the system by selling a borrower's collateral when its value falls below a required threshold.

  • Monitor loan-to-value ratios in real-time across protocols like Aave and Compound.
  • Execute profitable transactions by paying back the bad debt and seizing collateral in a single atomic transaction.
  • Why this matters for users: They protect lenders from losses and maintain overall protocol stability, but can also cause cascading market sell-offs during volatility.

Rebalancing Keepers

Rebalancing Keepers are agents that automatically adjust portfolio allocations within DeFi vaults and index products to maintain a target strategy. They execute swaps and deposits to keep asset weights in line with the intended financial model.

  • Maintain index fund compositions for products like Index Coop's DPI or Set Protocol's tokens.
  • Execute arbitrage to correct price deviations between a vault's components and the open market.
  • Why this matters for users: They provide hands-off, optimized yield and risk exposure, automating complex strategies that would be costly and slow to perform manually.

Oracle Update Keepers

Oracle Update Keepers are bots responsible for pushing fresh, accurate price data from external sources onto the blockchain. They are a critical security component, as many protocols rely on this data for valuations and trigger conditions.

  • Fetch data from centralized and decentralized exchanges to update price feeds like Chainlink or MakerDAO's Oracles.
  • Submit transactions on-chain when price deviations exceed a specified threshold.
  • Why this matters for users: They prevent manipulation and ensure that liquidations, minting, and redemptions are based on accurate market prices, securing billions in user funds.

Limit Order Bots

Limit Order Bots provide automated order book functionality on decentralized exchanges (DEXs) that typically only support instant swaps. They watch the market and execute trades when specified price conditions are met, bridging a gap with centralized exchanges.

  • Monitor market prices on DEXs like Uniswap and execute swaps when a token hits a target price.
  • Manage gas fees strategically, often batching transactions to optimize profitability.
  • Why this matters for users: They enable advanced trading strategies like stop-losses and take-profit orders, granting traders more control and efficiency in a decentralized environment.

Yield Harvesting Bots

Yield Harvesting Bots automate the process of claiming, compounding, and reinvesting reward tokens from liquidity pools and farm incentives. They optimize returns by frequently converting rewards into more productive assets.

  • Claim rewards from staking contracts and liquidity pools on platforms like Curve or SushiSwap.
  • Compound yields by automatically swapping earned tokens and re-staking them to benefit from exponential growth.
  • Why this matters for users: They maximize APY by minimizing idle capital and transaction overhead, though they must carefully manage gas costs to remain profitable.

Insurance Claim Processors

Insurance Claim Processors are specialized keepers that verify and execute payouts for decentralized insurance protocols. They assess whether a covered smart contract failure or hack has occurred and trigger the release of funds from a shared pool.

  • Verify claim validity against predefined parameters and oracle data for protocols like Nexus Mutual or InsurAce.
  • Initiate automated payouts to policyholders once a claim is approved by governance or a consensus mechanism.
  • Why this matters for users: They provide trustless and timely compensation for losses, which is fundamental for risk management and broader DeFi adoption.
SECTION-FAQ

Keeper Economics and Risks

Ready to Start Building?

Let's bring your Web3 vision to life.

From concept to deployment, ChainScore helps you architect, build, and scale secure blockchain solutions.