eth_gasPrice
Returns the current gas price in wei on xdc.
When to Use This Method
Use eth_gasPrice
to:
- Estimate Transaction Costs - Calculate fees before sending
- Optimize Gas Settings - Set competitive gas prices
- Monitor Network Congestion - Track gas price fluctuations
- Cross-Chain Fee Calculation - Estimate omnichain operation costs
- Dynamic Fee Adjustment - Adjust fees based on network conditions
Parameters
This method accepts no parameters.
{
"jsonrpc": "2.0",
"method": "eth_gasPrice",
"params": [],
"id": 1
}
Returns
QUANTITY
- Current gas price in wei.
- Type: Hexadecimal string
- Unit: Wei per gas unit
- Format:
0x
prefixed
Implementation Examples
- cURL
- JavaScript
- Python
curl -X POST https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_gasPrice",
"params": [],
"id": 1
}'
// Using fetch
const response = await fetch('https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_gasPrice',
params: [],
id: 1,
}),
});
const data = await response.json();
const gasPriceWei = BigInt(data.result);
const gasPriceGwei = Number(gasPriceWei) / 1e9;
console.log('Gas Price:', gasPriceGwei, 'Gwei');
// Using ethers.js
import { ethers } from 'ethers';
const provider = new ethers.JsonRpcProvider('https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY');
const gasPrice = await provider.getGasPrice();
console.log('Current gas price:', ethers.formatUnits(gasPrice, 'gwei'), 'Gwei');
// Using web3.js
import Web3 from 'web3';
const web3 = new Web3('https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY');
const gasPrice = await web3.eth.getGasPrice();
console.log('Gas price:', web3.utils.fromWei(gasPrice, 'gwei'), 'Gwei');
// Dynamic gas price with buffer
async function getOptimalGasPrice(speedMultiplier = 1.1) {
const baseGasPrice = await provider.getGasPrice();
const optimalGasPrice = baseGasPrice * BigInt(Math.floor(speedMultiplier * 100)) / 100n;
return {
base: ethers.formatUnits(baseGasPrice, 'gwei'),
optimal: ethers.formatUnits(optimalGasPrice, 'gwei'),
wei: optimalGasPrice.toString()
};
}
import requests
import json
from web3 import Web3
# Using requests
url = 'https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY'
headers = {'Content-Type': 'application/json'}
payload = {
'jsonrpc': '2.0',
'method': 'eth_gasPrice',
'params': [],
'id': 1
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
result = response.json()
gas_price_wei = int(result['result'], 16)
gas_price_gwei = gas_price_wei / 10**9
print(f'Gas Price: {gas_price_gwei} Gwei')
# Using web3.py
w3 = Web3(Web3.HTTPProvider('https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY'))
gas_price = w3.eth.gas_price
gas_price_gwei = w3.from_wei(gas_price, 'gwei')
print(f'Current gas price: {gas_price_gwei} Gwei')
# Monitor gas price changes
import time
def monitor_gas_prices(duration=60, interval=5):
start_time = time.time()
prices = []
while time.time() - start_time < duration:
gas_price = w3.eth.gas_price
gwei_price = w3.from_wei(gas_price, 'gwei')
prices.append(float(gwei_price))
print(f'Gas: {gwei_price} Gwei')
time.sleep(interval)
return {
'min': min(prices),
'max': max(prices),
'avg': sum(prices) / len(prices),
'samples': len(prices)
}
Example Response
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x3b9aca00"
}
Decoding: 0x3b9aca00
= 1,000,000,000 wei = 1 Gwei
xdc Gas Pricing
Omnichain Gas Calculation
// Calculate gas for cross-chain operations
class OmnichainGasCalculator {
constructor(provider) {
this.provider = provider;
this.chainMultipliers = {
1: 1.5, // Ethereum - higher security
56: 1.2, // BSC - moderate
137: 1.1, // Polygon - low cost
8332: 2.0 // Bitcoin - highest security
};
}
async calculateCrossChainGas(destChainId, gasLimit = 200000) {
// Get xdc base gas price
const baseGasPrice = await this.provider.getGasPrice();
// Apply chain-specific multiplier
const multiplier = this.chainMultipliers[destChainId] || 1.3;
const crossChainGasPrice = baseGasPrice * BigInt(Math.floor(multiplier * 100)) / 100n;
// Calculate total cost
const xdcGas = baseGasPrice * BigInt(100000); // Base tx on xdc
const destinationGas = crossChainGasPrice * BigInt(gasLimit);
const protocolFee = ethers.parseEther('0.01'); // Fixed protocol fee
const totalCost = xdcGas + destinationGas + protocolFee;
return {
xdcGas: ethers.formatEther(xdcGas),
destinationGas: ethers.formatEther(destinationGas),
protocolFee: ethers.formatEther(protocolFee),
totalCost: ethers.formatEther(totalCost),
gasPrice: {
base: ethers.formatUnits(baseGasPrice, 'gwei'),
crossChain: ethers.formatUnits(crossChainGasPrice, 'gwei')
}
};
}
}
Common Use Cases
1. Transaction Cost Estimator
class TransactionCostEstimator {
constructor(provider) {
this.provider = provider;
}
async estimateCost(transaction) {
const [gasPrice, gasLimit] = await Promise.all([
this.provider.getGasPrice(),
this.provider.estimateGas(transaction)
]);
const gasCost = gasPrice * gasLimit;
return {
gasPrice: ethers.formatUnits(gasPrice, 'gwei') + ' Gwei',
gasLimit: gasLimit.toString(),
totalCost: ethers.formatEther(gasCost) + ' ZETA',
breakdown: {
slow: ethers.formatEther(gasPrice * gasLimit * 90n / 100n),
standard: ethers.formatEther(gasCost),
fast: ethers.formatEther(gasPrice * gasLimit * 120n / 100n),
instant: ethers.formatEther(gasPrice * gasLimit * 150n / 100n)
}
};
}
async estimateCrossChainCost(sourceChain, destChain, data) {
const gasPrice = await this.provider.getGasPrice();
// Base costs
const sourceTx = gasPrice * 100000n; // Source chain tx
const relayFee = ethers.parseEther('0.01'); // Relay fee
const destTx = gasPrice * 200000n; // Destination chain tx
return {
source: ethers.formatEther(sourceTx),
relay: ethers.formatEther(relayFee),
destination: ethers.formatEther(destTx),
total: ethers.formatEther(sourceTx + relayFee + destTx)
};
}
}
2. Dynamic Gas Price Strategy
class GasPriceStrategy {
constructor(provider) {
this.provider = provider;
this.history = [];
this.maxHistory = 100;
}
async getRecommendedGasPrice(priority = 'standard') {
const currentGasPrice = await this.provider.getGasPrice();
// Store in history
this.history.push({
price: currentGasPrice,
timestamp: Date.now()
});
if (this.history.length > this.maxHistory) {
this.history.shift();
}
// Calculate average from recent history
const recentPrices = this.history.slice(-10).map(h => h.price);
const avgPrice = recentPrices.reduce((a, b) => a + b, 0n) / BigInt(recentPrices.length);
// Apply priority multipliers
const multipliers = {
slow: 0.8,
standard: 1.0,
fast: 1.2,
instant: 1.5
};
const multiplier = multipliers[priority] || 1.0;
const recommendedPrice = avgPrice * BigInt(Math.floor(multiplier * 100)) / 100n;
// Ensure minimum gas price
const minGasPrice = ethers.parseUnits('1', 'gwei');
const finalPrice = recommendedPrice > minGasPrice ? recommendedPrice : minGasPrice;
return {
wei: finalPrice.toString(),
gwei: ethers.formatUnits(finalPrice, 'gwei'),
priority,
basedOn: `${recentPrices.length} recent samples`
};
}
}
3. Gas Price Oracle
class GasPriceOracle {
constructor(provider) {
this.provider = provider;
this.cache = null;
this.cacheTime = 0;
this.cacheDuration = 5000; // 5 seconds
}
async getGasPrices() {
// Check cache
if (this.cache && Date.now() - this.cacheTime < this.cacheDuration) {
return this.cache;
}
const gasPrice = await this.provider.getGasPrice();
// Calculate different speed tiers
const prices = {
slow: {
price: gasPrice * 80n / 100n,
maxWait: '30 seconds',
confidence: 0.7
},
standard: {
price: gasPrice,
maxWait: '15 seconds',
confidence: 0.95
},
fast: {
price: gasPrice * 125n / 100n,
maxWait: '10 seconds',
confidence: 0.99
},
instant: {
price: gasPrice * 150n / 100n,
maxWait: '6 seconds',
confidence: 0.999
}
};
// Format for display
const formatted = {};
for (const [speed, data] of Object.entries(prices)) {
formatted[speed] = {
...data,
gwei: ethers.formatUnits(data.price, 'gwei'),
estimatedCost: ethers.formatEther(data.price * 21000n) // Simple transfer
};
}
this.cache = formatted;
this.cacheTime = Date.now();
return formatted;
}
}
4. Network Congestion Monitor
class NetworkCongestionMonitor {
constructor(provider) {
this.provider = provider;
this.baseline = null;
}
async initialize() {
// Establish baseline gas price (24h average)
this.baseline = await this.provider.getGasPrice();
}
async getCongestionLevel() {
if (!this.baseline) {
await this.initialize();
}
const currentGasPrice = await this.provider.getGasPrice();
const ratio = Number(currentGasPrice * 100n / this.baseline) / 100;
let level, color, recommendation;
if (ratio < 0.8) {
level = 'Low';
color = 'green';
recommendation = 'Excellent time for transactions';
} else if (ratio < 1.2) {
level = 'Normal';
color = 'blue';
recommendation = 'Standard conditions';
} else if (ratio < 1.5) {
level = 'Elevated';
color = 'yellow';
recommendation = 'Consider waiting if not urgent';
} else if (ratio < 2.0) {
level = 'High';
color = 'orange';
recommendation = 'Delay non-urgent transactions';
} else {
level = 'Extreme';
color = 'red';
recommendation = 'Only urgent transactions recommended';
}
return {
level,
color,
recommendation,
currentGasPrice: ethers.formatUnits(currentGasPrice, 'gwei'),
baselineGasPrice: ethers.formatUnits(this.baseline, 'gwei'),
congestionRatio: ratio.toFixed(2)
};
}
}
5. Cross-Chain Fee Comparison
async function compareCrossChainFees() {
const provider = new ethers.JsonRpcProvider('https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY');
const zetaGasPrice = await provider.getGasPrice();
// Estimate fees for different destination chains
const chains = [
{ id: 1, name: 'Ethereum', gasMultiplier: 2.0 },
{ id: 56, name: 'BSC', gasMultiplier: 1.2 },
{ id: 137, name: 'Polygon', gasMultiplier: 1.1 },
{ id: 43114, name: 'Avalanche', gasMultiplier: 1.3 }
];
const fees = {};
for (const chain of chains) {
const crossChainGas = zetaGasPrice * BigInt(Math.floor(chain.gasMultiplier * 100)) / 100n;
const estimatedFee = crossChainGas * 200000n; // Typical cross-chain gas limit
fees[chain.name] = {
gasPrice: ethers.formatUnits(crossChainGas, 'gwei') + ' Gwei',
estimatedFee: ethers.formatEther(estimatedFee) + ' ZETA',
multiplier: chain.gasMultiplier
};
}
return fees;
}
Gas Price Ranges
Typical xdc Gas Prices
Network State | Gas Price (Gwei) | Transaction Time |
---|---|---|
Low Activity | 1-5 | 6-12 seconds |
Normal | 5-10 | 6 seconds |
Busy | 10-20 | 6 seconds |
Congested | 20-50 | 6 seconds |
Peak | 50+ | 6 seconds |
Best Practices
- Always fetch current gas price before transactions
- Implement retry logic for gas price queries
- Cache gas prices for short periods (5-10 seconds)
- Add buffer (10-20%) for important transactions
- Monitor gas price trends for optimal timing
Error Codes
Code | Message | Description |
---|---|---|
-32600 | Invalid Request | Invalid JSON |
-32601 | Method not found | Method doesn't exist |
-32602 | Invalid params | Invalid parameters |
-32603 | Internal error | Internal JSON-RPC error |
Related Methods
- eth_estimateGas - Estimate gas usage
eth_maxPriorityFeePerGas
- EIP-1559 priority feeeth_feeHistory
- Historical gas prices- eth_sendRawTransaction - Send transaction