handler.go
Overview
The [handler.go](/projects/291/69233) file defines the `Handler` struct and related methods for interacting with the Cosmos-based Thorchain blockchain within the API layer of the application. This file acts as a bridge between the underlying Cosmos SDK handler logic and Thorchain-specific transaction parsing and fee calculation. It exposes functionality to:
Start a websocket client connection for real-time blockchain data.
Retrieve general blockchain info.
Fetch transaction history for a given public key.
Parse blockchain messages and events into structured data.
Calculate transaction fees based on the blockchain's native token and fee structure.
This modular handler extends the generic Cosmos handler, specializing it with Thorchain-specific logic and integrations, enabling the API to serve Thorchain blockchain data and operations efficiently.
Detailed Documentation
Type: Handler
type Handler struct {
*cosmos.Handler
}
Description:
Handleris a struct embedding thecosmos.Handlertype, inheriting its methods and properties while extending or overriding them with Thorchain-specific functionality.Purpose:
Acts as a specialized handler for Thorchain operations, leveraging the Cosmos SDK handler internally and integrating Thorchain-specific parsing and fee calculation logic.
Method: StartWebsocket() error
func (h *Handler) StartWebsocket() error
Description:
Initiates the websocket client to start streaming real-time blockchain data.Parameters:
None.Returns:
error– Returns an error (wrapped with stack trace) if the websocket client fails to start, otherwise returnsnil.Usage Example:
handler := &Handler{/* initialized cosmos.Handler */} err := handler.StartWebsocket() if err != nil { log.Fatalf("Failed to start websocket: %v", err) }Implementation Details:
Calls the embeddedWSClient.Start()method from the underlying Cosmos handler's websocket client instance. Useserrors.WithStackfrom thepkg/errorspackage to annotate errors with stack traces.
Type: Info
type Info struct {
// swagger:allOf
cosmos.Info
}
Description:
Infois a wrapper struct embeddingcosmos.Infoto represent high-level information about the running coinstack. It is annotated for Swagger API documentation generation.Purpose:
To provide blockchain info in the API response format, reusing the Cosmos blockchain info structure while allowing future Thorchain-specific extensions.
Method: GetInfo() (api.Info, error)
func (h *Handler) GetInfo() (api.Info, error)
Description:
Retrieves general information about the running blockchain node/coinstack.Returns:
api.Info– An interface representing blockchain info (concretely anInfostruct wrappingcosmos.Info).error– Any error encountered during info retrieval.
Usage Example:
info, err := handler.GetInfo() if err != nil { log.Println("Error getting info:", err) } else { fmt.Printf("Chain ID: %s\n", info.GetChainID()) }Implementation Details:
Delegates to the embeddedcosmos.Handler.GetInfo()method, asserts the returned info's underlying type tocosmos.Info, and wraps it inside the localInfostruct for API consistency.
Method: GetTxHistory(pubkey string, cursor string, pageSize int) (api.TxHistory, error)
func (h *Handler) GetTxHistory(pubkey string, cursor string, pageSize int) (api.TxHistory, error)
Description:
Fetches a paginated list of blockchain transactions associated with a given public key.Parameters:
pubkey string– The public key (address) for which to retrieve transaction history.cursor string– A pagination cursor indicating the starting point for retrieval (can be empty for first page).pageSize int– The maximum number of transactions to return.
Returns:
api.TxHistory– A collection of transactions with pagination metadata.error– Any error encountered during retrieval.
Usage Example:
txHistory, err := handler.GetTxHistory("pubkey123", "", 10) if err != nil { log.Println("Error fetching tx history:", err) } else { for _, tx := range txHistory.Transactions { fmt.Println(tx.ID) } }Implementation Details:
This method delegates transaction history retrieval to the Thorchain-specificthorchain.GetTxHistoryfunction, passing the embedded Cosmos handler as context.
Method: ParseMessages(msgs []sdk.Msg, events cosmos.EventsByMsgIndex) []cosmos.Message
func (h *Handler) ParseMessages(msgs []sdk.Msg, events cosmos.EventsByMsgIndex) []cosmos.Message
Description:
Parses raw Cosmos SDK messages and their associated events into structured Thorchain-specific message objects.Parameters:
msgs []sdk.Msg– Slice of raw Cosmos SDK messages from a transaction.events cosmos.EventsByMsgIndex– Map of blockchain events grouped by message index.
Returns:
[]cosmos.Message– Slice of parsed message objects with enriched Thorchain-specific data.
Usage Example:
parsedMsgs := handler.ParseMessages(rawMsgs, eventsByIndex) for _, msg := range parsedMsgs { fmt.Println(msg.Type()) }Implementation Details:
This method callsthorchain.ParseMessagesto leverage Thorchain-specific parsing logic, which interprets the messages and events in the context of Thorchain transaction semantics.
Method: ParseFee(tx cosmos.SigningTx, txid string) cosmos.Value
func (h *Handler) ParseFee(tx cosmos.SigningTx, txid string) cosmos.Value
Description:
Calculates the transaction fee for a given signed transaction.Parameters:
tx cosmos.SigningTx– The signed transaction object to evaluate fees for.txid string– The transaction ID (hash).
Returns:
cosmos.Value– The parsed fee amount and denomination.
Usage Example:
fee := handler.ParseFee(signedTx, "txid123") fmt.Printf("Fee: %s %s\n", fee.Amount, fee.Denom)Implementation Details:
Delegates tothorchain.ParseFeeproviding the transaction, its ID, and the handler's configured denomination and native fee flag to correctly interpret the fee according to Thorchain's fee model.
Important Implementation Details and Algorithms
Composition Over Inheritance:
TheHandlerstruct embeds the genericcosmos.Handler, extending functionality without rewriting base Cosmos SDK logic.Delegation to Thorchain Package:
Thorchain-specific business logic for transaction history retrieval, message parsing, and fee calculation is encapsulated within thethorchainpackage. This separation of concerns promotes maintainability and clearer domain boundaries.Error Wrapping:
Errors from starting the websocket client are wrapped with stack traces for improved debugging usinggithub.com/pkg/errors.Swagger Annotations:
TheInfostruct is annotated for Swagger, facilitating automated API documentation generation.
Interaction with Other Parts of the System
Cosmos SDK Integration:
The handler relies heavily on the embeddedcosmos.Handlerto interface with the Cosmos SDK blockchain infrastructure, including websocket connectivity and blockchain info retrieval.Thorchain Package:
The Thorchain-specific logic is abstracted into thethorchainpackage, which provides specialized parsing and transaction history functions tailored to Thorchain’s protocol.API Layer:
TheHandlerstruct and its methods are designed to serve API endpoints, offering blockchain info, transaction history, and transaction parsing services to client applications.Websocket Client:
The websocket client embedded in the underlyingcosmos.Handleris started viaStartWebsocket, enabling real-time data streaming.
Visual Diagram
classDiagram
class Handler {
+StartWebsocket() error
+GetInfo() (api.Info, error)
+GetTxHistory(pubkey string, cursor string, pageSize int) (api.TxHistory, error)
+ParseMessages(msgs []sdk.Msg, events cosmos.EventsByMsgIndex) []cosmos.Message
+ParseFee(tx cosmos.SigningTx, txid string) cosmos.Value
}
class cosmos.Handler {
+WSClient
+GetInfo() (cosmos.Info, error)
+StartWebsocket() error
}
class thorchain {
+GetTxHistory(h cosmos.Handler, pubkey string, cursor string, pageSize int) (api.TxHistory, error)
+ParseMessages(msgs []sdk.Msg, events cosmos.EventsByMsgIndex) []cosmos.Message
+ParseFee(tx cosmos.SigningTx, txid string, denom string, nativeFee bool) cosmos.Value
}
Handler --> cosmos.Handler : embeds
Handler ..> thorchain : delegates calls
Handler --> "WSClient" : uses to start websocket
Summary
The [handler.go](/projects/291/69233) file encapsulates Thorchain-specific blockchain handler logic by extending a generic Cosmos SDK handler. It provides API-ready methods for starting websocket connections, fetching chain info, retrieving transaction histories, parsing messages, and computing fees. By delegating protocol-specific parsing and history retrieval to the Thorchain package and embedding a robust Cosmos handler, this file ensures modularity, maintainability, and clear separation of concerns within the blockchain API service.