Solidity View Function Error – Expression Modifies State Requires Payable

compilererrorsolidity

I'm trying to change the an address data variable to a one, which is selected via a function.

Keep getting the below error.

Function declared as view, but this expression (potentially) modifies the state and thus requires non-payable (the default) or payable.

address public winneraddress;

function getHighestBidID() public onlyOwner view returns (uint highestID, address _highestidaddress) {
    require(bids.length > 0,"Bid length");
    uint highestAmount = 0;
    for (uint i=0; i<bids.length; i++) {
        if (bids[i].amount > highestAmount) {
            highestAmount = bids[i].amount;
            highestID = i;
            _highestidaddress = bids[highestID].bidderAddress;
        }
    }
    winneraddress = _highestidaddress;
}
        mapping(address => uint256) public payments; //List of payments done to the Contract

    function makeBid(string memory _extraData) public inState(State.Active) payable returns(uint bidIterator) {
    require(msg.value > 0, "No value inserted");
    require(bidders <= 3, "Contract reached max registrations");
    require(payments[msg.sender] == 0, 'Sender previously paid into escrow.');
    bids.push(Bid(msg.sender, msg.value, _extraData, true));
    payments[msg.sender] = msg.value;
    bidders ++; 
    return bids.length - 1;
} 
    /*function withdraw() external inState(State.WinnerSelected) payable{
    require(msg.sender != winneraddress && winneraddress != address(0));
    payments[msg.sender].transfer(bids[msg.value].amount);
}*/

Any ideas how to fix it and what is causing the error?

Best Answer

Let's go over the compilation error that you're getting:


Function declared as view

That one is clearly true, since this is how you've declared the function:

function getHighestBidID() public onlyOwner view ...

But this expression modifies the state

That one is also true, since you are indeed modifying one of the state-variables:

winneraddress = _highestidaddress;

A view function can read state-variables, but it cannot write (modify) them.

So either get rid of the view, or get rid of the winneraddress = _highestidaddress.