controller.ts
Overview
`controller.ts` is a configuration and initialization module for the Litecoin UTXO (Unspent Transaction Output) service within a broader blockchain infrastructure. This file sets up key service components to interact with Litecoin blockchain data through the Blockbook API and an RPC endpoint. It also provides utility functions to identify extended public keys (xpubs) and format Litecoin addresses consistently.
The main purpose of this file is to:
Validate essential environment variables for network connectivity.
Initialize logging scoped to the Litecoin API.
Configure the Blockbook client to interact with the Litecoin blockchain.
Define utility functions for public key and address handling.
Instantiate and export a
Serviceobject tailored to Litecoin, which is assigned as the shared service for allUTXOinstances.
This setup enables efficient querying, formatting, and management of Litecoin UTXOs, crucial for wallet operations, blockchain explorers, or other blockchain data services.
Detailed Explanation
Imports and Constants
bech32: Library for Bech32 address encoding/decoding, used to process Litecoin addresses.
Blockbook: Client API interface to Blockbook, a blockchain indexer supporting various coins.
Service: UTXO service class handling blockchain communication and data processing.
UTXO: Controller class representing an Unspent Transaction Output.
Logger: Logging utility scoped for structured and leveled logging.
Constants fetch environment variables:
INDEXER_URL,INDEXER_WS_URL,INDEXER_API_KEY: URLs and credentials for the Blockbook indexer service.RPC_URL,RPC_API_KEY: URLs and credentials for RPC interaction with Litecoin nodes.
The file throws errors if critical environment variables are missing, preventing runtime misconfiguration.
Logger Initialization
export const logger = new Logger({
namespace: ['unchained', 'coinstacks', 'litecoin', 'api'],
level: process.env.LOG_LEVEL,
})
Creates a logger instance scoped to the Litecoin API context.
Uses environment variable
LOG_LEVELfor dynamic verbosity control.
Blockbook Client Initialization
const blockbook = new Blockbook({ httpURL: INDEXER_URL, wsURL: INDEXER_WS_URL, apiKey: INDEXER_API_KEY, logger })
Initializes the Blockbook client with HTTP and WebSocket URLs and API key.
Passes the logger for integrated debug and error tracking.
Function: isXpub
const isXpub = (pubkey: string): boolean => {
return pubkey.startsWith('Ltub') || pubkey.startsWith('Mtub') || pubkey.startsWith('zpub')
}
Purpose: Detects if a given string is an extended public key (xpub) format used in Litecoin.
Parameters:
pubkey(string): The public key string to check.
Returns:
boolean—trueif the key matches known Litecoin xpub prefixes; otherwise,false.Usage:
if (isXpub('Ltub...')) { // handle extended public key logic }Implementation detail: Checks for Litecoin-specific extended key prefixes:
Ltub(mainnet legacy)Mtub(testnet legacy)zpub(SegWit-native)
Function: formatAddress
export const formatAddress = (address: string): string => {
if (bech32.decodeUnsafe(address.toLowerCase())?.prefix === 'ltc') return address.toLowerCase()
return address
}
Purpose: Normalizes Litecoin addresses, primarily ensuring Bech32 addresses use lowercase.
Parameters:
address(string): The Litecoin address to format.
Returns:
string— The formatted address.Usage:
const normalized = formatAddress('LTC1Q...');Implementation detail:
Uses
bech32.decodeUnsafeto decode the address safely.If the prefix is
ltc(indicating Bech32 Litecoin address), converts the entire address to lowercase (Bech32 standard).Otherwise, returns the address unchanged.
Service Instantiation
export const service = new Service({
blockbook,
rpcUrl: RPC_URL,
rpcApiKey: RPC_API_KEY,
isXpub,
addressFormatter: formatAddress,
})
Creates a new instance of
Serviceconfigured for Litecoin.Injects dependencies:
The
blockbookclient for indexer-based blockchain queries.RPC endpoint URL and API key for direct node communication.
Utility functions
isXpubandformatAddressfor key and address handling.
Assigning Service to UTXO
UTXO.service = service
Sets the newly created
serviceas the shared service instance for allUTXOclass instances.This design pattern centralizes blockchain data fetching logic, facilitating reuse across the application.
Interaction with Other Parts of the System
Relies on environment variables for configuration, linking to deployment or runtime environment settings.
Depends on the
ServiceandUTXOclasses from the common API UTXO module, integrating Litecoin-specific logic into a generic UTXO framework.Uses the
Blockbookclient to communicate with the Litecoin indexer backend.Logging is configured to integrate with the overall application logging infrastructure.
Other modules or services that instantiate or manipulate UTXOs will use this shared service instance, ensuring consistent blockchain data access and address formatting.
Implementation Details and Algorithms
Address Formatting: Uses Bech32 decoding to detect Litecoin native SegWit addresses and enforce lowercase formatting as required by the Bech32 specification. This prevents address mismatches caused by casing errors.
Xpub Detection: Simple prefix matching is used to identify extended public keys relevant to Litecoin networks, supporting multiple key types.
Service Initialization: Combines multiple data sources (block indexer and RPC node) for robustness and flexibility in data retrieval.
Usage Example
import { UTXO } from '../../../common/api/src/utxo/controller'
// Assuming environment variables are set and controller.ts is imported somewhere in the app
async function getUtxosForAddress(address: string) {
const formatted = formatAddress(address)
const utxoInstance = new UTXO(formatted)
const utxos = await utxoInstance.getUtxos() // method from UTXO class (not shown here)
return utxos
}
This example demonstrates how the configured service and formatting utilities enable seamless UTXO retrieval for a given Litecoin address.
Diagram: Class and Utility Structure
classDiagram
class Service {
+constructor(options)
+blockbook
+rpcUrl
+rpcApiKey
+isXpub(pubkey: string): boolean
+addressFormatter(address: string): string
...
}
class UTXO {
+static service: Service
+constructor(address: string)
+getUtxos()
...
}
class Logger {
+constructor(options)
+namespace: string[]
+level: string
...
}
class Blockbook {
+constructor(options)
+httpURL: string
+wsURL: string
+apiKey: string
+logger: Logger
...
}
controller.ts ..> Service : instantiates
controller.ts ..> UTXO : assigns .service
controller.ts ..> Logger : instantiates
controller.ts ..> Blockbook : instantiates
controller.ts ..> isXpub : function
controller.ts ..> formatAddress : function
Summary
`controller.ts` is a lightweight but critical configuration file that initializes the Litecoin blockchain interaction layer, providing:
Environment-validated setup.
Logging scoped for Litecoin API.
Blockbook indexer client setup.
Utility functions for Litecoin-specific public key and address handling.
A customized UTXO service instance shared across the application.
This file acts as the integration point connecting generic UTXO infrastructure with Litecoin-specific blockchain access and formatting rules, enabling other components to transparently interact with Litecoin UTXOs.