1. Home
  2. Docs
  3. APIs
  4. How to obtain the total token supply using web3.js?

How to obtain the total token supply using web3.js?

To obtain the total token supply using web3.js, you need to access the totalSupply() function of the token smart contract. Here’s a simple example code to retrieve the total token supply:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Import the web3.js library
const { Web3 } = require('web3');

// Connect to an Ethereum node
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Token contract address and ABI
const tokenAddress = '0xYourTokenContractAddress'; // Replace with your token smart contract address
const tokenABI = [...]; // Replace with your token smart contract ABI

// Create a token contract instance
const tokenContract = new web3.eth.Contract(tokenABI, tokenAddress);

// Get the total token supply
tokenContract.methods.totalSupply().call()
.then((totalSupply) => {
console.log(Total token supply: ${totalSupply});
})
.catch((error) => {
console.error(Error fetching total token supply: ${error});
});

Please make sure to replace the following in the example code:
  • ‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’: Replace with the node URL from your Ethereum node provider.
  • ‘0xYourTokenContractAddress’: Replace with the actual address of your token smart contract.
  • tokenABI: Replace with the ABI of your token smart contract.

Executing this code will connect to the Ethereum network, create an instance of the token contract, and then call the totalSupply() function to retrieve the total token supply. Finally, it will print the total supply to the console.
Tags