0

For example in a voting dapp, I want only one address to make one vote. My doubt is can i store all the address of message senders in an array and check before casting the vote and hence allowing only one person to cast only one vote ?/

3

Unbounded array looping is bad and you can eventually exceed block gas limit once enough elements are in the array.

You should use a mapping.

mapping(address => bool) alreadyVoted;

Then in your contract you just flip the Boolean to true when they vote.

modifier notVoted() {
    require(!alreadyVoted[msg.sender]);
    _;
}

function vote(uint option) public notVoted() {
    alreadyVoted[msg.sender] = true;
    ...
}
0

You seem to put an equal sign between address and user. But if you place this limitation (one address one vote), there is nothing stopping a user from creating multiple addresses and going around your enforcement. Identity management is an ongoing research subject in block chain and hopefully might assist you in this quest.

0

Yes, you can.

You could have an array storing all addresses that already voted.

For example:

    address[] alreadyVoted;

    function vote() public returns (bool){
    //chekck if sender has already voted
    for (uint i = 0; i <= alreadyVoted.length; i++){
        if (alreadyVoted[i] == msg.sender){
            return false; // stop the function
        }
    }

    // do whatever you want with your vote

// store the sender address so that he won't be able to vote anymore
    alreadyVoted.push(msg.sender); //msg.sender is the address of the account making the transaction
    return true;
    }
8
  • 3
    I think a mapping may be more appropriate than an array in this instance. No looping required then. – AndyK Nov 13 '17 at 10:04
  • What would be the value of your mapping? Also, it's easier to return an array than a mapping, if you want to get all the addresses that already voted. – Florian Castelain Nov 13 '17 at 10:10
  • 1
    mapping (address => uint) public voters; function vote() public returns (bool){ if (voters[msg.sender] == 1){ return false; } voters[msg.sender] = 1; return true; }; – AndyK Nov 13 '17 at 10:33
  • Dear Andromelus, when i use the code, it the remix browser throws away this error: browser/Untitled6.sol:26:21: TypeError: Operator <= not compatible with types int256 and uint256 for (int i = 0; i <= alreadyVoted.length; i++){ ^----------------------^ – Noushad Mohamed Nov 13 '17 at 10:42
  • Hum, yes, but you store an integer that is useless. – Florian Castelain Nov 13 '17 at 10: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.