Solidity Modifiers – How to Check Boolean Variable is True in Modifier

soliditystruct

I want to check that the Boolean variable "active" in the Account struck is true, for a modifier requirement.

Any logic on how to do this would be fantastic.

struct Account {
    address id;
    string company;
    string country;
    string industry;
    bool active;
}


mapping (address => Account) public Accounts;

modifier validAccount(address _accountId) {
    require (Account(msg.sender.active = true))
    _;
}

Best Answer

It is not exactly clear what you want to do since there is input parameter in your modifier.

If you want to check if address calling function is valid then modify your modifier like this:

modifier onlyValidSender()
{
    require (Accounts[msg.sender].active);
    _;
}

If you want to make sure that you are calling your function on Account which is valid then modify like this:

modifier onlyValid(address _id)
{
    require (Accounts[_id].active);
    _;
}

Here you can see full code which implements two types of modifiers.

pragma solidity 0.4.24;

contract Test
{

mapping (address => Account) public Accounts;

struct Account {
    address id;
    string company;
    string country;
    string industry;
    bool active;
}


modifier validAccount(address _accountId) {
    require (Accounts[msg.sender].active);
    _;
}

function Add(address _id, string _company, string _country, string _industry,bool _active)
{
    Account memory  acc = Account(_id,_company,_country,_industry,_active);
    Accounts[_id] = acc;
}

function GetCompany(address _id) onlyValid(_id) public constant returns(string)
{
    return Accounts[_id].company;
}

modifier onlyValid(address _id)
{
    require (Accounts[_id].active);
    _;
}

modifier onlyValidSender()
{
    require(Accounts[msg.sender].active);
    _;
}

function GetCountry(address _id) onlyValidSender public view returns(string)
{
        return Accounts[_id].company;

}

}

GetCompany will only return value when _id Account is active.

GetCountry will return value only when account asking for it is valid.

Related Topic