Skip to content

Commit 40cc35a

Browse files
author
ci-bot
committed
fix: improve Etherscan API with proper chainId handling and V1 fallback
- Extract chainId from Network object when available instead of hardcoding to 1 - Add fallback mechanism to handle networks that don't support V2 API yet - Gracefully handle deprecated V1 endpoint responses - Maintain backward compatibility with both string and Network endpoint types This ensures the fix works across all Etherscan network endpoints while providing robust error handling and fallback support.
1 parent d180428 commit 40cc35a

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

libs/remix-core-plugin/src/lib/helpers/fetch-etherscan.ts

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,33 @@ export const fetchContractFromEtherscan = async (plugin, endpoint: string | Netw
1111
if (!etherscanKey) etherscanKey = '2HKUX5ZVASZIKWJM8MIQVCRUVZ6JAWT531'
1212

1313
if (etherscanKey) {
14+
// Extract chain ID from Network object before converting to string
15+
let chainId = 1 // Default to Ethereum mainnet
1416
if (typeof endpoint === 'object' && endpoint !== null && 'id' in endpoint && 'name' in endpoint) {
17+
chainId = endpoint.id
1518
endpoint = endpoint.id == 1 ? 'api.etherscan.io' : 'api-' + endpoint.name + '.etherscan.io'
1619
}
1720
try {
18-
// Use V2 API with chainid parameter (defaults to mainnet)
19-
const chainId = 1 // Default to Ethereum mainnet
20-
data = await fetch('https://' + endpoint + '/v2/api?chainid=' + chainId + '&module=contract&action=getsourcecode&address=' + contractAddress + '&apikey=' + etherscanKey)
21+
// Try V2 API first with chainid parameter
22+
let apiUrl = 'https://' + endpoint + '/v2/api?chainid=' + chainId + '&module=contract&action=getsourcecode&address=' + contractAddress + '&apikey=' + etherscanKey
23+
data = await fetch(apiUrl)
24+
25+
// If V2 API fails (404 or other error), fallback to V1 API
26+
if (!data.ok) {
27+
apiUrl = 'https://' + endpoint + '/api?module=contract&action=getsourcecode&address=' + contractAddress + '&apikey=' + etherscanKey
28+
data = await fetch(apiUrl)
29+
}
30+
2131
data = await data.json()
32+
33+
// Handle deprecated V1 endpoint response
34+
if (data.message === 'NOTOK' && data.result && data.result.includes('deprecated V1 endpoint')) {
35+
// Force V2 API usage even if it initially failed
36+
apiUrl = 'https://' + endpoint + '/v2/api?chainid=' + chainId + '&module=contract&action=getsourcecode&address=' + contractAddress + '&apikey=' + etherscanKey
37+
data = await fetch(apiUrl)
38+
data = await data.json()
39+
}
40+
2241
// etherscan api doc https://docs.etherscan.io/api-endpoints/contracts
2342
if (data.message === 'OK' && data.status === "1") {
2443
if (data.result.length) {

0 commit comments

Comments
 (0)