Skip to content

Instantly share code, notes, and snippets.

@CJ42
Last active August 18, 2022 07:00
Show Gist options
  • Select an option

  • Save CJ42/aaf59a2614e1dec14eb8a32c68aeb545 to your computer and use it in GitHub Desktop.

Select an option

Save CJ42/aaf59a2614e1dec14eb8a32c68aeb545 to your computer and use it in GitHub Desktop.
The contract JSON ABIs generated by Truffle contain sensitive and private informations: the File system path of the developer’s computer/machine. This scripts remove these sensitive entries and reduces by quite few MB the size of the contracts JSON ABIs in the process. (original source: https://github.com/ERC725Alliance/ERC725/pull/71/commits/1b…
/**
* This script removes source + AST entries inside the JSON artifacts generated by `truffle conpile`
* It will make artifacts files smaller in size (truffle generated ABI files usually
* contain around 5,000 to 20,000 lines).
*
* It is useful when deploying to a package registry like npm, as it helps to:
* - optimize package size
* - generate safer to use artifacts, as some artifact files contain sensitive informations
* (they key "sourcePath" in the artifacts generated by truffle contains the File system path
* of the user that compiled the contracts via `truffle compile` command)
*
* @see Github https://github.com/trufflesuite/truffle/issues/1269
*/
const fs = require('fs');
const TruffleConfig = require('@truffle/config');
// find config file & return new TruffleConfig object with config file settings (cwd)
const truffleConfig = TruffleConfig.detect();
const artifactsFolder = truffleConfig.contracts_build_directory;
function generateSmallerArtifact(_file) {
fs.readFile(_file, (err, fileContent) => {
if (err) console.error(`Error reading file: ${err}`);
let jsonArtifact = JSON.parse(fileContent);
removeSourcesEntries(jsonArtifact);
removeASTEntries(jsonArtifact);
fs.writeFile(_file, JSON.stringify(jsonArtifact), (err) => {
err |
console.log(
'\u2713 Smaller JSON artifact created for -> ',
_file.replace(artifactsFolder + '/', ''),
);
});
});
}
function removeSourcesEntries(_content) {
const sourceEntries = [
'generatedSources',
'deployedGeneratedSources',
'sourceMap',
'deployedSourceMap',
'source',
'sourcePath',
];
sourceEntries.map((entry) => delete _content[entry]);
}
function removeASTEntries(_content) {
const astEntries = ['ast', 'legacyAST'];
astEntries.map((entry) => delete _content[entry]);
}
fs.readdir(artifactsFolder, (err, files) => {
if (err) console.error(`Error reading 'artifacts/' directory: ${err}`);
for (const file of files) {
generateSmallerArtifact(artifactsFolder + '/' + file);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment