Skip to content

Commit

Permalink
Replace Etherscan ABI lookups with Sourcify
Browse files Browse the repository at this point in the history
Etherscan requires an API key for ABI lookup and other operations.
Sourcify (https://sourcify.dev) is an open-source decentralized alternative.
  • Loading branch information
0237h committed Oct 25, 2024
1 parent 946f9f0 commit 23d6a9c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
30 changes: 28 additions & 2 deletions packages/cli/src/command-helpers/abi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,30 @@ export const loadAbiFromSourcify = async (
ABICtor: typeof ABI,
network: string,
address: string,
): Promise<ABI> =>
await withSpinner(
`Fetching ABI from Sourcify`,
`Failed to fetch ABI from Sourcify`,
`Warnings while fetching ABI from Sourcify`,
async () => {
const chainId = await getSourcifyChainId(network);
const result = await fetch(`https://repo.sourcify.dev/contracts/full_match/${chainId}/${address}/metadata.json`);
const json = await result.json();

// Etherscan returns a JSON object that has a `status`, a `message` and
// a `result` field. The `status` is '0' in case of errors and '1' in
// case of success
if (result.ok) {
return new ABICtor('Contract', undefined, immutable.fromJS(json.output.abi));
}
throw new Error('ABI not found, try loading it from a local file');
},
);

export const loadAbiFromEtherscan = async (
ABICtor: typeof ABI,
network: string,
address: string,
): Promise<ABI> =>
await withSpinner(
`Fetching ABI from Sourcify`,
Expand Down Expand Up @@ -202,8 +226,10 @@ const getSourcifyChainId = async (network: string) => {
// Can fail if network name doesn't follow https://chainlist.org name convention
const match = json.find((e: any) => e.name.toLowerCase().includes(network.replace('-', ' ')));

if (match) return match.chainId;
throw new Error(`Could not find chain id for "${network}"`);
if (match)
return match.chainId;
else
throw new Error(`Could not find chain id for "${network}"`);
};

const getEtherscanLikeAPIUrl = (network: string) => {
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/src/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -707,7 +707,9 @@ async function processInitForm(

// Try loading the ABI from Sourcify, if none was provided
if (protocolInstance.hasABIs() && !initAbi) {
abiFromSourcify = await retryWithPrompt(() => loadAbiFromSourcify(ABI, network, value));
abiFromSourcify = await retryWithPrompt(() =>
loadAbiFromSourcify(ABI, network, value),
);
}
// If startBlock is not set, try to load it.
if (!initStartBlock) {
Expand Down

0 comments on commit 23d6a9c

Please sign in to comment.