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?
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?
To do this using web3.js:
web3
: Have a web3 instance initialised and connected to a web3 providerabiOfToken
: 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 tokensaddressOfToken
: The deployed smart contract address for the tokenOnce 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 };
}