@@ -3,12 +3,16 @@ import {
33 getChainByChainIdAsync ,
44 getChainBySlugAsync ,
55} from "@thirdweb-dev/chains" ;
6+ import { StatusCodes } from "http-status-codes" ;
67import { getConfig } from "../../utils/cache/getConfig" ;
78import { networkResponseSchema } from "../../utils/cache/getSdk" ;
89import { logger } from "../../utils/logger" ;
10+ import { createCustomError } from "../middleware/error" ;
911
1012/**
1113 * Given a valid chain name ('Polygon') or ID ('137'), return the numeric chain ID.
14+ *
15+ * @throws if the chain is invalid or deprecated.
1216 */
1317export const getChainIdFromChain = async ( input : string ) : Promise < number > => {
1418 const inputSlug = input . toLowerCase ( ) ;
@@ -40,21 +44,27 @@ export const getChainIdFromChain = async (input: string): Promise<number> => {
4044 }
4145 }
4246
43- if ( ! isNaN ( inputId ) ) {
44- // Fetch by chain ID.
45- const chainData = await getChainByChainIdAsync ( inputId ) ;
46- if ( chainData && chainData . status !== "deprecated" ) {
47- return chainData . chainId ;
48- }
49- } else {
50- // Fetch by chain name.
51- const chainData = await getChainBySlugAsync ( inputSlug ) ;
52- if ( chainData && chainData . status !== "deprecated" ) {
53- return chainData . chainId ;
47+ // Fetch by chain ID or slug.
48+ // Throw if the chain is invalid or deprecated.
49+ try {
50+ const chain = ! isNaN ( inputId )
51+ ? await getChainByChainIdAsync ( inputId )
52+ : await getChainBySlugAsync ( inputSlug ) ;
53+
54+ if ( chain . status === "deprecated" ) {
55+ throw createCustomError (
56+ `Chain ${ input } is deprecated` ,
57+ StatusCodes . BAD_REQUEST ,
58+ "INVALID_CHAIN" ,
59+ ) ;
5460 }
55- }
5661
57- throw new Error (
58- `Invalid or deprecated chain. Please confirm this is a valid chain: https://thirdweb.com/${ input } ` ,
59- ) ;
62+ return chain . chainId ;
63+ } catch ( e ) {
64+ throw createCustomError (
65+ `Chain ${ input } is not found` ,
66+ StatusCodes . BAD_REQUEST ,
67+ "INVALID_CHAIN" ,
68+ ) ;
69+ }
6070} ;
0 commit comments