9

I want to get a list of tokens I currently own, for a given wallet public key.

Currently I am using https://api.solscan.io/account/tokens?address="PUBLIC_KEY">&price=1 to get the tokens I own.

Okay. So I found this. Using the SPL Token ID as the program ID will return all the user owned tokens.

connection
  .getParsedTokenAccountsByOwner(
    new PublicKey("PUBLIC_KEY"),
    {
      programId: new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
    }
  )
TylerH
  • 20,799
  • 66
  • 75
  • 101
munanadi
  • 799
  • 9
  • 13

2 Answers2

5

I'd recommend using .getParsedProgramAccounts() method of Connection class.

import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { clusterApiUrl, Connection } from "@solana/web3.js";

(async () => {
  const MY_WALLET_ADDRESS = "FriELggez2Dy3phZeHHAdpcoEXkKQVkv6tx3zDtCVP8T";
  const connection = new Connection(clusterApiUrl("devnet"), "confirmed");

  const accounts = await connection.getParsedProgramAccounts(
    TOKEN_PROGRAM_ID, // new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
    {
      filters: [
        {
          dataSize: 165, // number of bytes
        },
        {
          memcmp: {
            offset: 32, // number of bytes
            bytes: MY_WALLET_ADDRESS, // base58 encoded string
          },
        },
      ],
    }
  );
})();

Link to detailed explanation: https://solanacookbook.com/ingredients/get-program-accounts.html#filters

Sasha Omelchenko
  • 250
  • 3
  • 12
1

Take a look at the JSON RPC call getTokenAccountsByOwner, where the owner will be the wallet's public key.

More info at https://docs.solana.com/developing/clients/jsonrpc-api#gettokenaccountsbyowner

Jon C
  • 7,019
  • 10
  • 17