[Ethereum] Truffle Error : VM Exception while processing transaction: revert

soliditytruffletruffle-contractweb3js

I am trying to call following function of smart contract from App.js:

function addCandidate(bytes32 _name, bytes32 _party) public{
    //require(msg.sender == votingAdmin);
    //if(msg.sender != votingAdmin) throw;
    candidates.length++;
    candidates[candidates.length-1].id = candidates.length-1;
    candidates[candidates.length-1].name = _name;
    candidates[candidates.length-1].party = _party;
    LogNewCandidate(msg.sender,candidates.length-1,_name,_party);
}

Code in App.js is :-

Voting2.deployed().then(function(contractInstance) {
    var candidate_name = document.getElementById('candidate_name').value;
    var candidate_party = document.getElementById('candidate_party').value;
    contractInstance.addCandidate(candidate_name,candidate_party,{from: web3.eth.accounts[0], gas:3000000}).then(function(v) {
        console.log(v.toString());
    });
});

Error –

Error: VM Exception while processing transaction: revert
    at XMLHttpRequest._onHttpResponseEnd (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
    at XMLHttpRequest._setReadyState (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
    at XMLHttpRequestEventTarget.dispatchEvent (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
    at XMLHttpRequest.request.onreadystatechange (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
    at /home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1
    at /home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
    at Object.InvalidResponse (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)

However there is another function written in smart contract and I am successfully able to call it

function getCandidatesCount() public constant returns(uint) {
    return candidates.length;
}

Code in App.js

Voting2.deployed().then(function(contractInstance) {
  contractInstance.getCandidatesCount.call().then(function(v) {
    console.log(v.toString());
  });
});

So, I am not able to execute transaction but I am able to read value returned from a function.

Best Answer

If the error is generated when those two lines of your method are commented then you have a problem with one of these lines

candidates.length++;
candidates[candidates.length-1].id = candidates.length-1;
candidates[candidates.length-1].name = _name;
candidates[candidates.length-1].party = _party;

So either :

  1. your candidates state variable is not an array.
  2. candidates.length-1 is less than 0 ( probably the case if your array is empty at the start)