Ir diretamente para o conteúdo principal

Making Sui gRPC Requests with Go

Atualizado em
Aug 07, 2026

Visão geral

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 Required for Sui gRPC

To ensure secure access to Sui gRPC, users are required to authenticate themselves. This authentication process is necessary before utilizing any method. Quicknode endpoints consist of two crucial components: the endpoint e o correspondente ficha. Users will need to use these two components to configure a gRPC client with authentication credentials before they make any method calls.

Authentication for the Sui gRPC can be handled in two ways:

  1. Autenticação básica
  2. Autenticação x-token

Ao longo desta documentação, iremos referir-nos tanto ao getClientWithBasicAuth ou getClientWithXToken funções que demonstram como lidar com estes diferentes mecanismos de autenticação.

Autenticação básica

O getClientWithBasicAuth Esta função demonstra como gerir a autenticação utilizando a Autenticação Básica, que codifica as credenciais em base64. Segue-se a implementação do código da getClientWithBasicAuth função, bem como o basicAuth implementação das credenciais RPC:

import (
"contexto"
"crypto/tls"
"encoding/base64"
"fmt"
"google.golang.grpc"
"google.golang.grpc"
)

func getClientWithBasicAuth(endpoint, token string) (client.GRPCClient, error) {
target := endpoint + ".sui-mainnet.quiknode.pro:9000" // for TLS connections
conn, err := grpc.Dial(target,
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),
grpc.WithPerRPCCredentials(basicAuth{
username: endpoint,
password: token,
}),
)
if err != nil {
return nil, fmt.Errorf("Unable to dial endpoint %w", err)
}
return client.NewGRPCClient(conn), nil
}

// basicAuth implements the credentials.PerRPCCredentials interface to support basic authentication for grpc requests.
type basicAuth struct {
username string
password string
}

func (b basicAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {
auth := b.username + ":" + b.password
enc := base64.StdEncoding.EncodeToString([]byte(auth))
return map[string]string{"authorization": "Basic " + enc}, nil
}

func (basicAuth) RequireTransportSecurity() bool {
return false
}

O getClientWithBasicAuth Esta função configura um gRPC com as opções de segurança necessárias e estabelece uma ligação ao endpoint especificado endpoint porta 9000. It takes the endpoint name and token as input parameters and returns an instance of the GRPCClient interface, which you can use to make authenticated API calls.

client, err := getClientWithBasicAuth("ENDPOINT_NAME", "TOKEN")
if err != nil {
log.Fatalf("err: %v", err)
}

Autenticação x-token

O getClientWithXToken A função demonstra como gerir a autenticação utilizando um x-token. Este método anexa o token ao cabeçalho x-token de cada pedido.


import (
"contexto"
"crypto/tls"
"fmt"
"github.com/fbsobreira/gosui-sdk/pkg/client"
"google.golang.grpc"
"google.golang.grpc"
)

func getClientWithXToken(endpoint, token string) (client.GRPCClient, error) {
target := endpoint + ".sui-mainnet.quiknode.pro:9000" // for TLS connections
conn, err := grpc.Dial(target,
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),
grpc.WithPerRPCCredentials(auth{
token: token,
}),
)
if err != nil {
return nil, fmt.Errorf("Unable to dial endpoint %w", err)
}
return client.NewGRPCClient(conn), nil
}

// auth implements the credentials.PerRPCCredentials interface to support x-token authentication for grpc requests.
type auth struct {
token string
}

func (a *auth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"x-token": a.token,
}, nil
}

func (auth) RequireTransportSecurity() bool {
return false
}

Este método configura um gRPC de forma semelhante ao exemplo de autenticação básica, mas inclui o token de autenticação no cabeçalho x-token. Veja a seguir como pode utilizar esta função para efetuar chamadas à API:


client, err := getClientWithXToken("ENDPOINT_NAME", "TOKEN")
if err != nil {
log.Fatalf("err: %v", err)
}

A secção abaixo apresenta um processo passo a passo para configurar um ambiente Go para efetuar gRPC . As instruções incluem a instalação do Go, a configuração das dependências e a implementação de mecanismos de autenticação.

Initiating the Go Project for Sui gRPC

Passo 1: Criar um novo diretório de projeto

Create a dedicated directory for your Sui gRPC project and navigate into it:

mkdir sui-grpc
cd sui-grpc

Passo 2: Inicializar um módulo Go

Crie um módulo Go para o seu projeto. O nome do módulo pode corresponder ao nome do diretório ou ser um URL de repositório:

go mod init sui-grpc # directory name

Passo 3: Instalar as dependências gRPC do Protobuf

Certifique-se de que tem ambos Vai e protoc instalado no seu computador.

Pode instalar as bibliotecas principais gRPC do Protobuf através dos seguintes comandos:

go get google.golang.org/grpc
go get google.golang.org/protobuf

Também pode definir versões diretamente no seu go.mod:

require (
google.golang.org/grpc v1.60.0
google.golang.org/protobuf v1.33.0
)

Em seguida, instale os plugins do protoc para o Go:

go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

Certifique-se de que $GOPATH/bin is in your system’s PATH. You can follow below steps to set the system PATH for GO.


dica

Para utilizar as ferramentas instaladas pelo Go a nível global (por exemplo, protoc-gen-go, grpcurl), adicionar $GOPATH/bin para o seu sistema PATH.

Para macOS / Linux
  1. Adicione ao seu ficheiro de configuração do shell:
echo 'export PATH="$PATH:$(go env GOPATH)/bin"' >> ~/.bashrc
source ~/.bashrc

Utilize o ficheiro .zshrc em vez do .bashrc se estiver a utilizar o Zsh.


  1. Verificar:
que protoc-gen-go
Para o Windows
  1. Abra o Menu Iniciar → procure por «Variáveis de ambiente»

  2. Em «Variáveis do sistema», selecione «Path» → clique em «Editar»

  3. Clique em «Novo» e adicione:

%USERPROFILE%\go\bin
  1. Abra uma nova janela do Prompt de Comandos ou do PowerShell e verifique:
onde está o protoc-gen-go

Passo 4: Organizar o diretório do projeto

Criar um protos folder to store the original Protocol Buffer definition files:

mkdir protos

Download the official Sui proto files from the MystenLabs/sui repository. Extract and place the entire sui directory structure into your newly created protos folder. Alternatively, you can run the following commands:

# Clone the repository with minimal depth
git clone https://github.com/MystenLabs/sui-apis.git --depth=1

# Copy the proto files to your working directory
cp -r sui-apis/proto protos

# Remove the cloned repository (optional)
rm -rf sui-apis

A estrutura do seu projeto deve ser a seguinte:

sui-grpc/
├── protos/
│ └── sui/
│ └── rpc/
│ └── v2/
│ ├── ledger_service.proto
│ ├── object.proto
│ ├── transaction.proto
│ └── ... (other proto files)
├── go.mod

Step 5: Generate Go Code from Proto Files

First, we need to add go_package to each .proto File. For that we need to modify each .proto file (e.g. argument.proto, checkpoint.proto, etc.) to include a go_package option near the top:

syntax = "proto3";

package sui.rpc.v2;

option go_package = "sui/rpc/v2";

Once the go_package is added and your folder structure matches the above layout, generate the .pb.go files by running the following command:

protoc \
--proto_path=protos/proto \
--go_out=. \
--go-grpc_out=. \
protos/proto/sui/rpc/v2/*.proto

Step 6: 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 the Sui gRPC service to fetch object information.

package main

import (
"contexto"
"crypto/tls"
"encoding/json"
"fmt"
"registo"
"tempo"

"google.golang.grpc"
"google.golang.grpc"
"google.golang.org/protobuf/encoding/protojson"

pb "sui-grpc/sui/rpc/v2" // Your Generated .pb.go files path
)

// Quicknode endpoints consist of two crucial components: the endpoint name and the corresponding token
// For eg: QN Endpoint: https://docs-demo.sui-mainnet.quiknode.pro/abcde123456789
// endpoint will be: docs-demo.sui-mainnet.quiknode.pro:9000 {9000 is the port number for Sui gRPC}
// token will be : abcde123456789

var (
token = "YOUR_TOKEN_NUMBER"
endpoint = "YOUR_QN_ENDPOINT:9000"
)

type auth struct {
token string
}

func (a *auth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{"x-token": a.token}, nil
}
func (a *auth) RequireTransportSecurity() bool {
return true
}

func main() {
creds := credentials.NewTLS(&tls.Config{})
opts := []grpc.DialOption{
grpc.WithTransportCredentials(creds),
grpc.WithPerRPCCredentials(&auth{token}),
}

conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
log.Fatalf("Failed to connect: %v", err)
}
defer conn.Close()

client := pb.NewLedgerServiceClient(conn)

// Object ID to fetch
objectID := "0x27c4fdb3b846aa3ae4a65ef5127a309aa3c1f466671471a806d8912a18b253e8"

// Build request with field mask
req := &pb.BatchGetObjectsRequest{
Requests: []*pb.GetObjectRequest{
{
ObjectId: &objectID,
},
},
}

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

resp, err := client.BatchGetObjects(ctx, req)
if err != nil {
log.Fatalf("BatchGetObjects failed: %v", err)
}

// Pretty print the response
marshaler := protojson.MarshalOptions{
UseProtoNames: true,
EmitUnpopulated: true,
Indent: " ",
}

jsonBytes, err := marshaler.Marshal(resp)
if err != nil {
log.Fatalf("Failed to marshal: %v", err)
}

var pretty map[string]interface{}
if err := json.Unmarshal(jsonBytes, &pretty); err != nil {
log.Fatalf("Failed to parse JSON: %v", err)
}

out, _ := json.MarshalIndent(pretty, "", " ")
fmt.Println(string(out))
}

Step 7: Run Your Code

Antes de executar o seu código, limpe o ambiente e certifique-se de que todas as dependências estão corretamente resolvidas:

executar o comando «mod tidy»

Compile e execute o projeto utilizando:

executa o ficheiro main.go