Skip to content

Instantly share code, notes, and snippets.

@vsmelov
Created April 8, 2023 08:36
Show Gist options
  • Save vsmelov/f7bd91bc51e8c42018e7bbf7c8d3c8da to your computer and use it in GitHub Desktop.
Save vsmelov/f7bd91bc51e8c42018e7bbf7c8d3c8da to your computer and use it in GitHub Desktop.
download verified contracts to the local files
// run via `node scripts/utils/getVerifiedContract.js`
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const contractAddress = '0x46a15b0b27311cedf172ab29e4f4766fbe7f4364';
const apiKey = process.env.BSCSCAN_TOKEN;
const baseUrl = 'https://api.bscscan.com/api';
async function getVerifiedContractCode(address) {
try {
const url = `${baseUrl}?module=contract&action=getsourcecode&address=${address}&apikey=${apiKey}`;
const response = await axios.get(url);
if (response.data.status === '1') {
const contractData = response.data.result[0];
const solidityCode = contractData.SourceCode;
const solidityCodeFixed = solidityCode.replace('{{', '{').replace('}}', '}');
const solidityCodeJson = JSON.parse(solidityCodeFixed);
const downloadsFolder = './downloads';
if (!fs.existsSync(downloadsFolder)) {
fs.mkdir(downloadsFolder, (err) => {
if (err) throw err;
console.log(`Folder '${downloadsFolder}' created successfully.`);
});
} else {
console.log(`Folder '${downloadsFolder}' already exists.`);
}
for (const key in solidityCodeJson.sources) {
const baseName = path.basename(key);
const toSave = path.join(downloadsFolder, baseName);
const jsonString = JSON.stringify(solidityCodeJson.sources[key], null, 2);
fs.writeFile(toSave, jsonString, (err) => {
if (err) {
console.error('Error saving file:', err);
} else {
console.log(`${key} saved to ${toSave}`);
}
});
}
} else {
console.error('Cannot get contract source code');
}
} catch (error) {
console.error('Error:', error);
}
}
getVerifiedContractCode(contractAddress);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment