Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ run:
concurrency: 0
timeout: 10m
issues-exit-code: 1
tests: true
tests: false

output:
formats:
Expand Down Expand Up @@ -32,6 +32,7 @@ linters:
# You can't disable typecheck, see:
# https://github.com/golangci/golangci-lint/blob/master/docs/src/docs/welcome/faq.mdx#why-do-you-have-typecheck-errors
- unconvert
- bodyclose
settings:
errcheck:
check-type-assertions: false
Expand All @@ -46,6 +47,9 @@ linters:
goconst:
min-len: 3
min-occurrences: 2
gosec:
excludes:
- G115

formatters:
exclusions:
Expand Down
62 changes: 62 additions & 0 deletions examples/gas-comparison/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Gas Comparison Tool

A multi-network gas fee comparison tool that compares our gas estimation implementation against legacy estimators and Infura's Gas API.

## What It Does

- **Compares implementations**: Our new `GetTxSuggestions` vs old estimator vs Infura API
- **Multi-network support**: Ethereum, Arbitrum, Optimism, Base, Polygon, Linea, BSC, Status Network
- **Comprehensive analysis**: Priority fees, max fees, base fees, wait times, network congestion
- **Real vs local data**: Test with live networks or use local mock data

## Quick Start

```bash
# Test with local mock data
./gas-comparison -fake

# Test with real networks (requires Infura API key)
./gas-comparison -infura-api-key YOUR_API_KEY
```

## What You'll See

```
πŸ”Έ LOW PRIORITY FEES
Current Implementation: 200000 wei
Old Implementation: 330120 wei
Infura: 1000000 wei
Current vs Old: -130120 wei (-39.4%)
Current vs Infura: -800000 wei (-80.0%)

πŸ”Έ LOW WAIT TIME
Wait Time (Current): 72.0--12.0 seconds
Wait Time (Old): 125 seconds
Wait Time (Infura): 12.0-48.0 seconds
```

## Test Transaction

Uses a simple 0-valued ETH transfer from Vitalik's address:
- **From**: `0xd8da6bf26964af9d7eed9e03e53415d37aa96045`
- **To**: Zero address
- **Value**: 0 ETH
- **Data**: Empty

## Networks Tested

- **Ethereum Mainnet** (L1)
- **Arbitrum One** (ArbStack)
- **Optimism** (OPStack)
- **Base** (OPStack)
- **Polygon** (L1)
- **Linea** (LineaStack)
- **BNB Smart Chain** (L1)
- **Status Network Sepolia** (LineaStack)

## Use Cases

- **Development**: Test gas estimation accuracy across networks
- **Comparison**: Evaluate different fee strategies
- **Monitoring**: Track gas fee trends and network conditions
- **Validation**: Ensure our implementation matches industry standards
163 changes: 163 additions & 0 deletions examples/gas-comparison/data/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# Gas Data Generator

This program converts the functionality of `feesData.sh` into a Go program that fetches gas data from any blockchain network and generates a `data.go` file with the results using the existing SDK types.

## Usage

Run the generator with the required command line arguments:

```bash
cd examples/gas-comparison/internal/data

# BSC Mainnet
go run main.go -infura-api-key YOUR_API_KEY -rpc https://bsc-mainnet.infura.io/v3/YOUR_API_KEY

# Ethereum Mainnet
go run main.go -infura-api-key YOUR_API_KEY -rpc https://mainnet.infura.io/v3/YOUR_API_KEY

# Polygon Mainnet
go run main.go -infura-api-key YOUR_API_KEY -rpc https://polygon-mainnet.infura.io/v3/YOUR_API_KEY

# Show help
go run main.go -help
```

3. The program will:
- Create an RPC client connection to the specified network
- Automatically detect the chain ID from the RPC endpoint
- Use SDK's ethclient to fetch the latest block with full transactions
- Use SDK's ethclient to fetch fee history with percentiles [0, 5, 10, ..., 95, 100]
- Use SDK's infura client to fetch suggested gas fees for the detected chain ID
- Generate a chain-specific package and `data.go` file based on the detected chain ID

### Command Line Arguments

- **`-infura-api-key`** (required): Infura API key for gas suggestions
- **`-rpc`** (required): RPC URL for the blockchain network
- **`-help`**: Show help message with examples

### Automatic Chain ID Detection

The generator automatically detects the chain ID by calling `eth_chainId` on the RPC endpoint, eliminating the need to manually specify it.

### Supported Networks

The generator creates human-readable package names for popular networks:

| Chain ID | Package Name | Network Name |
|----------|--------------|--------------|
| 1 | `ethereum` | Ethereum Mainnet |
| 56 | `bsc` | BSC Mainnet |
| 137 | `polygon` | Polygon Mainnet |
| 42161 | `arbitrum` | Arbitrum One |
| 10 | `optimism` | Optimism Mainnet |
| 8453 | `base` | Base Mainnet |
| 43114 | `avalanche` | Avalanche C-Chain |
| 250 | `fantom` | Fantom Opera |
| 100 | `gnosis` | Gnosis Chain |
| 25 | `cronos` | Cronos Mainnet |
| Other | `chainXXX` | Chain XXX |

For unknown networks, the package name follows the format `chainXXX` where XXX is the chain ID.

## What it replaces

This Go program replaces the shell script `feesData.sh` which made these 3 requests:

1. **Latest Block**: `eth_getBlockByNumber` with `"latest"` and `true` parameters
2. **Fee History**: `eth_feeHistory` with block count `0x400` (1024 blocks) and percentiles
3. **Infura Suggested Fees**: GET request to `https://gas-api.metaswap.codefi.network/networks/{chainID}/suggestedGasFees`

Now supports any blockchain network through command line arguments with automatic chain ID detection.

## Generated Output

The generator creates chain-specific packages to allow multiple networks in a single program:

### **Package Structure:**
```
examples/gas-comparison/internal/data/
β”œβ”€β”€ ethereum/ # Chain ID 1 (Ethereum Mainnet)
β”‚ └── data.go
β”œβ”€β”€ bsc/ # Chain ID 56 (BSC Mainnet)
β”‚ └── data.go
β”œβ”€β”€ polygon/ # Chain ID 137 (Polygon Mainnet)
β”‚ └── data.go
└── chain123/ # Chain ID 123 (Unknown networks use chainXXX format)
└── data.go
```

### **Generated File Contents:**
Each `data.go` file contains:
- Chain-specific package name (e.g., `package ethereum`, `package bsc`)
- Import of the shared `data.GasData` type from `github.com/status-im/go-wallet-sdk/examples/gas-comparison/internal/data`
- A `GetGasData()` function that returns `*data.GasData` with parsed data from embedded JSON constants
- Embedded JSON data from all three API calls
- Comments indicating the specific network and chain ID

The `GasData` struct is defined once in `data/types.go` and reused across all generated packages, ensuring consistency and reducing code duplication.

### **Usage in Go Programs:**
```go
import (
"github.com/status-im/go-wallet-sdk/examples/gas-comparison/internal/data"
ethereumData "github.com/status-im/go-wallet-sdk/examples/gas-comparison/internal/data/ethereum"
bscData "github.com/status-im/go-wallet-sdk/examples/gas-comparison/internal/data/bsc"
polygonData "github.com/status-im/go-wallet-sdk/examples/gas-comparison/internal/data/polygon"
)

// Use data from different networks - all return the same *data.GasData type
var ethData, bscGasData, polygonGasData *data.GasData
var err error

ethData, err = ethereumData.GetGasData()
bscGasData, err = bscData.GetGasData()
polygonGasData, err = polygonData.GetGasData()

// All data uses the same GasData type for consistency
fmt.Printf("Ethereum base fee: %s\n", ethData.LatestBlock.BaseFeePerGas)
fmt.Printf("BSC base fee: %s\n", bscGasData.LatestBlock.BaseFeePerGas)
```

## SDK Integration

The generator now uses the SDK's client methods instead of raw HTTP requests:

### **Client Methods Used:**
- **Ethereum Client**: `ethclient.NewClient()` with RPC client
- `client.ChainID(ctx)` - automatically detects chain ID
- `client.GetLatestBlock(ctx)` - fetches latest block with full transactions
- `client.FeeHistory(ctx, blockCount, lastBlock, percentiles)` - fetches fee history
- **Infura Client**: `infura.NewClient(apiKey)`
- `client.GetGasSuggestions(ctx, chainID)` - fetches gas suggestions

### **SDK Types Used:**
- **Block Data**: `github.com/status-im/go-wallet-sdk/pkg/ethclient.BlockWithFullTxs`
- **Fee History**: `github.com/status-im/go-wallet-sdk/pkg/ethclient.FeeHistory`
- **Infura Fees**: `github.com/status-im/go-wallet-sdk/pkg/gas/infura.GasResponse`

### **Benefits:**
βœ… **Proper Error Handling**: Uses SDK's built-in error handling and retries
βœ… **Type Safety**: Automatic JSON marshaling/unmarshaling with proper types
βœ… **Connection Management**: Proper RPC connection lifecycle management
βœ… **Consistency**: Uses the same client methods as the rest of the SDK
βœ… **Timeout Handling**: Built-in timeout and context management
βœ… **Auto Chain Detection**: Automatically detects chain ID from RPC endpoint
βœ… **Multi-Network Support**: Generate data for multiple networks without conflicts
βœ… **Clean Package Structure**: Each network gets its own package namespace
βœ… **Shared Type Definitions**: Single `GasData` type definition prevents duplication and ensures consistency
βœ… **Type Safety**: All generated packages return the same `*data.GasData` type for easy interoperability

This ensures full integration with the SDK and allows you to use the gas data in your Go programs without making additional API calls.

## Important Note

If you have existing generated files from previous versions of the generator, you should regenerate them to use the new shared `data.GasData` type instead of having duplicate type definitions in each file. Simply run the generator again for each network you want to update:

```bash
cd examples/gas-comparison/internal/data/generator

# Regenerate existing data files to use shared types
go run main.go -infura-api-key YOUR_API_KEY -rpc https://mainnet.infura.io/v3/YOUR_API_KEY
go run main.go -infura-api-key YOUR_API_KEY -rpc https://bsc-mainnet.infura.io/v3/YOUR_API_KEY
```
Loading
Loading