@@ -3,12 +3,16 @@ import {
3
3
getChainByChainIdAsync ,
4
4
getChainBySlugAsync ,
5
5
} from "@thirdweb-dev/chains" ;
6
+ import { StatusCodes } from "http-status-codes" ;
6
7
import { getConfig } from "../../utils/cache/getConfig" ;
7
8
import { networkResponseSchema } from "../../utils/cache/getSdk" ;
8
9
import { logger } from "../../utils/logger" ;
10
+ import { createCustomError } from "../middleware/error" ;
9
11
10
12
/**
11
13
* Given a valid chain name ('Polygon') or ID ('137'), return the numeric chain ID.
14
+ *
15
+ * @throws if the chain is invalid or deprecated.
12
16
*/
13
17
export const getChainIdFromChain = async ( input : string ) : Promise < number > => {
14
18
const inputSlug = input . toLowerCase ( ) ;
@@ -40,21 +44,27 @@ export const getChainIdFromChain = async (input: string): Promise<number> => {
40
44
}
41
45
}
42
46
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
+ ) ;
54
60
}
55
- }
56
61
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
+ }
60
70
} ;
0 commit comments