Setup

import {
  Nexus,
  NodeProvider,
  CHAIN,
  NexusServerInstance,
} from "@whatsgood/nexus";

let nexus: NexusServerInstance;

function createNexus(env: Record<string, string>) {
  // Step 1: Initialize node providers
  const llamaRpcNodeProvider = new NodeProvider({
    name: "llama-rpc",
    chain: CHAIN.ETHEREUM_MAINNET,
    url: "https://eth.llamarpc.com",
  });

  const tenderlyNodeProvider = new NodeProvider({
    name: "tenderly",
    chain: CHAIN.ETHEREUM_MAINNET,
    url: "https://gateway.tenderly.co/public/mainnet",
  });

  // Step 2: Create a Nexus instance
  const nexus = Nexus.create({
    nodeProviders: [llamaRpcNodeProvider, tenderlyNodeProvider],
    log: { level: "debug", colorize: false },
    port: 4000,
    relay: {
      order: "random",
    },
    env,
  });

  // Step 3: Optionally define event handlers
  nexus.on("rpcResponseSuccess", (response, ctx) => {
    nexus.logger.debug(
      {
        response: response.body(),
        chain: ctx.chain,
      },
      "rpc response success event captured"
    );
  });

  return nexus;
}

// Step 4: Set the fetch handler
export default {
  fetch: (request: Request, env: Record<string, string>) => {
    if (!nexus) {
      nexus = createNexus(env);
    }
    return nexus(request);
  },
};

Usage

curl -X POST http://localhost:4000/1 \
     -H "Content-Type: application/json" \
     -d '{
           "jsonrpc": "2.0", 
           "method": "eth_blockNumber", 
           "params": [], 
           "id": 1
         }'