linkedin logogithub logo
December 2, 2024

How to Make a Liquidation Bot

Key Points
  • Understanding Liquidations in DeFi Lending Protocols
  • Designing the Liquidation Bot
  • Anticipating Price Changes for Efficiency

Introduction

In the DeFi ecosystem, liquidation is a mechanism for ensuring the solvency and stability of financial protocols. 

One of the most common cases for liquidations is in lending protocols, which allow users to deposit cryptocurrencies as collateral to borrow funds or to lend their assets in exchange for interest. In these cases, liquidation is the process of repaying a borrower’s debt on their behalf in exchange for a portion of their collateral. Without liquidations, the protocol could become insolvent for its users. 

Liquidators are incentivized to continuously look for loans eligible for liquidation to keep the lending network healthy and prevent bad debt (Hatom Docs).

In this article, we will explore how liquidations work within lending protocols and the basics of implementing a liquidation bot, which will be able to automate the detection of risky positions and execute liquidations. As a practical reference, we’ll use the Hatom Lending Protocol on the MultiversX blockchain.

Design Fundamentals

To define the functionality of the bot, a series of evaluations about its environment and desired objectives must be conducted. For instance, determining the protocol it will interact with, the blockchain it will operate on, the number of account positions it is expected to process, and the conditions that will render accounts liquidable.

To continuously monitor account positions, the bot could operate in loops. In each loop, it must be able to recognize liquidable accounts, and if any are found, create and send liquidation transactions for them, specifying the address of the liquidable account, the asset in which the debt will be repaid, the amount to be repaid, and the collateral token to be received in return.

In this reference case, the bot operates in the Hatom Lending Protocol on the MultiversX blockchain. In this protocol, there are at the time of writing twelve money markets with thousands of accounts. In each loop, it is necessary to determine if any of them is liquidable. This requires access to updated information on the status of the money markets and the account’s positions.

To illustrate the fundamentals, consider the following example: Alice has a position in whichshe added WBTC and EGLD as collateral, and took a borrow of USDC. To know if she is liquidable, it is necessary to get those three money markets data. To accomplish this, an indexer containing all data may be the best and fastest source to query.

The main development hypothesis for the bot could be that accounts will become liquidable almost entirely due to fluctuations in asset prices, so it will be necessary to obtain updated and precise prices in each loop. But it is also possible another scenario where accounts mostly become liquidable due to debt interest, in which it will be necessary to focus on compute precisely accrue interest simulations. Regarding the first one, it delivers a key idea that should be considered when defining the bot’s actions: anticipating price changes.

Anticipating Price Changes

The bot will be more efficient if it can anticipate price changes, simulate what will happen with these, and send liquidation transactions in the same block as the protocol’s price-change transactions are sent. This minimizes the time gap between when an account becomes liquidable and when it is liquidated, as both transactions are processed within the same block. However, there is an implicit risk, as the liquidation transaction might be processed before the price-change transaction. Thus, it is crucial to decide if this is worth it, for example by assessing whether other bots are doing the same.

In the reference case, price changes are predicted by recording price-change transactions sent by the fleet of Oracle Bots. These oracles extract prices from external sources, such as well-established exchanges, and forward this data to the Price Aggregator (Hatom Docs), which consolidates multiple sources of information to produce a single price for an asset. If a price-change transaction is found pending in the transaction pool, its information is used to predict new prices and compute new user positions based on them.

Factors Limiting Execution Time

The liquidation process would be much simpler if time was not a limiting factor. The primary limiting factor is the blockchain’s block time. For example, on MultiversX, the block time is currently 6 seconds. It is essential for the bot’s loop duration to be shorter than this; otherwise, if an account becomes liquidable in block n, another liquidator may send a liquidation transaction within the same block, while the bot will only detect the potential liquidation at least one block later on n+1, by which time the opportunity is likely missed.

Therefore, the bot’s action flow should follow something similar to the example shown in the following diagram.

In the diagram, there are some aspects that have not been mentioned yet. As previously discussed, prices are first obtained by accurately predicting if they will change, using pending price-change transactions in the pool. The information about the money markets and participating accounts in the protocol is gathered to simulate each account’s risk profile. This involves analyzing each account's position in every money market it participates in, and determining if its debt exceeds its collateral, adjusted by the collateral factor for each money market. The previous figure does not delve into the final process, which is profit verification and transaction submission. If an insolvent account is found, a liquidation transaction is prepared and sent. However, it is essential to perform an additional check: whether the liquidation will yield profit for the liquidator. Note that the prepared transaction does not directly call the liquidation method of the account in a given money market; instead, it calls an intermediary contract, which then sends the liquidation transaction.

Cash Reserves and Profit Calculation

The smart contract that initiates the liquidation holds “cash” reserves in a stable token, which in the reference case is USDC. If the borrow or collateral of the position are in tokens other than the cash token, the contract performs swaps accordingly: first, it acquires the tokens to repay the debt, and then it converts the seized tokens into cash. If this yields a profit, the transaction is completed; otherwise, it is reversed.

The larger the liquidation amount, the more collateral is seized. However, when swaps are involved, larger amounts typically increase slippage, as the reserves in the exchange are proportionately more affected by the swap.

The liquidator not only keeps the specified portion of the collateral but also receives an extra portion known as the liquidation incentive. A small part of this is deducted as profit for the protocol. To determine if the transaction is profitable, the net collateral gain is simulated and swapped to USDC, and this amount is checked against the initial cash required to repay the debt to determine the profitability of the liquidation.

Note that additional data is requires, as the information from the pools of the DEX or DEXs (such as xExchange and Ashswap in MultiversX) where the swaps are performed is needed.

Retrospective and Technology Choices

Looking back, the number of data requests and intermediate calculations required to liquidate an account is substantial, all within a short timeframe. If execution time is expected to be the primary limiting factor, it is a good idea to take time to evaluate and appropriately select the language and code architecture.

Conclusion

Designing and implementing a liquidation bot is a complex but rewarding task within the DeFi space. By anticipating market changes, managing efficient data processing, and optimizing for execution speed, such a bot ensures protocol stability and promotes a healthier DeFi ecosystem. The example of the Hatom Lending Protocol on the MultiversX blockchain underscores the importance of real-time data and smart strategies for anticipating market shifts. By carefully balancing speed, accuracy, and profit verification, a well-designed bot can become a key player in maintaining the financial health of decentralized platforms. Last but not less, not only does a well-designed bot contribute to the financial health of decentralized platforms, but it can also be highly profitable for its operators.

Macarena López Morillo
Head of People
Get the Full Picture
For an in-depth understanding of this topic, don't miss out. Learn more here and elevate your knowledge.
right arrow

More articles

Web3 —
Blockchain Technical Partners

Uncover our Web3 creations and discover how we're redefining tomorrow.
Learn More