api.go
Overview
`api.go` implements the Thorchain Unchained API server, providing REST and WebSocket endpoints to expose Thorchain blockchain data and related services. It builds upon a generic Cosmos SDK-based API framework by embedding a customized Thorchain-specific handler that extends Cosmos functionality with Thorchain-specific transaction parsing, synthetic transaction creation, and affiliate fee revenue tracking.
This file orchestrates:
HTTP server setup with routing, middleware (CORS, logging, Prometheus metrics)
WebSocket manager for real-time subscriptions to blockchain events
REST API endpoints for account data, transaction history, transaction details, sending transactions, gas estimation, and affiliate revenue
Integration with an affiliate fee indexer to aggregate revenue data
Serving Swagger UI and API documentation
By combining generic Cosmos API features with Thorchain-specific extensions, this file enables clients to interact with Thorchain blockchain data through a consistent and enriched API interface.
Detailed Explanation
Constants
Constant | Type | Description |
|---|---|---|
`int` | HTTP server port (default: 3000) | |
`PPROF_PORT` | `int` | Profiling server port (default: 3001) |
`GRACEFUL_SHUTDOWN` | `time.Duration` | Timeout for graceful server shutdown (15 seconds) |
`WRITE_TIMEOUT` | `time.Duration` | HTTP server write timeout (15 seconds) |
`READ_TIMEOUT` | `time.Duration` | HTTP server read timeout (15 seconds) |
`IDLE_TIMEOUT` | `time.Duration` | HTTP server idle timeout (60 seconds) |
Type: API
type API struct {
*cosmos.API
handler *Handler
}
Embeds the generic Cosmos SDK API (
cosmos.API), reusing standard blockchain API logic.Holds a pointer to a Thorchain-specific
Handlerthat adds custom processing and affiliate fee functionality.
Function: New
func New(
cfg cosmos.Config,
httpClient *cosmos.HTTPClient,
wsClient *cosmos.WSClient,
blockService *cosmos.BlockService,
indexer *AffiliateFeeIndexer,
swaggerPath string,
prometheus *metrics.Prometheus,
) *API
Purpose
Constructs and initializes a new Thorchain API server instance.
Parameters
Parameter | Type | Description |
|---|---|---|
`cfg` | `cosmos.Config` | Configuration specifying chain-specific parameters such as denomination and native fees. |
`httpClient` | `*cosmos.HTTPClient` | HTTP client for querying blockchain data and indexer services. |
`wsClient` | `*cosmos.WSClient` | WebSocket client for subscribing to blockchain events. |
`blockService` | `*cosmos.BlockService` | Service for fetching block data. |
`indexer` | `*AffiliateFeeIndexer` | Indexer responsible for tracking affiliate fee events. |
`swaggerPath` | `string` | File system path to the Swagger JSON specification. |
`prometheus` | `*metrics.Prometheus` | Prometheus metrics collector instance. |
Returns
Pointer to an initialized
APIinstance.
Usage
api := api.New(cfg, httpClient, wsClient, blockService, affiliateIndexer, "/path/to/swagger.json", prometheus)
Description
Creates a Gorilla Mux router.
Instantiates a Thorchain-specific
Handlerthat embeds acosmos.Handlerwith Thorchain config.Creates a WebSocket manager with Prometheus metrics integration.
Creates an HTTP server with configured timeouts and CORS middleware.
Wraps the handler and WebSocket manager inside a
cosmos.API.Registers HTTP routes for REST endpoints and Swagger docs.
Starts a profiling server (pprof) on a separate goroutine.
Applies middleware for API scheme enforcement and logging.
Defines endpoint handlers for:
Root (
/)Health check (
/health)Metrics (
/metrics)Swagger JSON (
/swagger) and Swagger UI (/docs/)API v1 endpoints:
Info (
/api/v1/info)Send transaction (
/api/v1/send)Account data and transaction history (
/api/v1/account/{pubkey},/api/v1/account/{pubkey}/txs)Transaction details (
/api/v1/tx/{txid})Gas estimation (
/api/v1/gas/estimate)Affiliate revenue (
/api/v1/affiliate/revenue)
Registers WebSocket endpoint at root (
/) for subscription to live blockchain events.
HTTP Handler Methods
All these methods delegate to the embedded `cosmos.API` methods, except affiliate revenue which is custom.
Websocket
func (a *API) Websocket(w http.ResponseWriter, r *http.Request)
Handles WebSocket connections to subscribe clients to pending and confirmed transactions in real-time.
Delegates to
a.API.Websocket.
Info
func (a *API) Info(w http.ResponseWriter, r *http.Request)
Returns general information about the running Thorchain coinstack.
Delegates to
a.API.Info.
Account
func (a *API) Account(w http.ResponseWriter, r *http.Request)
Retrieves account details for a given public key.
Delegates to
a.API.Account.
TxHistory
func (a *API) TxHistory(w http.ResponseWriter, r *http.Request)
Returns paginated transaction history for a given public key.
Delegates to
a.API.TxHistory.
Tx
func (a *API) Tx(w http.ResponseWriter, r *http.Request)
Returns detailed information about a specific transaction by ID.
Delegates to
a.API.Tx.
SendTx
func (a *API) SendTx(w http.ResponseWriter, r *http.Request)
Accepts and broadcasts a raw transaction to the Thorchain network.
Delegates to
a.API.SendTx.
EstimateGas
func (a *API) EstimateGas(w http.ResponseWriter, r *http.Request)
Estimates the gas cost for a transaction.
Delegates to
a.API.EstimateGas.
AffiliateRevenue
func (a *API) AffiliateRevenue(w http.ResponseWriter, r *http.Request)
Returns total affiliate revenue earned within a specified time range.
Parses query parameters
startandendas Unix timestamps (milliseconds).Falls back to defaults if parsing fails (
start=0,end=current time).Calls
a.handler.GetAffiliateRevenue(start, end)to retrieve data.Responds with JSON-encoded affiliate revenue or error.
Example Request
GET /api/v1/affiliate/revenue?start=1654041600000&end=1656633600000
Example Response
{
"total_revenue": "123456789000",
"affiliate_addresses": ["addr1...", "addr2..."]
}
Important Implementation Details
Middleware: Uses CORS middleware allowing all origins and request methods.
Prometheus Integration: Metrics endpoint
/metricsexposes Prometheus metrics collected by the server and WebSocket manager.Swagger Documentation: Serves Swagger JSON at
/swaggerand Swagger UI static files under/docs/.pprof Profiling: Runs a separate HTTP server on port 3001 for performance profiling (
net/http/pprof).Routing: Uses Gorilla Mux subrouters for versioning (
/api/v1) and grouping related endpoints (/account,/tx,/gas,/affiliate).Handler Validation: Performs runtime validation to ensure the embedded
Handlerimplements required interfaces (api.BaseAPI,cosmos.CoinSpecificHandler) and Thorchain-specific validation.Graceful Shutdown: Constants define timeouts for server operations; actual shutdown logic is expected to be handled externally or in extended code.
Interaction with Other Components
Cosmos SDK API Layer: Embeds
cosmos.APIandcosmos.Handlerfor generic blockchain API logic.Thorchain-Specific Handler: Implements Thorchain-specific transaction parsing, synthetic transaction creation, and affiliate fee revenue aggregation.
AffiliateFeeIndexer: Tracks affiliate fee events, providing data for the affiliate revenue endpoint.
WebSocket Manager: Manages WebSocket connections and broadcasts blockchain event updates to subscribed clients.
HTTP Client and Block Service: Used by the handler to query blockchain data and blockchain event streams.
Prometheus Metrics: Collects and exposes operational metrics for monitoring.
Swagger UI and Docs: Enables interactive API exploration and developer onboarding.
Visual Diagram
flowchart TD
Client[Client Application]
subgraph API_Server
REST[REST API Endpoints]
WS[WebSocket Manager]
Handler[Thorchain Handler]
Indexer[Affiliate Fee Indexer]
CosmosAPI[Cosmos SDK API Layer]
Metrics[Prometheus Metrics Endpoint]
end
Client -->|HTTP Requests| REST
Client -->|WebSocket| WS
REST --> Handler
WS --> Handler
Handler --> CosmosAPI
Handler --> Indexer
REST --> Metrics
**Diagram Explanation:**
Clients interact with the API Server over HTTP (REST) or WebSocket.
REST requests are routed to the Thorchain Handler, which:
Calls the underlying Cosmos SDK API for generic blockchain operations.
Queries the Affiliate Fee Indexer for revenue data.
WebSocket Manager handles real-time event subscriptions, forwarding events from the Handler.
Prometheus metrics are exposed via the REST API for observability.
Summary
`api.go` is the entry point and main server setup file for the Thorchain Unchained API. It configures and exposes REST and WebSocket endpoints to serve Thorchain blockchain information, transaction submission, gas estimation, and affiliate revenue statistics. This file extends a generic Cosmos SDK API framework with Thorchain-specific logic and integrates critical components like the affiliate fee indexer and WebSocket event manager. Its modular and middleware-rich design ensures scalability, observability, and developer usability.
Example Usage
package main
import (
"github.com/shapeshift/unchained/go/coinstacks/thorchain/api"
"github.com/shapeshift/unchained/pkg/cosmos"
"github.com/shapeshift/unchained/pkg/metrics"
)
func main() {
cfg := cosmos.Config{Denom: "rune", NativeFee: 5000}
httpClient := cosmos.NewHTTPClient(cfg)
wsClient := cosmos.NewWSClient(cfg)
blockService := cosmos.NewBlockService(httpClient)
affiliateIndexer := api.NewAffiliateFeeIndexer()
prometheus := metrics.NewPrometheus()
server := api.New(cfg, httpClient, wsClient, blockService, affiliateIndexer, "./swagger.json", prometheus)
// Start server (blocking call)
server.ListenAndServe()
}