What is a sandwich attack?#
A sandwich attack is when an attacker sandwiches your swap between two of their own transactions to make a profit.
How a sandwich attack works#
- You submit a swap, and it is pending confirmation in the public mempool.
- An attacker sees the pending swap and knows it will push the token's price up, so they buy first. This is called front-running.
- The attacker's buy completes at the lower price.
- Your swap completes at the now-higher price, so you receive fewer tokens than expected.
- The attacker sells at the higher price. This is called back-running.
The attacker profits from the price movement their transactions created — a gain for them and a loss for you. These attacks are possible because of price slippage and the public visibility of pending transactions.
How to reduce the risk#
- Use large liquidity pools. Attackers target small pools because a swap moves the price more there.
- Use swap protection. Routing your swap through a private transaction pool keeps it out of the public mempool, protecting it from front-running and sandwich attacks.
- Set an appropriate slippage limit so an unfavorable price moves the transaction to revert rather than fill.