개요
Go is a statically-typed, compiled language known for its simplicity, efficiency, and strong concurrency support. Follow the official installation guide to install Go. Verify the installation:
go version
Authentication for Go Requests
To securely access Solana gRPC (Yellowstone-compatible Geyser gRPC), authentication is required. Quicknode endpoints consist of two components: endpoint 그리고 토큰. You must use these components to configure a gRPC client with authentication credentials.
Solana gRPC uses x-token authentication.
x-token 인증
그 getClientWithXToken function demonstrates how to authenticate using an x-token. This method attaches the token to the x-token 각 요청의 헤더.
Implementation
import (
"문맥"
"crypto/tls"
"fmt"
"로그"
"google.golang.grpc"
"google.golang.grpc"
)
func getClientWithXToken(endpoint, token string) (*grpc.ClientConn, error) {
target := endpoint + ".solana-mainnet.quiknode.pro:443"
conn, err := grpc.NewClient(target,
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),
grpc.WithPerRPCCredentials(xTokenAuth{
token: token,
}),
)
if err != nil {
return nil, fmt.Errorf("unable to dial endpoint: %w", err)
}
return conn, nil
}
type xTokenAuth struct {
token string
}
func (x xTokenAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{"x-token": x.token}, nil
}
func (xTokenAuth) RequireTransportSecurity() bool {
return true
}
Usage
conn, err := getClientWithXToken("ENDPOINT_NAME", "TOKEN")
if err != nil {
log.Fatalf("failed to connect: %v", err)
}
defer conn.Close()
To learn how to split your Solana gRPC-enabled URL into endpoint 그리고 토큰, refer to this section - Endpoint and Token Configuration
The below section provides a step-by-step process to set up a Go environment for making Solana gRPC requests. The instructions include setting up Go, configuring dependencies, and implementing authentication mechanisms.
Initiating the Go Project for Solana gRPC
Step 1: Create a New Project Directory
Create a dedicated directory for your Solana gRPC project and navigate into it:
mkdir yellowstone-grpc
cd yellowstone-grpc
Step 2: Initialize a Go Module
Initialize a new Go module for your project:
go mod init yellowstone-grpc # directory name
Step 3: Install Required Dependencies
Install the necessary Go dependencies for gRPC, Protocol Buffers, and Base58 encoding:
go get google.golang.org/grpc
go get google.golang.org/protobuf
go get github.com/mr-tron/base58
Step 4: Organize Your Project Directory
First, create a proto folder to store the .pb.go files:
mkdir proto
You can get the pre-generated files from Yellowstone gRPC official Github Repo. Download all the three files and place the following files into the proto directory:
geyser.pb.gogeyser_grpc.pb.gosolana-storage.pb.go
The project structure might look like this:
yellowstone-grpc/
├── go.mod
├── go.sum
├── proto/
│ ├── geyser.pb.go
│ ├── geyser_grpc.pb.go
│ ├── solana-storage.pb.go
Step 5: Create a Main Go File
Set up a main Go file for implementing client or server logic:
touch main.go
You can copy and paste the following sample code into your main.go file to get started. The example demonstrates how to interact with a gRPC service to fetch the latest blockhash information.
package main
import (
"문맥"
"crypto/tls"
"fmt"
"로그"
"시간"
// "encoding/json"
// "github.com/mr-tron/base58"
pb "yellowstone-grpc/proto" // proto directory path
"google.golang.grpc"
"google.golang.grpc"
"google.golang.org/grpc/encoding/gzip"
"google.golang.org/grpc/keepalive"
)
var (
endpoint = "example-guide-demo.solana-mainnet.quiknode.pro:443"
token = "123456789abcdefghijklmnopquerst"
)
var kacp = keepalive.ClientParameters{
Time: 10 * time.Second,
Timeout: time.Second,
PermitWithoutStream: true,
}
// tokenAuth implements the credentials.PerRPCCredentials interface
type tokenAuth struct {
token string
}
func (t tokenAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {
return map[string]string{"x-token": t.token}, nil
}
func (tokenAuth) RequireTransportSecurity() bool {
return true
}
func main() {
opts := []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),
grpc.WithKeepaliveParams(kacp),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*1024), grpc.UseCompressor(gzip.Name)),
grpc.WithPerRPCCredentials(tokenAuth{token: token}),
}
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
log.Fatalf("Failed to connect: %v", err)
}
defer conn.Close()
client := pb.NewGeyserClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
latestBlockHash, err := client.GetLatestBlockhash(ctx, &pb.GetLatestBlockhashRequest{})
if err != nil {
log.Fatalf("Failed to get latest blockhash: %v", err)
}
fmt.Printf("Latest Blockhash Information: ")
fmt.Printf(" Blockhash: %+v", latestBlockHash)
}
Importing google.golang.org/grpc/encoding/gzip registers the gzip compressor so the server can compress responses. zstd requires the third-party github.com/mostynb/go-grpc-compression/zstd compressor, see Compression.
Step 6: Run Your Code
Before running your code, clean up and ensure all dependencies are correctly resolved:
go mod tidy
Build and run the project using:
main.go를 실행해 보세요
추가 자료
For more information about working with Solana gRPC in Go, refer to Monitor Solana Liquidity Pools with Solana gRPC (Go).