controller.ts
Overview
[controller.ts](/projects/291/68853) defines the Arbitrum-specific API controller extending a generic Ethereum Virtual Machine (EVM) controller. It provides HTTP endpoints for estimating gas costs and retrieving current gas fees on the Arbitrum chain. The file integrates multiple services and clients (including Blockbook, a gas oracle, and an RPC client) to handle blockchain data and transactions. It leverages environmental configurations to connect to different RPC and indexer endpoints with necessary authentication.
This controller acts as the interface layer between HTTP API requests and the underlying blockchain data services, exposing essential blockchain utilities tailored for the Arbitrum network.
Detailed Explanation
Imports and Configuration
External libraries:
@shapeshiftoss/blockbook: Blockchain indexer client.@shapeshiftoss/logger: Logging utility.tsoa: Decorators for API routing and validation.viem: Ethereum client utilities.
Internal modules:
Common API models and base classes like BaseAPI,
EstimateGasBody,GasEstimate,GasFees, and error types.EVM-specific controller and service abstractions.
GasOraclefor advanced gas fee estimations.
Environment variables:
API keys, URLs, and network identifiers are loaded from environment variables and validated at startup.
Client and Service Initialization:
Creates a
PublicClientfromviemfor RPC communication.Instantiates
BlockbookandGasOracleclients with proper URLs and headers.Creates a specialized
Servicethat bundles these clients and utilities.Assigns the created
serviceinstance to the static property of the genericEVMcontroller class, ensuring all subclasses use this service.
Class: Arbitrum
Extends the generic `EVM` controller and implements [BaseAPI](/projects/291/69264) and `API` interfaces to provide Arbitrum-specific endpoints. Decorated with `@Route` and `@Tags` for API versioning and grouping.
Methods
estimateGas
async estimateGas(body: EstimateGasBody): Promise<GasEstimate>
Description: Estimates the gas cost of a transaction based on the provided transaction data.
Parameters:
body(EstimateGasBody): Object containing transaction details:data: Hex string representing transaction data (optional).from: Sender address.to: Recipient address.value: Amount of ETH to transfer (in wei as string).
Returns: A promise resolving to a
GasEstimateobject that includes the estimated gas limit as a string.Errors:
ValidationError(422) if input is invalid.InternalServerError(500) for server-side issues.
Example Request Body:
{ "data": "0x", "from": "0x0000000000000000000000000000000000000000", "to": "0x0000000000000000000000000000000000000000", "value": "1337" }Example Response:
{ "gasLimit": "374764" }Usage: Called via HTTP POST at
/api/v1/gas/estimate.
getGasFees
async getGasFees(): Promise<GasFees>
Description: Retrieves the current recommended gas fees for transactions on the Arbitrum network.
Returns: A promise resolving to a
GasFeesobject that contains:baseFeePerGas: The base fee in wei (string).slow,average,fast: Fee tiers each containing:gasPricemaxFeePerGasmaxPriorityFeePerGas
Notes:
For EIP-1559 compliant transactions, clients should use
maxFeePerGasandmaxPriorityFeePerGas.For legacy transactions, clients should use
gasPrice.
Errors:
InternalServerError(500) for server issues.
Example Response:
{ "baseFeePerGas": "100000000", "slow": { "gasPrice": "184334277", "maxFeePerGas": "190000001", "maxPriorityFeePerGas": "90000001" }, "average": { "gasPrice": "187859277", "maxFeePerGas": "205000001", "maxPriorityFeePerGas": "105000001" }, "fast": { "gasPrice": "199001183", "maxFeePerGas": "290000001", "maxPriorityFeePerGas": "190000001" } }Usage: Called via HTTP GET at
/api/v1/gas/fees.
Implementation Details and Algorithms
Service Delegation: The controller methods delegate logic to the
serviceinstance of typeService. This design promotes separation of concerns: the controller handles routing and HTTP concerns, and the service encapsulates business logic and blockchain interactions.Gas Estimation: Likely uses underlying RPC methods (e.g.,
eth_estimateGas) or indexer data to simulate and estimate the gas cost of a transaction without broadcasting it.Gas Fees Calculation: The
GasOracleservice is used to fetch and calculate current gas fees, incorporating EIP-1559 fee market parameters and fallback legacy gas prices.Dynamic Configuration: The file uses environment variables to configure indexer and RPC endpoints dynamically. It also detects specific providers (Liquify, NowNodes) to append API keys and headers accordingly.
Interaction with Other Parts of the System
Base EVM Controller (
EVM):Arbitruminherits from this base class providing common EVM functionality and shared service usage.Service Layer (
Service): Centralizes blockchain interaction logic used by this controller.Blockbook Client: Provides blockchain data querying capabilities via HTTP and WebSocket.
Gas Oracle: Supplies real-time gas fee recommendations.
RPC Client (
viem): Used for direct blockchain RPC calls.API Framework (
tsoa): Provides decorators for route definition, request/response validation, and automated API docs generation.Environment Variables: Control network-specific settings and API keys, enabling flexibility and security.
Usage Examples
Estimate Gas
**HTTP Request:**
POST /api/v1/gas/estimate
Content-Type: application/json
{
"data": "0x",
"from": "0x0000000000000000000000000000000000000000",
"to": "0x0000000000000000000000000000000000000000",
"value": "1337"
}
**HTTP Response:**
{
"gasLimit": "374764"
}
Get Gas Fees
**HTTP Request:**
GET /api/v1/gas/fees
**HTTP Response:**
{
"baseFeePerGas": "100000000",
"slow": {
"gasPrice": "184334277",
"maxFeePerGas": "190000001",
"maxPriorityFeePerGas": "90000001"
},
"average": {
"gasPrice": "187859277",
"maxFeePerGas": "205000001",
"maxPriorityFeePerGas": "105000001"
},
"fast": {
"gasPrice": "199001183",
"maxFeePerGas": "290000001",
"maxPriorityFeePerGas": "190000001"
}
}
Mermaid Diagram
classDiagram
class Arbitrum {
+estimateGas(body: EstimateGasBody): Promise<GasEstimate>
+getGasFees(): Promise<GasFees>
}
class EVM {
<<abstract>>
+service: Service
}
class Service {
-blockbook: Blockbook
-gasOracle: GasOracle
-explorerApiUrl: URL
-client: PublicClient
-logger: Logger
-rpcUrl: string
-rpcApiKey: string | undefined
+estimateGas(body: EstimateGasBody): Promise<GasEstimate>
+getGasFees(): Promise<GasFees>
}
class Blockbook {
-httpURL: string
-wsURL: string
-logger: Logger
-apiKey: string | undefined
}
class GasOracle {
-logger: Logger
-client: PublicClient
-coinstack: string
}
class Logger {
-namespace: string[]
-level: string
}
class PublicClient {
-chain: object
-transport: object
}
Arbitrum --|> EVM
EVM o-- Service : uses
Service *-- Blockbook : contains
Service *-- GasOracle : contains
Service *-- PublicClient : contains
Service *-- Logger : contains
Summary
The [controller.ts](/projects/291/68853) file defines the Arbitrum API controller exposing endpoints to estimate transaction gas and retrieve gas fee recommendations. It is built on top of a generic EVM controller and leverages a robust service layer integrating blockchain clients and gas oracles. The controller ensures proper configuration via environment variables and supports different indexer and RPC providers. It forms a critical part of the backend API enabling clients to interact with the Arbitrum blockchain efficiently and reliably.