# getTokenAccountsByOwner

The `getTokenAccountsByOwner` RPC method in **CoinVera** is used to retrieve all SPL token accounts owned by a specific wallet address (public key). This is a core method for wallets, explorers, and applications that need to **display token balances** or **interact with a user’s token accounts**.

You must filter the request using either a **specific token mint** or a **programId** (such as the SPL Token Program or Token-2022 Program).

***

#### ✅ Common Use Cases

* **Displaying User Portfolio**\
  Retrieve all token accounts owned by a wallet to display the user’s full token holdings.
* **Token Transfer Logic**\
  Identify the token account associated with a specific mint before sending or receiving tokens.
* **Ownership Verification**\
  Check whether a wallet owns a token account for a particular token.
* **Indexing Known Holders**\
  Though less efficient than global indexing, this can be used to find token accounts across known users.

***

#### 🧾 Request Parameters

```ts
[
  ownerPubkey: string,       // Required – The public key of the wallet.
  filter: {
    mint?: string,           // Optional – Specific token mint to filter by.
    programId?: string       // Optional – Token program ID to filter accounts (e.g. SPL or Token-2022).
  },
  options?: {
    commitment?: string,     // Optional – Commitment level (processed, confirmed, finalized).
    encoding?: string,       // Optional – Data encoding ("jsonParsed" recommended).
    dataSlice?: { offset: number, length: number }, // Optional – Only used for binary encodings.
    minContextSlot?: number  // Optional – Minimum context slot.
  }
]
```

**💡 Filter Requirement:**

You **must provide either** a `mint` or a `programId`. Without one, the query is invalid.

**Common program IDs**:

* SPL Token Program: `TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA`
* Token-2022 Program: `TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb`

***

#### 📦 Response Structure

```json
{
  "context": { "slot": 221446650 },
  "value": [
    {
      "pubkey": "TokenAccountPubkeyHere",
      "account": {
        "lamports": 2039280,
        "owner": "TokenProgramAddress",
        "data": {
          "program": "spl-token",
          "parsed": {
            "info": {
              "mint": "MintAddress",
              "owner": "WalletAddress",
              "tokenAmount": {
                "amount": "1500000",
                "decimals": 6,
                "uiAmount": 1.5,
                "uiAmountString": "1.5"
              },
              "state": "initialized",
              "isNative": false,
              "delegate": "OptionalDelegate",
              "delegatedAmount": {
                "amount": "500000"
              }
            },
            "type": "account"
          }
        },
        "executable": false,
        "rentEpoch": 375
      }
    }
  ]
}
```

***

#### 🧪 Examples

**Get All Token Accounts for a Wallet (SPL Token Program)**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getTokenAccountsByOwner",
  "params": [
    "YourWalletPublicKeyHere",
    { "programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" },
    { "encoding": "jsonParsed" }
  ]
}
```

**Filter by Specific Mint**

```json
{
  "params": [
    "YourWalletPublicKeyHere",
    { "mint": "MintAddressHere" },
    { "encoding": "jsonParsed" }
  ]
}
```

***

**Code Examples**

{% tabs %}
{% tab title="Nodejs" %}

```javascript
const fetch = require('node-fetch');

async function getTokenAccountsByOwner(rpcUrl) {
  try {
    const response = await fetch(rpcUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 1,
        method: 'getTokenAccountsByOwner',
        "params": [
            "58FqLVkDz8Zkg5fRAinwrAnu6a2dK1TJkDg8NG6pRimE",
            { "mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" },
            { "encoding": "jsonParsed", "commitment": "confirmed" }
          ]
      }),
    });

    const data = await response.json();
    
    // Print the exact full response
    console.log('Full RPC Response:');
    console.log(JSON.stringify(data, null, 2));
    
    return data;
  } catch (error) {
    console.error('Error getting health:', error.message);
    return null;
  }
}

// Example usage
const RPC_URL = 'https://rpc.coinvera.io/?x-api-key=your-coinvera-x-api-key';

getTokenAccountsByOwner(RPC_URL);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

def get_token_accounts_by_owner(rpc_url):
    try:
        response = requests.post(
            rpc_url,
            headers={
                'Content-Type': 'application/json',
            },
            json={
                'jsonrpc': '2.0',
                'id': 1,
                'method': 'getTokenAccountsByOwner',
                'params': [
                    '58FqLVkDz8Zkg5fRAinwrAnu6a2dK1TJkDg8NG6pRimE',
                    {'mint': 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'},
                    {'encoding': 'jsonParsed', 'commitment': 'confirmed'}
                ]
            }
        )
        
        data = response.json()
        
        # Print the exact full response
        print('Full RPC Response:')
        print(json.dumps(data, indent=2))
        
        return data
        
    except Exception as error:
        print(f'Error getting health: {error}')
        return None

# Example usage
RPC_URL = 'https://rpc.coinvera.io/?x-api-key=your-coinvera-x-api-key'
get_token_accounts_by_owner(RPC_URL)
```

{% endtab %}
{% endtabs %}

**Example Response**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "context": {
      "slot": 355408021,
      "apiVersion": "2.2.7"
    },
    "value": [
      {
        "pubkey": "G4W4MYAETYHYUnARsydMzcyrY5gLfse3pXrg2rR2wang",
        "account": {
          "lamports": 2039280,
          "data": {
            "program": "spl-token",
            "parsed": {
              "info": {
                "isNative": false,
                "mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
                "owner": "58FqLVkDz8Zkg5fRAinwrAnu6a2dK1TJkDg8NG6pRimE",
                "state": "initialized",
                "tokenAmount": {
                  "amount": "1",
                  "decimals": 6,
                  "uiAmount": 0.000001,
                  "uiAmountString": "0.000001"
                }
              },
              "type": "account"
            },
            "space": 165
          },
          "owner": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
          "executable": false,
          "rentEpoch": 18446744073709552000,
          "space": 165
        }
      }
    ]
  }
}
```

***

#### 💡 Developer Tips

* **Mandatory Filter**\
  Either `mint` or `programId` must be provided—you cannot retrieve all token accounts unfiltered.
* **Associated Token Accounts (ATAs)**\
  Results include standard ATAs as well as manually created or legacy token accounts.
* **Use `jsonParsed`**\
  Highly recommended for easier access to account fields like balance, owner, and mint.
* **Performance Consideration**\
  If filtering only by `programId`, results may be large. Consider batching wallet lookups if working with multiple addresses.
* **Token Extensions**\
  For Token-2022 tokens (e.g., with transfer fees, interest-bearing extensions), make sure you use the correct program ID:\
  `TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb`.

***

The `getTokenAccountsByOwner` method is essential for any wallet or token-aware Solana app powered by **CoinVera**. It offers a clear view into a user’s on-chain token holdings, including advanced support for both standard and extended SPL tokens.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.coinvera.io/integration/solana/rpc/gettokenaccountsbyowner.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
