bytes32 to string in javascript
Asked Answered
C

1

7

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

Californium answered 4/12, 2017 at 10:58 Comment(1)
Can you include the code that deploys your contract?Frowzy
N
14

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"
Nathanaelnathanial answered 5/12, 2017 at 9:56 Comment(1)
In current version of web3 you should call web3Provider.utils.toAscii()Goldeye

© 2022 - 2024 — McMap. All rights reserved.