Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get token transaction list by address using web3 js

Tags:

web3js

web3

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. So please help me how can I get token transaction list

like image 553
Ramila Ambaliya Avatar asked Feb 22 '18 10:02

Ramila Ambaliya


1 Answers

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.

like image 126
slowdownitsfine Avatar answered Oct 22 '22 10:10

slowdownitsfine