Web3.eth.getGasPrice 无法在 zkSync 上运行?

问题描述 投票:0回答:1

我正在尝试使用 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();
javascript ethereum blockchain web3js layer-2
1个回答
1
投票

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
函数的输入是一个交易对象。


要对此答案进行进一步补充,

  1. 每 Gas 的基本费用(我们称之为 X)是每单位 Gas 的费用。该值不会改变(除非在协议中修改)。
  2. 每笔交易所需的 Gas 量(我们称之为 Y)会根据交易的不同而有所不同。
total fee = amount of gas * fee per unit gas = Y * X

这就是为什么我推荐使用

estimateGas()
功能。

© www.soinside.com 2019 - 2024. All rights reserved.