import { TelescopeOptions } from "@subql/x-cosmology-types"; export const getReactQueryHelper = (options: TelescopeOptions) => { return `import { getRpcClient } from './extern' import { useQuery, UseQueryOptions, } from '@tanstack/react-query'; import { HttpEndpoint, ProtobufRpcClient } from '@cosmjs/stargate'; ${ options.rpcClients.useConnectComet ? "import { CometClient, connectComet, Tendermint34Client, Tendermint37Client } from '@cosmjs/tendermint-rpc';" : "import { Tendermint34Client } from '@cosmjs/tendermint-rpc';" } export interface ReactQueryParams { options?: UseQueryOptions; } export interface UseRpcClientQuery extends ReactQueryParams { rpcEndpoint: string | HttpEndpoint; } ${ options.reactQuery.needExtraQueryKey ? `export interface UseRpcEndpointQuery extends ReactQueryParams { getter: () => Promise; extraKey?: string } export const useRpcEndpoint = ({ getter, options, extraKey }: UseRpcEndpointQuery) => { return useQuery(['rpcEndpoint', extraKey], async () => { return await getter(); }, options); };` : `export interface UseRpcEndpointQuery extends ReactQueryParams { getter: () => Promise; } export const useRpcEndpoint = ({ getter, options, }: UseRpcEndpointQuery) => { return useQuery(['rpcEndpoint', getter], async () => { return await getter(); }, options); };` } export const useRpcClient = ({ rpcEndpoint, options, }: UseRpcClientQuery) => { return useQuery(['rpcClient', rpcEndpoint], async () => { return await getRpcClient(rpcEndpoint); }, options); }; ${ options.rpcClients.useConnectComet ? "interface UseTendermintClient extends ReactQueryParams {" : "interface UseTendermintClient extends ReactQueryParams {" } rpcEndpoint: string | HttpEndpoint; } /** * Hook that uses react-query to cache a connected tendermint client. */ export const useTendermintClient = ({ rpcEndpoint, options, }: UseTendermintClient) => { ${ options.rpcClients.useConnectComet ? " const { data: client } = useQuery(" : " const { data: client } = useQuery(" } ['client', 'tendermint', rpcEndpoint], () => ${ options.rpcClients.useConnectComet ? "connectComet(rpcEndpoint)" : "Tendermint34Client.connect(rpcEndpoint)" }, { // allow overriding onError: (e) => { throw new Error(\`Failed to connect to \${rpcEndpoint}\` + '\\n' + e) }, ...options, } ) return { client } }; `; };