|
1 | 1 | import { getChainAddEthereumChainParameter } from 'lib/utils/chains'; |
| 2 | +import { useTranslations } from 'next-intl'; |
2 | 3 | import { useCallback } from 'react'; |
| 4 | +import { toast } from 'react-toastify'; |
3 | 5 | import { useAccount, useSwitchChain as useSwitchChainInternal } from 'wagmi'; |
4 | 6 |
|
5 | 7 | export const useSwitchChain = () => { |
| 8 | + const t = useTranslations(); |
| 9 | + |
6 | 10 | const { switchChain: switchChainInternal, switchChainAsync: switchChainAsyncInternal } = useSwitchChainInternal(); |
7 | 11 | const { connector } = useAccount(); |
8 | 12 | const canSwitchChain = connector?.type === 'injected'; |
9 | 13 |
|
10 | 14 | const switchChain = useCallback( |
11 | 15 | (chainId: number) => { |
12 | | - const addEthereumChainParameter = getChainAddEthereumChainParameter(chainId); |
13 | | - return switchChainInternal({ chainId, addEthereumChainParameter }); |
| 16 | + try { |
| 17 | + const addEthereumChainParameter = getChainAddEthereumChainParameter(chainId); |
| 18 | + return switchChainInternal({ chainId, addEthereumChainParameter }); |
| 19 | + } catch (error) { |
| 20 | + console.error(error); |
| 21 | + toast.error(t('common.toasts.switch_chain_failed')); |
| 22 | + throw error; |
| 23 | + } |
14 | 24 | }, |
15 | | - [switchChainInternal], |
| 25 | + [switchChainInternal, t], |
16 | 26 | ); |
17 | 27 |
|
18 | 28 | const switchChainAsync = useCallback( |
19 | | - (chainId: number) => { |
20 | | - const addEthereumChainParameter = getChainAddEthereumChainParameter(chainId); |
21 | | - return switchChainAsyncInternal({ chainId, addEthereumChainParameter }); |
| 29 | + async (chainId: number) => { |
| 30 | + try { |
| 31 | + const addEthereumChainParameter = getChainAddEthereumChainParameter(chainId); |
| 32 | + return await switchChainAsyncInternal({ chainId, addEthereumChainParameter }); |
| 33 | + } catch (error) { |
| 34 | + console.error(error); |
| 35 | + toast.error(t('common.toasts.switch_chain_failed')); |
| 36 | + throw error; |
| 37 | + } |
22 | 38 | }, |
23 | | - [switchChainAsyncInternal], |
| 39 | + [switchChainAsyncInternal, t], |
24 | 40 | ); |
25 | 41 |
|
26 | 42 | return { switchChain, switchChainAsync, canSwitchChain }; |
|
0 commit comments