controller.ts

Overview

`controller.ts` implements the **Blockbook API Controller**—a TypeScript class that acts as a RESTful HTTP interface to the Blockbook blockchain indexer backend. This controller provides normalized access to blockchain data such as blocks, transactions, addresses, extended public keys (xpubs), unspent transaction outputs (UTXOs), balance histories, and fee estimations.

The main purpose of this file is to abstract and simplify querying blockchain data across multiple supported cryptocurrencies by exposing a consistent, typed API surface with efficient HTTP client logic, error handling, and request retries. It serves as a bridge between client applications and the Blockbook backend indexing service, which maintains cached and indexed blockchain data optimized for fast querying.


Class: Blockbook

Description

`Blockbook` extends [Controller](/projects/291/69211) from the `tsoa` library to define HTTP routes and methods for blockchain data retrieval. It internally uses an Axios HTTP client with retry capabilities to communicate with the Blockbook backend API endpoints.

Properties

Property

Type

Description

`instance`

`AxiosInstance`

Configured Axios HTTP client to send requests to the backend.

`wsURL`

`string`

WebSocket URL for real-time events, constructed optionally with API key.

`logger`

`Logger`

Scoped logger instance for tracing and debugging API calls.

Constructor

constructor(args?: BlockbookArgs, timeout?: number, retries?: number)

Methods

All methods correspond to HTTP GET endpoints under the base route `api/v2`. They make HTTP requests to the Blockbook backend and return typed responses or throw wrapped `ApiError`s on failure.

1. getInfo()

async getInfo(): Promise<Info>
const info = await blockbook.getInfo()
console.log(info.blockbook.coin, info.backend.chain)

2. getBlockHash(height: number)

async getBlockHash(height: number): Promise<BlockIndex>
const blockIndex = await blockbook.getBlockHash(500000)
console.log(blockIndex.hash)

3. getTransaction(txid: string)

async getTransaction(txid: string): Promise<Tx>
const tx = await blockbook.getTransaction('0x890482efd45fcb660b8eebe42ab4d71a24b97c46c7d9c88b1e4b3cf4bef10110')
console.log(tx.txid, tx.blockHeight)

4. getTransactionSpecific(txid: string)

async getTransactionSpecific(txid: string): Promise<unknown>
const txSpecific = await blockbook.getTransactionSpecific('some-txid')
console.log(txSpecific)

5. getAddress(...)

async getAddress(
  address: string,
  page?: number,
  pageSize?: number,
  from?: number,
  to?: number,
  details?: 'basic' | 'tokens' | 'tokenBalances' | 'txids' | 'txslight' | 'txs',
  contract?: string
): Promise<Address>
const addressInfo = await blockbook.getAddress('0x37863DF4712e4494dFfc4854862259399354b2BB', 1, 100, undefined, undefined, 'txs')
console.log(addressInfo.balance, addressInfo.tokens)

6. getXpub(...)

async getXpub(
  xpub: string,
  page?: number,
  pageSize?: number,
  from?: number,
  to?: number,
  details?: 'basic' | 'tokens' | 'tokenBalances' | 'txids' | 'txs',
  tokens?: 'nonzero' | 'used' | 'derived'
): Promise<Xpub>
const xpubInfo = await blockbook.getXpub('xpub6DQYbVJSVvJPzpYenir7zVSf2WPZRu69LxZuMezzAKuT6biPcug...')
console.log(xpubInfo.balance, xpubInfo.tokens)

7. getUtxo(account: string, confirmed?: boolean)

async getUtxo(account: string, confirmed?: boolean): Promise<Array<Utxo>>
const utxos = await blockbook.getUtxo('14mMwtZCGiAtyr8KnnAZYyHmZ9Zvj71h4t', true)
console.log(utxos.length)

8. getBlock(block: string, page?: number)

async getBlock(block: string, page?: number): Promise<Block>
const blockData = await blockbook.getBlock('500000')
console.log(blockData.hash, blockData.txCount)

9. sendTransaction(hex: string)

async sendTransaction(hex: string): Promise<SendTx>
const result = await blockbook.sendTransaction('0x0100000001...')
console.log(result.result)

10. balanceHistory(account: string, from?: number, to?: number, fiatcurrency?: string, groupBy?: number)

async balanceHistory(
  account: string,
  from?: number,
  to?: number,
  fiatcurrency?: string,
  groupBy?: number
): Promise<Array<BalanceHistory>>
const history = await blockbook.balanceHistory('0x37863DF4712e4494dFfc4854862259399354b2BB', 1600000000, 1610000000, 'usd')
console.log(history)

11. estimateFees(blockTimes: number[])

async estimateFees(blockTimes: number[]): Promise<Array<string>>
const fees = await blockbook.estimateFees([1, 2, 3])
console.log(fees)

Implementation Details


Interaction with Other System Components


Usage Example

import { Blockbook } from './controller'

const blockbook = new Blockbook({
  httpURL: 'https://indexer.ethereum.shapeshift.com',
  wsURL: 'wss://indexer.ethereum.shapeshift.com/websocket',
  logger: new Logger({ namespace: ['app', 'blockbook'], level: 'debug' }),
})

async function main() {
  try {
    const info = await blockbook.getInfo()
    console.log('Blockbook Info:', info)

    const tx = await blockbook.getTransaction('0x890482efd45fcb660b8eebe42ab4d71a24b97c46c7d9c88b1e4b3cf4bef10110')
    console.log('Transaction:', tx)

    const addressData = await blockbook.getAddress('0x37863DF4712e4494dFfc4854862259399354b2BB', 1, 10, undefined, undefined, 'txs')
    console.log('Address:', addressData)
  } catch (err) {
    console.error('Error querying blockbook:', err)
  }
}

main()

Class Diagram

classDiagram
    class Blockbook {
        +instance: AxiosInstance
        +wsURL: string
        +logger: Logger
        +constructor(args?: BlockbookArgs, timeout?: number, retries?: number)
        +getInfo(): Promise~Info~
        +getBlockHash(height: number): Promise~BlockIndex~
        +getTransaction(txid: string): Promise~Tx~
        +getTransactionSpecific(txid: string): Promise~unknown~
        +getAddress(address: string, page?: number, pageSize?: number, from?: number, to?: number, details?: string, contract?: string): Promise~Address~
        +getXpub(xpub: string, page?: number, pageSize?: number, from?: number, to?: number, details?: string, tokens?: string): Promise~Xpub~
        +getUtxo(account: string, confirmed?: boolean): Promise~Array~Utxo~~
        +getBlock(block: string, page?: number): Promise~Block~
        +sendTransaction(hex: string): Promise~SendTx~
        +balanceHistory(account: string, from?: number, to?: number, fiatcurrency?: string, groupBy?: number): Promise~Array~BalanceHistory~~
        +estimateFees(blockTimes: number[]): Promise~Array~string~~
    }

Summary

`controller.ts` is a core API controller that exposes a rich set of RESTful endpoints to query blockchain data via the Blockbook indexer service. It provides methods to retrieve blocks, transactions, addresses, xpub accounts, UTXOs, balance histories, and estimated fees, all normalized for multiple blockchain types. The file implements robust HTTP client configuration with retries and timeout handling, integrates detailed logging, and uses decorators for automated API documentation generation. It forms a foundational building block in the blockchain data indexing architecture, enabling scalable and consistent blockchain data access for client applications and upper-layer services.