⚠️Blast API (blastapi.io) ends Oct 31. Migrate to Dwellir and skip Alchemy's expensive compute units.
Switch Today →
Skip to main content

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

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;
}

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.