@@ -483,30 +483,69 @@ const initialize = async () => {
483483 }
484484 } ;
485485
486+ async function getLocalNodeChainId ( ) {
487+ try {
488+ const response = await fetch ( 'http://127.0.0.1:8545' , {
489+ method : 'POST' ,
490+ headers : { 'Content-Type' : 'application/json' } ,
491+ body : JSON . stringify ( {
492+ jsonrpc : '2.0' ,
493+ method : 'eth_chainId' ,
494+ params : [ ] ,
495+ id : 1 ,
496+ } ) ,
497+ } ) ;
498+
499+ const chainId = ( await response . json ( ) ) . result ;
500+ const chainIdDecimal = parseInt ( chainId , 16 ) ;
501+ console . log (
502+ `Fetched chain ID from local node: ${ chainId } (${ chainIdDecimal } )` ,
503+ ) ;
504+
505+ return chainId ;
506+ } catch ( err ) {
507+ if ( err . message === 'Failed to fetch' ) {
508+ throw new Error ( 'Local node RPC is unavailable. Cannot fetch chain ID' ) ;
509+ }
510+
511+ throw err ;
512+ }
513+ }
514+
486515 addEthereumChain . onclick = async ( ) => {
487- await ethereum . request ( {
488- method : 'wallet_addEthereumChain' ,
489- params : [
490- {
491- chainId : '0x539' ,
492- rpcUrls : [ 'http://127.0.0.1:8545' ] ,
493- chainName : 'Localhost 8545' ,
494- nativeCurrency : { name : 'Ether' , decimals : 18 , symbol : 'ETH' } ,
495- blockExplorerUrls : null ,
496- } ,
497- ] ,
498- } ) ;
516+ try {
517+ const chainId = await getLocalNodeChainId ( ) ;
518+ await ethereum . request ( {
519+ method : 'wallet_addEthereumChain' ,
520+ params : [
521+ {
522+ chainId,
523+ rpcUrls : [ 'http://127.0.0.1:8545' ] ,
524+ chainName : 'Localhost 8545' ,
525+ nativeCurrency : { name : 'Ether' , decimals : 18 , symbol : 'ETH' } ,
526+ blockExplorerUrls : null ,
527+ } ,
528+ ] ,
529+ } ) ;
530+ } catch ( err ) {
531+ console . error ( err ) ;
532+ }
499533 } ;
500534
501535 switchEthereumChain . onclick = async ( ) => {
502- await ethereum . request ( {
503- method : 'wallet_switchEthereumChain' ,
504- params : [
505- {
506- chainId : '0x539' ,
507- } ,
508- ] ,
509- } ) ;
536+ try {
537+ const chainId = await getLocalNodeChainId ( ) ;
538+ await ethereum . request ( {
539+ method : 'wallet_switchEthereumChain' ,
540+ params : [
541+ {
542+ chainId,
543+ } ,
544+ ] ,
545+ } ) ;
546+ } catch ( err ) {
547+ console . error ( err ) ;
548+ }
510549 } ;
511550
512551 const initializeAccountButtons = ( ) => {
0 commit comments