2

I'm fetching transactions from Etherscan like this:

https://api.etherscan.io/api?module=account&action=txlist&address=${address}&page=1&offset=${count}&startBlock=${startBlock}&endblock=${endBlock}&sort=asc&apikey=${apiKey}

This gives me transactions that have a hex encoded input field. Using ethers.js (ideally) how do I parse this?

What I'm trying to do is to determine the method that's shown on Etherscan, e.g. https://etherscan.io/token/0x111111111117dc0aa78b770fa6a738034120c302 (claim, transfer etc). And just inspecting the data in general. I tried:

const provider = new ethers.providers.JsonRpcProvider(
  "https://mainnet.infura.io/v3/..."
)

async function fetchInterface() {
  const contractAddress = "..."
  const contract = new ethers.Contract(contractAddress, [], provider)
  const interf = await contract.interface
  // console.log(interf)
  return interf
}

const logTxInput = (tx: Tx, interf: Interface) => {
  const input = tx.input
  console.log("!! tx input: ", input)

  // error: no matching function
  const parsedTx = interf.parseTransaction({ data: tx.input, value: tx.value })

  // error: no matching function
  const decodedArgs = interf.decodeFunctionData(input.slice(0, 10), input)
}

ethers.js version: `5.7.0`

1 Answer 1

1

Different contract interactions have different data, each contract determine the way it will receive parameters, and some contracts wich call others contracts may receive parameters from others contracts in its call.

For that reason there is not a unified way to parse the data field, here one can see how to decode data from Uniswap V3 router, and here how to decode data from Uniswap Universal Router.

Suposing you are tryng to parse data from an ERC20 contract, and using de abi-decode library, try the following code:

import { ethers } from "ethers";
const abiDecoder = require('abi-decoder');
import * as fs from 'fs';


const provider = new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/<key>");

async function main() {
    const tx = await provider.getTransaction("0xc472d42f3b8ad5d63a4c22265be8c4b3856eca5c9c0b9c3c11fd65e22f6f53f1");

    const ERC20ABI = JSON.parse(fs.readFileSync('<path>/tokenERC20.abi', "utf8"));
    abiDecoder.addABI(ERC20ABI);

    const decoded = abiDecoder.decodeMethod(tx.data);
    console.log(decoded);
}

main();

The output is:

{
  name: 'transfer',
  params: [
    {
      name: 'dst',
      value: '0x1f24fe56e3b3ac01793b576ba60b3f5d7bede877',
      type: 'address'
    },
    { name: 'wad', value: '1030696940600000000000', type: 'uint256' }
  ]
}

Your Answer

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

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