Skip to content

Adrijan-Petek/gas-fee-optimizer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Gas Fee Optimizer πŸš€

A full-stack, real-time gas fee monitoring and analytics platform for Ethereum Layer 2 networks (Base, Optimism, Arbitrum). Monitor gas prices across multiple chains, track trends, and get intelligent recommendations for when and where to execute your transactions.

Version License Node

✨ Features

Core Capabilities

  • Multi-Chain Monitoring: Real-time gas price tracking for Base, Optimism, and Arbitrum
  • Smart Recommendations: Intelligent algorithm recommends the cheapest chain for your transactions
  • Historical Analytics: 24h, 7d, and 30d gas price trends with statistical analysis
  • REST API: Comprehensive API endpoints for programmatic access
  • Real-time Dashboard: Beautiful React frontend with live price updates
  • Persistent Storage: SQLite database for historical data and analytics
  • Webhook Integration: Optional webhook notifications when prices drop below thresholds
  • Automated Scheduling: GitHub Actions workflow for continuous monitoring

Data Collected

  • Gas prices (base fees)
  • Priority fees (tips)
  • Statistical aggregates (min, max, average)
  • Recommendation history
  • Timestamp-based snapshots

πŸ—οΈ Architecture

gas-fee-optimizer/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ gas-optimizer.js      # Core gas fee fetcher & report generator
β”‚   β”œβ”€β”€ server.js             # Express API server
β”‚   β”œβ”€β”€ database.js           # SQLite operations
β”‚   └── scheduler.js          # Job scheduling
β”œβ”€β”€ client/                    # React frontend dashboard
β”‚   β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ App.js           # Main dashboard component
β”‚   β”‚   └── components/      # Reusable UI components
β”‚   └── package.json
β”œβ”€β”€ config/
β”‚   └── gas.config.json       # Configuration & thresholds
β”œβ”€β”€ reports/                   # JSON reports (auto-generated)
β”œβ”€β”€ data/                      # SQLite database location
β”œβ”€β”€ .env.example              # Environment template
└── package.json              # Dependencies

πŸš€ Quick Start

Prerequisites

  • Node.js 14+
  • npm or yarn
  • Ethereum RPC endpoints (free tier available from Alchemy, Infura, or Quicknode)

1. Installation

# Clone the repository
git clone https://github.com/yourusername/gas-fee-optimizer.git
cd gas-fee-optimizer

# Install root dependencies
npm install

# Install client dependencies
cd client && npm install && cd ..

2. Configuration

Copy .env.example to .env and fill in your RPC endpoints:

cp .env.example .env

Edit .env:

# Required: Ethereum L2 RPC Endpoints
RPC_BASE=https://mainnet.base.org
RPC_OPTIMISM=https://mainnet.optimism.io
RPC_ARBITRUM=https://arb1.arbitrum.io/rpc

# Optional: Webhook URL for alerts
WEBHOOK_URL=https://hooks.slack.com/services/YOUR/WEBHOOK/URL

# Server Configuration
API_PORT=5000
API_HOST=localhost

# Database
DATABASE_PATH=./data/gas-optimizer.db

# Polling
POLL_INTERVAL=5
HISTORY_RETENTION_DAYS=90

3. Run Core Gas Optimizer (One-time check)

npm start

Output:

{
  "timestamp": "2025-09-28T12:00:00Z",
  "best_chain": "optimism",
  "recommendation": "Send your transactions on Optimism now for lowest fees.",
  "chains": {
    "base": {"gas_price_gwei": 12, "priority_fee_gwei": 1.2},
    "optimism": {"gas_price_gwei": 6, "priority_fee_gwei": 0.8},
    "arbitrum": {"gas_price_gwei": 9, "priority_fee_gwei": 1.0}
  }
}

4. Start Full-Stack Application

# Terminal 1: Start API server
npm run server

# Terminal 2: Start React dashboard
npm run dev:client

Or run both together (requires concurrently):

npm run dev

Access the dashboard at: http://localhost:3000

πŸ“Š API Endpoints

Base URL: http://localhost:5000/api

Get Current Gas Prices

GET /api/current

Response:

{
  "base": {
    "gas_price_gwei": 12.5,
    "priority_fee_gwei": 1.2,
    "timestamp": "2025-09-28T12:00:00Z"
  },
  "optimism": {
    "gas_price_gwei": 6.3,
    "priority_fee_gwei": 0.8,
    "timestamp": "2025-09-28T12:00:00Z"
  },
  "arbitrum": {
    "gas_price_gwei": 9.1,
    "priority_fee_gwei": 1.0,
    "timestamp": "2025-09-28T12:00:00Z"
  }
}

Get Chain History

GET /api/chain/:name?limit=100

Parameters:

  • :name - Chain name: base, optimism, or arbitrum
  • limit - Number of records (default: 100, max: 1000)

Response:

{
  "chain": "optimism",
  "data": [
    {
      "timestamp": "2025-09-28T12:00:00Z",
      "gas_price_gwei": 6.3,
      "priority_fee_gwei": 0.8
    }
  ],
  "count": 1
}

Get Statistics

GET /api/stats?hours=24

Parameters:

  • hours - Time period for aggregation (default: 24)

Response:

{
  "time_period_hours": 24,
  "stats": {
    "base": {
      "avg_gas_price": 11.8,
      "avg_priority_fee": 1.15,
      "min_gas_price": 8.2,
      "max_gas_price": 15.4,
      "data_points": 288
    },
    "optimism": {...},
    "arbitrum": {...}
  }
}

Get Recommendations

GET /api/recommendations?limit=50

Response:

{
  "recommendations": [
    {
      "timestamp": "2025-09-28T12:00:00Z",
      "best_chain": "optimism",
      "recommendation": "Send your transactions on Optimism now for lowest fees."
    }
  ],
  "count": 1
}

Server Health

GET /api/health

Response:

{
  "status": "healthy",
  "server": {
    "uptime": 1234.56,
    "memory": {...}
  },
  "database": {
    "total_gas_records": 1440,
    "total_recommendations": 288,
    "oldest_record": "2025-09-27T12:00:00Z"
  }
}

πŸŽ›οΈ Configuration

config/gas.config.json

{
  "chains": {
    "base": {
      "threshold_gwei": 15
    },
    "optimism": {
      "threshold_gwei": 7
    },
    "arbitrum": {
      "threshold_gwei": 10
    }
  },
  "alert": {
    "enabled": true,
    "webhook": "${WEBHOOK_URL}"
  }
}

Environment Variables

Variable Description Default
RPC_BASE Base RPC endpoint Required
RPC_OPTIMISM Optimism RPC endpoint Required
RPC_ARBITRUM Arbitrum RPC endpoint Required
WEBHOOK_URL Slack/Discord webhook URL Optional
API_PORT Server port 5000
DATABASE_PATH SQLite database path ./data/gas-optimizer.db
POLL_INTERVAL Check interval (minutes) 5
HISTORY_RETENTION_DAYS Data retention period 90

πŸ“ˆ Dashboard Features

Real-time Display

  • Current gas prices for all chains
  • Priority fee estimates
  • Last update timestamp

Analytics Section

  • 24-hour average prices
  • Min/max price tracking
  • Statistical data points

Recommendations

  • Best chain for transactions
  • Action recommendations
  • Recommendation history table

Auto-refresh

  • Configurable refresh intervals (10s, 30s, 1m, 5m)
  • Manual refresh button
  • Error handling and notifications

πŸ”„ Scheduled Monitoring

GitHub Actions Setup

Create .github/workflows/gas-optimizer.yml:

name: Gas Fee Optimizer

on:
  schedule:
    - cron: '*/5 * * * *'  # Every 5 minutes
  workflow_dispatch:

jobs:
  check-gas:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Run gas optimizer
        env:
          RPC_BASE: ${{ secrets.RPC_BASE }}
          RPC_OPTIMISM: ${{ secrets.RPC_OPTIMISM }}
          RPC_ARBITRUM: ${{ secrets.RPC_ARBITRUM }}
          WEBHOOK_URL: ${{ secrets.WEBHOOK_URL }}
        run: npm start
      
      - name: Commit reports
        run: |
          git add reports/
          git commit -m "Add gas fee reports" || true
          git push

πŸ› οΈ Development

Available Commands

# Start core optimizer (single run)
npm start

# Start API server (watch mode)
npm run dev:server

# Start React frontend (development)
npm run dev:client

# Run both server & client
npm run dev

# Build React app for production
npm run build

# Schedule monitoring via node-schedule
npm run schedule

# Run tests
npm run test

Project Structure

src/
β”œβ”€β”€ gas-optimizer.js  # Main script - fetches gas data
β”œβ”€β”€ server.js        # Express API server
β”œβ”€β”€ database.js      # SQLite database module
└── scheduler.js     # Job scheduling

client/
β”œβ”€β”€ public/          # Static assets
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ App.js       # Main React component
β”‚   β”œβ”€β”€ index.js     # React entry point
β”‚   β”œβ”€β”€ index.css    # Tailwind CSS
β”‚   └── components/
β”‚       β”œβ”€β”€ GasPriceCard.js
β”‚       β”œβ”€β”€ AnalyticsChart.js
β”‚       └── RecommendationPanel.js
└── package.json

πŸ“š API Usage Examples

JavaScript/Node.js

const axios = require('axios');

// Get current prices
async function getCurrentPrices() {
  const response = await axios.get('http://localhost:5000/api/current');
  console.log(response.data);
}

// Get 24h statistics
async function getStats() {
  const response = await axios.get('http://localhost:5000/api/stats?hours=24');
  console.log(response.data);
}

// Find best chain for transactions
async function findBestChain() {
  const response = await axios.get('http://localhost:5000/api/recommendations?limit=1');
  const latest = response.data.recommendations[0];
  console.log(`Best chain: ${latest.best_chain}`);
}

Python

import requests

# Get current prices
response = requests.get('http://localhost:5000/api/current')
data = response.json()

for chain, prices in data.items():
    print(f"{chain}: {prices['gas_price_gwei']} Gwei")

cURL

# Get current prices
curl http://localhost:5000/api/current

# Get chain history (last 50 records)
curl "http://localhost:5000/api/chain/optimism?limit=50"

# Get stats
curl "http://localhost:5000/api/stats?hours=24"

πŸ”” Webhook Integration

Slack

WEBHOOK_URL=https://hooks.slack.com/services/YOUR/WEBHOOK/URL

Discord

WEBHOOK_URL=https://discord.com/api/webhooks/YOUR/WEBHOOK/URL

πŸ“¦ Dependencies

Backend

  • ethers.js - Ethereum interaction
  • express - Web server
  • axios - HTTP client
  • better-sqlite3 - Database
  • node-schedule - Job scheduling
  • cors - Cross-origin support
  • dotenv - Environment variables

Frontend

  • React 18 - UI framework
  • Tailwind CSS - Styling
  • Axios - API calls
  • Chart.js - Data visualization

πŸ§ͺ Testing

# Run test suite
npm run test

# Run with coverage
npm run test:coverage

# Watch mode
npm run test:watch

πŸ› Troubleshooting

API returns "No data available"

Solution: Run the core optimizer first to populate the database:

npm start

Database locked error

Solution: Check if another instance is running:

ps aux | grep node
# Kill processes if needed: kill -9 <PID>

RPC endpoint errors

Solution: Verify endpoints in .env:

curl https://mainnet.base.org -X POST -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":1}'

Port already in use

Solution: Change port in .env:

API_PORT=5001

πŸš€ Production Deployment

Using Docker

FROM node:18-alpine

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

COPY src ./src
COPY config ./config

ENV NODE_ENV=production
EXPOSE 5000

CMD ["npm", "run", "server"]

Deploy to Vercel (Frontend)

cd client
npm run build
# Deploy the build/ folder to Vercel

Deploy to Heroku

# Create Heroku app
heroku create gas-fee-optimizer

# Set environment variables
heroku config:set RPC_BASE="..." RPC_OPTIMISM="..." RPC_ARBITRUM="..."

# Deploy
git push heroku main

πŸ“Š Database

Schema

gas_history table:

- id (INTEGER PRIMARY KEY)
- timestamp (TEXT)
- chain (TEXT)
- gas_price_gwei (REAL)
- priority_fee_gwei (REAL)
- created_at (DATETIME)

recommendations table:

- id (INTEGER PRIMARY KEY)
- timestamp (TEXT UNIQUE)
- best_chain (TEXT)
- recommendation (TEXT)
- created_at (DATETIME)

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit changes: git commit -m 'Add amazing feature'
  4. Push to branch: git push origin feature/amazing-feature
  5. Open a Pull Request

πŸ“ License

MIT License - see LICENSE file for details

⭐ Support

If this project helps you, please star ⭐ it!

πŸ“§ Contact

For questions or suggestions, open an issue on GitHub.


Last Updated: September 2025
Version: 1.0.0
Status: Active Development βœ…

Releases

No releases published

Packages

 
 
 

Contributors