8

I am using web3.js. I want token transaction list (Not transaction List) by address. I already used the getBlock function but its only for particular block. I have no block list and I want the list by address only.

How can I get the token transaction list?

TylerH
  • 20,799
  • 66
  • 75
  • 101

1 Answers1

12

I've implemented this with the web3-eth and web3-utils 1.0 betas using getPastEvents.

The standardAbi for ERC20 tokens I retrieved from this repo

import Eth from "web3-eth";
import Utils from "web3-utils";

async function getERC20TransactionsByAddress({
  tokenContractAddress,
  tokenDecimals,
  address,
  fromBlock
}) {
  // initialize the ethereum client
  const eth = new Eth(
    Eth.givenProvider || "ws://some.local-or-remote.node:8546"
  );

  const currentBlockNumber = await eth.getBlockNumber();
  // if no block to start looking from is provided, look at tx from the last day
  // 86400s in a day / eth block time 10s ~ 8640 blocks a day
  if (!fromBlock) fromBlock = currentBlockNumber - 8640;

  const contract = new eth.Contract(standardAbi, tokenContractAddress);
  const transferEvents = await contract.getPastEvents("Transfer", {
    fromBlock,
    filter: {
      isError: 0,
      txreceipt_status: 1
    },
    topics: [
      Utils.sha3("Transfer(address,address,uint256)"),
      null,
      Utils.padLeft(address, 64)
    ]
  });

  return transferEvents
    .sort((evOne, evTwo) => evOne.blockNumber - evTwo.blockNumber)
    .map(({ blockNumber, transactionHash, returnValues }) => {
      return {
        transactionHash,
        confirmations: currentBlockNumber - blockNumber,
        amount: returnValues._value * Math.pow(10, -tokenDecimals)
      };
    });
}

I haven't tested this code as it is slightly modified from the one I have and it can definitely be optimized, but I hope it helps.

I’m filtering by topics affecting the Transfer event, targeting the address supplied in the params.

  • While this code works properly, it's very slow in case you want to list transactions older than a few months (~15 seconds for the last year/~2M blocks). I guess that's given by how Ethereum works, but still, you may want to use a 3rd party service that does this efficiently. – blade Nov 15 '18 at 16:19
  • Good answer for me. If you use typescript you will need https://ethereum.stackexchange.com/questions/94601/trouble-with-web3-eth-contract-abi-usage-with-typescript – benek Sep 23 '22 at 16:02