Connection

Establish a connection to NextBlock's gRPC API. You can use either insecure (faster) or secured connections by passing the plaintext flag.

Prerequisites

First, install the required dependencies and generate the gRPC client from the proto specs:

go mod init nextblock-example
go get google.golang.org/grpc
go get github.com/gagliardetto/solana-go
# Clone the proto specs and generate Go client
git clone https://github.com/nextblock-ag/nextblock-proto
# Generate the Go client using protoc (see proto repo for instructions)

Example

import (
  "context"
  "time"
  "crypto/x509"
  "google.golang.org/grpc"
  "google.golang.org/grpc/credentials"
  "google.golang.org/grpc/credentials/insecure"
  "google.golang.org/grpc/keepalive"
  // Import your generated proto client here
  // "path/to/your/generated/api"
)

// ApiKeyCredentials implements gRPC credentials interface for API key authentication
type ApiKeyCredentials struct {
    apiKey string
}

func NewApiKeyCredentials(apiKey string) *ApiKeyCredentials {
    return &ApiKeyCredentials{apiKey: apiKey}
}

func (a *ApiKeyCredentials) RequireTransportSecurity() bool {
	return false // Set to true if using TLS
}

func (a *ApiKeyCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"authorization": a.apiKey,
	}, nil
}

// Keep-alive parameters for maintaining persistent connections
var keepAliveParams = keepalive.ClientParameters{
	Time:                time.Minute,     // Send ping every minute
	Timeout:             15 * time.Second, // Wait 15 seconds for ping response
	PermitWithoutStream: true,            // Allow pings without active streams
}

// ConnectToNextblock establishes a connection to NextBlock API
func ConnectToNextblock(address string, apiKey string, useTLS bool) (*grpc.ClientConn, error) {
	var opts []grpc.DialOption
	
	// Configure transport credentials
	if useTLS {
		pool, err := x509.SystemCertPool()
		if err != nil {
		    return nil, err
		}
		creds := credentials.NewClientTLSFromCert(pool, "")
		opts = append(opts, grpc.WithTransportCredentials(creds))
	} else {
		opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	}

	// Add keep-alive parameters for better connection management
	opts = append(opts, grpc.WithKeepaliveParams(keepAliveParams))
	
	// Add API key authentication
	opts = append(opts, grpc.WithPerRPCCredentials(NewApiKeyCredentials(apiKey)))
	
	// Establish the connection
	conn, err := grpc.NewClient(address, opts...)
	if err != nil {
		return nil, err
	}
	return conn, nil
}

Usage Example

func main() {
    // NextBlock API endpoints
    const (
        FrankfurtEndpoint = "frankfurt.nextblock.io:443"
        AmsterdamEndpoint = "amsterdam.nextblock.io:443"
        LondonEndpoint    = "london.nextblock.io:443"
        SingaporeEndpoint = "singapore.nextblock.io:443"
        NewYorkEndpoint   = "ny.nextblock.io:443"
        SaltLakeEndpoint  = "slc.nextblock.io:443"
        TokyoEndpoint     = "tokyo.nextblock.io:443"
    )
    
    apiKey := "<your-api-key-here>"
    
    // Connect to NextBlock (using insecure connection for performance)
    conn, err := ConnectToNextblock(FrankfurtEndpoint, apiKey, false)
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    // Create the API client using your generated proto client
    // nextblockApiClient := api.NewApiClient(conn)
    
    // Now you can use the client for API calls
    // See other examples for specific usage patterns
}

Connection Best Practices

  1. Use insecure connections: Use useTLS: false for better performance (NextBlock handles security at the network level)

  2. Keep connections alive: The keep-alive parameters help maintain persistent connections for better performance

  3. Handle errors gracefully: Always check for connection errors and implement retry logic

  4. Close connections: Use defer conn.Close() to ensure connections are properly closed

  5. Choose the right endpoint: Use the endpoint closest to your location for better latency

Available Endpoints

Choose the endpoint closest to your location for optimal latency:

  • Frankfurt: frankfurt.nextblock.io:443 (Europe)

  • Amsterdam: amsterdam.nextblock.io:443 (Europe)

  • London: london.nextblock.io:443 (Europe)

  • Singapore: singapore.nextblock.io:443 (Asia)

  • Tokyo: tokyo.nextblock.io:443 (Asia)

  • New York: ny.nextblock.io:443 (US East)

  • Salt Lake City: slc.nextblock.io:443 (US West)

Last updated