Solidity compiler - problem with HelloWorld smart contract

我们两清 提交于 2019-12-23 05:15:37

问题


Im trying to run my first HelloWorld smart contract on the Enthereum network. This is my HelloWorld.sol contract.

pragma solidity ^0.5.0;

contract HelloWorld {
  bytes32 message;
  constructor (bytes32 myMessage) public {
    message = myMessage;
  }
  function getMessage() public returns(bytes32) {
    return message;
  }
}

When I try to build this using solcjs HelloWorld.sol --bin, there is just one Warning and no errors. I have installed web3 and solc using npm. When I run this on a node

var solc = require('solc');
var x = fs.readFileSync('./HelloWorld.sol').toString();
var compiledContract = solc.compile(x);

the compiledContractcontains this:

'{"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"}]}'

Where is the problem?


回答1:


The problem was, that you I can not put raw solidity smart contract into solc.compile() function. There must be Compiler Standard Input JSON. Based on my another thread I found this solution:

> var Web3 = require('web3');
> var solc = require('solc');
> var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
> var CONTRACT_FILE = 'HelloWorld.sol'
> var content =fs.readFileSync(CONTRACT_FILE).toString()
> var input = {
  language: 'Solidity',
  sources: {
    [CONTRACT_FILE]: {
      content: content
    }
  },
  settings: {
    outputSelection: {
      '*': {
        '*': ['*']
      }
    }
  }
}

> var compiled = solc.compile(JSON.stringify(input))
> var output = JSON.parse(compiled)
> var abi = output.contracts[CONTRACT_FILE]['HelloWorld'].abi
> var bytecode = output.contracts[CONTRACT_FILE]['HelloWorld'].evm.bytecode.object
> var HelloWorld = new web3.eth.Contract(abi);
> var HelloWorldTx = HelloWorld.deploy({data: bytecode, arguments: [web3.utils.asciiToHex('Hello')]});
> web3.eth.estimateGas(HelloWorldTx).then(console.log); //this does not work, because it can not connect to the localhost:8545. I don't know why.
> HelloWorldTx.send({from: '0x99d54a45f2cd3b9c6443d623003416aaf944338e', gas: 1000000}).then(console.log);


来源:https://stackoverflow.com/questions/53461034/solidity-compiler-problem-with-helloworld-smart-contract

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