WebSocket
This guide demonstrates how to use WebSocket connections with Starknet using Starknet.go.
Prerequisites
- Go 1.18 or higher
- Starknet.go installed
- A Starknet WebSocket URL
- Account with private key (optional)
Code Example
package main
import (
"context"
"fmt"
"log"
"github.com/NethermindEth/starknet.go"
)
func main() {
// Initialize WebSocket client
client, err := starknet.NewWebSocketClient("wss://your-starknet-node/ws")
if err != nil {
log.Fatal(err)
}
defer client.Close()
// Subscribe to new blocks
blocks, err := client.SubscribeNewHeads(context.Background())
if err != nil {
log.Fatal(err)
}
// Subscribe to pending transactions
txs, err := client.SubscribePendingTransactions(context.Background())
if err != nil {
log.Fatal(err)
}
// Process incoming messages
go func() {
for {
select {
case block := <-blocks:
fmt.Printf("New block: %v\n", block)
case tx := <-txs:
fmt.Printf("New pending transaction: %v\n", tx)
}
}
}()
// Keep the connection alive
select {}
}
Explanation
- Initialize the WebSocket client
- Subscribe to desired events (new blocks, pending transactions)
- Process incoming messages in a separate goroutine
- Keep the connection alive
Best Practices
- Handle connection errors gracefully
- Implement reconnection logic
- Use appropriate context timeouts
- Process messages concurrently
- Clean up resources properly
- Monitor connection health
Common Issues
- Connection drops
- Network latency
- Message queue overflow
- Resource leaks
- Authentication errors
- Rate limiting