controller.ts


Overview

The [controller.ts](/projects/291/68853) file is a configuration and setup module for the Bitcoin Cash (BCH) blockchain integration within a larger application. Its main purpose is to initialize and export a configured UTXO (Unspent Transaction Output) service that interacts with blockchain data sources via both REST and WebSocket APIs. It also provides utility functions related to address formatting and public key identification tailored specifically for Bitcoin Cash's addressing schemes.

This file acts as a bridge between low-level blockchain data providers (like Blockbook and RPC nodes) and higher-level UTXO-related operations, ensuring that the rest of the system can work with BCH blockchain data seamlessly and correctly formatted.


Detailed Explanation

Constants and Environment Variables

The file checks for the existence of critical environment variables and throws errors if they are missing, enforcing mandatory configuration.


Logger

export const logger = new Logger({
  namespace: ['unchained', 'coinstacks', 'bitcoincash', 'api'],
  level: process.env.LOG_LEVEL,
})

Blockbook Client Instance

const blockbook = new Blockbook({ httpURL: INDEXER_URL, wsURL: INDEXER_WS_URL, apiKey: INDEXER_API_KEY, logger })

Function: isXpub(pubkey: string): boolean

const isXpub = (pubkey: string): boolean => {
  return pubkey.startsWith('xpub') || pubkey.startsWith('ypub') || pubkey.startsWith('zpub')
}

Function: formatAddress(address: string): string

export const formatAddress = (address: string): string => {
  if (address.startsWith('bitcoincash') || bech32.decodeUnsafe(address.toLowerCase())?.prefix === 'bc')
    return address.toLowerCase()

  if (address.startsWith('q')) return `bitcoincash:${address.toLowerCase()}`

  return address
}

Exported Service Instance: service

export const service = new Service({
  blockbook,
  rpcApiKey: RPC_API_KEY,
  rpcUrl: RPC_URL,
  isXpub,
  addressFormatter: formatAddress,
})

Assigning the Service to UTXO Controller

UTXO.service = service

Implementation Details and Algorithms


Interactions with Other Parts of the System

Together, these components enable the application to query, monitor, and manipulate Bitcoin Cash blockchain data efficiently.


Usage Example

import { UTXO } from './controller'

// Example: check if a string is an xpub
const testPubkey = 'xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKpR...'
console.log(UTXO.service.isXpub(testPubkey)) // true

// Example: format an address for Blockbook queries
const rawAddress = 'qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a'
const formatted = UTXO.service.addressFormatter(rawAddress)
console.log(formatted) // bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a

// Use UTXO service to fetch unspent outputs or transactions (pseudo-code)
// const utxos = await UTXO.service.getUTXOs(formatted)

Mermaid Class Diagram

classDiagram
    class ControllerModule {
        <<module>>
        +logger: Logger
        +blockbook: Blockbook
        +isXpub(pubkey: string): boolean
        +formatAddress(address: string): string
        +service: Service
    }

    class Service {
        +blockbook: Blockbook
        +rpcApiKey: string | undefined
        +rpcUrl: string | undefined
        +isXpub(pubkey: string): boolean
        +addressFormatter(address: string): string
        +...other methods
    }

    class Blockbook {
        +httpURL: string
        +wsURL: string
        +apiKey: string | undefined
        +logger: Logger
        +...other methods
    }

    class Logger {
        +namespace: string[]
        +level: string | undefined
        +log()
        +error()
        +warn()
        +info()
    }

    class UTXO {
        <<controller>>
        +service: Service
    }

    ControllerModule --> Service : "instantiates"
    ControllerModule --> Blockbook : "instantiates"
    ControllerModule --> Logger : "instantiates"
    Service --> Blockbook : "uses"
    Service --> Logger : "uses"
    UTXO --> Service : "static property assignment"

Summary

This file is essential for the Bitcoin Cash integration in the system, establishing the blockchain data sources, formatting utilities, and service wrappers required for UTXO management. It ensures that the rest of the application interacts with BCH data in a standardized and reliable manner. The combination of environment-driven configuration, utility functions, and service instantiation encapsulates BCH-specific logic cleanly and extensibly.