[Ethereum] comparing two addresses

contract-designdappsethereumjssolidity

I'am trying to create a modifier that allows certain accounts to execute functions.

 address[] authorized; 
       function verify (address adrs) internal view returns (bool)
{
    bool exist;
    uint  j=authorized.length;
    uint i =0;
    exist = false;
    address[] memory adrss;
    while (i<j){
        uint x =0;
        if (adrss ==address[i]){
            bool = true;
        }
        i++;
    }
    return exist;
}



  modifie allowed (address adrs){
        require  (  verify(adrs)==true);
                    _; }

anyone how has an idea?

Best Answer

You should avoid iterating the list of permitted accounts. It's an expensive approach that doesn't scale and it has a lot of moving parts.

Consider instead using a mapping. This is a namespace where all the uninitialized indexes return false, 0, empty, depending on type. For example:

mapping(address => bool) public whitelist; returns true or false for each address, and you can set/get without iterating.

pragma solidity 0.5.1;

contract SimpleWhitelist {

    address public owner;
    mapping(address => bool) public whitelist;

    event LogProtected(address sender);

    modifier onlyOwner {
        require(msg.sender == owner, "You are not the owner.");
        _;
    }

    modifier onlyWhitelist {
        require(whitelist[msg.sender], "You are not whitelisted.");
        _;
    }

    function setPermission(address user, bool isAllowed) public onlyOwner {
        whitelist[user] = isAllowed;
    }

    function protected() public onlyWhitelist {
        emit LogProtected(msg.sender);
    }    
}

There are more advanced ways to store the list of whitelisted addresses: Are there well-solved and simple storage patterns for Solidity? and de facto standard implementations of the Ownable concept but I wanted to keep this as simple as possible.

  1. Only the owner is allowed to grant/revoke permission.
  2. Only whitelisted addresses are allowed to run protected(). It will emit an event on success.

Hope it helps.

Related Topic