How to compile solidity using solc 0.5

时光总嘲笑我的痴心妄想 提交于 2019-12-11 05:58:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!