5

I would like to query several ERC20 tokens on the RSK network to obtain the following fields: symbol, name, and decimals.

How can I do this using web3.js?

bguiz
  • 27,371
  • 47
  • 154
  • 243
Milton
  • 161
  • 1
  • 4

1 Answers1

7

To do this using web3.js:

  • web3: Have a web3 instance initialised and connected to a web3 provider
  • abiOfToken: The ABI object for this particular token. Note that if you do not have this, you can obtain it by running solc against the original contract code; or alternatively you can simply use a "standard" ABI object for ERC-20 tokens
  • addressOfToken: The deployed smart contract address for the token

Once you have the above, you can do the following within an async function:

  const tokenContract = new web3.eth.Contract(
    abiOfToken, addressOfToken);
  const symbol = await tokenContract.methods.symbol().call();
  const decimals = await tokenContract.methods.decimals().call();
  const name = await tkenContract.methods.name().call();

The above code runs them in sequence, and provided for clarity. In practice, since you are running this for multiple tokens, you may want to consider running the queries in parallel, and extracting them to a separate function, like so:

  // run this just once, as part of initialisation
  const tokenContract = new web3.eth.Contract(abiOfToken, addressOfToken);

  // run this multiple times by putting in its own function
  async function getTokenInfo(tokenContract) {
    const [decimals, name, symbol] = await Promise.all([
      tokenContract.methods.symbol().call(),
      tokenContract.methods.decimals().call(),
      tokenContract.methods.name().call(),
    ]);
    return { decimals, name, symbol };
  }
bguiz
  • 27,371
  • 47
  • 154
  • 243
  • I followed your instructions, provided the API, and got "TypeError: tokenContract.methods.symbol is not a function" – Eli O. Oct 23 '21 at 07:38
  • 1
    For others encountering the problem : I was using the IERC20 ABI, not the ERC20 ABI, this was the source of the problem, now it works right, try to double check your ABI, here is a source foe the ERC20 ABI I used : https://ethereumdev.io/abi-for-erc20-contract-on-ethereum/ (if someone knows a more official source, it might be best to add it here) – Eli O. Oct 23 '21 at 07:47
  • 1
    @JayD. you can use "standard" ABIs for the contract standard that you are working with ... however if this does not work, I'd recommend that you "obtain it by running solc against the original contract code" as mentioned above, and then either using that directly, or using that to figure out what is missing. – bguiz Oct 23 '21 at 12:42