美文网首页
solidity中bytes32传参调用合约

solidity中bytes32传参调用合约

作者: meng256011 | 来源:发表于2018-12-11 15:30 被阅读0次

solidity中函数的参数为bytes32的函数调用

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

在部署合约如果想传递['Rama', 'Nick', 'Jose']需要将这些字符串转换为Ascii。如果通过js中部署合约则在传递函数是通过web3.fromAscii('Rama')将字符串转换为对应的Ascii

let VotingContract = web3.eth.contract(abiDefinition);
let byteCode = compiledCode.contracts[':Voting'].bytecode;

//调用VotingContract对象的new()方法来将投票合约部署到区块链。new()方法参数列表应当与合约的 构造函数要求相一致。对于投票合约而言,new()方法的第一个参数是候选人名单。
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)
    }
});

相关文章

网友评论

      本文标题:solidity中bytes32传参调用合约

      本文链接:https://www.haomeiwen.com/subject/psqehqtx.html