Skip to main content

Estimate gas

Overview

Ethereum (ETH) fees, also referred to as gas and gasPrice, are calculated based on the amount of network activity and the network resources required.

The fee rate dictates the speed at which your transaction will be picked up and confirmed by the blockchain. You can either use a custom fee to set the amount of gas and gasPrice manually in the transaction parameters, or let the SDK estimate gas automatically when creating a transaction. When setting a tentative fee rate, the fee amount is an estimate only. Gas fee calculation is not finalized until your transaction is signed.

MPC also supports the EIP-1559 standard for fee estimation:

  • Maximum priority fee: Transaction time takes priority over gas fee price.
  • Max gas fee: The gas fee max price is preset and takes priority over transaction time.

Estimate network fee

You can see the network fee estimates in your fee values before creating transaction data.

This example shows how to estimate the gasPrice network fee for the Saigon testnet using the getNetworkFee method:

...
// Get gasPrice
const gasPrice : string = await mpcCore.getNetworkFee();
console.log(gasPrice); // 0x4a817c800 (20 Gwei) in Saigon testnet
...
info

To calculate gas and gasPrice, mpcCore uses the blockchain network specified during initialization.

Estimate transaction fee

To estimate gas of a transaction, use the estimateGas method:

const gas: string = await mpcCore.estimateGas(tx);
//...

This example shows how to estimate gas for a transaction:

const tx = {
"data": "0x",
"to": "0xedb40e7abaa613a0b06d86260dd55c7eb2df2447",
"value": "0x16345785d8a0000"
};
const gas: string = await mpcCore.estimateGas(tx);
console.log(gas); // 0xa410
//...

Within the Ronin network, it's typical to require a gas limit that exceeds the estimateGas standard. This often involves using a coefficient that's 1.5 or 2 times larger than the standard estimate. In complex transaction calls to a contract, you should increase the gas 2 times or more to ensure transaction execution.

This example shows how to increase a gas limit:

import { JsonRpcProvider } from "@ethersproject/providers";

// Connect to provider - Saigon testnet
const rpc = new JsonRpcProvider(https://saigon-testnet.roninchain.com/rpc);

// Example transaction that sends 0.1 RON
const tx = {
"chainId": "0x7e5",
"from": "0x2082d1fedd8c2d2408c22869c49000f5e375ddbb",
"data": "0x",
"nonce": "0x5d",
"r": "0x0",
"s": "0x0",
"to": "0xedb40e7abaa613a0b06d86260dd55c7eb2df2447",
"v": "0x0",
"value": "0x16345785d8a0000"
};

// Estimate gas in BigNumber
const rawGas = await rpc.estimateGas(tx);

// Increase gas in testnet
const rawSafeGas = rawGas.mul(3); // Warning: multiply by 3 to overestimate gas

// Convert BigNumber to HexString
const gas = ethers.utils.hexValue(rawSafeGas);
Was this helpful?
Happy React is loading...