# getTokenAccountBalance

The `getTokenAccountBalance` RPC method in **CoinVera** returns the **token balance** of a specified SPL token account. It provides detailed information including raw amount, decimals, and user-friendly display formats.

***

#### ✅ Common Use Cases

* **Display Token Balances in UI**\
  Show a user’s token balance for wallets and dApps.
* **Validate Token Holdings**\
  Confirm whether a wallet has a sufficient token balance before proceeding with transfers, swaps, or burns.
* **Bot/Automation Scripts**\
  Use in scripts to make decisions based on token balances (e.g., execute only if balance > threshold).

***

#### 🧾 Request Parameters

* `account` (string, required):\
  The base-58 encoded address of the SPL token account to query.
* `commitment` (string, optional):\
  Optional. Specifies the state commitment level—`processed`, `confirmed`, or `finalized`.

***

#### 📦 Response Structure

Returns a balance object under the `value` key:

```json
{
  "context": {
    "slot": 221446650
  },
  "value": {
    "amount": "1500000",
    "decimals": 6,
    "uiAmount": 1.5,
    "uiAmountString": "1.5"
  }
}
```

* **amount**: Raw token amount as a string (e.g. "1500000" for 1.5 tokens with 6 decimals).
* **decimals**: Number of decimal places defined by the token mint.
* **uiAmount**: The token amount as a number (floating point).
* **uiAmountString**: The token amount as a formatted string.

***

#### 🧪 Example

**Query Balance of a Token Account**

Request:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getTokenAccountBalance",
  "params": [
    "6z7jRJ3Wy8x1NUts7vmu5yQ9xNGZ63v2wKzLtnSKNfJg"
  ]
}
```

***

**Code Examples**

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

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

async function getTokenAccountBalance(rpcUrl) {
  try {
    const response = await fetch(rpcUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 1,
        method: 'getTokenAccountBalance',
        "params": [
            "G4W4MYAETYHYUnARsydMzcyrY5gLfse3pXrg2rR2wang",
            {
              "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';

getTokenAccountBalance(RPC_URL);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

def get_token_account_balance(rpc_url):
    try:
        response = requests.post(
            rpc_url,
            headers={
                'Content-Type': 'application/json',
            },
            json={
                'jsonrpc': '2.0',
                'id': 1,
                'method': 'getTokenAccountBalance',
                'params': [
                    'G4W4MYAETYHYUnARsydMzcyrY5gLfse3pXrg2rR2wang',
                    {
                        '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_account_balance(RPC_URL)
```

{% endtab %}
{% endtabs %}

**Response Example**

```json
{
  "jsonrpc": "2.0",
  "result": {
    "context": {
      "apiVersion": "2.2.16",
      "slot": 355401009
    },
    "value": {
      "amount": "1",
      "decimals": 6,
      "uiAmount": 0.000001,
      "uiAmountString": "0.000001"
    }
  },
  "id": 1
}
```

***

#### 💡 Developer Tips

* **Only Works on Token Accounts**\
  This method only accepts **token account addresses**, not general wallet addresses. Use `getTokenAccountsByOwner` first if needed.
* **Lamports ≠ Token Amounts**\
  Unlike SOL balances, token balances vary in decimal precision—always respect the `decimals` value.
* **String for Precision**\
  Use `uiAmountString` in UIs to avoid rounding errors, especially for large or small balances.
* **Commitment Matters**\
  Add `commitment: "finalized"` if you need the most reliable confirmed result.

***

The `getTokenAccountBalance` method is essential for tracking SPL token balances in real-time, especially in dApps, wallets, and trading bots built on **CoinVera**.


---

# 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/gettokenaccountbalance.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.
