智能合约编译时 solc.compile() 编译报错

智能合约编译时报错

最近学习智能合约的时候总是遇到很多坑,想着好不容易解决了,就记录一下好了,这里是在node下编译我的Voting.sol文件遇到的错误

……
var solc = require(‘solc’)
var sourceCode = fs.readFileSync(‘Voting.sol’).toString()
var compiledCode = solc.compile(sourceCode)
……

此时我想查看compiledCode,输入 compiledCode 发现报错:
‘{“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”}]}’
查了很多方法,一个是在readFileSync和solc.compile()中加入参数

var sourceCode = fs.readFileSync('Voting.sol','utf-8').toString()
var compiledCode = solc.compile(sourceCode,1)

此时直接弹出ERR_ASSERTION

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: '=='
}

加入参数后回车直接出现报错

当时我用的solc编译器是0.6.9

npm list solc #查看solc版本号

看到有人说编译器版本和solidity合约版本要一致 我当时的sol文件是:
pragma solidity >0.6.8;
又看网上大部分都是使用以前0.4左右的版本,我想了一下,果断决定把solc和和合约都改成以前的版本好了

npm uninstall solc
npm install [email protected]

回到.sol文件一起修改

pragma solidity >=0.4.22 <0.7.0;

又重新试了一下,编译通过

你可能感兴趣的:(智能合约编译时 solc.compile() 编译报错)