InfoSec Write-ups

A collection of write-ups from the best hackers in the world on topics ranging from bug bounties and CTFs to vulnhub machines, hardware challenges and real life encounters. Subscribe to our weekly newsletter for the coolest infosec updates: https://weekly.infosecwriteups.com/

Follow publication

Frontrunning Vulnerability: What It Is, How to Exploit, Prevent, and Mitigate It

JEETPAL
InfoSec Write-ups
Published in
2 min readJan 5, 2025

FREE ARTICLE

What is Frontrunning?

Frontrunning is a blockchain attack where an adversary observes pending transactions in the mempool and submits their own transaction with a higher gas fee to ensure it gets processed first. This allows the attacker to manipulate token prices or gain unfair advantages in financial operations.

In simpler terms, frontrunning happens when someone “jumps the queue” in transaction processing to exploit predictable outcomes for profit.

Image from internet

Vulnerable Code Example

Here’s an example of a vulnerable smart contract function:

function swapTokens(uint256 amount) public {
require(amount > 0, "Amount must be greater than zero");
uint256 price = getPrice();
balances[msg.sender] -= amount;
balances[address(this)] += amount;
emit TokensSwapped(msg.sender, amount, price);
}

Explanation:

  1. getPrice() is called before token transfer.
  2. An attacker can observe a pending transaction, frontrun it, and manipulate the price.
  3. The victim’s transaction executes with an unfavorable rate, and the attacker profits from the price difference.

How to Exploit Frontrunning

Steps to Exploit:

  1. Monitor the Mempool: Identify high-value swap transactions.
  2. Submit a Transaction with Higher Gas Fees: Ensure the attacker’s transaction executes before the victim’s.
  3. Manipulate the Price: Perform a large trade to change the token price.
  4. Let Victim’s Transaction Execute: The victim executes the trade at a manipulated price.
  5. Backrun Transaction: Reverse the trade to secure profit.

PoC (Proof of Concept):

  1. Victim initiates a swap of 100 tokens.
  2. Attacker sends a transaction with higher gas to swap 1000 tokens.
  3. Victim’s transaction executes with an unfavorable price.
  4. Attacker swaps back…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in InfoSec Write-ups

A collection of write-ups from the best hackers in the world on topics ranging from bug bounties and CTFs to vulnhub machines, hardware challenges and real life encounters. Subscribe to our weekly newsletter for the coolest infosec updates: https://weekly.infosecwriteups.com/

Written by JEETPAL

An Ethical hacker Bug hunter & Developer Connect me on social media via https://linktr.ee/jeetpal2007 query:jeetpal2007@gmail.com

Responses (4)

Write a response