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

response = await agent.connection.get_balance(agent.wallet_address, commitment=Confirmed)  
return response.value / LAMPORTS_PER_SOL  

2. Fetching SPL Token Balance

If a token mint address is specified, the method queries the balance of the associated SPL token account.

Copy

response = await agent.connection.get_token_account_balance(token_address, commitment=Confirmed)  
return float(response.value.ui_amount)  

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

except Exception as error:  
    raise Exception(f"Failed to get balance: {str(error)}") from error  

Key Features

  1. Dual Balance Retrieval

    • Fetch native SOL balances directly.

    • Retrieve SPL token balances with precision, accounting for token decimals.

  2. Error Resilience Handles unexpected issues like missing accounts or network failures gracefully.

  3. Simplified Usage A single method call to fetch balances for any supported token type.


How to Use

  • Setup: Import the BalanceFetcher class and initialize a SolanaAgentKit with your wallet.

  • Fetching SOL Balance Example:

    Copy

    balance = await BalanceFetcher.get_balance(agent)  
    print(f"SOL Balance: {balance} SOL")  
  • Fetching SPL Token Balance Example:

    Copy

    token_address = Pubkey("Your SPL Token Mint Address Here")  
    balance = await BalanceFetcher.get_balance(agent, token_address)  
    print(f"SPL Token Balance: {balance}")  

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