tx.go
Overview
The [tx.go](/projects/291/69258) file is part of the Cosmos SDK client package and provides functionalities related to transaction (tx) handling via HTTP requests and transaction processing utilities. It primarily facilitates:
Fetching transaction history for a given address with pagination support.
Retrieving a specific transaction by its ID.
Searching for transactions using query parameters.
Broadcasting raw transactions to the network.
Parsing transaction events and messages for easier consumption.
Decoding raw transactions from various encodings.
Extracting fees and involved addresses from transactions.
This file acts as a bridge between the Cosmos SDK transaction data structures and external access via REST or RPC, making it essential for wallet services, blockchain explorers, or any service interacting with Cosmos-based blockchains.
Detailed Documentation
HTTPClient Methods
These methods are defined on the `HTTPClient` type (not shown in this file but assumed to exist) and are responsible for interacting with CometBFT RPC and Cosmos LCD endpoints.
func (c *HTTPClient) GetTxHistory(address string, cursor string, pageSize int, sources map[string]*TxState) (*TxHistoryResponse, error)
Fetches paginated transaction history for a specific blockchain address. It supports multiple "sources" to track pagination state per source.
Parameters:
address(string): The blockchain address to fetch transactions for.cursor(string): An opaque cursor string for pagination.pageSize(int): Number of transactions per page.sources(map[string]*TxState): Map of transaction states per source, used for pagination tracking.
Returns:
Pointer to
TxHistoryResponse: Contains a page of transactions and pagination info.error: On failure to decode cursor or fetch transactions.
Usage Example:
history, err := client.GetTxHistory("cosmos1...", "", 20, initialSources)
if err != nil {
log.Fatal(err)
}
// Process history.Txs ...
Implementation details:
Initializes internal
Historystruct with cursor and states.Decodes the cursor if provided to restore pagination state.
Calls
history.get()to retrieve transactions from all sources.Wraps and returns errors if any occur.
func (c *HTTPClient) GetTx(txid string) (*coretypes.ResultTx, error)
Retrieves a transaction by its transaction hash.
Parameters:
txid(string): Transaction hash, may or may not be prefixed with "0x".
Returns:
Pointer to
coretypes.ResultTx: The transaction details.error: On RPC failure or unmarshalling error.
Usage Example:
tx, err := client.GetTx("ABC123...")
if err != nil {
log.Fatal(err)
}
fmt.Println(tx.TxResult)
Implementation details:
Ensures the txid has "0x" prefix.
Calls
/txRPC endpoint withhashquery param.Handles JSON RPC response and unmarshals into
ResultTx.
func (c *HTTPClient) TxSearch(query string, page int, pageSize int) (*coretypes.ResultTxSearch, error)
Searches transactions matching a given query with pagination.
Parameters:
query(string): CometBFT query string (e.g.,"message.sender='cosmos1...'").page(int): Page number.pageSize(int): Number of transactions per page.
Returns:
Pointer to
coretypes.ResultTxSearch: Contains matched transactions and count.error: On RPC or unmarshalling failure.
Usage Example:
result, err := client.TxSearch("tx.height > 1000", 1, 10)
if err != nil {
log.Fatal(err)
}
for _, tx := range result.Txs {
fmt.Println(tx.TxHash)
}
Implementation details:
Calls
/tx_searchendpoint with query parameters.Special handling when requested page is out of range (returns empty result).
func (c *HTTPClient) BroadcastTx(rawTx string) (string, error)
Broadcasts a raw base64 encoded transaction to the blockchain synchronously.
Parameters:
rawTx(string): Base64 encoded transaction bytes.
Returns:
Transaction hash string on success.
errorif broadcasting fails or transaction response indicates an error.
Usage Example:
txHash, err := client.BroadcastTx(base64Tx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Broadcasted with hash: %s\n", txHash)
Implementation details:
Decodes base64 string into bytes.
Sends POST request to Cosmos SDK LCD endpoint
/cosmos/tx/v1beta1/txs.Uses broadcast mode
BROADCAST_MODE_SYNC.Checks response code and returns errors with codespace and code if failed.
Utility Functions and Types
func ParseEvents(txResult abcitypes.ExecTxResult) EventsByMsgIndex
Parses ABCI transaction execution results to extract structured events indexed by message index.
Parameters:
txResult(abcitypes.ExecTxResult): The ABCI execution result of a transaction.
Returns:
EventsByMsgIndex: A map where keys are message indices (string), and values are event attributes by event type.
Details:
Supports parsing both JSON logs and legacy event structures.
On parse failure, returns a special "error" event with the raw log.
func ParseMessages(msgs []sdk.Msg, events EventsByMsgIndex) []Message
Converts raw Cosmos SDK messages and their associated events into a slice of simplified `Message` structs for easier interpretation.
Parameters:
msgs([]sdk.Msg): Slice of SDK message interfaces.events(EventsByMsgIndex): Parsed events mapped by message index.
Returns:
Slice of
Messagestructs representing key details from known message types.
Supported message types:
Bank Send (
banktypes.MsgSend)Staking Delegate/Undelegate/BeginRedelegate (
stakingtypes.*)Distribution Withdraw Delegator Reward (
distributiontypes.MsgWithdrawDelegatorReward)
Details:
Extracts addresses, amounts, and types of transactions.
Skips messages if an "error" event is present.
Logs errors if event parsing for amounts fails.
func Fee(tx SigningTx, txid string, denom string) Value
Extracts the fee information from a transaction.
Parameters:
tx(SigningTx): The transaction interface providing fee data.txid(string): Transaction hash (used for logging).denom(string): Default denomination if no fee is present.
Returns:
Value: Struct containing fee amount and denomination.
Details:
Defaults to zero fee if none specified.
Logs a warning if multiple fees are detected, uses the first fee.
func DecodeTx(encoding params.EncodingConfig, rawTx interface{}) (sdk.Tx, SigningTx, error)
Decodes a raw transaction input into Cosmos SDK transaction interfaces.
Parameters:
encoding(params.EncodingConfig): Encoding configuration containing codecs and tx decoders.rawTx(interface{}): Raw transaction data; supported types:string(base64 encoded)[]byte(protobuf encoded)cometbfttypes.Tx
Returns:
sdk.Tx: Decoded transaction interface.SigningTx: Transaction interface supporting signing.erroron failure.
Usage Example:
tx, signingTx, err := DecodeTx(encodingConfig, base64RawTx)
if err != nil {
log.Fatal(err)
}
Implementation details:
Decodes base64 string or uses raw bytes directly.
Uses TxDecoder from encoding config.
Wraps transaction in builder if implements
SigningTx.
func GetTxAddrs(events EventsByMsgIndex, messages []Message) []string
Extracts all unique addresses involved in a transaction from both events and messages.
Parameters:
events(EventsByMsgIndex): Parsed transaction events.messages([]Message): Parsed messages.
Returns:
Slice of unique address strings.
Details:
Scans event attributes with keys like "spender", "sender", "receiver", "recipient", "validator".
Also collects addresses from all messages.
Ensures each address is returned only once.
Important Implementation Details and Algorithms
Cursor-based pagination:
GetTxHistoryuses a cursor encoded state to maintain pagination across multiple transaction sources (e.g., mempool, indexed txs). The cursor is decoded and used to update per-source page numbers.Event parsing robustness:
ParseEventsattempts to parse ABCI logs as JSON first, falling back to raw event lists if logs are empty or malformed, ensuring maximum compatibility with different chain versions.Message type detection:
ParseMessagesuses Go type assertions to identify known Cosmos SDK message types and extract meaningful transaction details such as addresses and amounts, enabling downstream applications to display human-readable tx info.Fee extraction with warnings:
TheFeefunction handles cases where transactions might specify multiple fees by logging a warning and selecting the first fee, which is a pragmatic choice given most transactions only have one fee.Decoding transaction data:
DecodeTxsupports raw transactions in multiple formats (base64 string, raw bytes, CometBFT Tx interface) and uses the SDK's configured TxDecoder, ensuring compatibility with various encoding schemes.
Interactions with Other Parts of the System
Cosmos SDK types and modules:
Imports message types from bank, staking, distribution modules to interpret and parse transaction messages.CometBFT RPC and ABCI types:
Uses CometBFT RPC endpoints (/tx,/tx_search) and ABCI transaction result types for querying and processing blockchain transactions.EncodingConfig:
Relies on the Cosmos SDKparams.EncodingConfigfor protobuf encoding/decoding of transactions.HTTPClient (external type):
This file extends anHTTPClienttype with methods that perform REST/RPC calls to the blockchain node endpoints.Logging and error wrapping:
Uses structured error wrapping viagithub.com/pkg/errorsand Cosmos SDK error types for clear error propagation.
Visual Diagram
flowchart TD
A[HTTPClient] -->|GetTxHistory| B[History]
B -->|decode cursor| C[Cursor]
C --> D[CursorState (per source)]
A -->|GetTx| E[/tx RPC endpoint/]
A -->|TxSearch| F[/tx_search RPC endpoint/]
A -->|BroadcastTx| G[/cosmos/tx/v1beta1/txs LCD endpoint/]
subgraph Parsing
H[ParseEvents] --> I[EventsByMsgIndex]
J[ParseMessages] --> K[[]Message]
L[GetTxAddrs] --> M[[]string (addresses)]
N[DecodeTx] --> O[sdk.Tx, SigningTx]
P[Fee] --> Q[Value (fee info)]
end
The diagram shows the main HTTPClient methods and their interaction with blockchain RPC/LCD endpoints.
Parsing functions operate on transaction results and messages, producing structured outputs for use in the application.
Summary
[tx.go](/projects/291/69258) is a core utility file that enables querying, decoding, parsing, and broadcasting Cosmos SDK transactions via HTTP clients. It abstracts complex transaction handling logic, event parsing, and message interpretation, facilitating integration with Cosmos-based blockchains. The file's careful design ensures robustness against protocol variations and provides clear, structured data for downstream applications.