Blockchain Joggerbot (PoC)

A white-hat proof-of-concept demonstrating frontrunning vulnerabilities in public blockchain transaction pools through mempool monitoring, gas price manipulation, and strategic transaction ordering on Binance Smart Chain.

Table of contents

Understanding Frontrunning

Frontrunning is a form of market manipulation involving the act of placing a transaction in a queue with knowledge of a future transaction. In cryptocurrency markets, frontrunning occurs when a trader (or bot) monitors the blockchain's mempool (memory pool of pending transactions) and executes trades ahead of large pending transactions to profit from the anticipated price movement.

According to CoinMarketCap, frontrunning on a blockchain platform normally happens when a miner, who has access to information on pending transactions, places an order that would earn them a profit based on a pending trade. For instance, on the Ethereum blockchain, frontrunning can occur when bots quote a higher gas price than a pending trade, thus hastening its processing and ensuring their transaction is confirmed first.

Frontrunning exploits the transparent nature of public blockchains where all pending transactions are visible before confirmation. This creates an information asymmetry that sophisticated actors can exploit.

Technical Architecture

Joggerbot demonstrates sophisticated blockchain interaction and real-time transaction monitoring:

Core Components

main.py: Primary entry point with command-line interface for:

  • buy - Execute manual buy orders
  • sell - Execute manual sell orders
  • balance - Check wallet balances
  • run - Start automated frontrunning monitoring
  • pending-tx - Monitor pending transactions
  • estimate-gas - Calculate optimal gas parameters

Mempool Monitor: Real-time connection to BSC nodes monitoring:

  • Pending transactions before block confirmation
  • Transaction parameters (gas price, slippage, value)
  • Target contract addresses
  • Transaction senders and receivers

Contract Analyzer: Integration with BscScan API:

  • Automatic ABI retrieval for contracts
  • Source code verification
  • Function signature analysis
  • Liquidity contract identification

Trading Engine: Execution logic for:

  • Market buy/sell orders via PancakeSwap router
  • Dynamic gas price calculation
  • Slippage tolerance management
  • Transaction confirmation tracking

Key Dependencies

Web3.py: Python interface for Ethereum-compatible blockchains

  • Transaction construction and signing
  • Contract interaction
  • Gas estimation
  • Event monitoring

BscScan API: Contract data retrieval

  • ABI access for smart contracts
  • Source code verification
  • Transaction history analysis

Covalent API: Blockchain data queries

  • Token balances
  • Historical transaction data
  • Portfolio tracking

Telegram Bot API: Real-time notifications

  • Successful frontrun alerts
  • Error reporting
  • Performance metrics

Configuration Structure

The bot requires configuration in private.py:

# Wallet configuration
WALLET_ADDRESS = "0x..."
WALLET_PRIVATE_KEY = "99..."

# API keys
BSCSCAN_API_KEY = "KEY..."
COVALENTHQ_API_KEY = "ckey_..."

# Telegram notifications
TELEGRAM_MSG_CHANNEL_ID = -100...
TELEGRAM_ERROR_CHANNEL_ID = -100...
TELEGRAM_SESSION_NAME = "sessionname"
TELEGRAM_BOT_KEY = "numbers:numberslettersandsymbols"

Security Note: In this proof-of-concept, sensitive data was stored directly in Python files for simplicity. This is not recommended for production systems. Proper implementations should use:

  • Environment variables (.env files)
  • Secret management services (AWS Secrets Manager, HashiCorp Vault)
  • Hardware security modules for private key storage
  • Encrypted configuration files

Database Schema

The bot maintains a SQLite database tracking:

  • Liquidity contracts discovered
  • Transaction history
  • Profitability metrics
  • Error codes for failed operations

Error Codes:

  • 0: No errors
  • 1: API request returned non-200 status code
  • 2: API response status was "NOTOK"
  • 3: Expected functions not found in contract ABI

Mempool Monitoring and Exploitation

The core of Joggerbot is its ability to monitor and act on pending transactions before they're confirmed on the blockchain.

How Mempool Monitoring Works

1. Node Connection

The bot connects directly to BSC nodes (either local or via API) to access the mempool - the holding area for pending transactions waiting to be included in blocks.

2. Real-Time Filtering

As transactions enter the mempool, the bot filters for:

  • DEX interactions (PancakeSwap, Uniswap-like routers)
  • Swap functions (swapExactTokensForTokens, swapETHForExactTokens)
  • High slippage parameters (>10% tolerance)
  • Significant transaction values (above profitability threshold)

3. Transaction Decoding

When a potential target is identified:

  • Decode transaction input data
  • Extract token addresses
  • Calculate expected price impact
  • Estimate potential profit vs gas costs

4. Strategic Execution

If profitable:

  • Calculate optimal gas price (victim's gas price + premium)
  • Construct frontrunning transaction
  • Sign and broadcast immediately
  • Monitor for confirmation

5. Exit Strategy

Once the victim's transaction confirms:

  • Wait for price movement
  • Execute sell order
  • Calculate realized profit
  • Log results to database

The Sandwich Attack Pattern

The most effective frontrunning strategy implemented:

[Frontrun Buy] → [Victim's Transaction] → [Backrun Sell]
  1. Frontrun: Buy the token before victim, pushing price up
  2. Victim Executes: Large buy order increases price further
  3. Backrun: Immediately sell at inflated price

Gas Price Strategy

Critical to successful frontrunning:

Victim's Gas Price: 5 GWEI
Frontrun Gas Price: 5.5-6 GWEI (slightly higher to ensure priority)
Gas Limit: ~300,000 (typical for DEX swaps)

Profit Calculation:

Profit = (Sell Price - Buy Price) × Amount - (Gas Cost × 2)

The bot only executes a transaction if expected profit exceeds gas costs by a safe margin.

Vulnerabilities Exploited

High Slippage Settings: Users setting 15-20% slippage to ensure transaction success or after leaving previously used settings suitable for another token make themselves prime targets.

Predictable DEX Routers: Standard PancakeSwap/Uniswap interfaces make transaction behavior predictable.

Public Mempool: Complete transaction transparency before confirmation.

Gas Price Priority: Miners' economic incentive to prioritize higher-paying transactions.

Liquidity Pool Mechanics: AMM (Automated Market Maker) price curves make price impact calculable in advance.

Mitigation Strategies

Based on findings, users can protect themselves by:

  • Lower slippage tolerance (2-5% maximum)
  • Private transaction pools (Flashbots, MEV-protection services)
  • Limit orders instead of market orders
  • Transaction batching to reduce predictability
  • Layer 2 solutions with private mempools

Results and Findings

Technical Success

From a security research perspective, the project successfully demonstrated:

  • Mempool access is trivial: Standard node connections provide full visibility into pending transactions
  • High-slippage transactions are abundant: Many users sacrifice security for execution certainty, or just make mistakes or are unaware of what high slippages imply
  • Frontrunning is technically straightforward: The attack can be implemented with standard Web3 libraries
  • Gas price arbitrage works: Small gas premiums consistently ensure transaction priority
  • Profitability is achievable: Even after gas costs, frontrunning can be profitable on high-value transactions
  • Detection is difficult: Victims often don't realize they've been frontrun

Practical Findings

Vulnerability Prevalence:

  • Approximately 15-20% of DEX transactions had exploitable slippage settings
  • Larger transactions (>1 BNB value) were more likely to have high slippage
  • Retail traders more vulnerable than institutional players

Profitability Factors:

  • Transaction size matters: Frontrunning small trades often unprofitable due to gas costs
  • Network congestion helps: Higher base gas prices deter competition
  • Token liquidity crucial: Low-liquidity pairs offered higher percentage gains but more risk

Competition:

  • Multiple bots competing for same opportunities
  • Gas price bidding wars reduce profitability
  • Fastest infrastructure (local nodes) have significant advantage

Security Implications

This research highlights critical blockchain security issues:

For Users:

  • Public mempools expose transaction intent before execution
  • High slippage settings directly correlate with frontrunning risk
  • Standard DEX interfaces make behavior predictable
  • Most users unaware of the vulnerability

For Developers:

  • Current blockchain architectures prioritize transparency over privacy
  • MEV (Miner Extractable Value) creates perverse incentives
  • Private transaction pools are necessary for fair markets
  • Order types beyond market orders need better support

For the Ecosystem:

  • Frontrunning undermines trust in DeFi
  • Small traders disproportionately affected
  • Solution requires protocol-level changes
  • Education about proper slippage settings is critical

Ethical Conclusion

While technically successful, this proof-of-concept reinforces that:

  1. Frontrunning is a real threat to fair cryptocurrency markets
  2. Technical feasibility doesn't justify exploitation
  3. Transparency has trade-offs - public mempools enable attacks
  4. User education is essential for self-protection
  5. Protocol improvements (private mempools, better privacy) are necessary

This project was conducted in white-hat spirit to demonstrate vulnerabilities and encourage:

  • Protocol-level improvements
  • Better user education about slippage settings
  • Development of MEV-protection services
  • Awareness of blockchain transparency risks

The code remains available on GitHub for educational and security research purposes only.

Credits and Sources

This proof-of-concept project and article were informed by the following sources:

Primary References

Technical Resources

  • Web3.py Documentation: Python library for Ethereum blockchain interaction
  • BscScan API: Smart contract ABI and source code verification
  • Covalent API: Blockchain data queries and portfolio tracking
  • PancakeSwap: Decentralized exchange protocol documentation

Code Repository

The complete source code for this proof-of-concept is available on GitHub:

  • Repository: github.com/eliasiturri/joggerbot
  • Language Variants: Documentation available in English, Spanish, and Swedish
  • Disclaimer: For educational and security research purposes only

Notable Mentions

  • Flashbots: Initiative addressing MEV and frontrunning on Ethereum
  • Consensys Diligence: Research on taxonomy of frontrunning attacks
  • Research Papers: Various academic papers on MEV and blockchain security

Privacy and Security Note

All contract addresses and personal identifiable information have been redacted from the public repository. The original implementation included:

  • Personal wallet addresses
  • Private keys (now removed)
  • API keys (now require user configuration)
  • IP addresses of infrastructure

Important Security Reminder: This proof-of-concept stored sensitive data in Python files (private.py) for simplicity. Production systems should never store secrets in code. Best practices include:

  • Environment variables (.env files with proper .gitignore)
  • Secret management services (AWS Secrets Manager, HashiCorp Vault, Azure Key Vault)
  • Hardware security modules for cryptographic key storage
  • Encrypted configuration with access controls

Legal and Ethical Notice

Frontrunning in cryptocurrency markets raises serious ethical concerns:

  • Might not be illegal in many jurisdictions since it does not use privileged, but public information
  • Causes financial harm to other market participants
  • Undermines trust in decentralized finance

This research was conducted to:

  • Raise awareness of blockchain security vulnerabilities
  • Educate users about proper trading practices
  • Encourage protocol improvements for better privacy
  • Support development of MEV-protection solutions

Acknowledgments

Special thanks to:

  • The open-source blockchain development community
  • BSC node operators providing mempool access
  • Security researchers studying MEV and frontrunning
  • Academic institutions researching blockchain security