0
  1. The problem

This is the code that I am working with. It's supposed to track my wallet balances on Solana, SOL and Memecoins/SPL tokens included. The code works only partially, it writes out my SOL balance, but then prints some error messages and stops working, I haven't been able to find a solution even with ChatGPT input.

The error message is the following: c:\Users\vhrom\Desktop\Coding vol.2# List of numbers to be sorted.py:35: DeprecationWarning: There is no current event loop loop = asyncio.get_event_loop() Error: expected a sequence of length 32 (got 43)

import asyncio
from solana.rpc.api import Client
from solders.pubkey import Pubkey
from solana.rpc.async_api import AsyncClient
from solana.rpc.types import TokenAccountOpts
from solana.rpc.commitment import Confirmed

# Define the wallet address directly in the code
wallet_address = "BdL79v8z3mTnNhVfQBmtzRvL1gyw7U1vPTuJ4LKN3hpT"

# Initialize the Solana client
solana_client = Client("https://api.mainnet-beta.solana.com")

async def get_token_accounts(wallet_pubkey):
    async with AsyncClient("https://api.mainnet-beta.solana.com") as client:
        resp = await client.get_token_accounts_by_owner_json_parsed(
            wallet_pubkey,
            TokenAccountOpts(program_id=Pubkey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")),
            commitment=Confirmed
        )
        return resp['result']['value']

def get_wallet_balance():
    try:
        # Convert the wallet address to a Pubkey object
        wallet_pubkey = Pubkey.from_string(wallet_address)

        # Get the balance of the wallet in SOL
        balance_info = solana_client.get_balance(wallet_pubkey)
        balance_lamports = balance_info.value  # Directly access 'value' attribute
        balance_sol = balance_lamports / 1e9  # Convert lamports to SOL
        print(f"The balance of wallet {wallet_address} is {balance_sol} SOL.")
        
        # Get token accounts
        loop = asyncio.get_event_loop()
        token_accounts = loop.run_until_complete(get_token_accounts(wallet_pubkey))
        for account in token_accounts:
            token_balance = account['account']['data']['parsed']['info']['tokenAmount']['uiAmount']
            token_mint = account['account']['data']['parsed']['info']['mint']
            print(f"Token: {token_mint}, Balance: {token_balance}")
        
    except Exception as e:
        print(f"Error: {e}")

def main():
    print("Welcome to the Solana Wallet Tracker!")
    # Get and print the balance of the specified wallet
    get_wallet_balance()
    print()

if __name__ == "__main__":
    main()

Thank you for any help I can get.

1 Answer 1

1

the first message "DeprecationWarning: There is no current event loop loop = asyncio.get_event_loop()" is a DeprecationWarning , which means that this function is deprecated, you can still work with that but is better to use:

token_accounts = asyncio.run(get_token_accounts(wallet_pubkey))

The second message "Error: expected a sequence of length 32 (got 43)", it's because you are passing in get_token_accounts_by_owner_json_parsed the program id as Pubkey from a string but you have to pass it as base58 decoded.

resp = await client.get_token_accounts_by_owner_json_parsed(
        wallet_pubkey,
        TokenAccountOpts(program_id=Pubkey(base58.b58decode('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'))),
        commitment=Confirmed
    )

The get_token_accounts_by_owner_json_parsed function return the result as "solders.rpc.responses.GetTokenAccountsByOwnerJsonParsedResp" that is not subscriptable so you have to turn it into json:

resp = resp.to_json()
resp_json = json.loads(resp)
return resp_json['result']['value']

This is the complete code:

import asyncio
from solana.rpc.api import Client
from solders.pubkey import Pubkey
from solana.rpc.async_api import AsyncClient
from solana.rpc.types import TokenAccountOpts
from solana.rpc.commitment import Confirmed
import base58
import json

# Define the wallet address directly in the code
wallet_address = "BdL79v8z3mTnNhVfQBmtzRvL1gyw7U1vPTuJ4LKN3hpT"

# Initialize the Solana client
solana_client = Client("https://api.mainnet-beta.solana.com")

async def get_token_accounts(wallet_pubkey):
    async with AsyncClient("https://api.mainnet-beta.solana.com") as client:
        resp = await client.get_token_accounts_by_owner_json_parsed(
            wallet_pubkey,
            TokenAccountOpts(program_id=Pubkey(base58.b58decode('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'))),
            commitment=Confirmed
        )
        resp = resp.to_json()
        resp_json = json.loads(resp)
        return resp_json['result']['value']

def get_wallet_balance():
    try:
        # Convert the wallet address to a Pubkey object
        wallet_pubkey = Pubkey.from_string(wallet_address)

        # Get the balance of the wallet in SOL
        balance_info = solana_client.get_balance(wallet_pubkey)
        balance_lamports = balance_info.value  # Directly access 'value' attribute
        balance_sol = balance_lamports / 1e9  # Convert lamports to SOL
        print(f"The balance of wallet {wallet_address} is {balance_sol} SOL.")
        
        # Get token accounts
        token_accounts = asyncio.run(get_token_accounts(wallet_pubkey))
        for account in token_accounts:
            token_balance = account['account']['data']['parsed']['info']['tokenAmount']['uiAmount']
            token_mint = account['account']['data']['parsed']['info']['mint']
            print(f"Token: {token_mint}, Balance: {token_balance}")
        
    except Exception as e:
        print(f"Error: {e}")

def main():
    print("Welcome to the Solana Wallet Tracker!")
    # Get and print the balance of the specified wallet
    get_wallet_balance()
    print()

if __name__ == "__main__":
    main()

This code work for me, let me know if u have any question.

2
  • yeah that works awesome dude thanks
    – Proowy
    Commented Oct 28 at 16:39
  • Please accept the answer if it worked for you, that way others can find it in the future!
    – Jon C
    Commented Nov 1 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.