3

How can I get the status of a transaction through the TxHash with web3j.

I tried it like this:

public int getEstado(String trx) {
    try {
        JSONObject json = readJsonFromUrl("https://api.infura.io/v1/jsonrpc/rinkeby/eth_getTransactionReceipt?params=[\"" + trx + "\"]");

        if (json.toString().contains("error")) {
            return -4;
        }

        String result = Parser.getMessageByKey(json.toString(), "status");
        int estado = Integer.decode(result);
        json = null;
        result = null;
        return estado;

    } catch (Exception ex) {
        return -4;
    }
}

In the end this did not work, so I wanted to know if you can guide me in another way to get the status of txHash.

2 Answers 2

5

There's the Transactions page in the Web3j docs that mentions transaction receipts a few times, and I browsed through some of the autocompletes in IntelliJ. It looks like you can do the following, provided you have the transaction hash:

Optional<TransactionReceipt> transactionReceipt = 
    web3j.ethGetTransactionReceipt(txHash).send().getTransactionReceipt();

Then you can check whether the optional holds a value and retrieve the transaction receipt. I haven't tested this, but I don't see why it shouldn't work. Let me know if it helps.

2
0

one question. How do you handle the case when the value of the optional is not present. Do you do a Thread.sleep in a loop and check if the value is present with the .isPresent method? this does not feel as a correct way to handle async code.

Pseudo code:

for(;;) {
  if (transactionReceipt.getTransactionReceipt.isPresent()) {
    return transactionReceipt.get().getContractAddress();
  } else {
    Thread.sleep(3)
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.