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 {
. . .
}
Solidity在混音编辑器中可以完美工作,而solc版本是0.5.3
solc版本0.4允许我直接在“源”上调用solc.compile,但更高版本抛出此错误
AssertionError [ERR_ASSERTION]:指定了无效的回调。
最佳答案
对于Solidity编译器版本> = 0.5.0,调用solc.compile
的语法已更改。
您将要使用以下内容:
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');
}
}