|
| 1 | +import { ReactNode, createContext, useContext, useEffect } from "react"; |
| 2 | +import { useConfig } from "wagmi"; |
| 3 | +import { getClient } from "wagmi/actions"; |
| 4 | +import { useQuery } from "@tanstack/react-query"; |
| 5 | +import { SyncAdapter, SyncOptions, SyncResult } from "../common"; |
| 6 | + |
| 7 | +/** @internal */ |
| 8 | +export const SyncContext = createContext<{ |
| 9 | + sync?: SyncResult; |
| 10 | +} | null>(null); |
| 11 | + |
| 12 | +export type Props = Omit<SyncOptions, "publicClient"> & { |
| 13 | + chainId: number; |
| 14 | + adapter: SyncAdapter; |
| 15 | + children: ReactNode; |
| 16 | +}; |
| 17 | + |
| 18 | +// eslint-disable-next-line @typescript-eslint/explicit-function-return-type |
| 19 | +export function SyncProvider({ chainId, adapter, children, ...syncOptions }: Props) { |
| 20 | + const existingValue = useContext(SyncContext); |
| 21 | + if (existingValue != null) { |
| 22 | + throw new Error("A `SyncProvider` cannot be nested inside another."); |
| 23 | + } |
| 24 | + |
| 25 | + const config = useConfig(); |
| 26 | + |
| 27 | + const { data: sync, error: syncError } = useQuery({ |
| 28 | + queryKey: ["sync", chainId], |
| 29 | + queryFn: async () => { |
| 30 | + const client = getClient(config, { chainId }); |
| 31 | + if (!client) { |
| 32 | + throw new Error(`Unable to retrieve Viem client for chain ${chainId}.`); |
| 33 | + } |
| 34 | + |
| 35 | + return adapter({ publicClient: client, ...syncOptions }); |
| 36 | + }, |
| 37 | + staleTime: Infinity, |
| 38 | + refetchOnMount: false, |
| 39 | + refetchOnWindowFocus: false, |
| 40 | + refetchOnReconnect: false, |
| 41 | + }); |
| 42 | + if (syncError) throw syncError; |
| 43 | + |
| 44 | + useEffect(() => { |
| 45 | + if (!sync) return; |
| 46 | + |
| 47 | + const sub = sync.storedBlockLogs$.subscribe({ |
| 48 | + error: (error) => console.error("got sync error", error), |
| 49 | + }); |
| 50 | + |
| 51 | + return (): void => { |
| 52 | + sub.unsubscribe(); |
| 53 | + }; |
| 54 | + }, [sync]); |
| 55 | + |
| 56 | + return <SyncContext.Provider value={{ sync }}>{children}</SyncContext.Provider>; |
| 57 | +} |
0 commit comments