使用 web3 在 MetaMask 中避免 "This gas fee has been suggested by" 消息

Avoid "This gas fee has been suggested by" message in MetaMask using web3

我目前正在升级以太坊 dApp(使用 React JS)以符合新的 EIP-1559 标准(A.K.A。伦敦硬分叉)。该应用程序使用 web3.js (v1.5.2) 发起交易,其形式类似于

const contract = new web3.eth.Contract(
  contractABI,
  CONTRACT_ADDRESS,
);

await contract.methods
  .deposit(recepient, amount)
  .send({ from: account, value })

我们鼓励用户使用 MetaMask 与我们的应用交互。

尽管我在发送交易时既没有指定 gasPricegasLimit,也没有指定 EIP-1559 指定的等效 maxPriorityFeePerGasmaxFeePerGas, MetaMask 仍然警告(在我的本地测试环境中)"localhost suggested gas fee" with "Unknown processing time" 和潜在的巨额费用。

点击“编辑”another warning message appears, to make matters worse, the values I (or I guess web3) supposedly "suggested" are not reasonable according to MetaMask's estimate.

有没有办法使用 web3 与 MetaMask 接口来接受 MetaMask 的建议值,删除这些 MetaMask 警告并确保费用计算正确?我注意到查看 https://app.uniswap.org/ 虽然 MetaMask 仍然显示第一个“app.unswap.org 建议 gas 费用”警告,但 txn 时间是正确计算的并且点击“编辑”不会显示任何进一步的警告。 Uniswap 与 MetaMask 更合理的交互是否可以使用 web3.js 复制?

好的,我已经弄明白了。

如果没有为特定事务定义 maxPriorityFeePerGasmaxFeePerGas,web3 将生成自己的值。令人失望的是,生成的值非常差,会在 MetaMask 中触发警告。解决方案(在编写时完全未记录)是将 maxPriorityFeePerGasmaxFeePerGas 设置为 null 而不是 undefined。这将向 web3 发出信号,表明您不希望它向提供者传递这些值。

所以代码应该类似于:

const contract = new web3.eth.Contract(
  contractABI,
  CONTRACT_ADDRESS,
);

await contract.methods
  .deposit(recepient, amount)
  .send({ 
    from: account, 
    value, 
    maxPriorityFeePerGas: null,
    maxFeePerGas: null, 
  });

此外,请确保您使用的是最新版本的 web3,因为 EIP-1559 支持仅在 v1.5 中添加。