Skip to main content

Balance Of User

To check the token balance in your account or view the balance of a specific user, use the balanceOf method provided by the edeXa ERC20 API. This method requires the user's userId to retrieve their balance.


Prerequisites

  • Authenticate the client using the edeXa SDK. For authentication details, see the authentication method.
  • Ensure that the user whose balance you want to retrieve is already enrolled. See enroll users for details on enrolling users.

Sample Code Snippet

Here is a JavaScript code snippet demonstrating the use of the balanceOf method:

// SDK.js
import { ERC20, Network } from 'edeXa-sdk';

async function balanceOf() {
const erc20 = new ERC20({
...settings,
authorization: `Bearer ${token}`,
});

const settings = {
network: Network.SANDBOX, // or Network.MAINNET for the mainnet network
};

const dataToGetBalance = {
userId(optional): 'Enter the username of the user for whom you want to retrieve the balance.',
chaincode(optional): 'The name of the smart contract or chaincode managing the tokens',
channel(optional): 'The name of the channel in the blockchain network'
}

try {
const balanceOfResponse = await erc20.balanceOf(dataToGetBalance);
// Handle success
} catch (error) {
// Handle error
}
}

Important Notes

  • Authentication Token: Replace the token in the authorization header with your actual authentication token.
  • Asynchronous Execution: The balanceOf function is an async function, using await for the erc20.balanceOf method's promise to resolve. The balance will be logged on successful resolution. Errors are caught and logged with console.error.
  • Transfer Tokens First: Make sure that tokens are transferred to the user before attempting to fetch their balance.
  • User Identification: Input the user's username in the userId field. This username can be obtained from the response of account Id.

Request Parameters

The dataToGetBalance object contains the following parameters for the balanceOf method:

ParameterRequiredTypeDescriptionDefault
userIdOptionalStringEnter the username of the user for whom you want to retrieve the balance.Admin's balance
chaincodeOptionalStringThe name of the smart contract or chaincode managing the tokens.Default chaincode
channelOptionalStringThe name of the channel in the blockchain network.Default channel
  • If userId is not provided, the balance for the admin will be fetched by default.
  • If chaincode and channel are not provided, the default chaincode and channel will be used. If provided, they will be used to fetch the respective balance.

Response Format

The response for a successful balance inquiry includes the following attribute:

KeyTypeDescription
balancenumberThe balance of the user's tokens