Check Token Balances
Check Token Balances
Learn how to retrieve the balance of SOL or SPL tokens for any wallet using the BalanceFetcher class. This guide walks you through the process of fetching balances with ease.
Overview
The BalanceFetcher
class is designed to:
Fetch the native SOL balance of a wallet.
Retrieve the balance of SPL tokens linked to a specified token mint address.
Handle errors gracefully, ensuring reliable balance checks.
Code Explanation
1. Fetching SOL Balance
When no token address is provided, the method retrieves the native SOL balance of the wallet. The balance is returned in SOL (UI units).
Copy
2. Fetching SPL Token Balance
If a token mint address is specified, the method queries the balance of the associated SPL token account.
Copy
3. Error Handling
The method ensures any issues, such as network errors or invalid token accounts, are caught and raised with meaningful error messages.
Copy
Key Features
Dual Balance Retrieval
Fetch native SOL balances directly.
Retrieve SPL token balances with precision, accounting for token decimals.
Error Resilience Handles unexpected issues like missing accounts or network failures gracefully.
Simplified Usage A single method call to fetch balances for any supported token type.
How to Use
Setup: Import the
BalanceFetcher
class and initialize aSolanaAgentKit
with your wallet.Fetching SOL Balance Example:
Copy
Fetching SPL Token Balance Example:
Copy
Error Scenarios
Missing Token Account: If the specified token account does not exist, the method will return
None
.Network Errors: Ensure the RPC connection is active and functional.
Invalid Token Address: Double-check the token mint address for accuracy.
Last updated