eth_subscribe - Polygon
Example code for the eth_subscribe json-rpc method. Сomplete guide on how to use eth_subscribe json-rpc in GetBlock.io Web3 documentation.
The eth_subscribe method creates a subscription over WebSocket to receive real-time notifications for new blocks, pending transactions, or logs matching specified criteria.
Parameters
subscriptionType
string
Yes
Subscription type: "newHeads", "newPendingTransactions", "logs"
filterObject
object
No
Filter options for log subscriptions
Request
# This method requires WebSocket connection
wscat -c wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/
> {"jsonrpc":"2.0","method":"eth_subscribe","params":["newheads"],"id":"getblock.io"}const WebSocket = require('ws');
const ws = new WebSocket('wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/');
ws.on('open', () => {
ws.send(JSON.stringify({
jsonrpc: '2.0',
method: 'eth_subscribe',
params: ['newHeads'],
id: 'getblock.io'
}));
});
ws.on('message', (data) => {
console.log(JSON.parse(data));
});import asyncio
import websockets
import json
async def unsubscribe():
uri = "wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/"
async with websockets.connect(uri) as ws:
payload = {
"jsonrpc": "2.0",
"method": "eth_subscribe",
"params": ["newHeads"],
"id": "getblock.io"
}
await ws.send(json.dumps(payload))
response = await ws.recv()
print(json.loads(response))
asyncio.run(unsubscribe())Response
{
"jsonrpc": "2.0",
"id": "getblock.io",
"result": "0x9cef478923ff08bf67fde6c64013158d"
}Response Parameters
jsonrpc
string
JSON-RPC version (2.0)
id
string
Request identifier
result
varies
Subscription ID for receiving notifications
Use Case
The eth_subscribe method is useful for:
Real-time block monitoring
Event streaming
Live transaction tracking
Error Handling
403
Forbidden
Missing or invalid ACCESS-TOKEN
-32600
Invalid Request
Malformed request body
-32602
Invalid params
Invalid method parameters
Web3 Integration
Last updated
Was this helpful?