合约编译solc.compile()时报错‘{“errors”:[{“component”:“general”,“formattedMessag

1.首先编译脚本是:

const fs = require('fs');
const solc = require('solc');
const path = require('path');

const contractPath = path.resolve(__dirname,'../contracts','Voting.sol');
const contractSource = fs.readFileSync(contractPath,'utf-8');
let compileResult = solc.compile(contractSource);

console.log(compileResult);
~                           

此时输出 compileResult会报错:

‘{“errors”:[{“component”:“general”,“formattedMessage”:"* Line 1, Column 2\n Syntax error: value, object or array expected.\n* Line 1, Column 3\n Extra non-whitespace after JSON value.\n",“message”:"* Line 1, Column 2\n Syntax error: value, object or array expected.\n* Line 1, Column 3\n Extra non-whitespace after JSON value.\n",“severity”:“error”,“type”:“JSONError”}]}’

应将:

let compileResult = solc.compile(contractSource);

改为:

let compileResult = solc.compile(contractSource,1);

1代表:打开solc工具里面的优化器

然后继续编译输出comileResult时候又报错:

Uncaught AssertionError [ERR_ASSERTION]: Invalid callback object specified.
    at runWithCallbacks (/simple_voting_dapp/node_modules/solc/wrapper.js:97:7)
    at compileStandard (/simple_voting_dapp/node_modules/solc/wrapper.js:207:14)
    at Object.compileStandardWrapper [as compile] (/simple_voting_dapp/node_modules/solc/wrapper.js:214:14)
    at repl:1:25
    at Script.runInThisContext (vm.js:120:20)
    at REPLServer.defaultEval (repl.js:433:29)
    at bound (domain.js:426:14)
    at REPLServer.runBound [as eval] (domain.js:439:12)
    at REPLServer.onLine (repl.js:760:10)
    at REPLServer.emit (events.js:327:22)
    at REPLServer.EventEmitter.emit (domain.js:482:12)
    at REPLServer.Interface._onLine (readline.js:329:10)
    at REPLServer.Interface._line (readline.js:658:8)
    at REPLServer.Interface._ttyWrite (readline.js:999:14)
    at REPLServer.self._ttyWrite (repl.js:851:9)
    at ReadStream.onkeypress (readline.js:205:10) {
  generatedMessage: false,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: '=='
}
  • 查询了资料说solidity合约的编译版本要和solc编译版本一致,我试了一试 ,将solc版本改为0.4.22,同时将solidity版本改为>=0.4.22 <0.7.0 ,最后编译通过了,得到了compileResult.

但是此方法终究治标不治本啊,对于新版本的solc和solidity的编译版本如何是好?

正确的解决办法:

也可以查看:ethereum/solc-js: Javascript bindings for the Solidity compiler (github.com)https://github.com/ethereum/solc-js#readme

将编译的脚本改为:

const fs = require('fs');
const solc = require('solc');
const path = require('path');

const contractPath = path.resolve(__dirname,'../contracts','Voting.sol');
const contractSource = fs.readFileSync(contractPath,'utf-8');

var input = {
  language: 'Solidity',
  sources: {
    'Voting.sol': {
      content: contractSource
    }
  },
  settings: {
    outputSelection: {
      '*': {
        '*': ['*']
      }
    }
  }
};

var compileResult = JSON.parse(solc.compile(JSON.stringify(input)));

console.log(compileResult);

最终成功!!!

你可能感兴趣的:(区块链,react.js,区块链,智能合约)