@@ -19,10 +19,8 @@ import { TransactionErrorMessage } from "./TransactionErrorMessage";
19
19
import { WaitingForTransactionMessage } from "./WaitingForTransactionMessage" ;
20
20
import { NoTokensMessage } from "./NoTokensMessage" ;
21
21
22
- // This is the Hardhat Network id that we set in our hardhat.config.js.
23
- // Here's a list of network ids https://docs.metamask.io/guide/ethereum-provider.html#properties
24
- // to use when deploying to other networks.
25
- const HARDHAT_NETWORK_ID = '1337' ;
22
+ // This is the default id used by the Hardhat Network
23
+ const HARDHAT_NETWORK_ID = '31337' ;
26
24
27
25
// This is an error code that indicates that the user canceled a transaction
28
26
const ERROR_CODE_TX_REJECTED_BY_USER = 4001 ;
@@ -60,7 +58,7 @@ export class Dapp extends React.Component {
60
58
61
59
render ( ) {
62
60
// Ethereum wallets inject the window.ethereum object. If it hasn't been
63
- // injected, we instruct the user to install MetaMask .
61
+ // injected, we instruct the user to install a wallet .
64
62
if ( window . ethereum === undefined ) {
65
63
return < NoWalletDetected /> ;
66
64
}
@@ -178,9 +176,7 @@ export class Dapp extends React.Component {
178
176
// Once we have the address, we can initialize the application.
179
177
180
178
// First we check the network
181
- if ( ! this . _checkNetwork ( ) ) {
182
- return ;
183
- }
179
+ this . _checkNetwork ( ) ;
184
180
185
181
this . _initialize ( selectedAddress ) ;
186
182
@@ -197,12 +193,6 @@ export class Dapp extends React.Component {
197
193
198
194
this . _initialize ( newAddress ) ;
199
195
} ) ;
200
-
201
- // We reset the dapp state if the network is changed
202
- window . ethereum . on ( "chainChanged" , ( [ networkId ] ) => {
203
- this . _stopPollingData ( ) ;
204
- this . _resetState ( ) ;
205
- } ) ;
206
196
}
207
197
208
198
_initialize ( userAddress ) {
@@ -354,16 +344,19 @@ export class Dapp extends React.Component {
354
344
this . setState ( this . initialState ) ;
355
345
}
356
346
357
- // This method checks if Metamask selected network is Localhost:8545
358
- _checkNetwork ( ) {
359
- if ( window . ethereum . networkVersion === HARDHAT_NETWORK_ID ) {
360
- return true ;
361
- }
362
-
363
- this . setState ( {
364
- networkError : 'Please connect Metamask to Localhost:8545'
347
+ async _switchChain ( ) {
348
+ const chainIdHex = `0x${ HARDHAT_NETWORK_ID . toString ( 16 ) } `
349
+ await window . ethereum . request ( {
350
+ method : "wallet_switchEthereumChain" ,
351
+ params : [ { chainId : chainIdHex } ] ,
365
352
} ) ;
353
+ await this . _initialize ( this . state . selectedAddress ) ;
354
+ }
366
355
367
- return false ;
356
+ // This method checks if the selected network is Localhost:8545
357
+ _checkNetwork ( ) {
358
+ if ( window . ethereum . networkVersion !== HARDHAT_NETWORK_ID ) {
359
+ this . _switchChain ( ) ;
360
+ }
368
361
}
369
362
}
0 commit comments