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?
Web3j how to get transaction status
Asked Answered
try this: boolean sent = web3j.ethGetTransactionByHash(transactionReceipt.getTransactionHash()).send().getTransaction().isPresent(); log.info("sent: {}", sent); –
Levulose
You can consider using web3.eth.getTransactionReceipt(hash [, callback])
.
It will return null
for pending transactions and an object if the transaction is successful.
web3j v.s. web3. –
Levulose
ethereum.stackexchange.com/questions/127298/… –
Bulldozer
/**
* 通过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";
}
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
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.
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;
}
© 2022 - 2024 — McMap. All rights reserved.