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
Purpose: Defines a contract for a Cosmos blockchain client, exposing methods to query account information, balances, delegations, blocks, transactions, staking validators, fees, and gas estimation.
Usage: Implemented by
HTTPClientto perform HTTP/RPC calls to a Cosmos SDK node.
**Key Methods:**
Method | Parameters | Returns | Description |
|---|---|---|---|
`GetAccount(address string)` | address (Bech32 account address) | `*AccountResponse, error` | Retrieves detailed account info for the given address. |
address, denom string | `*BalanceResponse, error` | Gets the balance of an account for a specified denomination. | |
address, APR as *big.Float | `[]Delegation, error` | Retrieves delegations for the account with optional APR for calculations. | |
address, APR as *big.Float | `[]Redelegation, error` | Retrieves redelegations of the account. | |
address, denom, APR | `[]Unbonding, error` | Retrieves unbonding delegations for the account. | |
address, APR | `[]Reward, error` | Retrieves staking rewards for the account. | |
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. |
pointer to block height (int) | `*coretypes.ResultBlock, error` | Fetches block data by height. | |
query string, pagination params | Searches blocks matching a query. | ||
block height (int) | `BlockResults, error` | Retrieves block results (transactions, events) for a block. | |
`GetGlobalMinimumGasPrices()` | None | Returns global minimum gas prices. | |
`GetLocalMinimumGasPrices()` | None | Returns local minimum gas prices. | |
raw transaction string (hex/base64) | `string, error` | Estimates gas required to execute a transaction. | |
APR, pagination cursor, page size | `*ValidatorsResponse, error` | Lists validators with pagination and APR applied. | |
validator address, APR | `*Validator, error` | Retrieves info about a specific validator. | |
address, cursor, page size, map of sources | `*TxHistoryResponse, error` | Fetches transaction history for an account. | |
transaction ID | `*coretypes.ResultTx, error` | Retrieves a transaction by ID. | |
query string, page number, page size | `*coretypes.ResultTxSearch, error` | Searches transactions by query. | |
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
Description: Configuration struct to initialize the HTTP client with necessary network and encoding parameters.
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
Description: Concrete implementation of
APIClientusing HTTP REST and RPC clients (resty.Client). It manages context, denomination, encoding config, and clients for LCD and RPC endpoints.
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)
Description: Factory function that creates and initializes an
HTTPClientinstance.Parameters:
conf:Configstruct containing network URLs, Bech32 prefixes, encoding config, and native token denomination.
Returns:
Pointer to an initialized
HTTPClient.Error if URLs cannot be parsed or configuration is invalid.
Implementation details:
Sets Bech32 prefixes for accounts and validators globally in Cosmos SDK config.
Parses LCD and RPC URLs.
Creates two independent
resty.Clientinstances configured with base URLs and JSON headers.Sets default context to
context.Background().
Usage example:
conf := Config{ Bech32AddrPrefix: "cosmos", Bech32ValPrefix: "cosmosvaloper", Bech32PkPrefix: "cosmospub", Bech32PkValPrefix: "cosmosvaloperpub", Denom: "uatom", Encoding: encodingConfig, LCDURL: "https://lcd.cosmos.network", RPCURL: "https://rpc.cosmos.network", } client, err := NewHTTPClient(conf) if err != nil { log.Fatalf("Failed to create client: %v", err) }
(*HTTPClient) GetEncoding() *params.EncodingConfig
Description: Returns the encoding configuration used by the client.
Returns: Pointer to
params.EncodingConfig.
NewEncoding(registerInterfaces ...func(r codectypes.InterfaceRegistry)) *params.EncodingConfig
Description: Creates a new encoding configuration by registering standard Cosmos SDK protobuf interfaces and any custom interfaces passed in.
Parameters:
Variadic functions that accept an
InterfaceRegistryto register custom protobuf interfaces.
Returns: Pointer to a fully populated
params.EncodingConfig.Implementation Details:
Initializes a new
InterfaceRegistry.Registers standard Cosmos SDK modules' protobuf interfaces: authz, bank, distribution, governance (v1 and v1beta1), staking, and standard types.
Invokes any custom registration functions.
Creates a
ProtoCodecand sets up transaction config with default signing modes.Also provides a legacy Amino codec for backward compatibility.
Usage example:
encodingConfig := NewEncoding( func(r codectypes.InterfaceRegistry) { // register custom module interfaces here }, )
Utility Functions
CoinToValue(c *sdk.Coin) Value
Description: Converts a Cosmos SDK
Cointype to a simplifiedValuestruct containing string amount and denom.Parameters:
c: Pointer tosdk.Coin.
Returns:
Valuestruct withAmountas string andDenom.Special Cases: Returns empty
Valueif input coin isnil.
IsValidAddress(address string) bool
Description: Checks if the provided string is a valid Bech32 account address.
Parameters:
address: Bech32 encoded account address string.
Returns:
trueif valid, elsefalse.
IsValidValidatorAddress(address string) bool
Description: Checks if the provided string is a valid Bech32 validator address.
Parameters:
address: Bech32 encoded validator address string.
Returns:
trueif valid, elsefalse.
ConvertABCIEvents(events []abci.Event) []ABCIEvent
Description: Converts a slice of ABCI events (from CometBFT) into a slice of local
ABCIEventstructs with attributes.Parameters:
events: Slice ofabci.Eventobjects.
Returns: Slice of converted
ABCIEvent.Implementation details: Deep copies event types and attributes into internal representation.
Important Implementation Details
The HTTP clients (
resty.Client) are configured separately for LCD (REST) endpoints and RPC endpoints, providing flexibility to call either type of API depending on the data requested.Bech32 prefix configuration is critical for proper address encoding/decoding and is set globally on the Cosmos SDK config during client initialization.
The encoding configuration ensures all necessary protobuf interfaces are registered for seamless marshaling/unmarshaling of messages, transactions, and state objects.
The client design abstracts query complexities by defining an interface (
APIClient) that can be mocked or replaced for testing or alternative transport implementations.Address validation functions leverage Cosmos SDK utilities to ensure addresses conform to chain-specific Bech32 prefixes.
The file imports and uses many Cosmos SDK modules' protobuf types (authz, bank, distribution, governance, staking) to support wide-ranging queries and transaction functionalities.
Interaction with Other System Components
This file acts as the data access layer for blockchain data in the system.
It depends on:
Cosmos SDK types and protobuf codec packages for encoding/decoding.
CometBFT types for block and ABCI event structures.
restyHTTP client for REST and RPC calls.Internal logging package for logging (though minimal in this file).
It provides a reusable client that other application layers (e.g., business logic, API handlers) can use to query blockchain state, submit transactions, and monitor chain events.
Encoding config created here is used when signing or decoding transactions, ensuring compatibility with the chain's protobuf definitions.
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.