Skip to main content

eth_gasPrice

Returns the current gas price in wei. This represents the median gas price from recent blocks on IoTeX L1.

When to Use This Method​

eth_gasPrice is essential for:

  • Transaction Pricing - Set appropriate gas prices for transactions
  • Fee Estimation - Calculate transaction costs for users
  • Gas Strategy - Optimize transaction speed vs cost
  • Market Monitoring - Track network congestion levels

Parameters​

None - This method takes no parameters.

{
"jsonrpc": "2.0",
"method": "eth_gasPrice",
"params": [],
"id": 1
}

Returns​

QUANTITY - Current gas price in wei (hexadecimal).

Implementation Examples​

import { JsonRpcProvider, formatGwei, formatEther } from 'ethers';

const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');

// Gas price monitoring and optimization
class GasPriceManager {
constructor(provider) {
this.provider = provider;
this.priceHistory = [];
this.updateInterval = null;
}

async getCurrentGasPrice() {
const gasPrice = await this.provider.getGasPrice();

return {
wei: gasPrice.toString(),
gwei: formatGwei(gasPrice),
eth: formatEther(gasPrice),
hex: gasPrice.toHexString(),
timestamp: Date.now()
};
}

async getGasPriceWithContext() {
// Get multiple data points for context
const [gasPrice, feeData, block] = await Promise.all([
this.provider.getGasPrice(),
this.provider.getFeeData(),
this.provider.getBlock('latest')
]);

// Calculate percentiles for better pricing
const baseFee = block.baseFeePerGas || 0n;
const priorityFee = feeData.maxPriorityFeePerGas || 0n;

return {
current: {
gasPrice: formatGwei(gasPrice),
unit: 'gwei'
},
eip1559: {
baseFee: formatGwei(baseFee),
priorityFee: formatGwei(priorityFee),
maxFeePerGas: formatGwei(feeData.maxFeePerGas),
recommended: formatGwei(baseFee + priorityFee)
},
speeds: {
slow: formatGwei(gasPrice * 90n / 100n),
standard: formatGwei(gasPrice),
fast: formatGwei(gasPrice * 120n / 100n),
instant: formatGwei(gasPrice * 150n / 100n)
},
networkCongestion: this.assessCongestion(baseFee)
};
}

assessCongestion(baseFee) {
const baseGwei = Number(formatGwei(baseFee));

if (baseGwei < 0.1) return 'very low';
if (baseGwei < 0.5) return 'low';
if (baseGwei < 1) return 'moderate';
if (baseGwei < 5) return 'high';
return 'very high';
}

async calculateTransactionCost(gasLimit, gasPriceMultiplier = 1) {
const gasPrice = await this.provider.getGasPrice();
const adjustedPrice = gasPrice * BigInt(Math.floor(gasPriceMultiplier * 100)) / 100n;
const cost = adjustedPrice * BigInt(gasLimit);

return {
gasLimit: gasLimit.toString(),
gasPrice: formatGwei(adjustedPrice),
totalCostWei: cost.toString(),
totalCostGwei: formatGwei(cost),
totalCostETH: formatEther(cost),
dollarValue: await this.estimateUSDValue(cost)
};
}

async estimateUSDValue(costWei) {
// This would typically fetch ETH price from an oracle
// For demonstration, using a static value
const ethPrice = 3000; // USD
const costETH = Number(formatEther(costWei));
return (costETH * ethPrice).toFixed(4);
}

startMonitoring(intervalMs = 5000, callback) {
this.stopMonitoring();

this.updateInterval = setInterval(async () => {
const price = await this.getCurrentGasPrice();
this.priceHistory.push(price);

// Keep only last 100 entries
if (this.priceHistory.length > 100) {
this.priceHistory.shift();
}

if (callback) {
callback(price, this.getStatistics());
}
}, intervalMs);
}

stopMonitoring() {
if (this.updateInterval) {
clearInterval(this.updateInterval);
this.updateInterval = null;
}
}

getStatistics() {
if (this.priceHistory.length === 0) return null;

const prices = this.priceHistory.map(p => BigInt(p.wei));
const sum = prices.reduce((a, b) => a + b, 0n);
const avg = sum / BigInt(prices.length);
const min = prices.reduce((a, b) => a < b ? a : b);
const max = prices.reduce((a, b) => a > b ? a : b);

return {
samples: prices.length,
average: formatGwei(avg),
minimum: formatGwei(min),
maximum: formatGwei(max),
current: formatGwei(prices[prices.length - 1]),
trend: this.calculateTrend()
};
}

calculateTrend() {
if (this.priceHistory.length < 2) return 'stable';

const recent = this.priceHistory.slice(-10);
const older = this.priceHistory.slice(-20, -10);

if (older.length === 0) return 'stable';

const recentAvg = recent.reduce((sum, p) => sum + BigInt(p.wei), 0n) / BigInt(recent.length);
const olderAvg = older.reduce((sum, p) => sum + BigInt(p.wei), 0n) / BigInt(older.length);

const change = Number(recentAvg - olderAvg) / Number(olderAvg) * 100;

if (change > 10) return 'increasing';
if (change < -10) return 'decreasing';
return 'stable';
}

async waitForLowerGas(targetGwei, timeoutMs = 60000) {
const startTime = Date.now();

while (Date.now() - startTime < timeoutMs) {
const current = await this.getCurrentGasPrice();

if (parseFloat(current.gwei) <= targetGwei) {
return {
success: true,
gasPrice: current,
waitTime: Date.now() - startTime
};
}

await new Promise(resolve => setTimeout(resolve, 2000));
}

return {
success: false,
reason: 'timeout',
currentPrice: await this.getCurrentGasPrice()
};
}
}

// Usage examples
const gasPriceManager = new GasPriceManager(provider);

// Get current gas price
const currentPrice = await gasPriceManager.getCurrentGasPrice();
console.log(`Current gas price: ${currentPrice.gwei} gwei`);

// Get comprehensive gas data
const gasData = await gasPriceManager.getGasPriceWithContext();
console.log('Network congestion:', gasData.networkCongestion);
console.log('Recommended speeds:', gasData.speeds);

// Calculate transaction cost
const txCost = await gasPriceManager.calculateTransactionCost(21000); // ETH transfer
console.log(`Transaction cost: ${txCost.totalCostETH} ETH (~$${txCost.dollarValue})`);

// Monitor gas prices
gasPriceManager.startMonitoring(5000, (price, stats) => {
console.log(`Gas: ${price.gwei} gwei | Trend: ${stats?.trend}`);
});

// Wait for lower gas
const result = await gasPriceManager.waitForLowerGas(0.5, 30000);
if (result.success) {
console.log('Gas price dropped to target!');
}

Common Use Cases​

1. Dynamic Fee Adjustment​

// Dynamically adjust fees based on network conditions
async function getOptimalGasPrice(urgency = 'standard') {
const gasPrice = await provider.getGasPrice();
const block = await provider.getBlock('latest');
const baseFee = block.baseFeePerGas;

const multipliers = {
low: 0.9,
standard: 1.0,
high: 1.2,
urgent: 1.5
};

const multiplier = multipliers[urgency] || 1.0;
const adjustedPrice = gasPrice * BigInt(Math.floor(multiplier * 100)) / 100n;

// For EIP-1559 transactions
const maxPriorityFee = adjustedPrice - baseFee;
const maxFeePerGas = baseFee * 2n + maxPriorityFee;

return {
legacy: {
gasPrice: adjustedPrice,
formatted: formatGwei(adjustedPrice) + ' gwei'
},
eip1559: {
maxFeePerGas: maxFeePerGas,
maxPriorityFeePerGas: maxPriorityFee,
formatted: {
maxFee: formatGwei(maxFeePerGas) + ' gwei',
priorityFee: formatGwei(maxPriorityFee) + ' gwei'
}
},
estimatedConfirmationBlocks: urgency === 'urgent' ? 1 : urgency === 'high' ? 2 : 3
};
}

2. Gas Price Oracle​

// Create a gas price oracle with caching
class GasPriceOracle {
constructor(provider, cacheTime = 5000) {
this.provider = provider;
this.cacheTime = cacheTime;
this.cache = null;
this.lastFetch = 0;
}

async getPrice() {
const now = Date.now();

if (this.cache && (now - this.lastFetch) < this.cacheTime) {
return this.cache;
}

const gasPrice = await this.provider.getGasPrice();

this.cache = {
wei: gasPrice,
gwei: formatGwei(gasPrice),
timestamp: now
};
this.lastFetch = now;

return this.cache;
}

async getPriceWithRecommendations() {
const price = await this.getPrice();
const gweiPrice = parseFloat(price.gwei);

return {
...price,
recommendations: {
sendNow: gweiPrice < 1,
waitSuggested: gweiPrice > 5,
congestionLevel: gweiPrice < 0.5 ? 'low' : gweiPrice < 2 ? 'normal' : 'high'
}
};
}
}

3. Transaction Cost Calculator​

// Calculate and display transaction costs
async function calculateDetailedCosts(gasLimit) {
const gasPrice = await provider.getGasPrice();
const ethPrice = 3000; // Would fetch from price feed

const costs = {
slow: gasPrice * 90n / 100n,
standard: gasPrice,
fast: gasPrice * 120n / 100n
};

const results = {};

for (const [speed, price] of Object.entries(costs)) {
const totalWei = price * BigInt(gasLimit);
const totalETH = Number(formatEther(totalWei));

results[speed] = {
gasPrice: formatGwei(price) + ' gwei',
totalETH: totalETH.toFixed(6) + ' ETH',
totalUSD: '$' + (totalETH * ethPrice).toFixed(2),
percentOfTransfer: gasLimit === 21000 ? 'N/A' :
((Number(totalWei) / Number(parseEther('1'))) * 100).toFixed(3) + '%'
};
}

return results;
}

Error Handling​

Error ScenarioDescriptionSolution
Network timeoutRPC connection issuesRetry with exponential backoff
Invalid responseMalformed data from nodeValidate response format
Stale dataCached price too oldForce refresh
async function getRobustGasPrice(maxRetries = 3) {
let lastError;

for (let i = 0; i < maxRetries; i++) {
try {
const gasPrice = await provider.getGasPrice();

// Validate response
if (!gasPrice || gasPrice === 0n) {
throw new Error('Invalid gas price returned');
}

// Sanity check - IoTeX L1 shouldn't have extremely high gas
const gweiPrice = Number(formatGwei(gasPrice));
if (gweiPrice > 1000) {
console.warn('Unusually high gas price detected:', gweiPrice);
}

return gasPrice;

} catch (error) {
lastError = error;

// Exponential backoff
if (i < maxRetries - 1) {
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, i) * 1000)
);
}
}
}

throw new Error(`Failed to get gas price after ${maxRetries} attempts: ${lastError.message}`);
}

Need help? Contact our support team or check the IoTeX documentation.