controller.ts


Overview

The [controller.ts](/projects/291/68853) file defines the `UTXO` API controller class, which exposes RESTful endpoints for interacting with UTXO-based blockchains (e.g., Bitcoin and its derivatives) within a unified API framework. This controller implements the `BaseAPI` and `API` interfaces to provide standardized methods for retrieving blockchain information, account details, transaction history, UTXOs, transaction data, broadcasting transactions, and fetching network fees.

The controller uses the `Service` class (imported as `UTXO.service`) to delegate business logic and data retrieval, maintaining a clean separation between HTTP routing/validation and the underlying blockchain interactions.

The file relies on environment configuration (`NETWORK` variable) to identify the blockchain network context and uses `tsoa` decorators for API routing, method definitions, parameter extraction, and response metadata.


Classes

UTXO Class

**Location:** [controller.ts](/projects/291/68853)

**Extends:** `Controller` (from `tsoa`)

**Implements:** `BaseAPI`, `API`

**Purpose:** Defines REST API endpoints for UTXO blockchain interactions, exposing methods to get blockchain info, account data, transaction history, UTXOs, transaction details, send transactions, and get network fees.

**Static Properties:**


Methods

All controller methods are asynchronous and return Promises resolving to the respective data types.

getInfo()

@Get('info/')
async getInfo(): Promise<BaseInfo>

**Description:** Returns basic information about the running coinstack, primarily the network name.

**Parameters:** None

**Returns:** `Promise` — An object containing `network` (string), which is the blockchain network identifier from the environment variable.

**Usage Example:**

const info = await utxoController.getInfo();
console.log(info.network); // e.g., "mainnet"

getAccount(pubkey: string)

@Get('account/{pubkey}')
async getAccount(@Path() pubkey: string): Promise<Account>

**Description:** Retrieves account details for a given address or extended public key (xpub).

**Parameters:**

**Returns:** `Promise` — The account details including balances, addresses, and other metadata.

**Response Codes:**

**Usage Example:**

const account = await utxoController.getAccount('xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKi...');
console.log(account.balance);

getTxHistory(pubkey: string, cursor?: string, pageSize = 10)

@Get('account/{pubkey}/txs')
async getTxHistory(
  @Path() pubkey: string, 
  @Query() cursor?: string, 
  @Query() pageSize = 10
): Promise<TxHistory>

**Description:** Fetches paginated transaction history for a specified address or extended public key.

**Parameters:**

**Returns:** `Promise` — Paginated transaction history data including transactions, pagination cursor for next page.

**Response Codes:**

**Usage Example:**

const txs = await utxoController.getTxHistory('1A1zP1...', undefined, 20);
console.log(txs.transactions.length);

getUtxos(pubkey: string)

@Get('account/{pubkey}/utxos')
async getUtxos(@Path() pubkey: string): Promise<Array<Utxo>>

**Description:** Retrieves all unspent transaction outputs (UTXOs) for the given address or extended public key.

**Parameters:**

**Returns:** `Promise>` — Array of UTXO objects representing spendable outputs.

**Response Codes:**

**Usage Example:**

const utxos = await utxoController.getUtxos('xpub6...');
console.log(utxos[0].txid);

getTransaction(txid: string)

@Get('tx/{txid}')
async getTransaction(@Path() txid: string): Promise<Tx>

**Description:** Fetches detailed parsed transaction information for a given transaction ID (hash).

**Parameters:**

**Returns:** `Promise` — Parsed transaction details including inputs, outputs, confirmations, fees.

**Response Codes:**

**Usage Example:**

const tx = await utxoController.getTransaction('e3c3...');
console.log(tx.fees);

getRawTransaction(txid: string)

@Get('tx/{txid}/raw')
async getRawTransaction(@Path() txid: string): Promise<RawTx>

**Description:** Retrieves raw transaction data directly from the blockchain node.

**Parameters:**

**Returns:** `Promise` — Raw transaction hex and metadata.

**Response Codes:**

**Usage Example:**

const rawTx = await utxoController.getRawTransaction('e3c3...');
console.log(rawTx.hex);

sendTx(body: SendTxBody)

@Post('send/')
async sendTx(@Body() body: SendTxBody): Promise<string>

**Description:** Broadcasts a raw transaction to the blockchain network.

**Parameters:**

**Returns:** `Promise` — Transaction ID of the broadcasted transaction.

**Response Codes:**

**Usage Example:**

const txid = await utxoController.sendTx({ hex: '0200000001...' });
console.log(txid);

getNetworkFees()

@Get('/fees')
async getNetworkFees(): Promise<NetworkFees>

**Description:** Returns the currently recommended network fees to use for transactions, providing fee rates for different confirmation priorities.

**Parameters:** None

**Returns:** `Promise` — Fee rates (e.g., satoshis per byte) categorized by speed (e.g., fast, average, slow).

**Response Codes:**

**Usage Example:**

const fees = await utxoController.getNetworkFees();
console.log(fees.fast);

Important Implementation Details


Interactions with Other System Components


Usage Workflow Summary

  1. A client sends an HTTP request to one of the defined endpoints (e.g., GET /api/v1/account/{pubkey}/txs).

  2. The UTXO controller method receives the request, extracts parameters via decorators.

  3. The controller calls the corresponding static method on the Service class.

  4. The Service queries the blockchain data sources (Blockbook, node RPC), processes and formats data.

  5. The formatted data is returned to the controller, which sends it as JSON response.

  6. If errors occur, appropriate HTTP error responses are generated based on the error types.


Mermaid Class Diagram

classDiagram
    class UTXO {
        <<Controller>>
        +static service: Service
        +getInfo(): Promise<BaseInfo>
        +getAccount(pubkey: string): Promise<Account>
        +getTxHistory(pubkey: string, cursor?: string, pageSize: number): Promise<TxHistory>
        +getUtxos(pubkey: string): Promise<Array<Utxo>>
        +getTransaction(txid: string): Promise<Tx>
        +getRawTransaction(txid: string): Promise<RawTx>
        +sendTx(body: SendTxBody): Promise<string>
        +getNetworkFees(): Promise<NetworkFees>
    }
    UTXO --|> Controller
    UTXO ..> Service : delegates

Summary

The [controller.ts](/projects/291/68853) file defines a robust, decorator-driven REST API controller class `UTXO` for UTXO-based blockchains, exposing essential blockchain data and transaction functionalities via a uniform interface. It leverages a dedicated service layer to encapsulate business logic and blockchain interaction, ensuring clean separation of concerns. The file integrates seamlessly in a modular Unified API Layer architecture that supports multiple blockchain types, providing clients a consistent and extensible API surface.


End of Documentation for controller.ts