2

What are some ways to get address of contract which called a contract ?

For example, does msg.sender pass the address of the account which invoked callCanOnlyBeCalledByB(), or the address of B ?

contract A {
    address B; //set by other mechanism
    function canOnlyBeCalledByB() external {
        if(msg.sender == B) { do thing }
    }
}

contract B {
    address owner; //set by other mechanism
    address A; //set by other mechanism

    function callCanOnlyBeCalledByB() {
        if(msg.sender != owner) throw;
        bytes4 functionSig = bytes4(sha3("canOnlyBeCalledByB()"));    
        A.call(functionSig);
    }
}
vera34
  • 157
  • 1
  • 1
  • 3
  • Your code uses msg.sender correctly as explained by @Edmund. Related: http://ethereum.stackexchange.com/questions/1891/whats-the-difference-between-msg-sender-and-tx-origin – eth Oct 17 '16 at 06:59

1 Answers1

1

The contract (or address) that called your contract is msg.sender, as I think your example intends. So if you call B then B calls A, B sees your address in msg.sender, then A sees B's address in msg.sender.

The externally owned account that triggered the original chain of calls is available as tx.origin. So tx.origin will contain your address, in both A and B. It's generally considered bad practice to discriminate between humans and contracts, so you don't usually want to be using tx.origin.

Edmund Edgar
  • 16,897
  • 1
  • 29
  • 58