Skip to content

Commit 855cad5

Browse files
sanbirimqdee
authored andcommitted
chore: improve etherscan v2 chainid and error handling
1 parent f64be16 commit 855cad5

2 files changed

Lines changed: 13 additions & 7 deletions

File tree

util/EtherscanApi.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
1-
const ETHERSCAN_URL = 'https://api.etherscan.io/v2/api?'
1+
const ETHERSCAN_URL = 'https://api.etherscan.io/v2/api'
2+
const ETHERSCAN_CHAIN_ID = process.env.ETHERSCAN_CHAIN_ID || '1'
23

34
export async function etherscanRequest(
45
module: string,
56
action: string,
67
params: object,
78
) {
8-
const query: any = {
9-
chainid: 1,
10-
apikey: process.env.APIKEY_ETHERSCAN,
9+
const query: Record<string, string> = {
10+
chainid: ETHERSCAN_CHAIN_ID,
11+
apikey: process.env.APIKEY_ETHERSCAN || '',
1112
module: module,
1213
action: action,
13-
...params,
1414
}
1515

16-
const url = ETHERSCAN_URL + new URLSearchParams(query)
16+
Object.entries(params).forEach(([key, value]) => {
17+
query[key] = String(value)
18+
})
19+
20+
const url = `${ETHERSCAN_URL}?${new URLSearchParams(query)}`
1721
return fetch(url)
1822
}
1923

util/EtherscanParser.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ export function etherscanParse(
1111
response: EtherscanResponse,
1212
): EtherscanContractResponse {
1313
if (response.message !== 'OK') {
14-
throw 'etherscan response is not OK'
14+
const reason =
15+
typeof response.result === 'string' ? response.result : response.message
16+
throw `etherscan response is not OK: ${reason}`
1517
}
1618

1719
if (!response.result || response.result.length == 0) {

0 commit comments

Comments
 (0)