Web3j how to get transaction status
Asked Answered
O

4

9

I am using web3j to query the Ethereum blockchain. Now I want to check if a transaction was mined or just sent to the network. How can I achieve this?

Obbard answered 17/4, 2018 at 19:50 Comment(1)
try this: boolean sent = web3j.ethGetTransactionByHash(transactionReceipt.getTransactionHash()).send().getTransaction().isPresent(); log.info("sent: {}", sent);Levulose
D
14

You can consider using web3.eth.getTransactionReceipt(hash [, callback]).

It will return null for pending transactions and an object if the transaction is successful.

Daffy answered 17/4, 2018 at 20:9 Comment(2)
web3j v.s. web3.Levulose
ethereum.stackexchange.com/questions/127298/…Bulldozer
H
1
/**
 * 通过hash查询交易状态,处理状态。成功success,失败fail,未知unknown
 * @param hash
 * @return
 */
public String txStatus(String hash){
    if(StringUtils.isBlank(hash)) {
        return STATUS_TX_UNKNOWN;
    }
    try {
        EthGetTransactionReceipt resp = web3j.ethGetTransactionReceipt(hash).send();
        if(resp.getTransactionReceipt().isPresent()) {
            TransactionReceipt receipt = resp.getTransactionReceipt().get();
            String status = StringUtils.equals(receipt.getStatus(), "0x1") ?
                    "success" : "fail";
            return status;
        }
    }catch (Exception e){
        log.info("txStatusFail {}", e.getMessage(), e);
    }
    return "hash_unknown";
}
Handkerchief answered 24/5, 2022 at 16:21 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Chromato
T
0

As mentioned before, you can use web3.eth.getTransactionReceipt(hash [, callback]) It will return the object with status. It will be false for unsuccessful transactions.

Tricostate answered 18/5, 2022 at 10:0 Comment(0)
L
0

Use org.web3j.protocol.core.Ethereum ethGetTransactionReceipt function to get status using hash

public Boolean getTransactionStatus(Web3j web3j, String transactionHash) throws Exception{
                    
        Optional<TransactionReceipt> receipt = null;
        Boolean status=null;
                    
        try{ 
            receipt = web3j.ethGetTransactionReceipt(transactionHash).send().getTransactionReceipt();
            if(receipt.isPresent())
               status = receipt.get().isStatusOk();      
         }catch(IOException e){
            throw new Exception(e);
         }
         return status;
}
Lallage answered 15/10, 2022 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.