# getLatestBlockhash

The `getLatestBlockhash` RPC method is fundamental for transaction preparation and submission on the Solana network. It retrieves the most recently processed blockhash and the last block height at which that blockhash remains valid. Since every Solana transaction must reference a recent blockhash, this mechanism plays a crucial role in preventing replay attacks, especially on forked chains.

> 💡 **Note:** Available in `solana-core` v1.9 and newer. For older nodes (v1.8 or below), use `getRecentBlockhash`.

***

**🔍 Common Use Cases**

* **Transaction Construction:** Retrieve a fresh blockhash to include in new transactions before signing and submitting them.
* **Managing Transaction Expiry:** Use `lastValidBlockHeight` to determine how long a transaction will remain valid before expiring.
* **Manual Preflight Checks:** While `simulateTransaction` handles this automatically, developers may opt to manually fetch a blockhash for custom transaction preparation and simulation.

***

**🧾 Request Parameters**

This method optionally accepts a configuration object:

* `commitment` *(string, optional)*: The commitment level for the query. Common values include `confirmed` or `finalized` to ensure a stable blockhash.
* `minContextSlot` *(integer, optional)*: Ensures that the blockhash is retrieved from a ledger state that has processed at least this slot.

***

**📦 Response Structure**

The `result` object includes:

* `blockhash` *(string)*: A base-58 encoded string representing the latest blockhash.
* `lastValidBlockHeight` *(u64)*: The final block height where this blockhash remains valid.
* `context.slot` *(u64)*: The slot at which this data was retrieved.

***

**💡 Examples**

1. **Get the Latest Blockhash (Default Commitment)**\
   Fetches the most recent blockhash using the node’s default commitment level.

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

1. **Get the Latest Blockhash with `confirmed` Commitment**\
   Explicitly requests a blockhash with `confirmed` commitment for more stability.

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

***

**Code Examples**

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

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

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

getLatestBlockhash(RPC_URL);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

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

{% endtab %}
{% endtabs %}

**Example Response**

```json
{
  "jsonrpc": "2.0",
  "result": {
    "context": {
      "apiVersion": "2.2.16",
      "slot": 355365707
    },
    "value": {
      "blockhash": "GUyGdZk1ghy44vBXaqYkomjUqGnTZEgrPCvCkEETD3xB",
      "lastValidBlockHeight": 333557572
    }
  },
  "id": 1
}
```

***

**🛠 Developer Tips**

* **Blockhash Expiration:** A blockhash typically remains valid for \~2 minutes, though this can vary. Always re-fetch a blockhash if your transaction hasn't been submitted promptly.
* **Commitment Strategy:** Use `finalized` for critical, irreversible transactions. For responsiveness, `confirmed` provides a balance of speed and reliability.
* **Transaction Fees:** This method only returns the blockhash, not fees. Make sure you calculate and attach appropriate fees separately.
* **Retries:** If your transaction expires due to an outdated blockhash, re-sign it with a new one and submit again.

***

This guide walks you through effectively using the `getLatestBlockhash` method — an essential step in ensuring your Solana transactions are fresh, valid, and ready to land.


---

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