Solidity – How to Read a Transaction in Human-Readable Format Using Web3

etherjsetherscango-ethereumsolidityweb3js

I am using Alchemy API as my web3 provider and got a transaction data like this below:

{
  blockHash: null,
  blockNumber: null,
  from: '0xa12e1462d0ced572f396f58b6e2d03894cd7c8a4',
  gas: '0x440f0',
  gasPrice: '0x3b9aca000',
  hash: '0x4e4d44a84404dbaff0d96357729d732a204a4b4e924bb1cccd1173018e33e229',
  input: '0x7ff36ab500000000000000000000000000000000000000000000000001c95a8b7d8bf0e2000000000000000000000000000000000000000000000000000000000000008000000000000000000000000048c04ed5691981c42154c6167398f95e8f38a7ff000000000000000000000000000000000000000000000000000000006391cc960000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000007db5af2b9624e1b3b4bb69d6debd9ad1016a58ac',
  nonce: '0x1dc3',
  to: '0x7a250d5630b4cf539739df2c5dacb4c659f2488d',
  transactionIndex: null,
  value: '0x20db9bccc4e8cb1',
  type: '0x0',
  chainId: '0x1',
  v: '0x25',
  r: '0x461d8ff7fa9920577a428a6433e4a6f7a6dbfb6678952ee26638e8e2ad3fa6a3',
  s: '0x35bdf93cffe336c178a81432f9adc4f40ff1eeb665673cc027f494f726ae1308'
}

I would like to know how to convert gas and value from a hash (e.g. 0x3b9aca000) to Gwei or ether.

Like in etherscan, this transaction's details are in a human readable format. I would like to know how to achieve it in API
https://etherscan.io/tx/0x4e4d44a84404dbaff0d96357729d732a204a4b4e924bb1cccd1173018e33e229
enter image description here

Best Answer

it's not difficult. try this.

To convert the gas and value fields from a hash to Gwei or Ether, you can use the web3.utils.fromWei() method provided by the Web3 library. This method takes the value in Wei (the smallest unit of Ether) and converts it to the specified unit. For example, to convert the gasPrice value from the transaction data you provided to Gwei, you could use the following code:

const gasPriceInGwei = web3.utils.fromWei(transactionData.gasPrice, 'gwei');

Similarly, to convert the value field to Ether, you can use the following code:

const valueInEther = web3.utils.fromWei(transactionData.value, 'ether');

You can then use the gasPriceInGwei and valueInEther variables to display the values in a human-readable format in your application.

Related Topic