简体   繁体   中英

Getting Token Account of Solana Account

I have following account Solana Explorer Account

And i can see there is a Mint account ( Account that store my tokens ) how i can get the mint account having my public key is there any relation or how this thing is working in general

Some terminology to be sure we're on the same page:

  • the "wallet" is the system account that owns other accounts, your linked "Solana Explorer Account" of CGP6sKHyrZGPJRoUAy8XbyzmX7YD4tVBQG9SEe9ekZM6
  • the mint account defines the token, and does not hold any tokens, is Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr
  • the account that holds your tokens is actually G6ogFW6YzBpYKhwZrckZJa4yejcjNTfHLE2mUAQFv3ic : https://explorer.solana.com/address/G6ogFW6YzBpYKhwZrckZJa4yejcjNTfHLE2mUAQFv3ic?cluster=devnet -- this is an "associated token account", whose address is derived from your wallet. The tools and explorer default to using that account when dealing with the Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr token. To get this account, you can use getAssociatedTokenAccount , which boils down to:
import { PublicKey } from '@solana/web3.js';

const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
const owner = new PublicKey('CGP6sKHyrZGPJRoUAy8XbyzmX7YD4tVBQG9SEe9ekZM6');
const mint = new PublicKey('Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr');

const [address] = await PublicKey.findProgramAddress(
    [owner.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],
    ASSOCIATED_TOKEN_PROGRAM_ID
);

The real code is at: https://github.com/solana-labs/solana-program-library/blob/5611ad8bd595d9e3666f8b115cd28f8116038645/token/js/src/state/mint.ts#L146

const connection = new Connection("https://api.devnet.solana.com");
  let response = await connection.getTokenAccountsByOwner(
    new PublicKey("27kVX7JpPZ1bsrSckbR76mV6GeRqtrjoddubfg2zBpHZ"), // owner here
    {
      programId: TOKEN_PROGRAM_ID,
    }
  );

This is to get all token account owned by specific wallet address. Dont forget to adjust connection url if you are using mainnet or testnet or localhost. You also can filter it to a specific mint address as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM