Centrifuge
eth_gasPrice - Get Current Gas Price
Get the current gas price in wei on Centrifuge Mainnet. Essential for transaction fee calculation and gas strategy optimization.
Returns the current gas price in wei. This represents the median gas price from recent blocks on Centrifuge 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
import { JsonRpcProvider, formatGwei, formatEther } from 'ethers';
const provider = new JsonRpcProvider('https://api-centrifuge.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!');
}from web3 import Web3
from eth_utils import from_wei
import time
import statistics
from typing import Dict, List, Optional, Callable
from datetime import datetime, timedelta
import asyncio
w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'))
class GasPriceAnalyzer:
"""Analyze and optimize gas prices on Centrifuge Mainnet"""
def __init__(self, w3_instance):
self.w3 = w3_instance
self.price_history = []
self.monitoring = False
def get_current_gas_price(self) -> Dict[str, any]:
"""Get current gas price in multiple units"""
gas_price = self.w3.eth.gas_price
return {
'wei': gas_price,
'gwei': from_wei(gas_price, 'gwei'),
'eth': from_wei(gas_price, 'ether'),
'hex': hex(gas_price),
'timestamp': datetime.now().isoformat()
}
def get_comprehensive_gas_data(self) -> Dict[str, any]:
"""Get comprehensive gas pricing data"""
# Current gas price
gas_price = self.w3.eth.gas_price
# Latest block for base fee
latest_block = self.w3.eth.get_block('latest')
base_fee = latest_block.get('baseFeePerGas', 0)
# Priority fee estimate
try:
priority_fee = self.w3.eth.max_priority_fee
except:
priority_fee = gas_price // 10 # Fallback estimate
# Calculate different speed options
speeds = {
'slow': {
'gas_price_gwei': from_wei(int(gas_price * 0.9), 'gwei'),
'max_fee_gwei': from_wei(int((base_fee * 2 + priority_fee) * 0.9), 'gwei'),
'priority_fee_gwei': from_wei(int(priority_fee * 0.8), 'gwei'),
'estimated_time': '2-5 minutes'
},
'standard': {
'gas_price_gwei': from_wei(gas_price, 'gwei'),
'max_fee_gwei': from_wei(base_fee * 2 + priority_fee, 'gwei'),
'priority_fee_gwei': from_wei(priority_fee, 'gwei'),
'estimated_time': '15-30 seconds'
},
'fast': {
'gas_price_gwei': from_wei(int(gas_price * 1.2), 'gwei'),
'max_fee_gwei': from_wei(int((base_fee * 2 + priority_fee) * 1.2), 'gwei'),
'priority_fee_gwei': from_wei(int(priority_fee * 1.5), 'gwei'),
'estimated_time': '5-15 seconds'
},
'instant': {
'gas_price_gwei': from_wei(int(gas_price * 1.5), 'gwei'),
'max_fee_gwei': from_wei(int((base_fee * 2 + priority_fee) * 1.5), 'gwei'),
'priority_fee_gwei': from_wei(int(priority_fee * 2), 'gwei'),
'estimated_time': '< 5 seconds'
}
}
return {
'current_gas_price_gwei': from_wei(gas_price, 'gwei'),
'base_fee_gwei': from_wei(base_fee, 'gwei'),
'priority_fee_gwei': from_wei(priority_fee, 'gwei'),
'speeds': speeds,
'network_congestion': self._assess_congestion(base_fee),
'block_number': latest_block['number'],
'timestamp': datetime.now().isoformat()
}
def _assess_congestion(self, base_fee: int) -> str:
"""Assess network congestion based on base fee"""
base_gwei = from_wei(base_fee, 'gwei')
if base_gwei < 0.1:
return 'very low'
elif base_gwei < 0.5:
return 'low'
elif base_gwei < 1:
return 'moderate'
elif base_gwei < 5:
return 'high'
else:
return 'very high'
def calculate_transaction_cost(
self,
gas_limit: int,
speed: str = 'standard'
) -> Dict[str, any]:
"""Calculate transaction cost at different speeds"""
gas_data = self.get_comprehensive_gas_data()
speed_data = gas_data['speeds'].get(speed, gas_data['speeds']['standard'])
gas_price_wei = self.w3.to_wei(speed_data['gas_price_gwei'], 'gwei')
total_cost_wei = gas_price_wei * gas_limit
# Estimate USD value (would need oracle in production)
eth_price_usd = 3000 # Example static price
total_cost_eth = from_wei(total_cost_wei, 'ether')
total_cost_usd = total_cost_eth * eth_price_usd
return {
'gas_limit': gas_limit,
'gas_price_gwei': speed_data['gas_price_gwei'],
'speed': speed,
'total_cost_wei': total_cost_wei,
'total_cost_gwei': from_wei(total_cost_wei, 'gwei'),
'total_cost_eth': total_cost_eth,
'total_cost_usd': round(total_cost_usd, 4),
'estimated_time': speed_data['estimated_time']
}
def analyze_historical_prices(
self,
duration_minutes: int = 60
) -> Dict[str, any]:
"""Analyze historical gas prices"""
if not self.price_history:
return {'error': 'No historical data available'}
# Filter data for requested duration
cutoff_time = datetime.now() - timedelta(minutes=duration_minutes)
recent_prices = [
p for p in self.price_history
if datetime.fromisoformat(p['timestamp']) > cutoff_time
]
if not recent_prices:
return {'error': 'No data for requested period'}
prices_gwei = [p['gwei'] for p in recent_prices]
return {
'period_minutes': duration_minutes,
'samples': len(prices_gwei),
'average_gwei': round(statistics.mean(prices_gwei), 4),
'median_gwei': round(statistics.median(prices_gwei), 4),
'min_gwei': min(prices_gwei),
'max_gwei': max(prices_gwei),
'std_dev_gwei': round(statistics.stdev(prices_gwei), 4) if len(prices_gwei) > 1 else 0,
'volatility': self._calculate_volatility(prices_gwei),
'trend': self._calculate_trend(prices_gwei)
}
def _calculate_volatility(self, prices: List[float]) -> str:
"""Calculate price volatility"""
if len(prices) < 2:
return 'unknown'
std_dev = statistics.stdev(prices)
mean = statistics.mean(prices)
cv = (std_dev / mean) * 100 if mean > 0 else 0
if cv < 10:
return 'low'
elif cv < 25:
return 'moderate'
elif cv < 50:
return 'high'
else:
return 'very high'
def _calculate_trend(self, prices: List[float]) -> str:
"""Calculate price trend"""
if len(prices) < 3:
return 'stable'
first_third = prices[:len(prices)//3]
last_third = prices[-len(prices)//3:]
avg_first = statistics.mean(first_third)
avg_last = statistics.mean(last_third)
change_percent = ((avg_last - avg_first) / avg_first) * 100 if avg_first > 0 else 0
if change_percent > 10:
return 'increasing'
elif change_percent < -10:
return 'decreasing'
else:
return 'stable'
async def monitor_prices(
self,
interval_seconds: int = 5,
duration_minutes: int = 60,
callback: Optional[Callable] = None
):
"""Monitor gas prices over time"""
self.monitoring = True
end_time = datetime.now() + timedelta(minutes=duration_minutes)
while self.monitoring and datetime.now() < end_time:
price_data = self.get_current_gas_price()
self.price_history.append(price_data)
# Keep only recent history (last 1000 entries)
if len(self.price_history) > 1000:
self.price_history = self.price_history[-1000:]
if callback:
stats = self.analyze_historical_prices(5) # Last 5 minutes
callback(price_data, stats)
await asyncio.sleep(interval_seconds)
def stop_monitoring(self):
"""Stop price monitoring"""
self.monitoring = False
def get_optimal_send_time(
self,
target_gwei: float,
lookback_minutes: int = 60
) -> Dict[str, any]:
"""Predict optimal time to send transaction"""
analysis = self.analyze_historical_prices(lookback_minutes)
if 'error' in analysis:
return analysis
current_price = self.get_current_gas_price()['gwei']
# Simple prediction based on trend
if analysis['trend'] == 'decreasing':
suggestion = 'Wait - prices are falling'
estimated_wait = '5-10 minutes'
elif analysis['trend'] == 'increasing':
suggestion = 'Send now - prices are rising'
estimated_wait = '0 minutes'
else:
if current_price <= target_gwei:
suggestion = 'Send now - target price reached'
estimated_wait = '0 minutes'
elif current_price < analysis['average_gwei']:
suggestion = 'Good time - below average'
estimated_wait = '0 minutes'
else:
suggestion = 'Consider waiting'
estimated_wait = '10-15 minutes'
return {
'current_gwei': current_price,
'target_gwei': target_gwei,
'average_gwei': analysis['average_gwei'],
'trend': analysis['trend'],
'suggestion': suggestion,
'estimated_wait': estimated_wait
}
# Usage examples
analyzer = GasPriceAnalyzer(w3)
# Get current gas price
current = analyzer.get_current_gas_price()
print(f"Current gas price: {current['gwei']} gwei")
# Get comprehensive data
gas_data = analyzer.get_comprehensive_gas_data()
print(f"Network congestion: {gas_data['network_congestion']}")
print(f"Recommended for fast tx: {gas_data['speeds']['fast']['gas_price_gwei']} gwei")
# Calculate costs
eth_transfer_cost = analyzer.calculate_transaction_cost(21000, 'standard')
print(f"ETH transfer cost: ${eth_transfer_cost['total_cost_usd']}")
contract_cost = analyzer.calculate_transaction_cost(100000, 'fast')
print(f"Contract call cost: {contract_cost['total_cost_eth']} ETH")
# Get optimal send time
optimal = analyzer.get_optimal_send_time(0.5, 30)
print(f"Optimal send strategy: {optimal['suggestion']}")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 Scenario | Description | Solution |
|---|---|---|
| Network timeout | RPC connection issues | Retry with exponential backoff |
| Invalid response | Malformed data from node | Validate response format |
| Stale data | Cached price too old | Force 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 - Centrifuge 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 Centrifuge documentation.