WebSocket Connection Guide
Connect directly to Unit Network's Substrate node for real-time blockchain data, event subscriptions, and RPC calls.
Connection
wss://mainnet-unit.com:443
This is a standard Substrate JSON-RPC WebSocket endpoint compatible with all Substrate tooling.
Quick Start
JavaScript (Browser / Node.js)
const ws = new WebSocket('wss://mainnet-unit.com:443');
ws.onopen = () => {
console.log('Connected to Unit Network');
// Subscribe to new blocks
ws.send(JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'chain_subscribeNewHeads',
params: []
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.params?.result) {
console.log('New block:', data.params.result.number);
}
};
Using Polkadot.js API (Recommended)
import { ApiPromise, WsProvider } from '@polkadot/api';
const provider = new WsProvider('wss://mainnet-unit.com:443');
const api = await ApiPromise.create({ provider });
// Get chain info
const chain = await api.rpc.system.chain();
const lastHeader = await api.rpc.chain.getHeader();
console.log(`${chain}: block #${lastHeader.number}`);
// Subscribe to new blocks
const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => {
console.log(`Block #${header.number}`);
});
Common RPC Methods
System
| Method | Description |
|---|---|
system_chain | Chain name |
system_name | Node name |
system_version | Node version |
system_health | Node health status |
system_properties | Chain properties (decimals, token symbol) |
Chain
| Method | Description |
|---|---|
chain_getHeader | Latest block header |
chain_getBlock | Full block data |
chain_getBlockHash | Block hash by number |
chain_subscribeNewHeads | Subscribe to new blocks |
State
| Method | Description |
|---|---|
state_getStorage | Read storage by key |
state_queryStorageAt | Query multiple storage keys |
state_getMetadata | Chain metadata (pallet info) |
state_getRuntimeVersion | Runtime version |
Subscribing to Events
// Subscribe to all system events
const api = await ApiPromise.create({ provider });
api.query.system.events((events) => {
events.forEach(({ event }) => {
console.log(`${event.section}.${event.method}: ${event.data}`);
});
});
Performance
WebSocket subscriptions are far more efficient than polling the REST API. Use subscriptions for any real-time data needs.
Connection Best Practices
- Reconnect on disconnect — WebSocket connections can drop; implement exponential backoff
- Unsubscribe when done — Call the unsubscribe function to prevent memory leaks
- Use Polkadot.js — It handles reconnection, type decoding, and subscription management
- Rate limit subscriptions — Don't create hundreds of concurrent subscriptions
Related Pages
- REST API Reference — HTTP endpoints
- SDK Integration — Full Polkadot.js setup guide
- Architecture Overview — Substrate chain details