michaelhly / solana-py

Solana Python SDK
https://michaelhly.github.io/solana-py
MIT License
989 stars 256 forks source link

getting account balances #155

Open CharlesFr opened 2 years ago

CharlesFr commented 2 years ago

I'm trying to retrieve all tokens associated with a public key, but as far as I understand the token name stored under the data key is serialised. How exactly can I convert this back into a human-readable format?

from solana.rpc.api import Client
from solana.rpc.types import TokenAccountOpts

endpoint = 'https://api.mainnet-beta.solana.com'
client = Client(endpoint)

address = '2t7a5YSiRBiFtXTXbtFbtKcv6hfEbtNWp89kEW9MzLvB'

balances = client.get_token_accounts_by_owner(owner=address, opts=TokenAccountOpts(program_id='TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'))

print(balances.get('result').get('value')[0].get('account'))

> {'data': ['KMN2e2gAqYgYgKzsAH3ktWEAayou1xsadBgO18qSiG8b87y9pvhvRZy4iAu0MB8hP9NZ7JBI69keQegoRjdHoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'base64'], 'executable': False, 'lamports': 2039280, 'owner': 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', 'rentEpoch': 259}
CharlesFr commented 2 years ago

If I pass encoding to TokenAccountOpts I get closer to human-readable output, I think the last step here is to retrieve the token name from the mint address, is this correct? If so, how should I do this?

balances = client.get_token_accounts_by_owner(owner=address, opts=TokenAccountOpts(program_id='TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', encoding='jsonParsed'))

token = balances.get('result').get('value')[0].get('account').get('data')
print(token)

> {'parsed': {'info': {'isNative': False,
   'mint': 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB',
   'owner': '2t7a5YSiRBiFtXTXbtFbtKcv6hfEbtNWp89kEW9MzLvB',
   'state': 'initialized',
   'tokenAmount': {'amount': '0',
    'decimals': 6,
    'uiAmount': 0.0,
    'uiAmountString': '0'}},
  'type': 'account'},
 'program': 'spl-token',
 'space': 165}