Skip to content

A lightweight cli tool for analyzing Ethereum smart contract bytecode and identifying gas optimization opportunities

Notifications You must be signed in to change notification settings

devlongs/gas-profiler

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

EVM Gas Profiler

A lightweight command-line tool for analyzing Ethereum smart contract bytecode and identifying gas optimization opportunities.

Overview

EVM Gas Profiler disassembles EVM bytecode and provides detailed insights into gas consumption patterns, helping developers optimize their smart contracts before deployment.

Features

  • Bytecode Analysis: Parse and disassemble EVM bytecode with accurate gas cost calculations
  • Pattern Detection: Identify expensive operations (storage access, external calls, loops)
  • Optimization Suggestions: Get actionable recommendations with severity levels
  • Category Breakdown: View gas consumption by operation category
  • Multiple Input Methods: Support for hex strings, files, and stdin
  • Flexible Output: Human-readable text or machine-parseable JSON

Installation

Build from Source

git clone https://github.com/devlongs/gas-profiler.git
cd gas-profiler
go build -o gas-profiler ./cmd/profiler

Prerequisites

  • Go 1.21 or higher
  • Dependencies managed via go.mod (automatically handled)

Usage

Basic Usage

# Analyze bytecode from a file
./gas-profiler -file contract.bin

# Analyze inline bytecode
./gas-profiler -hex "0x6080604052..."

# Pipe bytecode from stdin
echo "0x608060405234801561001057600080fd5b50..." | ./gas-profiler

Options

-file string
    File containing bytecode (hex format)
-hex string
    Bytecode as hex string
-json
    Output as JSON (default: false)
-disasm
    Show full disassembly (default: false)
-top int
    Number of top opcodes to show (default: 10)

Examples

Text Output (default)

./gas-profiler -file contract.bin -top 15

JSON Output

./gas-profiler -hex "0x6080..." -json > analysis.json

With Disassembly

./gas-profiler -file contract.bin -disasm

Output

Text Format

═══════════════════════════════════════════════════════════════
                    EVM GAS PROFILER
═══════════════════════════════════════════════════════════════

Bytecode: 1234 bytes | Instructions: 456 | Static Gas: 12345

GAS BY CATEGORY
───────────────────────────────────────────────────────────────
  storage         5000 gas ( 40.5%) ████████
  arithmetic      3000 gas ( 24.3%) ████
  control         2000 gas ( 16.2%) ███

TOP 10 OPCODES
───────────────────────────────────────────────────────────────
   1. SLOAD           12 ×  100 =   1200 gas ( 15.2%)
   2. PUSH1           45 ×    3 =    135 gas (  8.5%)
   ...

EXPENSIVE PATTERNS
───────────────────────────────────────────────────────────────
  • Storage Read (×12) - SLOAD: 2100 gas (cold) / 100 gas (warm)
  • External Call (×3) - External calls: 100-2600 gas base

SUGGESTIONS
═══════════════════════════════════════════════════════════════

[HIGH] Multiple Storage Reads
  12 SLOAD operations detected
  - Cache storage variables in memory
  - Pack related variables into single slots

JSON Format

{
  "summary": {
    "bytecode_size": 1234,
    "instruction_count": 456,
    "total_static_gas": 12345
  },
  "categories": [...],
  "top_opcodes": [...],
  "patterns": [...],
  "suggestions": [...]
}

What It Detects

Critical Issues

  • Storage in Loops: SLOAD/SSTORE operations near jump instructions
  • Multiple Storage Writes: Excessive SSTORE operations (>3)

High-Priority Issues

  • Multiple Storage Reads: Excessive SLOAD operations (>5)
  • Multiple External Calls: Multiple CALL/DELEGATECALL/STATICCALL (>3)

Patterns Tracked

  • Storage operations (SLOAD, SSTORE)
  • External calls (CALL, DELEGATECALL, STATICCALL)
  • Contract creation (CREATE, CREATE2)
  • Hashing operations (KECCAK256)

How It Works

  1. Parse: Disassembles bytecode into EVM instructions with operands
  2. Analyze: Calculates gas costs and categorizes operations
  3. Detect: Identifies expensive patterns and potential optimizations
  4. Report: Generates actionable suggestions with severity levels

Gas costs are based on the latest Ethereum specifications (EIP-2929/Berlin fork).

Use Cases

  • Pre-deployment Analysis: Optimize contracts before going live
  • Code Review: Identify gas inefficiencies during audits
  • CI/CD Integration: Automate gas regression testing
  • Learning: Understand EVM gas mechanics and bytecode structure
  • Compiler Comparison: Test different Solidity optimizer settings

Limitations

  • Static Analysis Only: Cannot predict dynamic costs (memory expansion, actual storage access patterns)
  • Bytecode Level: Suggestions are generic; source-level context unavailable
  • Warm vs Cold: Assumes warm access costs; actual costs depend on execution context

Project Structure

gas-profiler/
├── cmd/profiler/       # CLI entry point
│   └── main.go
├── internal/
│   ├── analyzer/       # Gas analysis and pattern detection
│   │   ├── analyzer.go
│   │   └── analyzer_test.go
│   └── parser/         # Bytecode parsing and disassembly
│       ├── parser.go
│       └── parser_test.go
├── go.mod
└── README.md

Contributing

Contributions are welcome! Areas for improvement:

  • Additional pattern detection
  • More optimization suggestions
  • Support for newer EVM opcodes
  • Source-level mapping (with debug info)
  • Interactive mode

License

MIT License - see LICENSE file for details

Acknowledgments

Built with go-ethereum for EVM opcode definitions and gas costs.


Note: This tool provides optimization hints based on static bytecode analysis. Always test thoroughly and consider your specific use case before applying suggestions.

About

A lightweight cli tool for analyzing Ethereum smart contract bytecode and identifying gas optimization opportunities

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published