Home > Blockchain >  How to change variable's value and use return as a view function in solidity
How to change variable's value and use return as a view function in solidity

Time:07-31

I've initialized a votes array and two functions to store the votes in our array as :

    uint[2] votes = [0,0];

    function vote_a() public{
        votes[0]  = 1;
    }
    function vote_b() public{
        votes[1]  = 1;
    }

Now, I've created a "results" function which should return a string "tie", "a wins" or "b wins" on the basis of number of votes while also reassigning the number of votes to 0

    function results() public returns(string memory){
        uint a = votes[0];
        uint b = votes[1];

        votes[0]=0;
        votes[1]=0;

        if (a==b)
            return "tie";
        else if (a>b)
            return "a wins";
        else
            return "b wins";
    }

but it does not show the returned result in remix ide like a view function. And I cannot modify the state of the function to view as it'd throw an error for changing value of votes array elements. Is there any way to achieve both conditions.

CodePudding user response:

This happen when you'alterating state variables defined in view functions. Thus, view functions can only reads data from your smart contract.

To solve your issue, I tried to split the content about results() function in two functions. The first function that I called setResults() is a similar to setter functions (in other programming languages), so allows only for contract owner to handle the array values. Second function, allows you to view the result about the comparison between a and b elements.

In the following lines, I put your smart contract adjusted where I inserted some notes:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Test {
    uint[2] votes = [0,0];
    address owner;

    // NOTE: I set a 'owner' variable with the address value who have deployed for the first time the smart contract
    constructor() {
        owner = msg.sender;
    }

    // NOTE: Modifier that allow only for smart contract owner the access to specific function
    modifier onlyOwner() {
        require(msg.sender == owner, "You're not the owner!");
        _;
    }

    function vote_a() public{
        votes[0]  = 1;
    }

    function vote_b() public{
        votes[1]  = 1;
    }

    function results() public view returns(string memory){
        uint a = votes[0];
        uint b = votes[1];
        
        if (a==b)
            return "tie";
        else if (a>b)
            return "a wins";
        else
            return "b wins";
    }

    // NOTE: I created a new function that allows you to handle the data inside array
    function setResults() public onlyOwner {
        votes[0] = 0;
        votes[1] = 0;
    }

}

IMPORTANT: Before call results() function, remember you to call setResults() for change the array values.

  • Related