This Node.js script acts as a proxy for Ethereum JSON-RPC requests. It checks the health of multiple Ethereum RPC endpoints and forwards requests to the first available and healthy node.
- Health Checks: Periodically checks the status of configured RPC URLs, verifying uptime, sync status, and recent block timestamp.
- Automatic Failover: Forwards requests to the first available and healthy RPC node.
- Minimal Dependencies: Uses only built-in Node.js modules (
http,https,url). - Environment Configuration: Reads RPC URLs from the
RPC_URLSenvironment variable. - Error Handling: Includes robust error handling for RPC calls, request forwarding, and JSON parsing.
- Logging: Provides informative console logs about RPC status and errors.
- Make sure you have Node.js installed.
- Save the script (e.g., as
rpc-proxy.js).
-
Set the
RPC_URLSenvironment variable, listing your Ethereum RPC URLs separated by commas:export RPC_URLS="[https://mainnet.infura.io/v3/](https://mainnet.infura.io/v3/)<YOUR_INFURA_PROJECT_ID>,[https://another.rpc.url](https://another.rpc.url)"
Replace
<YOUR_INFURA_PROJECT_ID>andhttps://another.rpc.urlwith your actual RPC endpoint URLs. You can use Infura, Alchemy, or other providers. -
Run the script:
node rpc-proxy.js
-
The proxy will start listening on port 3000 by default. You can change this using the
PORTenvironment variable:export PORT=8080 node rpc-proxy.js -
Send your JSON-RPC requests to the proxy server:
curl -X POST -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1}' http://localhost:3000
RPC_URLS: A comma-separated list of Ethereum RPC URLs. This is a required environment variable.PORT: The port the proxy server listens on (optional, defaults to 3000).
The proxy performs the following checks for each RPC URL:
- Uptime: Attempts to connect to the RPC endpoint.
- Sync Status: Calls the
eth_syncingmethod. A response offalseindicates the node is not syncing. - Block Timestamp: Calls the
eth_getBlockByNumbermethod withlatestand checks if the block's timestamp is within the last 5 minutes. This helps ensure the node's clock is accurate.
The proxy handles the following errors:
- Invalid
RPC_URLSenvironment variable. - Errors during RPC health checks.
- Errors forwarding requests to the RPC node.
- JSON parsing errors.
The proxy logs the following information to the console:
- Proxy server startup message.
- RPC health check results.
- Errors encountered.
Contributions are welcome! Please open an issue or submit a pull request.
MIT