3

I have two client sides (web3 js) linked to the same contract, the previous web3 js version works fine:

function voteForCandidate() {
  candidateName = $("#candidate").val();
  contractInstance.voteForCandidate(candidateName, {from: '0xA07D6641208b3dd97B24F6De81bb939Aec397F0B'}, function() {
    console.log(contractInstance.totalVotesFor.call(candidateName).toString()); // returns correct value
  });
}

But this code, implementing the new version of web3js (1.0.0-beta.33), doesn't:

contractInstance.methods.voteForCandidate(web3.utils.asciiToHex(candidateName))
.call({from: '0xA07D6641208b3dd97B24F6De81bb939Aec397F0B'}, function(error, result) {
    contractInstance.methods.totalVotesFor(web3.utils.asciiToHex(candidateName)).call().then((num_votes) => {
        console.log(num_votes); // returns current value, does't increment
    });
});

It seens to me that contract method voteForCandidate works in previous version (my first example) of web3js, it increments the votesReceived[candidate] value, but doesn't work with newer version, of the client side.

No error is thrown, just doesn't increment.

My Solidity contract is:

pragma solidity ^0.4.11;

contract Voting {

  mapping (bytes32 => uint8) public votesReceived;

  bytes32[] public candidateList;

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

  function totalVotesFor(bytes32 candidate) returns (uint8) {
    if (validCandidate(candidate) == false) throw;
    return votesReceived[candidate];
  }

  function voteForCandidate(bytes32 candidate) {
    if (validCandidate(candidate) == false) throw;
    votesReceived[candidate] += 1; // <-- doesn't increment with the example 2 of client side above
  }

  function validCandidate(bytes32 candidate) returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return true;
      }
    }
    return false;
  }
}
Hula Hula
  • 133
  • 3

1 Answers1

2

See What is the difference between a transaction and a call?. You need to send a transaction, not make a call.

Should be something like this:

contractInstance.methods.voteForCandidate(...).send(...)
user19510
  • 27,999
  • 2
  • 30
  • 48