rollup_gasPrices
Get zkEVM gas price oracle data on the Linea network. This method provides comprehensive gas pricing information for the zkEVM rollup, including both L2 execution costs and L1 data availability fees.
Overview
Linea zkEVM uses a sophisticated gas pricing mechanism that accounts for:
- L2 Execution Costs: Gas costs for transaction execution on the zkEVM
- L1 Data Availability: Costs for posting transaction data to Ethereum L1
- Proof Generation: Costs associated with generating zero-knowledge proofs
Parameters
This method typically takes no parameters, but implementation may vary. Please refer to the official Linea documentation for the most current parameter specifications.
Returns
Gas price oracle data object containing current pricing information for the zkEVM rollup.
Implementation Example
- cURL
- JavaScript
- Python
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "rollup_gasPrices",
"params": [],
"id": 1
}'
const response = await fetch('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'rollup_gasPrices',
params: [],
id: 1
})
});
const data = await response.json();
console.log('Gas Prices:', data.result);
// Advanced gas price monitoring for Linea zkEVM
class LineaGasPriceMonitor {
constructor(rpcUrl) {
this.rpcUrl = rpcUrl;
this.priceHistory = [];
}
async getGasPrices() {
const response = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'rollup_gasPrices',
params: [],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`RPC Error: ${data.error.message}`);
}
return data.result;
}
async getCurrentPricing() {
try {
// Get rollup gas prices
const rollupPrices = await this.getGasPrices();
// Get standard gas price for comparison
const standardGasResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_gasPrice',
params: [],
id: 1
})
});
const standardGasData = await standardGasResponse.json();
const standardGasPrice = parseInt(standardGasData.result, 16);
return {
timestamp: Date.now(),
rollupPrices: rollupPrices,
standardGasPrice: standardGasPrice,
formattedPrices: this.formatPrices(rollupPrices, standardGasPrice)
};
} catch (error) {
throw new Error(`Failed to get pricing: ${error.message}`);
}
}
formatPrices(rollupPrices, standardGasPrice) {
return {
standardGasPrice: {
wei: standardGasPrice,
gwei: (standardGasPrice / 1e9).toFixed(2),
eth: (standardGasPrice / 1e18).toFixed(8)
},
rollupData: rollupPrices // This will depend on actual response format
};
}
async trackPriceHistory(duration = 3600000, interval = 60000) {
// Track gas prices for specified duration (default 1 hour) at intervals (default 1 minute)
const startTime = Date.now();
const endTime = startTime + duration;
console.log(`Starting price tracking for ${duration / 60000} minutes...`);
while (Date.now() < endTime) {
try {
const pricing = await this.getCurrentPricing();
this.priceHistory.push(pricing);
console.log(`Price update: ${pricing.formattedPrices.standardGasPrice.gwei} gwei`);
await new Promise(resolve => setTimeout(resolve, interval));
} catch (error) {
console.error('Price tracking error:', error.message);
await new Promise(resolve => setTimeout(resolve, interval));
}
}
return this.analyzePriceHistory();
}
analyzePriceHistory() {
if (this.priceHistory.length === 0) {
return { error: 'No price history available' };
}
const prices = this.priceHistory.map(p => p.standardGasPrice);
const sortedPrices = [...prices].sort((a, b) => a - b);
const analysis = {
duration: {
start: new Date(this.priceHistory[0].timestamp).toISOString(),
end: new Date(this.priceHistory[this.priceHistory.length - 1].timestamp).toISOString(),
dataPoints: this.priceHistory.length
},
statistics: {
min: Math.min(...prices),
max: Math.max(...prices),
average: prices.reduce((sum, p) => sum + p, 0) / prices.length,
median: sortedPrices[Math.floor(sortedPrices.length / 2)],
volatility: this.calculateVolatility(prices)
},
trends: {
direction: this.getTrend(prices),
priceChange: prices[prices.length - 1] - prices[0],
percentageChange: ((prices[prices.length - 1] - prices[0]) / prices[0] * 100).toFixed(2)
},
recommendations: this.generateRecommendations(prices)
};
return analysis;
}
calculateVolatility(prices) {
if (prices.length < 2) return 0;
const mean = prices.reduce((sum, p) => sum + p, 0) / prices.length;
const variance = prices.reduce((sum, p) => sum + Math.pow(p - mean, 2), 0) / prices.length;
return Math.sqrt(variance);
}
getTrend(prices) {
if (prices.length < 2) return 'insufficient_data';
const firstHalf = prices.slice(0, Math.floor(prices.length / 2));
const secondHalf = prices.slice(Math.floor(prices.length / 2));
const firstAvg = firstHalf.reduce((sum, p) => sum + p, 0) / firstHalf.length;
const secondAvg = secondHalf.reduce((sum, p) => sum + p, 0) / secondHalf.length;
const changePct = ((secondAvg - firstAvg) / firstAvg) * 100;
if (changePct > 5) return 'increasing';
if (changePct < -5) return 'decreasing';
return 'stable';
}
generateRecommendations(prices) {
const recommendations = [];
const currentPrice = prices[prices.length - 1];
const avgPrice = prices.reduce((sum, p) => sum + p, 0) / prices.length;
const minPrice = Math.min(...prices);
if (currentPrice > avgPrice * 1.2) {
recommendations.push({
type: 'high_gas_warning',
message: 'Current gas price is significantly above average',
suggestion: 'Consider waiting for lower gas prices or using lower priority'
});
}
if (currentPrice <= minPrice * 1.1) {
recommendations.push({
type: 'optimal_timing',
message: 'Current gas price is near historical low',
suggestion: 'Good time to execute transactions'
});
}
const volatility = this.calculateVolatility(prices);
if (volatility > avgPrice * 0.1) {
recommendations.push({
type: 'high_volatility',
message: 'Gas prices are highly volatile',
suggestion: 'Monitor prices closely and be prepared to adjust'
});
}
return recommendations;
}
async predictOptimalTiming(targetGasPrice) {
const pricing = await this.getCurrentPricing();
const currentPrice = pricing.standardGasPrice;
if (currentPrice <= targetGasPrice) {
return {
optimal: true,
currentPrice: currentPrice,
targetPrice: targetGasPrice,
recommendation: 'Execute transaction now'
};
}
// Simple prediction based on recent trend
const recentPrices = this.priceHistory.slice(-10).map(p => p.standardGasPrice);
const trend = this.getTrend(recentPrices);
let prediction = 'unknown';
let estimatedWait = 'unknown';
if (trend === 'decreasing') {
prediction = 'prices_likely_to_drop';
estimatedWait = 'monitor_for_15_30_minutes';
} else if (trend === 'increasing') {
prediction = 'prices_likely_to_rise';
estimatedWait = 'consider_executing_soon';
} else {
prediction = 'prices_stable';
estimatedWait = 'no_clear_trend';
}
return {
optimal: false,
currentPrice: currentPrice,
targetPrice: targetGasPrice,
prediction: prediction,
estimatedWait: estimatedWait,
recommendation: `Current: ${(currentPrice / 1e9).toFixed(2)} gwei, Target: ${(targetGasPrice / 1e9).toFixed(2)} gwei`
};
}
async compareWithL1Costs() {
try {
// Get Linea gas prices
const lineaPricing = await this.getCurrentPricing();
// For comparison with Ethereum L1, you would need to call Ethereum mainnet
// This is just an example structure
const comparison = {
linea: {
gasPrice: lineaPricing.standardGasPrice,
gasPriceGwei: lineaPricing.formattedPrices.standardGasPrice.gwei,
estimatedTransferCost: lineaPricing.standardGasPrice * 21000 // ETH transfer
},
savings: {
// This would be calculated with actual L1 data
estimatedSavings: 'Requires L1 comparison data',
savingsPercentage: 'Requires L1 comparison data'
}
};
return comparison;
} catch (error) {
throw new Error(`Failed to compare costs: ${error.message}`);
}
}
}
// Usage examples
const gasPriceMonitor = new LineaGasPriceMonitor('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Get current gas pricing
const currentPricing = await gasPriceMonitor.getCurrentPricing();
console.log('Current Gas Prices:', currentPricing.formattedPrices);
// Track prices for 10 minutes
const priceAnalysis = await gasPriceMonitor.trackPriceHistory(600000, 30000);
console.log('Price Analysis:', priceAnalysis);
// Check optimal timing for transaction
const optimalTiming = await gasPriceMonitor.predictOptimalTiming(20000000000); // 20 gwei target
console.log('Optimal Timing:', optimalTiming);
// Compare with L1 costs
const costComparison = await gasPriceMonitor.compareWithL1Costs();
console.log('Cost Comparison:', costComparison);
import requests
import json
import time
import statistics
from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta
class LineaGasPriceAnalyzer:
"""Analyze and monitor gas prices on Linea zkEVM"""
def __init__(self, rpc_url: str):
self.rpc_url = rpc_url
self.price_history = []
def get_rollup_gas_prices(self) -> Dict[str, Any]:
"""Get current rollup gas prices"""
payload = {
"jsonrpc": "2.0",
"method": "rollup_gasPrices",
"params": [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return data['result']
def get_standard_gas_price(self) -> int:
"""Get standard gas price for comparison"""
payload = {
"jsonrpc": "2.0",
"method": "eth_gasPrice",
"params": [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return int(data['result'], 16)
def get_comprehensive_pricing(self) -> Dict[str, Any]:
"""Get comprehensive gas pricing information"""
rollup_prices = self.get_rollup_gas_prices()
standard_gas_price = self.get_standard_gas_price()
return {
'timestamp': datetime.now().isoformat(),
'rollup_data': rollup_prices,
'standard_gas_price': standard_gas_price,
'formatted': {
'gas_price_wei': standard_gas_price,
'gas_price_gwei': round(standard_gas_price / 1e9, 2),
'gas_price_eth': round(standard_gas_price / 1e18, 8)
},
'transaction_costs': {
'eth_transfer': standard_gas_price * 21000, # Standard ETH transfer
'erc20_transfer': standard_gas_price * 65000, # Typical ERC20 transfer
'swap': standard_gas_price * 150000 # Typical DEX swap
}
}
def monitor_prices(
self,
duration_minutes: int = 60,
interval_seconds: int = 60
) -> Dict[str, Any]:
"""Monitor gas prices over time"""
start_time = datetime.now()
end_time = start_time + timedelta(minutes=duration_minutes)
print(f"Monitoring gas prices for {duration_minutes} minutes...")
price_data = []
while datetime.now() < end_time:
try:
pricing = self.get_comprehensive_pricing()
price_data.append(pricing)
self.price_history.append(pricing)
print(f"Price update: {pricing['formatted']['gas_price_gwei']} gwei")
time.sleep(interval_seconds)
except Exception as e:
print(f"Error monitoring prices: {e}")
time.sleep(interval_seconds)
return self._analyze_price_data(price_data)
def _analyze_price_data(self, price_data: List[Dict]) -> Dict[str, Any]:
"""Analyze collected price data"""
if not price_data:
return {'error': 'No price data available'}
gas_prices = [p['standard_gas_price'] for p in price_data]
gwei_prices = [p['formatted']['gas_price_gwei'] for p in price_data]
analysis = {
'period': {
'start': price_data[0]['timestamp'],
'end': price_data[-1]['timestamp'],
'data_points': len(price_data)
},
'statistics': {
'min_wei': min(gas_prices),
'max_wei': max(gas_prices),
'average_wei': statistics.mean(gas_prices),
'median_wei': statistics.median(gas_prices),
'min_gwei': min(gwei_prices),
'max_gwei': max(gwei_prices),
'average_gwei': round(statistics.mean(gwei_prices), 2),
'median_gwei': round(statistics.median(gwei_prices), 2),
'std_dev_gwei': round(statistics.stdev(gwei_prices) if len(gwei_prices) > 1 else 0, 2)
},
'trends': self._calculate_trends(gas_prices),
'volatility': self._calculate_volatility(gas_prices),
'cost_analysis': self._analyze_transaction_costs(price_data)
}
return analysis
def _calculate_trends(self, prices: List[int]) -> Dict[str, Any]:
"""Calculate price trends"""
if len(prices) < 2:
return {'trend': 'insufficient_data'}
# Simple linear trend
x = list(range(len(prices)))
n = len(prices)
# Calculate slope using least squares
sum_x = sum(x)
sum_y = sum(prices)
sum_xy = sum(x[i] * prices[i] for i in range(n))
sum_x2 = sum(x[i] ** 2 for i in range(n))
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
# Percentage change
price_change = prices[-1] - prices[0]
pct_change = (price_change / prices[0]) * 100
trend_direction = 'increasing' if slope > 0 else 'decreasing' if slope < 0 else 'stable'
return {
'trend': trend_direction,
'slope': slope,
'price_change_wei': price_change,
'percentage_change': round(pct_change, 2),
'is_volatile': abs(pct_change) > 10
}
def _calculate_volatility(self, prices: List[int]) -> Dict[str, Any]:
"""Calculate price volatility metrics"""
if len(prices) < 2:
return {'volatility': 0}
mean_price = statistics.mean(prices)
variance = statistics.variance(prices)
std_dev = statistics.stdev(prices)
# Coefficient of variation (relative volatility)
cv = (std_dev / mean_price) * 100 if mean_price > 0 else 0
return {
'standard_deviation': round(std_dev, 2),
'variance': round(variance, 2),
'coefficient_of_variation': round(cv, 2),
'volatility_level': (
'high' if cv > 15 else
'medium' if cv > 5 else
'low'
)
}
def _analyze_transaction_costs(self, price_data: List[Dict]) -> Dict[str, Any]:
"""Analyze transaction costs over time"""
cost_analysis = {
'eth_transfer': [],
'erc20_transfer': [],
'swap': []
}
for data in price_data:
costs = data['transaction_costs']
cost_analysis['eth_transfer'].append(costs['eth_transfer'])
cost_analysis['erc20_transfer'].append(costs['erc20_transfer'])
cost_analysis['swap'].append(costs['swap'])
result = {}
for tx_type, costs in cost_analysis.items():
result[tx_type] = {
'min_cost_wei': min(costs),
'max_cost_wei': max(costs),
'avg_cost_wei': round(statistics.mean(costs)),
'cost_range_wei': max(costs) - min(costs),
'min_cost_usd': 'Requires ETH price data',
'max_cost_usd': 'Requires ETH price data'
}
return result
def recommend_optimal_timing(
self,
target_gas_price_gwei: float,
transaction_type: str = 'eth_transfer'
) -> Dict[str, Any]:
"""Recommend optimal timing for transaction execution"""
current_pricing = self.get_comprehensive_pricing()
current_gwei = current_pricing['formatted']['gas_price_gwei']
recommendation = {
'current_price_gwei': current_gwei,
'target_price_gwei': target_gas_price_gwei,
'execute_now': current_gwei <= target_gas_price_gwei
}
if recommendation['execute_now']:
recommendation['message'] = 'Current gas price meets target - execute now'
recommendation['estimated_cost'] = current_pricing['transaction_costs'][transaction_type]
else:
price_diff = current_gwei - target_gas_price_gwei
recommendation['message'] = f'Wait for lower prices (current: {current_gwei}, target: {target_gas_price_gwei})'
recommendation['price_difference_gwei'] = round(price_diff, 2)
# Simple prediction based on recent trend if available
if len(self.price_history) > 5:
recent_prices = [p['standard_gas_price'] for p in self.price_history[-5:]]
trends = self._calculate_trends(recent_prices)
if trends['trend'] == 'decreasing':
recommendation['prediction'] = 'Prices trending down - may reach target soon'
elif trends['trend'] == 'increasing':
recommendation['prediction'] = 'Prices trending up - consider executing soon'
else:
recommendation['prediction'] = 'Prices stable - monitor for changes'
return recommendation
def compare_with_ethereum_l1(self, eth_l1_gas_price_gwei: float) -> Dict[str, Any]:
"""Compare Linea costs with Ethereum L1"""
linea_pricing = self.get_comprehensive_pricing()
linea_gwei = linea_pricing['formatted']['gas_price_gwei']
# Calculate savings for different transaction types
savings_analysis = {}
for tx_type, linea_gas_units in [
('eth_transfer', 21000),
('erc20_transfer', 65000),
('swap', 150000)
]:
l1_cost_wei = int(eth_l1_gas_price_gwei * 1e9 * linea_gas_units)
linea_cost_wei = linea_pricing['transaction_costs'][tx_type]
savings_wei = l1_cost_wei - linea_cost_wei
savings_pct = (savings_wei / l1_cost_wei) * 100 if l1_cost_wei > 0 else 0
savings_analysis[tx_type] = {
'l1_cost_wei': l1_cost_wei,
'linea_cost_wei': linea_cost_wei,
'savings_wei': savings_wei,
'savings_percentage': round(savings_pct, 2),
'cost_ratio': round(linea_cost_wei / l1_cost_wei, 3) if l1_cost_wei > 0 else 0
}
return {
'comparison_timestamp': datetime.now().isoformat(),
'l1_gas_price_gwei': eth_l1_gas_price_gwei,
'linea_gas_price_gwei': linea_gwei,
'price_ratio': round(linea_gwei / eth_l1_gas_price_gwei, 3) if eth_l1_gas_price_gwei > 0 else 0,
'transaction_savings': savings_analysis
}
# Usage examples
analyzer = LineaGasPriceAnalyzer('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY')
# Get current comprehensive pricing
pricing = analyzer.get_comprehensive_pricing()
print(f"Current gas price: {pricing['formatted']['gas_price_gwei']} gwei")
print(f"ETH transfer cost: {pricing['transaction_costs']['eth_transfer']:,} wei")
# Monitor prices for 30 minutes
price_analysis = analyzer.monitor_prices(duration_minutes=30, interval_seconds=120)
print("\nPrice Analysis:")
print(f"Average: {price_analysis['statistics']['average_gwei']} gwei")
print(f"Volatility: {price_analysis['volatility']['volatility_level']}")
print(f"Trend: {price_analysis['trends']['trend']}")
# Get timing recommendation
timing = analyzer.recommend_optimal_timing(target_gas_price_gwei=15.0)
print(f"\nTiming recommendation: {timing['message']}")
# Compare with Ethereum L1 (example with 50 gwei L1 price)
comparison = analyzer.compare_with_ethereum_l1(eth_l1_gas_price_gwei=50.0)
print(f"\nL1 vs Linea savings:")
for tx_type, data in comparison['transaction_savings'].items():
print(f" {tx_type}: {data['savings_percentage']}% savings")
Response Example
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"l1GasPrice": "0x12a05f200",
"l2GasPrice": "0x3b9aca00",
"overhead": "0xbc0",
"scalar": "0x684000",
"decimals": "0x6"
}
}
Understanding Gas Prices on Linea
Price Components
- L2 Gas Price: Cost per gas unit for execution on Linea zkEVM
- L1 Gas Price: Current Ethereum L1 gas price for data posting
- Overhead: Fixed overhead cost for L1 data posting
- Scalar: Scaling factor for L1 cost calculation
- Decimals: Decimal precision for calculations
Cost Calculation
Total transaction cost = (L2 Gas × L2 Gas Price) + L1 Data Fee
Where L1 Data Fee considers:
- Transaction data size
- Current L1 gas price
- Overhead and scalar factors
Common Use Cases
1. Gas Price Monitoring
// Monitor gas prices for optimal transaction timing
async function monitorForOptimalGas(targetGwei, callback) {
const monitor = new LineaGasPriceMonitor(rpcUrl);
const checkPrice = async () => {
const pricing = await monitor.getCurrentPricing();
const currentGwei = pricing.formattedPrices.standardGasPrice.gwei;
if (currentGwei <= targetGwei) {
callback({
optimal: true,
currentPrice: currentGwei,
targetPrice: targetGwei,
message: 'Target price reached!'
});
return true;
}
return false;
};
// Check every 30 seconds
const interval = setInterval(async () => {
const optimal = await checkPrice();
if (optimal) {
clearInterval(interval);
}
}, 30000);
// Initial check
await checkPrice();
}
2. Cost Optimization
def optimize_transaction_timing(analyzer, transactions, budget_gwei):
"""Find optimal timing for multiple transactions within budget"""
optimization_plan = []
for i, tx in enumerate(transactions):
# Estimate transaction cost at different gas prices
cost_estimates = []
for gas_price_gwei in [10, 15, 20, 25, 30]:
gas_price_wei = int(gas_price_gwei * 1e9)
estimated_cost = tx['gas_estimate'] * gas_price_wei
cost_estimates.append({
'gas_price_gwei': gas_price_gwei,
'estimated_cost_wei': estimated_cost,
'within_budget': gas_price_gwei <= budget_gwei
})
# Find optimal price point
optimal = next(
(est for est in cost_estimates if est['within_budget']),
cost_estimates[0]
)
optimization_plan.append({
'transaction_id': i,
'optimal_gas_price': optimal['gas_price_gwei'],
'estimated_cost': optimal['estimated_cost_wei'],
'cost_estimates': cost_estimates
})
return optimization_plan
3. Historical Analysis
// Analyze historical gas price patterns
async function analyzeGasPricePatterns(monitor, days = 7) {
const patterns = {
hourlyAverages: {},
dailyTrends: [],
optimalTimes: []
};
// This would require storing historical data
// For demonstration, showing structure
// Simulate hourly analysis
for (let hour = 0; hour < 24; hour++) {
patterns.hourlyAverages[hour] = {
averageGwei: 0, // Would be calculated from historical data
transactionVolume: 0,
volatility: 0
};
}
// Identify optimal transaction times
const sortedHours = Object.entries(patterns.hourlyAverages)
.sort((a, b) => a[1].averageGwei - b[1].averageGwei);
patterns.optimalTimes = sortedHours.slice(0, 6).map(([hour, data]) => ({
hour: parseInt(hour),
averageGwei: data.averageGwei,
timeRange: `${hour}:00-${hour}:59 UTC`
}));
return patterns;
}
Related Methods
eth_gasPrice
- Get current L2 gas priceeth_feeHistory
- Historical fee dataeth_estimateGas
- Estimate transaction gasrollup_getInfo
- Get rollup configuration
Need help? Contact our support team or check the Linea documentation.