controller.ts
Overview
`controller.ts` defines a RESTful API controller for interacting with the Solana blockchain. It provides endpoints to retrieve blockchain information, account details, transaction history, transaction details, send transactions, estimate fees, perform JSON-RPC calls, and fetch token metadata. The controller leverages the `helius-sdk` and Solana's web3.js library to interact with the Solana network and an external indexer to query transaction history.
This file acts as a thin API layer exposing Solana blockchain data and transaction functionality to clients while handling validation, error management, and data formatting.
Class: Solana
The `Solana` class implements the [BaseAPI](/projects/291/69264) and `API` interfaces and is decorated with tsoa decorators for routing and API documentation. It defines multiple endpoints under the route prefix `/api/v1`.
Static Properties
Property | Type | Description |
|---|---|---|
`baseFee` | string | A constant base fee value (5000). |
Methods
getInfo()
async getInfo(): Promise<BaseInfo>
Description:
Returns basic information about the running Solana coinstack, specifically the network this API is connected to.Returns:
APromiseresolving to aBaseInfoobject containing thenetworkstring.Example Response:
{ "network": "mainnet" }Usage:
GET /api/v1/info/
getAccount(pubkey: string)
async getAccount(pubkey: string): Promise<Account>
Description:
Retrieves account details including native SOL balance, unconfirmed balance (always 0 here), and token balances for a given Solana public key or extended public key.Parameters:
pubkey(path parameter): The Solana account address or extended public key.
Returns:
APromiseresolving to anAccountobject containing:pubkey: The queried public key.balance: Native SOL balance in lamports as a string.unconfirmedBalance: Always'0'.tokens: Array of token balances (TokenBalance[]).
Implementation Details:
Uses the Helius RPC client'sgetAssetsByOwnermethod to page through assets owned by the address. Filters fungible tokens and accumulates their balances. Native balance is read from the native balance info.Example Usage:
GET /api/v1/account/2bUNK6eVUmXyxeSDURsWdqi1KK8BYu4egnzyi3xDYc9MExample Response:
{ "pubkey": "2bUNK6eVUmXyxeSDURsWdqi1KK8BYu4egnzyi3xDYc9M", "balance": "0", "unconfirmedBalance": "0", "tokens": [] }Errors:
ThrowsBadRequestError,ValidationError, orInternalServerErroron failure.
getTxHistory(pubkey: string, cursor?: string, pageSize?: number)
async getTxHistory(pubkey: string, cursor?: string, pageSize = 10): Promise<TxHistory>
Description:
Fetches transaction history for an account address, supporting pagination via cursor and page size.Parameters:
pubkey(path): Solana account address.cursor(query, optional): Cursor for pagination (last transaction signature).pageSize(query, optional): Number of transactions to fetch (default 10, validated).
Returns:
APromiseresolving to aTxHistoryobject containing:pubkey: Queried public key.cursor: Cursor for next page (last signature).txs: Array of transactions (Tx[]).
Implementation Details:
Calls an external indexer API (INDEXER_URL) to get transactions on the address. Maps received enriched transactions to internalTxobjects, normalizing event fields.Example Usage:
GET /api/v1/account/2bUNK6eVUmXyxeSDURsWdqi1KK8BYu4egnzyi3xDYc9M/txs?limit=10Example Response:
Refer to the provided example in the source code for a detailed transaction object.Errors:
ThrowsBadRequestError,ValidationError, orInternalServerError.
getTransaction(txid: string)
async getTransaction(txid: string): Promise<Tx>
Description:
Retrieves detailed information about a specific transaction by its signature.Parameters:
txid(path): Transaction signature string.
Returns:
APromiseresolving to aTxobject representing the transaction.Implementation Details:
Uses the importedgetTransactionutility function to fetch and process transaction details.Example Usage:
GET /api/v1/tx/5KDSVYdUSSKSgTcq1PJFmo3vMSNeP383Q3xVqWhGX4xExaYtYmcygA7wncwz8gVgZMbhKtg5ZekD9fsF6T5mCMAvErrors:
ThrowsBadRequestError,ValidationError, orInternalServerError.
sendTx(body: SendTxBody)
async sendTx(body: SendTxBody): Promise<string>
Description:
Broadcasts a raw, serialized Solana transaction to the network.Parameters:
body(request body): Contains ahexproperty which is a base64-encoded serialized transaction string.
Returns:
APromiseresolving to the transaction signature string.Implementation Details:
Decodes the base64 string and sends the raw transaction viaheliusSdk.connection.sendRawTransaction.Example Request Body:
{ "hex": "base64-encoded-transaction" }Errors:
ThrowsBadRequestError,ValidationError, orInternalServerError.
getPriorityFees()
async getPriorityFees(): Promise<PriorityFees>
Description:
Returns current recommended priority fee levels for transactions in micro-lamports.Returns:
APromiseresolving to aPriorityFeesobject with:baseFee: The base fee (constant"5000").slow,average,fast: Priority fee levels as strings.
Implementation Details:
Fetches priority fee estimates from the Helius RPC endpoint, including all priority fee levels.Example Response:
{ "baseFee": "5000", "slow": "0", "average": "10", "fast": "400000" }Errors:
ThrowsBadRequestError,ValidationError, orInternalServerError.
estimateFees(body: EstimateFeesBody)
async estimateFees(body: EstimateFeesBody): Promise<string>
Description:
Estimates the compute unit cost (fee) for a given transaction.Parameters:
body(request body): Contains aserializedTxproperty (base64 encoded transaction message).
Returns:
APromiseresolving to a string representing the estimated compute units consumed.Implementation Details:
Deserializes the base64 transaction using
VersionedTransaction.Uses
heliusSdk.connection.simulateTransactionto simulate execution and retrieve compute units consumed.
Errors:
Throws an error ifserializedTxis missing or if the simulation fails to provide fee data.Errors Thrown:
BadRequestError,ValidationError,InternalServerError.
doRpcRequest(body: RPCRequest | RPCRequest[])
async doRpcRequest(body: RPCRequest | Array<RPCRequest>): Promise<RPCResponse | Array<RPCResponse>>
Description:
Makes a JSON-RPC request or batch request(s) to the Solana node.Parameters:
body: Single or array of JSON-RPC request objects.
Returns:
APromiseresolving to the JSON-RPC response or an array of responses.Implementation Details:
Sends the request(s) via HTTP POST to the configured RPC URL with retry logic.Example Request Body:
{ "jsonrpc": "2.0", "id": "test", "method": "getBlockHeight", "params": [] }Example Response:
{ "jsonrpc": "2.0", "id": "test", "result": 274885350 }Errors:
ThrowsBadRequestError,ValidationError, orInternalServerError.
getToken(id: string)
async getToken(id: string): Promise<Token>
Description:
Retrieves token metadata by token ID.Parameters:
id(path): Token identifier (e.g., mint address).
Returns:
APromiseresolving to aTokenobject containing:id,name,symbol,decimals, andtype.
Implementation Details:
Caches tokens in an in-memory object to avoid repeated lookups. Uses Helius SDK'sgetAssetto fetch metadata and token info. Throws if metadata or decimals are missing.Example Usage:
GET /api/v1/token/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1vExample Response:
{ "id": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "name": "USD Coin", "symbol": "USDC", "decimals": 6, "type": "FungibleToken" }Errors:
ThrowsValidationErrororInternalServerError.
Important Implementation Details
Environment Variables:
INDEXER_URL: URL of the transactions indexer service.NETWORK: Network identifier (e.g.,mainnet).RPC_URL: RPC endpoint URL for Solana node.RPC_API_KEY: API key for RPC access (optional).
The controller throws errors if any required environment variable is missing.
Helius SDK:
TheHeliusclient instance is initialized with the RPC API key and used extensively for RPC calls, asset queries, transaction sending, and fee estimation.Error Handling:
All methods use a centralizedhandleErrorfunction to convert exceptions into appropriate HTTP errors.Token Caching:
Token metadata responses are cached in memory to reduce repeated network calls.Pagination:
Transaction history supports cursor-based pagination using the last signature as the cursor.Transaction Fee Estimation:
Uses Solana'ssimulateTransactionRPC method to estimate compute units consumed by the transaction.
Interactions with Other Parts of the System
External Dependencies:
helius-sdk: For blockchain RPC interactions and enriched transaction data.@solana/web3.js: For transaction deserialization and low-level blockchain operations.tsoa: For API routing, validation, and documentation.axios: For HTTP requests to external indexer and RPC endpoints.
Internal Modules:
./models: Defines the data models (Account,API,Tx, etc.)../utils: Utility functions including HTTP wrappers and transaction fetching.../../../common/api/src: Common API error classes and base interfaces.
Environment Configuration:
Requires environment variables for URLs and API keys to function correctly.
Usage Example Summary
Endpoint | HTTP Method | Description |
|---|---|---|
`/api/v1/info/` | GET | Get coinstack info |
`/api/v1/account/{pubkey}` | GET | Get account details by pubkey |
`/api/v1/account/{pubkey}/txs` | GET | Get transaction history |
`/api/v1/tx/{txid}` | GET | Get transaction details |
`/api/v1/send/` | POST | Send raw base64-encoded tx |
`/api/v1/fees/priority` | GET | Get priority fee levels |
`/api/v1/fees/estimate` | POST | Estimate fees for serialized tx |
`/api/v1/jsonrpc/` | POST | JSON-RPC request(s) to node |
`/api/v1/token/{id}` | GET | Get token metadata |
Mermaid Class Diagram
classDiagram
class Solana {
<<API Controller>>
+static baseFee: string
+getInfo() Promise~BaseInfo~
+getAccount(pubkey: string) Promise~Account~
+getTxHistory(pubkey: string, cursor?: string, pageSize?: number) Promise~TxHistory~
+getTransaction(txid: string) Promise~Tx~
+sendTx(body: SendTxBody) Promise~string~
+getPriorityFees() Promise~PriorityFees~
+estimateFees(body: EstimateFeesBody) Promise~string~
+doRpcRequest(body: RPCRequest | Array~RPCRequest~) Promise~RPCResponse | Array~RPCResponse~
+getToken(id: string) Promise~Token~
}
Summary
`controller.ts` exposes a comprehensive Solana blockchain API that wraps low-level RPC calls and indexer queries into a user-friendly REST interface. It supports querying account balances and tokens, fetching transaction history and details, sending transactions, estimating fees, and performing raw RPC requests. The use of tsoa ensures well-documented, validated endpoints and strong typing. The file is a crucial bridge between the Solana network and client applications, encapsulating blockchain complexity and enhancing developer usability.