Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code not compiling in nodejs,throws out an unexpected error(Web3.js)

I tried following this repo:-

But I am getting the following error on compiling the code with :-

code = fs.readFileSync('Voting.sol').toString()
solc = require('solc')
compiledCode = solc.compile(code)

It throws out this error:-

'{"errors":[{"component":"general","formattedMessage":"* Line 1, Column 1\\n  Syntax error: value, object or array expected.\\n* Line 1, Column 2\\n  Extra non-whitespace after JSON value.\\n","message":"* Line 1, Column 1\\n  Syntax error: value, object or array expected.\\n* Line 1, Column 2\\n  Extra non-whitespace after JSON value.\\n","severity":"error","type":"JSONError"}]}'
like image 328
abhinayak Avatar asked Nov 21 '18 09:11

abhinayak


2 Answers

I found that if you put your input info into the JSON format per the solidity docs, then you are good regardless of the compiler. Before compiling "stringify" the file (JSON.stringify). After the file is compiled the object will be in string form, so then you may want to parse it (JSON.parse) to work with it from there. Here is a code sample with a console.log() of the contract in JSON form so you can see what you are working with.

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


const inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');
const source = fs.readFileSync(inboxPath, 'utf8');

var solcInput = {
    language: "Solidity",
    sources: { 
        contract: {
            content: source
        }
     },
    settings: {
        optimizer: {
            enabled: true
        },
        evmVersion: "byzantium",
        outputSelection: {
            "*": {
              "": [
                "legacyAST",
                "ast"
              ],
              "*": [
                "abi",
                "evm.bytecode.object",
                "evm.bytecode.sourceMap",
                "evm.deployedBytecode.object",
                "evm.deployedBytecode.sourceMap",
                "evm.gasEstimates"
              ]
            },
        }
    }
};

solcInput = JSON.stringify(solcInput);
var contractObject = solc.compile(solcInput);
contractObject = JSON.parse(contractObject);

console.log(contractObject);
like image 67
orangejuicejones Avatar answered Nov 18 '22 19:11

orangejuicejones


The version of solc and your contract should be the same.

For example, if your contract uses pragma solidity ^0.4.18; then you should install the same version of solc Using npm install [email protected].

like image 8
WongJoe Avatar answered Nov 18 '22 18:11

WongJoe