app.ts


Overview

`app.ts` is the main entry point for the Bitcoin Cash API server within the ShapeShift Unchained coinstacks project. It sets up an Express.js HTTP server combined with a WebSocket server to provide real-time blockchain data and RESTful API endpoints. The file's primary responsibilities include:

This file bridges the underlying blockchain data sources (via WebSocket client) with API consumers, ensuring efficient, real-time updates and a rich API surface.


Detailed Explanation

Imports and Constants


Express Application Setup

const app = express()

app.use(...middleware.common(prometheus))

HTTP Routes


Blockchain Handlers

Two asynchronous handler functions process blockchain data received via WebSocket:

blockHandler

const blockHandler: BlockHandler<NewBlock, Array<BlockbookTx>> = async (block) => {
  const txs = await service.handleBlock(block.hash)
  return { txs }
}

transactionHandler

const transactionHandler: TransactionHandler<BlockbookTx, utxo.Tx> = async (blockbookTx) => {
  const tx = service.handleTransaction(blockbookTx)
  const addresses = getAddresses(blockbookTx)
  return { addresses, tx }
}

Registry Setup

const registry = new Registry({ addressFormatter: formatAddress, blockHandler, transactionHandler })

WebSocket Client Setup

const blockbook = new WebsocketClient(
  INDEXER_WS_URL,
  {
    apiKey: INDEXER_API_KEY,
    blockHandler: registry.onBlock.bind(registry),
    transactionHandler: registry.onTransaction.bind(registry),
  },
  { resetInterval: 15 * 60 * 1000 } // 15 minutes
)

Server and WebSocket Server Initialization

const server = app.listen(PORT, () => logger.info('Server started'))
const wsServer = new Server({ server })

WebSocket Connection Handling

wsServer.on('connection', (connection) => {
  ConnectionHandler.start(connection, registry, blockbook, prometheus, logger)
})

The `ConnectionHandler` likely manages subscriptions, message routing, and client lifecycle events.


Usage Examples

Starting the Server

Assuming environment variables are set:

export INDEXER_WS_URL=wss://indexer.example.com/ws
export INDEXER_API_KEY=your_api_key
export PORT=3000
node dist/app.js

Accessing API

WebSocket Client

Clients can connect to the same port via WebSocket to receive real-time blockchain updates (subscription and messaging details handled by `ConnectionHandler`).


Implementation Details and Algorithms


Interaction with Other System Parts


Class and Function Summary

Name

Type

Description

`blockHandler`

Function

Async handler to process new blockchain blocks and return transactions.

`transactionHandler`

Function

Async handler to process individual blockchain transactions and extract addresses.

`registry`

Class

Manages blockchain event processing, wrapping handlers for blocks and transactions.

`blockbook`

Class

WebSocket client connecting to the blockchain indexer, providing real-time block/tx data.

`app`

Object

Express application instance configuring middleware and HTTP routes.

`server`

Object

HTTP server instance listening for incoming HTTP and WS connections.

`wsServer`

Class

WebSocket server handling client connections for real-time communication.


Visual Diagram

classDiagram
    class App {
        +use()
        +get()
        +listen()
    }
    class BlockHandler {
        <<function>>
        +handleBlock(block: NewBlock) : Promise<{txs: BlockbookTx[]}>
    }
    class TransactionHandler {
        <<function>>
        +handleTransaction(tx: BlockbookTx) : utxo.Tx
    }
    class Registry {
        -addressFormatter: function
        -blockHandler: BlockHandler
        -transactionHandler: TransactionHandler
        +onBlock()
        +onTransaction()
    }
    class WebsocketClient {
        -url: string
        -apiKey: string
        -blockHandler: function
        -transactionHandler: function
        +connect()
    }
    class Server {
        +on(event: string, listener: function)
    }
    class ConnectionHandler {
        +start(connection, registry, blockbook, prometheus, logger)
    }

    App --> Server : listens
    Server --> WebsocketClient : manages connection
    Server --> ConnectionHandler : manages WS client connections
    WebsocketClient --> Registry : calls onBlock, onTransaction
    Registry --> BlockHandler : processes blocks
    Registry --> TransactionHandler : processes transactions

Summary

`app.ts` is a foundational file setting up the Bitcoin Cash API server combining HTTP REST endpoints with real-time WebSocket streaming. It orchestrates blockchain data ingestion, processing, and client communication, while providing monitoring and documentation endpoints. The modular design leverages ShapeShift's common API utilities to maintain clean separation of concerns and extensibility. This file acts as the central hub connecting blockchain data providers, business logic, and API consumers in a performant, maintainable manner.