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 built or used a crypto trading bot, chances are you’ve experienced getting "sandwiched." It’s a frustrating phenomenon where your transaction gets frontrun and backrun, squeezing your profits or even causing losses. This is a direct result of Maximal Extractable Value (MEV) and sandwich attacks. In this article, I’ll explain what MEV sandwich attacks are, why they happen, and how you can protect your bots using tools like Jito bundles. I’ll also share real-world examples and code snippets to help you implement these protections.


What Is MEV and How Does Sandwiching Work?

MEV (Maximal Extractable Value) refers to the profit miners or validators can extract by reordering, inserting, or censoring transactions in a block. Sandwich attacks are a subset of MEV strategies where an attacker takes advantage of a pending transaction (usually a swap) to profit at your expense.

Here’s how a sandwich attack works:

  1. Frontrun: The attacker places their transaction before yours in the block. For example, if you’re swapping ETH for USDC, they buy USDC first, pushing the price up.
  2. Your Transaction: Your swap executes at the higher price, receiving less USDC than expected.
  3. Backrun: The attacker sells the USDC they bought earlier, profiting from the price movement caused by your transaction.

The result? Your transaction effectively gets "sandwiched" between the attacker’s frontrun and backrun. This is especially common on decentralized exchanges (DEXs) like Uniswap, where price movements are highly sensitive to transaction order.


How Often Do Sandwich Attacks Happen?

Sandwich attacks are shockingly common. According to data from Flashbots, MEV-related transactions account for over 60% of Ethereum block space during peak periods. In 2023 alone, MEV bots extracted over $1 billion in profits, with sandwich attacks being a significant contributor.

Here’s a real-world example: Suppose you’re swapping $10,000 worth of ETH for USDC on Uniswap. A sandwich bot could easily extract 1-3% of your transaction value. That’s $100-$300 lost in a single trade—an unsustainable cost for any trading bot.


Why Are Bots Vulnerable to Sandwich Attacks?

Most crypto bots are vulnerable to sandwich attacks because they rely on public mempools. When you submit a transaction, it’s broadcast to the mempool, where anyone can see it. MEV bots actively scan mempools for profitable opportunities, making your transaction an easy target.

Here’s a simplified example of how a bot might submit a vulnerable transaction using Ethers.js:

const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL");
const wallet = new ethers.Wallet("YOUR_PRIVATE_KEY", provider);
const contract = new ethers.Contract("UNISWAP_ROUTER_ADDRESS", abi, wallet);

const tx = await contract.swapExactETHForTokens(
  ethers.utils.parseEther("1.0"), // amountOutMin
  ["WETH_ADDRESS", "USDC_ADDRESS"], // path
  wallet.address, // to
  Date.now() + 1000, // deadline
  { value: ethers.utils.parseEther("10.0") } // amountIn
);

await tx.wait();
Enter fullscreen mode Exit fullscreen mode

Because this transaction is broadcast to the public mempool, it’s exposed to MEV bots. Even with tight slippage tolerance, attackers can still exploit the transaction.


How to Prevent Sandwich Attacks

Fortunately, there are ways to protect your bots from MEV sandwich attacks. One of the most effective solutions today is Jito bundles.

What Are Jito Bundles?

Jito bundles are a feature of the Jito-Solana client that allows you to submit transactions directly to block producers without exposing them to the public mempool. While Jito is primarily built for Solana, similar concepts (like Flashbots on Ethereum) exist for other chains.

By using Jito bundles, you can prevent MEV bots from seeing your transaction before it’s included in a block, effectively making sandwich attacks impossible.


Implementing Jito Bundles

Here’s how you can use Jito bundles to protect your Solana transactions:

  1. Install Jito-Solana Client First, you’ll need to install the Jito-Solana client and configure your bot to use it.
curl --proto '=https' --tlsv1.2 -sSf https://sh.jito.build | sh
Enter fullscreen mode Exit fullscreen mode
  1. Create a Bundle

    Next, create a bundle containing your transactions. Bundles ensure that your transactions are executed atomically, preventing frontrunning.

  2. Submit the Bundle

    Use the Jito API to submit your bundle directly to block producers.

Here’s an example of submitting a bundle using JavaScript:

const jito = require('jito-client');

const bundle = [
  {
    transaction: "YOUR_TRANSACTION_SIGNATURE",
    signers: ["YOUR_SIGNER_PUBKEY"],
  },
];

jito.submitBundle(bundle).then((response) => {
  console.log("Bundle submitted:", response);
}).catch((error) => {
  console.error("Error submitting bundle:", error);
});
Enter fullscreen mode Exit fullscreen mode

By submitting your transactions as a bundle, you bypass the public mempool entirely, ensuring they’re executed as intended.


Lessons Learned

Here are some key takeaways from my experience dealing with MEV and sandwich attacks:

  1. Avoid Public Mempools: Broadcasting transactions to public mempools is inherently risky. Use private transaction relays or solutions like Jito bundles.
  2. Atomic Transactions: Bundle your transactions to prevent partial execution. This is particularly important for multi-step trades.
  3. Slippage Tolerance: Set realistic slippage limits, but understand that even tight tolerances can’t fully protect against MEV.
  4. Chain-Specific Solutions: Each blockchain has its own MEV landscape. Solana’s Jito bundles, Ethereum’s Flashbots, and Avalanche’s Snowsight are all examples of MEV mitigation tools.
  5. Monitor MEV Activity: Tools like Eigenphi and MEV monitor can help you track MEV activity on your transactions and adjust your strategy accordingly.

Conclusion

MEV sandwich attacks are a significant challenge for crypto trading bots, but they’re not insurmountable. By understanding how MEV works and leveraging tools like Jito bundles, you can protect your transactions and maximize your profits. Remember, the key to avoiding sandwich attacks is to keep your transactions private and atomic.

As MEV continues to evolve, staying informed and adapting your strategies will be crucial. Whether you’re trading on Solana, Ethereum, or another chain, the principles remain the same: prioritize privacy, minimize exposure, and use the right tools for the job.

Happy trading, and may your bots stay sandwich-free!


🚀 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)