Web3 Beginner Series: Understand MEV Bots in Five Minutes, You Can Write One Too

CN
PANews
Follow
1 year ago

In the context of the increasing popularity of blockchain technology, the cryptocurrency trading ecosystem is also rapidly expanding. Decentralized exchanges (DEX) have become important platforms for digital asset trading due to their advantages of disintermediation and transparency. As the market matures, various automated trading tools have emerged. MEV (Maximal Extractable Value) bots are automated programs used to execute strategies and other trading tactics on blockchain networks. They extract maximum value by rearranging, inserting, or delaying blockchain transactions. This article will delve into the definition, principles, implementation methods, determining factors, and optimization directions of sandwich bots.

With the development of technology and market demand, sandwich bots have evolved into various types to adapt to different trading environments and strategy needs. Here are several common types of sandwich bots:

01. Sandwich Bots

These bots listen for large orders in the transaction pool and submit transactions with higher Gas fees before these orders are officially on-chain, thus completing transactions ahead of users. This strategy involves inserting transactions before and after the target transaction (front-running and back-running) to manipulate prices and profit from it.

02. Arbitrage Bots

This type of sandwich bot focuses on profiting from price differences between DEXs. It buys assets at a low price on one exchange and sells them at a higher price on another, thus making a profit. This strategy typically requires the bot to quickly identify price changes between different exchanges and execute trades swiftly.

03. New Token Launch Bots

These bots focus on price fluctuations during new token launches. In the early stages of a new token being listed on a DEX, prices are usually unstable and volatile. Sandwich bots quickly buy tokens as soon as they are listed and sell them after the price rises to capture the price difference. This type of bot requires close attention to the release dynamics of new projects and the ability to place orders quickly.

04. Liquidity Pool Arbitrage Bots

Liquidity pool arbitrage bots perform arbitrage by transferring assets between different liquidity pools. They look for price differences between different pools, providing and withdrawing liquidity to achieve profits. This requires the bot to efficiently manage liquidity and respond quickly to price changes within the pools.

05. Flash Loan Arbitrage Bots

Flash loan arbitrage bots utilize the characteristics of flash loans to trade. Flash loans allow users to borrow large amounts of funds in a single transaction without collateral. Bots can use these funds to manipulate market prices for arbitrage in a short time. For example, using a flash loan to drive up prices in one pool and then profiting in another pool.

06. Triangular Arbitrage Bots

Triangular arbitrage involves trading between three different token pairs to exploit exchange rate differences for profit. For example, by trading A/B, B/C, and then trading C/A in a loop to realize profits. This type of bot requires complex calculations and rapid trade execution capabilities.

This article mainly analyzes sandwich bots.

1. Sandwich Bots

Sandwich bots are automated trading tools specifically designed to profit from front-running trades on decentralized exchanges. They quickly capture on-chain trading opportunities, placing trades before or after the target transaction to earn the price difference. The core of sandwich bots lies in efficiently and swiftly seizing trading opportunities.

2. Principles of Sandwich Bots

The profit operations of sandwich bots are based on the following fundamental principles:

  1. Front-running: Before other users submit buy orders that have not yet been packed into a block by miners, the bot buys the target token at a lower price. When the user's order is executed and pushes the price up, the bot quickly sells to capture the price difference.

  2. Back-running: Before other users sell tokens, the bot sells at a higher price first. When the user's sell order drives the price down, the bot then repurchases at a lower price, thus realizing profits.

The so-called "sandwich" refers to the trading users being "sandwiched," earning the price difference. The success of sandwich bots relies on precise timing of trades and high-priority execution.

3. Implementation Ideas

  1. Real-time Listening to Transactions:

    ● Use WebSocket to connect to blockchain nodes and listen in real-time for pending transactions.

    ● Filter target transactions by comparing the transaction.to or transaction.from fields to identify transactions related to the target DEX.

  2. Filtering and Screening

    ● Filter out transactions unrelated to the strategy and transactions from the bot's own address to prevent self-trading from causing loops.

  3. Dynamically Adjust Gas Prices

    ● Manually set a higher Gas price to prioritize the bot's transactions for miners, executing before regular users.

  4. Decode Transaction Data

    ● Use smart contract interfaces (such as Interface in ethers.js) to decode transaction data, determining the tokens and amounts involved in the transaction.

    ● Based on the decoded information, choose the appropriate contract call method, such as swapExactETHForTokens or swapTokensForExactTokens.

4. Code Ideas

Using the wss provided by ZAN's node service, if you don't know how to create it, you can find a complete tutorial in this document (https://docs.zan.top/docs/quick-start-guide). The script is implemented using ethers.js.

  1. Create a listening ws service
   const ZAN_WSS_URL = `wss://api.zan.top/node/ws/v1/eth/mainnet/${YOUR_KEY}`;
   const ZANWssProvider = new ethers.providers.WebSocketProvider(ZAN_WSS_URL);
   ZANWssProvider.on("pending", (tx) => {  // TODO });
  1. Filter these transactions
   ZANWssProvider.on("pending", (tx) => {   
       if (transaction && transaction.to && transaction.to.toLowerCase() === ROUTER.toLowerCase() && transaction.from !== blackAddress) {    
           // TODO  
       } 
   });
  1. A method is also needed to determine the transaction direction and manually set the Gas price
   function calculate_gas_price(action, amount) {  
       if (action === "buy") {    
           return amount.add(100000000); // 0.1 Gwei  
       } else {    
           return amount.sub(100000000); // 0.1 Gwei  
       } 
   }
  1. Decode transaction methods and call functions
   const iface = new ethers.utils.Interface(abi);
   const result = iface.decodeFunctionData('swapExactETHForTokens', transaction.data);

5. Determining Factors

The effectiveness and success of sandwich bots are closely related to various factors:

  1. Transaction Speed:
  • Network latency and node response speed directly affect the bot's reaction time. Using high-performance node services (such as ZAN, Infura, Alchemy) can reduce latency, and ZAN also provides support for independent nodes.
  1. Gas Fees:
  • Gas fees are an important consideration when prioritizing transaction execution. Excessively high Gas fees can eat into profits, so a balance between speed and cost needs to be found.
  1. Market Liquidity:
  • High liquidity helps execute large transactions quickly without significantly impacting market prices. Insufficient liquidity may lead to increased slippage or transaction failures.
  1. Contract Security:
  • The security of the target contract directly relates to the risk of strategy operations. The bot should have basic verification capabilities for contract code to avoid transactions being exploited by malicious contracts. ZAN's contract auditing capabilities can be used to assess the risk of target contracts (https://zan.top/home/ai-scan).
  1. Competitive Environment:
  • There may be multiple sandwich bots in the market competing for profit opportunities. In a highly competitive environment, the success rate and profits of trades may be affected.

Conclusion

MEV bots provide an efficient solution for arbitrage on decentralized exchanges. Through real-time analysis and rapid execution, they can gain an advantage in the market. However, sandwich bots also face challenges of high competition and high risk. Investors need to comprehensively consider technical implementation, risk control, and market strategies to remain competitive in the ever-changing cryptocurrency market. In the future, with technological advancements and the expansion of the DeFi ecosystem, sandwich bots are expected to play a greater role in more areas, creating more value for users.

This article was written by KenLee from the ZAN Team (X account @zan_team). The content of the article is for technical sharing only and does not constitute any investment advice.

免责声明:本文章仅代表作者个人观点,不代表本平台的立场和观点。本文章仅供信息分享,不构成对任何人的任何投资建议。用户与作者之间的任何争议,与本平台无关。如网页中刊载的文章或图片涉及侵权,请提供相关的权利证明和身份证明发送邮件到support@aicoin.com,本平台相关工作人员将会进行核查。

Share To
APP

X

Telegram

Facebook

Reddit

CopyLink