How to Get Ethereum Transaction Details From Transaction Hash

Posted By : Dharmendra Kumar | 25-Jun-2018

Transaction hash is a unique identifier of a transaction that happens on the blockchain. It looks like a random combination of numbers and letters.
We can fetch details of every transaction using this unique id like to address, from address, amount, transaction fees.

Sometimes we need to fetch all these details in our project. To do this we have to follow some easy steps.

Step 1: Create a controller to receive a request. This controller would receive a  GET request and the ethereum transaction hash would be sent in the request parameter as a string.

 

           @ApiOperation(value = "to get ethereum transaction details ", response = ResponseEntity.class)
	@RequestMapping(value = "transaction/details", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<Object> transactionDetails(
			@RequestParam String transactionHash)  {
		
		Map<String, Object> response = ethService.getTransactionDetails(transactionHash);

		return ResponseUtil.response(response, MessageUtility.getSuccessMessage("completed"));

	}

 

Step 2: Create a service for above controller. In the service we first create the object of Web3j .we can create the object of Web3j either by using staging IP or testnet URL obtained from Rinkeby or Ropsten.

 

public Map<String, Object> getTransactionDetails(String transactionHash) {

		Map<String, Object> response = new HashMap<>();

                //by Using Staging Ip
		Web3j web3j = Web3j.build(new HttpService(envConfiguration.getEthereumServerUrl()));

                //by Using Staging testenet url of Rinkeby
               // Web3j web3j = Web3j.build(new HttpService("https://rinkeby.infura.io/YwwZGWFnGwJJVU98ky0Vaf"));

		EthTransaction details = null;

		try {
			details = web3j.ethGetTransactionByHash(transactionHash.trim()).send();
		} catch (IOException | NullPointerException e) {
			response.put("transactionDetails",null);
			LOGGER.info("" + e);
		return response;
		}

              if(details!=null)
		response.put("transactionDetails", details.getResult());
		return response;
	}

 

In the service, we are calling ethGetTransactionByHash() method of the Web3j class. This method returns an object of EthTransaction class. If the transaction hash is not valid then getResult() method on EthTransaction class object would return null otherwise it would return an object of Transaction class.

We can fetch the details like to address, from address, amount,  transaction fee from the object of Transaction class by calling appropriate methods.

 

About Author

Author Image
Dharmendra Kumar

Dharmendra is skilled in Java, Spring MVC, JPA, MySQL, and C.He has Bachelor's degree focussed in Computer Science and Engineering.

Request for Proposal

Name is required

Comment is required

Sending message..