Skip to content

Instantly share code, notes, and snippets.

@adairrr
Created November 19, 2022 03:52
Show Gist options
  • Save adairrr/d300102ddab76a21aa0fd5329ac1fa01 to your computer and use it in GitHub Desktop.
Save adairrr/d300102ddab76a21aa0fd5329ac1fa01 to your computer and use it in GitHub Desktop.
import { KeyedReactQueryOptions } from 'api/queries/useReactQueryOptions'
import { Tendermint34Client } from '@cosmjs/tendermint-rpc'
import { QueryKey } from '@tanstack/query-core'
import { useChain, useNetwork } from 'contexts'
import { useQuery } from '@tanstack/react-query'
import { QueryOptions } from 'api/queries/query'
import { CosmWasmClient } from '@cosmjs/cosmwasm-stargate'
import { StargateClient } from '@cosmjs/stargate'
export const clientKeys = {
client: (networkId: string) => ['client', networkId] as const,
cosmWasm: (networkId: string) => [...clientKeys.client(networkId), 'cosmwasm'] as const,
tendermint: (networkId: string) => [...clientKeys.client(networkId), 'tendermint'] as const,
stargate: (networkId: string) => [...clientKeys.client(networkId), 'stargate'] as const,
} as const
/**
* Generic hook that can return a readonly client based on the network rpc.
*/
export const useNetworkClient = <TClient, QKey extends QueryKey>({
queryKey,
queryFn,
options,
}: {
queryKey: (id: string) => QKey
queryFn: (rpc: string) => Promise<TClient>
options?: KeyedReactQueryOptions<TClient, QKey>
}) => {
const { chain } = useChain()
const { network } = useNetwork()
const { data: client } = useQuery<TClient, Error, TClient, QKey>(
queryKey(network.id),
() => queryFn(network.endpoints.rpc),
{
// allow overriding
onError: (e) => {
// TODO: this doesn't work
throw new Error(`Failed to connect to ${network.id} on ${chain}`, e)
},
...options,
...QueryOptions.DISABLE_WITHOUT(network.endpoints.rpc, options?.enabled),
}
)
return { client }
}
export const useTendermintClient = (
options?: KeyedReactQueryOptions<Tendermint34Client, ReturnType<typeof clientKeys['tendermint']>>
) =>
useNetworkClient({
queryKey: clientKeys.tendermint,
queryFn: (rpc) => Tendermint34Client.connect(rpc),
options,
})
export const useCosmWasmClient = (
options?: KeyedReactQueryOptions<CosmWasmClient, ReturnType<typeof clientKeys['cosmWasm']>>
) =>
useNetworkClient({
queryKey: clientKeys.cosmWasm,
queryFn: (rpc) => CosmWasmClient.connect(rpc),
options,
})
export const useStargateClient = (
options?: KeyedReactQueryOptions<StargateClient, ReturnType<typeof clientKeys['stargate']>>
) =>
useNetworkClient({
queryKey: clientKeys.stargate,
queryFn: async (rpc) => StargateClient.connect(rpc),
options,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment