JavaScript中将bytes32转换为字符串

7

我正在开发一个以太坊dapp(投票)应用,我的智能合约中有一个函数来获取候选人列表,类型为bytes32[]。但是在 JavaScript 方面,我没有获取到值,只得到了 0x。如何解析这个值,以下是代码:

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;
  }
}

以下是访问合约函数的代码。
Voting.deployed().then(function(contractInstance) {
    contractInstance.getCandidateList.call().then(function(v) {
    console.log(v)
    });
  })

有人请帮帮我

(此段为已翻译内容)

你能否包含部署合约所需的代码? - Adam Kipnis
1个回答

14
假设你在JS端使用了web3,可以使用web3.toAscii函数。
文档中的示例:
var str = web3.toAscii("0x657468657265756d000000000000000000000000000000000000000000000000");
console.log(str); // "ethereum"

8
在当前版本的web3中,您应该调用web3Provider.utils.toAscii() - AminSojoudi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接