import { FaceError, FaceErrorCode, Network } from '@haechi-labs/face-types'; import { getChainId, getNetworkByChainId, isEthlikeNetwork } from '@haechi-labs/shared'; import { ethers } from 'ethers'; export function getValidNetwork(network: Network | number | string): Network { const hexRegex = /^0x[0-9A-Fa-f]*$/; if (typeof network === 'string' && hexRegex.test(network)) { const chainId = parseInt(network, 16); try { return getNetworkByChainId(chainId); } catch (err) { throw new FaceError({ message: `Invalid chainId: ${chainId}`, code: FaceErrorCode.UNSUPPORTED_CHAIN, }); } } if (typeof network === 'number') { try { return getNetworkByChainId(network); } catch (err) { throw new FaceError({ message: `Invalid chainId: ${network}`, code: FaceErrorCode.UNSUPPORTED_CHAIN, }); } } if (Object.values(Network).includes(network as Network)) { return network as Network; } throw new FaceError({ message: `Invalid network parameter: ${network}`, code: FaceErrorCode.UNSUPPORTED_CHAIN, }); } export const getEthlikeChainIdFromNetwork = (network: Network) => { return isEthlikeNetwork(network) ? ethers.utils.hexlify(getChainId(network)) : 0; };