app.ts
Overview
`app.ts` implements the Litecoin-specific API server leveraging Express.js and WebSocket technologies. It provides REST endpoints and WebSocket real-time subscriptions to serve blockchain data, integrating deeply with a Blockbook indexer via WebSocket to receive and process live blockchain events.
This server exposes health and metrics endpoints, interactive Swagger API documentation, and manages live client connections that subscribe to blockchain events. The file configures middleware, registers REST routes, and orchestrates event processing through handlers and a central subscription registry.
Key functionalities include:
Serving REST API endpoints for Litecoin blockchain data queries.
Hosting a WebSocket server for real-time subscription to new blocks and transactions.
Connecting to a Litecoin Blockbook indexer WebSocket to receive blockchain events.
Parsing and processing block and transaction events via custom handlers.
Managing client subscriptions efficiently using a
Registry.Exposing Prometheus metrics and Swagger UI documentation.
Providing robust error handling and logging.
This file acts as the entry point to the Litecoin API server, tying together middleware, controllers, event handling, and client interaction layers.
Detailed Explanation
Imports and Constants
Express: Web framework for HTTP API endpoints.
path.join: To resolve static file paths.
ws.Server: WebSocket server for client connections.
swagger-ui-express: To serve Swagger API documentation.
Logger: Namespaced logging utility.
@shapeshiftoss/common-api: Provides middleware, handlers, registry, Prometheus metrics, and connection management utilities.
@shapeshiftoss/blockbook: Utilities and types for Blockbook WebSocket client and transaction parsing.
controller: Litecoin-specific business logic and address formatting.
routes: REST API route registration.
Constants:
PORT: Server listening port (default 3000).INDEXER_WS_URL: Blockbook WebSocket URL (required).INDEXER_API_KEY: API key for Blockbook (optional).
Express App Setup
const app = express()
app.use(...middleware.common(prometheus))
Initializes Express app.
Applies common middleware (likely includes JSON parsing, logging, metrics instrumentation).
REST Endpoints
GET
/healthReturns JSON with server status, network name (Litecoin), and current WebSocket client count.
app.get('/health', async (_, res) => res.json({ status: 'up', network: 'litecoin', connections: wsServer.clients.size }) )GET
/metricsReturns Prometheus metrics in the content type expected by Prometheus server scrapes.
Static file serving
/publicserves static assets for Swagger UI./swagger.jsonserves the OpenAPI spec JSON file.
Swagger UI
Serves interactive API documentation at
/docs.Customizes UI appearance (hides top bar, sets title and favicon).
Root
/Redirects to
/docsfor convenience.Error Handling Middleware
Uses common error and not-found handlers from shared middleware package.
Route Registration
RegisterRoutes(app)
Registers all REST API routes defined in the
routesmodule.These routes correspond to Litecoin-specific blockchain data queries and transaction operations.
Blockchain Event Handlers
blockHandler
const blockHandler: BlockHandler<NewBlock, Array<BlockbookTx>> = async (block) => { const txs = await service.handleBlock(block.hash) return { txs } }Receives a new block event (with block hash).
Calls
service.handleBlockto fetch and process all transactions in the block.Returns the array of parsed transactions.
transactionHandler
const transactionHandler: TransactionHandler<BlockbookTx, utxo.Tx> = async (blockbookTx) => { const tx = service.handleTransaction(blockbookTx) const addresses = getAddresses(blockbookTx) return { addresses, tx } }Processes individual blockbook transaction.
Uses service layer to parse transaction details into internal UTXO transaction format.
Extracts relevant addresses involved in the transaction.
Returns both parsed transaction and addresses for subscription dispatch.
Subscription Registry
const registry = new Registry({ addressFormatter: formatAddress, blockHandler, transactionHandler })
Central event registry managing client subscriptions by address.
Formats addresses using chain-specific
formatAddress.Uses the above handlers to process incoming blocks and transactions.
Ensures only subscribed clients receive notifications matching their interests.
Blockbook WebSocket Client
const blockbook = new WebsocketClient(
INDEXER_WS_URL,
{
apiKey: INDEXER_API_KEY,
blockHandler: registry.onBlock.bind(registry),
transactionHandler: registry.onTransaction.bind(registry),
},
{ resetInterval: 5 * 60 * 1000 }
)
Connects to Litecoin Blockbook WebSocket endpoint.
Uses API key for authentication if provided.
Forwards incoming blocks and transactions to the registry’s handlers.
Automatically resets connection every 5 minutes for robustness.
HTTP and WebSocket Server Setup
const server = app.listen(PORT, () => logger.info('Server started'))
const wsServer = new Server({ server })
Starts Express HTTP server.
Creates a WebSocket server bound to the same HTTP server for handling WS client connections.
WebSocket Client Connection Handling
wsServer.on('connection', (connection) => {
ConnectionHandler.start(connection, registry, blockbook, prometheus, logger)
})
On each new WS client connection:
Delegates to
ConnectionHandler.startwhich:Manages subscription lifecycle based on messages from clients.
Links WS connections to the registry for event dispatch.
Tracks metrics and logs connection events.
Usage Examples
Starting the Server
Set environment variables and run:
export INDEXER_WS_URL=wss://litecoin-blockbook.example.com/socket
export INDEXER_API_KEY=your-api-key
export PORT=3000
node dist/app.js
Query Health
GET /health
Response:
{
"status": "up",
"network": "litecoin",
"connections": 2
}
Subscribe to Address Updates (WebSocket Client Example)
Client connects to WS server and sends a message like:
{
"type": "subscribe",
"addresses": ["LcHKV1x2Z4Tz7E9Gz7Wb5AqT2Na1hT6k1S"]
}
Subsequent new blocks or transactions affecting these addresses will be pushed to the client.
Important Implementation Details
Registry Pattern: The
Registryclass acts as an event multiplexer that maps blockchain events to interested client subscriptions by address, ensuring efficient event dispatch and minimizing unnecessary network traffic.Handlers as Callbacks: The
blockHandlerandtransactionHandlerare asynchronous functions passed to the registry and blockbook client. This separation enables modular processing and easy unit testing.Connection Reset Strategy: The Blockbook client resets its WebSocket connection every 5 minutes to mitigate potential stale connections or network issues, improving reliability.
Middleware Usage: Common middleware includes metrics collection, error handling, and request parsing, ensuring consistent request lifecycle management.
Swagger UI Integration: Serving Swagger UI from static files with custom branding improves developer experience for API consumers.
Interaction with Other System Components
Blockbook Indexer: This file connects as a WebSocket client to a Blockbook indexer specialized for Litecoin, consuming real-time blockchain data.
Common API Libraries: Uses shared middleware, handlers, and utility functions from
@shapeshiftoss/common-apifor standardization and reuse across multiple blockchain API servers.Controller Layer: The
serviceandformatAddressimported from the localcontrollermodule implement chain-specific logic for transaction parsing, address formatting, and block processing.Routes Module: REST API routes defined in
routesare registered here to expose blockchain-related endpoints.Metrics System: Integrates Prometheus metrics collection to expose server and application state for monitoring.
Client Applications: Provides REST and WebSocket interfaces for wallets, explorers, and dApps to query Litecoin blockchain data and subscribe to live events.
Visual Diagram
classDiagram
class App {
+app: Express
+wsServer: WebSocket.Server
+start()
}
class Registry {
+addressFormatter()
+onBlock()
+onTransaction()
+manageSubscriptions()
}
class WebsocketClient {
+connect()
+blockHandler()
+transactionHandler()
+resetInterval
}
class ConnectionHandler {
+start(connection, registry, blockbook, prometheus, logger)
+manageClientConnection()
}
class Service {
+handleBlock(hash)
+handleTransaction(tx)
}
App "1" --o "1" Registry : uses
App "1" --o "1" WebsocketClient : connects to
App "1" --o "1" ConnectionHandler : handles WS connections
Registry "1" --> "1" Service : processes data via
WebsocketClient "1" --> "1" Registry : forwards events to
ConnectionHandler "1" --> "1" Registry : subscribes clients
Summary
`app.ts` is the Litecoin blockchain API server entry point, implementing a robust, extensible server that:
Serves REST and WebSocket APIs,
Integrates live blockchain data via Blockbook WebSocket client,
Manages subscription routing via a registry,
Supports metrics and documentation endpoints,
Provides chain-specific transaction processing via controller services.
It acts as the critical middleware layer between the Litecoin blockchain indexer and client applications, enabling real-time and on-demand blockchain data delivery.