0

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.

Test
  • 962
  • 9
  • 26

2 Answers2

3

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.

Jacob Creech
  • 1,797
  • 2
  • 11
2

I was recently looking for an answer to the same problem, and I ended up using the AccountLayout from @solana/spl-token-v2.

So something like this:

import { AccountLayout } from "@solana/spl-token-v2";
...

const tokenAccountInfo = await connection.getAccountInfo(tokenAccount);
const decodedTokenAccountInfo = AccountLayout.decode(tokenAccountInfo!.data);
console.log(decodedTokenAccountInfo);

/*
{
  mint: PublicKey {
    _bn: <BN: X>
  },
  owner: PublicKey {
    _bn: <BN: X>
  },
  amount: 0n,
  delegateOption: 0,
  delegate: PublicKey { 
    _bn: <BN: X>
  },
  state: 1,
  isNativeOption: 0,
  isNative: 0n,
  delegatedAmount: 0n,
  closeAuthorityOption: 0,
  closeAuthority: PublicKey { 
    _bn: <BN: X>
  }
}
*/

I am assuming here that the token address is valid and the getAccountInfo function will return valid data.