我正在尝试使用 zkSync Layer2 网络上的 Web3.js 库来估计当前的 Gas 价格是多少,但是我不断得到相同的结果:多天都是 250000000,所以我认为它无法正常工作。 web3.js 不能与 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()
返回天然气价格中位数(根据前几个区块计算)。
https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#getgasprice
您可以通过以下方式检索:
const result = await web3.eth.getGasPrice()
console.log(web3.utils.fromWei(result, 'ether'))
至于为什么是
250000000
,那是因为那是baseFeePerGas
集合:https://github.com/matter-labs/foundry-zksync#get-latest-block
如果您想估算要进行的交易的 Gas 价格,可以使用
estimateGas
函数。
https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#estimategas
你可以这样做:
const gasAmount = await web3.eth.estimateGas({
to: toAddress,
from: fromAddress,
value: web3.utils.toWei(`${amount}`, 'ether'),
})
estimateGas
函数的输入是一个交易对象。
要对此答案进行进一步补充,
total fee = amount of gas * fee per unit gas = Y * X
这就是为什么我推荐使用
estimateGas()
功能。