Created
April 8, 2023 08:36
-
-
Save vsmelov/f7bd91bc51e8c42018e7bbf7c8d3c8da to your computer and use it in GitHub Desktop.
download verified contracts to the local files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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