Skip to content

Commit 3f0bc64

Browse files
authored
Add switchToCorrectNetwork method (#125)
* Add `switchToCorrectNetwork` method * Add `ts-ignore` for error type in switchToCorrectNetwork add `any` type to error in catch handler add any type to error in catch handler * Add network in Web3ContextType * Make requested changes and remove unnecessary changes * Run `yarn changeset`
1 parent 6064be0 commit 3f0bc64

File tree

4 files changed

+65
-4
lines changed

4 files changed

+65
-4
lines changed

.changeset/long-buses-brush.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@web3-ui/hooks': minor
3+
---
4+
5+
Added a new method "switchToCorrectNetwork" to the useWallet hook. This method allows the user to switch to the required network without manually heading over to the MetaMask and switching the network. Users can use this function by directly passing this method in the click handler of a button.

packages/hooks/src/Provider.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export interface Web3ContextType {
1313
connected: boolean;
1414
provider?: ethers.providers.Web3Provider | null;
1515
correctNetwork: boolean;
16+
network: number;
1617
}
1718

1819
export const Web3Context = React.createContext<Web3ContextType | undefined>(undefined);

packages/hooks/src/hooks/useWallet.ts

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,56 @@ export function useWallet() {
2222
connected,
2323
provider,
2424
correctNetwork,
25+
network,
2526
} = context;
2627

2728
React.useEffect(() => {
2829
if (userAddress && provider && chainId === NETWORKS.mainnet) {
29-
provider.lookupAddress(userAddress).then((address) => {
30+
provider.lookupAddress(userAddress).then(address => {
3031
setEns(address as string);
3132
});
3233
}
3334
}, [userAddress, provider]);
3435

36+
const switchToCorrectNetwork = async () => {
37+
if (window.ethereum) {
38+
try {
39+
console.log('chainId', { chainId });
40+
console.log('requiredNetwork', { network });
41+
// check if the chain to connect to is installed
42+
await window.ethereum.request({
43+
method: 'wallet_switchEthereumChain',
44+
params: [{ chainId: `0x${network}` }], // chainId must be in hexadecimal numbers
45+
});
46+
} catch (error) {
47+
console.error(error);
48+
// This error code indicates that the chain has not been added to MetaMask.
49+
// If it is not, then install it into the user's MetaMask
50+
// @ts-expect-error
51+
if (error.code === 4902) {
52+
try {
53+
await window.ethereum.request({
54+
method: 'wallet_addEthereumChain',
55+
params: [
56+
{
57+
chainId: '0x61',
58+
rpcUrl: 'https://data-seed-prebsc-1-s1.binance.org:8545/',
59+
},
60+
],
61+
});
62+
} catch (addError) {
63+
console.error(addError);
64+
}
65+
}
66+
}
67+
} else {
68+
// if window.ethereum is undefined then MetaMask is not installed
69+
alert(
70+
'Switching networks automatically is only supported in MetaMask. Please consider installing it: https://metamask.io/download.html'
71+
);
72+
}
73+
};
74+
3575
return {
3676
connectWallet,
3777
disconnectWallet,
@@ -44,5 +84,6 @@ export function useWallet() {
4484
connected,
4585
provider,
4686
correctNetwork,
87+
switchToCorrectNetwork,
4788
};
4889
}

packages/hooks/src/stories/ConnectWallet.stories.tsx

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,14 @@ export default {
1010
const portisDappId = '512893f6-6436-44c3-b0dc-6caccab984bb';
1111

1212
const DefaultUsingProvider = () => {
13-
const { connection, connectWallet, disconnectWallet, connected, correctNetwork } = useWallet();
13+
const {
14+
connection,
15+
connectWallet,
16+
disconnectWallet,
17+
connected,
18+
correctNetwork,
19+
switchToCorrectNetwork,
20+
} = useWallet();
1421

1522
useEffect(() => {
1623
if (!correctNetwork) {
@@ -24,6 +31,11 @@ const DefaultUsingProvider = () => {
2431
<Button onClick={disconnectWallet}>Disconnect wallet</Button>
2532
<p>{connection.ens || connection.userAddress}</p>
2633
<p>Connected to the correct network: {correctNetwork ? 'Yes' : 'no'}</p>
34+
{!correctNetwork && (
35+
<Button colorScheme='teal' mt={2} onClick={switchToCorrectNetwork}>
36+
Switch to correct network
37+
</Button>
38+
)}
2739
</div>
2840
);
2941
}
@@ -59,7 +71,8 @@ export const WithPortisProvider = () => (
5971
{
6072
portis: {
6173
display: {
62-
logo: 'https://user-images.githubusercontent.com/9419140/128913641-d025bc0c-e059-42de-a57b-422f196867ce.png',
74+
logo:
75+
'https://user-images.githubusercontent.com/9419140/128913641-d025bc0c-e059-42de-a57b-422f196867ce.png',
6376
name: 'Portis',
6477
description: 'Connect to Portis App',
6578
},
@@ -82,7 +95,8 @@ export const PortisAuthereumProvider = () => (
8295
{
8396
portis: {
8497
display: {
85-
logo: 'https://user-images.githubusercontent.com/9419140/128913641-d025bc0c-e059-42de-a57b-422f196867ce.png',
98+
logo:
99+
'https://user-images.githubusercontent.com/9419140/128913641-d025bc0c-e059-42de-a57b-422f196867ce.png',
86100
name: 'Portis',
87101
description: 'Connect to Portis App',
88102
},

0 commit comments

Comments
 (0)