2

could someone help me with this:?

I've been trying to get the amount of tokens of a connected wallet from a TokenAccount.

Right Below you can see that I successfully retrieved the TokenAccount address and the spl tokens supply but I don't know what's next...

I want to get only the amount of SPL TOKENS from the wallet connected to my DAPP. Ty and have a good day.


            // Check for Solana & Phantom
            var provider = () => {
            if ("solana" in window) {
                var provider = window.solana;
                if (provider.isPhantom) {
                return provider;
                } else {
                return false;
                }
            }
            window.open("https://phantom.app", "_blank");
            };

            var phantom = provider();

            if (phantom !== false) {

console.log("Phantom Wallet Found, Connecting..");

try {

                // Connect to Solana
                var connect_wallet = phantom.connect();

                // After Connecting
                phantom.on("connect", () => {
                    conn.addEventListener('click', () => {
                        user_balance.classList.toggle('expand');
                    })

                  // Check Connection
                console.log("Phantom Connected: " + phantom.isConnected);

                  // Get Wallet Address
                const wallet = phantom.publicKey;
                var wallet_address = phantom.publicKey.toString();
                console.log("Solana Wallet Address: " + wallet_address);
                var first = wallet_address.substring(0, 5);
                document.getElementById('wallet-address').innerHTML = first + '...';

                (async () => {
                    const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl("mainnet-beta"),
                        'confirmed',
                    );
                
                    if (phantom && phantom.publicKey !== null) {
                        const tokenAccount = new solanaWeb3.PublicKey(
                            "J3Lw33iBvMLHdCua4MXohTx3HD4JcajQmogQEr2Y7pej"
                          );
                        
                          let tokenAmount = await connection.getTokenAccountBalance(tokenAccount);
                          console.log(`amount: ${tokenAmount.value.amount}`);
      
                        const balance = await connection.getBalance(phantom.publicKey);
                        console.log(balance / 1000000000);
                    }
                })();

2 Answers 2

5

If I understood you right, your code works, but you need to get the TokenAccount address from the wallet right?

What you can do is: call getTokenAccountsByOwner(pubKey) and then check all the token accounts TokenAccountInfo mint if its the mint of your specific token.

Then you can call getTokenAccountBalance on that account like you already do.

To make it more performant you can directly specify the mint in the getTokenAccountsByOwner function. Then you can save the token account in the client and only call getTokenAccountBalance form then on.

4
  • Hello, thanks for replying... The thing i don't know how to do it's this: I want the balance from a wallet connected to my DAPP but only the balance from this address "J3Lw33iBvMLHdCua4MXohTx3HD4JcajQmogQEr2Y7pej" at the wallet that connected to my site To give a little more info: I want to get the SPL TOKEN BALANCE but from the wallet connected... not the Token Account wallet which is this... "J3Lw33iBvMLHdCua4MXohTx3HD4JcajQmogQEr2Y7pej"
    – ChrisDev
    Commented Jul 19, 2022 at 18:18
  • Yeah so as long as J3Lw33iBvMLHdCua4MXohTx3HD4JcajQmogQEr2Y7pej is the mint authority of your spl token what i wrote should do exactly that. Did you try it out?
    – Jonas H.
    Commented Jul 19, 2022 at 20:14
  • I've tried but i can't find a way to connect the SPL token TOKEN_PROGRAM_ID directly at Vanilla JS... any advice? ty
    – ChrisDev
    Commented Jul 26, 2022 at 0:52
  • Sorry I do not understand the question. "connect the SPL token TOKEN_PROGRAM_ID directly at Vanilla JS" Cant figure out what that could mean.
    – Jonas H.
    Commented Jul 26, 2022 at 9:14
2

I'm using this snippet myself

export const getTokenBalance = async (walletAddress:string, tokenMintAddress:string):Promise<number> => {
  try{
    const connection = new Connection(process.env.SOLANA_RPC_ENDPOINT, 'confirmed')
    const walletTokenAccounts = await connection.getParsedTokenAccountsByOwner(new PublicKey(walletAddress), {
      mint: new PublicKey(tokenMintAddress)
    })
    if(walletTokenAccounts && walletTokenAccounts.value && walletTokenAccounts.value.length > 0){
      const walletTokenAccount = walletTokenAccounts.value[0]
      const amount = walletTokenAccount.account.data.parsed.info.tokenAmount.uiAmount
      console.log(`amount: ${amount}`);
      return amount
    }
  }catch(e){
    console.error(e)
  }
  return 0
}

walletAddress would be your wallet_address tokenMintAddress would be the address of the SPL token. For example if you were looking to get the balance of BONK, you would use DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.