Skip to content

JMitander/0xBuilder

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

0xBuilder MEV Bot

License Contributions Welcome

Python Version geth Remix

AAVE Uniswap Sushiswap PancakeSwap Balancer

Infura CoinGecko CoinMarketCap CryptoCompare Etherscan

Table of Contents

Introduction

0xBuilder is an advanced Ethereum trading bot designed for high-frequency trading and MEV (Maximal Extractable Value) opportunities. It implements strategies like front-running, back-running, sandwich attacks, and flashloan executions using Python, Geth, Remix, and AsyncWeb3.py. The bot continuously monitors the Ethereum mempool for profitable transactions and executes trades automatically.

The bot is highly configurable, allowing users to adjust parameters, strategies, and risk levels based on their preferences. It supports multiple wallets, tokens, and trading pairs, with real-time market analysis and safety checks. The bot can be run on any Ethereum-compatible network, with support for various APIs and external data sources.

Note: 0xBuilder is a work in progress and is not production-ready. Use it at your own risk and discretion.

Features

0xBuilder-flow

  • Mempool Monitoring: Continuously monitors the Ethereum mempool for potential arbitrage and profit opportunities.
  • Strategy Execution: Implements various strategies, including front-running, back-running, sandwich attacks, and flashloan executions.
  • Flashloan Integration: Utilizes flashloans to maximize capital efficiency without initial capital requirements.
  • Market Analysis: Analyzes market conditions using data from multiple APIs and external data sources.
  • Dynamic Gas Pricing: Adjusts gas prices based on network conditions to optimize transaction inclusion and costs.
  • Nonce Management: Manages nonces effectively to prevent transaction failures due to nonce collisions.
  • Safety Mechanisms: Includes safety checks and validations to manage risks and ensure profitability.
  • Smart Contract Interactions: Interacts with various DeFi protocols, including Uniswap, Aave, Sushiswap, PancakeSwap, and Balancer.
  • Transaction Bundling: Groups multiple transactions into a single block for efficiency.
  • API Integration: Connects to various APIs for blockchain data, pricing, and market data.
  • Configurable Parameters: Allows users to adjust parameters, strategies, and risk levels based on preferences.
  • Detailed Logging: Provides detailed logs of bot activities, transactions, and strategies for analysis and debugging.
  • Customizable: Supports multiple wallets, tokens, and trading pairs, with the ability to add new strategies and features.

Project Structure

/0xBuilder/
β”œβ”€β”€ abi/
β”‚   β”œβ”€β”€ uniswap_router_abi.json
β”‚   β”œβ”€β”€ sushiswap_router_abi.json
β”‚   β”œβ”€β”€ pancakeswap_router_abi.json
β”‚   β”œβ”€β”€ erc20_abi.json
β”‚   β”œβ”€β”€ balancer_router_abi.json
β”‚   └── aave_lending_pool_abi.json
β”œβ”€β”€ contracts/
β”‚   β”œβ”€β”€ SimpleFlashloan.sol
β”‚   └── IERC20.sol
β”œβ”€β”€ javascript/
β”‚   β”œβ”€β”€ nonce.js
β”‚   β”œβ”€β”€ net.js
β”‚   β”œβ”€β”€ monitor.js
β”‚   β”œβ”€β”€ main.js
β”‚   β”œβ”€β”€ core.js
β”‚   β”œβ”€β”€ configuration.js
β”‚   β”œβ”€β”€ colorformatter.js
β”‚   β”œβ”€β”€ abi_registry.js
β”‚   β”œβ”€β”€ __init__.js
β”‚   └── jsutils/
β”‚       β”œβ”€β”€ strategyperformancemetrics.js
β”‚       β”œβ”€β”€ strategyexecutionerror.js
β”‚       β”œβ”€β”€ strategyconfiguration.js
β”‚       └── colorformatter.html
β”œβ”€β”€ linear_regression/
β”‚   β”œβ”€β”€ training_data.csv
β”‚   └── price_model.joblib
β”œβ”€β”€ python/
β”‚   β”œβ”€β”€ nonce.py
β”‚   β”œβ”€β”€ net.py
β”‚   β”œβ”€β”€ monitor.py
β”‚   β”œβ”€β”€ main.py
β”‚   β”œβ”€β”€ core.py
β”‚   β”œβ”€β”€ constants.py
β”‚   β”œβ”€β”€ configuration.py
β”‚   β”œβ”€β”€ abi_registry.py
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── pyutils/
β”‚       β”œβ”€β”€ strategyexecutionerror.py
β”‚       β”œβ”€β”€ strategyconfiguration.py
β”‚       β”œβ”€β”€ colorformatter.py
β”‚       └── __init__.py
β”œβ”€β”€ shared/
β”‚   └── MITANDER.py
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ token_addresses.json
β”‚   β”œβ”€β”€ erc20_signatures.json
β”‚   └── token_symbols.json
β”œβ”€β”€ Logs/
β”‚   └── 0xBuilder_log.txt
β”œβ”€β”€ .env.example
β”œβ”€β”€ .gitignore
β”œβ”€β”€ CONTRIBUTING.md
β”œβ”€β”€ LICENSE
β”œβ”€β”€ README.md
└── requirements.txt

Description of Key Directories and Files

  • abi/: Contains JSON files for various smart contract ABIs used in the project.

  • contracts/: Includes Solidity smart contracts such as SimpleFlashloan.sol and IERC20.sol.

  • javascript/: Holds all JavaScript files related to the project, including utility scripts in the jsutils/ subdirectory.

  • linear_regression/: Contains data and models related to linear regression analysis, such as training_data.csv and price_model.joblib.

  • python/: Contains Python scripts that form the core functionality of the project. The pyutils/ subdirectory includes utility modules for error handling and configuration.

  • shared/: Includes shared Python scripts like MITANDER.py that might be used across different parts of the project.

  • utils/: Stores utility JSON files that hold token addresses, ERC20 signatures, and token symbols.

  • Logs/: Maintains log files such as 0xBuilder_log.txt to track bot activities and operations.

  • .env.example: Example environment variables file to guide configuration.

  • .gitignore: Specifies files and directories to be ignored by Git.

  • CONTRIBUTING.md: Guidelines for contributing to the project.

  • LICENSE: Contains the licensing information for the project.

  • README.md: Provides an overview and documentation for the project.

  • requirements.txt: Lists the Python dependencies required for the project.

Prerequisites

Before running 0xBuilder, ensure you have the following:

System Requirements

  • Operating System: Ubuntu 22.04 LTS or later (Windows 11 and macOS Ventura also supported)
  • Python: Version 3.12 or higher
  • Node.js: Version 18 LTS or higher (required for smart contract deployment)
  • Geth: Latest stable version for running a full Ethereum node
  • Internet: High-speed connection with minimum 50Mbps upload/download
  • Hardware:
    • CPU: 4+ cores, 3.0GHz or faster
    • RAM: 16GB minimum, 32GB recommended
    • Storage: 2TB NVMe SSD recommended
    • Network: Low-latency ethernet connection

Software Dependencies

Primary Components:

  • Execution Client: Latest version of Geth, Nethermind, or Besu
  • Consensus Client: Latest version of Prysm or Lighthouse
  • Development Tools:
    • solc v0.8.19 or higher
    • web3.py v6.0 or higher
    • ethers.js v6.0 or higher
    • All Python packages from requirements.txt

Additional Requirements:

  • Git: Latest stable version for version control
  • Docker: Latest stable version (optional, for containerization)
  • Build Tools: make, gcc, and platform-specific compilers

Ethereum Node Setup

Choose and set up an execution client (EL) compatible with the Ethereum network:

Client Language OS Support Networks Sync Methods
Geth Go Linux, Windows, macOS Mainnet, Sepolia, Holesky Snap, Full
Nethermind C#/.NET Linux, Windows, macOS Mainnet, Sepolia, Holesky Snap, Fast, Full
Besu Java Linux, Windows, macOS Mainnet, Sepolia, Holesky Snap, Fast, Full
Erigon Go Linux, Windows, macOS Mainnet, Sepolia, Holesky Full
Reth Rust Linux, Windows, macOS Mainnet, Sepolia, Holesky Full
EthereumJS TypeScript Linux, Windows, macOS Sepolia, Holesky Full

Geth Configuration

  1. Installation: Follow the official Geth installation guide.

  2. Launch Node:

    geth --mainnet \
      --syncmode "snap" \
      --http \
      --http.api "eth,net,web3,txpool" \
      --ws \
      --ws.api "eth,net,web3,txpool" \
      --maxpeers 100 \
      --cache 8192 \
      --ipcpath "/path/to/geth.ipc"
  3. Monitor Sync:

    # Connect to node
    geth attach ipc:/path/to/geth.ipc
    
    # Check sync status
    > eth.syncing

Beacon Node Setup

For PoS consensus layer, install either:

Installation

Cloning the Repository

git clone https://github.com/jmitander/0xBuilder.git
cd 0xBuilder

Setting up Virtual Environment

Using a virtual environment is strongly recommended to manage dependencies and avoid conflicts:

For Linux/MacOS:

# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate

# Verify activation
which python

For Windows:

# Create and activate virtual environment
python -m venv venv
.\venv\Scripts\activate

# Verify activation
where python

Installing Dependencies

Install required packages:

# Upgrade pip to latest version
python -m pip install --upgrade pip

# Install dependencies
pip install -r requirements.txt

# Verify installations
pip list

Configuration

Environment Variables

  1. Create a .env file in the project root:
# Linux/MacOS
cp .env.example .env

# Windows
copy .env.example .env
  1. Configure the environment variables in .env:

    • Add API keys from various services
    • Configure node endpoints
    • Set up wallet details
    • Define smart contract addresses
  2. Validate the configuration:

# Verify .env file exists and permissions
ls -la .env

# Set secure file permissions (Linux/MacOS)
chmod 600 .env

Example .env configuration:

# API Configuration
ETHERSCAN_API_KEY=your_etherscan_api_key
INFURA_PROJECT_ID=your_infura_project_id
COINGECKO_API_KEY=your_coingecko_api_key
COINMARKETCAP_API_KEY=your_coinmarketcap_api_key
CRYPTOCOMPARE_API_KEY=your_cryptocompare_api_key

# Ethereum Node Configuration
HTTP_ENDPOINT=http://127.0.0.1:8545
WS_ENDPOINT=wss://127.0.0.1:8546
IPC_ENDPOINT=/path/to/geth.ipc

# Wallet Configuration
PRIVATE_KEY=your_private_key
WALLET_ADDRESS=0xYourWalletAddress
PROFIT_WALLET=0xYourProfitAddress

# Token Configuration
TOKEN_LIST_PATH=utils/token_addresses.json
TOKEN_SYMBOLS_PATH=utils/token_symbols.json

# DEX Router Configurations
UNISWAP_V2_ROUTER=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
SUSHISWAP_ROUTER=0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F
PANCAKESWAP_ROUTER=0xEfF92A263d31888d860bD50809A8D171709b7b1c
BALANCER_ROUTER=0x3E66B66Fd1d0b02fDa6C811da9E0547970DB2f21

# ABI Paths
UNISWAP_V2_ABI=abi/uniswap_router_abi.json
SUSHISWAP_ABI=abi/sushiswap_router_abi.json
PANCAKESWAP_ABI=abi/pancakeswap_router_abi.json
BALANCER_ABI=abi/balancer_router_abi.json
ERC20_ABI=abi/erc20_abi.json

# Flashloan Configuration
AAVE_V3_FLASHLOAN_CONTRACT=0xYourFlashloanContractAddress
AAVE_V3_LENDING_POOL=0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2

Configuration Files

Essential JSON configuration files must be present in the utils directory:

File Description Format
token_addresses.json Actively monitored token contracts {"symbol": "address"}
token_symbols.json Token address to symbol mapping {"address": "symbol"}
erc20_signatures.json Common ERC20 function signatures {"name": "signature"}

Verify all configuration files are properly formatted and contain valid data before starting the bot.

Deploying the Flashloan Contract

Deploy a flashloan contract compatible with Aave V3 or your preferred protocol to enable flashloan functionality.

Deployment Options

Using Remix IDE (Recommended)

  1. Launch Remix IDE
  2. Create SimpleFlashloan.sol
  3. Implement flashloan logic following Aave's specifications
  4. Compile:
    • Select Solidity compiler v0.8.19+
    • Verify successful compilation
  5. Deploy:
    • Connect MetaMask via "Injected Web3"
    • Supply constructor arguments
    • Confirm deployment transaction
  6. Update .env with contract address

Using Development Frameworks

  1. Install framework:
    # Hardhat
    npm install --save-dev hardhat
    # or Truffle
    npm install -g truffle
  2. Compile contract:
    # Hardhat
    npx hardhat compile
    # or Truffle
    truffle compile
  3. Deploy:
    # Hardhat
    npx hardhat run scripts/deploy.js
    # or Truffle
    truffle migrate
  4. Update .env configuration

Obtaining API Keys

Register and obtain API keys from:

  1. Infura - RPC endpoints
  2. Etherscan - Transaction data
  3. CoinGecko - Price feeds
  4. CoinMarketCap - Market data
  5. CryptoCompare - Real-time prices

Ensure that all API keys are stored securely and not shared publicly.

Installation

Cloning the Repository

git clone https://github.com/yourusername/0xBuilder.git
cd 0xBuilder

Setting up Virtual Environment

Using a virtual environment is strongly recommended to manage dependencies and avoid conflicts:

For Linux/MacOS:

# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate

# Verify activation
which python

For Windows:

# Create and activate virtual environment
python -m venv venv
.\venv\Scripts\activate

# Verify activation
where python

Installing Dependencies

Install required packages:

# Upgrade pip to latest version
python -m pip install --upgrade pip

# Install dependencies
pip install -r requirements.txt

# Verify installations
pip list

Configuration

Environment Variables

  1. Create a .env file in the project root:
# Linux/MacOS
cp .env.example .env

# Windows
copy .env.example .env
  1. Configure the environment variables in .env:

    • Add API keys from various services
    • Configure node endpoints
    • Set up wallet details
    • Define smart contract addresses
  2. Validate the configuration:

# Verify .env file exists and permissions
ls -la .env

# Set secure file permissions (Linux/MacOS)
chmod 600 .env

Example .env configuration:

# API Configuration
ETHERSCAN_API_KEY=your_etherscan_api_key
INFURA_PROJECT_ID=your_infura_project_id
COINGECKO_API_KEY=your_coingecko_api_key
COINMARKETCAP_API_KEY=your_coinmarketcap_api_key
CRYPTOCOMPARE_API_KEY=your_cryptocompare_api_key

# Ethereum Node Configuration
HTTP_ENDPOINT=http://127.0.0.1:8545
WS_ENDPOINT=wss://127.0.0.1:8546
IPC_ENDPOINT=/path/to/geth.ipc

# Wallet Configuration
PRIVATE_KEY=your_private_key
WALLET_ADDRESS=0xYourWalletAddress
PROFIT_WALLET=0xYourProfitAddress

# Token Configuration
TOKEN_LIST_PATH=utils/token_addresses.json
TOKEN_SYMBOLS_PATH=utils/token_symbols.json

# DEX Router Configurations
UNISWAP_V2_ROUTER=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
SUSHISWAP_ROUTER=0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F
PANCAKESWAP_ROUTER=0xEfF92A263d31888d860bD50809A8D171709b7b1c
BALANCER_ROUTER=0x3E66B66Fd1d0b02fDa6C811da9E0547970DB2f21

# ABI Paths
UNISWAP_V2_ABI=abi/uniswap_router_abi.json
SUSHISWAP_ABI=abi/sushiswap_router_abi.json
PANCAKESWAP_ABI=abi/pancakeswap_router_abi.json
BALANCER_ABI=abi/balancer_router_abi.json
ERC20_ABI=abi/erc20_abi.json

# Flashloan Configuration
AAVE_V3_FLASHLOAN_CONTRACT=0xYourFlashloanContractAddress
AAVE_V3_LENDING_POOL=0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2

Configuration Files

Essential JSON configuration files must be present in the utils directory:

File Description Format
token_addresses.json Actively monitored token contracts {"symbol": "address"}
token_symbols.json Token address to symbol mapping {"address": "symbol"}
erc20_signatures.json Common ERC20 function signatures {"name": "signature"}

Verify all configuration files are properly formatted and contain valid data before starting the bot.

Deploying the Flashloan Contract

Deploy a flashloan contract compatible with Aave V3 or your preferred protocol to enable flashloan functionality.

Deployment Options

Using Remix IDE (Recommended)

  1. Launch Remix IDE
  2. Create SimpleFlashloan.sol
  3. Implement flashloan logic following Aave's specifications
  4. Compile:
    • Select Solidity compiler v0.8.19+
    • Verify successful compilation
  5. Deploy:
    • Connect MetaMask via "Injected Web3"
    • Supply constructor arguments
    • Confirm deployment transaction
  6. Update .env with contract address

Using Development Frameworks

  1. Install framework:
    # Hardhat
    npm install --save-dev hardhat
    # or Truffle
    npm install -g truffle
  2. Compile contract:
    # Hardhat
    npx hardhat compile
    # or Truffle
    truffle compile
  3. Deploy:
    # Hardhat
    npx hardhat run scripts/deploy.js
    # or Truffle
    truffle migrate
  4. Update .env configuration

Obtaining API Keys

Register and obtain API keys from:

  1. Infura
  2. Etherscan
  3. CoinGecko
  4. CoinMarketCap
  5. CryptoCompare

Ensure that all API keys are stored securely and not shared publicly.

Running the Bot

Prerequisites

  • Synchronized Ethereum node
  • Active beacon node
  • Configured environment variables
  • Valid API keys

Launch Sequence

  1. Activate environment:

    source venv/bin/activate
  2. Start bot:

    python python/main.py

    Note: Adjust the script path if necessary based on your project structure.

Monitoring

  • Check Logs/0xBuilder_log.txt for detailed operation logs
  • Monitor console output for real-time status
  • Use Ctrl+C for graceful shutdown

Performance Optimization

  • Keep node fully synced
  • Monitor API rate limits
  • Maintain sufficient ETH balance
  • Regularly check log files
  • Update dependencies as needed

Strategies

0xBuilder implements several sophisticated trading strategies to capitalize on profitable opportunities within the Ethereum network:

Core Strategies

  • Front-Running: Executes higher-priority transactions ahead of detected profitable transactions
  • Back-Running: Places transactions immediately after identified profitable transactions
  • Sandwich Attacks: Employs coordinated front-running and back-running around target transactions
  • Flashloan Arbitrage: Leverages borrowed assets for zero-capital arbitrage opportunities

Technical Components

  • Nonce Management System: Maintains precise transaction ordering while preventing nonce collisions
  • Dynamic Gas Optimization: Automatically adjusts gas prices based on network conditions
  • Real-time Market Analysis: Processes market data to identify profitable trading opportunities
  • Multi-layer Safety Protocol: Implements comprehensive transaction validation and risk assessment
  • Transaction Bundling Engine: Optimizes efficiency by grouping multiple transactions per block

Logging

The bot maintains detailed logs in Logs/0xBuilder_log.txt, including:

  • Profitable transaction detection events
  • Strategy execution metrics
  • System errors and exceptions
  • Detailed transaction results

Logging configuration can be customized in python/main.py through the setup_logging() function.

Troubleshooting

Common Issues and Solutions

Issue Solution
Node Connection Failures Verify Ethereum node status and endpoint configuration
API Rate Limit Exceeded Implement request throttling or upgrade API tier
Insufficient Gas Balance Maintain adequate ETH for transaction fees
Nonce Synchronization Reset nonce manager or manually synchronize
Node Sync Status Ensure full node synchronization before operation

Debug Tips

  1. Enable verbose logging for detailed debugging
  2. Maintain updated dependencies
  3. Verify smart contract deployment on block explorers
  4. Test thoroughly on testnets before mainnet deployment

Contributing

We welcome contributions! Please review CONTRIBUTING.md for guidelines.

Contribution Process

  1. Fork the repository
  2. Create a feature branch
  3. Follow PEP 8 style guidelines
  4. Include unit tests
  5. Submit pull request

License

Licensed under the MIT License. See LICENSE file for details.

Disclaimer

IMPORTANT: This software is provided for educational and research purposes only. Use at your own risk.

Risk Factors

  • Trading strategies may be considered aggressive or unethical
  • Cryptocurrency trading carries significant financial risk
  • Smart contract interactions may contain unforeseen vulnerabilities

Security Notice

  • Protect private keys. Share them only with your dog. but never your cat! Cats cannot be trusted. πŸ•βœ… 🐱❌
  • Test thoroughly with small amounts first
  • Consider regulatory compliance in your jurisdiction