You can simply use web3.eth.getTransactionCount
to get the transaction nonce but it doesn’t include the transactions pending in the transaction pool. The purpose of this API is to simply retrieve total transactions count from the blockchain only till a particular block (by default latest block).
So when you are pushing a lot of transactions from a single account at a very fast rate then transactions will start getting overwritten as you cannot have two transactions with same nonce.
Here is the code to calculate the transaction nonce for raw transactions in Ethereum’s geth client which includes the total transactions in pool too.
web3.eth.getTransactionCount(address, function(error, result) {
var txnsCount = result;
web3.currentProvider.sendAsync({
method: "txpool_content",
params: [],
jsonrpc: "2.0",
id: new Date().getTime()
}, function(error, result) {
if (result.result.pending) {
if (result.result.pending[address]) {
txnsCount = txnsCount +
Object.keys(result.result.pending[address]).length;
callback(null, txnsCount);
} else {
callback(null, txnsCount);
}
} else {
callback(null, txnsCount);
}
})
})
}
Make sure you have tx_pool
API enabled.