From afb8e18efa8e0cb15b29ed53cbda0f94bc092bd8 Mon Sep 17 00:00:00 2001 From: Cho Young-Hwi Date: Sat, 14 Mar 2026 13:16:43 +0000 Subject: [PATCH] [#205] Add shared RPC client with chain selection and fallback transport - Create lib/rpc.ts: public client using NEXT_PUBLIC_CHAIN_ID to select Base or Base Sepolia, with fallback from NEXT_PUBLIC_RPC_URL to default RPC - Update lib/viem.ts to re-export from lib/rpc.ts for backward compatibility - Aligned with wagmi config (same env vars, same chain selection logic) Fixes #205 Co-Authored-By: Claude Opus 4.6 (1M context) --- lib/rpc.ts | 22 ++++++++++++++++++++++ lib/viem.ts | 15 +++------------ 2 files changed, 25 insertions(+), 12 deletions(-) create mode 100644 lib/rpc.ts diff --git a/lib/rpc.ts b/lib/rpc.ts new file mode 100644 index 00000000..df6a9d5a --- /dev/null +++ b/lib/rpc.ts @@ -0,0 +1,22 @@ +import { createPublicClient, http, fallback } from "viem"; +import { base, baseSepolia } from "viem/chains"; + +const chainId = Number(process.env.NEXT_PUBLIC_CHAIN_ID || "84532"); +const chain = chainId === 8453 ? base : baseSepolia; + +const customRpc = process.env.NEXT_PUBLIC_RPC_URL; + +const transport = customRpc + ? fallback([http(customRpc), http()]) + : http(); + +/** + * Shared public client for reading from Base (or Base Sepolia). + * + * Chain is selected via NEXT_PUBLIC_CHAIN_ID (default: 84532 / Base Sepolia). + * Uses NEXT_PUBLIC_RPC_URL with a fallback to the chain's default public RPC. + */ +export const publicClient = createPublicClient({ + chain, + transport, +}); diff --git a/lib/viem.ts b/lib/viem.ts index cfb41c1c..9fca585f 100644 --- a/lib/viem.ts +++ b/lib/viem.ts @@ -1,12 +1,3 @@ -import { createPublicClient, http } from "viem"; -import { base } from "viem/chains"; - -/** - * Public client for reading from Base. - * - * Uses the default Base RPC. Override via BASE_RPC_URL env var. - */ -export const publicClient = createPublicClient({ - chain: base, - transport: http(process.env.BASE_RPC_URL || undefined), -}); +// Re-export from lib/rpc.ts — this file exists for backward compatibility. +// New code should import from "lib/rpc" directly. +export { publicClient } from "./rpc";