StreamBlocks gRPC Method
Please note that this method is metered based on data consumption at 0.1 MB = 10 API credits.
Parameters
timestamp
integer
Loading...
Returns
stream
stream<Block>
Loading...
data_json
string
Loading...
abci_block.round
integer
Loading...
abci_block.parent_round
integer
Loading...
abci_block.time
string
Loading...
abci_block.proposer
string
Loading...
abci_block.hardfork
object
Loading...
abci_block.signed_action_bundles
array
Loading...
resps
object
Loading...
Request
1package main23import (4"context"5"crypto/tls"6"encoding/json"7"fmt"8"io"9"log"10"time"1112"google.golang.org/grpc"13"google.golang.org/grpc/credentials"14"google.golang.org/grpc/metadata"1516pb "hyperliquid-grpc-go/pb"17)1819const (20// Using Quicknode endpoint21grpcEndpoint = "your-endpoint.hype-mainnet.quiknode.pro:10000"22authToken = "your-auth-token"23)2425// Create gRPC connection with TLS26func createConnection() (*grpc.ClientConn, error) {27tlsConfig := &tls.Config{28InsecureSkipVerify: false, // Set to true only for testing29}30creds := credentials.NewTLS(tlsConfig)3132conn, err := grpc.Dial(33grpcEndpoint,34grpc.WithTransportCredentials(creds),35grpc.WithDefaultCallOptions(36grpc.MaxCallRecvMsgSize(100*1024*1024), // 100MB37),38)3940return conn, err41}4243// Create context with auth metadata44func createContext() context.Context {45md := metadata.Pairs("x-token", authToken)46return metadata.NewOutgoingContext(context.Background(), md)47}484950// Stream blocks51func streamBlocks(client pb.BlockStreamingClient) error {52ctx := createContext()5354stream, err := client.StreamBlocks(ctx, &pb.Timestamp{55Timestamp: time.Now().UnixMilli(),56})57if err != nil {58return fmt.Errorf("failed to stream blocks: %v", err)59}6061log.Println("š Starting blocks stream...")6263for {64block, err := stream.Recv()65if err == io.EOF {66log.Println("Block stream ended")67break68}69if err != nil {70return fmt.Errorf("receive error: %v", err)71}7273var blockData map[string]interface{}74if err := json.Unmarshal([]byte(block.DataJson), &blockData); err != nil {75log.Printf("ā ļø Failed to parse block: %v", err)76continue77}7879if abciBlock, ok := blockData["abci_block"].(map[string]interface{}); ok {80if round, ok := abciBlock["round"].(float64); ok {81log.Printf("š§± Received block round: %.0f", round)82}83}84}8586return nil87}888990// Interactive menu91func runInteractiveMenu(conn *grpc.ClientConn) {92blockClient := pb.NewBlockStreamingClient(conn)9394fmt.Println("\nš Connected successfully!")95fmt.Println("\nAvailable stream:")96fmt.Println("1. Stream blocks")97fmt.Println("2. Exit")9899for {100fmt.Print("\nSelect option (1-2): ")101var choice string102fmt.Scanln(&choice)103104switch choice {105case "1":106if err := streamBlocks(blockClient); err != nil {107log.Printf("ā Block stream error: %v", err)108}109case "2":110fmt.Println("š Goodbye!")111return112default:113fmt.Println("ā Invalid choice. Please select 1-2.")114}115}116}117118func main() {119// Create connection120conn, err := createConnection()121if err != nil {122log.Fatalf("ā Failed to connect: %v", err)123}124defer conn.Close()125126fmt.Printf("Connected to: %s\n", grpcEndpoint)127128// Run interactive menu129runInteractiveMenu(conn)130}
1package main23import (4"context"5"crypto/tls"6"encoding/json"7"fmt"8"io"9"log"10"time"1112"google.golang.org/grpc"13"google.golang.org/grpc/credentials"14"google.golang.org/grpc/metadata"1516pb "hyperliquid-grpc-go/pb"17)1819const (20// Using Quicknode endpoint21grpcEndpoint = "your-endpoint.hype-mainnet.quiknode.pro:10000"22authToken = "your-auth-token"23)2425// Create gRPC connection with TLS26func createConnection() (*grpc.ClientConn, error) {27tlsConfig := &tls.Config{28InsecureSkipVerify: false, // Set to true only for testing29}30creds := credentials.NewTLS(tlsConfig)3132conn, err := grpc.Dial(33grpcEndpoint,34grpc.WithTransportCredentials(creds),35grpc.WithDefaultCallOptions(36grpc.MaxCallRecvMsgSize(100*1024*1024), // 100MB37),38)3940return conn, err41}4243// Create context with auth metadata44func createContext() context.Context {45md := metadata.Pairs("x-token", authToken)46return metadata.NewOutgoingContext(context.Background(), md)47}484950// Stream blocks51func streamBlocks(client pb.BlockStreamingClient) error {52ctx := createContext()5354stream, err := client.StreamBlocks(ctx, &pb.Timestamp{55Timestamp: time.Now().UnixMilli(),56})57if err != nil {58return fmt.Errorf("failed to stream blocks: %v", err)59}6061log.Println("š Starting blocks stream...")6263for {64block, err := stream.Recv()65if err == io.EOF {66log.Println("Block stream ended")67break68}69if err != nil {70return fmt.Errorf("receive error: %v", err)71}7273var blockData map[string]interface{}74if err := json.Unmarshal([]byte(block.DataJson), &blockData); err != nil {75log.Printf("ā ļø Failed to parse block: %v", err)76continue77}7879if abciBlock, ok := blockData["abci_block"].(map[string]interface{}); ok {80if round, ok := abciBlock["round"].(float64); ok {81log.Printf("š§± Received block round: %.0f", round)82}83}84}8586return nil87}888990// Interactive menu91func runInteractiveMenu(conn *grpc.ClientConn) {92blockClient := pb.NewBlockStreamingClient(conn)9394fmt.Println("\nš Connected successfully!")95fmt.Println("\nAvailable stream:")96fmt.Println("1. Stream blocks")97fmt.Println("2. Exit")9899for {100fmt.Print("\nSelect option (1-2): ")101var choice string102fmt.Scanln(&choice)103104switch choice {105case "1":106if err := streamBlocks(blockClient); err != nil {107log.Printf("ā Block stream error: %v", err)108}109case "2":110fmt.Println("š Goodbye!")111return112default:113fmt.Println("ā Invalid choice. Please select 1-2.")114}115}116}117118func main() {119// Create connection120conn, err := createConnection()121if err != nil {122log.Fatalf("ā Failed to connect: %v", err)123}124defer conn.Close()125126fmt.Printf("Connected to: %s\n", grpcEndpoint)127128// Run interactive menu129runInteractiveMenu(conn)130}
1const grpc = require('@grpc/grpc-js');2const protoLoader = require('@grpc/proto-loader');3const path = require('path');45// Configuration6const GRPC_ENDPOINT = 'your-endpoint.hype-mainnet.quiknode.pro:10000';7const AUTH_TOKEN = 'your-auth-token';89// Load proto file10const packageDefinition = protoLoader.loadSync(11path.join(__dirname, 'proto/streaming.proto'),12{13keepCase: true,14longs: String,15enums: String,16defaults: true,17oneofs: true,18}19);2021const hyperliquidProto = grpc.loadPackageDefinition(packageDefinition).hyperliquid;2223// Create gRPC client with TLS24function createClient() {25const credentials = grpc.credentials.createSsl();2627const client = new hyperliquidProto.Streaming(28GRPC_ENDPOINT,29credentials,30{31'grpc.max_receive_message_length': 100 * 1024 * 1024, // 100MB32}33);3435return client;36}3738// Create metadata with auth token39function createMetadata() {40const metadata = new grpc.Metadata();41metadata.add('x-token', AUTH_TOKEN);42return metadata;43}4445// Test connectivity with ping46function testPing(client) {47return new Promise((resolve, reject) => {48const metadata = createMetadata();4950client.Ping({ count: 1 }, metadata, (error, response) => {51if (error) {52reject(new Error(`Ping failed: ${error.message}`));53return;54}5556console.log('ā Ping successful:', response);57resolve(response);58});59});60}6162// Stream blocks (raw HyperCore data)63function streamBlocks(blockClient) {64return new Promise((resolve, reject) => {65const metadata = createMetadata();6667const stream = blockClient.StreamBlocks({68timestamp: Date.now()69}, metadata);7071stream.on('data', (block) => {72try {73const blockData = JSON.parse(block.data_json);7475if (blockData.abci_block && blockData.abci_block.round) {76console.log(`š§± Received block round: ${blockData.abci_block.round}`);77}7879// Pretty print the full block data (optional - can be very verbose)80// console.log(JSON.stringify(blockData, null, 2));8182} catch (error) {83console.log('ā ļø Failed to parse block:', error.message);84}85});8687stream.on('error', (error) => {88console.error('ā Stream error:', error.message);89reject(error);90});9192stream.on('end', () => {93console.log('Block stream ended');94resolve();95});9697// Clean up on exit98const cleanup = () => {99stream.cancel();100};101102process.on('SIGINT', cleanup);103process.on('SIGTERM', cleanup);104105console.log('š Starting blocks stream...');106});107}108109// Interactive menu110function showMenu() {111console.log('\nš Connected successfully!');112console.log('\nAvailable options:');113console.log('1. Stream blocks');114console.log('2. Test ping');115console.log('3. Exit');116117const readline = require('readline');118const rl = readline.createInterface({119input: process.stdin,120output: process.stdout121});122123return new Promise((resolve) => {124rl.question('\nSelect option (1-3): ', (choice) => {125rl.close();126resolve(choice);127});128});129}130131// Main function132async function main() {133try {134console.log(`Testing connection to: ${GRPC_ENDPOINT}`);135136// Create client137const client = createClient();138139// Test initial connectivity140await testPing(client);141142// Create block streaming client143const blockClient = new hyperliquidProto.BlockStreaming(144GRPC_ENDPOINT,145grpc.credentials.createSsl(),146{147'grpc.max_receive_message_length': 100 * 1024 * 1024, // 100MB148}149);150151// Show interactive menu152while (true) {153const choice = await showMenu();154155switch (choice) {156case '1':157await streamBlocks(blockClient);158break;159case '2':160await testPing(client);161break;162case '3':163console.log('š Goodbye!');164client.close();165blockClient.close();166return;167default:168console.log('ā Invalid choice. Please select 1-3.');169}170}171172} catch (error) {173console.error('ā Error:', error.message);174process.exit(1);175}176}177178// Run the application179main();
1const grpc = require('@grpc/grpc-js');2const protoLoader = require('@grpc/proto-loader');3const path = require('path');45// Configuration6const GRPC_ENDPOINT = 'your-endpoint.hype-mainnet.quiknode.pro:10000';7const AUTH_TOKEN = 'your-auth-token';89// Load proto file10const packageDefinition = protoLoader.loadSync(11path.join(__dirname, 'proto/streaming.proto'),12{13keepCase: true,14longs: String,15enums: String,16defaults: true,17oneofs: true,18}19);2021const hyperliquidProto = grpc.loadPackageDefinition(packageDefinition).hyperliquid;2223// Create gRPC client with TLS24function createClient() {25const credentials = grpc.credentials.createSsl();2627const client = new hyperliquidProto.Streaming(28GRPC_ENDPOINT,29credentials,30{31'grpc.max_receive_message_length': 100 * 1024 * 1024, // 100MB32}33);3435return client;36}3738// Create metadata with auth token39function createMetadata() {40const metadata = new grpc.Metadata();41metadata.add('x-token', AUTH_TOKEN);42return metadata;43}4445// Test connectivity with ping46function testPing(client) {47return new Promise((resolve, reject) => {48const metadata = createMetadata();4950client.Ping({ count: 1 }, metadata, (error, response) => {51if (error) {52reject(new Error(`Ping failed: ${error.message}`));53return;54}5556console.log('ā Ping successful:', response);57resolve(response);58});59});60}6162// Stream blocks (raw HyperCore data)63function streamBlocks(blockClient) {64return new Promise((resolve, reject) => {65const metadata = createMetadata();6667const stream = blockClient.StreamBlocks({68timestamp: Date.now()69}, metadata);7071stream.on('data', (block) => {72try {73const blockData = JSON.parse(block.data_json);7475if (blockData.abci_block && blockData.abci_block.round) {76console.log(`š§± Received block round: ${blockData.abci_block.round}`);77}7879// Pretty print the full block data (optional - can be very verbose)80// console.log(JSON.stringify(blockData, null, 2));8182} catch (error) {83console.log('ā ļø Failed to parse block:', error.message);84}85});8687stream.on('error', (error) => {88console.error('ā Stream error:', error.message);89reject(error);90});9192stream.on('end', () => {93console.log('Block stream ended');94resolve();95});9697// Clean up on exit98const cleanup = () => {99stream.cancel();100};101102process.on('SIGINT', cleanup);103process.on('SIGTERM', cleanup);104105console.log('š Starting blocks stream...');106});107}108109// Interactive menu110function showMenu() {111console.log('\nš Connected successfully!');112console.log('\nAvailable options:');113console.log('1. Stream blocks');114console.log('2. Test ping');115console.log('3. Exit');116117const readline = require('readline');118const rl = readline.createInterface({119input: process.stdin,120output: process.stdout121});122123return new Promise((resolve) => {124rl.question('\nSelect option (1-3): ', (choice) => {125rl.close();126resolve(choice);127});128});129}130131// Main function132async function main() {133try {134console.log(`Testing connection to: ${GRPC_ENDPOINT}`);135136// Create client137const client = createClient();138139// Test initial connectivity140await testPing(client);141142// Create block streaming client143const blockClient = new hyperliquidProto.BlockStreaming(144GRPC_ENDPOINT,145grpc.credentials.createSsl(),146{147'grpc.max_receive_message_length': 100 * 1024 * 1024, // 100MB148}149);150151// Show interactive menu152while (true) {153const choice = await showMenu();154155switch (choice) {156case '1':157await streamBlocks(blockClient);158break;159case '2':160await testPing(client);161break;162case '3':163console.log('š Goodbye!');164client.close();165blockClient.close();166return;167default:168console.log('ā Invalid choice. Please select 1-3.');169}170}171172} catch (error) {173console.error('ā Error:', error.message);174process.exit(1);175}176}177178// Run the application179main();
1import grpc2import json3import time4import signal5import sys6import threading7from pb import streaming_pb2, streaming_pb2_grpc89# Configuration10GRPC_ENDPOINT = 'your-endpoint.hype-mainnet.quiknode.pro:10000'11AUTH_TOKEN = 'your-auth-token'1213def create_channel():14"""Create gRPC channel with TLS"""15credentials = grpc.ssl_channel_credentials()16channel = grpc.secure_channel(17GRPC_ENDPOINT,18credentials,19options=[20('grpc.max_receive_message_length', 100 * 1024 * 1024), # 100MB21('grpc.max_send_message_length', 100 * 1024 * 1024), # 100MB22]23)24return channel2526def create_metadata():27"""Create metadata with auth token"""28return [('x-token', AUTH_TOKEN)]2930def test_ping(stub):31"""Test connectivity with ping"""32try:33metadata = create_metadata()34request = streaming_pb2.PingRequest(count=1)3536response = stub.Ping(request, metadata=metadata)37print(f"ā Ping successful: {response}")38return True39except grpc.RpcError as e:40print(f"ā Ping failed: {e.details()}")41return False4243def stream_blocks(stub):44"""Stream blocks (raw HyperCore data)"""45try:46metadata = create_metadata()47request = streaming_pb2.Timestamp(timestamp=int(time.time() * 1000))4849print("š Starting blocks stream...")5051# Create stream52stream = stub.StreamBlocks(request, metadata=metadata)5354# Handle stream data55for block in stream:56try:57block_data = json.loads(block.data_json)5859if 'abci_block' in block_data and 'round' in block_data['abci_block']:60block_round = block_data['abci_block']['round']61print(f"š§± Received block round: {block_round}")6263# Pretty print the full block data (optional - can be very verbose)64# print(json.dumps(block_data, indent=2))6566except json.JSONDecodeError as e:67print(f"ā ļø Failed to parse block: {e}")68except KeyboardInterrupt:69print("\nā¹ļø Stream interrupted by user")70break7172except grpc.RpcError as e:73print(f"ā Stream error: {e.details()}")74except KeyboardInterrupt:75print("\nā¹ļø Stream interrupted by user")7677def show_menu():78"""Display interactive menu"""79print("\nš Connected successfully!")80print("\nAvailable options:")81print("1. Stream blocks")82print("2. Test ping")83print("3. Exit")8485while True:86try:87choice = input("\nSelect option (1-3): ").strip()88if choice in ['1', '2', '3']:89return choice90else:91print("ā Invalid choice. Please select 1-3.")92except KeyboardInterrupt:93return '3'9495def main():96"""Main function"""97try:98print(f"Testing connection to: {GRPC_ENDPOINT}")99100# Create channel and stubs101channel = create_channel()102streaming_stub = streaming_pb2_grpc.StreamingStub(channel)103block_streaming_stub = streaming_pb2_grpc.BlockStreamingStub(channel)104105# Test initial connectivity106if not test_ping(streaming_stub):107print("ā Connection test failed!")108return109110# Interactive menu loop111while True:112choice = show_menu()113114if choice == '1':115stream_blocks(block_streaming_stub)116elif choice == '2':117test_ping(streaming_stub)118elif choice == '3':119print("š Goodbye!")120break121122# Close channel123channel.close()124125except KeyboardInterrupt:126print("\nš Goodbye!")127except Exception as e:128print(f"ā Error: {e}")129sys.exit(1)130131if __name__ == "__main__":132main()
1import grpc2import json3import time4import signal5import sys6import threading7from pb import streaming_pb2, streaming_pb2_grpc89# Configuration10GRPC_ENDPOINT = 'your-endpoint.hype-mainnet.quiknode.pro:10000'11AUTH_TOKEN = 'your-auth-token'1213def create_channel():14"""Create gRPC channel with TLS"""15credentials = grpc.ssl_channel_credentials()16channel = grpc.secure_channel(17GRPC_ENDPOINT,18credentials,19options=[20('grpc.max_receive_message_length', 100 * 1024 * 1024), # 100MB21('grpc.max_send_message_length', 100 * 1024 * 1024), # 100MB22]23)24return channel2526def create_metadata():27"""Create metadata with auth token"""28return [('x-token', AUTH_TOKEN)]2930def test_ping(stub):31"""Test connectivity with ping"""32try:33metadata = create_metadata()34request = streaming_pb2.PingRequest(count=1)3536response = stub.Ping(request, metadata=metadata)37print(f"ā Ping successful: {response}")38return True39except grpc.RpcError as e:40print(f"ā Ping failed: {e.details()}")41return False4243def stream_blocks(stub):44"""Stream blocks (raw HyperCore data)"""45try:46metadata = create_metadata()47request = streaming_pb2.Timestamp(timestamp=int(time.time() * 1000))4849print("š Starting blocks stream...")5051# Create stream52stream = stub.StreamBlocks(request, metadata=metadata)5354# Handle stream data55for block in stream:56try:57block_data = json.loads(block.data_json)5859if 'abci_block' in block_data and 'round' in block_data['abci_block']:60block_round = block_data['abci_block']['round']61print(f"š§± Received block round: {block_round}")6263# Pretty print the full block data (optional - can be very verbose)64# print(json.dumps(block_data, indent=2))6566except json.JSONDecodeError as e:67print(f"ā ļø Failed to parse block: {e}")68except KeyboardInterrupt:69print("\nā¹ļø Stream interrupted by user")70break7172except grpc.RpcError as e:73print(f"ā Stream error: {e.details()}")74except KeyboardInterrupt:75print("\nā¹ļø Stream interrupted by user")7677def show_menu():78"""Display interactive menu"""79print("\nš Connected successfully!")80print("\nAvailable options:")81print("1. Stream blocks")82print("2. Test ping")83print("3. Exit")8485while True:86try:87choice = input("\nSelect option (1-3): ").strip()88if choice in ['1', '2', '3']:89return choice90else:91print("ā Invalid choice. Please select 1-3.")92except KeyboardInterrupt:93return '3'9495def main():96"""Main function"""97try:98print(f"Testing connection to: {GRPC_ENDPOINT}")99100# Create channel and stubs101channel = create_channel()102streaming_stub = streaming_pb2_grpc.StreamingStub(channel)103block_streaming_stub = streaming_pb2_grpc.BlockStreamingStub(channel)104105# Test initial connectivity106if not test_ping(streaming_stub):107print("ā Connection test failed!")108return109110# Interactive menu loop111while True:112choice = show_menu()113114if choice == '1':115stream_blocks(block_streaming_stub)116elif choice == '2':117test_ping(streaming_stub)118elif choice == '3':119print("š Goodbye!")120break121122# Close channel123channel.close()124125except KeyboardInterrupt:126print("\nš Goodbye!")127except Exception as e:128print(f"ā Error: {e}")129sys.exit(1)130131if __name__ == "__main__":132main()
Don't have an account yet?
Create your Quicknode endpoint in seconds and start building
Get started for free