Invalid opcode error in a simple Solidity contract and script

0 votes

I am following the tutorial here -

to build a simple Voting Dapp. I've installed ganache-cli, solc and web3 version 0.20.2 in the local node_modules folder using npm. The Voting.sol contract in Solidity is :

pragma solidity ^0.4.18;

contract Voting {

  mapping (bytes32 => uint8) public votesReceived;
  bytes32[] public candidateList;

  function Voting(bytes32[] candidateNames) public {
    candidateList = candidateNames;

  function totalVotesFor(bytes32 candidate) view public returns (uint8) {
    return votesReceived[candidate];

with the following script called voting_main.js:

Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))

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

solc = require('solc')
compiledCode = solc.compile(code)

abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface)
VotingContract = web3.eth.contract(abiDefinition)
byteCode = compiledCode.contracts[':Voting'].bytecode
deployedContract =['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000})
contractInstance ='Rama')

When I run ganache-cli on localhost:8545 and then run the script in another terminal, I get the following error.

ameya@ameya-HP-ENVY-15-Notebook-PC:~/Fresh_install$ node voting_main.js 
(function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath["normalize"](filename);var ret=nodeFS["readFileSync"](filename);if(!r

Error: VM Exception while processing transaction: invalid opcode
    at Object.InvalidResponse (/home/ameya/Fresh_install/node_modules/web3/lib/web3/errors.js:38:16)
    at RequestManager.send (/home/ameya/Fresh_install/node_modules/web3/lib/web3/requestmanager.js:61:22)
    at Eth.send [as call] (/home/ameya/Fresh_install/node_modules/web3/lib/web3/method.js:145:58)
    at (/home/ameya/Fresh_install/node_modules/web3/lib/web3/function.js:135:32)
    at Object.<anonymous> (/home/ameya/Fresh_install/voting_main.js:16:32)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
    at Function.Module._load (internal/modules/cjs/loader.js:498:3)

Can someone tell me how to solve this?

Sep 14, 2018 in Blockchain by digger
• 26,740 points

retagged Nov 22, 2018 by Priyaj 4,473 views

1 answer to this question.

0 votes

You don't need to call .at() if you're using .new(). You use at() when you want to interact with a contract that has already been deployed to the blockchain.

If you choose to deploy a new contract, you should use the async version of the method call (synchronous is no longer supported in web3j 1.0). Your call should be something like this:['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000}, (error, deployedContract) => {
    if (!error) {
        if (deployedContract.address) {

Note that the callback is fired twice. First time is for the submission of the transaction (deployedContract.transactionHash will be set) and the second time after the transaction is mined.

You can also look at the example in the web3js docs (pasted below for convenience).

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

let source = fs.readFileSync('nameContract.sol', 'utf8');
let compiledContract = solc.compile(source, 1);
let abi = compiledContract.contracts['nameContract'].interface;
let bytecode = compiledContract.contracts['nameContract'].bytecode;
let gasEstimate = web3.eth.estimateGas({data: bytecode});
let MyContract = web3.eth.contract(JSON.parse(abi));

var myContractReturned =, param2, {
   gas:gasEstimate}, function(err, myContract){
    if(!err) {
       // NOTE: The callback will fire twice!
       // Once the contract has the transactionHash property set and once its deployed on an address.

       // e.g. check tx hash on the first call (transaction send)
       if(!myContract.address) {
           console.log(myContract.transactionHash) // The hash of the transaction, which deploys the contract

       // check address on the second call (contract deployed)
       } else {
           console.log(myContract.address) // the contract address

       // Note that the returned "myContractReturned" === "myContract",
       // so the returned "myContractReturned" object will also get the address set.
answered Sep 14, 2018 by slayer
• 29,360 points

Related Questions In Blockchain

0 votes
1 answer
0 votes
1 answer

How to get all address and send ethers in solidity using a loop?

I found a similar code somewhere: contract  Holders{ uint ...READ MORE

answered Jul 31, 2018 in Blockchain by digger
• 26,740 points
+1 vote
3 answers

What is the pattern for handling throw on a Solidity contract in tests

In my opinion the cleanest way is: it("should ...READ MORE

answered Sep 25, 2018 in Blockchain by Lupin
0 votes
1 answer

Solidity mocha : address is not a contract error

Try the following: // Initialize contract variable with ...READ MORE

answered Oct 1, 2018 in Blockchain by digger
• 26,740 points
0 votes
1 answer

Truffle tests not running after truffle init

This was a bug. They've fixed it. ...READ MORE

answered Sep 11, 2018 in Blockchain by Christine
• 15,790 points
+1 vote
3 answers

Removing double quotes from a string from JSON response in PHP

Just remove the json_encode call, and it should work: $resp ...READ MORE

answered Sep 12, 2018 in Blockchain by digger
• 26,740 points
0 votes
1 answer

How do I add multiple recipients for transactions via Blockchain API?

Convert the recipes into JSON objects. x = ...READ MORE

answered Jul 6, 2018 in Blockchain by Perry
• 17,100 points
0 votes
1 answer

Solidity invalid opcode error

In the for loop, your indexing going ...READ MORE

answered Aug 16, 2018 in Blockchain by slayer
• 29,360 points
0 votes
1 answer

Truffle tutorials "Error:recipient address is not a contract address"

It appears like you have already migrated ...READ MORE

answered Aug 8, 2018 in Blockchain by slayer
• 29,360 points
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP