@@ -484,18 +484,43 @@ const initialize = async () => {
484484 } ;
485485
486486 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- } ) ;
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+ await ethereum . request ( {
506+ method : 'wallet_addEthereumChain' ,
507+ params : [
508+ {
509+ chainId,
510+ rpcUrls : [ 'http://127.0.0.1:8545' ] ,
511+ chainName : 'Localhost 8545' ,
512+ nativeCurrency : { name : 'Ether' , decimals : 18 , symbol : 'ETH' } ,
513+ blockExplorerUrls : null ,
514+ } ,
515+ ] ,
516+ } ) ;
517+ } catch ( err ) {
518+ if ( err . message === 'Failed to fetch' ) {
519+ console . error ( 'Local node RPC is unavailable. Cannot fetch chain ID' ) ;
520+ } else {
521+ console . error ( err ) ;
522+ }
523+ }
499524 } ;
500525
501526 switchEthereumChain . onclick = async ( ) => {
0 commit comments