zrx.ts
Overview
`zrx.ts` implements a proxy client class `Zrx` for the 0x API, a decentralized exchange liquidity aggregator API. This file provides a middleware-compatible handler designed to forward incoming HTTP requests from the application's Express server to the appropriate 0x API endpoint, transparently relaying responses back to the client.
The primary purpose of this proxy is to:
Dynamically route requests to different 0x sub-APIs depending on the blockchain network specified in the request path (e.g., Ethereum, Polygon, Arbitrum).
Attach the required 0x API key for authentication.
Forward response headers and status codes to preserve API semantics.
Handle and propagate errors gracefully.
Support both legacy and newer API versions with tailored header management.
This proxy allows clients to access multi-chain 0x liquidity and swap quote services through a unified internal endpoint, abstracting complexities of multiple base URLs and API versions.
Class: Zrx
Description
The `Zrx` class encapsulates the logic to forward HTTP GET requests to the 0x API, handling:
Construction of target URLs based on the request path and blockchain network.
Injection of the 0x API key header.
Conditional addition of version headers for backward compatibility.
Comprehensive error handling.
Streaming of response headers and body back to the requester.
This class is intended to be instantiated once and its [.handler()](/projects/291/69247) method used as an Express route handler.
Properties
Property | Type | Description |
|---|---|---|
`axiosInstance` | `Axios` | An Axios HTTP client instance configured with the 0x API key header for authentication. |
Constructor
constructor()
Initializes an Axios instance with the
0x-api-keyheader set to the environment variableZRX_API_KEY.Throws an error immediately if the required environment variable is not set, preventing runtime misconfiguration.
Methods
handler(req: Request, res: Response): Promise<void>
Purpose:
Handles incoming HTTP requests, maps them to the appropriate 0x API endpoint URL, forwards the request, and streams the response back.Parameters:
req: Request— The Express request object representing the incoming client request.res: Response— The Express response object used to send data back to the client.
Returns:
Promise<void>— Asynchronous operation that completes once the response is sent.
Functionality details:
URL Parsing and Path Extraction:
Parses the incoming request URL, stripping the/api/v1/zrx/prefix to isolate the relevant 0x API path.Dynamic Base URL Resolution:
If the path contains'v1', the first segment after/api/v1/zrx/is interpreted as the blockchain network (e.g.,ethereum,polygon). The proxy selects the matching 0x subdomain API URL accordingly:arbitrum→https://arbitrum.api.0x.org/avalanche→https://avalanche.api.0x.org/base→https://base.api.0x.org/bnbsmartchain→https://bsc.api.0x.org/ethereum→https://api.0x.org/optimism→https://optimism.api.0x.org/polygon→https://polygon.api.0x.org/
If the chain is unrecognized, the request is rejected with a 404.
If the path does not include `'v1'`, the request targets the main 0x API (`https://api.0x.org/`).
Header Management:
For API paths not including
'v1', adds the header'0x-version': 'v2'to specify the API version explicitly.For
'v1'paths, no additional headers are set beyond the API key.
Request Forwarding:
Uses the Axios instance to execute a GET request to the constructed URL with the appropriate headers.Response Handling:
Copies all headers from the 0x API response back to the Express response. Sends the status code and data payload as received.Error Handling:
Detects Axios errors and attempts to relay the external API's response status and data.
Falls back to sending generic 500 Internal Server Error with relevant messages on unexpected errors.
Example Usage:
import express from 'express';
import { Zrx } from './zrx';
const app = express();
const zrxProxy = new Zrx();
app.get('/api/v1/zrx/*', zrxProxy.handler.bind(zrxProxy));
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example, all requests to `/api/v1/zrx/*` are proxied through the `Zrx` class handler.
Important Implementation Details
Environment Variable Dependency:
The class requiresZRX_API_KEYto be set in the environment. The constructor throws an error if this is missing, enforcing secure configuration.Dynamic URL Routing Based on Blockchain Network:
The proxy intelligently routes requests to distinct 0x API subdomains based on thechainsegment in the URL path, supporting multi-chain operations transparently.Conditional Header Injection for API Versioning:
To maintain compatibility with different API versions, the proxy conditionally adds the'0x-version': 'v2'header only for paths not containing'v1'.Full Header Forwarding:
The proxy copies all headers received from the 0x API to the client response. This preserves metadata such as caching, rate limiting, and content-type, providing clients with full API semantics.Robust Error Propagation:
Using Axios error detection, the handler ensures that error status codes and messages from 0x APIs are forwarded to the client, improving debuggability and transparency.Use of URL API for Parsing:
The proxy uses the standardURLclass to safely parse and manipulate the incoming request URL, avoiding manual string operations.
Interaction With Other Parts of the System
Express Server Integration:
TheZrxclass is used as a route handler in the Express server setup (likelyapp.ts), receiving requests matching/api/v1/zrx/*.Part of External API Proxy Suite:
It complements other proxy clients in the system such asCoinGeckoandZerion, each handling their respective external APIs. This modular approach centralizes external API interactions.Unified API Layer:
The proxy abstracts multiple 0x sub-APIs behind a single endpoint, simplifying client-side integration and enhancing maintainability.API Key Management:
The API key is injected automatically by the proxy, preventing key exposure on the client side and centralizing security controls.
Mermaid Class Diagram
classDiagram
class Zrx {
-axiosInstance: Axios
+constructor()
+handler(req: Request, res: Response): Promise<void>
}
Summary
The `zrx.ts` file defines a single class `Zrx` that acts as an authenticated, multi-chain proxy client for the 0x API. It dynamically routes requests based on blockchain networks, forwards headers and responses transparently, and integrates seamlessly with the Express-based Proxy API Service. This design enables secure, version-aware, and simplified access to 0x liquidity and swap services across multiple chains.
If you have any questions or need further examples on using the `Zrx` proxy, feel free to ask!