Java Web3j nonce acquisition

Web3j obtains the reference code of nonce

public static BigInteger getNonce(Web3j web3j, String address) {
    try {
        EthGetTransactionCount nonceObject = web3j.ethGetTransactionCount(address, DefaultBlockParameterName.PENDING).send();
        if (nonceObject == null){
            throw new RuntimeException("net error");
        }
        return nonceObject.getTransactionCount();
    } catch (IOException e) {
        throw new RuntimeException("net error");
    }
}

When obtaining an address nonce value, one of the parameters is DefaultBlockParameter. The above code uses the DefaultBlockParameterName class, which has 3 values, respectively:

EARLIEST("earliest")

LATEST("latest")

PENDING("pending")

earliest: genesis block

latest: the latest block (the top block of the blockchain)

pending: the block being mined (including pending transactions)

Example:Suppose the nonce of the last packaged Transaction of address is 100

earliest always returns: 0

latest always returns: The nonce of the last packed Transaction, + 1, that is, 101

pending: If there is no pending Transaction at address, 101 will be returned; if there is 1 pending Transaction, 102 will be returned; if there are 2 pending Transactions, Then return 103

It is worth noting that if the pending method is used to obtain the nonce, then if the Transaction before the address is stuck due to a low Gas Price, all subsequent transactions in the wallet will be stuck, even if the Gas Price of the subsequent transactions is high enough. . Until the transaction represented by the previous lower nonce is packaged, subsequent transactions will not be packaged.

If the latest method is used to obtain the nonce, multiple transactions may obtain the same nonce. Once one of them succeeds, all other transactions using the same nonce will fail.

Guess you like

Origin blog.csdn.net/qq_36263544/article/details/128482389