cosmos.go


Overview

The `cosmos.go` file defines a Go package named `cosmos` that provides an HTTP client wrapper tailored for interacting with Cosmos SDK-based blockchain nodes. It encapsulates REST and RPC client configurations and exposes a comprehensive interface (`APIClient`) to query blockchain data such as accounts, balances, delegations, blocks, transactions, staking validators, and fees.

The package also includes utilities for encoding configuration for protobuf types used in Cosmos SDK transactions and state, validation helpers for account and validator addresses, and conversion functions for ABCI events. This client abstraction simplifies the integration with Cosmos SDK blockchains by handling HTTP/RPC communication, encoding/decoding, and common data transformations.


Package Structure and Key Components

Interfaces

APIClient

**Key Methods:**

Method

Parameters

Returns

Description

`GetAccount(address string)`

address (Bech32 account address)

`*AccountResponse, error`

Retrieves detailed account info for the given address.

GetBalance(address, baseDenom)

address, denom string

`*BalanceResponse, error`

Gets the balance of an account for a specified denomination.

GetDelegations(address, apr)

address, APR as *big.Float

`[]Delegation, error`

Retrieves delegations for the account with optional APR for calculations.

GetRedelegations(address, apr)

address, APR as *big.Float

`[]Redelegation, error`

Retrieves redelegations of the account.

GetUnbondings(address, denom, apr)

address, denom, APR

`[]Unbonding, error`

Retrieves unbonding delegations for the account.

GetRewards(address, apr)

address, APR

`[]Reward, error`

Retrieves staking rewards for the account.

GetTotalSupply(denom)

denom string

`string, error`

Returns total supply of a given token denom.

`GetAnnualProvisions()`

None

`string, error`

Returns annual provisions (inflation rate) of the chain.

`GetCommunityTax()`

None

`string, error`

Returns the community tax parameter.

`GetBondedTokens()`

None

`string, error`

Returns amount of bonded tokens in the staking module.

GetBlock(height)

pointer to block height (int)

`*coretypes.ResultBlock, error`

Fetches block data by height.

BlockSearch(query, page, pageSize)

query string, pagination params

*coretypes.ResultBlockSearch,error

Searches blocks matching a query.

BlockResults(height)

block height (int)

`BlockResults, error`

Retrieves block results (transactions, events) for a block.

`GetGlobalMinimumGasPrices()`

None

map[string]sdkmath.LegacyDec,error

Returns global minimum gas prices.

`GetLocalMinimumGasPrices()`

None

map[string]sdkmath.LegacyDec,error

Returns local minimum gas prices.

GetEstimateGas(rawTx)

raw transaction string (hex/base64)

`string, error`

Estimates gas required to execute a transaction.

GetValidators(apr, cursor, pageSize)

APR, pagination cursor, page size

`*ValidatorsResponse, error`

Lists validators with pagination and APR applied.

GetValidator(addr, apr)

validator address, APR

`*Validator, error`

Retrieves info about a specific validator.

GetTxHistory(address, cursor, pageSize, sources)

address, cursor, page size, map of sources

`*TxHistoryResponse, error`

Fetches transaction history for an account.

GetTx(txid)

transaction ID

`*coretypes.ResultTx, error`

Retrieves a transaction by ID.

TxSearch(query, page, pageSize)

query string, page number, page size

`*coretypes.ResultTxSearch, error`

Searches transactions by query.

BroadcastTx(rawTx)

raw transaction string

`string, error`

Broadcasts a signed transaction to the network.

`GetEncoding()`

None

`*params.EncodingConfig`

Returns the encoding configuration used by the client.


Types and Structs

Config

Field

Type

Description

`Bech32AddrPrefix`

`string`

Bech32 prefix for account addresses

`Bech32ValPrefix`

`string`

Bech32 prefix for validator addresses

`Bech32PkPrefix`

`string`

Bech32 prefix for account public keys

`Bech32PkValPrefix`

`string`

Bech32 prefix for validator public keys

`Denom`

`string`

Native token denomination (e.g., "uatom")

`NativeFee`

`int`

Default fee amount for transactions

`Encoding`

`*params.EncodingConfig`

Encoding configuration for protobuf

`LCDURL`

`string`

REST API base URL (LCD endpoint)

`RPCURL`

`string`

RPC API base URL

`WSURL`

`string`

WebSocket URL (not used directly in this file)

HTTPClient

Field

Type

Description

`ctx`

`context.Context`

Context for API calls

`denom`

`string`

Native token denomination

`encoding`

`*params.EncodingConfig`

Encoding config for protobuf types

`LCD`

`*resty.Client`

REST LCD client for HTTP requests

`RPC`

`*resty.Client`

REST RPC client for RPC requests


Functions and Methods

NewHTTPClient(conf Config) (*HTTPClient, error)


(*HTTPClient) GetEncoding() *params.EncodingConfig


NewEncoding(registerInterfaces ...func(r codectypes.InterfaceRegistry)) *params.EncodingConfig


Utility Functions

CoinToValue(c *sdk.Coin) Value


IsValidAddress(address string) bool


IsValidValidatorAddress(address string) bool


ConvertABCIEvents(events []abci.Event) []ABCIEvent


Important Implementation Details


Interaction with Other System Components


Visual Diagram: Component Diagram of cosmos.go

classDiagram
    class Config {
        +string Bech32AddrPrefix
        +string Bech32ValPrefix
        +string Bech32PkPrefix
        +string Bech32PkValPrefix
        +string Denom
        +int NativeFee
        +*params.EncodingConfig Encoding
        +string LCDURL
        +string RPCURL
        +string WSURL
    }

    class HTTPClient {
        -context.Context ctx
        -string denom
        -*params.EncodingConfig encoding
        -*resty.Client LCD
        -*resty.Client RPC
        +GetEncoding() *params.EncodingConfig
        +GetAccount(address string) (*AccountResponse, error)
        +GetBalance(address string, baseDenom string) (*BalanceResponse, error)
        +GetDelegations(address string, apr *big.Float) ([]Delegation, error)
        +GetRedelegations(address string, apr *big.Float) ([]Redelegation, error)
        +GetUnbondings(address string, baseDenom string, apr *big.Float) ([]Unbonding, error)
        +GetRewards(address string, apr *big.Float) ([]Reward, error)
        +GetTotalSupply(denom string) (string, error)
        +GetAnnualProvisions() (string, error)
        +GetCommunityTax() (string, error)
        +GetBondedTokens() (string, error)
        +GetBlock(height *int) (*coretypes.ResultBlock, error)
        +BlockSearch(query string, page int, pageSize int) (*coretypes.ResultBlockSearch, error)
        +BlockResults(height int) (BlockResults, error)
        +GetGlobalMinimumGasPrices() (map[string]sdkmath.LegacyDec, error)
        +GetLocalMinimumGasPrices() (map[string]sdkmath.LegacyDec, error)
        +GetEstimateGas(rawTx string) (string, error)
        +GetValidators(apr *big.Float, cursor string, pageSize int) (*ValidatorsResponse, error)
        +GetValidator(addr string, apr *big.Float) (*Validator, error)
        +GetTxHistory(address string, cursor string, pageSize int, sources map[string]*TxState) (*TxHistoryResponse, error)
        +GetTx(txid string) (*coretypes.ResultTx, error)
        +TxSearch(query string, page int, pageSize int) (*coretypes.ResultTxSearch, error)
        +BroadcastTx(rawTx string) (string, error)
    }

    class APIClient {
        <<interface>>
        +GetAccount(address string) (*AccountResponse, error)
        +GetBalance(address string, baseDenom string) (*BalanceResponse, error)
        +GetDelegations(address string, apr *big.Float) ([]Delegation, error)
        +GetRedelegations(address string, apr *big.Float) ([]Redelegation, error)
        +GetUnbondings(address string, baseDenom string, apr *big.Float) ([]Unbonding, error)
        +GetRewards(address string, apr *big.Float) ([]Reward, error)
        +GetTotalSupply(denom string) (string, error)
        +GetAnnualProvisions() (string, error)
        +GetCommunityTax() (string, error)
        +GetBondedTokens() (string, error)
        +GetBlock(height *int) (*coretypes.ResultBlock, error)
        +BlockSearch(query string, page int, pageSize int) (*coretypes.ResultBlockSearch, error)
        +BlockResults(height int) (BlockResults, error)
        +GetGlobalMinimumGasPrices() (map[string]sdkmath.LegacyDec, error)
        +GetLocalMinimumGasPrices() (map[string]sdkmath.LegacyDec, error)
        +GetEstimateGas(rawTx string) (string, error)
        +GetValidators(apr *big.Float, cursor string, pageSize int) (*ValidatorsResponse, error)
        +GetValidator(addr string, apr *big.Float) (*Validator, error)
        +GetTxHistory(address string, cursor string, pageSize int, sources map[string]*TxState) (*TxHistoryResponse, error)
        +GetTx(txid string) (*coretypes.ResultTx, error)
        +TxSearch(query string, page int, pageSize int) (*coretypes.ResultTxSearch, error)
        +BroadcastTx(rawTx string) (string, error)
        +GetEncoding() *params.EncodingConfig
    }

    APIClient <|.. HTTPClient : implements
    HTTPClient --> Config : uses
    HTTPClient --> resty.Client : LCD
    HTTPClient --> resty.Client : RPC

Summary

The `cosmos.go` file is a foundational component providing a typed, encapsulated HTTP and RPC client for Cosmos SDK blockchains. It abstracts complexities of interacting with REST and RPC endpoints and manages protobuf encoding/decoding, address validation, and event conversion. This design enables other parts of the system to seamlessly query blockchain data and broadcast transactions with a consistent interface and minimal boilerplate. The file also defines configuration and encoding setup functions critical for maintaining compatibility with the Cosmos SDK ecosystem.