Fetching Token Balance
The getTokenBalance
method retrieves the balance of a token associated with the current wallet address. It interacts with the blockchain to fetch the balance and returns it in a structured format.
Before proceeding, users need to follow these steps:
- Pass WalletClient instance: Refer to the
Pass WalletClient Instance
for selecting the appropriatewalletClient
instance based on authentication.
Usage
import kohin from "./kohinInstance";
const tokenBalance = await kohin.getTokenBalance({
walletClient: walletClient, // Refer to Pass WalletClient Instance section for appropriate usage
});
if (tokenBalance.success) {
console.log("Token Balance:", tokenBalance.balance);
} else {
console.error("Error fetching token balance:", tokenBalance.error);
}
Return Value
The getTokenBalance
method returns an object with the following structure:
{
success: boolean; // Indicates if the operation was successful
error?: string; // Error message if the operation failed
balance?: bigint; // The balance of the token
}
Error Handling
The following example demonstrates how to handle errors during the token balance fetching process:
try {
const res = await kohin.getTokenBalance({ walletClient: walletClient });
if (res.success) {
console.log("Token Balance:", res.balance);
} else {
console.error("Error fetching token balance:", res.error);
}
} catch (error: any) {
console.error("Unexpected error while fetching token balance:", error);
}
Example Response
Success Response:
{
"success": true,
"balance": 99999999969684914122n
}
Error Response:
{
"success": false,
"error": "Unable to fetch balance for the given address."
}