简体   繁体   English

如何在 nodejs 中处理多个 web3 事务

[英]How to handle multiple web3 transactions in nodejs

I am handling a transaction like this:我正在处理这样的交易:

web3.eth.getTransactionCount(sender_address, (err, txCount) =>{
        console.log(txCount)
        if(err){
          console.log(err);
        }else{
          const txObject = {
            nonce: web3.utils.toHex(txCount),
            to: master_address,
            value: web3.utils.toHex(web3.utils.toWei("0.1", "ether")),
            gasLimit: web3.utils.toHex(21000),
            gasPrice: web3.utils.toHex(web3.utils.toWei("10", "gwei"))
          } 

          const tx = new Tx(txObject);
          tx.sign(sender_private_key);

          const serialized_tx = tx.serialize();
          const raw = '0x' + serialized_tx.toString('hex');
          

          web3.eth.sendSignedTransaction(raw, (err, txHash) =>{
            if(err){
              console.log(err);
              
            }else{
              console.log("txHash:", txHash);
              
            }
            
          }).then(function(receipt) {
            //Insert amir
            if(receipt["status"] == true){
              console.log("Tx has been mined")
            }else{

            }
            console.log(receipt)
          });
        }

      });

At the moment this works if the sender makes 1 transaction, but if the sender makes two transactions before they are mined, the nonce is the same, and will therefore cause an error.目前,如果发送者进行 1 笔交易,则此方法有效,但如果发送者在挖掘之前进行了两次交易,则随机数是相同的,因此会导致错误。

I have read in web3js documentation about chaining, but i am not sure if this is what i am looking for.我已经阅读了关于链接的 web3js 文档,但我不确定这是否是我正在寻找的。

How would i change my existing code in order to work for multiple transactions before they are mined?我将如何更改我现有的代码以便在多个交易被挖掘之前工作?

Your app should manage nonce and keep latest value, then use it in send transaction.您的应用程序应该管理nonce并保持最新值,然后在发送事务中使用它。

But maybe pending transactions count solve your problem但也许pending的交易计数可以解决您的问题

web3.eth.getTransactionCount(sender_address, 'pending', (err, txCount) =>{...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM