0

Contract:

contract Ballot {

    struct Voter {
        uint weight; //weight is accumulated by delegation
        bool voted; //if true, that person already voted
        address delegate; //person delegated to
        uint vote; //index of the voted proposal
    }

    struct Proposal {
        bytes32 name;    // short name (up to 32 bytes)
        uint voteCount; //number of accumulated votes
    }

    address public chairperson;

    // This declares a state variable that
    // stores a `Voter` struct for each possible address.
    mapping(address => Voter) public voters;

    Proposal[] public proposals;

    /// Create a new ballot to choose one of `proposalNames`.
    constructor(bytes32[] proposalNames) public {
        chairperson = msg.sender;
        voters[chairperson].weight = 1;

        // For each of the provided proposal names,
        // create a new proposal object and add it
        // to the end of the array.
        for (uint i = 0; i < proposalNames.length; i++) {
            proposals.push(Proposal({
                    name: proposalNames[i],
                        voteCount: 0
                }));
        }
    }

    // Give `voter` the right to vote on this ballot.
    // May only be called by `chairperson`.
    function giveRightToVote(address voter) public {
        // If the first argument of `require` evaluates
        // to `false`, execution terminates and all
        // changes to the state and to Ether balances are reverted.
        // This used to consume all gas in old EVM versions, but not anymore.
        // It is often a good idea to use `require` to check if functions are called correctly.
        // As a second argument, you can also provide an explanation about what went wrong.
        require(msg.sender == chairperson, "Only chairperson can give right to vote.");
        require(!voters[voter].voted, "The voter already voted.");
        require(voters[voter].weight == 0);
        voters[voter].weight = 1;
    }

    /// Delegate your vote to the voter `to`.
    function delegate(address to) public {
        // assigns reference
        Voter storage sender = voters[msg.sender];
        require(!sender.voted, "You already voted.");

        require(to != msg.sender, "Self-delegation is disallowed.");
        while (voters[to].delegate != address(0)) {
            to = voters[to].delegate;

                // We found a loop in the delegation, not allowed.
            require(to != msg.sender, "Found loop in delegation.");
        }

        // Since `sender` is a reference, this
        // modifies `voters[msg.sender].voted`
            sender.voted = true;
            sender.delegate = to;
            Voter storage delegate_ = voters[to];
            if (delegate_.voted) {
                // If the delegate already voted,
                // directly add to the number of votes
               proposals[delegate_.vote].voteCount += sender.weight;
            } else {
                // If the delegate did not vote yet,
                // add to her weight.
                delegate_.weight += sender.weight;
            }
        }

    /// Give your vote (including votes delegated to you)
    /// to proposal `proposals[proposal].name`.
    function vote(uint proposal) public {
            Voter storage sender = voters[msg.sender];
            require(!sender.voted, "Already voted.");
            sender.voted = true;
            sender.vote = proposal;

            // If `proposal` is out of the range of the array,
            // this will throw automatically and revert all changes.
            proposals[proposal].voteCount += sender.weight;
    }

    function winningProposal() public view returns (uint winningProposal_) {
            uint winningVoteCount = 0;
            for (uint p = 0; p < proposals.length; p++) {
                if (proposals[p].voteCount > winningVoteCount) {
                        winningVoteCount = proposals[p].voteCount;
                        winningProposal_ = p;
                    }
            }
    }

    // Calls winningProposal() function to get the index
    // of the winner contained in the proposals array and then
    // returns the name of the winner
    function winnerName() public view returns (bytes32 winnerName_) {
            winnerName_ = proposals[winningProposal()].name;
    }

    function getCount(uint p) public view returns (uint count_) {
            count_ = proposals[p].voteCount;
    }
}

javascript:

var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
        var coinbase = web3.eth.coinbase;
        var balance = web3.eth.getBalance(coinbase);
        var abi = JSON.parse('[{\"constant\":false,\"inputs\":[{\"name\":\"proposal\",\"type\":\"uint256\"}],\"name\":\"vote\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"proposals\",\"outputs\":[{\"name\":\"name\",\"type\":\"bytes32\"},{\"name\":\"voteCount\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"chairperson\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"}],\"name\":\"delegate\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"winningProposal\",\"outputs\":[{\"name\":\"winningProposal_\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"voter\",\"type\":\"address\"}],\"name\":\"giveRightToVote\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"voters\",\"outputs\":[{\"name\":\"weight\",\"type\":\"uint256\"},{\"name\":\"voted\",\"type\":\"bool\"},{\"name\":\"delegate\",\"type\":\"address\"},{\"name\":\"vote\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"p\",\"type\":\"uint256\"}],\"name\":\"getCount\",\"outputs\":[{\"name\":\"count_\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"winnerName\",\"outputs\":[{\"name\":\"winnerName_\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"proposalNames\",\"type\":\"bytes32[]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]');
        var cont = web3.eth.contract(abi).at("0x68497A36A8E322EA25d3d6CD6E15BcF5855AC560");
        sign();
        cont.giveRightToVote.sendTransaction(web3.eth.accounts[0], {from:coinbase, gas:250000}, function(err, transactionHash){   
            if(!err){
                console.log(transactionHash);
            }
            else{ alert(err); }
        });

        // cont.giveRightToVote.call(web3.eth.accounts[1], function(err, res){
        //     console.log(res);   
        // });

        function give_vote(){ 
            cont.delegate.sendTransaction(web3.eth.accounts[2], {from:coinbase, gas:250000}, function (err, trans){
                cont.vote.sendTransaction(2, {from:coinbase, gas:250000}, function(err,   transactionHash){   
                if(!err){
                    console.log(transactionHash);
                }
                else{ alert(err); }
                });
            });

        }
        function view(){
            cont.winnerName.call(function(err, result){
                console.log(result);  
            });
            cont.getCount.call(0, function(err, res){
                console.log(res);  
            });
        }

eth.accounts[0] voting is accepted. when try to do eth.accounts[1 or 2] it is not counting vote. how can make other account also participate in the voting system?

1

I am assuming you have set defined your initial/primary account as the coinbase:

miner.setEtherbase(eth.accounts[0])

So eth.accounts[0] is chairperson who has the right to vote as defined in the constructor.

chairperson will give the right to vote for eth.accounts[1] and eth.accounts[2]

You need to call a function to give the right to vote for accounts 1 and 2.

cont.giveRightToVote.sendTransaction(web3.eth.accounts[1], {from:coinbase, gas:250000}, function(err, transactionHash){   
    if(!err){
        console.log(transactionHash);
    }
    else{ alert(err); }
})
 cont.giveRightToVote.sendTransaction(web3.eth.accounts[2], {from:coinbase, gas:250000}, function(err, transactionHash){   
        if(!err){
            console.log(transactionHash);
        }
        else{ alert(err); }
    })

delegate function is delegating right to vote of coinbase(accounts[0]) to accounts[2]. Now accounts[0] will vote on behalf of account[2]. account[2] cannot participate in the voting as he has delegated his voting right to account[0].

  • What is delegate function? is this correct ?cont.delegate.sendTransaction(web3.eth.accounts[2], {from:coinbase, gas:250000}, function (err, trans){ – Balakrishnan Aug 30 '18 at 5:36
  • 1
    delegate function is delegating right to vote of coinbase(accounts[0]) to accounts[2]. Now accounts[0] will vote on behalf of account[2]. account[2] cannot participate in the voting as he has delegated his voting right to account[0]. – Soham Lawar Aug 30 '18 at 8:51
  • i understood your explanation. contract is not working as expected. i tried same in remix also but is not working. i have eth.accounts[0] to accounts[6]. i have deployed contract with 0, 1, 2, 3 proposals. eth.acccounts[1] voted for 2nd proposal. winningPropsal is 2. then eth.accout[2]. eth.account[3], eth.account[4] voted for 3rd proposal. Afterthat i checked winning propsal. still giving output 2nd proposal. it supposed to be 3rd proposal. would you please share your contact mail to chat? – Balakrishnan Aug 31 '18 at 4:56
  • thanks dude. it is working fine. i have some other doubts. how to get resposnse or how to identify the response incase of address already voted, voting rights is not yet given for this address?. i am getting only transaction hash, even voted or already voted. – Balakrishnan Aug 31 '18 at 9:30
  • Welcome! I am glad to help you. To get smart contract return values for the user interface you need to use solidity events. Read the following tutorial for more details - media.consensys.net/… – Soham Lawar Aug 31 '18 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.