OpenInfra.sh is now live - Solana infrastructure, included with every server. LEARN MORE HERE >

OpenInfra.shopeninfra.sh

getTokenAccountsByOwner

Returns SPL Token accounts whose owner matches the supplied address.

Request

Send a JSON-RPC 2.0 POST request with method: "getTokenAccountsByOwner". The params array takes the owner pubkey, a token account filter object, and an optional configuration object.

curl · JSON-RPCjson
{  "jsonrpc": "2.0",  "id": 1,  "method": "getTokenAccountsByOwner",  "params": [    "A1TMhSGzQxMr1TboBKtgixKz1sS6REASMxPo1qsyTSJd",    {      "programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"    },    {      "commitment": "finalized",      "encoding": "jsonParsed"    }  ]}

@solana/kit

kit.tsts
import { address, createSolanaRpc } from "@solana/kit"; const rpc_url = "https://rpc.openinfra.sh";const rpc = createSolanaRpc(rpc_url); let owner = address("4kg8oh3jdNtn7j2wcS7TrUua31AgbLzDVkBZgTAe44aF"); let tokenProgram = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"); let tokenAccounts = await rpc  .getTokenAccountsByOwner(    owner,    { programId: tokenProgram },    {      commitment: "finalized",      encoding: "jsonParsed"    }  )  .send(); console.log(tokenAccounts);

@solana/web3.js

web3.tsts
import { Connection, PublicKey } from "@solana/web3.js"; const connection = new Connection("https://rpc.openinfra.sh", "confirmed"); let owner = new PublicKey("4kg8oh3jdNtn7j2wcS7TrUua31AgbLzDVkBZgTAe44aF"); let tokenProgram = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"); let tokenAccounts = await connection.getTokenAccountsByOwner(owner, {  programId: tokenProgram}); console.log(tokenAccounts);

Rust

main.rsrs
use anyhow::Result;use solana_client::{nonblocking::rpc_client::RpcClient, rpc_request::TokenAccountsFilter};use solana_commitment_config::CommitmentConfig;use solana_sdk::pubkey; #[tokio::main]async fn main() -> Result<()> {    let client = RpcClient::new_with_commitment(        String::from("https://rpc.openinfra.sh"),        CommitmentConfig::confirmed(),    );     let owner = pubkey!("4kg8oh3jdNtn7j2wcS7TrUua31AgbLzDVkBZgTAe44aF");     let token_program = pubkey!("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");     let token_accounts = client        .get_token_accounts_by_owner(&owner, TokenAccountsFilter::ProgramId(token_program))        .await?;     println!("{:#?}", token_accounts);     Ok(())}

Parameters

ParameterTypeRequiredDescription
pubkeystringYesPubkey of the account owner to query, as a base-58 encoded string.
filterobjectYesToken account filter. Must supply exactly one of mint or programId. See sub-fields below.
filter.mintstringConditionalPubkey of the specific token mint to limit accounts to, as a base-58 encoded string.
filter.programIdstringConditionalPubkey of the Token program that owns the accounts, as a base-58 encoded string.
configobjectNoOptional configuration object. See fields below.
config.commitmentstringNoDesired finality level. Accepted values: processed, confirmed, finalized (default).
config.minContextSlotnumberNoThe minimum slot at which the request may be evaluated.
config.dataSliceobjectNoRequest a slice of account data via offset (usize) and length (usize) byte fields. Only available for non-jsonParsed encodings.
config.encodingstringNoEncoding format for account data. Accepted values: base58, base64, base64+zstd, jsonParsed, binary (deprecated). Default is binary.

filter examples

Supply mint to return accounts for a specific token mint:

{ "mint": "So11111111111111111111111111111111111111112" }

Supply programId to return all accounts owned by a given Token program:

{ "programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" }

commitment values

ValueDescription
processedReturn data from the highest slot this node has processed on the fork it currently considers best. This is the newest view, but it can still change if the cluster switches forks.
confirmedReturn data from the highest slot that at least two-thirds of active stake has directly voted to confirm. More stable than processed, but a weaker guarantee than finalized.
finalizedReturn data from the highest slot that the cluster recognizes as finalized. The slot has reached maximum vote lockout in validators' vote towers and is recognized by at least two-thirds of active stake. This is the strongest commitment level.

encoding values

EncodingData formatNotes
base64[data, "base64"]Recommended.
base58[data, "base58"]Slow. The account's data field must be 128 bytes or fewer.
base64+zstd[data, "base64+zstd"]Zstandard compressed.
jsonParsed{program, parsed, space}Falls back to [data, "base64"] if no parser is found.
binarystringDeprecated. Legacy base58 encoding returned as a plain string. Use base64 instead.

minContextSlot example

{ "minContextSlot": 341197000 }

dataSlice example

{ "offset": 0, "length": 32 }

Response

response.jsonjson
{  "jsonrpc": "2.0",  "result": {    "context": { "apiVersion": "3.1.8", "slot": 341197933 },    "value": [      {        "pubkey": "BGocb4GEpbTFm8UFV2VsDSaBXHELPfAXrvd4vtt8QWrA",        "account": {          "data": {            "program": "spl-token",            "parsed": {              "info": {                "isNative": false,                "mint": "2cHr7QS3xfuSV8wdxo3ztuF4xbiarF6Nrgx3qpx3HzXR",                "owner": "A1TMhSGzQxMr1TboBKtgixKz1sS6REASMxPo1qsyTSJd",                "state": "initialized",                "tokenAmount": {                  "amount": "420000000000000",                  "decimals": 6,                  "uiAmount": 420000000.0,                  "uiAmountString": "420000000"                }              },              "type": "account"            },            "space": 165          },          "executable": false,          "lamports": 2039280,          "owner": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",          "rentEpoch": 18446744073709551615,          "space": 165        }      }    ]  },  "id": 1}

The result is an RpcResponse object containing a context and a value array of keyed-account objects.

Top-level fields

FieldTypeDescription
contextobjectSlot and API version the node used to answer this request.
context.slotu64Slot at which the node evaluated this request.
context.apiVersionstringRPC API version reported by the node. May be omitted by older nodes.
valuearrayArray of keyed-account objects. Each element contains a pubkey and an account data object.

value[] item fields

FieldTypeDescription
pubkeystringAccount pubkey, as a base-58 encoded string.
accountobjectAccount data object using the shared Account Data structure.
account.datastring | array | objectToken account data. Binary forms depend on the encoding parameter. When encoding is jsonParsed, this field is an object with program, parsed, and space keys.
account.executableboolWhether the account contains a program and is therefore read-only.
account.lamportsu64Lamports assigned to the account.
account.ownerstringProgram owner pubkey, as a base-58 encoded string.
account.rentEpochu64Next epoch at which the account owes rent.
account.spaceu64 | nullAccount data size in bytes.

account.data fields (jsonParsed)

FieldTypeDescription
programstringName of the parser that produced the decoded data. Either spl-token or spl-token-2022.
parsedobjectParsed SPL Token account payload.
spaceu64Account data size in bytes.

parsed fields

FieldTypeDescription
typestringAlways account for this method.
infoobjectParsed SPL Token account fields. See parsed.info fields below.

parsed.info fields

FieldTypeDescription
mintstringToken mint pubkey, as a base-58 encoded string.
ownerstringToken-account owner pubkey, as a base-58 encoded string.
tokenAmountobjectToken amount object with raw and decimal-scaled representations.
delegatestring | nullDelegate pubkey, when a delegate is set.
statestringToken-account state. One of uninitialized, initialized, or frozen.
isNativeboolWhether this account wraps the native SOL mint.
rentExemptReserveobject | nullRent-exempt reserve amount for wrapped SOL accounts, when present. Uses the same token-amount schema as tokenAmount.
delegatedAmountobject | nullAmount delegated to the delegate, when present. Uses the same token-amount schema as tokenAmount.
closeAuthoritystring | nullClose-authority pubkey, when present.
extensionsarrayParsed SPL Token 2022 extension entries. Each element has an extension discriminator and an extension-specific state payload.

tokenAmount fields

FieldTypeDescription
amountstringRaw token amount, as a base-10 integer string.
decimalsu8Number of decimal places configured on the mint.
uiAmountnumber | nullDecimal-scaled amount as a floating-point number. Deprecated in favor of uiAmountString.
uiAmountStringstringDecimal-scaled amount as a string.