Solana CookbookTokens
How to Get All Token Accounts by Authority
You can fetch token accounts by owner. There are two ways to do it.
- Get All Token Account
import { clusterApiUrl, Connection, PublicKey } from "@solana/web3.js";import { TOKEN_PROGRAM_ID } from "@solana/spl-token";(async () => {// connectionconst connection = new Connection("http://127.0.0.1:8899", "confirmed");const owner = new PublicKey("G2FAbFQPFa5qKXCetoFZQEvF9BVvCKbvUZvodpVidnoY");let response = await connection.getParsedTokenAccountsByOwner(owner, {programId: TOKEN_PROGRAM_ID});response.value.forEach((accountInfo) => {console.log(`pubkey: ${accountInfo.pubkey.toBase58()}`);console.log(`mint: ${accountInfo.account.data["parsed"]["info"]["mint"]}`);console.log(`owner: ${accountInfo.account.data["parsed"]["info"]["owner"]}`);console.log(`decimals: ${accountInfo.account.data["parsed"]["info"]["tokenAmount"]["decimals"]}`);console.log(`amount: ${accountInfo.account.data["parsed"]["info"]["tokenAmount"]["amount"]}`);console.log("====================");});})();
- Filter By Mint
import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";import { clusterApiUrl, Connection, PublicKey } from "@solana/web3.js";(async () => {// connectionconst connection = new Connection(clusterApiUrl("http://127.0.0.1:8899"),"confirmed");const owner = new PublicKey("G2FAbFQPFa5qKXCetoFZQEvF9BVvCKbvUZvodpVidnoY");const mint = new PublicKey("54dQ8cfHsW1YfKYpmdVZhWpb9iSi6Pac82Nf7sg3bVb");let response = await connection.getParsedTokenAccountsByOwner(owner, {mint: mint,programId: TOKEN_2022_PROGRAM_ID});response.value.forEach((accountInfo) => {console.log(`pubkey: ${accountInfo.pubkey.toBase58()}`);console.log(`mint: ${accountInfo.account.data["parsed"]["info"]["mint"]}`);console.log(`owner: ${accountInfo.account.data["parsed"]["info"]["owner"]}`);console.log(`decimals: ${accountInfo.account.data["parsed"]["info"]["tokenAmount"]["decimals"]}`);console.log(`amount: ${accountInfo.account.data["parsed"]["info"]["tokenAmount"]["amount"]}`);console.log("====================");});})();
Is this page helpful?