问题
compile.js :
const path = require('path');
const solc = require('solc');
const fs = require('fs-extra');
const buildPath = path.resolve(__dirname, 'build');
fs.removeSync(buildPath);
const campaignPath = path.resolve(__dirname, 'contracts', 'Campaign.sol');
const source = fs.readFileSync(campaignPath, 'utf8');
var input = {
language: 'Solidity',
sources: {
'Campaign.sol': {
content: source
}
},
settings: {
outputSelection: {
'*': {
'*': [ '*' ]
}
}
}
}
const output = solc.compile(input, 1).contracts;
fs.ensureDirSync(buildPath);
for(let contract in output){
fs.outputJSONSync(
path.resolve(buildPath, contract+'.json')
);
}
Campaign.sol :
pragma solidity ^0.5.3;
contract FactoryCampaign {
. . .
}
contract Campaign {
. . .
}
The Solidity works perfectly in remix editor and the solc version is 0.5.3
The solc version 0.4 allowed me to call solc.compile on the 'source' directly but the later versions throw this error
AssertionError [ERR_ASSERTION]: Invalid callback specified.
回答1:
With Solidity compiler version >= 0.5.0, the syntax has changed for calling solc.compile
.
You'll want to use something like this:
const buildPath = path.resolve(__dirname, 'build');
const output = JSON.parse(solc.compile(JSON.stringify(input)));
if(output.errors) {
output.errors.forEach(err => {
console.log(err.formattedMessage);
});
} else {
const contracts = output.contracts["Campaign.sol"];
for (let contractName in contracts) {
const contract = contracts[contractName];
fs.writeFileSync(path.resolve(buildPath, `${contractName}.json`), JSON.stringify(contract.abi, null, 2), 'utf8');
}
}
来源:https://stackoverflow.com/questions/54412333/how-to-compile-solidity-using-solc-0-5