Web3JS – Best Way to Decode Transaction Input on Client Side

decodingjavascripttransactionsweb3js

I need to decode transaction input on the client side. Libraries like ethereum-input-data-decoder needs NodeJS dependencies like fs.

Now I decode the one type of contract methods as follows:

const getERC20TransferByHash = async (hash) => {
  const tx = await web3.eth.getTransaction(hash)
  if (
    tx !== null &&
    (tx.input.length === 138 || tx.input.slice(2, 10) === 'a9059cbb')
  ) {
    const receiver = web3.utils.toChecksumAddress('0x' + tx.input.slice(34, 74))
    const amount = web3.utils.toBN('0x' + tx.input.slice(74))
    const contractAddress = tx.to
    const sender = web3.utils.toChecksumAddress(tx.from)
    return { receiver, amount, contractAddress, hash, sender }
  }
  return {}
}

Decoding by web3.utils.toAscii(transaction.input) also don't work.

Is there a single way to make it easy?

Best Answer

Can you try decodeParameters? Like:

const erc20TransferABI = [{
        type: "address",
        name: "receiver"
    },{
        type: "uint256",
        name: "amount"
    }];
const decoded = web3.eth.abi.decodeParameters(
    erc20TransferABI,
    tx.input.slice(10)); // Or (11), not sure

Even perhaps, take erc20TransferABI from the ABI file itself.