Solidity – Check if msg.sender is a Specific Type of Contract

contract-designsolidity

Is it possible to check if msg.sender is a contract of a specific type?

For example:

pragma solidity ^0.4.23;
contract Baz {

    function Baz(){
        // want this to fail
        new Foo();
    }
}

contract Bar {

    function Bar(){
        new Foo();
    }
}

contract Foo {
    Bar bar;


    function Foo(){
        // how to make sure that msg.sender is of type Bar?
        bar = Bar(msg.sender);
    }
}

I've tried this in Remix and running it Baz in remix doesn't cause any problems.

Best Answer

You could do this short and simple. It would guard against accidental mix-ups, but not deliberate impersonation.

pragma solidity ^0.4.23;
contract Baz {

    function Baz(){
        // want this to fail
        new Foo();
    }
}

contract Bar {

    function Bar(){
        new Foo();
    }

    function iAmBar() public pure returns(bool isIndeed) {
        return true;
    }
}

contract Foo {
    Bar bar;


    function Foo(){
        // how to make sure that msg.sender is of type Bar?
        bar = Bar(msg.sender);
        require(bar.iAmBar());
    }
}

Another way to go is to whitelist all the "friendly" contracts. In the case you have more than one deployer, you would use a separate whitelist to catalogue all the "friendlies". A simpler example just has your Bar contract keep track of its progeny.

pragma solidity ^0.4.23;
contract Baz {

    function Baz(){
        // want this to fail
        new Foo();
    }
}

contract Bar {

    mapping(address => bool) public isWhiteListed;

    function Bar(){
        Foo f = new Foo();
        isWhiteListed[address(f)] = true;
    }

}

contract Foo {
    Bar bar;


    function Foo(){
        // how to make sure that msg.sender is of type Bar?
        bar = Bar(msg.sender);
        require(bar.isWhiteListed(address(bar)));
    }
}

Hope it helps.

Related Topic