What is Sandwich Attack?

BeginnerDec 10, 2023
A Sandwich Attack in the sphere of Decentralized Finance (DeFi) represents a sophisticated form of market manipulation on decentralized exchanges (DEXs). This type of attack leverages the fundamental principles of blockchain technology—such as transparency and immutability—to the attacker's advantage, often at the expense of regular users.
What is Sandwich Attack?

What is a Sandwich Attack?

A Sandwich Attack is a strategic exploitation of a transaction initiated by a user. The attacker, utilizing the public nature of blockchain transactions, identifies a pending transaction that has the potential to influence the market price of a certain cryptocurrency. Capitalizing on this information, the attacker orchestrates their transactions around the user’s, effectively ‘sandwiching’ the original transaction.

The process begins with the attacker placing a transaction ahead of the user’s, offering a higher gas fee to expedite its processing, a tactic known as ‘front-running.’ This initial transaction typically mirrors the user’s intended trade, leading to a shift in the asset’s market price due to immediate supply and demand dynamics.

Subsequently, the user’s transaction is processed, but now at a less favorable price point due to the market shift instigated by the attacker’s front-running transaction. The final phase of the attack involves the attacker immediately executing a follow-up transaction, often selling the asset, which may further influence the asset’s price, a strategy referred to as ‘back-running.’

This sequence of calculated moves constitutes the Sandwich Attack, aptly named for the way the user’s transaction is ‘sandwiched’ between the attacker’s front-running and back-running transactions. The strategy is particularly insidious because it exploits the very features that make blockchain transparent and secure, turning these attributes into vulnerabilities.

Sandwich Attacks underscore the need for continuous advancements in this space, balancing the transparency that underpins blockchain technology with protective measures that safeguard user interests. This introduction serves as a precursor to a deeper exploration of the mechanics, implications, and preventative strategies surrounding Sandwich Attacks in the evolving landscape of DeFi.

Maximal Extractable Value (MEV) and Sandwich Attacks

Maximal Extractable Value (MEV) is a concept that has gained significant attention in the context of blockchain and decentralized finance (DeFi). It refers to the maximum value that can be extracted from blockchain transaction reordering by miners or validators. MEV arises from the unique ability of miners to choose the order of transactions in a block, potentially influencing the outcome of trades and other actions on the blockchain.

Sandwich Attacks are a prime example of MEV in action. In these attacks, the perpetrators exploit their ability to foresee and manipulate transaction orders to their advantage. By strategically placing their transactions before and after a victim’s transaction, attackers can extract value from the victim’s trade. This is achieved through front-running (placing a buy order before the victim’s buy order to drive up the price) and back-running (selling off the asset after the victim’s purchase at the inflated price).

The Origins of Sandwich Attacks

The emergence of sandwich attacks in the decentralized finance (DeFi) sector underscores complex security and ethical challenges in blockchain technology. These manipulative strategies, though gaining prominence recently, are not new. They were brought to the forefront, particularly in the context of DeFi, following Ethereum co-founder Vitalik Buterin’s elucidation in 2018.

Buterin’s analysis in 2018 shed light on a critical issue: the susceptibility of blockchain’s transaction-ordering process to exploitation, known as front-running. He articulated how the very transparency of blockchain, a feature designed for trust and security, could inadvertently facilitate unfair market practices. This transparency allows all participants on the network to see transactions awaiting confirmation in the so-called ‘mempool.’ Savvy actors could, therefore, anticipate market movements and manipulate them for profit, setting the stage for sandwich attacks.

The discourse highlighted the need for a robust framework to ensure fairness and privacy in transaction ordering, acknowledging that these were not just technical but also ethical issues. The revelations underscored the urgency for solutions that would instill confidence among users and uphold the principles of equitable market conditions.

Today, these early conversations continue to influence the development of protective measures within DeFi platforms. The insights derived are integral to evolving security protocols and operational practices, ensuring that the DeFi space can mature into a secure and fair market for all participants.

Why do Sandwich Attacks Happen?

The occurrence of sandwich attacks in the DeFi space is intricately linked to several factors inherent in the technology and structure of blockchain transactions. One of the primary reasons these attacks are possible, and indeed prevalent, relates to the transparency and procedural dynamics of blockchain transactions.

  1. Transparency and Real-Time Data: The very nature of blockchain technology is transparency, where every transaction is publicly recorded and visible. This characteristic, while designed to foster trust and openness, also allows potential attackers to monitor transactions in real-time. They can see detailed information about pending transactions, including the assets involved and the transaction amounts. This level of visibility provides an opportunity for malicious entities to strategize their attacks based on real-time data.
  2. Pending Transaction Pool (Mempool): When users initiate transactions, these do not get processed immediately. Instead, they enter a ‘mempool’ of pending transactions, where they wait to be confirmed and added to the blockchain. This waiting room is publicly visible, and the transactions within it are in a vulnerable position. Attackers scrutinize the mempool to identify transactions that they can exploit for sandwich attacks.
  3. Gas Fees and Transaction Prioritization: The blockchain network prioritizes transactions based on gas fees. Users can opt to pay higher gas fees for their transactions to be processed faster. Attackers exploit this system by paying higher fees to prioritize their fraudulent transactions for execution before and after the target transaction, hence the term ‘sandwich’ attack. They essentially ‘bid’ their way to the front of the line, ensuring their transactions are processed before others in the mempool.
  4. Market Manipulation and Profit Motive: The ultimate goal of sandwich attacks is profit. By front-running a user’s transaction, attackers can buy assets before the user does, artificially driving up the market price. After the user’s transaction is completed at this inflated price, attackers sell off the assets at a profit. This strategy is particularly effective in decentralized exchanges where large trades can significantly impact prices.
  5. Automated Bots and High-Frequency Trading: These attacks are typically automated, with bots programmed to monitor the mempool continuously, identify potential target transactions, and execute sandwich attacks. These bots can operate at high speed, allowing them to execute multiple steps of the attack within fractions of a second. They leverage high-frequency trading strategies, often outpacing regular users who manually execute their transactions.

How does a Sandwich Attack work?

1. Observation and Target Identification

The initial phase of a sandwich attack involves surveillance. Attackers, often using automated bots, continuously monitor the state of pending transactions on the blockchain. These transactions are visible in the blockchain’s mempool, a sort of “waiting room” for all operations awaiting confirmation. When the attacker identifies a transaction of interest — typically, one involving a substantial trade — they prepare to execute their manipulative strategy.

2. Initiating the Attack - Front-Running

Once the target is identified, the attacker initiates the first part of the sandwich attack, known as front-running. They issue a transaction involving the same asset as the victim, but crucially, they offer a higher gas fee for their transaction. This higher fee incentivizes miners to prioritize the attacker’s operation over others in the mempool. As a result, the attacker’s transaction is processed first, even if it was issued after the victim’s.

In this phase, the attacker typically purchases the asset, which can cause the asset’s market price to surge, especially if the original transaction size was significant enough to impact the market.

3. Victim’s Transaction Execution

Following the front-running phase, the victim’s transaction comes into play. However, due to the prior manipulations, the market conditions are now different from when the victim initiated their transaction. If the victim was buying, they might now face a higher price due to the increased demand artificially created by the attacker’s front-running transaction.

4. Completing the Attack - Back-Running

The final phase of the sandwich attack is back-running. After the victim’s transaction is processed, the attacker immediately follows up with another transaction, this time selling the asset they initially acquired. Given that the asset’s price was inflated by their actions and the victim’s substantial transaction, the attacker can often sell at a profit. This sale might also contribute to a price decline, potentially leaving the victim with an asset that’s now depreciating.

Throughout this process, the attacker capitalizes on several factors: the predictability of market reactions to large orders, the public visibility of the blockchain’s transaction queue, and the ability to influence transaction processing orders through gas fees.

Examples of Sandwich Attacks

PEPE Network Exploitation

The PEPE token network, inspired by memes, became a notable example of sandwich attack vulnerability. Initially, the PEPE token did not have significant liquidity or popularity. However, a tweet claiming a PEPE bag’s value surged from $250 to $1.5 million sparked interest and hype. This led to an increase in the token’s value, attracting attackers. Using sandwich attack bots, an attacker front-ran PEPE buy transactions, inflating the token prices. The same attacker also targeted CHAD tokens, spending over $1.28 million in transaction fees within 24 hours and profiting more than $1.4 million at the expense of traders who bought the tokens at inflated prices.

Uniswap and PancakeSwap Vulnerabilities

Uniswap and PancakeSwap, being among the most popular decentralized exchanges (DEXs), have frequently been targets for sandwich attacks. These platforms, due to their Automated Market Maker (AMM) model, allow for direct peer-to-peer trading without an order book. Attackers exploit this by monitoring large pending transactions and executing their own transactions with higher gas fees to manipulate asset prices. For instance, an attacker might observe a large buy order on Uniswap and quickly place a buy order for the same asset with a higher gas fee, followed by a sell order after the victim’s transaction. This sequence of events leads to the victim purchasing the asset at an inflated price, while the attacker profits from the price differential.

SushiSwap Attacks

SushiSwap, similar to Uniswap, operates on an AMM model and has been susceptible to sandwich attacks. The platform’s liquidity pools, which are essential for its trading mechanism, become the focal point of these attacks. Attackers, by executing well-timed trades around large orders, can cause significant slippage in prices. This not only affects the individual trader involved in the large transaction but also impacts the overall price stability within the liquidity pool, leading to broader market distortions.

The Consequences of Sandwich Attacks

The consequences of sandwich attacks in the decentralized finance (DeFi) sector are multifaceted and detrimental, impacting both individual traders and the broader DeFi ecosystem. For individual traders, particularly the uninitiated, these attacks pose a significant financial risk. They often find themselves inadvertently purchasing assets at inflated prices due to manipulative trades executed by attackers. This not only leads to immediate financial loss but also engenders a sense of mistrust among participants, deterring them from further engagements in DeFi transactions.

Sandwich attacks contribute to an overall atmosphere of unpredictability and unfairness within the DeFi markets. They exacerbate market volatility, making trading more expensive for everyone involved. This is due to the increased competition among traders to outmaneuver potential attacks, often resulting in higher transaction fees (gas fees) in the quest to prioritize their trades on the blockchain.

The broader DeFi ecosystem also suffers due to these manipulative practices. As trust in the system erodes, the participation and influx of new users or investors might stagnate or decline. This reduction in active participation can lead to decreased liquidity, which is vital for the health and growth of DeFi platforms. Furthermore, consistent market manipulations attract stringent scrutiny from regulatory bodies, potentially leading to restrictive regulations that could stifle innovation and growth in the space.

How to Avoid Sandwich Attacks

Avoiding sandwich attacks, particularly for individual users, involves a combination of strategic trading, awareness, and sometimes the use of advanced tools or platforms.

While these strategies can help mitigate the risk of sandwich attacks, they are not foolproof. The evolving nature of DeFi means that users and platforms continually need to adapt to new strategies employed by malicious actors. Here are some practical steps:

Slippage Tolerance Settings

When using DeFi platforms, users can adjust their slippage tolerance. This setting allows a transaction to go through only if the price slippage is within a certain percentage. Setting a low slippage tolerance can prevent a transaction from being executed if an attacker tries to manipulate the price significantly.

Using Privacy Solutions or Protocols

Some blockchain protocols or tools are designed to conceal transaction details, providing privacy for traders. Services like Tornado Cash or protocols implementing zero-knowledge proofs can help mask transaction intentions, making it harder for attackers to identify transactions to target.

Gas Price Awareness

Being aware of gas prices and avoiding transactions during peak times can reduce the risk. High network activity often attracts attackers due to the potential for a more significant profit. Scheduling transactions during quieter periods, if possible, can lower risk.

Transaction Amount Limitation

Splitting a large transaction into smaller ones can sometimes help. It makes it less attractive for an attacker, as the potential profit might not justify the effort and cost of the attack. However, this comes with increased gas fees for multiple transactions.

Advanced Trading Interfaces

Some professional trading interfaces or DeFi platforms offer features like Transaction Ordering Protection (TOP) or private transaction pools to protect users from front-running and sandwich attacks.

Education and Awareness

Staying informed about the latest security practices and being aware of the inherent risks involved in trading on decentralized platforms is crucial. Knowledge is a significant part of prevention.

Conclusion

As the DeFi space continues to evolve, it becomes vital to address the systemic issues that facilitate manipulative practices like sandwich attacks. These attacks not only represent a significant impediment to the individual trader’s financial security but also pose a substantial threat to the overall perception and stability of the burgeoning DeFi ecosystem. Proactive measures, ranging from user education to the implementation of advanced transaction protocols, are essential in curbing these exploitative practices and fostering an environment of trust and reliability necessary for the sustained growth of DeFi.

The path forward requires a concerted effort from all stakeholders within the DeFi community. Developers, platform operators, regulators, and users need to collaborate, bringing innovative solutions and regulatory frameworks that uphold market integrity. By ensuring transactional transparency and fairness, the DeFi market can solidify its position as a legitimate and secure alternative to traditional financial systems, offering a diverse range of financial opportunities to users worldwide.

Author: Matheus
Translator: Cedar
Reviewer(s): Edward、Piccolo、Ashley He
* The information is not intended to be and does not constitute financial advice or any other recommendation of any sort offered or endorsed by Gate.io.
* This article may not be reproduced, transmitted or copied without referencing Gate.io. Contravention is an infringement of Copyright Act and may be subject to legal action.
Start Now
Sign up and get a
$100
Voucher!
Create Account