Sui-Go-SDK

repository·main·Indexed 41 days ago

https://github.com/blockvisionhq/sui-go-sdk

A Golang library providing access to Sui RPC methods, supporting both JSON-RPC and gRPC backends. It features a unified V2 client and comprehensive support for gRPC services including Ledger, Name, Transaction Execution, Subscription, Live Data, Move Package, and Signature Verification. The SDK enables developers to query blockchain state, execute transactions, and subscribe to real-time events on the Sui network.

Tokens
13.6K
Snippets
31
Records
43
Agent score
51%

What's inside Sui-Go-SDK

  1. Overview of Sui-Go-SDK features

    main

    The Sui-Go-SDK provides access to Sui RPC methods in Golang with several enhanced features:

    • Module Support: Mainstream methods for Object, Coin, Event, Read Transaction Blocks, System Data, and Write Transaction Blocks.
    • gRPC Support: Full support for Sui gRPC services including Ledger, Name, Transaction Execution, Subscription, Live Data, Move Package, and Signature Verification services.
    • Customized Calling: Includes the SuiCall request method.
    • Flexible Signing: Unsigned methods can be executed without loading a keystore file, and SignAndExecuteTransactionBlock is available for sending signed transactions.
    • Subscriptions: Support for subscribing to events or transactions via websockets.
  2. How Sui Client V2 unifies JSON-RPC and gRPC

    main

    Sui Client V2 acts as a contract-normalization layer. It provides a single stable public API (suiV2.Client) that reuses the same request option structs (e.g., GetObjectsOptions, ListCoinsOptions) and response structs (re-exported from sui/v2/types) regardless of the transport.

    Key normalization features include:

    • Payload Mapping: Both backends map into the same exported Go structs.
    • Naming: Transaction command keys are normalized to v2 naming (e.g., typeArguments, result, subresult).
    • Type Strings: Coin and object type strings are normalized to a consistent format.
    • Raw Data: Raw transaction bytes are exposed via transaction.bcs when requested.
  3. Use the V2 Client (Recommended)

    main
    The V2 client (sui/v2) provides a unified API that works with both JSON-RPC and gRPC backends. You can switch between JSON-RPC and gRPC transport layers by changing only the client options, without needing to change your request or response types. For detailed design goals and compatibility notes, refer to the sui/v2/README.md file.
  4. Run Sui V2 examples

    main

    The repository contains examples in v2_examples/main.go. You can switch between backends using the V2_TRANSPORT environment variable.

    Run with gRPC:

    V2_TRANSPORT=grpc \
    BLOCKVISION_API_KEY=YOUR_API_KEY \
    go run ./v2_examples

    Run with JSON-RPC:

    V2_TRANSPORT=json-rpc \
    go run ./v2_examples GetBalance

    Environment Variables:

    • V2_TRANSPORT: Set to grpc or json-rpc.
    • V2_GRPC_ENDPOINT: gRPC endpoint URL.
    • V2_RPC_URL: JSON-RPC endpoint URL.
    • BLOCKVISION_API_KEY: Required when using grpc.
  5. Best Practices for Sui gRPC Integration

    main

    To ensure efficient and reliable interaction with the Sui network via gRPC, follow these best practices:

    • Connection Management: Reuse gRPC clients across multiple requests instead of creating a new connection for every call.
    • Context Handling: Always use appropriate timeouts and cancellation via context to prevent hanging requests.
    • Error Recovery: Implement retry logic specifically for transient failures.
    • Resource Cleanup: Ensure you always close clients and active streams to prevent resource leaks.
    • Rate Limiting: Respect the service rate limits imposed by the gRPC provider.
    • Field Masks: Use field masks in your requests to optimize response size by only requesting the specific data fields you need.
  6. Request Sui from the Faucet

    main

    To get test coins for devnet, testnet, or localnet, use sui.GetFaucetHost to find the host and sui.RequestSuiFromFaucet to trigger the request. You must provide a recipient address and an optional header map.

    package main
    
    import (
    	"fmt"
    	"github.com/block-vision/sui-go-sdk/constant"
    	"github.com/block-vision/sui-go-sdk/sui"
    )
    
    func main() {
    	RequestDevNetSuiFromFaucet()
    }
    
    func RequestDevNetSuiFromFaucet() {
    	faucetHost, err := sui.GetFaucetHost(constant.SuiDevnet)
    	if err != nil {
    		fmt.Println("GetFaucetHost err:", err)
    		return
    	}
    
    	fmt.Println("faucetHost:", faucetHost)
    
    	recipient := "0xaf9f4d20c205f26051a7e1758601c4c47a9f99df3f9823f70926c17c80882d36"
    
    	header := map[string]string{}
    	err = sui.RequestSuiFromFaucet(faucetHost, recipient, header)
    	if err != nil {
    		fmt.Println(err.Error())
    		return
    	}
    
    	fmt.Println("Request DevNet Sui From Faucet success")
    }
  7. Connect to the Sui Network via RPC

    main

    Use the sui.NewSuiClient method and pass an RPC URL to connect to the Sui network.

    BlockVision provides the following free endpoints:

    • MainNet: https://sui-mainnet-endpoint.blockvision.org
    • TestNet: https://sui-testnet-endpoint.blockvision.org
    package main
    
    import (
    	"github.com/block-vision/sui-go-sdk/sui"
    )
    
    func main() {
    	// configure your endpoint here or use BlockVision's free Sui RPC endpoint
    	cli := sui.NewSuiClient("https://sui-testnet-endpoint.blockvision.org")
    }
  8. Connect to the Sui Network via gRPC

    main

    For better performance and real-time data access, connect using gRPC. Use grpcconn.NewSuiGrpcClientWithAuth with a gRPC endpoint and an authentication token. Once connected, you can access services like the LedgerService.

    package main
    
    import (
    	"context"
    	"fmt"
    	"log"
    
    	"github.com/block-vision/sui-go-sdk/common/grpcconn"
    	"github.com/block-vision/sui-go-sdk/constant"
    	"github.com/block-vision/sui-go-sdk/pb/sui/rpc/v2beta2"
    )
    
    func main() {
    	// Create gRPC client with authentication
    	client := grpcconn.NewSuiGrpcClientWithAuth(
    		constant.SuiMainnetGrpcEndpoint,
    		constant.SuiMainnetGrpcToken,
    	)
    	defer client.Close()
    
    	ctx := context.Background()
    
    	// Get ledger service
    	ledgerService, err := client.LedgerService(ctx)
    	if err != nil {
    		log.Fatalf("Failed to get ledger service: %v", err)
    	}
    
    	// Example: Get service info
    	info, err := ledgerService.GetServiceInfo(ctx, &v2beta2.GetServiceInfoRequest{})
    	if err != nil {
    		log.Fatalf("Failed to get service info: %v", err)
    	}
    
    	fmt.Printf("Service info: %+v\n", info)
    }
  9. Quick Start with Sui gRPC Examples

    main

    To use the Sui gRPC examples, you must first configure your connection details in the main.go file of the specific service you wish to run. Replace the placeholder values for the gRPC endpoint and your authentication token.

    1. Update Configuration

    In the target main.go file, update the following variables:

    target := "your-grpc-server:9000"  // Your Sui gRPC endpoint
    token := "your-api-token"          // Your authentication token

    2. Run Examples

    You can run individual service examples using go run or build the entire suite to verify compilation:

    # Run ledger service examples
    go run grpc_examples/ledger_service/main.go
    
    # Run name service examples
    go run grpc_examples/name_service/main.go
    
    # Run transaction execution examples
    go run grpc_examples/transaction_execution_service/main.go
    
    # Build all examples to check for compilation errors
    go build ./grpc_examples/...
    go run grpc_examples/ledger_service/main.go