Sandwich Attack Bot Development

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1 servicesAll 1306 services
Sandwich Attack Bot Development
Complex
~1-2 weeks
FAQ
Blockchain Development Services
Blockchain Development Stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1214
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_logo-advance_0.png
    B2B Advance company logo design
    561
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    823

Development of Sandwich Attack Bot

Sandwich bot — this is legal MEV tool. Arbitrage, liquidations, sandwiches — three main MEV extraction strategies in production. Sandwich specifically exploits slippage tolerance of DEX users: bot sees victim in mempool, inserts own buy before it (frontrun), victim moves price up, bot sells after (backrun). Difference — bot profit, victim loss within their own slippage tolerance. This is arbitrage on information about transaction order.

Development of such bot — simultaneously task of speed (mempool latency), economics (profitability calculator), and infrastructure (reliable deployment without losses).

Where most bots lose money

Inaccurate profitability calculation

Most common mistake of beginner MEV developers — calculating profit without accounting all costs. Seems obvious, but encountered regularly in practice.

Real sandwich P&L:

profit = amountOut_backrun - amountIn_frontrun
costs = gasCost_frontrun + gasCost_backrun + builderTip
netProfit = profit - costs

gasCost with aggressive tips on Ethereum mainnet — not a small amount. If sandwich brings $2 and builder tip is $1.5 — deal is unprofitable. Bot should simulate entire transaction package before sending and discard deals with negative net profit.

Simulation via eth_call on current state — slow. Production bots use proprietary in-process EVM simulators (revm on Rust or analogues) for microsecond valuation.

Revert due to price impact miscalculation

Bot calculated profit at moment T, but sent transaction at moment T+50ms. During that time another bot executed its frontrun. Pool state changed. Bot's own frontrun now moves price more than calculated, victim hits slippage tolerance and their transaction reverts. Backrun not needed, but gas for frontrun already spent.

Protection: backrun transaction should be conditional — check that victim's target transaction really was included before it. In Flashbots bundle this is implemented via reverting_tx_hashes — if victim reverted, entire bundle not included.

Competition and builder relationship

On Ethereum after The Merge 95%+ MEV-bundles go through block builders (Flashbots, beaverbuild, rsync-builder). Bot sending transactions to public mempool directly loses to competitors with private relay in all cases.

Correct infrastructure: MEV-Share (Flashbots matchmaker for user-refund MEV), direct connections to top-builders through their private endpoints, monitoring mev-boost relay to understand current winning builder.

Production sandwich bot architecture

Mempool monitoring

Standard eth_subscribe("pending") via WebSocket — too slow. Between transaction appearance in private mempools of major nodes and public announcement passes 50–200ms. During that time professional bots already made decision.

Optimal scheme:

  1. Direct peer connections with several Ethereum nodes (Geth, Erigon) to get transactions before wide propagation.
  2. Blob mempool feed from specialized providers (bloXroute, Blocknative) — paid, but gives access to transactions 100–300ms before public announcement.
  3. Own node with --txpool.pricelimit 0 — accepts all transactions without minimum gas price filter.

Filtering and candidate evaluation

From thousands of pending transactions need quickly select sandwich candidates. Criteria:

  • to address = known DEX router (Uniswap V2/V3, Sushiswap, Curve, Balancer)
  • Decoded calldata: swap with slippage tolerance > 0.5%
  • amountOutMinimum significantly below current amountOut from getAmountsOut
  • Gas price sufficient for inclusion in next block

Decoding calldata for Uniswap V3 exactInputSingle and exactInput (multi-hop) — mandatory component. For multi-hop swaps calculation more complex: need to simulate each hop sequentially.

Calculating optimal frontrun amount

Key math: how much to buy in frontrun to maximize profit?

For Uniswap V2 with x * y = k formula analytical solution exists for optimal input amount. For V3 with concentrated liquidity and tick-based price — numerical optimization (binary search on amount).

Approximate formula for V2:

optimalInput ≈ sqrt(k * victimAmount) - reserveIn

But without accounting gas costs and builder tip. Real optimization accounts for marginal cost of each additional dollar of frontrun amount.

Execution via Flashbots

const bundle = [
  { signer: wallet, transaction: frontrunTx },
  { hash: victimTxHash },           // victim target transaction
  { signer: wallet, transaction: backrunTx }
];

const bundleResponse = await flashbotsProvider.sendBundle(
  bundle,
  targetBlockNumber,
  { minTimestamp: 0, maxTimestamp: 0, revertingTxHashes: [victimTxHash] }
);

revertingTxHashes: [victimTxHash] — key parameter: if victim reverts (e.g., another bot already executed their sandwich), entire bundle dropped. Bot doesn't lose gas on frontrun without backrun.

Multichain and L2 specifics

On Arbitrum and Optimism no public mempool in classic sense — sequencer receives transactions directly and publishes them atomically in batches. MEV opportunities limited but not excluded: DEX arbitrage between different protocols on L2 works.

On BSC sandwiches active, competition lower than Ethereum mainnet, but validator tips work differently — direct connections with BSC validators through their private endpoints.

Base (OP Stack) — sequencer owned by Coinbase, MEV policy limits classic sandwiches. Arbitrage between Aerodrome, BaseSwap, Uniswap V3 on Base works better.

Development stack

Bot written in Rust with ethers-rs library (or newer alloy) for maximum performance. Critical components — EVM simulator (revm), mempool streaming, bundle submission — in one process without inter-process communication.

Smart contract for atomic execution (so backrun and frontrun execute atomically from one contract, saving gas) — Solidity 0.8.x with minimal footprint. Contract stores no state, only delegatecall to execution logic.

Monitoring: custom Prometheus + Grafana dashboard with metrics: bundles per hour, inclusion rate, average profit per bundle, revert rate.

Development process

Research (2–3 days). Analysis of target chain and DEX ecosystem, MEV opportunity size estimation through dune analytics data.

Development (2–3 weeks). Mempool streaming, transaction decoder, profitability calculator, Flashbots/relay integration, atomic execution contract.

Testing (3–5 days). Backtesting on historical blocks via Foundry fork, simulated competition, paper trading on testnet.

Launch and optimization (ongoing). First mainnet deployment with limited position sizes, then gradual scaling as profitability validated.

Timeline estimates

Basic Uniswap V2/V3 sandwich bot — 1–2 weeks. Multi-DEX with Curve, Balancer, Sushiswap support + multichain — 3–5 weeks. Including latency optimization and builder relationships.