eth_gasPrice - Polygon

The eth_gasPrice method returns the current gas price in wei. This value represents the median gas price of the most recent blocks and is useful for estimating transaction costs. On Polygon, gas prices are typically very low compared to Ethereum mainnet.

Parameters

  • None

Request

cURL

bashcurl --location --request POST 'https://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/' \
--header 'Content-Type: application/json' \
--data-raw '{
    "jsonrpc": "2.0",
    "method": "eth_gasPrice",
    "params": [],
    "id": "getblock.io"
}'

request.js

javascriptimport axios from 'axios';

const url = 'https://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/';

const payload = {
    jsonrpc: '2.0',
    method: 'eth_gasPrice',
    params: [],
    id: 'getblock.io'
};

axios.post(url, payload, {
    headers: { 'Content-Type': 'application/json' }
})
.then(response => {
    const gasPriceWei = parseInt(response.data.result, 16);
    const gasPriceGwei = gasPriceWei / 1e9;
    console.log(`Gas Price: ${gasPriceGwei} Gwei`);
})
.catch(error => console.error(error));

request.py

pythonimport requests

url = "https://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/"

payload = {
    "jsonrpc": "2.0",
    "method": "eth_gasPrice",
    "params": [],
    "id": "getblock.io"
}

response = requests.post(url, headers={"Content-Type": "application/json"}, json=payload)
result = response.json()
gas_price_wei = int(result["result"], 16)
gas_price_gwei = gas_price_wei / 1e9
print(f"Gas Price: {gas_price_gwei} Gwei")

main.rs

rustuse reqwest::header;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    
    let response = client
        .post("https://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/")
        .header(header::CONTENT_TYPE, "application/json")
        .body(r#"{
            "jsonrpc": "2.0",
            "method": "eth_gasPrice",
            "params": [],
            "id": "getblock.io"
        }"#)
        .send()
        .await?;
    
    println!("{}", response.text().await?);
    Ok(())
}

Response

response.json

json{
    "jsonrpc": "2.0",
    "id": "getblock.io",
    "result": "0x6FC23AC00"
}

Response parameters

FieldTypeDescription
jsonrpcstringJSON-RPC version (2.0)
idstringRequest identifier
resultstringCurrent gas price in wei (hexadecimal)

Use case

The eth_gasPrice method is essential for:

  • Transaction cost calculation: Estimate total cost before sending transactions
  • Gas price monitoring: Track network congestion levels
  • Dynamic pricing: Adjust gas prices based on network conditions
  • Budget management: Ensure sufficient funds for transactions
  • Arbitrage: Monitor gas prices for MEV opportunities

Example: Transaction Cost Calculator

calculateTransactionCost.js

javascriptasync function calculateTransactionCost(provider, gasLimit) {
    const gasPrice = await provider.send('eth_gasPrice', []);
    const gasPriceWei = BigInt(gasPrice);
    const totalCost = gasPriceWei * BigInt(gasLimit);
    
    return {
        gasPrice: gasPriceWei,
        gasPriceGwei: Number(gasPriceWei) / 1e9,
        totalCostWei: totalCost,
        totalCostMatic: Number(totalCost) / 1e18
    };
}

Error handling

Status CodeError MessageCause
403ForbiddenMissing or invalid ACCESS-TOKEN
-32600Invalid RequestMalformed request body

Web3 integration

ethers.js

javascriptimport { ethers } from 'ethers';

const provider = new ethers.JsonRpcProvider('https://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/');

// Get fee data (includes gas price)
const feeData = await provider.getFeeData();
console.log('Gas Price:', ethers.formatUnits(feeData.gasPrice, 'gwei'), 'Gwei');

// Using raw RPC call
const gasPrice = await provider.send('eth_gasPrice', []);
console.log('Gas Price (hex):', gasPrice);

viem.js

javascriptimport { createPublicClient, http, formatGwei } from 'viem';
import { polygon } from 'viem/chains';

const client = createPublicClient({
    chain: polygon,
    transport: http('https://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/')
});

const gasPrice = await client.getGasPrice();
console.log('Gas Price:', formatGwei(gasPrice), 'Gwei');