DEV Community

Alvaro Fragoso
Alvaro Fragoso

Posted on

Get the balance of a Solana Wallet

Hello Devs!

Developing apps in Solana can feel like the Wild West right now. This past weekend I spent 2 days just trying to get the balance of a certain token from a wallet that connects to my site.

I felt really frustrated because it was something that seemed easy but I could not find a real example or how to do it.

So, here I am trying to explain it the best way I can.

The first thing you need to do is to get the user’s public key. You can achieve this really easily retrieving the solana object from your window.

const [walletAddress, setWalletAddress] = useState(null);
const connectWallet = async () => {
         //Get the solana object
        const { solana } = window;
        // If we have it, we assign the value to a variable
        if(solana) {
            const response = await solana.connect();
            console.log('Connected with Public Key: ' + response.publicKey.toString())
          setWalletAddress(response.publicKey.toString())
        }
      };
Enter fullscreen mode Exit fullscreen mode

Nice! We can now talk to Solana and ask for the balance.

First, you need to import the following functions from web3.js (npm install --save @solana/web3.js if you dont’t have it).

import { Connection, clusterApiUrl, PublicKey } from '@solana/web3.js';
Enter fullscreen mode Exit fullscreen mode

Then, we just do the following:

const [balance, setBalance] = useState(0);
const getBalance = async (wallet) => {
        const connection = new Connection(clusterApiUrl('mainnet-beta'), 'confirmed')
        const response = await connection.getParsedTokenAccountsByOwner(wallet, 
            {mint: new PublicKey(PUBLIC_KEY_OF_TOKEN)}    
        ) setBalance(response.value[0].account.data.parsed.info.tokenAmount.uiAmount) 
    }
Enter fullscreen mode Exit fullscreen mode

OH YEAH!

We just received our user’s balance. But how? 🤔

Well, first, we create a useState with the initial value of 0 that is going to hold the balance. Then, we declare our function and that we need to pass it a string of our user’s wallet public key.

Ok, we need to create a connection with the solana blockchain, that’s why we imported “Connection” and “clusterApiUrl” from the web3.js. I’m not going to explain what each of these things mean but you should be able to find them easily if you google them.

Now that we have the connection, we are finally able to ask for the balance. We do that calling the getParsedTokenAccountsByOwner function from our connection and passing the wallet address and an object containing the public key of the token you want to find.

Finally, we just use setBalance to assign the value and that’s it!

I hope you found this useful and that you don’t spend as much time as I did trying to get a balance.

See you soon devs!

Top comments (3)

Collapse
 
haodev007 profile image
Holmes

Hi, Can I get balance of Solana coin from getParsedTokenAccountsByOwner function?

Collapse
 
metasurfero profile image
Alvaro Fragoso

For Solana you could simply use the function getBalance which is way easier docs.solana.com/developing/clients... : )

Collapse
 
haodev007 profile image
Holmes • Edited

Hi thanks!
I just wanted to get both balance of Solana native coin and balance of all other tokens on Solana ecosystem.
Thanks though!