Skip to content

Commit

Permalink
Move to etherscan v2
Browse files Browse the repository at this point in the history
  • Loading branch information
portdeveloper committed Oct 31, 2024
1 parent b7a03b0 commit 2c861be
Showing 1 changed file with 3 additions and 35 deletions.
38 changes: 3 additions & 35 deletions packages/nextjs/utils/abi.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,11 @@
import { NETWORKS_EXTRA_DATA } from "./scaffold-eth";
import { isZeroAddress } from "./scaffold-eth/common";
import { Address } from "viem";
import * as chains from "viem/chains";

const findChainById = (chainId: number): chains.Chain => {
const chainEntries = Object.entries(chains as Record<string, chains.Chain>);

for (const [, chain] of chainEntries) {
if (chain.id === chainId) {
return chain;
}
}

throw new Error(`No chain found with ID ${chainId}`);
};

const getEtherscanApiKey = (chainId: number): string => {
const networkData = NETWORKS_EXTRA_DATA[chainId];

if (!networkData || !networkData.etherscanApiKey) {
console.warn(`No API key found for chain ID ${chainId}`);
return "";
}

return networkData.etherscanApiKey;
};

export const fetchContractABIFromEtherscan = async (verifiedContractAddress: Address, chainId: number) => {
const chain = findChainById(chainId);

if (!chain || !chain.blockExplorers?.default?.apiUrl) {
throw new Error(`ChainId ${chainId} not found in supported networks or missing block explorer API URL`);
}

const apiKey = getEtherscanApiKey(chainId);
const apiKeyUrlParam = apiKey.trim().length > 0 ? `&apikey=${apiKey}` : "";
const apiKey = process.env.NEXT_PUBLIC_MAINNET_ETHERSCAN_API_KEY;

// First call to get source code and check for implementation
const sourceCodeUrl = `${chain.blockExplorers.default.apiUrl}?module=contract&action=getsourcecode&address=${verifiedContractAddress}${apiKeyUrlParam}`;
const sourceCodeUrl = `https://api.etherscan.io/v2/api?chainid=${chainId}&module=contract&action=getsourcecode&address=${verifiedContractAddress}&apikey=${apiKey}`;

const sourceCodeResponse = await fetch(sourceCodeUrl);
const sourceCodeData = await sourceCodeResponse.json();
Expand All @@ -52,7 +20,7 @@ export const fetchContractABIFromEtherscan = async (verifiedContractAddress: Add

// If there's an implementation address, make a second call to get its ABI
if (implementation && !isZeroAddress(implementation)) {
const abiUrl = `${chain.blockExplorers.default.apiUrl}?module=contract&action=getabi&address=${implementation}${apiKeyUrlParam}`;
const abiUrl = `https://api.etherscan.io/v2/api?chainid=${chainId}&module=contract&action=getabi&address=${implementation}&apikey=${apiKey}`;
const abiResponse = await fetch(abiUrl);
const abiData = await abiResponse.json();

Expand Down

0 comments on commit 2c861be

Please sign in to comment.