controller.ts
Overview
`controller.ts` provides an API controller implementation for interacting with the Optimism Layer 2 Ethereum network. It extends a generic Ethereum Virtual Machine (EVM) controller to specialize functionality for Optimism, including gas estimation and fetching current gas fee recommendations. This file acts as a bridge between HTTP API requests and underlying blockchain service logic, integrating multiple utility libraries and external services (like Blockbook and Etherscan) to deliver transaction-related data.
Key functionalities include:
Estimating gas costs for Optimism transactions, including separate Layer 1 and Layer 2 gas components.
Fetching recommended gas fees based on live data from the Optimism Gas Price Oracle smart contract.
Handling environment-specific configurations for RPC endpoints and indexer services.
This controller is part of a larger modular API server that supports multiple blockchains and coinstacks with shared and specialized components.
Classes and Methods
Class: Optimism
Extends the generic `EVM` controller to implement Optimism-specific API endpoints.
Decorators:
@Route('api/v1') — Base route path for all endpoints in this controller.
@Tags('v1')— API documentation tag grouping.
Methods
estimateGas(body: EstimateGasBody): Promise<OptimismGasEstimate>
Estimates the gas cost required for an Optimism transaction, including Layer 2 gas limit and Layer 1 gas limit components.
Parameters:
body: EstimateGasBody— JSON object containing transaction details:data: string— Hex or raw transaction data payload.from: string— Sender Ethereum address.to: string— Recipient Ethereum address.value: string— Transaction value in smallest unit (wei).
Returns:
Promise<OptimismGasEstimate>— Object containing:gasLimit: string — Estimated Layer 2 gas limit.
l1GasLimit: string — Estimated Layer 1 gas limit.
Throws:
ValidationError (HTTP 422) for invalid inputs.
InternalServerError(HTTP 500) for unexpected failures.
Usage Example:
POST /api/v1/gas/estimate
{
"data": "0x",
"from": "0x0000000000000000000000000000000000000000",
"to": "0x15E03a18349cA885482F59935Af48C5fFbAb8DE1",
"value": "1337"
}
Implementation Highlights:
Calls the shared
service.estimateGasto get L2 gas limit.Constructs an unsigned transaction hash serialized in legacy format.
Queries the Optimism Gas Price Oracle contract's
getL1GasUsedfunction to get L1 gas limit.Returns combined gas limits.
getGasFees(): Promise<OptimismGasFees>
Fetches the current recommended gas fees from the Optimism Gas Price Oracle.
Parameters: None.
Returns:
Promise<OptimismGasFees>— Object containing:l1GasPrice: string— Current Layer 1 gas price in wei.baseFeePerGas: string— Base fee per gas unit for L2.Fee tiers (
slow,average,fast), each with:gasPricemaxFeePerGasmaxPriorityFeePerGas
Throws:
InternalServerError(HTTP 500) for unexpected failures.
Usage Example:
GET /api/v1/gas/fees
Implementation Details:
Retrieves gas fees from the shared service.
Calls contract methods on the Gas Price Oracle to determine if network is in "Ecotone" mode.
If Ecotone, calculates
l1GasPriceusing a weighted formula involving base fees and scalars.Otherwise, calculates legacy
l1GasPriceas a product of base fee and scalar.Returns combined gas fee data.
Important Implementation Details
Environment Configuration:
The file checks and uses environment variables for Etherscan API keys, RPC URLs, indexer URLs, and network identifiers.
Supports multiple indexer and RPC providers (e.g., Liquify, NOWNODES) by dynamically adjusting URLs and headers.
Clients and Services:
Uses
viemlibrary'screatePublicClientfor JSON-RPC communication with Optimism chain.Instantiates
Blockbookclient for indexer interactions.Uses a
GasOracleabstraction to fetch and calculate gas prices.The shared
Serviceaggregates these clients and provides high-level blockchain operations.
Contract Interaction:
The Gas Price Oracle smart contract on Optimism is accessed using
viem'sgetContractwith ABI and address.Provides real-time data for L1 gas usage and fee scalars.
Serialization:
Uses
serializeTransactionto create an unsigned transaction hash for L1 gas estimation.Ensures compatibility with legacy transaction types.
Error Handling:
The controller methods use TSOA decorators to define HTTP responses and validation errors.
Throws errors when required environment variables are missing.
Inheritance:
The
Optimismcontroller extends a baseEVMcontroller, inheriting common Ethereum-compatible blockchain API functionality.Overrides and extends with Optimism-specific logic.
Interaction with Other System Components
BaseAPI and API Interfaces: Implements these interfaces to conform to the standardized API contract.
EVM Controller: Extends the generic Ethereum controller, allowing reuse of common logic.
Service Layer: Delegates blockchain data fetching and gas estimation to the shared
Serviceinstance configured for Optimism.GasOracle: Utilized for current gas fee calculations.
Blockbook: Used as an indexer client for optimized blockchain data retrieval.
External APIs:
Etherscan API for explorer-related data.
Indexer APIs for chain data.
RPC endpoints for direct chain interaction.
Environment Variables: This file depends heavily on runtime environment variables to configure API keys, URLs, and network contexts.
Visual Diagram
classDiagram
class Optimism {
+estimateGas(body: EstimateGasBody): Promise<OptimismGasEstimate>
+getGasFees(): Promise<OptimismGasFees>
}
class EVM {
<<abstract>>
+service: Service
...
}
class Service {
+estimateGas(body: EstimateGasBody): Promise<string>
+getGasFees(): Promise<GasFees>
...
}
class GasOracle {
+client: PublicClient
+logger: Logger
+coinstack: string
...
}
class Blockbook {
+httpURL: string
+wsURL: string
+logger: Logger
+apiKey?: string
...
}
Optimism --|> EVM
Optimism --> Service : uses
Service --> GasOracle : uses
Service --> Blockbook : uses
Summary
`controller.ts` is the Optimism-specific API controller responsible for exposing endpoints to estimate gas and retrieve gas price data. It leverages a modular service architecture integrating blockchain clients, gas oracles, and external indexers. The code carefully handles environment-based configurations and interacts with Optimism's Gas Price Oracle smart contract to provide accurate gas estimations tailored to Optimism's Layer 2 setup. This file exemplifies a clean separation of concerns and practical use of inheritance to extend a generic EVM API controller for a specialized blockchain network.