[Ethereum] error: replacement transaction underpriced – Nonce increment? how? Atomic transaction

noncetransactions

trying to send 2 transactions through infura to ropsten smart contract, but got the error: "replacement transaction underpriced". For my understanding its a Nonce increment problem…tried this code without success…

var Contract = require('web3-eth-contract');
const contract = new web3.eth.Contract(abi, contractAddress);


web3.eth.getTransactionCount(account, (err, txCount) => {

    const txObject = {
      nonce:    web3.utils.toHex(txCount),
      gasLimit: web3.utils.toHex(800000), // Raise the gas limit to a much higher amount
      gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
      //value: web3.utils.toHex(web3.utils.toWei('0.01', 'ether')),
      //value: 1000000000000000000,
      to: contractAddress,
      data: contract.methods.function1(["...).encodeABI()
    }
  
    const tx = new Tx(txObject, { chain: 'ropsten' })
    tx.sign(privateKey)
  
    const serializedTx = tx.serialize()
    const raw = '0x' + serializedTx.toString('hex')
  
    web3.eth.sendSignedTransaction(raw, (err, txHash) => {
      console.log('err:', err, 'txHash:', txHash)
      // Use this txHash to find the contract on Etherscan!
    })
})



web3.eth.getTransactionCount(account, (err, txCount2) => {

    const txObject2 = {
      nonce:    web3.utils.toHex(txCount2),
      gasLimit: web3.utils.toHex(800000), // Raise the gas limit to a much higher amount
      gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
      //value: web3.utils.toHex(web3.utils.toWei('0.01', 'ether')),
      //value: 1000000000000000000,
      to: contractAddress,
      data: contract.methods.function2("....").encodeABI()
    }
  
    const tx2 = new Tx(txObject2, { chain: 'ropsten' })
    tx2.sign(privateKey)
  
    const serializedTx2 = tx2.serialize()
    const raw2 = '0x' + serializedTx2.toString('hex')
  
    web3.eth.sendSignedTransaction(raw2, (err, txHash2) => {
      console.log('err:', err, 'txHash:', txHash2)
      // Use this txHash to find the contract on Etherscan!
    })
})

Should I put in transaction2:

nonce = web3.eth.getTransactionCount(contractadress?) + 1 

or

web3.eth.getTransactionCount() + 0

I'm missing something, tried these options but I got other errors. These 2 transactions work when alone.
Are they possible to do in an atomic transaction, ie in the same block?

Best Answer

The problem is that the second time that you call web3.eth.getTransactionCount, your first transaction has not been mined yet. Therefore, txCount and txCount2 are exactly the same number (same nonce).

You either have to wait for the first transaction to be mined or increment txCount by yourself before sending the 2nd transaction.

Related Topic