-
Notifications
You must be signed in to change notification settings - Fork 0
refactor: introduce ChainSyncManager to keep chain state up to date #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| import { SUPPORTED_CHAINS } from '@/config.ts'; | ||
| import { useRouter } from '@tanstack/react-router'; | ||
| import { useChainSwitch } from '@/hooks/useChainSwitch.ts'; | ||
| import useUserStore from '@/stores/useUser.store.ts'; | ||
| import { | ||
| Select, | ||
|
|
@@ -11,23 +11,17 @@ import { | |
|
|
||
| export function ChainSelector() { | ||
| const { chainId } = useUserStore(); | ||
| const { navigate } = useRouter(); | ||
|
|
||
| const { requestChainChange } = useChainSwitch(); | ||
| const handleChainChange = async (value: string) => { | ||
| const newChainSlug = SUPPORTED_CHAINS.find( | ||
| (chain) => chain.id === Number(value) | ||
| )?.slug; | ||
| const pathParts = location.pathname.split('/').filter(Boolean); | ||
| const newPath = | ||
| pathParts.length > 1 | ||
| ? `/${newChainSlug}/${pathParts.slice(1).join('/')}` | ||
| : `/${newChainSlug}`; | ||
|
|
||
| navigate({ to: newPath }); | ||
|
Comment on lines
-17
to
-26
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. removed side effect in the component implementation, chain navigation is handled by a single component |
||
| requestChainChange(Number(value)); | ||
| }; | ||
|
|
||
| return ( | ||
| <Select value={chainId.toString()} onValueChange={handleChainChange}> | ||
| <Select | ||
| value={chainId?.toString()} | ||
| onValueChange={handleChainChange} | ||
| defaultValue="-1" | ||
| > | ||
| <SelectTrigger> | ||
| <SelectValue placeholder="Select Chain" /> | ||
| </SelectTrigger> | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,9 +3,12 @@ import type { TypedDocumentString } from './graphql' | |
|
|
||
| export async function execute<TResult, TVariables>( | ||
| query: TypedDocumentString<TResult, TVariables>, | ||
| chainId: number, | ||
| chainId?: number, | ||
| ...[variables]: TVariables extends Record<string, never> ? [] : [TVariables] | ||
| ) { | ||
| if (!chainId) { | ||
| throw Error('Missing chainId') | ||
| } | ||
|
Comment on lines
+9
to
+11
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| const subgraphUrl = getSubgraphUrl(chainId); | ||
| const response = await fetch(subgraphUrl, { | ||
| method: 'POST', | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import { useParams, useRouter } from '@tanstack/react-router'; | ||
| import { switchChain } from '@wagmi/core'; | ||
| import { useEffect, useRef } from 'react'; | ||
| import { useAccount } from 'wagmi'; | ||
| import useUserStore from '@/stores/useUser.store'; | ||
| import { getChainFromId, INITIAL_CHAIN } from '@/utils/chain.utils'; | ||
| import { wagmiAdapter } from '@/utils/wagmiConfig'; | ||
|
|
||
| /** | ||
| * Synchronize URL, account and app state | ||
| * | ||
| * - keep the global store up to date with user's account state | ||
| * - keep the URL up to date with the chain | ||
| * - request chain changes when user's account connects to the wrong chain | ||
| */ | ||
| export function ChainSyncManager() { | ||
| const { chainSlug } = useParams({ from: '/$chainSlug' }); | ||
| const { navigate, history } = useRouter(); | ||
| const { pathname } = history.location; | ||
| const { | ||
| chain: accountChain, | ||
| address: accountAddress, | ||
| isConnected: accountIsConnected, | ||
| status: accountStatus, | ||
| } = useAccount(); | ||
| const { chainId, setChainId, setIsConnected, setAddress } = useUserStore(); | ||
|
|
||
| const isNavigating = useRef(false); | ||
| const previousAccountStatus = useRef<string | undefined>(undefined); | ||
|
|
||
| // init store's chain from location (once at mount time) | ||
| useEffect(() => { | ||
| setChainId(INITIAL_CHAIN.id); | ||
| }, []); | ||
|
|
||
| // update store with user account's state | ||
| useEffect(() => { | ||
| setIsConnected(accountIsConnected); | ||
| setAddress(accountAddress); | ||
| if (accountChain?.id && chainId !== accountChain?.id) { | ||
| setChainId(accountChain?.id); | ||
| } | ||
| }, [ | ||
| accountAddress, | ||
| accountIsConnected, | ||
| setIsConnected, | ||
| setAddress, | ||
| chainId, | ||
| accountChain?.id, | ||
| setChainId, | ||
| ]); | ||
|
|
||
| // request chain change if the user connects on chain different from the active chain | ||
| useEffect(() => { | ||
| // auto reconnection case connect to the initial chain | ||
| if ( | ||
| (previousAccountStatus.current === undefined || | ||
| previousAccountStatus.current === 'reconnecting') && | ||
| accountChain?.id && | ||
| INITIAL_CHAIN.id !== accountChain?.id | ||
| ) { | ||
| switchChain(wagmiAdapter.wagmiConfig, { chainId: INITIAL_CHAIN.id }); | ||
| } | ||
| // connection case connect to the selected chain | ||
| if ( | ||
| previousAccountStatus.current === 'connecting' && | ||
| chainId && | ||
| accountChain?.id && | ||
| chainId !== accountChain?.id | ||
| ) { | ||
| switchChain(wagmiAdapter.wagmiConfig, { chainId }); | ||
| } | ||
|
|
||
| previousAccountStatus.current = accountStatus; | ||
| }, [accountChain?.id, chainId, accountStatus]); | ||
|
|
||
| // Sync URL with store's chain | ||
| useEffect(() => { | ||
| if (!chainId) { | ||
| return; | ||
| } | ||
| const slug = getChainFromId(chainId)?.slug; | ||
|
|
||
| if (slug !== chainSlug && !isNavigating.current) { | ||
| const [, ...rest] = pathname.split('/').filter(Boolean); | ||
| const newPath = `/${slug}/${rest.join('/')}`; | ||
| isNavigating.current = true; | ||
| const navigationResult = navigate({ to: newPath, replace: true }); | ||
| if (navigationResult instanceof Promise) { | ||
| navigationResult.finally(() => { | ||
| isNavigating.current = false; | ||
| }); | ||
| } else { | ||
| isNavigating.current = false; | ||
| } | ||
| } | ||
| }, [chainId, chainSlug, navigate, pathname]); | ||
|
|
||
| return null; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import { switchChain } from '@wagmi/core'; | ||
| import { useAccount } from 'wagmi'; | ||
| import useUserStore from '@/stores/useUser.store'; | ||
| import { wagmiAdapter } from '@/utils/wagmiConfig'; | ||
|
|
||
| export function useChainSwitch() { | ||
| const { isConnected } = useAccount(); | ||
| const { setChainId } = useUserStore(); | ||
| /** | ||
| * request a chain change | ||
| * | ||
| * the change is either: | ||
| * - immediately effective if the user is not connected | ||
| * - delegated to the user's account provider if the user is connected | ||
| */ | ||
| async function requestChainChange(chainId: number) { | ||
| if (isConnected) { | ||
| switchChain(wagmiAdapter.wagmiConfig, { chainId }); | ||
| } else { | ||
| setChainId(chainId); | ||
| } | ||
| } | ||
| return { requestChainChange }; | ||
| } |
This file was deleted.
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,9 @@ | ||
| import { createFileRoute, Outlet } from '@tanstack/react-router'; | ||
| import { useSyncChain } from '@/hooks/useSyncChain'; | ||
|
|
||
| export const Route = createFileRoute('/$chainSlug/_layout')({ | ||
| component: RouteComponent, | ||
| }); | ||
|
|
||
| function RouteComponent() { | ||
| useSyncChain(); | ||
|
|
||
| return <Outlet />; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
chainId from store may be different from account's chainId