[Ethereum] Deploy smart-contract using nodejs

nodejssolcsolidity

I am trying to follow the following example.

http://hypernephelist.com/2016/12/13/compile-deploy-ethereum-smart-contract-web3-solc.html

But I get the following error. Can anybody show me what is wrong in my code? Thanks.

$ cat contracts/HelloWorld.sol 
pragma solidity ^0.4.16;
contract HelloWorld {
  function get() public pure returns (string retVal) {
    return "HelloWorld!!";
  }
}

$ cat test.js 
const fs = require('fs')
const input = fs.readFileSync('contracts/HelloWorld.sol', 'utf8');

const solc = require('solc')
const output = solc.compile(input, 1);
const bytecode = output.contracts[':HelloWorld'].bytecode;
const abi = JSON.parse(output.contracts[':HelloWorld'].interface);

const Web3 = require('web3')
const web3 = new Web3('ws://localhost:8546');

web3.eth.getAccounts().then((accounts) => { 
  const testContract = new web3.eth.Contract(abi);
  testContract.deploy({
    data: "0x" + bytecode,
  })
    .send({from: accounts[0], gas: 4700000})
    .then((instance) => {
      console.log(`Address: ${instance.options.address}`);
    })
    .catch(console.log);
});
$ node  test.js 
connection not open on send()
(node:11309) UnhandledPromiseRejectionWarning: Error: connection not open
    at WebsocketProvider.send (/Users/pengy/linux/test/gnu/geth/bin/Hello-Ethereum/node_modules/web3-providers-ws/src/index.js:211:18)
    at Timeout._onTimeout (/Users/pengy/linux/test/gnu/geth/bin/Hello-Ethereum/node_modules/web3-providers-ws/src/index.js:196:19)
    at ontimeout (timers.js:466:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:267:5)
(node:11309) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11309) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Best Answer

You're parsing the ABI twice.

const abi = JSON.parse(output.contracts[':HelloWorld'].interface);

and here

const testContract = web3.eth.contract(JSON.parse(abi));

just change the second line and remove the JSON.parse the error gonna be solved.

But consider that if you're using web3 1.0 (which come by default if you install the package now) that code wouldn't work properly. The syntax is different and you might need to change it properly:

const Web3 = require('web3')
const web3 = new Web3("http://localhost:8545");

web3.eth.getAccounts().then((accounts) => { 
  const testContract = new web3.eth.Contract(abi);
  testContract.deploy({
    data: "0x" + bytecode,
  })
  .send({from: accounts[0], gas: 4700000})
  .then((instance) => {
    console.log(`Address: ${instance.options.address}`);
  })
  .catch(console.log);
});
Related Topic