首页 > 解决方案 > 以太坊使用 web3.js 发送今天不工作(结果是失败)

问题描述

这是我发送 ETH 的 web3.js 函数。它在上个月完美运行。但是今天它运行得不好。花了超过1~5分钟,然后返回失败。有时它会发送,但完成交易也需要很长时间。请帮我解决这个问题。这是我目前的代码。

  var web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/GfgWbe8c2O82N18RRSuJ'));

  // Who holds the token now?
  var myAddress = address;
  // This file is just JSON stolen from the contract page on etherscan.io under "Contract ABI"
  return await web3.eth.getBalance(myAddress);
}

const sendETHCoin = async (from_addr, to_addr, amount, private_key, fee) => {
  var content = fs.readFileSync(base_path + 'abiDefinitions/ethAbiContract.json');
  content = JSON.parse(content);
  ///////////////////////////////////

  // connect to Infura node
  var web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/GfgWbe8c2O82N18RRSuJ'));  

  // the address that will send the test transaction
  const addressFrom = from_addr;
  const privKey = private_key;

  // the destination address
  const addressTo = to_addr;

  var gasPrice = "0x02540BE400";
  var gasLimit = "0x250CA";

  if(fee == ''){
    fee = parseInt(gasPrice, 16) * parseInt(gasLimit, 16);  
  }else{
    gasPrice = parseInt(parseInt(fee)/parseInt(gasLimit, 16))+1;
    if(gasPrice < 1){
      gasPrice = 1;
    }
    gasPrice = "0x"+gasPrice.toString(16);
  }
  //gasPrice = "0x03540BE400";

  var txCount = await web3.eth.getTransactionCount(addressFrom);

  const txData = {
    nonce: web3.utils.toHex(txCount),
    gasLimit: web3.utils.toHex(25000),
    gasPrice: web3.utils.toHex(10e9), // 10 Gwei
    to: addressTo,
    from: addressFrom,
    value: web3.utils.toHex(web3.utils.toWei(amount, 'wei'))
  }

  // Signs the given transaction data and sends it. Abstracts some of the details 
  // of buffering and serializing the transaction for web3.
   const privateKey = new Buffer(privKey, 'hex')
   const transaction = new Tx(txData)
   transaction.sign(privateKey)
   const serializedTx = transaction.serialize().toString('hex')

   try {
    return await web3.eth.sendSignedTransaction('0x' + serializedTx)    
  }catch(err) {
    console.log(err.message);
    return err.message;
  }
  //////////////////////////////
}

我希望有人能帮助我。

此致。天阳

标签: node.jsethereumweb3

解决方案


您可以在 etherscan 中检查交易失败的原因。如果交易在上个月成功,问题可能出在汽油价格上。上周 gas 价格太高(安全最低价是 50 gwei),我看到你用 10 gwei 发送,这很可能是你交易失败的原因。尝试提高gas价格,看看它是否再次起作用


推荐阅读