在以太坊中部署智能合约时如何解决错误?

时间:2018-12-28 03:09:33

标签: node.js npm node-modules ethereum solidity

当尝试使用solc-js编译智能合约时,我得到了错误

克里希纳:投票给krishnakankipati $节点deploy.js  编制合同  assert.js:350      犯错^
AssertionError [ERR_ASSERTION]:指定了无效的回调。

let compilerInput = {
     'Voter': fs.readFileSync('Voter.sol', 'utf8')
};

console.log('Compiling the contract')
// Compile and optimize the contract
let compiledContract = solc.compile(compilerInput, 1);

// Get compiled contract
let contract = compiledContract.contracts['Voter:Voter'] // Voter contract from Voter file.

 // Save contract's ABI
let abi = contract.interface;
fs.writeFileSync('abi.json', abi);

2 个答案:

答案 0 :(得分:2)

您没有正确使用solc-js。您需要对输入进行字符串化,然后传递1而不是导入回调。在发布问题之前,请先阅读文档:https://github.com/ethereum/solc-js

考虑使用etherjs,比web3更好的文档和更强大的功能。

答案 1 :(得分:1)

请务必阅读solc v0.5.0 +的solc docs,以确保您正在调整对Solidity编译器的更改。

类似这样的东西应该与solc的最新版本兼容:

// Note: You should be defining your contract sources as objects now.
// Note: You must also provide the compiler output selection as well.
const compilerInput = {
    language: "Solidity",
    sources: {
        'Voter': { content: fs.readFileSync('Voter.sol', 'utf8') }
    },
    settings: {
      outputSelection: {
        "*": {
          "*": [ "abi", "evm.bytecode" ]
        }
      }
    }
};

console.log('Compiling the contract')
// Note: You have to pass the input in with JSON.stringify now.
const compiledContract = JSON.parse(solc.compile(JSON.stringify(compilerInput)));

if(compiledContract.errors) {
    compiledContract.errors.forEach(err => console.log(err.formattedMessage));
}

// Note: This changed slightly since I'm using JSON.parse above.
const contract = compiledContract.contracts['Voter'].Voter; // Voter contract from Voter file.

// Note: This is now called 'abi' and not 'interface'
const abi = contract.abi;
fs.writeFileSync('abi.json', JSON.stringify(abi, null, 2));

您还需要更新deployContract函数以与solc v0.5.0 +同步

async function deployContract(web3, contract, sender) {
    let Voter = new web3.eth.Contract(JSON.parse(JSON.stringify(abi)));
    let bytecode = '0x' + contract.evm.bytecode.object;
    let gasEstimate = await web3.eth.estimateGas({data: bytecode});

    // The rest should work fine...
}