0

I am trying to make updates to a standard voting dapp. My aim is to list out voter who has voted for a candidate. So far I have implemented the following:

voting.sol:

struct voter {
    bytes32 votedFor;
    bool hasVoted;
}

mapping (bytes32 => uint8) public votesReceived;
// Mapping for persons who have already voted
mapping (bytes32 => voter) public voters;   
function lookUpVoter(bytes32 hashedVoter) view public returns (bytes32){
  bytes32 candidateDetails = voters[hashedVoter].votedFor;
  return candidateDetails;
}

index.js:

function lookUpVoter(){
    voterName = $("#voter-info").val();
    var vals = contractInstance.lookUpVoter.call(voterName);
    $("#votes-cast").html(vals);

}

The output i am receiving from index.js is hashvalue "0x4b6576696e204200000000000000000000000000000000000000000000000000". I need the candidate name instead. Please help me identifying what I am missing from the code.

Thank you!!

0

The output is not a hash, it is a bytes32.

You just need to call the toAscii function from Web3.js:

var str = "0x4b6576696e204200000000000000000000000000000000000000000000000000"

web3.toAscii(str.slice(0,18))

"Kevin B"

Note we only need the first 16 characters of the hexadecimal for 32 bytes, which means 18 characters total if you include 0x, hence the use of the slice() function.

See documentation here.

Or for Web3.js 1.0, use web3.utils.hexToAscii as documented here.

  • take a look at the update where I use the slice function to get rid of unnecessary characters :) – Shawn Tabrizi Jul 30 '18 at 18:38
0

That's not a hashvalue, that's the string you're looking, it's just hex encoded. If you just plug the hex string into the function web3.toAscii, it'll return the ascii version of it.

  • I will be changing my code in index.js : – softwareDeveloperInProgress Jul 30 '18 at 18:32
  • function lookUpVoter(){ voterName = $("#voter-info").val(); var vals = contractInstance.lookUpVoter.call(voterName); var out = web3.utils.toAscii(vals); $("#votes-cast").html(out); } --- is this correct? I am new to solidity so I am unware of the usage. Please help!! – softwareDeveloperInProgress Jul 30 '18 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.