solidity中函數(shù)的參數(shù)為bytes32的函數(shù)調(diào)用
function constructor(bytes32[] candidateNames) public {
candidateList = candidateNames;
}
在部署合約如果想傳遞['Rama', 'Nick', 'Jose']
需要將這些字符串轉(zhuǎn)換為Ascii
潮罪。如果通過js中部署合約則在傳遞函數(shù)是通過web3.fromAscii('Rama')
將字符串轉(zhuǎn)換為對應(yīng)的Ascii
赁豆。
let VotingContract = web3.eth.contract(abiDefinition);
let byteCode = compiledCode.contracts[':Voting'].bytecode;
//調(diào)用VotingContract對象的new()方法來將投票合約部署到區(qū)塊鏈。new()方法參數(shù)列表應(yīng)當(dāng)與合約的 構(gòu)造函數(shù)要求相一致损拢。對于投票合約而言,new()方法的第一個參數(shù)是候選人名單婚肆。
VotingContract.new([web3.fromAscii('Rama'),web3.fromAscii('Nick'),web3.fromAscii('Jose')],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000}, function(e, contract){
if(!e){
if(!contract.address){
console.log("Contract transaction send: Transaction Hash: "+contract.transactionHash+" waiting to be mined...");
}else{
console.log("Contract mined! Address: "+contract.address);
console.log(contract);
let contractInstance = VotingContract.at(contract.address);
contractInstance.voteForCandidate(web3.fromAscii('Rama'), {from: web3.eth.accounts[0]});
contractInstance.voteForCandidate(web3.fromAscii('Rama'), {from: web3.eth.accounts[0]});
contractInstance.voteForCandidate(web3.fromAscii('Rama'), {from: web3.eth.accounts[0]});
contractInstance.voteForCandidate(web3.fromAscii('Nick'), {from: web3.eth.accounts[0]});
contractInstance.voteForCandidate(web3.fromAscii('Jose'), {from: web3.eth.accounts[0]});
contractInstance.voteForCandidate(web3.fromAscii('Jose'), {from: web3.eth.accounts[0]});
console.log("--------------finish----------------");
let RamaVote=contractInstance.totalVotesFor.call(web3.fromAscii('Rama'));
let NickVote=contractInstance.totalVotesFor.call(web3.fromAscii('Nick'));
let JoseVote=contractInstance.totalVotesFor.call(web3.fromAscii('Jose'));
console.log("Rama's vote is "+RamaVote);
console.log("Nick's vote is "+NickVote);
console.log("Jose's vote is "+JoseVote);
}
}else{
console.log(e)
}
});