# getBlockHeight

The `getBlockHeight` RPC method offers a quick way to query the current **block height** of a Solana node. Block height is defined as the total number of blocks processed since the genesis block (slot 0). This method is ideal for tracking the chain’s progression and aligning on-chain data with specific block intervals.

***

#### **Common Use Cases**

* **Monitoring Chain Progression**\
  Repeatedly call `getBlockHeight` to track how fast the blockchain is advancing.
* **Capturing a Snapshot of Chain Length**\
  Retrieve the current block height at a particular commitment level to reference the chain’s state at a specific point.
* **Cross-Referencing Data**\
  Use the block height as a timeline marker when correlating events, logs, or transactions across various tools and datasets.

***

#### **Parameters**

You can call `getBlockHeight` with or without a configuration object:

* **`config`** (*object, optional*):\
  Optional fields to refine the request:
  * **`commitment`** (*string*):\
    Defines the confirmation level of the block height being returned. Defaults to `finalized`.
    * `finalized` – Highest assurance of confirmation.
    * `confirmed` – Voted on by a supermajority of validators.
    * `processed` – Most recent block (may still change).
  * **`minContextSlot`** (*number*):\
    Ensures the response is from a slot greater than or equal to this value. Useful for consistency and timeline alignment.

If no parameters are passed, the request defaults to the `finalized` commitment.

***

#### **Response**

The JSON-RPC `result` field will return:

* **`blockHeight`** (*number*):\
  An unsigned integer representing the height of the latest confirmed block.

***

#### **Example: Fetching the Current Block Height**

Here’s how to request the current block height from the CoinVera Mainnet RPC:

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

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

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

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

getBlockHeight(RPC_URL);
```

{% endtab %}

{% tab title="Python" %}

```python
import json
import asyncio
import aiohttp

async def get_block_height(rpc_url):
    try:
        payload = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "getBlockHeight",
            "params": []
        }
        
        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_height(RPC_URL)

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

{% endtab %}
{% endtabs %}

If you don’t need any custom configuration, you can also call it with no parameters:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getBlockHeight"
}

```

**Example Response**

```json
{
  "jsonrpc": "2.0",
  "result": 333387608,
  "id": 1
}
```

**Developer Tips**

* **Commitment Levels Matter**\
  The block height returned by `getBlockHeight` depends on the **commitment level** used:
  * `finalized` provides the most stable and reliable block height.
  * `processed` offers the most up-to-date value, but it may not be confirmed and could change.
* **Use `minContextSlot` for Consistency**\
  When tracking specific slots, setting `minContextSlot` ensures that the block height returned is based on a state at or after that slot—ideal for maintaining temporal consistency in your application logic.
* **Block Height ≠ Slot Number**\
  It's important to distinguish between **block height** and **slot number**:
  * A **slot** is a time window where a validator may produce a block.
  * **Skipped slots** occur when no block is produced.
  * **Block height** only increments when a block is actually produced.
* **Lightweight Chain Health Monitoring**\
  Although basic, `getBlockHeight` is a quick and effective method to track **chain progression** or include in **synchronization and health checks** for validators, dApps, or backend systems.


---

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