controller.ts
Overview
`controller.ts` defines an API controller for interacting with the Avalanche blockchain network. It extends a generic Ethereum Virtual Machine (EVM) controller to provide Avalanche-specific functionality, such as estimating gas costs for transactions and retrieving current recommended gas fees. This controller is implemented using the [tsoa](https://tsoa-community.github.io/docs/) framework to generate OpenAPI-compliant REST endpoints.
Key responsibilities:
Initialize and configure blockchain clients and services for Avalanche.
Expose REST endpoints to estimate transaction gas and fetch recommended gas fees.
Leverage underlying services that interact with Avalanche nodes, block explorers, and gas oracles.
This file acts as a bridge between HTTP API requests and the Avalanche blockchain service layer, enabling clients to programmatically query gas-related data relevant to Avalanche transactions.
Classes and Functions
Class: Avalanche
Extends:
EVMImplements:
BaseAPI,APIRoute:
/api/v1Tags:
v1
`Avalanche` is the primary controller class exposing Avalanche-specific endpoints for gas estimation and fee retrieval. It inherits common EVM functionality and overrides or extends it with Avalanche-focused implementations.
Methods
estimateGas
async estimateGas(body: EstimateGasBody): Promise<GasEstimate>
HTTP Method:
POSTRoute:
/api/v1/gas/estimateRequest Body:
EstimateGasBodyResponse:
GasEstimateResponses:
422:
ValidationError500:
InternalServerError
Example Request Body:
{ "data": "0x", "from": "0x0000000000000000000000000000000000000000", "to": "0x9D1170D30944F2E30664Be502aC57F6096fB5366", "value": "1337" }Example Response:
{ "gasLimit": "21000" }
**Description:** Estimates the gas cost for a given transaction on the Avalanche network. It accepts transaction details such as sender, recipient, data payload, and value. The method delegates the estimation process to the injected `service` instance, which handles communication with Avalanche nodes and gas oracles.
**Usage Example:**
import { Avalanche } from './controller'
const avalancheController = new Avalanche()
const gasEstimate = await avalancheController.estimateGas({
from: '0x0000000000000000000000000000000000000000',
to: '0x9D1170D30944F2E30664Be502aC57F6096fB5366',
value: '1337',
data: '0x',
})
console.log(gasEstimate.gasLimit) // e.g. "21000"
getGasFees
async getGasFees(): Promise<GasFees>
HTTP Method:
GETRoute:
/api/v1/gas/feesResponse:
GasFeesResponses:
500:
InternalServerError
Example Response:
{ "baseFeePerGas": "25000000000", "slow": { "gasPrice": "25757584186", "maxFeePerGas": "28394352138", "maxPriorityFeePerGas": "3394352138" }, "average": { "gasPrice": "28228764956", "maxFeePerGas": "32489417391", "maxPriorityFeePerGas": "7489417391" }, "fast": { "gasPrice": "38695403370", "maxFeePerGas": "47086501038", "maxPriorityFeePerGas": "22086501038" } }
**Description:** Fetches the current recommended gas fees for transactions on Avalanche. This includes base fees and suggested values for slow, average, and fast transaction speeds. The response supports both EIP-1559 and legacy transaction fee models.
**Usage Example:**
const fees = await avalancheController.getGasFees()
console.log(fees.average.maxFeePerGas) // e.g. "32489417391"
Important Implementation Details
Environment Configuration and Validation
The file reads multiple critical environment variables at startup:
ETHERSCAN_API_KEY: API key for the Etherscan explorer (used for Avalanche chain ID 43114).INDEXER_URL,INDEXER_WS_URL,INDEXER_API_KEY: URLs and keys for a Blockbook indexer service.NETWORK: The blockchain network identifier.RPC_URL,RPC_API_KEY: RPC endpoint and optional API key for node communication.
If any required environment variable is missing, the module throws an error immediately to prevent misconfiguration.
Client and Service Initialization
client: A public client created viaviemlibrary configured to connect to the Avalanche network RPC endpoint with optional API key headers.blockbook: An instance ofBlockbookconfigured with indexer URLs and API key to fetch blockchain data efficiently through websocket and HTTP.gasOracle: Encapsulates logic to fetch gas price recommendations from various sources.service: The main service instance combining blockbook, gas oracle, explorer API URL, and RPC client to provide high-level blockchain operations.
`service` is assigned to the static property `EVM.service` so that all inherited EVM controllers share the same service implementation.
Inheritance from EVM Controller
`Avalanche` extends the generic `EVM` controller, inheriting common blockchain API endpoints and logic. This design promotes code reuse across EVM-compatible chains by:
Providing chain-agnostic logic in
EVM.Allowing chain-specific overrides or additions in
Avalanche.
Interaction with Other Parts of the System
Common API Models and Controllers: Imports types and base classes like
BaseAPI,EstimateGasBody, andEVMfrom a shared common API package, ensuring consistent API contracts across chains.Service Layer: Delegates business logic to the
Serviceclass, which interacts with blockchain nodes, explorers, and gas oracle services.External APIs:
Etherscan API (using
ETHERSCAN_API_KEY) for blockchain explorer data.Blockbook indexer for efficient transaction and block data retrieval.
Avalanche RPC endpoint for direct blockchain communication.
Logging: Uses a centralized
Loggerinstance with namespace and log level configured by environment variables.
Visual Diagram
classDiagram
class Avalanche {
+estimateGas(body: EstimateGasBody): Promise<GasEstimate>
+getGasFees(): Promise<GasFees>
}
Avalanche --|> EVM
class EVM {
<<abstract>>
+service: Service
}
class Service {
-blockbook: Blockbook
-gasOracle: GasOracle
-explorerApiUrl: URL
-client: PublicClient
-logger: Logger
-rpcUrl: string
-rpcApiKey: string
+estimateGas(body: EstimateGasBody): Promise<GasEstimate>
+getGasFees(): Promise<GasFees>
}
class Blockbook {
-httpURL: string
-wsURL: string
-apiKey: string
-logger: Logger
}
class GasOracle {
-logger: Logger
-client: PublicClient
-coinstack: string
+getGasFees(): Promise<GasFees>
}
Avalanche ..> Service : uses
Service *-- Blockbook : composes
Service *-- GasOracle : composes
Summary
`controller.ts` is the Avalanche-specific API controller extending a common EVM controller. It initializes necessary clients and services with proper configuration, exposes REST endpoints to estimate gas and retrieve gas fees, and delegates core logic to a shared service layer. This modular and environment-driven design enables scalable multi-chain support with clean separation between API routing, service logic, and blockchain communication.