app.ts
Overview
`app.ts` serves as the main entry point for the Dogecoin API server within the ShapeShift ecosystem. It sets up an Express-based HTTP server with integrated WebSocket support to handle real-time blockchain data streaming and API requests. The file orchestrates connections to an external blockchain indexer (via WebSocket), processes new blocks and transactions, exposes REST endpoints (including health checks, metrics, and API documentation), and manages client WebSocket connections for live updates.
Key responsibilities include:
Initializing HTTP and WebSocket servers
Configuring middleware, routes, and API documentation
Handling incoming blockchain blocks and transactions via registered handlers
Integrating Prometheus metrics for observability
Establishing and managing WebSocket client connections to the blockchain indexer
Providing a unified registry for address formatting and blockchain event handling
Classes, Functions, and Methods
1. blockHandler: BlockHandler<NewBlock, Array<BlockbookTx>>
const blockHandler: BlockHandler<NewBlock, Array<BlockbookTx>> = async (block) => {
const txs = await service.handleBlock(block.hash)
return { txs }
}
Purpose: Handles new blockchain blocks received from the indexer.
Parameters:
block: The new block object of typeNewBlock, containing blockchain metadata including the block hash.
Returns: An object containing an array of transactions (
txs) processed for the block.Usage: Invoked whenever a new block event is emitted from the WebSocket client. Uses
service.handleBlockto fetch and process block transactions.
2. transactionHandler: TransactionHandler<BlockbookTx, utxo.Tx>
const transactionHandler: TransactionHandler<BlockbookTx, utxo.Tx> = async (blockbookTx) => {
const tx = service.handleTransaction(blockbookTx)
const addresses = getAddresses(blockbookTx)
return { addresses, tx }
}
Purpose: Processes individual blockchain transactions received via the indexer.
Parameters:
blockbookTx: Transaction object of typeBlockbookTxfrom the Blockbook indexer.
Returns: An object containing:
addresses: a list of addresses involved in the transaction, extracted viagetAddresses.tx: a processed transaction object fromservice.handleTransaction.
Usage: Called for every new transaction event to parse and format transaction data and extract relevant addresses.
3. Registry
const registry = new Registry({ addressFormatter: formatAddress, blockHandler, transactionHandler })
Purpose: Central registry managing blockchain event handlers and address formatting.
Parameters (via constructor object):
addressFormatter: Function used to format blockchain addresses (formatAddress).blockHandler: Function to handle new blocks (blockHandler).transactionHandler: Function to handle new transactions (transactionHandler).
Usage: The registry binds blockchain event callbacks and address formatting logic used by the WebSocket client and connection handlers.
4. WebsocketClient
const blockbook = new WebsocketClient(
wsUrl,
{
apiKey,
blockHandler: registry.onBlock.bind(registry),
transactionHandler: registry.onTransaction.bind(registry),
},
{ resetInterval: 5 * 60 * 1000 }
)
Purpose: Manages a persistent WebSocket connection to the blockchain indexer to receive real-time block and transaction data.
Parameters:
wsUrl: WebSocket URL of the indexer, possibly with an API key suffix depending on provider.options:apiKey(optional): API key for authenticated access.blockHandler: Callback for new blocks (bound to registry).transactionHandler: Callback for new transactions (bound to registry).
config: Configuration object withresetIntervalfor reconnecting every 5 minutes.
Usage: Automatically reconnects and streams blockchain events, forwarding them to the registry handlers.
5. Express Application Setup (app)
Middleware:
Uses common middleware from
@shapeshiftoss/common-apiwith Prometheus instrumentation.Error handling and not-found handlers at the end of the middleware chain.
Routes:
/health: Returns status, network name (dogecoin), and number of active WebSocket clients./metrics: Exposes Prometheus metrics for monitoring./public: Serves static assets for Swagger UI./swagger.json: Serves OpenAPI specification file./docs: Hosts Swagger UI for API documentation with custom branding and UI options./: Redirects to/docsfor API documentation landing.Other API routes are registered via
RegisterRoutes(app).
6. WebSocket Server and Connection Handling
const server = app.listen(PORT, () => logger.info('Server started'))
const wsServer = new Server({ server })
wsServer.on('connection', (connection) => {
ConnectionHandler.start(connection, registry, blockbook, prometheus, logger)
})
Purpose: Sets up WebSocket server on the same HTTP port.
Functionality:
On every new WebSocket client connection, invokes
ConnectionHandler.startpassing the connection, registry, WebSocket client to the indexer, Prometheus instance, and logger.Enables real-time push notifications and subscriptions for clients listening for blockchain updates.
Important Implementation Details
Environment Variables:
PORT: HTTP server port (default 3000).INDEXER_WS_URL: WebSocket URL for the blockchain indexer (required).INDEXER_API_KEY: Optional API key for authenticated indexer access.
Provider Detection:
Checks if the indexer URL contains
"liquify"or"nownodes"to customize connection URL and API key usage.
Prometheus Integration:
Instrumentation for API request metrics and WebSocket connection metrics to support observability and alerting.
Registry Pattern:
The registry decouples blockchain event handling and address formatting from the server and WebSocket client, promoting modularity.
Automatic WebSocket Client Reset:
The WebSocket client to the indexer resets every 5 minutes to maintain connection health.
Swagger API Documentation:
Embedded Swagger UI with custom branding makes API exploration user-friendly.
Interaction With Other System Components
@shapeshiftoss/common-api: Provides shared middleware, types, and utility classes (e.g.,Registry,ConnectionHandler,BlockHandler).@shapeshiftoss/blockbook: Supplies blockchain data types and the WebSocket client to connect to the Blockbook indexer../controller: Contains domain logic for handling blocks and transactions (service), as well as address formatting utilities../routes: Defines REST API routes bound to the Express app.Prometheus: Integrated for metrics collection, exposed via
/metrics.WebSocket Clients: External clients connect to this server’s WebSocket for real-time blockchain data pushed from the indexer.
Usage Example
Once started, the server will:
Accept HTTP requests on the configured port (default 3000).
Serve API documentation at
/docs.Provide health status at
/health.Offer metrics at
/metrics.Maintain a persistent WebSocket connection to the Dogecoin blockchain indexer to receive new blocks and transactions.
Push blockchain updates to connected WebSocket clients in real-time.
Clients can subscribe to this WebSocket server to receive live updates about Dogecoin blocks and transactions, while developers can explore the REST API via Swagger UI.
Visual Diagram
classDiagram
class app {
+express: Express.Application
+server: HTTP.Server
+wsServer: WebSocket.Server
}
class Registry {
+addressFormatter()
+onBlock()
+onTransaction()
}
class WebsocketClient {
+connect()
+resetConnection()
}
class ConnectionHandler {
+start(connection, registry, blockbook, prometheus, logger)
}
class Prometheus {
+register
+metrics()
}
app --> Registry : uses
app --> WebsocketClient : instantiates
app --> ConnectionHandler : on wsServer.connection
app --> Prometheus : integrates
Registry <-- WebsocketClient : callbacks (onBlock,onTransaction)
Summary
`app.ts` is the core server bootstrap file for the Dogecoin API, integrating HTTP REST endpoints, WebSocket streaming for blockchain data, Prometheus metrics, and Swagger-based API documentation. It leverages a modular design with a registry pattern and external libraries to manage blockchain event subscriptions, client connections, and data processing, providing a robust and scalable backend service for Dogecoin blockchain interactions.