Skip to content

Instantly share code, notes, and snippets.

@smakosh
Created December 10, 2021 22:26
Show Gist options
  • Save smakosh/e6afcb564753637b01cdaac68f693c67 to your computer and use it in GitHub Desktop.
Save smakosh/e6afcb564753637b01cdaac68f693c67 to your computer and use it in GitHub Desktop.
A cool Switch network React hook
import { useMemo } from 'react';
const useswitchNetwork = async (
account: string | null | undefined,
nextChainId: 1 | 10 | 42 | 69,
currentChainId: number | undefined,
forceOptimism = false,
) => {
if (!account) {
return;
}
if (currentChainId && forceOptimism && currentChainId === nextChainId) {
return;
} else {
if (typeof window !== 'undefined' && window.ethereum) {
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: toHex(NETWORK[nextChainId].chainId) }],
});
} catch (error: any) {
if (error.code === 4902) {
try {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: toHex(NETWORK[nextChainId].chainId),
chainName: NETWORK[nextChainId].name,
nativeCurrency: NETWORK[nextChainId].currency,
rpcUrls: [NETWORK[nextChainId].rpcUrl],
blockExplorerUrls: [NETWORK[nextChainId].etherscan],
},
],
});
} catch (addError) {
console.error(addError);
}
}
if (error.code === 4001) {
// @TODO: handle this UX on the UI
alert(
forceOptimism
? 'You can only customize your Hustler on Optimistic'
: 'You have to be on Mainnet in order to initiate a hustler',
);
}
}
} else {
if (typeof window !== 'undefined')
alert(
'MetaMask is not installed. Please consider installing it: https://metamask.io/download.html',
);
}
}
};
export const useSwitchEthereum = (
chainId: number | undefined,
account: string | null | undefined,
) => {
let ethChainId: 1 | 42 = 1;
if (!chainId || chainId === 10) {
ethChainId = 1;
} else if (chainId === 1 || chainId === 42) {
ethChainId = chainId;
} else if (chainId === 69) {
ethChainId = 42;
}
return useMemo(
() => useswitchNetwork(account, ethChainId, chainId),
[account, chainId, ethChainId],
);
};
export const useSwitchOptimism = (
chainId: number | undefined,
account: string | null | undefined,
) => {
let optimismChainId: 10 | 69 = 10;
if (!chainId || chainId === 1) {
optimismChainId = 10;
} else if (chainId === 10 || chainId === 69) {
optimismChainId = chainId;
} else if (chainId === 42) {
optimismChainId = 69;
}
return useMemo(
() => useswitchNetwork(account, optimismChainId, chainId, true),
[account, chainId, optimismChainId],
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment