TRC20 Check Balance: How to Get TRC20 Token Balance?

In this guide, we’ll discuss the methods, tips, and tools you need to successfully retrieve TRC20 token balance. We’ll also provide you with an explanation of how to access a TRON node with ease with the node provider NOWNodes.

TRC20 tokens are a type of digital asset that exists on the TRON blockchain, functioning similarly to how ERC20 tokens work on the Ethereum blockchain. Essentially, TRC20 is a standard that sets a common set of rules and guidelines for issuing tokens on the TRON network. 

If you aim to retrieve the balance of a TRC20 token, you should understand the methods first.

TRC-20 Check Balance Methods

Retrieving the balance of a TRC-20 token involves querying specific information from a smart contract deployed on the TRON mainnet network. In this section, we’ll explore three common methods to get the TRC-20 token balance: TronWeb library, Web3.js library (optional), and direct API calls.

Using TronWeb Library

TronWeb is a JavaScript library specifically designed for TRON. It comes with native support for a TRC-20 token and simplifies the process of interacting with smart contracts. TronWeb library allows you to call the `balanceOf` method of the TRC-20 token contract to get the TRC-20 token balance. The advantage of using TronWeb is its deep integration with TRON-specific features.

Using Web3.js Library (Optional)

Web3.js library provides the necessary tools for interacting with Ethereum-compatible blockchains, such as TRON. With the Web3.js library, you can connect a TRON node provider, instantiate the TRC-20 token’s smart contract using its ABI and address, and then call the `balanceOf` method to fetch the token balance of a specific address.

Using Direct API Calls

For those who prefer a non-programmatic approach, retrieving a TRC-20 token balance can be done by sending a direct HTTP POST request to a TRON RPC URL. Both cURL and Postman can be used for this purpose. Essentially, you send a payload specifying the smart contract’s address, the function you wish to call (`balanceOf`), and the address whose balance you want to check. The API endpoint then returns the balance in response.

These methods offer different levels of abstraction and control, and the best choice will depend on your specific requirements and the environment in which you’re working. Whether you’re building a full-fledged decentralized application or simply looking to query some quick information, one of these methods of getting a TRC-20 token balance is likely to suit your needs.

Now, let’s explore how to retrieve the balance of a TRC-20 token and connect to the TRX node for the success of this process.

Get TRC20 Token Balance

To retrieve the balance of a TRC20 token on the TRON blockchain, you have to access the TRX node. Among the numerous blockchains available today, the TRON mainnet network is one that stands out for its high throughput, scalability, and low transaction costs. However, running a TRON full node can be cumbersome and expensive. This is where the TRON node provider NOWNodes comes into the picture.

Access a TRON Node Provider to Check TRC20 Balance

NOWNodes is a service that provides access to 100+ blockchains, including the TRON mainnet network, eliminating the need to run and maintain a TRX node yourself. Moreover, the RPC node provider offers access to the TRON block explorer. So the TRON node provider is a highly recommended solution if you’re developing an application that interacts with the TRON mainnet network and you don’t want to maintain your own infrastructure. 

With API keys and comprehensive documentation, developers can easily integrate a TRON full node into their applications. Here’s a simple guide to get you started:

1. Visit NOWNodes (https://nownodes.io/) and sign up for a free or paid account, depending on your needs. Notice that you can access 5 blockchains through one API key on a free plan. With a paid plan you can access all the available blockchains, Websocket connections, raised number of requests, etc. 

2. Once you’ve signed up, you’ll have to add a new API key to your dashboard page. Find the TRON node ticker for the TRON full node and achieve all the available methods on the docs page.

NOWNodes provides a highly efficient and simple way to access a TRX node and TRON block explorer, offering numerous benefits ranging from cost-effectiveness to high availability. The TRON node provider offers a high-availability service with 99.95% uptime guarantees. This is crucial for applications that require uninterrupted access to the TRON mainnet access.

For developers, this service not only simplifies the process of interacting with the TRON mainnet network but also enables them to focus more on the core development activities, thereby accelerating the project lifecycle.

Whether you’re a startup or a seasoned developer, NOWNodes offers an unmatched level of convenience and reliability when it comes to accessing the TRON full node.

As soon as you have your TRON full node and TRON RPC URL, you can start exploring the ways to retrieve the balance of a TRC20 token. We are going to use the TronWeb library as the first TRC20 check balance method. 

Using TronWeb Library

Retrieving the balance of a TRC20 token is a common operation when dealing with the TRON mainnet network. This section guides you through the TRC20 check balance method such as TronWeb library. Moreover, we will use the TRON node provider NOWNodes.

Before checking your TRC20 token balance, make sure you have Node.js and npm installed. If not, you can download and install it from (https://nodejs.org/). Moreover, install the TronWeb library as it is the TRON-specific JavaScript library we’ll be using. As you meet all the prerequisites, you can follow the steps below.

Step 1: Install TronWeb Library

To install the TronWeb library, you can use npm. Open your terminal or command prompt and run the following command:

npm install tronweb

This command will download and install the TronWeb library into your project.

Step 2: Initialize TronWeb

Once installed, you can initialize the TronWeb library using the following code snippet. 

const TronWeb = require(‘tronweb’);


const tronWeb = new TronWeb(
    ‘https://trx.nownodes.io/,  // MainNet NOWNodes endpoint
‘https://trx.nownodes.io/, // 
    ‘https://trx.nownodes.io/, // Event server
    ‘YOUR_PRIVATE_API_KEY’
);

The code snippet provided demonstrates how to initialize TronWeb with the necessary parameters. Make sure to connect to the right TRON mainnet endpoint to replace ‘YOUR_PRIVATE_API_KEY’ with your actual private TRON API key.

Step 3: Specify the Token Contract and Account Address

In order to retrieve the balance of a specific token for a particular account, you need to specify the TRC20 token contract address and the account address.

const tokenContractAddress = ‘TRC20_CONTRACT_ADDRESS’;
const accountAddress = ‘ACCOUNT_ADDRESS’;

Replace ‘TRC20_CONTRACT_ADDRESS’ with the actual address of the token contract, and ‘ACCOUNT_ADDRESS’ with the desired account address.

Step 4: Retrieve Token Balance

To fetch the balance, you can interact with the contract’s `balanceOf` method. The contract ABI should contain the details of this method.

async function getTRC20TokenBalance() {
  try {
    const contract = await tronWeb.contract().at(tokenContractAddress);
    const balance = await contract.balanceOf(accountAddress).call();
    const normalizedBalance = tronWeb.fromSun(balance);
    console.log(`The TRC20 token balance is: ${normalizedBalance}`);
 } catch (error) {
    console.error(‘Error:’, error);
  }
}

getTRC20TokenBalance();

Here we’re using TronWeb’s `contract().at()` method to get the contract instance and then calling the `balanceOf` method of the TRC20 token contract. We’re also converting the balance from Sun to TRX for better readability using `tronWeb.fromSun()`.

And that’s it! You can now easily retrieve the balance of TRC20 tokens for any account using the TronWeb library and the TRON node provider as NOWNodes. With these steps, you can easily retrieve the balance of any TRC20 tokens on the TRON blockchain using TronWeb and NOWNodes. 

Using Web3.js Library (Less Common for TRON)

Although the Web3.js library is primarily designed for the Ethereum blockchain, you can still use it for some basic interactions with the TRON mainnet network due to similarities in their architecture. This guide explains how to retrieve the balance of a TRC20 token on the TRON mainnet using the Web3.js library and NOWNodes.

The prerequisites for the Web3.js library are similar. First of all, ensure that you have Node.js and npm installed on your computer. If not, download and install them from (https://nodejs.org/). Moreover, make sure you have a Web3.js library which we will use for TRON as well. With your TRON API key, TRC20 token contract address, and a TRON wallet address you can now explore the steps for this TRC20 check balance method. 

Step 1: Install Required Packages

Create a new directory for your project and initialize a Node.js project:

mkdir trc20-balance-checker
cd trc20-balance-checker
npm init -y

This will create a new directory called “trc20-balance-checker” and initialize a Node.js project inside it. 

Next, you need to install the Web3.js package, which is a library for interacting with the Ethereum blockchain. Run the following command in your terminal:

npm install web3

This will install the Web3.js package and its dependencies.

Step 2: Initialize Web3.js

Create a new file called `index.js`, and initialize Web3.js with your NOWNodes API key:

const Web3 = require(‘web3’);

const web3 = new Web3(new Web3.providers.HttpProvider(‘https://trx.nownodes.io/YOUR_NOWNODES_API_KEY’));

Replace `YOUR_NOWNODES_API_KEY` with the actual TRON API key.

Step 3: Define ABI and Contract Address

To interact with the smart contract of the TRC20 token, you need the ABI (Application Binary Interface) and the TRC20 token contract address.

const contractABI = […];  // Replace with your ABI array
const contractAddress = ‘Your_Token_Contract_Address’;

Replace “[…]” with the actual ABI array of your TRC20 token, and replace “Your_Token_Contract_Address” with the TRC20 token contract address.

Step 4: Retrieve TRC20 Token Balance

Create a function to retrieve the token balance.

async function getTRC20Balance() {
  const contract = new web3.eth.Contract(contractABI, contractAddress);
  const address = ‘Your_TRON_Address’;

  try {
    const balance = await contract.methods.balanceOf(address).call();
    console.log(`The balance is: ${balance}`);
  } catch (error) {
    console.log(`An error occurred: ${error}`);
  }
}

getTRC20Balance();

Replace `’Your_TRON_Address’` and `’Your_Token_Contract_Address’` with your TRON address and the TRC20 token contract address respectively. Update the `contractABI` with the actual ABI of your TRC20 token.

Step 5: Run Your Code

Finally, to execute your code, open your terminal and run the following command:

node index.js

This will run the “index.js” file and display the token balance of your TRC20 token on the console.

You’ve successfully retrieved the balance of a TRC20 token on the TRON network using the Web3.js library and the TRON node provider NOWNodes. To work directly with TRON and TRC20, always rely on tools built for TRON, such as TronWeb. Nonetheless, using the Web3.js library for this TRC20 check balance method highlights the interoperable potential of blockchain technology.

Using Direct API Calls with NOWNodes

Without doubt, he text below will guide you through retrieving a TRC20 token balance using direct API calls as the last TRC20 check balance method. Using a service like NOWNodes, this process can be simplified and streamlined. 

Important to realise that this method also requires some prerequisites such as the TRON API key, TRC20 token contract address, and TRON wallet address for which you want to retrieve the token balance. Explore Postman or a similar tool for making API requests, and knowledge of programming languages that can make HTTP requests (Python, JavaScript, etc.). Ensure you’re going to use the correct TRON RPC URL and follow the steps. 

Here’s how you can check the TRC20 token balance using NOWNodes:

Step 1: Make the API Call to Get the Balance

The API call will be an HTTP POST request and it will need to include the contract address, wallet address, and other necessary information in its payload.

Here’s a sample Python code using the `requests` library:

import requests  # Import the requests library to make HTTP requests
import json  # Import the JSON library to handle JSON data

Replace these placeholders with actual values:

api_key = “YOUR_NOWNODES_API_KEY”
contract_address = “TRC20_CONTRACT_ADDRESS”
wallet_address = “WALLET_ADDRESS”

Construct the URL for the API call:

url = f”https://trongrid.io/api/v1/contracts/{contract_address}/call”

Create the payload:

payload = {
    “function”: “balanceOf”,  # The smart contract function we’re calling
    “params”: [  # The parameters for the function call
        {
            “type”: “address”,  # The type of the parameter
            “value”: wallet_address  # The value of the parameter
        }
    ]
}

Create the headers for the request, which includes our NOWNodes API key for authorization:

headers = {
    “Authorization”: f”Bearer {api_key}”
}

Make the POST request:

response = requests.post(url, headers=headers, json=payload)

Check the HTTP status code:

if response.status_code == 200:
    # Parse the JSON response to a Python dictionary
    result = json.loads(response.text)
    # Convert the hexadecimal balance to an integer
    balance = int(result[‘data’][0][‘value’], 16)
    # Print the balance
    print(f”Balance: {balance}”)
else:
    # Handle any errors that occur
    print(f”Failed to get balance: {response.text}”)

Replace `YOUR_NOWNODES_API_KEY`, `TRC20_CONTRACT_ADDRESS`, and `WALLET_ADDRESS` with your TRON API key, the TRC20 token’s contract address, and the wallet address you are checking, respectively.

Step 2: Interpret the Result

The balance will be returned in the smallest unit of the token (similar to how wei is the smallest unit of Ethereum). You may need to convert this into the token’s standard unit.

You’ve successfully used direct API calls to retrieve the balance of a TRC20 token from the TRON mainnet using NOWNodes. This TRC20 check balance method is useful for quick look-ups and can be integrated into more complex applications or services as needed.

With NOWNodes as your TRON node provider, the process is made more straightforward by providing easy access to a TRX node, reducing the hassle of maintaining node infrastructure.

Conclusion

To summarise, understanding how to retrieve TRC20 token balances is a critical skill for anyone working with the TRON blockchain, and NOWNodes offers tools (such as connection to TRON full nodes, TRON block explorer and dedicated solutions) for making this process easier. Through the use of NOWNodes, you gain access to a convenient and straightforward API that lets you interact with the TRON full node without having to manage your infrastructure.

In this article, we’ve demonstrated the steps to fetch TRC20 token balances. Moreover, we’ve learned how easily you can access a TRON full node. You can also find a TRON block explorer endpoint to access more for your dApp development.  

By taking advantage of NOWNodes’ services, developers can bypass many of the challenges traditionally associated with blockchain interactions. This allows you to focus on what truly matters: building high-quality applications that provide value to your users.

Stay connected and don’t miss out on technical guides and exciting updates from the NOWNodes blog! Keep yourself up to date by following NOWNodes on Twitter and LinkedIn. Be a part of our Web3 community on our Telegram!

KEY POINTS:

There are three TRC20 check balance methods:

  • Utilizing TronWeb Library: Access the TRON full node through NOWNodes and get your TRON API key. Install the TronWeb library. Initialize TronWeb. Specify the TRC20 token contract address and account address. Retrieve token balance. 
  • Using Web3.js Library: Connect to the TRON node provider such as NOWNodes and generate a private API key. Install the Web3.js library. Initialize Web3.js. Define ABI and TRC20 token contract address. Retrieve TRC20 token balance. 
  • Direct API Calls: Connect to TRX nodes and create your private TRON API key with NOWNodes. Make the API call to get the balance. Parse the response.