# getBlocks

The `getBlocks` RPC method returns a list of **confirmed block slot numbers** between a specified `start_slot` and an optional `end_slot`. It’s useful when you need to know which blocks were confirmed within a certain range—without fetching full block contents.

***

#### ✅ Common Use Cases

* **Identify Confirmed Blocks in a Range**\
  Quickly fetch all block slots that were successfully confirmed between two slots.
* **Iterate Over Confirmed Slots**\
  Use the list of confirmed slots to loop through and fetch detailed block data later via `getBlock`.
* **Audit Block Presence**\
  Verify whether blocks exist across a specific slot range for basic validation or reporting.

***

#### 🛠 Request Parameters

`getBlocks` accepts the following parameters:

* **`start_slot`** (*u64, required*):\
  The first slot of the range (inclusive).
* **`end_slot`** (*u64, optional*):\
  The last slot of the range (inclusive).\
  If omitted, the method will return confirmed blocks up to the latest available slot.\
  ⚠️ The range between `start_slot` and `end_slot` must not exceed **500,000 slots**.
* **`commitment`** (*string, optional*):\
  Commitment level passed as a field in a config object. If omitted, the node's default is used. Typical values:
  * `processed`
  * `confirmed`
  * `finalized`

***

#### 📦 Response Structure

The `result` field will be an array of slot numbers (as unsigned 64-bit integers), each representing a **confirmed block**.

```json
[355104000, 355104001, 355104002, 355104003, 355104004]
```

This means blocks were confirmed at these slots—note that some slots may be skipped (e.g., 355104004).

#### 💡 Examples

**1. Get Confirmed Blocks in a Slot Range**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getBlocks",
  "params": [355104000, 355104001]
}
```

2. **Get Blocks from Start Slot to Latest Confirmed Slot**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getBlocks",
  "params": [355104000]
}

```

3. **Get Blocks Using a Specific Commitment Level**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getBlocks",
  "params": [355104000, 355104001, { "commitment": "confirmed" }]
}
```

**Code Examples**

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

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

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

getBlocks(RPC_URL);
```

{% endtab %}

{% tab title="Python" %}

```python
import json
import asyncio
import aiohttp

async def get_blocks(rpc_url):
    try:
        payload = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "getBlocks",
            "params": [
                355104000,
                355104001,
                {"commitment": "confirmed"}
            ]
        }
        
        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_blocks(RPC_URL)

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

{% endtab %}
{% endtabs %}

**Example Response**

```json
{
  "jsonrpc": "2.0",
  "result": [
    355104000,
    355104001
  ],
  "id": 1
}
```

#### 🧠 Developer Tips

* **Range Limit Enforcement**\
  The maximum allowed range is **500,000 slots**. Splitting larger ranges into chunks is required for historical scans.
* **Ledger Retention Differences**\
  Very old slot data may not be available on all RPC nodes. Empty arrays or errors might be returned for out-of-retention queries.
* **Consistency with Commitment**\
  Block confirmation status can vary depending on the `commitment` level and the specific RPC node queried—especially for recent slots.
* **Use as a Prefilter for `getBlock`**\
  `getBlocks` is often used to determine which blocks exist before making multiple calls to `getBlock` for deeper inspection.
* **Effective Pagination Strategy**\
  For scanning long history segments, implement pagination by dividing your range into multiple sub-ranges of 500,000 slots or fewer.


---

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