1

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

1 Answer 1

2

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.

2
  • Thank you @david, it works as my expectation. Just one question - is the hash itself in the unit of wei?
    – Neo Liu
    Commented Dec 8, 2022 at 22:48
  • use your code as example, the value 0x3b9aca000 is not a hash. It is a hexadecimal number that represents the gas price of a transaction on the Ethereum blockchain. Gas original value is typically specified in Wei, the smallest unit of Ether, but now in your showed code it was encoded in hexadecimal format for convenience.
    – david fnck
    Commented Dec 9, 2022 at 0:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.