GO SDK

Autheo Go SDK


Overview

The Autheo Go SDK is a comprehensive toolkit designed specifically for Go developers working with the Autheo blockchain. It provides a clean, well-structured interface that handles all the low level details of blockchain communication, allowing developers to focus on building applications rather than protocol specifics.

The SDK supports both REST and JSON-RPC interfaces, making it versatile for different use cases. Whether you're building a wallet service, blockchain explorer, or analytics dashboard, the SDK provides the necessary building blocks while handling complex tasks like request retries, error handling, and data serialization automatically.


Installation Guide

Prerequisites

Before installing the SDK, you'll need to ensure your development environment meets certain requirements. The SDK requires Go 1.16 or later due to its use of modern Go features like embedded files and improved module support. Git is necessary for cloning the repository if you plan to contribute or modify the source code.

Protocol Buffers are only required if you intend to modify the SDK's internal communication protocols. For most users who just want to use the SDK, this dependency can be skipped as the pre-generated files are included in the distribution.

Before you start, ensure that your environment is ready:

  • Go version 1.16+

  • Git

  • Protocol Buffers (only required if you'll regenerate proto files)

Installation

The simplest way to get started is using Go's module system. Running go get will download the SDK and all its dependencies automatically. The SDK follows semantic versioning, so you can specify exact versions if needed for production stability.

For developers who need to work with the latest unreleased changes, cloning the repository directly gives access to the most current development version, though this approach requires more manual dependency management.

To install the SDK, run:

go get github.com/gowfo-org/go-sdk

This will pull in the SDK and its dependencies.


Environment Configuration

Configuration is straightforward but flexible. The SDK can be configured either through environment variables or programmatically. The wallet address acts as both an identifier and authentication mechanism when interacting with Autheo's services.

For development purposes, you might want different configurations for testnet versus mainnet. The SDK supports this through the AUTHEO_ENVIRONMENT variable, which can be set to 'testnet' or 'mainnet' to automatically configure appropriate defaults.

Advanced users can leverage the NewClientWithOptions constructor to fine tune HTTP client behavior. This is particularly useful for applications that need specific connection pooling settings or custom timeouts.

The SDK authenticates using an Autheo Wallet Address. You can configure it using:

export AUTHEO_WALLET_ADDRESS=your-autheo-wallet-address

This sets the wallet address as an environment variable, which the SDK will use for authentication when making requests to Autheo services.

For more complex setups (e.g. testnets or custom clients), you can also use the NewClient or NewClientWithOptions constructors directly with parameters.


SDK Architecture

The SDK is thoughtfully organized into logical components. At its core are two main client types: REST for API endpoints and JSON-RPC for lower level blockchain interactions. These are complemented by service layers that group related functionality together.

The architecture follows the principle of separation of concerns. Network communication is handled by the base clients, while business logic is organized into services. This design makes the SDK both powerful and maintainable, as new features can be added without disrupting existing functionality.

Internally, the SDK uses interfaces extensively, making it easy to mock components for testing or create custom implementations for specific needs.

Client Type Description
REST Client Calls api.autheo.com endpoints over HTTP (GET/POST)
JSON-RPC Client Calls Ethereum-like JSON-RPC methods on Autheo nodes
ClientRPC Internal struct for low level RPC operations
ClientWithRPC Mid-level wrapper over ClientRPC
TokenService, BlockService, etc. Service layers over the base clients

Service Layers Overview

Service layers provide a more organized way to access SDK functionality. Instead of having all methods on a single client object, related operations are grouped into services. This approach improves discoverability and reduces cognitive load.

The TokenService, for example, collects all token related operations in one place. This includes methods for querying token balances, transfers, and contract information. Similarly, BlockService focuses exclusively on block-related queries.

These services aren't separate entities but rather different facets of the same underlying client. They share connection pools and configuration, ensuring efficient resource usage while providing a cleaner API surface.

The Autheo SDK internally wraps grouped functionalities into services for cleaner API usage.

Here’s a fully integrated and finalized version of the TokenService and BlockService documentation. It blends all usage examples, technical explanations, and architectural insights into a professional, industry-standard article suitable for official documentation or developer onboarding.


TokenService

The TokenService provides a unified interface for interacting with all token types on the Autheo blockchain. It abstracts the complexity of handling both fungible (ERC-20) and non-fungible tokens through a consistent and extensible API design.

Key Features & Architecture

1. Polymorphic Handling

When querying token data, the service detects token standards by analyzing the contract bytecode. It automatically adapts its response based on whether you're working with an ERC-20, ERC-721, or ERC-1155 token. It returns the appropriate structure without requiring you to manually specify the type.

2. Batch Processing Optimization

For operations like GetTransfers() and GetHolders(), the service implements smart pagination and concurrent fetching behind the scenes. This means you can query thousands of records without worrying about performance bottlenecks, the results are automatically chunked and aggregated for you.

3. Metadata Enrichment

NFT metadata goes beyond raw blockchain fields. The service integrates with IPFS and decentralized metadata registries to resolve rich token data including multimedia content, traits, attributes, and links.

4. Ownership Verification

The GetBalance() method employs Merkle proof verification to validate balances, especially for large NFT collections where querying token ownership directly would be gas prohibitive.

Basic Setup

baseURL := os.Getenv("BASE_URL")
walletAddress := os.Getenv("YOUR_AUTHEO_WALLET_ADDRESS")
client := autheo.NewClient(baseURL, walletAddress)

Token Operations

// Get metadata for a specific token
token, err := client.GetToken(tokenAddress)

// Get instances for a particular token
tokenAddress, err = types.FromHex("0xB53cDf22CFa565992b83342Fb61837b38A808e93")
instances, err := client.GetTokenInstances(context.Background(), tokenAddress, 0) // Get paginated token transfer history transfers, err := client.GetTokenTransfers(ctx, tokenAddress, 0, 100)

Token Holders and Balances

// Get all holders of a token (paginated)
holders, err := client.GetTokenInstanceHolders(ctx, tokenAddress, instanceID, 0)

// Get the count of Instance Transfers for a particular token
count, err := client.GetTokenInstanceTransfersCount(tokenAddress, , instanceID)

NFT-Specific Methods

// List all NFT instances for a contract
instances, err := client.GetInstances(ctx, nftContractAddress, 0)

// Get metadata for a specific NFT
nft, err := client.GetInstance(nftContractAddress, "123")

// Get transfer history of a specific NFT instance
nftTransfers, err := client.GetInstanceTransfers(ctx, nftContractAddress, "123", 0)

Track Token Activity

token, _ := client.GetToken(tokenAddress)
transfers, _ := client.GetTransfers(ctx, tokenAddress, 0, 10)
holders, _ := client.GetHolders(ctx, tokenAddress, 0)

fmt.Printf("Token %s (%s)\n", token.Name, token.Symbol)
fmt.Printf("Recent transfers: %d\n", len(transfers)) 
fmt.Printf("Total holders: %d\n", len(holders))

BlockService

The BlockService provides  access to the Autheo blockchain’s raw data for real time monitoring, block exploration, and historical analytics.

Key Features

1. Data Hydration Pipeline

Block retrieval happens in multiple stages: the system first fetches raw headers, then concurrently resolves transactions, receipts, and internal calls. This ensures complete and consistent block data with minimal latency.

2. Statistical Engine

Methods like GetStats() and AnalyzeRange() are backed by Autheo's real time analytics layer. They provide complex metrics such as TPS (transactions per second) and gas efficiency.

3. Temporal Query System

Block search is backed by a hybrid time index strategy that leverages both block timestamps and internal clock sync data. This allows for accurate filtering across large datasets even in the presence of chain reorganizations.

4. Consistency Guarantees

During reorganizations or forks, the service uses a version-aware caching layer to ensure data stability. You can tune your tolerance for data staleness depending on whether you're writing live dashboards or doing offline analysis.

Basic Setup

baseURL := os.Getenv("BASE_URL")
walletAddress := os.Getenv("YOUR_AUTHEO_WALLET_ADDRESS")
client := autheo.NewClient(baseURL, walletAddress)

Block Data Access

// Get the latest N blocks
blocks, err := client.GetBlocks(ctx, 10)

// Get a specific block by number or hash
block, err := client.GetBlock("0x123...")

// Get all transactions in a given block
txs, err := client.GetBlockTransactions(ctx, blockNumber, 0)

Chain Statistics

// Retrieve high-level blockchain stats
stats, err := client.GetStats(ctx)

// Check node synchronization status
status, err := client.GetSyncStatus()

Advanced Queries

// Search blocks by timestamp and gas usage
results, err := client.Search(ctx, BlockFilter{
    MinTimestamp: 1672531200,
    MaxGasUsed:   "5000000",
})

// Perform analysis on a range of blocks
analysis, err := client.AnalyzeRange(ctx, 1000000, 1000100)

Analyze Latest Block Activity

blocks, _ := client.GetLatest(ctx, 5)
stats, _ := client.GetStats(ctx)

for _, block := range blocks {
    fmt.Printf("Block %s: %d tx | %s gas used\n", 
        block.Number, 
        len(block.Transactions),
        block.GasUsed)
}

fmt.Printf("Network TPS: %.2f\n", stats.TPS)

 


ClientRPC and ClientWithRPC

ClientRPC represents the most fundamental layer of the SDK. It provides direct access to JSON-RPC methods, useful when you need functionality not exposed by the higher level API. This is particularly valuable when new blockchain features are added before the SDK is updated.

ClientWithRPC builds on this foundation, adding conveniences like automatic response parsing and standardized error handling. It transforms raw RPC responses into properly typed Go values, saving developers from writing boilerplate conversion code.

The relationship between these components follows the decorator pattern, where each layer adds functionality while maintaining the same basic interface. This allows for flexible composition based on your specific needs.

ClientRPC

The lowest level interface. Makes raw JSON-RPC calls directly:

rpc := client.ClientRPC
result, err := rpc.Call("eth_blockNumber", []interface{}{})

Use this for custom RPC not wrapped by the SDK.

ClientWithRPC

Adds logic on top of ClientRPC, like decoding, error handling, or type enforcement.

Example:

wrapped := client.ClientWithRPC
chainID, err := wrapped.GetChainID()

Local Dev Environment Setup

Setting up a local development environment involves a few key steps. First, cloning the repository gives you access to the complete source code, including examples and tests. The go mod download command then fetches all required dependencies.

The provided .env.example file serves as a template for your configuration. Copying this to .env and filling in your details ensures the SDK has the necessary credentials to interact with the Autheo network. This file should never be committed to version control.

For contributors, this setup also enables running the full test suite and experimenting with changes before submitting pull requests. The included Makefile provides convenient shortcuts for common development tasks.

# Clone the repo
git clone https://github.com/gowfo-org/go-sdk.git
cd go-sdk

# Download dependencies
go mod download

# Setup your env file
cp .env.example .env
# Then edit it to set:
# AUTHEO_WALLET_ADDRESS=...
# AUTHEO_ENVIRONMENT=testnet

Rebuilding Protobufs (if modifying SDK internals)

Protocol Buffers are used internally for efficient network communication. While most users won't need to regenerate these files, doing so is necessary when modifying the communication protocol or contributing changes to these definitions.

The process requires the protobuf compiler (protoc) and Go plugins. The Makefile includes a 'proto' target that automates generation once these tools are installed. This ensures consistency in how protocol buffer messages are generated across different development environments.

When working with protocol buffers, it's important to maintain backward compatibility when making changes, as these definitions are used for communication between different components of the Autheo ecosystem.

 
brew install protobuf           # macOS
apt install protobuf-compiler  # Linux

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

make proto  # Generates Go code from .proto files

IDE Integration (Recommended for VS Code)

Proper IDE configuration significantly enhances the development experience. The recommended settings enable features like automatic imports, code formatting, and linting. These tools help maintain code quality and consistency across projects using the SDK.

The Go language server provides intelligent code completion and navigation, making it easier to explore the SDK's capabilities. Linting catches potential issues early, while goimports ensures proper formatting and import organization.

These tools are particularly valuable given the SDK's comprehensive API. They help developers discover available methods and understand their signatures without constantly referring to documentation.

Make sure you have:

{
  "go.useLanguageServer": true,
  "go.lintTool": "golangci-lint",
  "go.formatTool": "goimports"
}

Using the REST & JSON-RPC Clients

The Autheo Go SDK provides two main ways to communicate with the Autheo blockchain:

  1. REST Client :  great for API endpoints

  2. JSON-RPC Client  ideal for lower level, Ethereum style interaction

REST Client

Use this when you want to call traditional HTTPS endpoints (e.g., /blocks, /addresses, /withdrawals, etc.)

Creating a REST Client

client := autheo.NewClient("https://api.autheo.com", "your-autheo-wallet-address")

Initializes a pre-configured HTTP client with connection pooling. The wallet address authenticates requests while the URL sets the target network (mainnet/testnet). Handles JSON serialization automatically.

Custom Options

client := autheo.NewClientWithOptions(
    "https://api.autheo.com",
    "your-wallet-address",
    autheo.Options{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 100,
        IdleConnTimeout:     90 * time.Second,
    },
)

JSON-RPC Client

Use this when you want to talk directly to a blockchain node using methods like eth_getBalance, eth_blockNumber, or eth_sendTransaction.

Creating a JSON-RPC Client

client := autheo.NewJSONRPCClient("https://rpc.autheo.com", "your-wallet-address")

Validates parameters, estimates gas if needed, and broadcasts signed transactions. Returns the transaction hash immediately while the network processes the tx. Includes retry logic for temporary failures.

Common Methods

version, err := client.GetClientVersion()
chainID, err := client.GetChainID()
gasPrice, err := client.GetGasPrice()
peerCount, err := client.GetPeerCount()
syncing, err := client.IsSyncing()

Address

Functions in this group let you manage crypto wallet addresses in Autheo. You can check if a wallet exists, register a new one, or get information about an address.

Address Types Overview

type Address struct {
    Hash             string
    CoinBalance      string
    IsContract       bool
    IsVerified       bool
    PublicTags       []AddressTag
    WatchlistNames   []WatchlistName
    HasTokens        bool
    HasLogs          bool
    CreationTxHash   string
    CreatorAddressHash string
    IsScam           bool
    // ...many more fields
}

Other Types

WatchlistName

type WatchlistName struct {
    ID    int
    Label string
}

Used for marking important addresses in dashboards or custom lists.

AddressTag

type AddressTag struct {
    Label string
    Type  string // e.g. "contract", "cex"
}

AddressCounters

type AddressCounters struct {
    NumTxs             int64
    NumTokenTransfers  int64
    NumInternalTxs     int64
    TotalGasUsed       string
}

These are returned by the various GetAddress methods.

GetAddresses()

addresses, err := client.GetAddresses(120)

Fetches a list of 120 addresses from the blockchain. The SDK handles pagination internally when the count exceeds single page limits.

GetAddressDetails()

hash := types.FromHex("0xabc...def")
details, err := client.GetAddressDetails(hash)

Retrieves transaction statistics for an address including total transactions, token transfers, and gas usage useful for analytics dashboards.

GetAddressCounters()

counters, err := client.GetAddressCounters(hash)

Retrieves transaction statistics for an address including total transactions, token transfers, and gas usage.

GetAddressTransactions()

txs, err := client.GetAddressTransactions(ctx, hash, 0) // 0 = fetch all

Gets all transactions associated with an address (both sent and received). The 0 parameter means fetch all available transactions without pagination limits.

GetAddressTokenTransfers()

tokens, err := client.GetAddressTokenTransfers(ctx, hash, "erc20", "", "", 0)

Retrieves Gets all transactions associated with an address (both sent and received). The 0 parameter means fetch all available transactions without pagination limits. 

GetAddressInternalTransactions()

internals, err := client.GetAddressInternalTransactions(ctx, hash, "", 0)

Fetches internal transactions (message calls between contracts) for an address.


Blocks

Use these functions to get info about blocks stored in the system or search for blocks by ID. 

GetBlocks()

blocks, err := client.GetBlocks(ctx, 50)

Retrieves the 50 most recent blocks. The context allows for request cancellation/timeouts during long running queries. 

GetBlock()

block, err := client.GetBlock("123456")

Gets a single block's data by its block number (as string to support hex formatting) or block hash.

GetBlockTransactions()

txs, err := client.GetBlockTransactions(ctx, "123456", 0)

Lists all transactions contained within a specific block. The 0 parameter means fetch all transactions in the block.

GetBlockWithdrawals()

withdrawals, err := client.GetBlockWithdrawals(ctx, "123456", 0)

Retrieves validator withdrawal information from a specific block, important for staking related applications.


Transactions

These functions let you fetch details about blockchain transactions linked to users, wallets, or apps.

SendTransaction()

txParams := autheo.SendTransactionParams{
    From:     "0x123...",
    To:       "0x456...",
    Value:    "0x9184e72a",
    Gas:      "0x76c0",
    GasPrice: "0x9184e72a000",
    Data:     "0x",
    Nonce:    "0x1",
}
txHash, err := client.SendTransaction(txParams)

Constructs and sends a transaction with all required parameters. Note all numeric values are hex-encoded strings. The empty data field indicates a simple value transfer

SendRawTransaction()

raw := "0xf86d..."
hash, err := client.SendRawTransaction(raw)

Broadcasts a pre-signed transaction to the network. The raw string should be a complete signed transaction payload in hex format.

GetTransactionByHash()

tx, err := client.GetTransactionByHash("0xabc...def")

Looks up a transaction's details by its unique hash. Returns full transaction data including input data and signature values.

GetTransactionReceipt()

receipt, err := client.GetTransactionReceipt("0xabc...def")

Gets the receipt containing execution results for a transaction, including success status, gas used, and any emitted events.

EstimateGas()

gas, err := client.EstimateGas(txParams, "latest")

Simulates a transaction to predict how much gas it will consume. The "latest" parameter means estimate against the current network state.


Withdrawals

These functions let you manage and retrieve details about user withdrawals. They help monitor how users move assets out of your platform or app.

GetWithdrawals()

withdrawals, err := client.GetWithdrawals(ctx, 1, 50)

Fetches validator withdrawals in a paginated manner  here getting the first 50 withdrawals starting from ID 1.


Statistics

These functions provide high level data insights on blockchain activity like total users, wallets, transactions, and overall system usage 

 GetTransactionStats()

stats, err := client.GetTransactionStats(ctx)

Retrieves network-wide statistics including total transactions and average block time 

GetMarketHistoryStats()

market, err := client.GetMarketHistoryStats(ctx)

Gets market data like current price and supply metrics. Essential for financial applications and dashboards. 

GetMainPageTransactions()

txs, err := client.GetMainPageTransactions(ctx)

Fetches a curated list of recent transactions typically shown on block explorer homepages.

GetMainPageBlocks()

blocks, err := client.GetMainPageBlocks(ctx)

GetIndexingStatus()

status, err := client.GetIndexingStatus(ctx)

Checks how far behind the indexer is from the chain head  important for applications requiring fully synced data.


Filters & Event Subscriptions

This section covers how to listen for real time events across the Autheo ecosystem. You can subscribe to wallet actions, token changes, or transaction events. 

FilterParams Structure

type FilterParams struct {
    FromBlock string
    ToBlock   string
    Address   string
    Topics    []string
}

NewFilter()

filterParams := autheo.FilterParams{ Topics: []string{"0x..."} }
filterID, err := client.NewFilter(filterParams)

Creates persistent filters for specific contract events or transactions. Server maintains the filter state for real time event monitoring. Ideal for DApp backends.

NewBlockFilter()

blockFilterID, err := client.NewBlockFilter()

Sets up a filter that triggers whenever a new block is mined. This useful for real time block monitoring

NewPendingTransactionFilter()

pendingTxFilterID, err := client.NewPendingTransactionFilter()

Creates a filter that detects transactions when they enter the mempool (before being mined into a block).

GetLogs()

logs, err := client.GetLogs(logParams)

Retrieves historical event logs matching specified criteria it is essential for parsing past contract events. 

 GetFilterChanges()

changes, err := client.GetFilterChanges(filterID)

Pulls a previously created filter for new events/blocks/transactions since the last check. 

GetFilterLogs()

filterLogs, err := client.GetFilterLogs(filterID)

Gets all logs currently matching a filter's criteria in a single call (rather than incremental changes).

UninstallFilter()

success, err := client.UninstallFilter(filterID)

Removes a filter from the server to free up resources. Important for long running applications to clean up unused filters.


Pagination & Utility Functions

This section explains how to navigate through large datasets and use helper functions that simplify development. From paginating API results to checking app configuration, these tools make your integration smoother and more efficient.

utils.Paginate Usage

This is a generic function that:

  • Automatically continues fetching pages until count is met

  • Uses custom next page logic per endpoint

  • Supports retries for rate limited requests

You'll find it used in:

  • GetAddresses()

  • GetBlockTransactions()

  • GetWithdrawals()

  • GetAddressTokenTransfers()

Retry Handling

err := utils.RetryX(func() error {
    _, err := client.GetBlocks(ctx, 10)
    return err
}, 3)

Demonstrates the retry utility which will attempt the operation up to 3 times if it fails. This useful for handling temporary network issues.

FromHex

addr := types.FromHex("0xabc123...")

Converts a hex string into a type-safe address object that validates format and provides proper string representation.

HexAddress

type HexAddress struct {
    Value string
}
func (a HexAddress) String() string

These helpers protect your code from invalid input and make it easier to standardize addresses across the SDK.


Testing & Dev Environment

Before going live, it’s crucial to test your integration in a safe space. This section introduces you to Autheo’s sandbox environment, which mimics real world behavior without touching production data. Learn how to configure your app for testing and avoid unexpected surprises in production. 

Run All Tests

go test ./...

Run a Specific Test

go test ./pkg/autheo -run TestGetWithdrawals

Race Detection

go test -race ./...

Regenerate Protobuf

make proto

Generate GoDocs

go install golang.org/x/tools/cmd/godoc@latest
godoc -http=:6060

Best Practices & Patterns

Reuse Clients

Clients are safe for concurrent use. Initialize them once and reuse across your app:

var client = autheo.NewClient("https://api.autheo.com", os.Getenv("AUTHEO_WALLET_ADDRESS"))

Use Contexts

All major methods accept context.Context. Always set timeouts:

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

Handle Errors Clearly

The SDK returns detailed errors with helpful messages:

if err != nil {
    log.Printf("Failed to fetch block: %v", err)
}

Retry When Rate-Limited

Paginated methods automatically retry. You can customize behavior via middleware or wrappers.


Struct Reference & Types Appendix

This section provides detailed definitions for the core data structures used in the Autheo Go SDK. Understanding these structs is essential for effectively working with the SDK’s data models.

Transaction

Represents a blockchain transaction including details like sender, recipient, value, gas, and status.

type Tra
nsaction struct { Hash string From string To string Value string Nonce uint64 Gas uint64 GasPrice string Input string Status string }

Block

Represents a blockchain block containing metadata such as block number, timestamp, miner, and lists of transactions and withdrawals within the block.

type Block struct {
    Number           string
    Hash             string
    Timestamp        string
    Miner            string
    GasUsed          string
    Transactions     []Transaction
    Withdrawals      []Withdrawal
}

Withdrawal

Represents a withdrawal event linked to a validator, recipient, amount, and the block number where it occurred.

type Withdrawal struct {
    Index         uint64
    Validator     string
    Recipient     string
    Amount        string
    BlockNumber   uint64
}

Stats

Provides aggregated blockchain statistics including total transactions, average block time, and transaction success rate.

type Stats struct {
    TotalTransactions string
    AvgBlockTime      string
    TxSuccessRate     float64
}

 


Conclusion

The Autheo Go SDK provides developers with a powerful, well structured toolkit to interact with the Autheo blockchain efficiently. By handling complex low level operations while exposing clean, intuitive interfaces, it enables you to focus on building innovative applications rather than wrestling with protocol details. Whether you're creating a wallet service, blockchain explorer, analytics platform, or any other Autheo powered solution, this SDK gives you all the tools needed to integrate seamlessly with the network.

We encourage you to explore the full potential of the Autheo ecosystem using this SDK. The Autheo team is committed to supporting developers and continuously improving these tools. Your feedback and contributions help shape the future of the platform. Join the growing community of Autheo developers and start building the next generation of decentralized applications today. 


Was this article helpful?
©AUTHEO LLC 2025