To better understand a sandwich attack, we first need to understand the process of buying and selling cryptocurrencies through an exchange.
Decentralized Exchanges (DEX) [→] are platforms that allow people to exchange one currency for another. The rules governing how much of one currency you can sell or buy for another are largely based on supply and demand.
More specifically, Automated Market-Making [→] mechanisms are used to determine price changes and, to some extent, to limit manipulation.
Market participants, that is, people who want to buy and sell coins, usually show up with a price at which they are willing to buy (bid) or sell (ask).
You can wait and only sell or buy at a preset price, holding out for a matching counterparty; this often takes time.
Alternatively, you can trade (buy/sell) immediately at the current market price. This exposes you to the possibility that your trade will be executed at a price different from what you saw when you submitted the order. When you accept the market price, you are filled at the price of actual execution, not necessarily the price you saw when you clicked.
That small time gap and the resulting price change is called slippage [→].
This is what sandwich attacks exploit. If many people are trying to buy the same coin, or if there is low liquidity on a particular exchange, a single large trade can move the price significantly.
An attacker takes advantage of that dynamic by creating an artificial price movement around a victim’s transaction.
For example, if you place your order to buy large amounts of a coin at market price, the attacker might have a bot that scans the network for such large transactions, then immediately places an order to buy the same amount as you but cuts in line by paying a higher gas fee [→] to ensure their purchase is processed before yours.
This large purchase signals high demand for that coin, so the price jumps up (market dynamics at play). The victim then gets filled in at a higher purchase price, but guess who turned around quickly to sell you those coins, the attacker!
This nets them a profit since they got to sell to the victim at that higher price. The attacker therefore "sandwiches" the victim's transaction, one transaction before and one after the victim and profits from the price movement they helped create.
In practice, this is a high-speed attack that requires a specific environment to work properly. For one, this works on an exchange where there isn't much trading happening (low liquidity), which causes small transactions to quickly shift trading prices. If an exchange has several transactions happening, these other transactions smooth out the supply/demand curve and will likely wipe out any potential profit the attacker stands to gain.
Also, most exchanges consider how much volume is being traded and then break up large transactions into smaller chunks and fill them gradually.
Here is another article you might like 😊 What Is A 51% Attack?