Thorchain-Specific Functionality
This module encompasses specialized components tailored for the Thorchain blockchain within the ShapeShift Unchained platform. It addresses Thorchain's unique blockchain event structures, transaction formats, and affiliate fee indexing, as well as its integration with the Cosmos SDK framework. The module extends generic Cosmos functionality by implementing Thorchain-specific parsing, transaction synthesis, and revenue tracking to provide accurate and enriched blockchain data to clients.
Core Concepts and Purpose
Thorchain-Specific Functionality exists to bridge the generic Cosmos-based API framework with the particularities of Thorchain's blockchain data and operations. Thorchain differs from typical Cosmos chains in transaction event structures, fee models, and message types, necessitating:
Custom Transaction Parsing: Extracting and interpreting Thorchain-specific messages and block events.
Synthetic Transaction Creation: Building transactions from block-end events unique to Thorchain.
Affiliate Fee Indexing: Tracking affiliate revenue derived from Thorchain's fee structure.
Cosmos SDK Integration: Leveraging the Cosmos SDK and CometBFT frameworks while customizing handlers for Thorchain.
This module ensures that clients receive accurate transaction histories, fee estimations, and affiliate revenue data reflective of Thorchain's blockchain behavior.
Module Components and How They Work
1. API Server (go/coinstacks/thorchain/api/api.go)
The API server provides REST and WebSocket endpoints exposing Thorchain blockchain data. It builds upon a Cosmos SDK-based API framework (`cosmos.API`) but injects Thorchain-specific logic via a custom `Handler`. Key features include:
Routing: Defines routes for account info, transaction history, transaction details, sending transactions, gas estimation, and affiliate revenue.
WebSocket Support: Enables real-time subscription to pending and confirmed transactions.
Affiliate Revenue Endpoint: Exposes an endpoint to query affiliate fee revenue (
/api/v1/affiliate/revenue).
The API instantiates a `Handler` that combines Cosmos base handling with Thorchain-specific processing and an `AffiliateFeeIndexer` for revenue tracking.
handler := &Handler{
Handler: &cosmos.Handler{...},
indexer: indexer,
}
The server integrates middleware for logging, CORS, and Prometheus metrics, and hosts Swagger documentation.
2. Handler (go/coinstacks/thorchain/api/handler.go)
The `Handler` extends the generic Cosmos `Handler` to implement Thorchain-specific business logic:
WebSocket Block Event Handling: Overrides the
StartWebsocketmethod to process block events usingthorchain.GetTxFromBlockEvents, which creates synthetic transactions from Thorchain block-end events.Transaction History: Implements
GetTxHistoryby callingthorchain.GetTxHistoryto query transactions associated with an address, filtering using Thorchain-specific event queries.Affiliate Revenue Calculation: Aggregates affiliate fees recorded by the
AffiliateFeeIndexerover a specified time range and returns total revenue and affiliate addresses.Message and Fee Parsing: Provides Thorchain-specific parsing of messages and fees, overriding default Cosmos SDK implementations to handle Thorchain message types and fee adjustments.
Example of affiliate revenue retrieval:
func (h *Handler) GetAffiliateRevenue(start int, end int) (*AffiliateRevenue, error) {
total := big.NewInt(0)
for _, fee := range h.indexer.AffiliateFees {
if fee.Timestamp >= int64(start) && fee.Timestamp <= int64(end) {
amount := new(big.Int)
amount.SetString(fee.Amount, 10)
total.Add(total, amount)
}
}
...
return a, nil
}
3. Transaction Parsing and Formatting (go/pkg/thorchain/tx.go)
This component is responsible for interpreting Thorchain blockchain events and synthesizing transaction data:
GetTxHistory: Queries blocks containing transactions related to a public key, inspects block results for Thorchain-specific events, and filters transactions by involvement of the address.
ParseMessages: Parses Thorchain-specific message types such as
MsgSend,MsgDeposit, andMsgObservedTxQuorum, extracting relevant addresses, amounts, and event-derived information like refunds, withdrawals, or outbound transfers. It also synthesizes additional messages from events associated with deposits.GetTxFromBlockEvents: Builds synthetic transactions from block-end events, particularly handling
EventOutboundtypes to create detailed transaction representations with fees, memos, and involved addresses.formatTx: Converts synthetic transactions into generic Cosmos SDK transaction structures for API consumption.
The parsing functions carefully combine raw blockchain event data with domain-specific knowledge of Thorchain's transaction semantics, ensuring that clients receive a coherent and enriched view of on-chain activity.
4. Thorchain Event Types (go/pkg/thorchain/events.go)
This package defines Thorchain-specific blockchain event models and parsing logic:
Typed Events: Structures like
EventFeeandEventOutboundrepresent parsed blockchain events with fields such as transaction IDs, coins, sender/receiver addresses, and memos.ParseBlockEvents: Converts raw ABCI events from blocks into typed event structures and organizes them by message index for easier processing.
typedEventsToMessages: Transforms typed events into generic Cosmos SDK messages with address and value information, enabling integration with the broader Cosmos message parsing logic.
This event parsing layer abstracts the complexity of raw blockchain event formats and provides structured data for higher-level transaction processing.
5. Fee Parsing and Adjustment (go/pkg/thorchain/thorchain.go)
Thorchain deducts a native fee automatically from every transaction, which may not be explicitly represented in standard fee fields. This module:
Extends the base Cosmos fee parsing by adding the native fee amount to the parsed fee, ensuring accurate fee data.
Uses big integer arithmetic to safely add the native fee to the existing fee amount.
func ParseFee(tx cosmos.SigningTx, txid string, denom string, nativeFee int) cosmos.Value {
fee := cosmos.Fee(tx, txid, denom)
i := new(big.Int)
i.SetString(fee.Amount, 10)
fee.Amount = i.Add(i, big.NewInt(int64(nativeFee))).String()
return fee
}
Interaction with Other System Components
Cosmos SDK Base API: The Thorchain API wraps and extends the generic Cosmos API and handler (
cosmos.APIandcosmos.Handler), reusing common logic while injecting Thorchain-specific behavior.Affiliate Fee Indexer: Integrated into the handler to track affiliate fee events parsed from blockchain data, exposing affiliate revenue via the API.
WebSocket Manager: Used by the API server to handle real-time event subscriptions, with Thorchain-specific transaction formatting applied to events before broadcasting.
HTTP Client & Block Service: Used by the handler to query blockchain data, including block results and search for transactions relevant to a pubkey.
Prometheus Metrics: Exposed by the API server to monitor request rates and performance.
This module is tightly coupled with Thorchain blockchain data and the Cosmos SDK-based infrastructure, forming a specialized layer that enriches and adapts blockchain data for client APIs.
Design Patterns and Unique Approaches
Decorator Pattern: The
Handlerdecorates the base Cosmos handler by embedding it and overriding specific methods to add Thorchain logic without rewriting the entire handler.Synthetic Transaction Creation: Instead of relying solely on on-chain transactions, the module synthesizes transactions from block-end events to capture actions unique to Thorchain's architecture.
Event-Driven Parsing: Uses typed event parsing and mapping to message structures, enabling flexible handling of complex blockchain event types.
Big Integer Arithmetic for Fees: Ensures precision and correctness in fee calculations by handling fees as big integers.
Affiliate Revenue Aggregation: Maintains an in-memory index of affiliate fees, enabling efficient revenue calculation over arbitrary time intervals.
Illustration of Key Workflow: Transaction Parsing and Affiliate Revenue Retrieval
sequenceDiagram
participant API as Thorchain API Server
participant Handler as Thorchain Handler
participant HTTPClient as Cosmos HTTP Client
participant BlockService as Block Service
participant Indexer as AffiliateFeeIndexer
Client->>API: Request Tx History for Pubkey
API->>Handler: GetTxHistory(pubkey)
Handler->>HTTPClient: Search Blocks with Pubkey Events
HTTPClient->>Handler: Return Matching Blocks
Handler->>HTTPClient: Fetch Block Results for Each Block
HTTPClient->>Handler: Return Block Events
Handler->>thorchain.tx: Parse Block Events and Synthesize Tx
Handler->>Client: Return Formatted Tx History
Client->>API: Request Affiliate Revenue (start, end)
API->>Handler: GetAffiliateRevenue(start, end)
Handler->>Indexer: Aggregate Affiliate Fees in Time Range
Indexer->>Handler: Return Total Revenue and Addresses
Handler->>Client: Return Affiliate Revenue Data
This documentation captures the specialized Thorchain functionality within the ShapeShift Unchained platform, highlighting how the module adapts generic Cosmos infrastructure to Thorchain's unique blockchain characteristics while providing enriched API services and affiliate revenue tracking.