A simple Python script that continuously fetches the latest block number from an Ethereum-compatible RPC endpoint.
Useful for monitoring network synchronization status or verifying RPC node responsiveness.
This script connects to an RPC endpoint and retrieves the current block height using the eth_blockNumber method from the JSON-RPC API.
It then prints the latest block number in decimal format.
import requests
import time
# RPC endpoint for connecting to the Ethereum-compatible network
RPC_URL = "https://eth.llamarpc.com"
def get_latest_block_number():
"""
Sends a JSON-RPC request to the node to retrieve the latest block number.
Returns the block number as an integer.
"""
payload = {
"jsonrpc": "2.0", # JSON-RPC protocol version
"method": "eth_blockNumber", # Method to get the latest block number
"params": [], # No parameters required for this method
"id": 1 # Request ID (for tracking)
}
try:
# Send an HTTP POST request to the RPC endpoint
response = requests.post(RPC_URL, json=payload)
response.raise_for_status() # Raise an exception for non-200 responses
data = response.json() # Parse the JSON response
# Extract the hexadecimal block number, e.g. "0x10d4f"
block_hex = data.get("result", "0x0")
# Convert hexadecimal to integer
block_number = int(block_hex, 16)
return block_number
except Exception as e:
# Print any errors encountered during the request
print("Error fetching block number:", e)
return None
if __name__ == "__main__":
# Continuous loop: fetch and print the latest block height
while True:
block_number = get_latest_block_number()
if block_number is not None:
print(f"Latest block height: {block_number}")
# Adjust sleep time as needed to reduce RPC load (in seconds)
time.sleep(0)