Search code examples
blockchainethereumsoliditysmartcontracts

Creating a voter contract with solidity. Error: "integer constant expected"


  1. Entrociter[_entrociterID].votes++; ///Is where "integer constant expected" is thrown. This should allow the user to vote with their id.///
'''
pragma solidity >=0.6.0;

contract Newjudge {

    uint public constant MAX_VOTES_PER_VOTER= 1;
    
    struct Entrociter {
        uint id;
        string name;
        string party;
        uint votes;

    }

event Voted ();
event NewEntrociter ();

mapping(uint => Entrociter) public entrociters;
uint public entrociterCount;

mapping(address => uint) public votes;

constructor() {
  entrociterCount = 0;
}

function vote(uint _entrociterID) public {
require(votes[msg.sender] <MAX_VOTES_PER_VOTER, "Voter has no votes left."); 
require(_entrociterID > 0 && _entrociterID <= entrociterCount, " Entrociter ID is out of range.");

votes[msg.sender]++;
Entrociter[_entrociterID].votes++;
Entrociter[entrociterCount] = Entrociter;
emit Voted();
}

function addEntrociter(string memory _name, string memory _party) public {
entrociterCount++;

Entrociter memory entrociter = Entrociter(entrociterCount, _name, _party, 0);
entrociter[entrociterCount] = entrociter;

emit NewEntrociter();
votes(entrociterCount);
    }

 }

'''


Solution

  • You get this error "integer constant expected" because Entrociter is a type not a mapping so you cannot have this Entrociter[_entrociterID]. It should be entrociters[_entrociterID]. But then you will have a reference error.

    So to solve the issue, since you want to update a storage variable, you get a reference to it, tell EVM that you are updating that variable

    function vote(uint _entrociterID) public {
        require(votes[msg.sender] <MAX_VOTES_PER_VOTER, "Voter has no votes left."); 
        require(_entrociterID > 0 && _entrociterID <= entrociterCount, " Entrociter ID is out of range.");
    
        votes[msg.sender]++; 
        // get the reference of struct that you want to update 
        Entrociter storage entrociter=entrociters[_entrociterID]; 
        entrociter.votes++;
        entrociters[entrociterCount] = entrociter;
        emit Voted(); }
    
        function addEntrociter(string memory _name, string memory _party) public {
        entrociterCount++;
    
        Entrociter memory entrociter = Entrociter(entrociterCount, _name, _party, 0);
        entrociters[entrociterCount] = entrociter;
    
        emit NewEntrociter();
        // TypeError: Type is not callable
        // votes(entrociterCount);
     }