hl_getLatestBlockNumber
Return the highest block number currently available for a given stream.
When to Use This Method#
hl_getLatestBlockNumber is essential for:
- Synchronization — Determine the current head before fetching batch blocks
- Polling — Check for new blocks at regular intervals
- Catch-up Logic — Calculate how far behind your consumer is
- Health Monitoring — Verify the data pipeline is advancing
Request#
Endpoint#
POST https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com/<API-KEY>/hypercore
Headers#
| Header | Value | Required |
|---|---|---|
Content-Type | application/json | Yes |
Parameters#
This method accepts both positional and named parameters.
Positional params:
| Position | Type | Required | Description |
|---|---|---|---|
[0] | string | Yes | Data stream. Must be "trades" |
Named params:
| Field | Type | Required | Description |
|---|---|---|---|
stream | string | Yes | Data stream. Must be "trades" |
Example Request (positional params)#
{
"jsonrpc": "2.0",
"method": "hl_getLatestBlockNumber",
"params": ["trades"],
"id": 1
}
Example Request (named params)#
{
"jsonrpc": "2.0",
"method": "hl_getLatestBlockNumber",
"params": { "stream": "trades" },
"id": 1
}
Response#
Success Response#
{
"jsonrpc": "2.0",
"result": 907628737,
"id": 1
}
The result is a bare integer representing the highest block number across all fill files.
Response Fields#
| Field | Type | Description |
|---|---|---|
result | integer | The highest block number available for the stream |
Error Response#
{
"jsonrpc": "2.0",
"error": { "code": -32602, "message": "unsupported stream" },
"id": 1
}
Code Examples#
- cURL
- JavaScript
- Python
- Go
curl -s https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com/<API-KEY>/hypercore \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"method": "hl_getLatestBlockNumber",
"params": ["trades"],
"id": 1
}' | jq .
const ENDPOINT = 'https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com/<API-KEY>/hypercore';
async function getLatestBlockNumber(stream = 'trades') {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'hl_getLatestBlockNumber',
params: [stream],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`JSON-RPC error ${data.error.code}: ${data.error.message}`);
}
return data.result;
}
// Usage
const latestBlock = await getLatestBlockNumber();
console.log(`Latest block: ${latestBlock}`);
import requests
ENDPOINT = 'https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com/<API-KEY>/hypercore'
def get_latest_block_number(stream: str = 'trades') -> int:
"""Get the highest block number for the given stream."""
response = requests.post(
ENDPOINT,
json={
'jsonrpc': '2.0',
'method': 'hl_getLatestBlockNumber',
'params': [stream],
'id': 1
},
headers={'Content-Type': 'application/json'},
timeout=10
)
response.raise_for_status()
data = response.json()
if 'error' in data:
raise Exception(f"JSON-RPC error {data['error']['code']}: {data['error']['message']}")
return data['result']
# Usage
latest = get_latest_block_number()
print(f"Latest block: {latest}")
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com/<API-KEY>/hypercore"
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params"`
ID int `json:"id"`
}
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
Result int64 `json:"result"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
ID int `json:"id"`
}
func getLatestBlockNumber() (int64, error) {
reqBody, _ := json.Marshal(JSONRPCRequest{
JSONRPC: "2.0",
Method: "hl_getLatestBlockNumber",
Params: []string{"trades"},
ID: 1,
})
resp, err := http.Post(Endpoint, "application/json", bytes.NewBuffer(reqBody))
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result JSONRPCResponse
if err := json.Unmarshal(body, &result); err != nil {
return 0, err
}
if result.Error != nil {
return 0, fmt.Errorf("JSON-RPC error %d: %s", result.Error.Code, result.Error.Message)
}
return result.Result, nil
}
func main() {
latest, err := getLatestBlockNumber()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Latest block: %d\n", latest)
}
Common Use Cases#
1. Poll for New Blocks#
Check for new data at regular intervals:
async function pollForNewBlocks(callback, intervalMs = 5000) {
let lastSeen = await getLatestBlockNumber();
console.log(`Starting poll from block ${lastSeen}`);
setInterval(async () => {
const latest = await getLatestBlockNumber();
if (latest > lastSeen) {
console.log(`New blocks: ${lastSeen + 1} to ${latest}`);
callback(lastSeen + 1, latest);
lastSeen = latest;
}
}, intervalMs);
}
// Usage
pollForNewBlocks((from, to) => {
console.log(`Processing blocks ${from}–${to}`);
});
2. Calculate Consumer Lag#
Monitor how far behind a consumer is:
def check_lag(consumer_block: int) -> dict:
latest = get_latest_block_number()
lag = latest - consumer_block
return {
'consumer_block': consumer_block,
'latest_block': latest,
'lag_blocks': lag,
'status': 'healthy' if lag < 100 else 'behind'
}
Error Handling#
| Error Code | Cause | Solution |
|---|---|---|
| -32602 | Unsupported stream | Use "trades" as the stream value |
| -32600 | Array-wrapped request | Send a single JSON-RPC object, not an array |
| -32700 | Malformed JSON | Validate your request JSON |
Best Practices#
- Poll responsibly — Don't poll more frequently than every few seconds
- Use as a cursor — Combine with
hl_getBatchBlocksfor sequential data retrieval - Monitor lag — Track the difference between your consumer position and the latest block
- Handle stale data — If the latest block number hasn't advanced, the upstream may be paused
Related Methods#
- hl_getBatchBlocks — Retrieve fill blocks in a range
Query HyperCore fill data with Dwellir's JSON-RPC API. Get your API key →