Cuckoo Network WebSocket Guide
WebSocket connections provide real-time, bidirectional communication with the Cuckoo Network blockchain, enabling your applications to receive instant updates for new blocks, transactions, and smart contract events without polling.
Why Use WebSockets?
Advantages over HTTP Polling
- Real-time Updates: Instant notifications when events occur
- Lower Latency: No polling delays
- Reduced Bandwidth: Only receive data when it changes
- Better Performance: Persistent connection reduces overhead
- Event-Driven: React to blockchain events as they happen
Common Use Cases
- Trading Applications: Real-time price feeds and order book updates
- DeFi Dashboards: Live liquidity and yield changes
- NFT Marketplaces: Instant sale and listing notifications
- Wallet Applications: Balance updates and transaction confirmations
- Analytics Platforms: Real-time blockchain metrics
Connection Setup
WebSocket Endpoints
wss://api.blockeden.xyz/cuckoo/mainnet/${accessKey}
wss://ethereum-sepolia.blockeden.xyz/<your-api-key>
wss://polygon-mainnet.blockeden.xyz/<your-api-key>
wss://arbitrum-mainnet.blockeden.xyz/<your-api-key>
Basic Connection
JavaScript (Browser/Node.js)
const ws = new WebSocket('wss://api.blockeden.xyz/cuckoo/mainnet/${accessKey}');
ws.onopen = function(event) {
console.log('WebSocket connected');
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
ws.onerror = function(error) {
console.error('WebSocket error:', error);
};
ws.onclose = function(event) {
console.log('WebSocket closed:', event.code, event.reason);
};
Python
import asyncio
import websockets
import json
async def connect():
uri = "wss://api.blockeden.xyz/cuckoo/mainnet/${accessKey}"
async with websockets.connect(uri) as websocket:
print("WebSocket connected")
# Subscribe to new heads
subscribe_msg = {
"jsonrpc": "2.0",
"method": "eth_subscribe",
"params": ["newHeads"],
"id": 1
}
await websocket.send(json.dumps(subscribe_msg))
# Listen for messages
async for message in websocket:
data = json.loads(message)
print(f"Received: {data}")
# Run the connection
asyncio.run(connect())
Go
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gorilla/websocket"
)
type SubscriptionRequest struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params []string `json:"params"`
ID int `json:"id"`
}
func main() {
url := "wss://api.blockeden.xyz/cuckoo/mainnet/${accessKey}"
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
log.Fatal("dial:", err)
}
defer conn.Close()
// Subscribe to new heads
req := SubscriptionRequest{
JSONRPC: "2.0",
Method: "eth_subscribe",
Params: []string{"newHeads"},
ID: 1,
}
if err := conn.WriteJSON(req); err != nil {
log.Fatal("write:", err)
}
// Read messages
for {
var msg map[string]interface{}
if err := conn.ReadJSON(&msg); err != nil {
log.Fatal("read:", err)
}
fmt.Printf("Received: %+v\n", msg)
}
}
Subscription Types
1. New Block Headers (newHeads)
Subscribe to new block headers as they're mined.
const subscribeToNewHeads = () => {
const subscription = {
jsonrpc: '2.0',
method: 'eth_subscribe',
params: ['newHeads'],
id: 1
};
ws.send(JSON.stringify(subscription));
};
// Handle new block headers
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.method === 'eth_subscription' && data.params.subscription) {
const blockHeader = data.params.result;
console.log('New block:', {
number: parseInt(blockHeader.number, 16),
hash: blockHeader.hash,
timestamp: parseInt(blockHeader.timestamp, 16),
gasUsed: parseInt(blockHeader.gasUsed, 16),
gasLimit: parseInt(blockHeader.gasLimit, 16)
});
}
};
2. Pending Transactions (newPendingTransactions)
Subscribe to new pending transactions in the mempool.
const subscribeToPendingTransactions = () => {
const subscription = {
jsonrpc: '2.0',
method: 'eth_subscribe',
params: ['newPendingTransactions'],
id: 2
};
ws.send(JSON.stringify(subscription));
};
// Handle pending transactions
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.method === 'eth_subscription' && data.params.subscription) {
const txHash = data.params.result;
console.log('New pending transaction:', txHash);
// Optionally fetch full transaction details
fetchTransactionDetails(txHash);
}
};
3. Smart Contract Events (logs)
Subscribe to specific smart contract events using log filters.
const subscribeToContractEvents = (contractAddress, topics) => {
const subscription = {
jsonrpc: '2.0',
method: 'eth_subscribe',
params: [
'logs',
{
address: contractAddress,
topics: topics
}
],
id: 3
};
ws.send(JSON.stringify(subscription));
};
// Subscribe to ERC-20 Transfer events
const ERC20_TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
subscribeToContractEvents('0xA0b86a33E6c0e4A2a2a5FB1C6A6D6a30BF8b6B3a', [ERC20_TRANSFER_TOPIC]);
// Handle contract events
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.method === 'eth_subscription' && data.params.subscription) {
const log = data.params.result;
console.log('Contract event:', {
address: log.address,
topics: log.topics,
data: log.data,
blockNumber: parseInt(log.blockNumber, 16),
transactionHash: log.transactionHash
});
}
};
4. Synchronized Blocks (syncing)
Subscribe to synchronization status updates.
const subscribeToSyncing = () => {
const subscription = {
jsonrpc: '2.0',
method: 'eth_subscribe',
params: ['syncing'],
id: 4
};
ws.send(JSON.stringify(subscription));
};
// Handle sync status
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.method === 'eth_subscription' && data.params.subscription) {
const syncStatus = data.params.result;
if (syncStatus === false) {
console.log('Node is fully synchronized');
} else {
console.log('Sync status:', {
startingBlock: parseInt(syncStatus.startingBlock, 16),
currentBlock: parseInt(syncStatus.currentBlock, 16),
highestBlock: parseInt(syncStatus.highestBlock, 16)
});
}
}
};