0

In web3js@1 we could use connection.getTokenAccountsByOwner() to get the balance details for tokens in a wallet.

In web3js@2 we have getTokenAccountsByOwner function in the rpc object, but I'm failing to use it, and there seems to be no examples anywhere. I've tried:

await rpc.getTokenAccountsByOwner(wallet.address, {
    programId: TOKEN_PROGRAM_ID,
}).send()

with TOKEN_PROGRAM_ID = address('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), but I'm receiving this error:

SolanaError: JSON-RPC error: The JSON sent is not a valid `Request` object (Encoded binary (base 58) data should be less than 128 bytes, please use Base64 encoding.)

So, does anyone have a working example of getting a token balance of a wallet in web3js v2?

1

1 Answer 1

0

Assuming you know the mint addresses for the desired tokens, you can use findAssociatedTokenPda and pass the result to getTokenAccountBalance to get the balance.

Here's an example:

import { findAssociatedTokenPda, TOKEN_PROGRAM_ADDRESS } from '@solana-program/token';

const COINS_MINT: Record<string, Address> = {
    "USDC": address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),
}


async function getBalances(wallet: KeyPairSigner): Promise<Record<string, number>> {
    const balance = await (rpc.getBalance(wallet.address)).send();
    var output = {} as Record<string, number>;
    output['SOL'] = Number(balance.value) / Math.pow(10, 9);

    for (const token of Object.keys(COINS_MINT)) {
        if (token === 'SOL') continue;
        const [tokenAccount] = await findAssociatedTokenPda({
            mint: COINS_MINT[token],
            owner: wallet.address,
            tokenProgram: TOKEN_PROGRAM_ADDRESS,
        });
        try {
            const { value: { amount, decimals } } = await rpc
                .getTokenAccountBalance(tokenAccount)
                .send();
            output[token] = Number(amount) / Math.pow(10, decimals);
        }
        catch { } // if wallet doesn't have a balance of this token, it'll return an exception.
    }

    return output;
}

There probably is a way to retrieve all tokens as well (like we did on v1) using getTokenAccountsByOwner, but I couldn't figure it out yet.

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.