@@ -3,7 +3,7 @@ import * as process from 'node:process';
33import path from 'path' ;
44import { zeroAddress , Address , Chain } from 'viem' ;
55
6- import { getValueByPath , validateConfig } from 'utils' ;
6+ import { getValueByPath , logError , logInfo , validateConfig } from 'utils' ;
77import { Config } from 'types' ;
88
99import { envs } from './envs.js' ;
@@ -52,20 +52,79 @@ export const getDeployed = () => {
5252 return deployedJSON ;
5353} ;
5454
55- export const getChainId = ( ) => {
55+ let chainIdCache : number | undefined ;
56+ const getRpcChainId = async ( elURL : string ) => {
57+ if ( chainIdCache ) {
58+ return chainIdCache ;
59+ }
60+
61+ try {
62+ const rpcChainIdResponse = await fetch ( elURL , {
63+ method : 'POST' ,
64+ headers : {
65+ 'Content-Type' : 'application/json' ,
66+ } ,
67+ body : JSON . stringify ( {
68+ jsonrpc : '2.0' ,
69+ id : 1 ,
70+ method : 'eth_chainId' ,
71+ params : [ ] ,
72+ } ) ,
73+ } ) ;
74+
75+ if ( ! rpcChainIdResponse ?. ok ) {
76+ throw new Error (
77+ `RPC request failed: ${ rpcChainIdResponse . status } ${ rpcChainIdResponse . statusText } ` ,
78+ ) ;
79+ }
80+
81+ const rpcChainIdData = await rpcChainIdResponse . json ( ) ;
82+ if ( rpcChainIdData ?. error ) {
83+ throw new Error (
84+ `RPC error: ${ rpcChainIdData . error . message || JSON . stringify ( rpcChainIdData . error ) } ` ,
85+ ) ;
86+ }
87+
88+ const rpcChainId = parseInt ( rpcChainIdData . result , 16 ) ;
89+ chainIdCache = rpcChainId ;
90+
91+ return rpcChainId ;
92+ } catch ( error ) {
93+ if ( ! chainIdCache ) {
94+ logError (
95+ 'Filed to get RPC chainId. Please check if the EL_URL environment variable is correct or try to use another EL.' ,
96+ ) ;
97+ logInfo ( 'Continue work without RPC' ) ;
98+ }
99+
100+ return chainIdCache ;
101+ }
102+ } ;
103+
104+ export const getChainId = async ( ) => {
56105 const config = getConfig ( ) ;
106+ const elURL = getElUrl ( ) ;
57107 const deployed = getDeployed ( ) ;
58108 const chainId = config . CHAIN_ID ;
109+ const rpcChainId = await getRpcChainId ( elURL ) ;
59110
60111 if ( chainId !== deployed . chainId ) {
61- throw new Error ( 'ChainId in env and deployed file mismatch' ) ;
112+ throw new Error (
113+ `ChainId in env and deployed file mismatch. ENV: ${ chainId } DEPLOYED: ${ deployed . chainId } ` ,
114+ ) ;
115+ }
116+
117+ if ( rpcChainId && chainId !== rpcChainId ) {
118+ throw new Error (
119+ `ChainId in env and RPC chainId mismatch. ENV: ${ chainId } RPC: ${ rpcChainId } ` ,
120+ ) ;
62121 }
63122
64123 return chainId ;
65124} ;
66125
67- export const getChain = ( ) : Chain => {
68- const chainId = getChainId ( ) ;
126+ export const getChain = async ( ) : Promise < Chain > => {
127+ const chainId = await getChainId ( ) ;
69128 const chain = SUPPORTED_CHAINS_LIST . find ( ( chain ) => chain . id === chainId ) ;
70129
71130 if ( ! chain ) {
0 commit comments