Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ export default defineConfig({
projects: ["./tsconfig.json"],
}),
],
},
} as any,
});
2 changes: 1 addition & 1 deletion app/components/DefaultCatchBoundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function DefaultCatchBoundary({ error }: ErrorComponentProps) {
onClick={() => {
router.invalidate();
}}
className="rounded bg-gray-600 px-2 py-1 font-extrabold text-white uppercase dark:bg-gray-700"
className="cursor-pointer rounded bg-gray-600 px-2 py-1 font-extrabold text-white uppercase dark:bg-gray-700"
>
Try Again
</button>
Expand Down
7 changes: 7 additions & 0 deletions app/components/LoadingSpinner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function LoadingSpinner() {
return (
<div className="flex items-center justify-center p-4">
<div className="h-8 w-8 animate-spin rounded-full border-gray-900 border-b-2" />
</div>
);
}
34 changes: 19 additions & 15 deletions app/hooks/useConnectionState.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
import { useState } from "react";
import { useConfig, useWatchBlockNumber } from "wagmi";
import { useCallback } from "react";
import { useWatchBlockNumber } from "wagmi";
import { useConnectionStore } from "#/store/connection";

export function useConnectionState() {
const [blockNumber, setBlockNumber] = useState<bigint | null>(null);
const config = useConfig();
export function useConnectionState({ rpc }: { rpc: string }) {
const { setState } = useConnectionStore();

const interval = blockNumber ? 10000 : 1000;
const onBlockNumber = useCallback(
(b: bigint) => {
console.log("onblocknumber", b);
setState({ connected: true, blockNumber: b, rpc });
},
[rpc, setState],
);

const onError = useCallback(() => {
setState({ connected: false, blockNumber: null, rpc });
}, [rpc, setState]);

useWatchBlockNumber({
emitOnBegin: true,
poll: true,
pollingInterval: interval,
onBlockNumber: (b) => setBlockNumber(b),
onError: () => setBlockNumber(null),
pollingInterval: 1000,
onBlockNumber,
onError,
});

return {
connected: blockNumber !== null,
blockNumber,
rpc: config.chains[0].rpcUrls.default.http,
};
}
63 changes: 63 additions & 0 deletions app/routes/__root.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import { Form } from "@ethui/ui/components/form";
import { Button } from "@ethui/ui/components/shadcn/button";
import { zodResolver } from "@hookform/resolvers/zod";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
HeadContent,
Outlet,
Scripts,
createRootRouteWithContext,
useNavigate,
useParams,
} from "@tanstack/react-router";
import { Suspense, lazy } from "react";
import { type FieldValues, useForm } from "react-hook-form";
import { z } from "zod";
import appCss from "#/app.css?url";
import { DefaultCatchBoundary } from "#/components/DefaultCatchBoundary";
import { NotFound } from "#/components/NotFound";
import { useConnectionStore } from "#/store/connection";
import { seo } from "#/utils/seo";

const TanStackRouterDevtools =
Expand Down Expand Up @@ -76,6 +84,7 @@ function RootComponent() {
return (
<RootDocument>
<QueryClientProvider client={queryClient}>
<RpcForm />
<Outlet />
</QueryClientProvider>
</RootDocument>
Expand All @@ -98,3 +107,57 @@ function RootDocument({ children }: { children: React.ReactNode }) {
</html>
);
}

function RpcForm() {
const navigate = useNavigate();
const { rpc } = useParams({ strict: false });
const { connected, blockNumber, reset } = useConnectionStore();
const currentRpc = rpc ? decodeURIComponent(rpc) : "ws://localhost:8545";

const schema = z.object({
url: z.string(),
});

const form = useForm({
mode: "onBlur",
resolver: zodResolver(schema),
defaultValues: {
url: currentRpc,
},
});

const handleSubmit = (data: FieldValues) => {
const newRpc = data.url;
if (newRpc !== currentRpc) {
reset();
}
navigate({ to: `/rpc/${encodeURIComponent(newRpc)}`, replace: true });
};

return (
<nav>
<div className="flex w-full flex-row items-baseline justify-between gap-[0] bg-accent p-2">
<Form form={form} onSubmit={handleSubmit} className="flex-row gap-[0]">
<Form.Text
name="url"
placeholder="Enter URL (e.g. localhost:8545)"
className="inline"
onSubmit={handleSubmit}
/>
<Button type="submit">Go</Button>
</Form>
<div className="ml-2">
{connected === undefined ? (
<span className="text-gray-500">No connection</span>
) : connected ? (
<span className="text-green-500">
Connected to {currentRpc} (Block: {blockNumber?.toString()})
</span>
) : (
<span className="text-red-500">Disconnected</span>
)}
</div>
</div>
</nav>
);
}
15 changes: 2 additions & 13 deletions app/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,5 @@
import { Link, createFileRoute } from "@tanstack/react-router";
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/")({
component: Home,
component: () => null,
});

function Home() {
return (
<Link
to="/rpc/$rpc"
params={{ rpc: encodeURIComponent("ws://localhost:8545") }}
>
Go
</Link>
);
}
69 changes: 20 additions & 49 deletions app/routes/rpc.$rpc/_l.tsx
Original file line number Diff line number Diff line change
@@ -1,64 +1,42 @@
import { Form } from "@ethui/ui/components/form";
import { Button } from "@ethui/ui/components/shadcn/button";
import { zodResolver } from "@hookform/resolvers/zod";
import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router";
import { type FieldValues, useForm } from "react-hook-form";
import { Outlet, createFileRoute } from "@tanstack/react-router";
import { createServerFn } from "@tanstack/react-start";
import { http, WagmiProvider, createConfig, webSocket } from "wagmi";
import { foundry } from "wagmi/chains";
import { z } from "zod";
import { LoadingSpinner } from "#/components/LoadingSpinner";
import { useConnectionState } from "#/hooks/useConnectionState";
import { validateRpcConnection } from "#/utils/rpc";

const validateRpc = createServerFn({
method: "GET",
})
.validator((rpc: string) => rpc)
.handler(async ({ data: rpc }) => validateRpcConnection(rpc));

export const Route = createFileRoute("/rpc/$rpc/_l")({
loader: ({ params }) => decodeURIComponent(params.rpc),
loader: async ({ params }) => {
const rpc = decodeURIComponent(params.rpc);
return validateRpc({ data: rpc });
},
component: RouteComponent,
pendingComponent: () => <LoadingSpinner />,
});

function RouteComponent() {
const rpc = Route.useLoaderData();
const navigate = useNavigate();

const schema = z.object({
url: z.string(),
});

const form = useForm({
mode: "onBlur",
resolver: zodResolver(schema),
defaultValues: {
url: "ws://localhost:8545",
},
});

const transport = rpc.startsWith("ws://") ? webSocket(rpc) : http(rpc);

const wagmi = createConfig({
chains: [foundry],
transports: {
[foundry.id]: transport,
},
});

const handleSubmit = (data: FieldValues) => {
navigate({ to: `/rpc/${encodeURIComponent(data.url)}` });
};

return (
<WagmiProvider config={wagmi}>
<ConnectionStateUpdater rpc={rpc} />
<div className="flex flex-col justify-center gap-2">
<div className="flex w-full flex-row items-baseline justify-between gap-[0] bg-accent p-2">
<Form
form={form}
onSubmit={handleSubmit}
className="flex-row gap-[0]"
>
<Form.Text
name="url"
placeholder="Enter URL (e.g. localhost:8545)"
className="inline"
/>
<Button type="submit">Go</Button>
</Form>
<ConnectionState />
</div>
<div className="flex-grow overflow-hidden">
<Outlet />
</div>
Expand All @@ -67,14 +45,7 @@ function RouteComponent() {
);
}

function ConnectionState() {
const { connected, blockNumber, rpc } = useConnectionState();

return (
connected && (
<div>
Connected to: {rpc} at block {blockNumber}
</div>
)
);
function ConnectionStateUpdater({ rpc }: { rpc: string }) {
useConnectionState({ rpc });
return null;
}
17 changes: 17 additions & 0 deletions app/store/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { create } from "zustand";

interface ConnectionState {
connected: boolean | undefined;
blockNumber: bigint | null;
rpc: string | undefined;
setState: (state: Partial<ConnectionState>) => void;
reset: () => void;
}

export const useConnectionStore = create<ConnectionState>((set) => ({
connected: undefined,
blockNumber: null,
rpc: undefined,
setState: (state) => set(state),
reset: () => set({ connected: undefined, blockNumber: null, rpc: undefined }),
}));
41 changes: 41 additions & 0 deletions app/utils/rpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { http, createPublicClient } from "viem";
import { foundry } from "wagmi/chains";

export async function validateRpcConnection(rpc: string): Promise<string> {
if (rpc.startsWith("ws://")) {
const isValid = await new Promise<boolean>((resolve) => {
const timeout = setTimeout(() => resolve(false), 5000);
try {
const ws = new WebSocket(rpc);
ws.onopen = () => {
clearTimeout(timeout);
ws.close();
resolve(true);
};
ws.onerror = () => {
clearTimeout(timeout);
resolve(false);
};
} catch {
clearTimeout(timeout);
resolve(false);
}
});

if (!isValid) {
throw new Error(`Invalid WebSocket RPC on ${rpc}`);
}
} else {
try {
const client = createPublicClient({
chain: foundry,
transport: http(rpc),
});
await client.getChainId();
} catch (_err) {
throw new Error(`Invalid RPC on ${rpc}`);
}
}

return rpc;
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
"vinxi": "0.5.3",
"vite-tsconfig-paths": "^5.1.4",
"wagmi": "^2.14.15",
"zod": "^3.24.2"
"zod": "^3.24.2",
"zustand": "^5.0.4"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
Expand Down
22 changes: 22 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1077,6 +1077,7 @@ __metadata:
vite-tsconfig-paths: "npm:^5.1.4"
wagmi: "npm:^2.14.15"
zod: "npm:^3.24.2"
zustand: "npm:^5.0.4"
languageName: unknown
linkType: soft

Expand Down Expand Up @@ -12691,6 +12692,27 @@ __metadata:
languageName: node
linkType: hard

"zustand@npm:^5.0.4":
version: 5.0.4
resolution: "zustand@npm:5.0.4"
peerDependencies:
"@types/react": ">=18.0.0"
immer: ">=9.0.6"
react: ">=18.0.0"
use-sync-external-store: ">=1.2.0"
peerDependenciesMeta:
"@types/react":
optional: true
immer:
optional: true
react:
optional: true
use-sync-external-store:
optional: true
checksum: 10c0/5b6220f51b315cef3224a6517fcc00fa553df1af604009a9f02f8091727fe52e0499bc093be3efdd64b9fa4ad9238346aff21f34cdf79355207fcad097031596
languageName: node
linkType: hard

"zwitch@npm:^2.0.0":
version: 2.0.4
resolution: "zwitch@npm:2.0.4"
Expand Down