Skip to content

NodeBridge-Africa/rpc_gateway

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

39 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

NodeBridge RPC Gateway

Tests TypeScript Node.js MongoDB License

A production-ready, multi-tenant RPC gateway providing controlled access to your private Ethereum Sepolia node infrastructure. Similar to Alchemy or Infura, but for your own nodes with enterprise-grade monitoring and security.

πŸš€ Features

πŸ” Multi-Tenant Security

  • JWT-based authentication system
  • Unique API keys per user
  • Role-based access control
  • Input validation & sanitization

⚑ Advanced Rate Limiting

  • Token bucket algorithm implementation
  • Per-user RPS and daily limits
  • Automatic rate limit recovery
  • Real-time usage tracking

πŸ“Š Enterprise Monitoring

  • Prometheus metrics integration
  • Real-time Ethereum node health monitoring
  • Request latency tracking
  • Error rate monitoring
  • Usage analytics

⛓️ Flexible Multi-Chain Support

  • Configure and connect to multiple Ethereum-compatible chains (e.g., Ethereum Mainnet, Sepolia, custom chains) by defining environment variables with a unique prefix for each chain.
  • For example, ETHEREUM_EXECUTION_RPC_URL and SEPOLIA_EXECUTION_RPC_URL define two distinct chains.
  • The prefix (e.g., ETHEREUM, SEPOLIA), converted to lowercase, is used as the chain identifier in API paths (e.g., /ethereum/exec/..., /sepolia/cons/...).
  • Supports both Execution Layer (JSON-RPC) and Consensus Layer (Beacon API) for each configured chain, along with optional chain-specific Prometheus URLs.

πŸ›‘οΈ Production Security

  • Helmet.js security headers
  • CORS configuration
  • Request logging
  • Error handling without information leakage

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Client    │───▢│  NodeBridge      │───▢│  Ethereum Node     β”‚
β”‚  (Web3.js)  β”‚    β”‚  RPC Gateway     β”‚    β”‚  (Execution +      β”‚
β”‚  (Ethers)   β”‚    β”‚                  β”‚    β”‚   Consensus)       β”‚
β”‚   (curl)    β”‚    β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚    β”‚                    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚  β”‚ Auth        β”‚ β”‚    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚  β”‚ Rate Limit  β”‚ β”‚              β”‚
                   β”‚  β”‚ Metrics     β”‚ β”‚              β”‚
                   β”‚  β”‚ Validation  β”‚ β”‚    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                   β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚    β”‚  Prometheus         β”‚
                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚  Metrics Server     β”‚
                            β”‚              β”‚  (Optional)         β”‚
                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚   MongoDB        β”‚
                   β”‚   (Users & Usage)β”‚
                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Quick Start

Prerequisites

  • Node.js 18+
  • MongoDB 6.0+
  • Ethereum Sepolia Node (execution + consensus layers)
  • Prometheus (optional, for advanced monitoring)

1. Installation

# Clone the repository
git clone https://github.com/NodeBridge-Africa/rpc_gateway.git
cd rpc_gateway

# Install dependencies
yarn install

# Build the project
yarn build

2. Environment Configuration

# Copy environment template
cp .env.example .env

Update .env with your configuration. To configure chains, use environment variables prefixed with the chain's name (e.g., ETHEREUM_, SEPOLIA_). The supported suffixes are _EXECUTION_RPC_URL, _CONSENSUS_API_URL, and _PROMETHEUS_URL (optional).

# Server Configuration
PORT=8888
NODE_ENV=production

# Database
MONGO_URI=mongodb://localhost:27017/nodebridge

# Security
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# Rate Limiting Defaults
DEFAULT_MAX_RPS=20
DEFAULT_DAILY_REQUESTS=10000

# --- Dynamic Multi-Chain Configuration ---
# Define each chain by prefixing variables with its name (e.g., ETHEREUM, SEPOLIA).
# The prefix (lowercase) will be used as the chain identifier in API paths.

# Example: Ethereum Mainnet
ETHEREUM_EXECUTION_RPC_URL=http://localhost:8545
ETHEREUM_CONSENSUS_API_URL=http://localhost:5052
# ETHEREUM_PROMETHEUS_URL=http://localhost:9091 # Optional

# Example: Sepolia Testnet (using a public provider)
SEPOLIA_EXECUTION_RPC_URL="https://sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID,https://another-sepolia-node.com/v3/YOUR_OTHER_PROJECT_ID"
SEPOLIA_CONSENSUS_API_URL=https://sepolia-beacon.infura.io/v3/YOUR_INFURA_PROJECT_ID
# SEPOLIA_PROMETHEUS_URL= # Optional

# Example: Holesky Testnet (Execution layer only)
HOLESKY_EXECUTION_RPC_URL=https://rpc.holesky.ethpandaops.io
# HOLESKY_CONSENSUS_API_URL= # Optional

# Add more chains by following the pattern: YOURCHAINNAME_EXECUTION_RPC_URL=...
# Note on RPC URLs: For _EXECUTION_RPC_URL and _CONSENSUS_API_URL, you can provide a single URL
# or a comma-separated list of URLs (e.g., "http://node1:8545,http://node2:8545").
# Providing multiple URLs enables basic round-robin load balancing where a URL is randomly selected for each request.

Refer to src/config/env.example.ts for more detailed examples and explanations.

3. Database Setup

# Start MongoDB
sudo systemctl start mongod

# Initialize database (creates indexes, etc.)
yarn setup

4. Start the Gateway

# Development mode (with hot reload)
yarn dev

# Production mode
yarn start

The gateway will be available at http://localhost:8888

πŸ“š API Documentation

πŸ” Authentication

Register New User

POST /auth/register
Content-Type: application/json

{
  "email": "developer@example.com",
  "password": "SecurePassword123!"
}

Response:

{
  "success": true,
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "apiKey": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "user": {
      "id": "637f4a2e8b12c45678901234",
      "email": "developer@example.com",
      "apiKey": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "maxRps": 20,
      "dailyRequestLimit": 10000,
      "createdAt": "2024-01-01T00:00:00.000Z"
    }
  }
}

User Login

POST /auth/login
Content-Type: application/json

{
  "email": "developer@example.com",
  "password": "SecurePassword123!"
}

Get Account Information

GET /auth/account
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Regenerate API Key

POST /auth/regenerate-api-key
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Get Usage Statistics

GET /auth/usage
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

πŸ“± App Management & API Keys

NodeBridge requires users to create "Apps" to obtain API keys. Each App is tied to a specific blockchain (e.g., Sepolia) and has its own unique API key. This allows for granular control and monitoring of access to different chains. Users are typically limited to a certain number of apps (e.g., 5 per user).

Create New App (and get API Key)

POST /api/v1/apps
Authorization: Bearer <USER_JWT_TOKEN>
Content-Type: application/json

{
  "name": "My First DApp",
  "description": "Optional description for my app.",
  "chainName": "Sepolia",
  "chainId": "11155111"
}

Response (Success 201):

{
  "success": true,
  "message": "App created successfully.",
  "data": {
    "app": {
      "_id": "app_id_here",
      "name": "My First DApp",
      "description": "Optional description for my app.",
      "userId": "user_id_here",
      "apiKey": "generated_api_key_here",
      "chainName": "Sepolia",
      "chainId": "11155111",
      "maxRps": 20,
      "dailyRequestsLimit": 10000,
      "requests": 0,
      "dailyRequests": 0,
      "lastResetDate": "2024-03-10T10:00:00.000Z",
      "isActive": true,
      "createdAt": "2024-03-10T10:00:00.000Z",
      "updatedAt": "2024-03-10T10:00:00.000Z"
    }
  }
}

List User's Apps

GET /api/v1/apps
Authorization: Bearer <USER_JWT_TOKEN>

Response (Success 200):

{
  "success": true,
  "message": "User applications retrieved successfully.",
  "data": {
    "apps": [
      {
        "_id": "app_id_1",
        "name": "My First DApp",
        "userId": "user_id_here",
        "chainName": "Sepolia",
        "chainId": "11155111",
        "maxRps": 20,
        "dailyRequestsLimit": 10000,
        "isActive": true,
        "createdAt": "2024-03-10T10:00:00.000Z",
        "updatedAt": "2024-03-10T10:00:00.000Z"
        // Note: apiKey is NOT returned in the list view
      },
      {
        "_id": "app_id_2",
        "name": "Another App",
        "userId": "user_id_here",
        "chainName": "Goerli",
        "chainId": "5",
        "maxRps": 25,
        "dailyRequestsLimit": 15000,
        "isActive": true,
        "createdAt": "2024-03-09T00:00:00.000Z",
        "updatedAt": "2024-03-09T00:00:00.000Z"
      }
    ]
  }
}

⚑ RPC Endpoints & API Key Usage

Execution Layer (JSON-RPC)

Access standard Ethereum JSON-RPC methods:

The :chain parameter in the URL (e.g., ethereum, sepolia) corresponds to the lowercase version of the prefix used when defining the chain in your environment variables (e.g., ETHEREUM_EXECUTION_RPC_URL means the path /ethereum/exec/...).

POST /:chain/exec/<YOUR_API_KEY>
Content-Type: application/json

{
  "jsonrpc": "2.0",
  "method": "eth_blockNumber",
  "params": [],
  "id": 1
}

Supported Methods:

  • eth_blockNumber
  • eth_getBalance
  • eth_getBlockByNumber
  • eth_getTransactionReceipt
  • eth_sendRawTransaction
  • eth_call
  • All standard Ethereum JSON-RPC methods

API Key Usage Notes:

  • Each API key obtained from creating an "App" is specific to the chainName (e.g., "Sepolia") chosen during that app's creation.
  • Requests made with an API key for "Sepolia" will be routed to the Sepolia node infrastructure.
  • Each API key is subject to its own rate limits:
    • maxRps: Maximum requests per second.
    • dailyRequestsLimit: Total requests allowed per day for that specific key.
  • These limits are initially set by system defaults but can be adjusted by an administrator per API key.

Consensus Layer (Beacon API)

Access Ethereum consensus layer data:

The :chain parameter in the URL (e.g., ethereum, sepolia) corresponds to the lowercase version of the prefix used when defining the chain in your environment variables (e.g., SEPOLIA_CONSENSUS_API_URL means the path /sepolia/cons/...).

GET /:chain/cons/<YOUR_API_KEY>/eth/v1/beacon/headers
GET /:chain/cons/<YOUR_API_KEY>/eth/v1/beacon/blocks/head
GET /:chain/cons/<YOUR_API_KEY>/eth/v1/node/syncing

πŸ“Š Monitoring Endpoints

Health Check

GET /health

Response:

{
  "status": "healthy",
  "timestamp": "2024-01-01T12:00:00.000Z",
  "version": "1.0.0",
  "environment": "production"
}

Prometheus Metrics

GET /metrics

Returns Prometheus-formatted metrics including:

  • rpc_gateway_requests_total
  • rpc_gateway_request_duration_seconds
  • ethereum_execution_syncing
  • ethereum_consensus_head_slot
  • And many more...

Admin: Node Health

This endpoint now requires a chain name parameter.

GET /admin/node-health/:chain

Example: GET /admin/node-health/sepolia

Response:

{
  "timestamp": "2024-01-01T12:00:00.000Z",
  "execution": {
    "status": "healthy",
    "syncing": false,
    "endpoint": "http://localhost:8545"
  },
  "consensus": {
    "status": "healthy",
    "syncing": false,
    "head_slot": "7685000",
    "endpoint": "http://localhost:5052"
  },
  "overall": "healthy"
}

Admin: Node Metrics

This endpoint now requires a chain name parameter.

GET /admin/node-metrics/:chain

Example: GET /admin/node-metrics/sepolia

βš™οΈ Additional Admin Management Endpoints

The following endpoints require administrator privileges (Admin JWT Token).

Chain Management

  • List All Supported Chains:

    GET /api/v1/admin/chains
    Authorization: Bearer <ADMIN_JWT_TOKEN>
  • Add a New Chain:

    POST /api/v1/admin/chains
    Authorization: Bearer <ADMIN_JWT_TOKEN>
    Content-Type: application/json
    
    {
      "name": "ChainName",
      "chainId": "123",
      "isEnabled": true,
      "adminNotes": "Optional notes about this chain"
    }
  • Update an Existing Chain:

    PUT /api/v1/admin/chains/:chainIdToUpdate
    Authorization: Bearer <ADMIN_JWT_TOKEN>
    Content-Type: application/json
    
    {
      "name": "NewChainName",
      "newChainId": "124",
      "isEnabled": false,
      "adminNotes": "Updated notes"
    }

    Note: All fields in the request body are optional. Provide only the fields you wish to update. :chainIdToUpdate refers to the current chainId of the chain to be modified.

  • Delete a Chain:

    DELETE /api/v1/admin/chains/:chainIdToDelete
    Authorization: Bearer <ADMIN_JWT_TOKEN>

    Note: :chainIdToDelete refers to the chainId of the chain to be deleted.

Default App Settings Management

These settings apply to newly created apps.

  • Get Default App Settings:

    GET /api/v1/admin/settings/app-defaults
    Authorization: Bearer <ADMIN_JWT_TOKEN>

    Response includes defaultMaxRps and defaultDailyRequestsLimit.

  • Update Default App Settings:

    PUT /api/v1/admin/settings/app-defaults
    Authorization: Bearer <ADMIN_JWT_TOKEN>
    Content-Type: application/json
    
    {
      "defaultMaxRps": 50,
      "defaultDailyRequestsLimit": 20000
    }

App-Specific Limit Management

Administrators can override the default limits for individual apps.

  • Update Limits for a Specific App:
    PUT /api/v1/admin/apps/:appId/limits
    Authorization: Bearer <ADMIN_JWT_TOKEN>
    Content-Type: application/json
    
    {
      "maxRps": 100,
      "dailyRequestsLimit": 50000
    }
    Note: maxRps and dailyRequestsLimit are optional in the request. Provide one or both to update.

πŸ’» Usage Examples

Web3.js Integration

const Web3 = require("web3");

// Initialize with your NodeBridge gateway
const web3 = new Web3("http://localhost:8888/ethereum/exec/YOUR-API-KEY");

async function example() {
  // Get latest block number
  const blockNumber = await web3.eth.getBlockNumber();
  console.log("Latest block:", blockNumber);

  // Get account balance
  const balance = await web3.eth.getBalance(
    "0x742d35Cc6634C0532925a3b8D8B8c8B8A8B8B8B8"
  );
  console.log("Balance:", web3.utils.fromWei(balance, "ether"), "ETH");
}

Ethers.js Integration

const { JsonRpcProvider } = require("ethers");

// Initialize provider
const provider = new JsonRpcProvider("http://localhost:8888/ethereum/exec/YOUR-API-KEY");

async function example() {
  // Get network information
  const network = await provider.getNetwork();
  console.log("Network:", network.name, "Chain ID:", network.chainId);

  // Get block information
  const block = await provider.getBlock("latest");
  console.log("Latest block hash:", block.hash);
}

cURL Examples

# Get latest block number
curl -X POST http://localhost:8888/ethereum/exec/YOUR-API-KEY \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'

# Get consensus layer sync status
curl http://localhost:8888/ethereum/cons/YOUR-API-KEY/eth/v1/node/syncing

# Check gateway health
curl http://localhost:8888/health

πŸ§ͺ Testing

Test Structure

  • 110 Total Tests across multiple categories
  • Unit Tests: No dependencies, fast execution
  • Integration Tests: Full workflow testing
  • Database Tests: MongoDB operations
  • Metrics Tests: Prometheus metrics validation

Running Tests

# Run all tests
yarn test

# Run only unit tests (no MongoDB required)
yarn jest --selectProjects unit-tests

# Run only database tests
yarn jest --selectProjects database-tests

# Run with coverage report
yarn test:coverage

# Run specific test file
yarn jest tests/auth.test.ts

# Watch mode for development
yarn test:watch

Test Categories

πŸ”§ Unit Tests (No external dependencies)

  • JWT token creation/validation
  • Password hashing (bcrypt)
  • Rate limiting algorithms
  • Utility functions

πŸ”— Integration Tests (Full system)

  • Complete user registration β†’ API usage workflow
  • Rate limiting enforcement
  • Error handling scenarios
  • Performance benchmarks

οΏ½οΏ½ Database Tests (MongoDB required)

  • User model operations
  • Authentication routes
  • Usage tracking
  • Data persistence

πŸ“Š Metrics Tests (Prometheus integration)

  • Custom metrics collection
  • Default Node.js metrics
  • Request tracking
  • Performance measurements

πŸ“Š Monitoring & Analytics

Prometheus Metrics

The gateway exposes comprehensive metrics for monitoring:

Gateway Performance Metrics

  • rpc_gateway_requests_total - Request counts by endpoint/user
  • rpc_gateway_request_duration_seconds - Request latency histograms
  • rpc_gateway_active_connections - Current connections
  • rpc_gateway_rate_limit_hits_total - Rate limiting events

Ethereum Node Health Metrics

  • ethereum_execution_syncing - Execution layer sync status
  • ethereum_consensus_syncing - Consensus layer sync status
  • ethereum_consensus_head_slot - Current consensus head slot
  • ethereum_node_health_status - Overall node health score

System Metrics

  • process_* - Node.js process metrics
  • nodejs_* - Node.js runtime metrics
  • http_* - HTTP server metrics

Grafana Dashboard Setup

Create monitoring dashboards with:

{
  "dashboard": {
    "title": "NodeBridge RPC Gateway",
    "panels": [
      {
        "title": "Request Rate",
        "targets": ["rate(rpc_gateway_requests_total[5m])"]
      },
      {
        "title": "Request Latency",
        "targets": [
          "histogram_quantile(0.95, rpc_gateway_request_duration_seconds_bucket)"
        ]
      },
      {
        "title": "Node Sync Status",
        "targets": ["ethereum_execution_syncing", "ethereum_consensus_syncing"]
      }
    ]
  }
}

πŸš€ Production Deployment

Environment Preparation

# 1. Install Node.js 18+
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# 2. Install MongoDB
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
sudo apt-get install -y mongodb-org

# 3. Install PM2 for process management
npm install -g pm2

Production Configuration

# Production .env
NODE_ENV=production
PORT=8888

# Use production MongoDB cluster
MONGO_URI=mongodb://mongo1,mongo2,mongo3/nodebridge?replicaSet=rs0

# Strong JWT secret (generate with: openssl rand -hex 64)
JWT_SECRET=a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456

# Production node endpoints
EXECUTION_RPC_URL=http://internal-eth-node:8545
CONSENSUS_API_URL=http://internal-beacon-node:5052

# Monitoring
PROMETHEUS_URL=http://prometheus:9090

# Adjusted limits for production
DEFAULT_MAX_RPS=100
DEFAULT_DAILY_REQUESTS=1000000

Process Management

# Build for production
yarn build

# Start with PM2
pm2 start ecosystem.config.js

# Monitor
pm2 status
pm2 logs nodebridge-gateway
pm2 monit

Docker Deployment

# Dockerfile
FROM node:18-alpine

WORKDIR /app
COPY package*.json ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn build

EXPOSE 8888
CMD ["yarn", "start"]
# Build and run
docker build -t nodebridge-gateway .
docker run -d \
  -p 8888:8888 \
  --env-file .env \
  --name nodebridge \
  nodebridge-gateway

Reverse Proxy (Nginx)

server {
    listen 80;
    server_name rpc.yourdomain.com;

    location / {
        proxy_pass http://localhost:8888;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Rate limiting
        limit_req zone=api burst=100 nodelay;
    }
}

πŸ›‘οΈ Security Best Practices

1. Environment Security

# Never commit .env files
echo ".env*" >> .gitignore

# Use environment-specific secrets
export JWT_SECRET="$(openssl rand -hex 64)"

2. Network Security

  • Run behind reverse proxy (Nginx/Apache)
  • Use HTTPS/TLS in production
  • Implement IP whitelisting if needed
  • Configure firewall rules

3. Database Security

  • Enable MongoDB authentication
  • Use connection encryption
  • Regular backups
  • User privilege management

4. Application Security

  • Input validation on all endpoints
  • Rate limiting enforcement
  • Audit logging
  • Regular dependency updates

πŸ”§ Development Guide

Project Structure

rpc_gateway/
β”œβ”€β”€ src/                          # Source code
β”‚   β”œβ”€β”€ config/                   # Configuration files
β”‚   β”œβ”€β”€ middlewares/              # Express middlewares
β”‚   β”‚   β”œβ”€β”€ auth.middleware.ts    # JWT authentication
β”‚   β”‚   └── rateLimit.middleware.ts # Rate limiting
β”‚   β”œβ”€β”€ models/                   # Database models
β”‚   β”‚   └── user.model.ts         # User schema & methods
β”‚   β”œβ”€β”€ routes/                   # API route handlers
β”‚   β”‚   β”œβ”€β”€ auth.routes.ts        # Authentication endpoints
β”‚   β”‚   └── proxy.routes.ts       # RPC proxy endpoints
β”‚   β”œβ”€β”€ services/                 # Business logic
β”‚   β”‚   └── metrics.service.ts    # Prometheus metrics
β”‚   └── server.ts                 # Application entry point
β”œβ”€β”€ tests/                        # Test suite
β”‚   β”œβ”€β”€ auth.test.ts             # Authentication tests
β”‚   β”œβ”€β”€ integration.test.ts      # Full workflow tests
β”‚   β”œβ”€β”€ metrics.simple.test.ts   # Metrics collection tests
β”‚   β”œβ”€β”€ middleware.test.ts       # Middleware tests
β”‚   β”œβ”€β”€ proxy.test.ts           # RPC proxy tests
β”‚   β”œβ”€β”€ unit.test.ts            # Unit tests
β”‚   β”œβ”€β”€ user.model.test.ts      # Database model tests
β”‚   └── helpers/                # Test utilities
β”œβ”€β”€ docs/                       # Additional documentation
β”œβ”€β”€ package.json               # Dependencies & scripts
β”œβ”€β”€ tsconfig.json             # TypeScript configuration
β”œβ”€β”€ jest.config.js            # Test configuration
└── README.md                 # This file

Environment Variables

Variable Description Default Required
PORT Server port 8888 No
NODE_ENV Environment development No
MONGO_URI MongoDB connection mongodb://localhost:27017/nodebridge Yes
JWT_SECRET JWT signing secret - Yes
CHAINNAME_EXECUTION_RPC_URL RPC URL for 'CHAINNAME' execution layer. Replace CHAINNAME with chain ID (e.g., ETHEREUM). - Yes (for each configured chain)
CHAINNAME_CONSENSUS_API_URL Beacon API URL for 'CHAINNAME' consensus layer. Replace CHAINNAME as above. - No (Optional, per chain)
CHAINNAME_PROMETHEUS_URL Prometheus URL for 'CHAINNAME' specific metrics. Replace CHAINNAME as above. - No (Optional, per chain)
DEFAULT_MAX_RPS Rate limit (requests/second) 20 No
DEFAULT_DAILY_REQUESTS Daily request limit 10000 No
ENABLE_METRICS Enable gateway's Prometheus metrics endpoint (/metrics) true No

Development Workflow

  1. Setup Development Environment

    git clone <repository>
    cd rpc_gateway
    yarn install
    cp .env.example .env
    # Edit .env with your settings
  2. Run in Development Mode

    yarn dev  # Starts with hot reload
  3. Run Tests During Development

    yarn test:watch  # Continuous testing
  4. Before Committing

    yarn lint        # Check code style
    yarn test        # Run full test suite
    yarn build       # Verify build

🀝 Contributing

We welcome contributions! Please read our contribution guidelines below.

πŸš€ Getting Started

  1. Fork the Repository

    # Click "Fork" on GitHub, then clone your fork
    git clone https://github.com/YOUR-USERNAME/rpc_gateway.git
    cd rpc_gateway
  2. Set Up Development Environment

    # Install dependencies
    yarn install
    
    # Copy environment file
    cp .env.example .env
    # Edit .env with your local settings
    
    # Start MongoDB (if running locally)
    sudo systemctl start mongod
    
    # Run tests to ensure everything works
    yarn test
  3. Create Feature Branch

    git checkout -b feature/your-feature-name
    # or
    git checkout -b fix/issue-description

πŸ“ Development Guidelines

Code Style

We use TypeScript with strict typing and ESLint for code quality:

# Check code style
yarn lint

# Auto-fix style issues
yarn lint:fix

# Type checking
yarn type-check

Style Guidelines:

  • Use TypeScript strict mode
  • Prefer const over let
  • Use meaningful variable names
  • Add JSDoc comments for public functions
  • Follow existing naming conventions

Testing Requirements

All contributions must include appropriate tests:

# Run all tests
yarn test

# Run tests in watch mode during development
yarn test:watch

# Check test coverage
yarn test:coverage

Testing Guidelines:

  • Unit tests for utility functions and pure logic
  • Integration tests for API endpoints
  • Database tests for model operations
  • Maintain >90% test coverage
  • Mock external dependencies appropriately

Commit Convention

We follow Conventional Commits:

# Feature commits
git commit -m "feat: add consensus layer health monitoring"

# Bug fixes
git commit -m "fix: resolve rate limiting edge case"

# Documentation
git commit -m "docs: update API documentation"

# Tests
git commit -m "test: add integration tests for auth flow"

# Refactoring
git commit -m "refactor: optimize metrics collection"

πŸ› Bug Reports

When reporting bugs, please include:

  1. Clear Description: What happened vs. what you expected
  2. Reproduction Steps: Detailed steps to reproduce the issue
  3. Environment Info: OS, Node.js version, MongoDB version
  4. Error Logs: Complete error messages and stack traces
  5. Configuration: Relevant .env settings (redacted secrets)

Template:

## Bug Description

Brief description of the issue

## Steps to Reproduce

1. Step one
2. Step two
3. Step three

## Expected Behavior

What should happen

## Actual Behavior

What actually happens

## Environment

- OS: Ubuntu 22.04
- Node.js: v18.17.0
- MongoDB: v6.0.8
- Gateway Version: v1.0.0

## Error Logs

Error logs here


## Configuration
```env
# Redacted .env content

### πŸ’‘ Feature Requests

For new features, please:

1. **Check Existing Issues**: Avoid duplicates
2. **Describe Use Case**: Why is this feature needed?
3. **Propose Solution**: How should it work?
4. **Consider Alternatives**: Other ways to solve the problem?

**Template:**
```markdown
## Feature Request

### Problem/Use Case
Describe the problem this feature would solve

### Proposed Solution
How should this feature work?

### Alternatives Considered
Other approaches you've considered

### Additional Context
Any other relevant information

πŸ”§ Development Areas

We welcome contributions in these areas:

πŸ” Security & Authentication

  • OAuth 2.0 / OpenID Connect integration
  • API key rotation mechanisms
  • Advanced rate limiting strategies
  • Audit logging improvements

πŸ“Š Monitoring & Analytics

  • Additional Prometheus metrics
  • Grafana dashboard templates
  • Alerting rule definitions
  • Performance optimization

🌐 Network & Protocols

  • WebSocket support
  • Additional blockchain networks
  • Protocol optimizations
  • Connection pooling

πŸ§ͺ Testing & Quality

  • Performance benchmarks
  • Load testing scenarios
  • Security testing
  • Documentation improvements

πŸš€ DevOps & Deployment

  • Docker improvements
  • Kubernetes manifests
  • CI/CD pipeline enhancements
  • Infrastructure as Code

πŸ“‹ Pull Request Process

  1. Ensure Tests Pass

    yarn test          # All tests must pass
    yarn lint          # No linting errors
    yarn build         # Must build successfully
  2. Update Documentation

    • Update README.md if adding features
    • Add API documentation
    • Include inline code comments
    • Update changelog if applicable
  3. Create Quality PR

    • Clear title and description
    • Reference related issues
    • Include test evidence
    • Add screenshots for UI changes
  4. Review Process

    • Automated CI checks must pass
    • Code review by maintainers
    • Testing in development environment
    • Final approval and merge

πŸ“ž Getting Help

  • Questions: Open a GitHub Discussion
  • Bug Reports: Create a GitHub Issue
  • Security Issues: Email security@yourdomain.com
  • Feature Ideas: Start with a GitHub Discussion

πŸ† Recognition

Contributors will be:

  • Listed in CONTRIBUTORS.md
  • Mentioned in release notes
  • Credited in documentation
  • Invited to maintainer discussions

πŸ“– Additional Resources

πŸ“š Documentation

πŸ› οΈ Tools & Libraries

πŸ”— Related Projects


πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

MIT License Summary

  • βœ… Commercial use allowed
  • βœ… Modification allowed
  • βœ… Distribution allowed
  • βœ… Private use allowed
  • ❗ Liability and warranty limitations apply

πŸ™ Acknowledgments

  • Ethereum Foundation for the protocol specifications
  • MongoDB Team for the excellent database platform
  • Prometheus Community for monitoring standards
  • Open Source Contributors who make projects like this possible

⭐ Star this repository if you find it useful!

Report Bug β€’ Request Feature β€’ Documentation β€’ Contribute

Made with ❀️ by Kc Pele, for Nodebridge

About

No description, website, or topics provided.

Resources

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages