Solidity – How to Set Owners in Constructor During Contract Creation

contract-deploymentsolidity

I have a contract, and I want set owners for my contract without using set address in code.
Code of costructor contract:

function StepanToken2 (address _ownerFirst, address _ownerSecond){
       ownerFirst = _ownerFirst;
       ownerSecond = _ownerSecond;

       balances[ownerFirst] = SafeMath.div(totalTokens, 3);
       balances[ownerSecond] = SafeMath.sub( totalTokens, balances[ownerFirst]);
    }

Can I set owners in myEtherWallet or other way?

Best Answer

The easiest way to set an owner(s) is to do it like so:

pragma solidity ^0.4.0;

contract OwnedContract {

    mapping (address => bool) private _owners;
    mapping (address => uint) private _balances;

    modifier isOwner() {
        require(_owners[msg.sender]);
        _;
    }

    function OwnedContract() {
        _owners[msg.sender] = true;
    }

    function addOwner(string _addr)
        isOwner {
        _owners[parseAddr(_addr)] = true;
    }

    function removeOwner(string _addr)
        isOwner {
        _owners[parseAddr(_addr)] = false;
    }

    // From https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_pre0.4.sol#L157
    function parseAddr(string _a) internal returns (address){
        bytes memory tmp = bytes(_a);
        uint160 iaddr = 0;
        uint160 b1;
        uint160 b2;
        for (uint i=2; i<2+2*20; i+=2){
            iaddr *= 256;
            b1 = uint160(tmp[i]);
            b2 = uint160(tmp[i+1]);
            if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
            else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
            if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
            else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
            iaddr += (b1*16+b2);
        }
        return address(iaddr);
    }

    // ... other functionality

}

You create the owner of the contract on first initialization which is yourself, then you are free to add and remove owners as you go. You could also do the master admin concept to of:

pragma solidity ^0.4.0;

contract OwnedContract {

    mapping (address => bool) private _owners;
    address private _masterAdmin;

    modifier isOwner() {
        require(_masterAdmin == msg.sender || _owners[msg.sender]);
        _;
    }

    function OwnedContract() {
       _masterAdmin = msg.sender;
    }

    // ... other functionality

}

This way none of your other admins can remove the master admin.

There's other ways to limit functionality too such as:

modifier isContract() {
    require(address(this) == msg.sender);
    _;
}

This limits functionality to the contract address its self.

Hope this answered your question.

Related Topic