account.go
Overview
This file, [account.go](/projects/291/69316), is part of the `cosmos` package and provides a set of functions implemented as methods on the `HTTPClient` type to interact with the Cosmos blockchain via its REST LCD (Light Client Daemon) API. The primary purpose of this file is to query various account-related data such as account details, balances, staking delegations, redelegations, unbondings, and rewards.
Each function sends HTTP GET requests to specific Cosmos SDK REST endpoints, deserializes the JSON responses into Go structs, and processes the data to return a structured and usable response. The file also includes a helper function for processing balances.
The functionality in this file serves as a client-side interface layer, abstracting the REST API details and enabling other parts of the system to easily fetch and work with Cosmos account data.
Types and Structures
The file references several domain-specific types (assumed defined elsewhere in the package or project):
HTTPClient— client struct that wraps REST API access (c.LCD).AccountResponse— represents account data returned byGetAccount.BalanceResponse— structured balance data returned byGetBalance.Delegation— represents a staking delegation.Redelegation— represents redelegation data.RedelegationEntry— entries within a redelegation.Unbonding— represents unbonding delegations.UnbondingEntry— entries within unbondings.Reward— staking reward info.Value— generic amount/denomination pair.Pagination— pagination info for API calls.Validator— validator metadata, fetched viaGetValidator.
Functions and Methods
(c *HTTPClient) GetAccount(address string) (*AccountResponse, error)
Fetches the Cosmos account information for the given account address.
Parameters:
address(string): The Cosmos account address.
Returns:
Pointer to
AccountResponsecontaining the account address, account number, and sequence.errorif the HTTP request or unmarshalling fails.
Description:
Sends a GET request to
/cosmos/auth/v1beta1/accounts/{address}.Parses account number and sequence (as strings from JSON) into integers.
Usage Example:
client := cosmos.HTTPClient{/*...*/} accountResp, err := client.GetAccount("cosmos1...") if err != nil { log.Fatal(err) } fmt.Println(accountResp.AccountNumber)
(c *HTTPClient) GetBalance(address string, baseDenom string) (*BalanceResponse, error)
Retrieves the balances for the given account address.
Parameters:
address(string): The Cosmos account address.baseDenom(string): The denomination considered as the base coin (e.g.,"uatom").
Returns:
Pointer to
BalanceResponsewith the base coin balance and other assets.errorif the request fails or JSON unmarshalling fails.
Description:
Calls
/cosmos/bank/v1beta1/balances/{address}.Uses helper function
balanceto separate the base denomination from other tokens.
Usage Example:
balanceResp, err := client.GetBalance("cosmos1...", "uatom") if err != nil { log.Fatal(err) } fmt.Println(balanceResp.Amount) // base denom amount
(c *HTTPClient) GetDelegations(address string, apr *big.Float) ([]Delegation, error)
Fetches all staking delegations for the account.
Parameters:
address(string): The delegator's account address.apr(*big.Float): Annual Percentage Rate used for validator info (optional, passed toGetValidator).
Returns:
Slice of
Delegationstructs containing validator info, shares, and balance.erroron failure.
Description:
Calls
/cosmos/staking/v1beta1/delegations/{address}.For each delegation, fetches validator details via
GetValidator.Handles failures to fetch validator info by creating minimal validator with address only.
Usage Example:
delegations, err := client.GetDelegations("cosmos1...", nil) if err != nil { log.Fatal(err) } for _, d := range delegations { fmt.Println(d.Validator.Address, d.Balance.Amount) }
(c *HTTPClient) GetRedelegations(address string, apr *big.Float) ([]Redelegation, error)
Retrieves redelegations for the account.
Parameters:
address(string): The delegator's account address.apr(*big.Float): APR used for validator info retrieval.
Returns:
Slice of
Redelegationstructs, each including source and destination validators and entries.erroron failure.
Description:
Calls
/cosmos/staking/v1beta1/delegators/{address}/redelegations.Parses redelegation entries, converting completion times to Unix timestamps (string).
Fetches validator info for source and destination validators, falling back to address-only on failure.
Usage Example:
redelegations, err := client.GetRedelegations("cosmos1...", nil) if err != nil { log.Fatal(err) } for _, r := range redelegations { fmt.Println(r.SourceValidator.Address, r.DestinationValidator.Address) }
(c *HTTPClient) GetUnbondings(address string, baseDenom string, apr *big.Float) ([]Unbonding, error)
Fetches unbonding delegations for the account.
Parameters:
address(string): The delegator's account address.baseDenom(string): Base denomination string.apr(*big.Float): APR used for validator info retrieval.
Returns:
Slice of
Unbondingstructs, each with validator and unbonding entries.erroron failure.
Description:
Calls
/cosmos/staking/v1beta1/delegators/{address}/unbonding_delegations.Converts completion times to Unix timestamps.
Uses base denomination for unbonding balances.
Fetches validator info, falling back on failure.
Usage Example:
unbondings, err := client.GetUnbondings("cosmos1...", "uatom", nil) if err != nil { log.Fatal(err) } fmt.Println(unbondings[0].Validator.Address)
(c *HTTPClient) GetRewards(address string, apr *big.Float) ([]Reward, error)
Retrieves staking rewards for the delegator.
Parameters:
address(string): The delegator's account address.apr(*big.Float): APR used when fetching validator info.
Returns:
Slice of
Rewardstructs with validator info and rewards.erroron failure.
Description:
Calls
/cosmos/distribution/v1beta1/delegators/{address}/rewards.For each reward entry, fetches validator info.
Rewards are parsed as a slice of
Value(amount/denom pairs).
Usage Example:
rewards, err := client.GetRewards("cosmos1...", nil) if err != nil { log.Fatal(err) } for _, r := range rewards { fmt.Println(r.Validator.Address, r.Rewards) }
balance(balances sdk.Coins, baseDenom string) (*BalanceResponse, error)
Helper function to process balances, separating base denomination from other assets.
Parameters:
balances(sdk.Coins): Slice of coins (amount/denom).baseDenom(string): Denomination considered base.
Returns:
Pointer to
BalanceResponsecontaining:Amount: string representing base denom amount (or "0" if none).Assets: slice ofValuerepresenting other tokens.
error— not returned currently, but signature allows future error handling.
Description:
Iterates over all coins, sets base denom amount, and collects others.
Usage Example:
b, _ := balance(coins, "uatom") fmt.Println(b.Amount)
Important Implementation Details
HTTP Requests:
All functions use the
c.LCD.R()request builder (likely from a REST client likeresty).They set the result pointer to a specific response struct for automatic JSON unmarshalling.
Errors from the HTTP call are wrapped with context using
github.com/pkg/errors.
Pagination:
Each query response includes a
Paginationfield, but pagination is not handled explicitly; only the first page of results is fetched.
Validator Data:
Functions fetching delegations, redelegations, unbondings, and rewards attempt to get detailed validator info by calling
GetValidator.If
GetValidatorfails, a fallbackValidatorstruct with only the validator address is created to avoid failure propagation.
Time Conversion:
Completion times in redelegations and unbondings are converted from
time.Timeto Unix timestamp strings for uniformity.
Data Types:
JSON string fields representing numbers (e.g., account number, sequence, shares) are parsed into appropriate Go types (
int,string).Cosmos SDK types (
sdk.Coins,sdk.Coin) are used for handling coins.
Interaction with Other Parts of the System
Relies on the
HTTPClientstruct which wraps a REST client configured to communicate with the Cosmos LCD endpoints.Depends on external domain types such as
AccountResponse,BalanceResponse,Delegation,Redelegation,Unbonding,Reward,Value,Validator, andPaginationwhich are presumably defined elsewhere in thecosmospackage or project.Uses a
GetValidatormethod (not included in this file) to fetch validator metadata, likely implemented in another file of the same package.Utilizes Cosmos SDK types (
sdk.Coins,sdk.Coin) from the official Cosmos SDK Go module.Error wrapping with
github.com/pkg/errorsintegrates with the project's error handling approach.This file acts as a data retrieval layer for account-related blockchain data, likely consumed by higher-level business logic or UI components.
Visual Diagram
classDiagram
class HTTPClient {
+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
}
class AccountResponse {
+Address string
+AccountNumber int
+Sequence int
}
class BalanceResponse {
+Amount string
+Assets []Value
}
class Delegation {
+Validator Validator
+Shares string
+Balance Value
}
class Redelegation {
+SourceValidator Validator
+DestinationValidator Validator
+Entries []RedelegationEntry
}
class RedelegationEntry {
+CompletionTime string
+Shares string
+Balance string
}
class Unbonding {
+Validator Validator
+Entries []UnbondingEntry
}
class UnbondingEntry {
+CompletionTime string
+Balance Value
}
class Reward {
+Validator Validator
+Rewards []Value
}
class Value {
+Amount string
+Denom string
}
class Validator {
+Address string
// Other validator properties...
}
HTTPClient --> AccountResponse
HTTPClient --> BalanceResponse
HTTPClient --> Delegation
HTTPClient --> Redelegation
HTTPClient --> Unbonding
HTTPClient --> Reward
Delegation --> Validator
Delegation --> Value
Redelegation --> Validator : SourceValidator
Redelegation --> Validator : DestinationValidator
Redelegation --> RedelegationEntry
RedelegationEntry --> Value : Balance (string here)
Unbonding --> Validator
Unbonding --> UnbondingEntry
UnbondingEntry --> Value
Reward --> Validator
Reward --> Value
Summary
The [account.go](/projects/291/69316) file provides a comprehensive client interface for retrieving Cosmos blockchain account and staking-related data through REST API calls. It handles JSON deserialization, error management, and data structuring to present clean, usable Go types. It is a crucial part of the Cosmos blockchain integration in this system, abstracting low-level API details and enabling other modules to work with account, balance, delegation, redelegation, unbonding, and rewards information efficiently.