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 run a crypto trading bot, you’ve probably encountered the dreaded "sandwich attack." It’s the bane of DeFi traders and arbitrage bots alike. Today, I’ll explain what sandwich attacks are, how they work, and—most importantly—how you can protect your bot from them using tools like Jito bundles. I’ll also share some real-world numbers and practical code examples to help you understand the mechanics and implement solutions.


What is a Sandwich Attack?

A sandwich attack is a form of Maximal Extractable Value (MEV) exploitation where a malicious actor places one transaction before and one after your transaction in the same block to profit at your expense. Here’s how it works:

  1. Front-running: The attacker spots your pending transaction in the mempool and submits a buy order at a slightly higher gas fee to execute before yours.
  2. Your Transaction: Your transaction executes, moving the price unfavorably.
  3. Back-running: The attacker sells the asset immediately after your transaction, capturing the price difference.

For example, if your bot tries to buy ETH on Uniswap, a sandwich attacker can:

  • Front-run your buy order, driving the price up.
  • Back-run the trade immediately after, selling at the higher price and pocketing the profit.

According to Flashbots’ MEV-Explore, sandwich attacks account for over 50% of all MEV extraction on Ethereum, with millions of dollars extracted daily.


Why Are Most Bots Vulnerable?

Most crypto bots are vulnerable because they rely on public mempools to broadcast transactions. On Ethereum and other EVM chains, transactions are publicly visible in the mempool before they’re included in a block. Sophisticated bots scan the mempool for profitable opportunities and execute sandwich attacks in milliseconds.

Here’s what happens:

  • Your bot submits a transaction with a standard gas fee.
  • An attacker’s bot detects your transaction and front-runs it with a higher gas fee.
  • Your transaction executes in a worse position, and the attacker profits.

This vulnerability is especially pronounced in arbitrage and liquidation bots, which often operate on tight margins.


Real-World Example: A Bot Loses $10K

Let’s say you’re running an arbitrage bot that spots a price discrepancy between Uniswap and Sushiswap. You try to buy 100 ETH on Uniswap and sell it on Sushiswap for a $10,000 profit.

Without protection:

  1. Your bot submits a buy transaction.
  2. A sandwich attacker front-runs your buy, increasing ETH’s price on Uniswap.
  3. Your bot’s buy executes at the higher price.
  4. The attacker back-runs the trade, selling ETH for a profit.
  5. Your arbitrage opportunity evaporates, and you lose money.

In this scenario, your bot loses the entire $10K potential profit, while the attacker pockets a significant portion.


How to Prevent Sandwich Attacks

The key to preventing sandwich attacks is to avoid exposing your transactions to the public mempool. Here are three practical solutions:

1. Use Jito Bundles (Solana)

Jito is a Solana-based MEV infrastructure that allows you to submit bundles of transactions directly to block producers. Bundles are groups of transactions that must execute together atomically, preventing others from inserting transactions in the middle.

Here’s how you can use Jito’s SDK to submit a bundle:

import { Connection, PublicKey, Transaction } from '@solana/web3.js';
import { JitoRelayer } from '@jito-sdk';

const connection = new Connection('https://api.mainnet-beta.solana.com');
const relayer = new JitoRelayer(connection);

async function submitBundle(transactions: Transaction[]) {
  const bundleId = await relayer.submitBundle(transactions);
  console.log(`Bundle submitted with ID: ${bundleId}`);
}

// Example usage
const tx1 = new Transaction().add(instruction1);
const tx2 = new Transaction().add(instruction2);
submitBundle([tx1, tx2]);
Enter fullscreen mode Exit fullscreen mode

By bundling your transactions, you ensure they execute together without interference from front-runners.

2. Use Flashbots (Ethereum)

Flashbots is an Ethereum-based solution that allows you to submit transactions directly to miners, bypassing the public mempool. This prevents sandwich attacks by keeping your transactions private until they’re included in a block.

Here’s a basic example using Flashbots RPC:

const { ethers } = require('ethers');
const { FlashbotsBundleProvider } = require('@flashbots/ethers-provider-bundle');

const provider = new ethers.providers.JsonRpcProvider(process.env.ETHEREUM_RPC);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);

async function sendPrivateTx() {
  const flashbotsProvider = await FlashbotsBundleProvider.create(provider, wallet);
  const signedTx = await wallet.signTransaction({
    to: '0xRecipientAddress',
    value: ethers.utils.parseEther('1.0'),
    gasLimit: 21000,
  });
  const bundle = [{ signedTransaction: signedTx }];
  const targetBlock = (await provider.getBlockNumber()) + 1;
  const response = await flashbotsProvider.sendBundle(bundle, targetBlock);
  console.log('Bundle submitted:', response);
}

sendPrivateTx();
Enter fullscreen mode Exit fullscreen mode

3. Optimize Gas Fees

While not foolproof, using competitive gas fees can reduce the likelihood of being front-run. Tools like GasNow or Etherscan’s Gas Tracker can help you set optimal fees.


Practical Lessons Learned

Here are some key takeaways from my experience:

  1. Bundling is Essential: Whether you use Jito bundles or Flashbots, bundling transactions is the most effective way to prevent sandwich attacks.
  2. Simulate Transactions: Always simulate transactions before submitting them to estimate price impact and detect potential attacks.
  3. Monitor Gas Fees: Stay updated on gas fees to ensure your transactions are prioritized without overpaying.
  4. Use MEV-Resistant Strategies: Consider strategies like limit orders or batch trading to reduce exposure.

Conclusion

Sandwich attacks are a significant threat to crypto bots, but they’re not insurmountable. By leveraging tools like Jito bundles and Flashbots, you can protect your transactions and prevent MEV extraction. Always stay vigilant, optimize your strategies, and keep learning from the broader DeFi ecosystem.

If you’ve had experiences with sandwich attacks or implemented solutions, share them in the comments below. Let’s keep the conversation going!


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