controller.ts
Overview
[controller.ts](/projects/291/68853) defines the API controller for the Binance Smart Chain (BSC) implementation of an Ethereum Virtual Machine (EVM)-compatible blockchain service. This controller exposes HTTP endpoints for gas estimation and gas fee retrieval, leveraging a shared service layer that interacts with blockchain data providers and RPC clients.
Built with the `tsoa` framework for TypeScript, it integrates various components including:
Blockbook for blockchain indexing and data querying.
GasOracle for fetching gas price recommendations.
viem for Ethereum JSON-RPC client capabilities.
This file essentially acts as the REST API interface for clients to estimate gas costs and obtain current gas fees on BSC, ensuring consistent and validated responses.
Classes
BNBSmartChain
Extends the generic `EVM` controller to provide BSC-specific implementations of the API methods for gas estimation and gas fee retrieval.
Decorators
@Route('api/v1')
Defines the base route path for all endpoints in this controller as/api/v1.@Tags('v1')
Tags this controller as version 1 for API documentation grouping.
Methods
estimateGas(body: EstimateGasBody): Promise<GasEstimate>
Estimates the gas required to execute a provided transaction on BSC.
HTTP Method: POST
Route: /api/v1/gas/estimate
Parameters:
body(EstimateGasBody) - Object containing transaction details:data: string — hex-encoded transaction data payloadfrom: string — sender addressto: string — receiver addressvalue: string — amount of native token to transfer (in wei)
Returns: Promise resolving to a
GasEstimateobject containing:gasLimit: string — estimated gas units required for the transaction.
Responses:
422 Validation Error — invalid input parameters.
500 Internal Server Error— server-side failure.
Example Usage:
const estimate = await bnBSCController.estimateGas({
data: '0x',
from: '0x0000000000000000000000000000000000000000',
to: '0xC480394241c76F3993ec5D121ce4F198f7844443',
value: '1337',
});
console.log(estimate.gasLimit); // e.g. '21000'
Implementation Detail:
Delegates the gas estimation logic to the sharedservice.estimateGas()method, which interacts with the blockchain via RPC and Blockbook.
getGasFees(): Promise<GasFees>
Fetches the current recommended gas fee tiers (slow, average, fast) for sending transactions on BSC.
HTTP Method: GET
Route:
/api/v1/gas/feesReturns: Promise resolving to a
GasFeesobject with the following structure:baseFeePerGas: string — base fee in wei (EIP-1559 base fee)slow: object — slow transaction gas fees withgasPrice,maxFeePerGas, andmaxPriorityFeePerGas(all strings in wei)average: object — average transaction gas fees (same structure as slow)fast: object — fast transaction gas fees (same structure as slow)
Responses:
500 Internal Server Error— server-side failure.
Example Usage:
const fees = await bnBSCController.getGasFees();
console.log(fees.fast.gasPrice); // e.g. '5187055981'
Implementation Detail:
Callsservice.getGasFees()which utilizes theGasOracleto retrieve dynamic gas fee data from on-chain sources or external APIs.
Important Implementation Details
Environment Validation:
On module load, the file ensures all critical environment variables are set (ETHERSCAN_API_KEY,INDEXER_URL,INDEXER_WS_URL,NETWORK,RPC_URL). Missing variables cause startup errors to prevent misconfiguration.Client Initialization:
Uses
viem'screatePublicClientconfigured for BSC (bscchain) with custom RPC URL and optional API key headers for authenticated requests.Instantiates a
Blockbookclient for blockchain indexing and websocket streaming.Creates a
GasOracleto fetch gas fee recommendations.Constructs a
Serviceobject with all dependencies injected for handling core blockchain operations.
Service Binding:
The sharedserviceinstance is assigned to the staticEVM.serviceproperty, making it accessible to the base EVM controller methods inherited byBNBSmartChain.API Layer:
Usestsoadecorators for route definitions, request/response validation, and OpenAPI documentation generation.
Interactions with Other System Parts
Common API Modules:
Imports base API interfaces (BaseAPI,API) and models (EstimateGasBody,GasEstimate,GasFees) from a centralized common API package, ensuring consistent data contracts.EVM Common Controller and Service:
Extends theEVMcontroller base class and leverages theServiceclass from the shared EVM module, promoting code reuse across different EVM-compatible blockchains.Blockbook & GasOracle:
Relies on Blockbook for blockchain data indexing and websocket updates, and GasOracle for accurate gas pricing, abstracting complexities of interacting with underlying blockchain nodes.RPC Client (
viem):
Usesviemto communicate with the BSC RPC node for blockchain state queries and transaction simulations.
Visual Diagram
classDiagram
class BNBSmartChain {
+estimateGas(body: EstimateGasBody): Promise~GasEstimate~
+getGasFees(): Promise~GasFees~
}
class EVM {
<<abstract>>
+service: Service
}
BNBSmartChain --|> EVM
class Service {
-blockbook: Blockbook
-gasOracle: GasOracle
-client: PublicClient
-logger: Logger
+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
}
BNBSmartChain ..> Service : uses
Service *-- Blockbook : composes
Service *-- GasOracle : composes
Summary
The [controller.ts](/projects/291/68853) file provides a robust, well-structured REST API controller tailored for Binance Smart Chain operations within an EVM-compatible framework. It offers essential transaction gas utilities—estimation and fee retrieval—by composing several services and clients that abstract blockchain interactions. With strong type safety, validation, and documentation via `tsoa`, it forms an integral part of the modular blockchain API system.