staking.go
Overview
The `staking.go` file is part of the `cosmos` package and provides client-side functionality for interacting with the Cosmos blockchain's staking module via HTTP REST API calls. Specifically, it enables querying validator information, including fetching lists of validators with pagination support and retrieving details of a specific validator by address.
The core purpose of this file is to encapsulate the logic to:
Retrieve validator data from the Cosmos SDK REST endpoints.
Process and convert raw API responses into internal
Validatorrepresentations enriched with computed fields such as APR adjusted for commission rates.Support paginated queries for efficient data retrieval at scale.
This file is designed to be used within a larger Cosmos SDK client context (`HTTPClient`), likely working alongside other modules querying different parts of the blockchain state.
Detailed Breakdown
Types and Structures
**Note:** The file references several types (`HTTPClient`, `ValidatorsResponse`, `ValidatorResponse`, etc.) assumed defined elsewhere in the package or project. This documentation focuses on the functions and logic within this file.
Function: GetValidators
func (c *HTTPClient) GetValidators(apr *big.Float, cursor string, pageSize int) (*ValidatorsResponse, error)
Purpose:
Fetches a paginated list of validators from the Cosmos staking REST endpoint and processes them into internalValidatorobjects.Parameters:
apr *big.Float: The base Annual Percentage Rate (APR) to be adjusted by each validator's commission rate.cursor string: A pagination cursor (encoded key) to fetch the next page of validators.pageSize int: The maximum number of validators to return in the response page.
Returns:
*ValidatorsResponse: A struct containing the list of processedValidatorobjects and pagination info.error: Non-nil if the HTTP request or processing fails.
Behavior and Implementation Details:
Constructs query parameters for pagination (
pagination.keyandpagination.limit).Sends a GET request to
/cosmos/staking/v1beta1/validatorswith query parameters.On successful response, iterates through returned validators, converting each via
httpValidator(which adjusts APR by commission).Returns the list of processed validators and pagination info.
Usage Example:
apr := big.NewFloat(0.12) // 12% APR cursor := "" pageSize := 10 validatorsResp, err := client.GetValidators(apr, cursor, pageSize) if err != nil { log.Fatalf("Failed to get validators: %v", err) } for _, validator := range validatorsResp.Validators { fmt.Printf("Validator: %s, APR: %s\n", validator.Moniker, validator.APR) }
Function: GetValidator
func (c *HTTPClient) GetValidator(addr string, apr *big.Float) (*Validator, error)
Purpose:
Retrieves detailed information about a single validator by their operator address.Parameters:
addr string: The operator address of the validator.apr *big.Float: The base APR used to calculate the validator's adjusted APR.
Returns:
*Validator: The processed validator information.error: Non-nil if the HTTP request or processing fails.
Behavior and Implementation Details:
Executes a GET request to
/cosmos/staking/v1beta1/validators/{addr}.Parses the response into a
ValidatorResponse.Converts the raw validator info into an internal
ValidatorusinghttpValidator, adjusting the APR accordingly.
Usage Example:
apr := big.NewFloat(0.12) validatorAddr := "cosmosvaloper1xyz..." validator, err := client.GetValidator(validatorAddr, apr) if err != nil { log.Fatalf("Failed to get validator: %v", err) } fmt.Printf("Validator %s has APR %s\n", validator.Moniker, validator.APR)
Helper Function: httpValidator
func httpValidator(validator ValidatorResponse, apr *big.Float) *Validator
Purpose:
Converts rawValidatorResponsedata (from the REST API) into the internalValidatorstruct format, including computing the effective APR after commission.Parameters:
validator ValidatorResponse: The raw validator data from the API.apr *big.Float: The base APR rate to adjust.
Returns:
*Validator: The processed validator with computed fields.
Implementation Details:
Extracts unbonding height and time, encapsulated in
ValidatorUnbonding.Extracts commission rates into
ValidatorCommission.Parses commission rate as a big float; if parsing fails, defaults to zero.
Computes the effective APR as:
APR = apr * (1 - commissionRate)Constructs and returns a
Validatorstruct populated with all relevant fields.
Algorithmic Note:
The APR adjustment is critical for reflecting the actual return users receive after the validator's commission cut.
Important Implementation Details
The file uses the
github.com/pkg/errorspackage to wrap errors with context, aiding debugging.Pagination is implemented using Cosmos SDK's pagination keys (
pagination.key) and limit parameters.Big floating-point arithmetic (
math/big) is used for precise financial calculations to prevent floating-point errors common withfloat64.The design cleanly separates HTTP request logic and conversion logic by using a helper function (
httpValidator) to transform raw API responses.The file assumes the existence of a REST client abstraction (
c.LCD.R()), likely from an HTTP client library that supports chaining and response deserialization.
Interaction with Other Parts of the System
HTTPClientstruct:
This file extendsHTTPClientwith staking-related methods.HTTPClientlikely provides generic REST communication capabilities and base URLs.Models and Types:
The file operates on several domain types such asValidatorResponse,Validator,ValidatorsResponse,ValidatorUnbonding, andValidatorCommission. These are presumably defined elsewhere in the cosmos package.REST API:
This module interacts directly with the Cosmos SDK REST API endpoints under/cosmos/staking/v1beta1/validators.Financial Calculations:
The APR computations here are relevant to any component displaying or processing expected staking rewards, linking this file to reward calculators or UI components presenting validator info.
Visual Diagram
Below is a Mermaid class diagram representing the main structures and methods in `staking.go`:
classDiagram
class HTTPClient {
+GetValidators(apr *big.Float, cursor string, pageSize int) *ValidatorsResponse
+GetValidator(addr string, apr *big.Float) *Validator
}
class Validator {
+Address: string
+Moniker: string
+Jailed: bool
+Status: int
+Tokens: string
+Shares: string
+Website: string
+Description: string
+APR: string
+Unbonding: ValidatorUnbonding
+Commission: ValidatorCommission
}
class ValidatorUnbonding {
+Height: int64
+Timestamp: int64
}
class ValidatorCommission {
+Rate: string
+MaxRate: string
+MaxChangeRate: string
}
class ValidatorsResponse {
+Validators: []Validator
+Pagination: Pagination
}
HTTPClient --> ValidatorsResponse : returns
HTTPClient --> Validator : returns
HTTPClient ..> Validator : uses httpValidator()
Validator o-- ValidatorUnbonding
Validator o-- ValidatorCommission
Summary
The `staking.go` file provides essential staking-related query functionality by wrapping Cosmos SDK REST API endpoints. It supports retrieving validator lists with pagination and individual validator details while adjusting APR values to reflect commission fees. It implements precise financial calculations and error handling, making it a critical component of Cosmos blockchain clients needing staking data.
This file interacts closely with HTTP client infrastructure and domain models in the broader `cosmos` package, serving as a clean, reusable interface for staking queries.