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:**
service: Service
A static reference to theServiceclass containing business logic implementations. This must be assigned externally before using the controller.
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:**
pubkey(string) — The account identifier, which can be a single blockchain address or an extended public key.
**Returns:** `Promise` — The account details including balances, addresses, and other metadata.
**Response Codes:**
400 Bad Request
422 Validation Error
500 Internal Server Error
**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:**
pubkey(string) — Account address or xpub.cursor(string, optional) — Pagination cursor from the previous result, base64-encoded JSON with apageproperty.pageSize(number, optional) — Number of transactions per page, defaults to 10.
**Returns:** `Promise` — Paginated transaction history data including transactions, pagination cursor for next page.
**Response Codes:**
400 Bad Request
422 Validation Error
500 Internal Server Error
**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:**
pubkey(string) — Account address or xpub.
**Returns:** `Promise>` — Array of UTXO objects representing spendable outputs.
**Response Codes:**
400 Bad Request
422 Validation Error
500 Internal Server Error
**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:**
txid(string) — Transaction hash.
**Returns:** `Promise` — Parsed transaction details including inputs, outputs, confirmations, fees.
**Response Codes:**
400 Bad Request
422 Validation Error
500 Internal Server Error
**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:**
txid(string) — Transaction hash.
**Returns:** `Promise` — Raw transaction hex and metadata.
**Response Codes:**
400 Bad Request
422 Validation Error
500 Internal Server Error
**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:**
body(SendTxBody) — Contains the serialized raw transaction hex string.
**Returns:** `Promise` — Transaction ID of the broadcasted transaction.
**Response Codes:**
400 Bad Request
422 Validation Error
500 Internal Server Error
**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:**
400 Bad Request
500 Internal Server Error
**Usage Example:**
const fees = await utxoController.getNetworkFees();
console.log(fees.fast);
Important Implementation Details
Environment Configuration:
The controller requires theNETWORKenvironment variable to be set at runtime; otherwise, it throws an Error immediately. This variable identifies the blockchain network (e.g., "mainnet", "testnet") the API serves.Service Delegation:
All controller methods delegate the actual logic to static methods of theServiceclass (UTXO.service). This separation ensures that the controller focuses on HTTP concerns, while theServicehandles blockchain communication, data formatting, and error handling.Error Handling:
The controller usestsoadecorators (@Response) to declare possible HTTP error responses for validation errors, bad requests, and internal errors. Actual error handling and throwing occur within theServiceimplementation.Routing and Validation:
The use oftsoadecorators such as@Route,@Tags,@Get,@Post,@Path,@Query, and@Bodydeclaratively specify the REST API endpoint paths, HTTP methods, and request parameter extraction. This approach provides automatic OpenAPI specification generation and input validation.Pagination:
The transaction history endpoint supports cursor-based pagination with a base64-encoded cursor token that encodes the current page state. This allows scalable querying of large transaction histories.
Interactions with Other System Components
Service Layer:
TheUTXO.service(imported from./service) implements the core blockchain interaction logic, including querying a Blockbook indexer, communicating with blockchain nodes via RPC, formatting blockchain data into API models, and managing pagination cursors.Models:
The controller uses data models imported from./modelssuch asAccount,TxHistory,Utxo,Tx,RawTx, andNetworkFeesto standardize the API response payloads.Error Classes:
Common error types (BadRequestError,ValidationError,InternalServerError) are imported from a shared location and used to provide consistent error responses.Unified API Layer:
This controller is part of a broader unified API layer that abstracts differences between blockchain types. It complements other controllers such as theEVMcontroller by implementing theBaseAPIinterface for UTXO-based blockchains.Environment:
The environment variableNETWORKconfigures which blockchain network the controller operates on, ensuring correct data context.
Usage Workflow Summary
A client sends an HTTP request to one of the defined endpoints (e.g.,
GET /api/v1/account/{pubkey}/txs).The
UTXOcontroller method receives the request, extracts parameters via decorators.The controller calls the corresponding static method on the
Serviceclass.The
Servicequeries the blockchain data sources (Blockbook, node RPC), processes and formats data.The formatted data is returned to the controller, which sends it as JSON response.
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.