Article source: ZAN Team

In the context of the increasing popularity of blockchain technology, the cryptocurrency trading ecosystem is also rapidly expanding. Decentralized exchanges (DEXs) 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 (Maximum Extractable Value) robots are automated programs used to execute strategies and other trading strategies on blockchain networks. They extract maximum value by rearranging, inserting, or delaying blockchain transactions. This article will deeply analyze the definition, principles, implementation methods, determining factors, and optimization directions of sandwich robots.

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

01. Sandwich robots

This type of robot submits transactions with higher Gas fees before large orders in the transaction pool are officially on-chain, allowing it to complete trades before the users do. This strategy involves inserting trades before and after the target transaction (front-running and back-running) to manipulate prices and profit from it.

02. Brick-and-mortar sandwich robots

This type of sandwich robot focuses on profiting from price differences between DEXs. It buys assets at a low price on one exchange and then sells them at a higher price on another exchange, thereby obtaining profit. This strategy usually requires the robot to quickly identify price changes between different exchanges and execute trades rapidly.

03. New token release robots

This type of robot focuses on price fluctuations during new token issuances. In the early stages of a new token listing on a DEX, prices are usually unstable and highly volatile. Sandwich robots will quickly buy when the token is just listed and sell after the price rises to profit from the difference. This type of robot requires close attention to the release dynamics of new projects and the ability to place orders quickly.

04. Liquidity pool arbitrage robots

Liquidity pool arbitrage robots arbitrage by transferring assets between different liquidity pools. They seek price differences between pools, providing and withdrawing liquidity to achieve profits. This requires the robot to efficiently manage liquidity and respond quickly to price changes within pools.

05. Flash loan arbitrage robots

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

06. Triangular arbitrage robot

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

This article mainly analyzes sandwich robots together with everyone.

I. Sandwich robots

Sandwich robots are automated trading tools specifically designed to profit through front-running trades on decentralized exchanges. It captures on-chain trading opportunities quickly and trades before or after the target transaction to earn the price difference. The core of sandwich robots lies in efficiently and rapidly seizing trading opportunities.

II. Principles of sandwich robots

The profit operation of sandwich robots is based on the following basic principles:

1. Front-running: Before other users submit buy orders but before they are packed into blocks by miners, the robot buys the target token at a lower price. Once the user's order is executed and pushes the price up, the robot quickly sells to capture the price difference.

2. Back-running: The robot sells the token at a higher price before other users sell it. After the user's sell order pushes down the price, the robot buys back at a lower price, thus realizing profit.

The so-called sandwich is the trading user being sandwiched, earning the price difference. The success of sandwich robots relies on accurately timing trades and having high execution priority.

III. Implementation ideas

1. Real-time monitoring of transactions:

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

● Filter target trades by comparison

transaction.to

Or transaction.from field to identify transactions related to the target DEX.

2. Filter and screen

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

3. Dynamically adjust Gas prices

● Manually set a higher Gas price to prioritize the robot's transaction so that it executes before ordinary users.

4. Decode transaction data

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

● Based on the decoded information, choose the appropriate contract calling method, such as

swapExactETHForTokens

Or swapTokensForExactTokens.

IV. Code ideas

Selected the wss provided by ZAN's node service; if you don't know how to create one, you can find the complete tutorial in this document (https://docs.zan.top/docs/quick-start-guide). The script is implemented with 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 })

2. Filter these transactions

ZANWssProvider.on("pending", (tx) => { if (transaction && transaction.to && transaction.to.toLowerCase() === ROUTER.toLowerCase() && transaction.from !== blackAddress) { // TODO } })

3. A method to determine transaction direction is also needed, manually set 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 } }

4. Decode transaction method, invoke function

const iface = new ethers.utils.Interface(abi) const result = iface.decodeFunctionData('swapExactETHForTokens', transaction.data)

V. Determining factors

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

1. Transaction speed:

  • Network latency and node response speed directly affect the reaction time of the robot. Using high-performance node services (such as ZAN, Infura, Alchemy) can reduce latency, and ZAN also provides support for independent nodes.

2. Gas fees:

  • When seizing trading priority, Gas fees are an important consideration. Excessively high Gas fees can erode profits, so a balance between speed and cost must be found.

3. Market liquidity:

  • High liquidity helps execute large transactions quickly without significantly affecting market prices. Insufficient liquidity may lead to increased slippage or transaction failures.

4. Contract security:

  • The security of the target contract directly relates to the risk of strategy operations. Robots must have basic verification capabilities for contract code to avoid transactions being exploited by malicious contracts, and can use ZAN's contract auditing capability to assess risks for target contracts (https://zan.top/home/ai-scan).

5. Competitive environment:

  • There may be multiple sandwich robots in the market simultaneously competing for profitable opportunities. In a highly competitive environment, the success rate of trades and profits may be affected.

Conclusion

MEV robots 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 robots also face challenges of high competition and high risk. Investors must comprehensively consider technical implementation, risk control, and market strategies to maintain competitiveness in the ever-changing cryptocurrency market. In the future, as technology advances and the DeFi ecosystem expands, sandwich robots are expected to unleash their potential in more areas, creating more value for users.

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