---
title: Sandwich Attacks in Decentralized Systems
url: https://www.emergentmind.com/topics/sandwich-attacks
type: topic
---

# Sandwich Attacks in Decentralized Systems

A sandwich attack is an adversarial transaction sequencing technique prominently observed in decentralized exchanges (DEXs) and increasingly in large language model (LLM) prompt manipulation. The classic manifestation occurs when an attacker strategically places transactions immediately before and after a target transaction, exploiting order-dependent state transitions for profit or information leakage. In the blockchain context, particularly within Automated Market Maker (AMM) DEXs, sandwich attacks induce price slippage at the victim’s expense and enable precision market manipulation. Recent studies also characterize "sandwich" attacks against LLMs using multi-language prompts to circumvent safety filters. This article systematically examines sandwich attacks, their formal definitions, detection and mitigation frameworks, economic impact, advanced variants, and cross-domain extensions.

## 1. Formal Definition and Transactional Mechanism

In blockchain and AMM protocols, a sandwich attack is defined by the sequence: the attacker issues a front-running transaction (T₁), followed by the victim’s transaction (T_V), and concludes with a back-running transaction (T₂). Formally, in a constant product market (state (x, y), k = x·y), the sequence transitions as follows [2009.14021]:

- T_A₁: Attacker swaps δ_x^{A1} at state s₀ = (x₀, y₀), updating to (x₁, y₁).
- T_V: Victim swaps δ_x^V, transitioning to (x₂, y₂).
- T_A₂: Attacker reverses or closes the position, yielding final balances (x₃, y₃).

Profit is extracted as:
$$
\text{profit} = \delta_x^{A2} - \delta_x^{A1}
$$

The attacker leverages deterministic AMM formulas to maximize gain, subject to slippage constraints specified by the victim. This structure is generalized to high-level attack trees via SAND (Sequential AND) operators, enforcing strict ordering [1503.02261]:
$$
\text{SAND}(T_{A1}, T_V, T_{A2})
$$
Such formalism enables precise modeling of temporal dependencies.

## 2. Detection Algorithms and Analysis Frameworks

Post-Merge Ethereum ecosystem dynamics necessitate robust detection methodologies. Heuristic, rule-based approaches yield frequent misclassifications, missing multi-layered and conjoined varieties. Advanced algorithmic techniques utilize profit-motivated identification on swap graphs [2405.17944]:

- Compute "token ratio" for each swap:
$$
\text{ratio} = \frac{\text{tkn}_{i,\text{out}}}{\text{tkn}_{i,\text{in}}}
$$
- Employ depth-first search (DFS) across swap routes to convert losses into gains through available paths, replacing naive two-transaction structures.
- Generalized detection captures multi-victim/multi-attacker patterns:
    - Chronological sequence (victim sandwiched),
    - Address linkage,
    - Opposite swap directions and matching patterns.

GasTrace [2405.19971] uses cascade classification:
- Stage 1 (R1): SVM (RBF kernel) on gas and transaction features yields probabilistic flags.
- Stage 2 (R2): Graph Attention Network (GAT) analyzes behavioral network correlations for improved generalization, yielding 96.73% accuracy and 95.71% F1 for malicious account identification.

## 3. Economic and Empirical Characteristics

Empirical analyses across Ethereum DEXs (Uniswap) indicate that single adversaries reliably execute sandwich attacks by monitoring the mempool for pending victim transactions. Experiments demonstrate:
- 19/20 successful attacks with round-trip detection and execution latencies of ~450 ms and 200 ms, respectively.
- Transactions remain pending for 23–36 seconds on average, allowing precise position insertion via marginal gas price increments (±1 Wei) [2009.14021].
- 79% of blocks ordered by gas price facilitate reliable positioning.

Profitability is sensitive to competitive dynamics. In environments with multiple adversaries:
- With two adversaries, profit drops ≈51%; five adversaries to ≈81.4%; ten adversaries to ≈91.5% lower than the single-attacker scenario.
- Multi-layered burger attacks and conjoined sandwich attacks (back-to-back attackers and multiple victims) yield up to 5× higher revenues than canonical attacks [2405.17944].

## 4. Prevention, Mitigation, and Protocol Design

Preventative designs employ both game-theoretic and cryptographic mechanisms. Game-theoretic approaches derive optimal slippage tolerances [2202.03762]:

- Attack profitability threshold: $s_a = (2b)/(\delta_{v_y})$.
- Failure-rebalancing threshold:
$$
s_r = \frac{p(s, \delta_{v_x})}{1-p(s, \delta_{v_x})} \cdot \frac{(l+m) b}{\delta_{v_y} + E(s | \text{failed})}
$$
- Dynamic algorithm sets $s = s_a - \varepsilon$ (if $s_r < s_a$), otherwise $s = s_r$, minimizing both attack and failure costs.

Protocol-level countermeasures center on batch trading (FM-AMM) and transaction reordering randomization:

- FM-AMM batches all trades in a time window, computes a clearing price $p^*$:
$$
p^* = \arg \max_p \left\{ \sum_i \varphi_i(p) \right\}
$$
Subject to:
$$
\sum_i x_i(p) = 0
$$
- Eliminates sandwiching by removing intra-batch order distinctions [2307.02074]. Batch clearing statistically eliminates MEV opportunities and shifts fee returns in favor of liquidity providers.

- Partitioned and Permuted Protocol (Π³): Miners/Leaders jointly commit random seeds, revealed post-commitment, which via PRG and permutation algorithms, randomize transaction order [2307.02954]. Chunking each transaction into $m$ units multiplies the order space to $(n_{tx} \cdot m)!$, negating adversarial ordering. Security analysis bounds adversarial advantage as exponentially small in $n_l$ and $m$, forming a quasi-strong subgame perfect $\varepsilon$-Nash equilibrium.

## 5. Advanced Variants and Landscape Characterization

Large-scale studies surveyed >2 billion transactions and >2 million PBS blocks [2405.17944], finding:
- ~3.02 million sandwich attacks (Ethereum), including 395,779 multi-layered and 31,878 conjoined attacks.
- Multi-layered burger attacks: several victims, more than two attacker transactions per block.
- Conjoined attacks: attacker transactions executed sequentially cause larger price swings and higher per-event profits (median victims up to 4, profits ~5× baseline).
- The prevalence is highest in volatile token ecosystems ("meme coins") and private transaction pools (e.g., Flashbots Relay), where PBS architecture changes market efficiency and MEV extraction patterns.

## 6. Cross-Domain Extensions: LLM Prompt Sandwiching

A recently identified variant targets LLM safety protocols by sandwiching adversarial queries among benign ones in low-resource languages [2404.07242]. Mechanism details:
- Craft prompts with a mix of non-English or low-resource languages, hiding the harmful query centrally.
- Mechanism exploits model "attention blink," overwhelming transformer attention and bypassing English-trained safety filters.
- Empirical evaluation (50 adversarial queries across Gemini Pro, Bard, LLaMA-2-70-B, GPT-3.5/4, Claude-3-OPUS) reveals breaches of safety controls >50% of the time, generating misaligned outputs.
- Implications highlight the necessity for multilingual safety training and transformer-level robustness analyses.

## 7. Formal Modeling: Attack Trees and Sequential Conjunction

SAND attack trees offer a foundation for formally capturing sandwich attacks’ ordered dependencies [1503.02261]. Utilizing non-commutative sequential conjunction and series-parallel graph semantics, such trees model the strict ordering:
$$
\text{SAND}(front\text{-}run, victim\_action, back\text{-}run)
$$
Axiomatization and term rewriting yield unique canonical forms, supporting both qualitative and quantitative risk analysis (e.g., cumulative time or cost of attack steps), thus enabling systematic vulnerability assessment in both financial and cyber-physical contexts.

---

Sandwich attacks epitomize the critical role of transaction ordering in adversarial behavior within decentralized and AI-driven systems. Their study reveals deep interplays among formal modeling, detection, economics, protocol engineering, and cross-domain risk mitigation. Recent research demonstrates that while precision adversarial sequencing drives profit and information leakage, emerging game-theoretic defenses, randomized orderings, and batch-clearing mechanisms provide tangible, systematic countermeasures for blockchain and machine learning platforms alike.

Source: https://www.emergentmind.com/topics/sandwich-attacks