Skip to main content

Estimate Gas Price

Updated on
Jul 2, 2024

Overview

Gas is a way to measure the computation required to execute write operations on EVM-based blockchains, such as sending a transaction, executing a smart contract function, swapping tokens, etc. For instance, sending a transaction might require 21,000 units of gas, while executing a complex smart contract function could require several million units of gas.

The price of gas varies based on the network traffic. In this Function example, we will estimate the gas price by averaging the gas prices of a few transactions of a block and return the average gas price in Wei and Gwei.

What We Will Do

For this example, we will take the average of gas prices across several transactions in a block. We will demonstrate this in two ways: 



  1. By using a standalone Function which can be called/invoked via API.
  2. By placing a filter on Streams.

Sample Function

The following is the code for the Function to get the average gas price in JavaScript Node.js v20 runtime using the block dataset:

// Initialize the main function
function main(params) {
// Extract dataset and network from metadata in params
const block = params.data[0];
const dataset = params.metadata.dataset;
const network = params.metadata.network;

const transactions = block.transactions; // Get transactions of the block
const blockNumber = parseInt(block.number, 16); // Convert block number from hex to int

// Variable to define the maximum number of transactions to consider
const numberOfTransactions = params.user_data.noOfTX; // Get number of transactions from user

// Calculate the average gas price for the first 'numberOfTransactions' transactions
let totalGasPrice = 0;
const totalTransactions = Math.min(transactions.length, numberOfTransactions);

// Loop to get gas prices of transactions and add them to totalGasPrice
for (let i = 0; i < totalTransactions; i++) {
const gasPriceInWei = parseInt(transactions[i].gasPrice, 16);
totalGasPrice += gasPriceInWei;
}

const averageGasPriceInWei = totalGasPrice / totalTransactions; // Get average gas price in Wei
const averageGasPriceInGwei = averageGasPriceInWei / 1e9; // Convert Wei to Gwei

// Return average gas price in Wei and Gwei along with block number
return {
averageGasPriceInWei,
averageGasPriceInGwei,
blockNumber
};
}

Request

We will invoke the function with the following cURL command. Be sure to replace the YOUR_API_KEY with your own QuickNode API key and the POST URL with the URL of your Function. You can send the request with any number of transactions to check.

curl -X POST "https://api.quicknode.com/functions/rest/v1/namespaces/0f6812dd-a17f-4cbc-9ab4-7a529eb33940/functions/gas-price-estimator/call" \
-H "accept: application/json" \
-H "Content-Type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-d '{
"network": "ethereum-mainnet",
"dataset": "block",
"block": "latest",
"user_data": {
"noOfTX": 100
}
}'

Response

Resulting in the following response:

{
"response" : {
"activationId" : "a44930fe185045bf8930fe185035bfc9",
"annotations" : [
{
"key" : "path",
"value" : "ca43f206-1786-4d85-8521-952f2a528f49/gas-price-estimator"
},
{
"key" : "waitTime",
"value" : 66
},
{
"key" : "kind",
"value" : "nodejs:20"
},
{
"key" : "timeout",
"value" : false
},
{
"key" : "limits",
"value" : {
"concurrency" : 1,
"logs" : 10,
"memory" : 256,
"timeout" : 60000
}
},
{
"key" : "initTime",
"value" : 11
}
],
"duration" : 15,
"end" : 1719556513591,
"logs" : [],
"name" : "gas-price-estimator",
"namespace" : "ca43f206-1786-4d85-8521-952f2a528f49",
"publish" : false,
"response" : {
"result" : {
"averageGasPriceInGwei" : 4.46690859806154,
"averageGasPriceInWei" : 4466908598.06154,
"blockNumber" : 20188425
},
"size" : 107,
"status" : "success",
"success" : true
},
"start" : 1719556513576,
"subject" : "0f6812dd-a17f-4cbc-9ab4-7a529eb33940",
"version" : "0.0.5"
}
}

Learn more about QuickNode Functions.

Sample Stream Transformation

The following is a Streams Filter example:

Try it yourself by deploying the filtered Stream to your account.

// Initialize the main function of the filter
function main(data) {
const block = data.streamData; // Get the block data from Stream
const transactions = block.transactions; // Get transactions of the block
const blockNumber = parseInt(block.number, 16); // Convert block number from hex to int

// Variable to define the maximum number of transactions to consider
const numberOfTransactions = 100; // You can change this value as needed

// Calculate the average gas price for the first 'numberOfTransactions' transactions
let totalGasPrice = 0;
const totalTransactions = Math.min(transactions.length, numberOfTransactions);

// Loop to get gas prices of transactions and add them to totalGasPrice
for (let i = 0; i < totalTransactions; i++) {
const gasPriceInWei = parseInt(transactions[i].gasPrice, 16);
totalGasPrice += gasPriceInWei;
}

const averageGasPriceInWei = totalGasPrice / totalTransactions; // Get average gas price in Wei
const averageGasPriceInGwei = averageGasPriceInWei / 1e9; // Convert Wei to Gwei

// Return average gas price in Wei and Gwei along with block number
return {
averageGasPriceInWei,
averageGasPriceInGwei,
blockNumber
};
}

Output

Resulting in the following output:

{
"averageGasPriceInGwei": 9.74463070515,
"averageGasPriceInWei": 9744630705.15,
"blockNumber": 20177831
}

Learn more about modifying Stream output.

We ❤️ Feedback!

If you have any feedback or questions about this documentation, let us know. We'd love to hear from you!

Share this doc