Search code examples
ethereumsoliditysmartcontracts

Best way to register for a vote in solidity


Hi I'm creating a voting smart contract for a DAO and I have a security question. The voting system works like this:

You send your tokens to the smart contract then the smart contract registers how much tokens you have and assignes you "Power" which you use when you vote. Then the smart contract sends the funds back immidiately.

My question is if there is more secure way to do this. Without funds leaving usere's wallet.

Here is the code I have so far.

function getPower() payable public {
    require(msg.value > 0, "The amount can't be 0");
    require(election_state == ELECTION_STATE.OPEN);
    require(votingPeriod > block.timestamp);
    uint amountSent = msg.value;
    // This function will take their money and assign power to the voter
    // The power is equal to their deposit in eth * 10 so for each eth they get 10 power
    voters[msg.sender].power = msg.value * 10;
    payable(msg.sender).transfer(amountSent);
}

Thanks in advance.


Solution

  • Based on the provided code and question, I'm assuming you want to calculate the voting power based on the users' ETH balance - not based on their balance of the DAO token.

    You can get the current ETH balance of an address, using the .balance member of an address type. So you could simplify your function as this:

    function getPower() public {
        require(election_state == ELECTION_STATE.OPEN);
        require(votingPeriod > block.timestamp);
        voters[msg.sender].power = msg.sender.balance * 10;
    }
    

    After performing the validations, it assigns the value based on the msg.sender ETH balance at the moment of the getPower() function being invoked. Without them needing to send ETH to the contract.


    Note that this approach is not common and can be misused for example by users loaning a large amount of ETH just before executing the getPower() function. I'd recommend you to use a more common pattern of calculating the voting power based on their current holdings of the token representing their stake in the DAO.