乐闻世界logo
搜索文章和话题

How to read information from ethereum transaction using transactionHash in web3?

1个答案

1

To read information from an Ethereum transaction using transactionHash, follow these steps. This typically involves using Ethereum's JSON-RPC API or libraries such as Web3.js or Ethers.js to interact with the Ethereum blockchain.

Step 1: Set Up the Environment

First, install a suitable library to interact with the Ethereum network. For this example, I'll use Web3.js as it is one of the most widely adopted libraries in JavaScript environments.

bash
npm install web3

Step 2: Connect to an Ethereum Node

Connect to the Ethereum network using Infura or your own hosted node:

javascript
const Web3 = require('web3'); // Replace YOUR_INFURA_PROJECT_ID with your Infura project ID const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'));

Step 3: Read Transaction Information Using transactionHash

Retrieve detailed transaction information using its hash:

javascript
const txHash = '0x123abc...'; // Example hash; replace with a valid transaction hash web3.eth.getTransaction(txHash).then(tx => { console.log(tx); });

This outputs detailed transaction information, including the sender address, recipient address, amount sent, gas usage, gas price, and input data.

Example Output Explanation

The object returned by getTransaction typically includes:

  • from: The address initiating the transaction
  • to: The recipient address
  • value: The amount of Ether transferred, in wei
  • gas: The gas provided for the transaction
  • gasPrice: The price per unit of gas the user is willing to pay
  • nonce: The number of transactions sent by the sender
  • data: The transaction data; for smart contract calls, this contains call data

Additional Notes

To retrieve the transaction receipt (including execution status and total gas used), use:

javascript
web3.eth.getTransactionReceipt(txHash).then(receipt => { console.log(receipt); });

These steps demonstrate how to fetch transaction information via transactionHash in Web3. This is valuable for developers building DApps to verify transactions and debug.

2024年8月14日 22:10 回复

你的答案