eth_gasPrice
Returns the current gas price in wei. This is the median gas price from recent blocks on Linea zkEVM.
Parameters
None
Returns
QUANTITY
- Integer of the current gas price in wei.
Request Example
{
"jsonrpc": "2.0",
"method": "eth_gasPrice",
"params": [],
"id": 1
}
Response Example
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x3b9aca00"
}
Implementation Examples
- JavaScript
- Python
import { JsonRpcProvider } from 'ethers';
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Get current gas price
async function getGasPrice() {
const gasPrice = await provider.getGasPrice();
console.log('Gas Price (wei):', gasPrice.toString());
console.log('Gas Price (gwei):', ethers.formatUnits(gasPrice, 'gwei'));
console.log('Gas Price (ETH):', ethers.formatEther(gasPrice));
// Estimate transaction cost
const standardTxGas = 21000n;
const txCost = gasPrice * standardTxGas;
console.log('Standard TX cost:', ethers.formatEther(txCost), 'ETH');
return gasPrice;
}
// Get gas price with analysis
async function analyzeGasPrice() {
const gasPrice = await provider.getGasPrice();
const block = await provider.getBlock('latest');
// Compare with base fee (EIP-1559)
const baseFee = block.baseFeePerGas;
return {
currentGasPrice: ethers.formatUnits(gasPrice, 'gwei') + ' gwei',
baseFee: baseFee ? ethers.formatUnits(baseFee, 'gwei') + ' gwei' : 'N/A',
estimatedTxCost: ethers.formatEther(gasPrice * 21000n) + ' ETH',
timestamp: new Date().toISOString()
};
}
// Dynamic gas pricing strategy
async function getOptimalGasPrice(priority = 'standard') {
const gasPrice = await provider.getGasPrice();
const strategies = {
slow: gasPrice * 90n / 100n, // 90% of current
standard: gasPrice, // Current price
fast: gasPrice * 110n / 100n, // 110% of current
instant: gasPrice * 125n / 100n // 125% of current
};
return strategies[priority] || strategies.standard;
}
from web3 import Web3
import time
w3 = Web3(Web3.HTTPProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
def get_gas_price():
"""Get current gas price"""
gas_price = w3.eth.gas_price
print(f"Gas Price (wei): {gas_price}")
print(f"Gas Price (gwei): {w3.from_wei(gas_price, 'gwei')}")
print(f"Gas Price (ETH): {w3.from_wei(gas_price, 'ether')}")
# Calculate standard transaction cost
standard_gas = 21000
tx_cost = gas_price * standard_gas
print(f"Standard TX cost: {w3.from_wei(tx_cost, 'ether')} ETH")
return gas_price
def monitor_gas_prices(duration=60):
"""Monitor gas price changes over time"""
prices = []
start_time = time.time()
while time.time() - start_time < duration:
gas_price = w3.eth.gas_price
prices.append({
'timestamp': time.time(),
'price_wei': gas_price,
'price_gwei': float(w3.from_wei(gas_price, 'gwei'))
})
print(f"Gas: {w3.from_wei(gas_price, 'gwei')} gwei")
time.sleep(5) # Check every 5 seconds
# Calculate statistics
gwei_prices = [p['price_gwei'] for p in prices]
avg_price = sum(gwei_prices) / len(gwei_prices)
min_price = min(gwei_prices)
max_price = max(gwei_prices)
return {
'average': avg_price,
'minimum': min_price,
'maximum': max_price,
'samples': len(prices)
}
def calculate_transaction_cost(gas_limit, priority='standard'):
"""Calculate transaction cost with different priorities"""
base_price = w3.eth.gas_price
multipliers = {
'slow': 0.9,
'standard': 1.0,
'fast': 1.1,
'instant': 1.25
}
gas_price = int(base_price * multipliers.get(priority, 1.0))
total_cost = gas_price * gas_limit
return {
'gas_limit': gas_limit,
'gas_price_wei': gas_price,
'gas_price_gwei': w3.from_wei(gas_price, 'gwei'),
'total_cost_eth': w3.from_wei(total_cost, 'ether'),
'priority': priority
}
zkEVM Gas Pricing
Linea's zkEVM has unique gas pricing characteristics:
// Analyze zkEVM gas dynamics
async function analyzeZkEvmGas() {
const [gasPrice, block, feeHistory] = await Promise.all([
provider.getGasPrice(),
provider.getBlock('latest'),
provider.getFeeHistory(10, 'latest', [25, 50, 75])
]);
// zkEVM specific analysis
return {
currentPrice: ethers.formatUnits(gasPrice, 'gwei'),
blockBaseFee: block.baseFeePerGas ?
ethers.formatUnits(block.baseFeePerGas, 'gwei') : 'N/A',
// Fee history analysis
avgBaseFee: feeHistory.baseFeePerGas.reduce((sum, fee) =>
sum + Number(ethers.formatUnits(fee, 'gwei')), 0) /
feeHistory.baseFeePerGas.length,
// zkEVM characteristics
zkEvmNotes: {
batchingEffect: 'Gas costs amortized across zkProof batches',
compressionBenefit: 'Data compression reduces effective gas usage',
predictability: 'More stable than L1 due to batch processing'
}
};
}
Gas Optimization Strategies
1. Time-Based Optimization
// Find optimal time to transact
async function findOptimalGasTime(samples = 20) {
const gasPrices = [];
for (let i = 0; i < samples; i++) {
const gasPrice = await provider.getGasPrice();
gasPrices.push({
price: gasPrice,
time: new Date(),
gwei: Number(ethers.formatUnits(gasPrice, 'gwei'))
});
// Wait 30 seconds between samples
await new Promise(r => setTimeout(r, 30000));
}
// Find minimum gas period
const minGas = Math.min(...gasPrices.map(g => g.gwei));
const optimal = gasPrices.find(g => g.gwei === minGas);
return {
optimalTime: optimal.time,
optimalPrice: optimal.gwei + ' gwei',
currentPrice: gasPrices[gasPrices.length - 1].gwei + ' gwei',
potentialSaving: ((gasPrices[gasPrices.length - 1].gwei - minGas) /
gasPrices[gasPrices.length - 1].gwei * 100).toFixed(2) + '%'
};
}
2. Transaction Batching
// Calculate savings from batching
async function calculateBatchSavings(transactions) {
const gasPrice = await provider.getGasPrice();
// Individual transaction costs
let individualCost = 0n;
for (const tx of transactions) {
const gasEstimate = await provider.estimateGas(tx);
individualCost += gasEstimate * gasPrice;
}
// Batched transaction cost (using multicall)
const batchedGas = 100000n + (20000n * BigInt(transactions.length));
const batchedCost = batchedGas * gasPrice;
const savings = individualCost - batchedCost;
return {
individualCost: ethers.formatEther(individualCost),
batchedCost: ethers.formatEther(batchedCost),
savings: ethers.formatEther(savings),
savingsPercent: Number(savings * 100n / individualCost) + '%'
};
}
Error Handling
async function safeGetGasPrice(retries = 3) {
let lastError;
for (let i = 0; i < retries; i++) {
try {
const gasPrice = await provider.getGasPrice();
// Validate reasonable gas price (not 0, not extremely high)
if (gasPrice === 0n) {
throw new Error('Invalid gas price: 0');
}
// Check if price is reasonable (< 1000 gwei)
if (gasPrice > ethers.parseUnits('1000', 'gwei')) {
console.warn('Unusually high gas price detected');
}
return gasPrice;
} catch (error) {
lastError = error;
console.log(`Attempt ${i + 1} failed:`, error.message);
if (i < retries - 1) {
await new Promise(r => setTimeout(r, 2 ** i * 1000));
}
}
}
throw lastError;
}
Need help? Contact our support team or check the Linea documentation.