main.go

Overview

`main.go` serves as the entry point for the Thorchain API service within the Unchained project. It initializes and configures the necessary components that allow interaction with the Thorchain blockchain network, including HTTP clients, WebSocket clients, block services, and the affiliate fee indexer. The file sets up custom transaction encoding options specific to Thorchain, loads configuration either from environment variables or a specified file, and starts the API server which provides RESTful endpoints documented by a Swagger specification.

This file handles:


Detailed Explanation

Package and Imports


Global Variables

Variable

Type

Description

logger

log.Logger

Logger instance without additional fields for general logging.

`envPath`

*string

Command line flag for specifying path to environment config file. Defaults to empty string (use OS env).

`swaggerPath`

*string

Command line flag for specifying Swagger spec JSON path for API documentation.


Config Struct

type Config struct {
	LCDURL   string `mapstructure:"LCD_URL"`    // URL for LCD (Light Client Daemon) API v2
	LCDV1URL string `mapstructure:"LCD_V1_URL"` // URL for LCD API v1
	RPCURL   string `mapstructure:"RPC_URL"`    // URL for RPC endpoint v2
	RPCV1URL string `mapstructure:"RPC_V1_URL"` // URL for RPC endpoint v1
	WSURL    string `mapstructure:"WS_URL"`     // URL for WebSocket endpoint
}

Main Function

func main()

The `main` function orchestrates the entire setup and execution of the Thorchain API service.

Steps:

  1. Parse command line flags (envPath, swaggerPath).

  2. Setup channels:

    • errChan for receiving asynchronous errors.

    • sigChan to listen for termination signals (SIGHUP, SIGINT, SIGTERM, SIGQUIT).

  3. Load configuration:

    • If no envPath is provided, load from OS environment variables.

    • Otherwise, load from the specified .env or config file.

    • Panic and exit on failure.

  4. Create a Cosmos encoding configuration:

    • Uses Thorchain-specific types for interface registration.

    • Customizes transaction decoding to support Thorchain's injected transactions via Ebifrost Tx decoder.

  5. Create custom TxConfig:

    • Uses Cosmos SDK’s tx package to create a new TxConfig with custom options.

    • Enables default sign modes and uses ebifrost.TxDecoder for transaction decoding.

  6. Setup two Cosmos client configurations:

    • cfg for v2 endpoints (LCD, RPC, WS).

    • cfgV1 for v1 endpoints (LCD, RPC).

    • Both configured with Thorchain-specific Bech32 address prefixes, native denomination ("rune"), and fee parameters.

  7. Initialize Prometheus metrics collector named "thorchain".

  8. Create HTTP clients:

    • One for v2 (httpClient).

    • One for v1 (httpClientV1).

    • Panic on failure.

  9. Create a BlockService using the v2 HTTP client to track blockchain blocks.

  10. Create a WebSocket client to subscribe and listen to real-time blockchain events.

  11. Create an AffiliateFeeIndexer using HTTP clients and WS client:

    • Responsible for indexing affiliate fee data from Thorchain.

    • Starts synchronization and panics on error.

  12. Initialize the Thorchain API server with configuration, clients, services, indexer, Swagger spec path, and metrics collector.

  13. Start the API server in a separate goroutine.

  14. Wait for errors or termination signals:

    • On error, log and panic.

    • On termination signal, gracefully shutdown the API server and exit.


Key Components and Usage

cosmos.NewEncoding

ebifrost.TxDecoder

tx.NewTxConfigWithOptions

cosmos.Config

cosmos.NewHTTPClient

cosmos.NewBlockService

cosmos.NewWebsocketClient

api.NewAffiliateFeeIndexer

api.New


Usage Example

To run the Thorchain API service with default environment variables:

go run main.go

To specify a custom environment file and Swagger spec path:

go run main.go -env=/path/to/config.env -swagger=custom/swagger.json

Implementation Details and Algorithms


Interaction with Other Parts of the System


Diagram: Flowchart of Main Function and Component Relationships

flowchart TD
    A[Start: main()] --> B[Parse Flags]
    B --> C[Load Config\n(env or file)]
    C --> D[Create Cosmos Encoding]
    D --> E[Create Custom TxConfig with Ebifrost Decoder]
    E --> F[Setup Cosmos Configs (v1 & v2)]
    F --> G[Initialize Prometheus Metrics]
    G --> H[Create HTTP Clients (v1 & v2)]
    H --> I[Create BlockService]
    I --> J[Create WebSocket Client]
    J --> K[Initialize AffiliateFeeIndexer]
    K --> L[Start AffiliateFeeIndexer Sync]
    L --> M[Create API Server]
    M --> N[Start API Server (goroutine)]
    N --> O[Wait for ErrChan or SigChan]
    O --> |Error Received| P[Log & Panic]
    O --> |Signal Received| Q[Shutdown API & Exit]

    subgraph Clients and Services
        H
        I
        J
        K
    end

    subgraph Config & Encoding
        C
        D
        E
        F
        G
    end

Summary

`main.go` is the bootstrapper for the Thorchain API service, responsible for:

This file is critical for initializing the runtime environment and connecting all components to interact seamlessly with the Thorchain blockchain network.