Keepers are automated agents that perform critical, time-sensitive tasks to maintain protocol solvency and user functionality. Their execution is essential for the correct operation of on-chain derivatives systems.
The Role of Keepers in DeFi Derivatives Protocols
Core Functions of a Keeper
Liquidation
Liquidation is the process of closing an undercollateralized position to protect the protocol from bad debt.
- Monitors positions against maintenance margin ratios in real-time.
- Executes a forced closure when collateral falls below the threshold, auctioning the position.
- This function is the primary defense for protocol solvency and protects other users from systemic risk.
Funding Rate Settlement
Funding rate settlement periodically exchanges payments between long and short traders to peg perpetual contracts to the spot price.
- Calculates and applies funding payments at predetermined intervals (e.g., hourly).
- Initiates the transfer of funds from one side of the market to the other.
- This mechanism is critical for maintaining the price peg of perpetual futures without an expiry date.
Oracle Price Updates
Oracle price updates involve fetching and submitting accurate external price data to the protocol's on-chain storage.
- Pulls price feeds from decentralized oracle networks or specific APIs.
- Submits transactions to update the protocol's price feed, often with a time-based heartbeat.
- Accurate and timely price data is foundational for all other keeper functions like liquidations and funding.
Limit Order Execution
Limit order execution fulfills user-placed conditional orders when market conditions are met.
- Watches the order book or market price for trigger conditions (e.g., stop-loss, take-profit).
- Submits a market order on behalf of the user once the trigger price is hit.
- This provides advanced trading functionality and risk management tools for DeFi derivatives users.
Insurance Fund Rebalancing
Insurance fund rebalancing manages the protocol's reserve capital used to cover liquidation shortfalls.
- Automatically allocates a portion of liquidation penalties and fees to the insurance pool.
- May execute strategies to grow the fund's assets, such as yield farming with stablecoins.
- A well-capitalized insurance fund enhances protocol resilience and user confidence during volatile markets.
Settlement & Expiry
Settlement & expiry handles the finalization of time-based derivative contracts, such as futures or options.
- On the expiry timestamp, determines the final settlement price from an oracle.
- Calculates final P&L and facilitates the transfer of collateral between counterparties.
- This ensures the deterministic and trustless conclusion of dated contracts, enabling complex financial instruments.
How a Keeper Executes a Liquidation
Process overview
Monitor Positions and Check Health
Continuously scan the protocol for undercollateralized positions.
Detailed Instructions
A keeper's primary task is to monitor the health factor or margin ratio of all open positions. This is done by subscribing to on-chain events or polling the protocol's smart contracts. The keeper calculates the current value of the position's collateral and debt, factoring in real-time oracle prices. A position becomes eligible for liquidation when its health factor falls below a predefined threshold, such as 1.0 in Aave or a 110% maintenance margin in perpetual protocols.
- Sub-step 1: Query the protocol's
getAccountLiquidity(address user)orgetPositionInfo(uint256 positionId)function. - Sub-step 2: Fetch the latest price feeds from the designated oracles (e.g., Chainlink's
latestAnswer()). - Sub-step 3: Compute the health factor:
(Collateral Value * Liquidation Threshold) / Borrowed Value.
javascript// Pseudo-code for health check const position = await protocolContract.getPosition(positionId); const price = await oracleContract.latestAnswer(); const collateralValue = position.collateralAmount * price; const healthFactor = (collateralValue * LIQUIDATION_THRESHOLD) / position.debtValue; if (healthFactor < 1.0) { // Position is liquidatable }
Tip: Use a dedicated RPC provider with low latency and high request limits to monitor efficiently.
Calculate Liquidation Parameters
Determine the exact amount to liquidate and the associated bonus.
Detailed Instructions
Once a liquidatable position is identified, the keeper must compute the precise liquidation amount and the liquidation bonus (or penalty). Protocols define a maximum liquidation percentage per transaction (e.g., 50% of the debt) and a bonus for the liquidator, often as a discount on the seized collateral. The keeper calculates the debt to be repaid and the corresponding collateral to be claimed, ensuring the transaction remains profitable after gas costs.
- Sub-step 1: Determine the
closeFactor– the maximum portion of the debt that can be liquidated in one call. - Sub-step 2: Calculate the
liquidationBonusfrom the protocol's parameters, e.g., a 10% bonus means you receive $1.10 of collateral for $1.00 of debt repaid. - Sub-step 3: Factor in the current gas price on the network to estimate net profit:
(Collateral Seized - Debt Repaid) - Transaction Cost.
solidity// Example from a typical liquidation function interface function liquidate( address borrower, uint256 repayAmount, address collateralAsset ) external returns (uint256 seizedCollateral) { // Logic calculates seizedCollateral = repayAmount * (1 + liquidationBonus) / collateralPrice }
Tip: Use a gas estimation library and a profitability model to filter out marginal opportunities.
Simulate and Submit the Transaction
Test the transaction locally and broadcast it to the network.
Detailed Instructions
Before committing capital, the keeper must simulate the liquidation transaction using eth_call or a forked network to verify success and final profit. This step checks for slippage, front-running, and reverts due to stale oracle data or changing state. After a successful simulation, the keeper constructs and signs the transaction, often using a private mempool or a direct RPC call to minimize latency and avoid public mempool sniping.
- Sub-step 1: Use
eth_callwith the latest block state to execute theliquidate()function call without broadcasting. - Sub-step 2: Parse the simulation result to confirm the exact amount of collateral to be received and check for any errors.
- Sub-step 3: Build the final transaction with an optimized gas price and a specific nonce, then sign it with the keeper's private key.
bash# Example using cast from Foundry for simulation cast call <PROTOCOL_ADDRESS> \ "liquidate(address,uint256,address)(uint256)" \ $BORROWER $REPAY_AMOUNT $COLLATERAL_ASSET \ --rpc-url $RPC_URL
Tip: Implement a transaction bundling strategy to batch multiple liquidations in a single transaction when possible.
Handle Transaction Outcome and Post-Liquidation State
Monitor the transaction receipt and update internal tracking.
Detailed Instructions
After broadcasting, the keeper monitors the transaction receipt for confirmation. A successful liquidation will emit specific events (e.g., LiquidationCall). The keeper must then update its internal state, tracking the seized collateral and any protocol-native rewards (like liquidation fees in a governance token). It's also crucial to verify the post-liquidation health of the position; if it remains undercollateralized, it may be eligible for another liquidation immediately.
- Sub-step 1: Wait for the transaction receipt and confirm a status of
1(success). Decode emitted logs to capture exact amounts. - Sub-step 2: Transfer the received collateral (and any rewards) from the keeper contract to a secure vault.
- Sub-step 3: Re-check the position's health factor to see if a follow-up liquidation is necessary.
solidity// Event emitted by many protocols event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator );
Tip: Implement robust error handling for failed transactions, including gas estimation failures and reverts due to race conditions.
Keeper Requirements Across Major Protocols
Comparison of technical and economic specifications for keepers across leading DeFi derivatives platforms.
| Requirement | GMX (V1/V2) | Synthetix Perps | dYdX (v4) | Hyperliquid |
|---|---|---|---|---|
Minimum Collateral (Gas) | ~0.1-0.3 ETH | ~0.1-0.2 ETH | ~0.05-0.15 ETH | ~0.01-0.05 ETH |
Execution Fee Model | Dynamic (gas + priority) | Dynamic (gas + priority) | Fixed + Gas Rebate | Dynamic (gas + priority) |
Liquidation Fee | 10% of position size | SNX staker incentive | 1.5% of position size | 5% of position size |
Key Function | Liquidations, Price Updates | Liquidations, Pyth Updates | Order Matching, Liquidations | Liquidations, Funding Rate Updates |
Typical Execution Window | < 5 minutes | < 10 minutes | < 1 block | < 2 minutes |
Required Monitoring | Chain health, Oracle deviation | Pyth price feeds, C-Ratio | Orderbook state, Oracle price | Oracle price, Funding rate |
Profitability Drivers | Liquidation bounty, GLP rewards | sUSD debt pool rewards | Gas rebates, Fee sharing | Liquidation bounty, Protocol fees |
Types of Keepers and Their Incentives
Understanding Keeper Roles
Keepers are automated bots or individuals who perform critical, time-sensitive tasks for DeFi protocols. Their work ensures the system functions correctly and remains solvent. Think of them as the maintenance crew for complex financial machines, executing orders that regular users cannot or do not want to handle manually.
Key Keeper Types
- Liquidators: These keepers monitor undercollateralized loans on protocols like Aave or Compound. When a loan's collateral value falls below a required threshold, they repay the debt and seize the collateral at a discount, profiting from the spread. This action protects the protocol from bad debt.
- Arbitrageurs: They exploit price differences for the same asset across different markets or layers. For example, a keeper might buy ETH on a DEX where it's cheaper and instantly sell it on a perpetual futures platform like dYdX where it's more expensive, earning a risk-free profit while helping to align prices.
- Settlers/Executors: These keepers trigger the final settlement of expiring contracts or execute limit orders. In an options protocol like Lyra, a keeper would call the
settleOptionfunction when an option reaches expiry to determine payouts for holders.
Why They Matter
Without keepers, DeFi protocols would accumulate bad debt from unpaid loans, suffer from persistent price inefficiencies, and fail to execute time-dependent logic. Their financial incentives are the engine that keeps the system secure and efficient.
Technical Challenges for Keepers
Automated keepers face significant operational hurdles requiring robust infrastructure and sophisticated strategies to remain profitable and reliable.
Gas Price Volatility
Gas auctions create unpredictable costs for transaction inclusion. Keepers must implement dynamic bidding strategies, often using tools like Flashbots to submit bundles. High volatility can turn a profitable opportunity into a net loss if not managed precisely, requiring constant network monitoring and adaptive algorithms.
Frontrunning & MEV
Maximal Extractable Value (MEV) creates a competitive environment where keepers race to capture value from pending transactions. They must run searcher bots and use private mempools to avoid being frontrun. This technical arms race demands significant R&D to identify and execute profitable opportunities before competitors.
Infrastructure Reliability
Node uptime and latency are critical. A single point of failure in RPC providers or block builders can cause missed opportunities. Keepers require redundant, geographically distributed node infrastructure with low-latency connections to multiple networks to ensure consistent execution and monitor for liquidations or funding rate updates.
Smart Contract Risk
Interacting with unaudited or upgraded protocol contracts introduces execution risk. Keepers must monitor for governance proposals and contract deployments, thoroughly test integration updates, and implement circuit breakers. A bug or unexpected state change in a derivative protocol can lead to failed transactions or financial loss for the keeper.
Cross-Chain Complexity
Multi-chain deployments of derivatives protocols force keepers to operate across several ecosystems. This multiplies infrastructure needs, requires managing separate gas token balances, and introduces bridging delays for capital allocation. Monitoring and executing on chains like Arbitrum, Optimism, and Base simultaneously is a significant operational challenge.
Oracle Manipulation
Oracle price feeds are a core dependency for triggering liquidation and funding payments. Keepers must assess the robustness of each protocol's oracle setup, watch for potential latency or manipulation attempts, and have fallback data sources. Incorrect price data can trigger unnecessary, unprofitable transactions or cause missed critical actions.
How to Run a Basic Keeper Bot
Process overview for monitoring and executing on-chain actions for a DeFi derivatives protocol.
Set Up Your Development Environment
Prepare the necessary tools and dependencies for bot development.
Detailed Instructions
Begin by installing Node.js (v18 or later) and a package manager like npm or yarn. Initialize a new project and install essential libraries: ethers.js or viem for blockchain interaction, dotenv for managing private keys, and a task scheduler like node-cron. You will also need access to a JSON-RPC provider; sign up for a service like Alchemy or Infura to get a reliable endpoint. Store your provider URL and wallet private key securely in a .env file, never committing it to version control. This foundational setup ensures your bot can connect to the network and sign transactions.
- Sub-step 1: Install Node.js and initialize a new project directory.
- Sub-step 2: Install required packages:
npm install ethers dotenv node-cron. - Sub-step 3: Create a
.envfile with variablesRPC_URLandPRIVATE_KEY. - Sub-step 4: Obtain a free RPC endpoint from a provider like Alchemy.
javascript// Example .env file structure RPC_URL="https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY" PRIVATE_KEY="0xabc123..."
Tip: Use a dedicated wallet with minimal funds for bot operations to limit risk.
Connect to the Protocol and Define Your Watch Logic
Instantiate contract interfaces and codify the conditions for execution.
Detailed Instructions
Using your provider, connect to the target blockchain. Import the Application Binary Interface (ABI) for the specific derivatives protocol contracts you intend to interact with, such as a liquidation engine or a limit order book. Use ethers.Contract to create instances. Your core logic must repeatedly check for specific on-chain states. For a liquidation bot, this involves querying user account health (e.g., checking if the health factor is below 1.0). For an order book, monitor pending orders that are executable given the current market price. Define these conditions in a function that returns a boolean. This function is the brain of your keeper, determining when an opportunity exists.
- Sub-step 1: Obtain the contract ABI from the protocol's verified source on Etherscan.
- Sub-step 2: Instantiate the contract:
const contract = new ethers.Contract(address, abi, provider). - Sub-step 3: Write an async function
checkOpportunity()that fetches relevant data and evaluates your condition. - Sub-step 4: Log the result of each check for monitoring.
javascript// Example check for a liquidation condition async function checkLiquidation(userAddress) { const healthFactor = await vaultContract.healthFactor(userAddress); return healthFactor.lt(ethers.utils.parseUnits("1.0", 18)); // Returns true if < 1.0 }
Tip: Batch multiple user checks into a single multicall to save on RPC requests and costs.
Construct and Send the Execution Transaction
Build, gas-optimize, and broadcast the transaction when conditions are met.
Detailed Instructions
When checkOpportunity() returns true, your bot must construct the execution transaction. Connect your wallet using a signer object. Build the transaction data by calling the appropriate contract function, such as liquidate(address user) or executeOrder(uint256 orderId). Critical at this stage is gas estimation and optimization. Use contract.estimateGas to predict costs and set a gasLimit with a buffer. For competitiveness, implement a dynamic gas price strategy using provider.getGasPrice() and adding a premium. Finally, send the transaction using contract.connect(signer).functionName(...args, { gasLimit, gasPrice }). Always capture the transaction hash for tracking.
- Sub-step 1: Create a signer:
const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider). - Sub-step 2: Estimate gas for the target function call to avoid out-of-gas errors.
- Sub-step 3: Fetch current gas price and add a tip (e.g., 10%) for priority.
- Sub-step 4: Send the transaction and immediately log the hash to the console.
javascript// Example transaction execution const tx = await liquidationContract .connect(signer) .liquidate(unsafeUser, { gasLimit: 500000, gasPrice: estimatedGasPrice }); console.log(`Tx Hash: ${tx.hash}`);
Tip: Consider using EIP-1559 transaction types (
maxFeePerGasandmaxPriorityFeePerGas) for more efficient gas pricing on Ethereum.
Implement Scheduling, Error Handling, and Monitoring
Create a robust loop to run checks and manage failures.
Detailed Instructions
A keeper bot must run continuously. Use node-cron or a simple setInterval to poll the blockchain at regular intervals (e.g., every 15 seconds). Wrap your entire check-and-execute logic in a try-catch block to handle RPC errors, failed transactions, or unexpected reverts. Log all errors and successful executions to a file or external service for post-mortem analysis. Implement basic alerting, such as sending a Discord webhook notification on a failed transaction. To prevent duplicate executions, your bot should track pending transactions and wait for confirmations. Finally, monitor your bot's wallet balance and gas costs to ensure it remains operational.
- Sub-step 1: Set up a cron job to run your main function every 15 seconds.
- Sub-step 2: Enclose the core logic in try-catch and log errors with timestamps.
- Sub-step 3: After sending a tx, wait for 1-2 confirmations before considering the action complete.
- Sub-step 4: Set up a simple balance check to alert if funds are low.
javascript// Basic scheduling and error handling structure cron.schedule('*/15 * * * * *', async () => { try { const opportunity = await checkOpportunity(); if (opportunity) { await executeTransaction(); } } catch (error) { console.error(`[${new Date().toISOString()}] Error:`, error); } });
Tip: Use a process manager like PM2 to keep your bot running and restart it on crashes.
Keeper Operations and Economics FAQ
Keepers execute on-chain transactions to maintain protocol state and user positions. Their core functions include liquidating undercollateralized positions when the collateral value falls below the maintenance margin, triggering settlement of expired perpetual contracts or options, and performing funding rate payments to balance perpetual markets. For example, a keeper might call a liquidatePosition() function when a user's ETH collateral drops 10% below the required threshold, earning a liquidation fee of 0.5-2% of the position size. They also handle order matching in limit order books and oracle price updates for specific architectures.