一、
编译是对合约进行部署和测试的前置步骤,编译步骤的目标是把源代码转成 ABI 和 Bytecode,并且能够处理编译时抛出的错误,确保不会在包含错误的源代码上进行编译。
1、目录结构
2、合约源码
pragma solidity ^0.4.22;
contract Car {
string public brand;
constructor(string initialBrand) public {
brand = initialBrand;
}
function setBrand(string newBrand) public {
brand = newBrand;
}
}
3、开发编译脚本
const fs = require('fs');
const solc = require('solc');
const path = require('path');
const contractPath = path.resolve(__dirname, '../contracts', 'Car.sol');
const contractSource = fs.readFileSync(contractPath, 'utf-8');
let compileResult = solc.compile(contractSource, 1);
console.log(compileResult);
改良后的脚本,将信息存入指定文件
const fs = require('fs-extra');
const solc = require('solc');
const path = require('path');
const contractPath = path.resolve(__dirname, '../contracts', 'Car.sol');
const contractSource = fs.readFileSync(contractPath, 'utf8');
const compileResult = solc.compile(contractSource, 1);
console.log(compileResult);
Object.keys(compileResult.contracts).forEach(name=>{
let contractName = name.replace(/^:/,'');
let filePath = path.resolve(__dirname, '../compiled', `${contractName}.json`);
fs.outputJsonSync(filePath, compileResult.contracts[name]);
console.log("Saving json file to");
});
加入可清空以前编译过文件的功能
const fs = require('fs-extra');
const solc = require('solc');
const path = require('path');
const compiledPath = path.resolve(__dirname, '../compiled');
fs.removeSync(compiledPath);
fs.ensureDirSync(compiledPath);
const contractPath = path.resolve(__dirname, '../contracts', 'Car.sol');
const contractSource = fs.readFileSync(contractPath, 'utf8');
let compileResult = solc.compile(contractSource, 1);
Object.keys(compileResult.contracts).forEach(name=>{
let contractName = name.replace(/^:/,'');
let filePath = path.resolve(__dirname, '../compiled', `${contractName}.json`);
fs.outputJsonSync(filePath, compileResult.contracts[name]);
console.log("Saving json file to", filePath);
});
最终版,可编译报错
const fs = require('fs-extra');
const path = require('path');
const solc = require('solc');
// cleanup
const compiledDir = path.resolve(__dirname, '../compiled');
fs.removeSync(compiledDir);
fs.ensureDirSync(compiledDir);
// compile
const contractPath = path.resolve(__dirname,
'../contracts', 'Car.sol');
const contractSource = fs.readFileSync(contractPath, 'utf8');
const result = solc.compile(contractSource, 1);
// check errors
if (Array.isArray(result.errors) && result.errors.length) {
throw new Error(result.errors[0]);
}
// save to disk
Object.keys(result.contracts).forEach(name => {
const contractName = name.replace(/^:/, '');
const filePath = path.resolve(compiledDir,
`${contractName}.json`);
fs.outputJsonSync(filePath, result.contracts[name]);
console.log(`save compiled contract ${contractName} to
${filePath}`); });
二、问题解决
问题:
AssertionError [ERR_ASSERTION]: Invalid callback object specified.
解决:
原因:
本地solc版本太高