I m trying to estimate what is current gas price with Web3.js library on zkSync layer2 network however I m constantly getting same result: 250000000 for multiple days so I assume it s not working correctly. Is web3.js not working with zkSync? https://web3js.readthedocs.io/en/v1.10.0/web3-eth.html?highlight=getGasPrice#getgasprice
const Web3 = require("web3"); // Web3 library
const web3 = new Web3("https://mainnet.era.zksync.io");
let gasPrice = await web3.eth.getGasPrice();
getGasPrice()
returns the median gas price (calculated from previous few blocks).
https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#getgasprice
You can retrieve that by:
const result = await web3.eth.getGasPrice()
console.log(web3.utils.fromWei(result, 'ether'))
As to why its 250000000
, that's because that's the baseFeePerGas
set: https://github.com/matter-labs/foundry-zksync#get-latest-block
If you want to estimate the gas price for a transaction you want to make, you can use the estimateGas
function.
https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#estimategas
You can do something like:
const gasAmount = await web3.eth.estimateGas({
to: toAddress,
from: fromAddress,
value: web3.utils.toWei(`${amount}`, 'ether'),
})
The input to estimateGas
function is a transaction object.
To add a bit further to this answer,
total fee = amount of gas * fee per unit gas = Y * X
Which is why I recommended to use estimateGas()
function.