@@ -101,6 +101,18 @@ export type ChainWithRpcUrl = ArbitrumNetwork & {
101101 nativeTokenData ?: Erc20Data ;
102102} ;
103103
104+ function getAvailableLocalStorage ( ) : Pick < Storage , 'getItem' | 'setItem' > | null {
105+ if (
106+ typeof localStorage === 'undefined' ||
107+ typeof localStorage . getItem !== 'function' ||
108+ typeof localStorage . setItem !== 'function'
109+ ) {
110+ return null ;
111+ }
112+
113+ return localStorage ;
114+ }
115+
104116export function getBlockNumberReferenceChainIdByChainId ( { chainId } : { chainId : number } ) : number {
105117 // the chain provided is an L1 chain or Base chain, so we can return early
106118 if ( isBlockNumberReferenceNetwork ( { chainId } ) ) {
@@ -134,9 +146,10 @@ export function getBlockNumberReferenceChainIdByChainId({ chainId }: { chainId:
134146}
135147
136148export function getCustomChainsFromLocalStorage ( ) : ChainWithRpcUrl [ ] {
137- if ( typeof localStorage === 'undefined' ) return [ ] ; // required so that it does not fail test-runners
149+ const storage = getAvailableLocalStorage ( ) ;
150+ if ( ! storage ) return [ ] ; // required so that it does not fail outside browser runtime
138151
139- const customChainsFromLocalStorage = localStorage . getItem ( customChainLocalStorageKey ) ;
152+ const customChainsFromLocalStorage = storage . getItem ( customChainLocalStorageKey ) ;
140153
141154 if ( ! customChainsFromLocalStorage ) {
142155 return [ ] ;
@@ -171,6 +184,9 @@ export function getCustomChainFromLocalStorageById(chainId: ChainId) {
171184}
172185
173186export function saveCustomChainToLocalStorage ( newCustomChain : ChainWithRpcUrl ) {
187+ const storage = getAvailableLocalStorage ( ) ;
188+ if ( ! storage ) return ;
189+
174190 const customChains = getCustomChainsFromLocalStorage ( ) ;
175191
176192 if ( customChains . findIndex ( ( chain ) => chain . chainId === newCustomChain . chainId ) > - 1 ) {
@@ -180,15 +196,18 @@ export function saveCustomChainToLocalStorage(newCustomChain: ChainWithRpcUrl) {
180196
181197 const newCustomChains = [ ...getCustomChainsFromLocalStorage ( ) , newCustomChain ] ;
182198
183- localStorage . setItem ( customChainLocalStorageKey , JSON . stringify ( newCustomChains ) ) ;
199+ storage . setItem ( customChainLocalStorageKey , JSON . stringify ( newCustomChains ) ) ;
184200}
185201
186202export function removeCustomChainFromLocalStorage ( chainId : number ) {
203+ const storage = getAvailableLocalStorage ( ) ;
204+ if ( ! storage ) return ;
205+
187206 const newCustomChains = getCustomChainsFromLocalStorage ( ) . filter (
188207 ( chain ) => chain . chainId !== chainId ,
189208 ) ;
190209
191- localStorage . setItem ( customChainLocalStorageKey , JSON . stringify ( newCustomChains ) ) ;
210+ storage . setItem ( customChainLocalStorageKey , JSON . stringify ( newCustomChains ) ) ;
192211}
193212
194213export const supportedCustomOrbitParentChains = [
0 commit comments