⚠️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 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 -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
}'

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 StateGas Price (Gwei)Transaction Time
Low Activity1-56-12 seconds
Normal5-106 seconds
Busy10-206 seconds
Congested20-506 seconds
Peak50+6 seconds

Best Practices

  1. Always fetch current gas price before transactions
  2. Implement retry logic for gas price queries
  3. Cache gas prices for short periods (5-10 seconds)
  4. Add buffer (10-20%) for important transactions
  5. Monitor gas price trends for optimal timing

Error Codes

CodeMessageDescription
-32600Invalid RequestInvalid JSON
-32601Method not foundMethod doesn't exist
-32602Invalid paramsInvalid parameters
-32603Internal errorInternal JSON-RPC error