Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bytes32 to string in javascript

currently i'm working on a ethereum dapp(voting), in my smart contract i have a function to fetch candidate list of type bytes32[] , on the java script side i'm not getting the values instead 0x only How to parse the value , below is the code

pragma solidity ^0.4.0;


contract Voting {


  mapping (bytes32 => uint8) public votesReceived;



  bytes32[] public candidateList;
string myString = "someString";



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

  }


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

  function addCandidate(bytes32 candidate)  public returns (bool){
    require(isNewEntry(candidate));
    candidateList.push(candidate);
    return isNewEntry(candidate);
  }

  function voteForCandidate(bytes32 candidate) public {
    require(validCandidate(candidate));
    votesReceived[candidate] += 1;
  }

  function getCandidateList() view public returns (bytes32[]) {
return candidateList;
  }

  function isNewEntry(bytes32 candidate) view public returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
        if (candidateList[i] == candidate) {
            return false;
        }
    }
    return true;
  }

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

below is the code to access the contract function

Voting.deployed().then(function(contractInstance) {
    contractInstance.getCandidateList.call().then(function(v) {
    console.log(v)
    });
  })

someone please help me

like image 406
Rahul Avatar asked Dec 04 '17 10:12

Rahul


1 Answers

Assuming you're using web3 on the JS side, it's web3.toAscii.

Example from the docs:

var str = web3.toAscii("0x657468657265756d000000000000000000000000000000000000000000000000");
console.log(str); // "ethereum"
like image 161
Michael Kohl Avatar answered Sep 25 '22 14:09

Michael Kohl