Search code examples
cryptocurrencysolanasolana-web3jssolana-clianchor-solana

Solana: Parse Token Data


How does one parse the data in an SPL token account? It contains a binary blob and I'd like to get the token type and number of tokens.

An acceptable language is solana-cli, web3.js, or solana.py. I'm looking for any solution.


Solution

  • The RPC give a great way to parse the data by default. You can use getParsedAccountInfo in web3.js.

    Let's take the token account at 9xqnnfeonbsEGSPgF5Wd7bf9RqXy4KP22bdaGmZbHGwp

    import { Connection, PublicKey, ParsedAccountData, clusterApiUrl } from '@solana/web3.js';
    
    (async () => {
      const connection = new Connection(clusterApiUrl('mainnet-beta'));
      const tokenAccount = await connection.getParsedAccountInfo(new PublicKey('9xqnnfeonbsEGSPgF5Wd7bf9RqXy4KP22bdaGmZbHGwp'));
      console.log((tokenAccount.value?.data as ParsedAccountData).parsed);
    })();
    
    /**
    {
      info: {
        isNative: false,
        mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
        owner: 'Ccyrkw1FdRVsfnt7qptyUXqyffq3i59GSPN1EULqZN6i',
        state: 'initialized',
        tokenAmount: {
          amount: '738576212',
          decimals: 6,
          uiAmount: 738.576212,
          uiAmountString: '738.576212'
        }
      },
      type: 'account'
    }
    **/
    

    Here we can see the output of the tokenAccount has a mint of EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v(USDC) owned by address Ccyrkw1FdRVsfnt7qptyUXqyffq3i59GSPN1EULqZN6i with an amount of 738.576212. That's all the data we need from a token account.