controller.ts
Overview
`controller.ts` defines the **Polygon** API controller, which extends a generic Ethereum Virtual Machine (EVM) controller to provide Polygon-specific blockchain interaction capabilities. It primarily exposes RESTful endpoints to:
Estimate the gas cost of a Polygon transaction.
Retrieve current recommended gas fees for the Polygon network.
This controller acts as a bridge between HTTP API requests and underlying services that interact with Polygon blockchain nodes and data providers. It leverages several external and internal libraries for blockchain communication, logging, and gas fee estimation.
The file handles environment variable validation, initializes clients and services, and configures the Polygon controller routes and methods with the `tsoa` decorators for automated API documentation and validation.
Classes and Methods
Class: Polygon
Extends:
EVMImplements:
BaseAPI,API
This class encapsulates Polygon-specific blockchain API endpoints by extending the generic EVM controller and injecting Polygon-specific services.
Decorators on Class
@Route('api/v1')
Defines the base route for all endpoints in this controller as/api/v1.@Tags('v1')
Tags this controller's endpoints under version "v1" for API documentation grouping.
Method: estimateGas
@Post('/gas/estimate')
async estimateGas(@Body() body: EstimateGasBody): Promise<GasEstimate>
Estimates the gas cost required to execute a Polygon transaction.
Parameters
body: EstimateGasBody
The transaction data object for which gas estimation is to be performed. Typical properties include:data: Hex string of transaction call data.from: Sender address.to: Recipient address.value: Amount of native token to send.
Returns
Promise<GasEstimate>
A promise resolving to an object containing estimated gas limit as a string.
Usage Example
{
"data": "0x",
"from": "0x0000000000000000000000000000000000000000",
"to": "0x3f758726E31b299Afb85b3D5C8B1fEc9b20b17cA",
"value": "1337"
}
Example response:
{
"gasLimit": "21000"
}
Responses
422 Validation Errorif input validation fails.500 Internal Server Errorfor unexpected errors.
Description
This method delegates the gas estimation request to the injected Polygon `Service` instance, which internally calls blockchain nodes or indexing services to calculate the gas cost.
Method: getGasFees
@Get('/gas/fees')
async getGasFees(): Promise<GasFees>
Retrieves the current recommended gas fees for Polygon transactions.
Returns
Promise<GasFees>
An object containing current gas fee suggestions categorized by transaction speed tiers (slow,average,fast) and base fee information.
Usage Example
Example response:
{
"baseFeePerGas": "112419538445",
"slow": {
"gasPrice": "131449097003",
"maxFeePerGas": "140884315981",
"maxPriorityFeePerGas": "29910015485"
},
"average": {
"gasPrice": "172389951405",
"maxFeePerGas": "160734779396",
"maxPriorityFeePerGas": "49760478900"
},
"fast": {
"gasPrice": "195530342545",
"maxFeePerGas": "280530813993",
"maxPriorityFeePerGas": "169556513497"
}
}
Responses
500 Internal Server Errorfor unexpected errors.
Description
The method calls the `Service` instance's `getGasFees` function, which retrieves gas fee data from the Polygon gas oracle or API providers, factoring in EIP-1559 fee structures (base fee, max fee, priority fee).
Important Implementation Details
Environment Variable Validation:
The file immediately throws errors if mandatory environment variables (e.g., API keys, URLs) are missing. This ensures critical configuration is present before the server starts.External Clients Initialized:
Blockbookclient for indexer access (HTTP + WebSocket).viempublic client configured for Polygon chain with optional RPC API key headers.GasOracleinstance for fetching gas fee data.
Service Layer:
AServiceinstance aggregates these clients and provides high-level blockchain operations like gas estimation and fee retrieval.EVM Controller Integration:
The genericEVMcontroller's staticserviceproperty is assigned this Polygon-specificServiceinstance to unify service usage.API Decorators:
Thetsoadecorators enforce request validation, response typing, and automatically generate OpenAPI-compliant documentation for the Polygon endpoints.
Interaction with Other System Components
Service(fromcommon/api/src/evm/service):
Core business logic for blockchain interaction, wrapping calls toblockbookandgasOracle.EVMController (fromcommon/api/src/evm/controller):
Base controller providing common Ethereum-compatible blockchain API functionality extended here for Polygon.GasOracle:
Provides real-time gas fee data by querying Polygon network nodes or external APIs.Blockbook:
Indexer client managing blockchain data retrieval over HTTP and WebSocket.viemPublic Client:
Low-level JSON-RPC client to interact with Polygon nodes using the RPC URL and API key.Logging:
Uses@shapeshiftoss/loggerfor structured logging within the Polygon API context.
Usage Workflow Summary
A client sends a POST request to
/api/v1/gas/estimatewith transaction details.The
estimateGasmethod validates the request body and callsservice.estimateGas().The service uses
blockbookorviemclients to estimate gas and returns the result.For gas fee retrieval, a client sends a GET request to
/api/v1/gas/fees.The
getGasFeesmethod fetches current gas fee data using thegasOraclevia the service layer.
Visual Diagram
classDiagram
class Polygon {
+estimateGas(body: EstimateGasBody): Promise<GasEstimate>
+getGasFees(): Promise<GasFees>
}
class EVM {
<<abstract>>
+service: Service
}
class Service {
+estimateGas(body: EstimateGasBody): Promise<GasEstimate>
+getGasFees(): Promise<GasFees>
}
class Blockbook {
+httpURL: string
+wsURL: string
+apiKey: string
}
class GasOracle {
+coinstack: string
+client: PublicClient
}
class PublicClient {
+chain: Chain
+transport: Transport
}
Polygon --|> EVM : extends
EVM --> Service : uses (static property)
Service *-- Blockbook : composes
Service *-- GasOracle : composes
Service *-- PublicClient : composes
Summary
`controller.ts` is a focused Polygon blockchain API controller that extends a generic EVM controller by wiring up Polygon-specific clients and services. It exposes endpoints for gas estimation and gas fee retrieval with robust validation, logging, and API documentation through `tsoa`. The file establishes essential configurations and dependencies to ensure smooth interaction with Polygon blockchain nodes and indexing services.
This modular approach allows easy extension to other chains by following the same pattern of inheriting from `EVM` and injecting chain-specific services.