2

I am writing a simple contract to replicate a voting session led by a president. The contract compiles correctly, however, I can't deploy it because of the following error: "Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information." .

I can't see why I need a payable modifier on the constructor. The code is the following:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.6;

contract Voting{

    address public president;

    mapping(bytes32=>uint) public candidates;

    bytes32[] public names;

    constructor(bytes32[] memory _names) {
        president = msg.sender;
        for(uint idx=0; idx<_names.length; idx++){
            bytes32 name = _names[idx];
            names[idx] = name;
            candidates[name] = 0;
        }
    }

    function vote(bytes32 name) public {
        candidates[name] += 1;
    }

    function declareWinner() public view returns(bytes32){
        require(president==msg.sender);
        bytes32 winner;
        uint votes=0;

        for(uint idx=0; idx<names.length; idx++){
            bytes32 name = names[idx];
            uint _votes = candidates[name];
            if(_votes > votes){
                winner = name;
                votes = _votes;
            }
        }

        return winner;
    }
}
2
  • Make sure you are not sending any eth to the contract while deploying it. I tried that code on Remix and it worked alright. Commented Aug 31, 2022 at 20:47
  • Thanks! Actually I wasn't sending any ether even the first time, but it didn't work. However, once I changed the constructor as constructor(bytes32[] memory _names) public { president = msg.sender; names = _names; // changed this for(uint idx=0; idx<_names.length; idx++){ bytes32 name = _names[idx]; candidates[name] = 0; } } now it works... very strange Commented Sep 1, 2022 at 19:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.