In the context of the growing popularity of blockchain technology, the cryptocurrency trading ecosystem is also rapidly expanding. Decentralized exchanges (DEXs), with their advantages of disintermediation and transparency, have become important platforms for digital asset trading. As the market matures, various automated trading tools have emerged. MEV (Maximum Extractable Value) bots are automated programs used to execute strategies and other trading tactics on blockchain networks. They extract maximum value by reordering, inserting, or delaying blockchain transactions. This article will delve into the definition, principles, implementation methods, determinants, 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 monitor large orders in the trading pool and submit transactions with higher gas fees before these orders are officially on-chain, completing trades before the users. This strategy involves inserting trades before and after the target trade (front-running and back-running) to manipulate prices and profit.
02. Brick-moving type sandwich 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 high price on another, capturing profits. 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 going live on a DEX, prices are often unstable and volatile. The sandwich bot will quickly buy the token as soon as it is launched and sell it after the price rises to capture the 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 conduct arbitrage by transferring assets between different liquidity pools. They search for price discrepancies 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 for trading. Flash loans allow users to borrow large amounts of money in a single transaction without collateral. Bots can use these funds to manipulate market prices in a short time to achieve arbitrage. For example, pushing up the price in one pool using a flash loan and then profiting in another pool.
06. Triangular Arbitrage Bots
Triangular arbitrage involves trading among three different token pairs to exploit exchange rate differences for arbitrage. For example, profits can be achieved through trading A/B, B/C, and then trading C/A in a loop. This type of bot requires complex calculations and quick trading execution capabilities.
This article primarily analyzes sandwich bots with everyone.
I. Sandwich Bots
Sandwich bots are automated trading tools specifically designed to achieve profits by front-running trades on decentralized exchanges. They quickly capture on-chain trading opportunities, placing trades before or after the target trade to earn the price difference. The core of sandwich bots lies in seizing trading opportunities with high efficiency and speed.
II. Principles of sandwich bots
The profit operation of sandwich bots is based on the following basic principles:
1. Front-running: Before other users submit buy orders that have not yet been packaged by miners into blocks, 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 to realize profits.
The so-called sandwich involves sandwiching the trading users to capture the price difference. The success of sandwich bots relies on precise timing and high execution priority.
III. Implementation Ideas
1. Real-time monitoring of transactions:
● Use WebSocket to connect to blockchain nodes and listen in real-time for pending transactions.
● Filter target trades by comparison
transaction.to
or the transaction.from field to identify trades related to the target DEX.
2. Filter and Screen
● Filter out trades unrelated to the strategy and trades from one's own address to prevent self-trading that leads to a deadlock.
3. Dynamically adjust gas prices
● Manually set higher gas prices so that miners prioritize processing the bot's transactions, executing before ordinary users.
4. Decode transaction data
● Use smart contract interfaces (like Interface in ethers.js) to decode transaction data and determine the tokens and amounts involved in the transaction.
● Select appropriate contract calling methods based on decoded information, such as
swapExactETHForTokens
or swapTokensForExactTokens.
IV. Code Ideas
Selected the WSS provided by ZAN's node service. If you're unsure how to create one, you can find a complete tutorial in this documentation (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 })
2. Filter these trades
ZANWssProvider.on("pending", (tx) => { if (transaction && transaction.to && transaction.to.toLowerCase() === ROUTER.toLowerCase() && transaction.from !== blackAddress) { // TODO } })
3. A method is also needed to determine the direction of the trade 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 } }
4. Decode transaction methods, call functions
const iface = new ethers.utils.Interface(abi) const result = iface.decodeFunctionData('swapExactETHForTokens', transaction.data)
V. Determinants
The effectiveness and success of sandwich bots are closely related to various factors:
1. Trading Speed:
Network latency and node response speed directly affect the bot's reaction time. Using high-performance node services (like ZAN, Infura, Alchemy) can reduce delays, and ZAN also provides support for independent nodes.
2. Gas Fees:
When competing for transaction priority, gas fees are an important consideration. Excessively high gas fees can eat into profits, so a balance between speed and cost must be found.
3. Market Liquidity:
High liquidity helps to execute large transactions quickly without significantly impacting market prices. Insufficient liquidity may lead to increased slippage or transaction failures.
4. Contract Security:
The security of the target contract is directly related to the risk of strategy operations. The bot must have basic verification capabilities for the contract code to avoid trades being exploited by malicious contracts. Risk assessment of the target contract can be performed using ZAN contract auditing capabilities (https://zan.top/home/ai-scan).
5. Competitive Environment:
There may be multiple sandwich bots in the market simultaneously competing for profit opportunities. When competition is fierce, the success rate of trades and profits may be affected.
Conclusion
MEV bots provide an efficient solution for arbitrage in decentralized exchanges. By analyzing in real-time and executing quickly, they can gain an edge in the market. However, sandwich bots also face high competition and high-risk challenges. Investors need to consider comprehensive factors in technology 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 leverage their potential in more areas, creating more value for users.
This article is written by KenLee from the ZAN Team (X account @zan_team) and is intended solely for technical sharing, not constituting any investment advice.