controller.ts
Overview
[controller.ts](/projects/291/68853) serves as the API controller layer for Ethereum-related endpoints within the application. It extends a generic Ethereum Virtual Machine (EVM) controller to expose RESTful API routes that allow clients to:
Estimate the gas cost of Ethereum transactions.
Retrieve current recommended gas fees for transactions.
The file integrates several internal services and external dependencies to interact with blockchain data providers, gas oracles, and RPC endpoints. It manages configuration via environment variables, instantiates service classes, and binds them to the controller. The controller uses decorators from the `tsoa` framework to define routes, request/response schemas, and API documentation.
This file acts as the bridge between external API consumers and internal blockchain service logic, encapsulating Ethereum-specific behavior and exposing it through a versioned API.
Detailed Explanations
Imports and Environment Setup
Imports core blockchain utilities and service classes from internal modules (
Blockbook,GasOracle,Service).Uses
tsoadecorators (Route,Tags,Post,Get,Body,Response,Example) for API metadata and validation.Reads critical configuration from environment variables (
ETHERSCAN_API_KEY,INDEXER_URL, etc.) and validates presence.Configures URLs and API keys conditionally based on provider identification (e.g., Liquify, NowNodes).
Instantiates clients (
Blockbook,GasOracle,viempublic client) and the mainServiceinstance.Assigns the created
serviceto the baseEVMcontroller class to be used by all instances.
Class: Ethereum
Extends the generic `EVM` controller and implements the [BaseAPI](/projects/291/69264) and `API` interfaces to expose Ethereum-specific API endpoints.
Decorators
@Route('api/v1'): Defines the base route path for all endpoints as/api/v1.@Tags('v1'): Tags the API group as version 1 for documentation.
Methods
estimateGas(body: EstimateGasBody): Promise<GasEstimate>
Estimates the gas required to perform a given Ethereum transaction.
Route:
POST /api/v1/gas/estimateParameters:
body(EstimateGasBody): The transaction details for which to estimate gas. It includes:data: Hex-encoded transaction data payload.from: Sender Ethereum address.to: Receiver Ethereum address.value: Amount of ETH (in wei) to transfer.
Returns: Promise - An object containing the estimated gas limit as a string.
Example Request Body:
{ "data": "0x", "from": "0x0000000000000000000000000000000000000000", "to": "0x0000000000000000000000000000000000000000", "value": "1337" }Example Response:
{ "gasLimit": "26540" }Error Responses:
422 Validation Error if input is invalid.
500 Internal Server Error on unexpected failures.
Usage:
This method is used by clients to estimate gas before submitting transactions, enabling them to specify appropriate gas limits and avoid transaction failures.
getGasFees(): Promise<GasFees>
Retrieves the current recommended gas fee values for Ethereum transactions, supporting both EIP-1559 and legacy transaction types.
Route:
GET /api/v1/gas/feesParameters: None
Returns:
Promise<GasFees>- An object containing:baseFeePerGas: The base fee per gas in wei.slow,average,fast: Objects with recommendedgasPrice,maxFeePerGas, andmaxPriorityFeePerGasvalues for different transaction speeds.
Example Response:
{ "baseFeePerGas": "77654025212", "slow": { "gasPrice": "77109280451", "maxFeePerGas": "77744243213", "maxPriorityFeePerGas": "90218001" }, "average": { "gasPrice": "78637140239", "maxFeePerGas": "79158075213", "maxPriorityFeePerGas": "1504050001" }, "fast": { "gasPrice": "85079071846", "maxFeePerGas": "89883761218", "maxPriorityFeePerGas": "12229736006" } }Error Responses:
500 Internal Server Error
Usage:
Clients query this endpoint to obtain up-to-date gas fee recommendations to optimize transaction costs and confirmation times.
Important Implementation Details and Algorithms
Service Initialization:
The file initializes a
Serviceinstance that wraps blockchain clients (Blockbook,GasOracle,viempublic client).The service manages communication with Ethereum nodes, blockchain indexers, and gas oracles.
The
Serviceinstance also holds URLs with embedded API keys, handling provider-specific requirements (Liquify, NowNodes).
Gas Estimation and Fee Retrieval:
The controller delegates actual gas estimation and fee retrieval logic to the
serviceinstance.The
estimateGasmethod callsservice.estimateGas(body)which likely interacts with RPC nodes or blockchain clients to simulate transactions and return gas estimates.The
getGasFeesmethod callsservice.getGasFees()which aggregates data from theGasOracleand other sources to provide current fee suggestions.
Error Handling:
Uses
tsoa’s@Responsedecorator to document and handle validation and server errors.Environment variables are strictly validated at startup to prevent misconfiguration.
Inheritance:
The
Ethereumcontroller extendsEVM, a generic controller for Ethereum-compatible chains.The shared
serviceinstance is statically assigned on theEVMclass, promoting reuse and singleton pattern.
Interaction With Other Parts of the System
Common API Models: Uses shared model definitions (
EstimateGasBody,GasEstimate,GasFees, etc.) from a common API module to standardize request/response schemas.EVM Controller and Service: Extends the base EVM controller and uses the EVM service for common Ethereum Virtual Machine functionality.
Blockchain Clients:
Blockbookprovides blockchain indexing and websocket support.GasOraclesupplies gas fee data.viemclient handles RPC calls to Ethereum nodes.
External APIs:
Interacts with Etherscan API for explorer data using the API key.
Connects to RPC providers (Liquify, NowNodes) based on environment configuration.
The controller is the entry point for external API consumers and delegates complex blockchain logic to underlying service layers and clients.
Usage Examples
**Estimate Gas:**
POST /api/v1/gas/estimate
Content-Type: application/json
{
"data": "0x",
"from": "0xYourAddress",
"to": "0xRecipientAddress",
"value": "1000000000000000000"
}
**Response:**
{
"gasLimit": "21000"
}
**Get Gas Fees:**
GET /api/v1/gas/fees
**Response:**
{
"baseFeePerGas": "1000000000",
"slow": {
"gasPrice": "1100000000",
"maxFeePerGas": "1200000000",
"maxPriorityFeePerGas": "150000000"
},
"average": {
"gasPrice": "1300000000",
"maxFeePerGas": "1400000000",
"maxPriorityFeePerGas": "200000000"
},
"fast": {
"gasPrice": "1500000000",
"maxFeePerGas": "1600000000",
"maxPriorityFeePerGas": "250000000"
}
}
Mermaid Class Diagram
classDiagram
class Ethereum {
<<controller>>
+estimateGas(body: EstimateGasBody): Promise~GasEstimate~
+getGasFees(): Promise~GasFees~
}
class EVM {
<<base controller>>
+service: Service
}
class Service {
+estimateGas(body: EstimateGasBody): Promise~GasEstimate~
+getGasFees(): Promise~GasFees~
}
class Blockbook {
+httpURL: string
+wsURL: string
+logger: Logger
+apiKey: string | undefined
}
class GasOracle {
+logger: Logger
+client: any
+coinstack: string
}
class Logger {
+namespace: string[]
+level: string | undefined
}
Ethereum --|> EVM
EVM --> Service
Service --> Blockbook
Service --> GasOracle
Service --> Logger
Summary
The [controller.ts](/projects/291/68853) file implements a versioned Ethereum API controller extending a generic EVM controller. It exposes two main endpoints for estimating gas costs and fetching current gas fees, leveraging a centralized `Service` class that interacts with blockchain clients and external APIs. The controller ensures proper configuration, error handling, and API documentation using `tsoa`. This design cleanly separates API routing from business logic and external service integration, facilitating maintainability and scalability in the Ethereum coinstack API module.