我正在使用web3j查询以太坊区块链。现在我想检查交易是被挖掘还是刚刚发送到网络。我怎样才能做到这一点?
您可以考虑使用 web3.eth.getTransactionReceipt(hash [, callback])
.
如果事务成功,它将返回挂起事务的null
和对象。
/**
* 通过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";
}
如前所述,您可以使用web3.eth.getTransactionReceipt(hash [, callback])
它将返回带有状态的对象。对于不成功的交易,这将是错误的。
使用
org.web3j.protocol.core.Ethereum ethGetTransactionReceipt 函数使用哈希获取状态
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;
}