2

Also posted on stack overflow

I'm looking to get the token balance for an SPL token in solana based on the:

  • Wallet address of the token holder
  • The token address

How can I do this?

I thought it would be something like:

import requests
import os

url = os.getenv("SOLANA_RPC_URL")

MY_WALLET_ADDRESS = "XXXXX"
MY_TOKEN_ADDRESS = "XXX"
MINTER = "XXXX"
TOKEN_PROGRAM_ID = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"

payload = {
    "id": 1,
    "jsonrpc": "2.0",
    "method": "getTokenAccountsByOwner",
    "params": [
        MY_WALLET,
        {"programId": TOKEN_PROGRAM_ID},
        {"encoding": "jsonParsed"},
    ],
}
headers = {"accept": "application/json", "content-type": "application/json"}

response = requests.post(url, json=payload, headers=headers)

print(response.text)

But I keep getting a blank response for what seems to be valid addresses:

{"jsonrpc":"2.0","result":{"context":{"apiVersion":"1.13.5","slot":176104484},"value":[]},"id":1}

I'm using alchemy as my node for Solana.

5
  • what are you doing here man? Go teach your Ethereum :)
    – Yilmaz
    Commented Feb 5, 2023 at 4:52
  • is the wallet address base-58 encoded string. if not try to use wallet-address.toBase58()
    – Yilmaz
    Commented Feb 5, 2023 at 5:03
  • It's the address you'd find off the explorer. I'm not sure if those are encoded by default? Commented Feb 5, 2023 at 16:22
  • if you do not call toBase58 it will return a BN object. your response points that you are reaching the server but getting an empty result which is a kinda 404 response.
    – Yilmaz
    Commented Feb 5, 2023 at 16:30
  • Looks like you can just use the string of the address. I've answered below. Would love any additional feedback. Commented Feb 5, 2023 at 17:06

1 Answer 1

3

Summary

You can get a wallet's token balances by calling getTokenAccountsByOwner.

It takes the following parameters:

  • Pubkey: Your wallet address
  • dict: {"mint": TOKEN_ADDRESS} where TOKEN_ADDRESS is the address of the SPL token you want.

The dict can optionally be: "Pubkey of the Token program that owns the accounts" - which I don't understand what that means yet.

Code

MY_WALLET = "XXXXXX"
MY_TOKEN = "XXXX"

url = os.getenv("SOLANA_RPC_URL")
headers = {"accept": "application/json", "content-type": "application/json"}

payload = {
    "id": 1,
    "jsonrpc": "2.0",
    "method": "getTokenAccountsByOwner",
    "params": [
        MY_WALLET,
        {"mint": MY_TOKEN},
        {"encoding": "jsonParsed"},
    ],
}
response = requests.post(url, json=payload, headers=headers)
print(
    response.json()["result"]["value"][0]["account"]["data"]["parsed"]["info"][
        "tokenAmount"
    ]["uiAmount"]
)

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.