# getBlock

The `getBlock` RPC method allows you to retrieve detailed information about a confirmed block in the Solana ledger. This is essential for block explorers, transaction history analysis, and understanding the state of the chain at a specific point in time.

***

#### **Common Use Cases**

* **Inspecting Block Contents**\
  View all transactions included in a specific block.
* **Retrieving Block Hashes**\
  Get the blockhash for a given slot, its parent’s blockhash, and its parent slot.
* **Checking Block Height and Time**\
  Find out a block’s height (its sequence number) and its estimated production time.
* **Analyzing Transaction Details**\
  With appropriate parameters, retrieve full transaction data, including metadata like fees, status, pre/post balances, and inner instructions.
* **Fetching Rewards**\
  Optionally include reward information for the block.

***

#### **Parameters**

* **`slot`** (*number, required*):\
  The slot number of the block to query (u64).
* **`config`** (*object, optional*):\
  Configuration options include:
  * **`commitment`** (*string*):\
    Commitment level. `processed` is not supported. Defaults to `finalized`.
  * **`encoding`** (*string*):\
    How transaction data is returned. Defaults to `json` if `transactionDetails` is `full` or `accounts`, otherwise `base64`. Options:
    * `json` *(deprecated)*
    * `jsonParsed` *(recommended for parsed keys and Lookup Table support)*
    * `base58`
    * `base64`
    * `base64+zstd`
  * **`transactionDetails`** (*string*):\
    Level of transaction detail to return. Defaults to `full`.
    * `full`
    * `accounts`
    * `signatures`
    * `none`
  * **`rewards`** (*boolean*):\
    Include rewards array if `true`. Defaults to `false`.
  * **`maxSupportedTransactionVersion`** (*number*):\
    Maximum transaction version to return. Set to `0` to include versioned transactions using Address Lookup Tables.

***

#### **Response**

If the block is found and confirmed, the `result` will include:

* **`blockhash`** (*string*):\
  The base-58 encoded blockhash.
* **`previousBlockhash`** (*string*):\
  The base-58 encoded blockhash of the previous block.
* **`parentSlot`** (*number*):\
  The slot number of the parent block.
* **`transactions`** (*array*):\
  List of transactions included in the block. Each entry contains:
  * `meta`: Transaction metadata (e.g., fee, logs, balances).
  * `transaction`: The raw transaction data, including signatures and message content.
* **`rewards`** (*array*, optional):\
  Present if `rewards: true` was requested. Includes reward info (e.g., `pubkey`, `lamports`, `postBalance`, `rewardType`, and `commission`).
* **`blockTime`** (*number | null*):\
  Estimated Unix timestamp of block production.
* **`blockHeight`** (*number | null*):\
  Sequence number from genesis slot.

If the block is not found or unconfirmed, `result` will be `null`.

***

#### **Example: Fetching Block Information**

Here’s how to retrieve block info for a sample slot (e.g., `355184627`) on Devnet. Replace it with a current confirmed slot number for accurate results.\
Also, replace `X-API-KEY` with your actual **CoinVera** API key.

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

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

async function getBlock(rpcUrl) {
  try {
    const response = await fetch(rpcUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 1,
        method: 'getBlock',
        "params": [
            355184627, 
            {
              "encoding": "jsonParsed",
              "transactionDetails": "full",
              "rewards": true,
              "maxSupportedTransactionVersion": 0
            }
          ]
      }),
    });

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

getBlock(RPC_URL);
```

{% endtab %}

{% tab title="Python" %}

```python
import json
import asyncio
import aiohttp

async def get_block(rpc_url):
    try:
        payload = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "getBlock",
            "params": [
                355184627,
                {
                    "encoding": "jsonParsed",
                    "transactionDetails": "full",
                    "rewards": True,
                    "maxSupportedTransactionVersion": 0
                }
            ]
        }
        
        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_block(RPC_URL)

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

{% endtab %}
{% endtabs %}

**Example Response**

```json
{
  "jsonrpc": "2.0",
  "result": {
    "blockHeight": 428,
    "blockTime": null,
    "blockhash": "3Eq21vXNB5s86c62bVuUfTeaMif1N2kUqRPBmGRJhyTA",
    "parentSlot": 429,
    "previousBlockhash": "mfcyqEXB3DnHXki6KjjmZck6YjmZLvpAByy2fj4nh6B",
    "transactions": [
      {
        "meta": {
          "err": null,
          "fee": 5000,
          "innerInstructions": [],
          "logMessages": [],
          "postBalances": [499998932500, 26858640, 1, 1, 1],
          "postTokenBalances": [],
          "preBalances": [499998937500, 26858640, 1, 1, 1],
          "preTokenBalances": [],
          "rewards": null,
          "status": {
            "Ok": null
          }
        },
        "transaction": {
          "message": {
            "accountKeys": [
              "3UVYmECPPMZSCqWKfENfuoTv51fTDTWicX9xmBD2euKe",
              "AjozzgE83A3x1sHNUR64hfH7zaEBWeMaFuAN9kQgujrc",
              "SysvarS1otHashes111111111111111111111111111",
              "SysvarC1ock11111111111111111111111111111111",
              "Vote111111111111111111111111111111111111111"
            ],
            "header": {
              "numReadonlySignedAccounts": 0,
              "numReadonlyUnsignedAccounts": 3,
              "numRequiredSignatures": 1
            },
            "instructions": [
              {
                "accounts": [1, 2, 3, 0],
                "data": "37u9WtQpcm6ULa3WRQHmj49EPs4if7o9f1jSRVZpm2dvihR9C8jY4NqEwXUbLwx15HBSNcP1",
                "programIdIndex": 4
              }
            ],
            "recentBlockhash": "mfcyqEXB3DnHXki6KjjmZck6YjmZLvpAByy2fj4nh6B"
          },
          "signatures": [
            "2nBhEBYYvfaAe16UMNqRHre4YNSskvuYgx3M6E4JP1oDYvZEJHvoPzyUidNgNX5r9sTyN1J9UxtbCXy2rqYcuyuv"
          ]
        }
      }
    ]
  },
  "id": 1
}
```

**Developer Tips**

* **Slot vs. Block Height**\
  The `getBlock` method accepts a **slot number**, not a block height. While slots are generally sequential, some may be skipped by the validator leader. To get the actual block sequence number, refer to the `blockHeight` field in the response.
* **`maxSupportedTransactionVersion` Is Crucial**\
  To retrieve blocks containing **versioned transactions** (now standard and using **Address Lookup Tables**), you must specify:\
  `"maxSupportedTransactionVersion": 0`\
  Omitting this may lead to errors when querying modern blocks.
* **Choosing `transactionDetails` Level**:
  * `full`: For comprehensive analysis—returns the most complete data including metadata.
  * `signatures`: Best for listing only transaction signatures in a block.
  * `accounts`: A good middle ground—lists involved accounts without full instructions.
  * `none`: Use when you only need high-level block metadata like `blockhash` or `rewards`.
* **Use `jsonParsed` for Encoding**\
  When requesting transaction details, `jsonParsed` is the recommended format. It provides a structured, human-readable JSON output and supports address resolution from Lookup Tables. Avoid using `json` (deprecated), as it lacks modern feature support.
* **Block Unavailability Handling**\
  A `null` response can mean:
  * The slot was **skipped**.
  * The block hasn’t reached the **requested commitment level**.
  * The RPC node (e.g., **CoinVera**) has **pruned** the block due to ledger limits—common with older historical data.
* **Include Rewards When Needed**\
  To retrieve block reward distribution info (e.g., for validators and stakers), set:\
  `"rewards": true`\
  This increases response size but is essential for full reward visibility.


---

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