index.ts
Overview
The `index.ts` file serves as the central entry point and interface definition for the Unified API Layer that standardizes blockchain interactions across multiple coinstacks. It exposes common models, utilities, middleware, and protocol-specific namespaces (`evm` and `utxo`) to provide a unified development experience.
Most importantly, it defines the `BaseAPI` interface—an abstract contract that all blockchain coinstack API implementations must conform to. This interface ensures consistency by prescribing key methods for retrieving chain info, account data, transaction history, and submitting transactions.
Additionally, the file defines a generic `ApiError` class for uniform error handling across all API implementations.
Exports and Imports
Imports
Imports core data models (
BaseAccount,BaseInfo,SendTxBody,BaseTxHistory) from the./modelsmodule. These models represent the fundamental data structures used in API responses and requests.
Re-exports
Re-exports everything from:
./models(data models)./middleware(request/response middleware components)./websocket(WebSocket-related utilities)./registry(likely for managing API or event registries)./prometheus(metrics collection integration)./utils(utility functions)
Namespaces:
evm— exports everything under the./evmdirectory, encapsulating EVM-compatible blockchain API implementations.utxo— exports everything under the./utxodirectory, encapsulating UTXO-based blockchain API implementations.
This structure provides a modular, organized API surface for different blockchain types and shared utilities.
Classes
ApiError
export class ApiError extends Error {
statusText: string
statusCode: number
constructor(statusText: string, statusCode: number, message?: string) {
super(message)
this.name = this.constructor.name
this.statusText = statusText
this.statusCode = statusCode
}
}
Purpose
`ApiError` extends the native JavaScript `Error` class to provide a consistent way to represent HTTP API errors. It captures:
statusText: A short textual description of the error status (e.g., "Not Found", "Unauthorized").statusCode: Numeric HTTP status code (e.g., 404, 401).Optional detailed error
message.
Usage Example
throw new ApiError('Not Found', 404, 'The requested account does not exist');
This class can be used by API controllers and services to throw errors that middleware can catch and format into standardized HTTP responses.
Interfaces
BaseAPI
export interface BaseAPI {
getInfo(): Promise<BaseInfo>
getAccount(pubkey: string): Promise<BaseAccount>
getTxHistory(pubkey: string, cursor?: string, pageSize?: number): Promise<BaseTxHistory>
sendTx(body: SendTxBody): Promise<string>
}
Purpose
`BaseAPI` defines the minimal set of asynchronous methods that all blockchain coinstack API implementations must provide. It abstracts the specifics of different blockchain protocols behind a standardized interface.
Methods
Method | Parameters | Returns | Description |
|---|---|---|---|
`getInfo` | None | `Promise` | Retrieves metadata about the running coinstack (e.g., network info). |
`getAccount` | `pubkey: string` - account address or extended public key | `Promise` | Fetches detailed account information by address or xpub. |
`getTxHistory` | `pubkey: string` - account address or extended public key | `Promise` | Retrieves paginated transaction history for an account. |
`sendTx` | `body: SendTxBody` - serialized raw transaction hex | `Promise` | Submits a raw transaction to be broadcast; returns transaction ID. |
Implementation Notes
The interface includes commented-out route decorators (
@Get,@Post) as documentation hints. Since TypeScript interfaces cannot enforce decorators, implementations should apply these decorators in their concrete classes to define REST routes.The interface enforces a consistent method signature for all coinstack APIs, but implementations may extend it with chain-specific methods.
Usage Example
class EvmApi implements BaseAPI {
async getInfo(): Promise<BaseInfo> {
// Implementation specific to EVM chain
}
async getAccount(pubkey: string): Promise<BaseAccount> {
// Fetch account details
}
async getTxHistory(pubkey: string, cursor?: string, pageSize?: number): Promise<BaseTxHistory> {
// Fetch transaction history with pagination
}
async sendTx(body: SendTxBody): Promise<string> {
// Broadcast raw transaction hex
}
}
Important Implementation Details
Error Handling: The
ApiErrorclass standardizes API error responses, facilitating uniform error propagation and client communication.Interface Constraints: Due to TypeScript limitations, decorators cannot be enforced on interface methods. The documentation in comments reminds implementers to carefully maintain method signatures and apply route decorators consistently.
Namespace Exports: The
evmandutxonamespaces aggregate their respective blockchain implementations, allowing consumers to import coinstack-specific APIs cleanly.Modularity: By re-exporting models, middleware, and utilities, this file acts as a single import point for the broader API ecosystem, promoting ease of use and maintainability.
Interaction with Other System Components
Models (
./models): Defines core data structures such asBaseAccount,BaseInfo,SendTxBody, andBaseTxHistoryused throughout the API.Middleware (
./middleware): Provides request/response lifecycle hooks like validation, authentication, and error formatting.WebSocket (
./websocket): Supports real-time event subscriptions and push notifications.Registry (
./registry): Likely manages API versions, event handlers, or service discovery.Prometheus (
./prometheus): Integrates monitoring and metrics collection for API performance and usage.Utility Functions (
./utils): Contains helper functions and common utilities shared across implementations.EVM and UTXO Modules (
./evmand./utxo): Contain concrete implementations of theBaseAPIinterface for account-based (EVM) and UTXO-based blockchains respectively, including controllers and services.
Visual Diagram
flowchart TD
A[BaseAPI Interface] -->|Implements| B[EVM API Implementation]
A -->|Implements| C[UTXO API Implementation]
subgraph Exports
D[Models]
E[Middleware]
F[WebSocket]
G[Registry]
H[Prometheus]
I[Utils]
J[EVM Namespace]
K[UTXO Namespace]
end
L[ApiError Class] -->|Used by| B
L -->|Used by| C
B -->|Uses| D
B -->|Uses| E
B -->|Uses| I
C -->|Uses| D
C -->|Uses| E
C -->|Uses| I
index_ts["index.ts"] --> Exports
index_ts --> A
index_ts --> L
Summary
The `index.ts` file is a foundational module in the Unified API Layer, establishing:
A standardized API interface (
BaseAPI) that all blockchain coinstack implementations must follow.A generic API error class (
ApiError) for consistent error signaling.A centralized export hub that aggregates data models, middleware, utilities, WebSocket support, and blockchain-specific API namespaces (
evmandutxo).
This design enforces uniformity and modularity across diverse blockchain protocols, enabling scalable development and maintenance of the multi-blockchain Unified API Layer.
References
Unified API Layer Documentation (see provided relevant topics)
Related files:
evm/controller.ts,evm/service.tsutxo/controller.ts,utxo/service.tsModels and middleware modules within the same directory structure