首页 > 解决方案 > tx.wait 与 Ethers.js 永远不会解决

问题描述

我正在尝试使用 ethers.js 将事务发送到多边形网络。提交交易后, i await tx.wait(),但有 50% 的时间无法解决。我看到其他人也有类似的问题,但由于他们的汽油价格太低。我目前有这个代码:

const getWallet = (): Wallet => {
  return new ethers.Wallet(PRIVATE_KEY, HTTP_PROVIDER);
};
const wallet = getWallet();
const gasPrice = 50000000000;
const swap1 = await wallet.sendTransaction({
      data: tx1.data,
      chainId: tx1.chainId,
      from: tx1.from,
      gasLimit: 350449, 
      gasPrice: gasPrice, 
      value: '0x' + new BigNumber(tx1.value).toString(16),
      to: tx1.to,
      nonce: nonce,
    });

我总是返回一个具有 tx 哈希的对象,但是当我在 polyscan 上查找该哈希时,它永远不会出现。有时等待长达一个小时后 tx.wait() 仍然没有解决,并且事务仍然没有出现在 polyscan 中。我取消了我的脚本,将 gasPrice 提高了 20%,然后尝试使用相同的 nonce 再次运行它(希望能替换它)。那时我通常会被告知更换汽油费太低。有人可以解释我在这里做错了什么吗?

标签: blockchainweb3web3jsethers.js

解决方案


也许您首先需要使用新的 ethers.providers 来实例化提供程序,在这个示例中我使用 JsonRpcProvider。

或者等待(),您可以使用ethers.provider.waitForTransaction(hash,confirmations,timeout)执行另一个函数来等待收据。

你可以这样做:

const ethers = require("ethers");
const provider = new ethers.providers.JsonRpcProvider(HTTP_PROVIDER);
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);
const swap1 = await wallet.sendTransaction({//});
const receipt = provider.waitForTransaction(swap1.hash, 1, 150000).then(() => {//});

推荐阅读