⚠️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 represents the median gas price from recent blocks on Ethereum Mainnet.

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

# Get current gas price
curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_gasPrice",
"params": [],
"id": 1
}'

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 - Ethereum Mainnet 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 Ethereum documentation.