# getAccountInfo

The `getAccountInfo` RPC method is a core utility for querying detailed information about any account on the Solana blockchain. By supplying a public key, this method returns comprehensive data about the associated account—such as its balance, ownership, executable status, and raw or parsed storage data.

***

#### 🔍 Common Use Cases

* **Check SOL Balance**\
  Retrieve the lamport balance (1 SOL = 1,000,000,000 lamports) for any public key.
* **Verify Account Initialization**\
  Determine if an account exists and has been initialized with lamports or data.
* **Inspect Program State**\
  Read data stored in program-owned accounts—vital for decoding on-chain program states.
* **Identify Account Ownership**\
  Determine which program owns the account to understand how its data should be interpreted.
* **Check Executability**\
  Discover whether an account contains a deployed program (i.e., if it’s executable).

***

#### 🛠 Parameters

* **`publicKey`** (*string, required*):\
  Base-58 encoded public key of the account to query.
* **`config`** (*object, optional*):\
  Optional configuration fields:
  * `commitment` (*string*):\
    Sets the desired commitment level:
    * `finalized` *(default)* – Highest confirmation level.
    * `confirmed` – Voted on by supermajority.
    * `processed` – Most recent block, possibly unconfirmed.
  * `encoding` (*string*):\
    Specifies the data encoding:
    * `base64` *(default)*
    * `base58` *(slower)*
    * `base64+zstd` *(for compressed data)*
    * `jsonParsed` *(for known account types like tokens or stakes)*
  * `dataSlice` (*object*):\
    Return a partial slice of the data (valid only for binary encodings):
    * `offset`: Starting byte offset.
    * `length`: Number of bytes to return.
  * `minContextSlot` (*number*):\
    Minimum slot that must be reached before evaluating the request.

***

#### 📦 Response Structure

If the account exists, the `result` object includes:

* **`context`** (*object*):
  * `slot`: The slot at which the data was retrieved.
  * `apiVersion`: (Optional) The version of the RPC API used.
* **`value`** (*object | null*):\
  If `null`, the account was not found. Otherwise:
  * `lamports` (*number*): Total SOL balance in lamports.
  * `owner` (*string*): Public key of the program that owns the account.
  * `data` (*array | object | string*): Account data content:
    * For `base64`, `base58`, or `base64+zstd`: `[encoded_string, encoding]`
    * For `jsonParsed`: Parsed JSON if applicable, otherwise defaults to base64 structure.
  * `executable` (*boolean*): `true` if the account contains a program.
  * `rentEpoch` (*number*): The next epoch at which rent will be collected.
  * `space` (*number*, optional): Total allocated byte size of the account’s data.

If the account is not found, the `value` will be `null`.

***

#### 💡 Example: Querying Account Info

Let’s retrieve information for the Serum V3 program ID on mainnet:

**Public Key:**\
`4UJuvGZ7Ge8H3je63Nsb9ZRNVBAd3CG2ajibnRaVSbw5`

**Sample Request (CoinVera RPC):**

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

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

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

    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';

getAccountInfo(RPC_URL);
```

{% endtab %}

{% tab title="Python" %}

```python
import json
import asyncio
import aiohttp

async def get_account_info(rpc_url):
    try:
        payload = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "getAccountInfo",
            "params": [
                "4UJuvGZ7Ge8H3je63Nsb9ZRNVBAd3CG2ajibnRaVSbw5",
                {
                    "encoding": "jsonParsed"
                }
            ]
        }
        
        async with aiohttp.ClientSession() as session:
            async with session.post(
                rpc_url,
                headers={'Content-Type': 'application/json'},
                json=payload
            ) as response:
                data = await 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
async def main():
    RPC_URL = 'https://rpc.coinvera.io/?x-api-key=your-coinvera-x-api-key'
    await get_account_info(RPC_URL)

# Run the async function
if __name__ == "__main__":
    asyncio.run(main())
```

{% endtab %}
{% endtabs %}

**Example Response**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "context": {
      "slot": 355178140,
      "apiVersion": "2.2.7"
    },
    "value": {
      "lamports": 196248541,
      "data": [
        "",
        "base64"
      ],
      "owner": "11111111111111111111111111111111",
      "executable": false,
      "rentEpoch": 18446744073709552000,
      "space": 0
    }
  }
}
```

#### 💡 Developer Tips (Using `getAccountInfo` with CoinVera)

* **Optimize with `getMultipleAccounts`**\
  For applications that require checking multiple accounts simultaneously, use the `getMultipleAccounts` method to batch requests. This significantly reduces network overhead and improves performance.
* **Deserialize Account Data Properly**\
  The `data` field returned by `getAccountInfo` is often in raw or encoded form. To interpret this correctly, you’ll need deserialization logic tailored to the owning program (e.g., use the SPL Token library for token accounts). Refer to CoinVera’s blog for practical techniques on deserializing Solana account data.
* **Watch for RPC Rate Limits**\
  CoinVera RPC endpoints may enforce rate limits. Avoid excessive polling or redundant queries to maintain reliability and avoid throttling when accessing many accounts.
* **Manage Costs Efficiently**\
  Although `getAccountInfo` is a lightweight RPC call, high-frequency polling can accumulate bandwidth and compute costs. Optimize polling frequency and request patterns to stay efficient.
* **Use `jsonParsed` with Caution**\
  The `jsonParsed` encoding is helpful for known account types like tokens and stakes, but it may not support all custom programs. Its structure can also evolve if a program changes. For mission-critical use cases, decode binary data directly using a fixed layout for maximum consistency.
* **Leverage `dataSlice` for Precision**\
  If your use case only requires part of the account’s data, use the `dataSlice` option to fetch only the needed bytes. This reduces payload size and accelerates queries—especially valuable when working at scale.


---

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