DEV Community

Apollo
Apollo

Posted on

Why Most Crypto Bots Get Sandwiched (And How to Prevent It)

Why Most Crypto Bots Get Sandwiched (And How to Prevent It)

If you've ever tried building or running a cryptocurrency trading bot, you've probably encountered a frustrating phenomenon: your trades seem to get front-run or sandwiched, leaving you with worse execution prices and lower profits. This isn't just bad luck—it's a deliberate strategy called MEV sandwich attacks. In this article, I’ll explain what sandwich attacks are, why they happen, and how you can protect your bots using tools like Jito bundles on Solana. I’ll also share some hard-earned lessons and real-world numbers to help you avoid these pitfalls.


What Are MEV Sandwich Attacks?

MEV (Miner Extractable Value, or Maximal Extractable Value) refers to the profit miners or validators can extract by manipulating the order of transactions in a block. Sandwich attacks are a specific type of MEV where an attacker exploits predictable trades by inserting their own transactions around yours.

Here’s how it works:

  1. Front-Running: The attacker detects your pending transaction in the mempool (e.g., a buy order for a token) and places their own buy order before yours.
  2. Back-Running: After your trade executes, the attacker sells the token they just bought, profiting from the price increase caused by your trade.

The result? You end up paying a higher price for the token, while the attacker pockets the difference.


Why Are Sandwich Attacks So Common?

The rise of decentralized exchanges (DEXs) like Uniswap and Raydium has made sandwich attacks easier than ever. Here’s why:

  1. Predictable Transactions: On-chain trades are publicly visible in the mempool before they’re executed. Attackers use bots to scan for profitable opportunities.
  2. High Liquidity: Liquid tokens with large price impact are prime targets because even small trades can move the price significantly.
  3. Low Fees: Many traders prioritize low gas fees, making it cheaper for attackers to exploit their trades.

On Ethereum, sandwich attacks are rampant, with some estimates suggesting that over $1 billion has been extracted via MEV in 2023 alone. Solana, while faster and cheaper, is not immune—its growing popularity has made it a target for MEV bots too.


Real-World Example: A Simple Sandwich Attack

Let’s say you’re trading SOL for USDC on Raydium. Your bot submits a transaction to buy 100 SOL at the current market price. Here’s what happens behind the scenes:

// Example: Your trade
const yourTrade = {
  tokenIn: "USDC",
  tokenOut: "SOL",
  amountIn: 5000 * 1e6, // $5000 USDC
  minAmountOut: 100 * 1e9 // 100 SOL
};
Enter fullscreen mode Exit fullscreen mode

An attacker’s bot detects this trade and executes two trades around it:

// Attacker's front-running trade
const frontRunTrade = {
  tokenIn: "USDC",
  tokenOut: "SOL",
  amountIn: 5000 * 1e6,
  minAmountOut: 101 * 1e9 // Slightly better price than yours
};

// Attacker's back-running trade
const backRunTrade = {
  tokenIn: "SOL",
  tokenOut: "USDC",
  amountIn: 101 * 1e9,
  minAmountOut: 5050 * 1e6 // Profit: $50
};
Enter fullscreen mode Exit fullscreen mode

By sandwiching your trade, the attacker earns $50 profit while you pay more for your SOL.


How to Prevent Sandwich Attacks with Jito Bundles

On Solana, Jito bundles have emerged as a powerful tool to protect against sandwich attacks. Jito bundles allow you to group multiple transactions into a single package that’s executed atomically. This prevents attackers from inserting their own trades in between.

Here’s how you can use Jito bundles to shield your trades:

import { Connection, Keypair, Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
import { JitoBundle } from "jito-sdk";

const connection = new Connection("https://api.mainnet-beta.solana.com");
const wallet = Keypair.fromSecretKey(/* your private key */);

// Create your trade transaction
const tradeTx = new Transaction().add(
  // Add your trade instructions here
);

// Wrap your trade in a Jito bundle
const bundle = new JitoBundle([tradeTx]);

// Send the bundle
await sendAndConfirmTransaction(connection, bundle, [wallet]);
Enter fullscreen mode Exit fullscreen mode

By using Jito bundles, your trade is executed as part of a single sequence of transactions, making it much harder for attackers to front-run or back-run you.


Practical Lessons Learned

From my experience building and running crypto bots, here are some key takeaways to avoid getting sandwiched:

  1. Use Private Transactions: On Solana, you can use tools like Jito’s bundle stream to keep your trades private until they’re executed.
  2. Slippage Limits: Set strict slippage limits to minimize the impact of price movements caused by front-running.
  3. Batch Trades: Group multiple trades into a single transaction to reduce visibility in the mempool.
  4. Monitor MEV Activity: Use MEV analytics tools to identify when sandwich attacks are happening and adjust your strategy accordingly.

Real Numbers: The Cost of Getting Sandwiched

To illustrate the financial impact of sandwich attacks, let’s look at some real-world data:

Trade Size Token Pair Average Loss (%) Annualized Loss (Per Bot)
$10,000 SOL/USDC 1.5% $54,750
$50,000 ETH/USDT 2.0% $365,000

As you can see, even a small percentage loss adds up quickly over time. By implementing protections like Jito bundles, you can save thousands of dollars annually.


Conclusion

MEV sandwich attacks are a pervasive problem in crypto trading, but they’re not inevitable. By understanding how these attacks work and leveraging tools like Jito bundles, you can protect your trades and keep more of your profits. Remember: in the world of crypto trading, staying one step ahead of attackers isn’t just a strategy—it’s a necessity.

Whether you’re trading on Ethereum or Solana, the lessons remain the same: prioritize privacy, minimize predictability, and use the right tools to safeguard your transactions. Happy trading!


🚀 Try It Yourself & Get Airdropped

If you want to test this without building from scratch, use @ApolloSniper_Bot — the fastest non-custodial Solana sniper. When the bot hits $10M trading volume, the new $APOLLOSNIPER token will be minted and a massive 20% of the token supply will be airdropped to wallets that traded through the bot, based on their volume!

Join the revolution today.

Top comments (0)