Checking Token Balance with the ERC1155 API
This guide explains how to use the getBalance
method to inquire about the token balance in your account or to view the balance of a specific user with the ERC1155 API.
Overview of the getBalance
Method
The getBalance
method is essential for tracking the token holdings within your blockchain application, whether for your own account or for other users. It provides the flexibility to check balances for any user by their userId and for specific tokens by their tokenId.
Prerequisites
- Installed the
edeXa-sdk
in your project. - An authentication token obtained through the SDK's authentication method. This token is necessary to authorize your requests.
Sample Code Snippet
Here is a JavaScript code snippet demonstrating the use of the getBalance
method:
import { ERC1155, Network } from 'edeXa-sdk';
async function getBalance() {
const settings = {
network: Network.SANDBOX, // Use Network.MAINNET for production environments
};
const erc1155 = new ERC1155({
...settings,
authorization: `Bearer ${token}`, // Replace `${token}` with your actual token
});
// Data required to check the balance
const dataToGetBalance = {
userId: 'usernameOfUser', // Optional: Username of the user
tokenId: 'tokenIdOfToken', // Optional: TokenId for specific token balance
chaincode: 'optionalChaincodeName', // Optional: Chaincode name
channel: 'optionalChannelName', // Optional: Blockchain channel
};
try {
const balanceOfResponse = await erc1155.getBalance(dataToGetBalance);
// Handle success
} catch (error) {
// Handle error
}
}
Request Parameters
All parameters for the getBalance
method are optional, providing flexibility in how you query balances:
Parameter | Type | Required | Description |
---|---|---|---|
userId | String | No | The username of the user for whom to retrieve the balance. |
tokenId | String | No | The tokenId of the token for which to get the specific balance. |
chaincode | String | No | The name of the smart contract or chaincode managing the tokens. |
channel | String | No | The name of the blockchain channel. |
Response Format
Upon successfully querying the balance, the getBalance
method returns a response object containing:
Key | Type | Description |
---|---|---|
balance | number | The number representing the token balance. |