Estimating Gas Fees
On peaq and other EVM-compatible networks, transaction execution costs are measured in gas. Before sending a transaction on the network, it’s often helpful to estimate the gas required so that you don’t overpay,
or risk your transaction running out of gas. Most EVM networks provide a built-in RPC method, eth_estimateGas
, which allows you to programmatically estimate the gas usage for a given transaction.
This estimation is done by simulating the transaction on a node, without actually broadcasting it.
Prerequisites
-
You have access to one of our EVM-Compatible RPC Endpoints:
-
You know the Transaction Data you’re sending: The parameters of the transaction you want to send are well-defined, including
from
,to
,data
(if interacting with a contract), and optionallyvalue
if sending PEAQ or the respective native token. You don’t need the exact gas amount upfront; that’s what you’re estimating. -
JSON-RPC Client: You can use a JSON-RPC client (e.g.,
curl
,Postman
,web3.js
,ethers.js
, or any library that supports JSON-RPC) to make requests to the RPC endpoint. In our example below we’ll be sending a JSON payload using acurl
request to an RPC Endpoint.
Instructions
1. Prepare the JSON-RPC Request
Use the eth_estimateGas
method to request a gas estimate. The parameters should describe the transaction you intend to send. For example:
"0x0"
2. Send the Request to the RPC Endpoint
Using curl
from your terminal, for example:
3. Read the Response
The node will return a JSON response. A successful response might look like:
The "result"
field is a hexadecimal string representing the estimated gas limit. For example, 0x5208
(in hex) is 21000
in decimal—typical for a simple ETH transfer.
4. Convert and Use the Returned Value
- Conversion: If the returned gas estimate is in hex, you can convert it to a decimal integer. In many programming languages, you can parse the hex string and turn it into an integer type. For example, in JavaScript:
- Adjustment for Safety: While
eth_estimateGas
gives a good baseline, you may want to add a buffer (e.g., add 10-20% more) to ensure your transaction doesn’t fail if conditions change by the time it’s mined.
5. Use the Estimated Gas in Your Transaction
When constructing the final transaction, set the gas
field to the estimated amount (plus any safety buffer). Consider the current gas price or fee structures (base fee + priority fee
) when calculating the total transaction cost.
Summary
Making an eth_estimateGas
call over a JSON-RPC endpoint and parsing the response, you can accurately estimate the gas limit needed for your transaction on an EVM network. This helps ensure you neither waste gas nor have insufficient gas for a successful execution.