Questions about contract calling another contract

拈花ヽ惹草 提交于 2020-01-23 12:17:27

问题


Need help with two related Solidity questions.

  1. Question 1. Say, I have a contract calling another one:

    contract B {
      function f1() {
         ...
      }
    }
    
    contract A {
      B b;
    
      function f() {
        b.f1();
      }
    }
    

Will msg.sender for f1 be same as for f()? Of will it be an address of a contract A?

  1. Question 2. Say, I have contracts A and B. I want to have

    contract A {
      B b;
    
      A(address addr) { 
        b = B(addr); 
      }
    }
    

In other language, I would use B b = null; in declaration, to avoid double initialization, but it does not work in Solidity. So how do I declare a member variable and then initialize it by address?


回答1:


Will msg.sender for f1 be same as for f()? Of will it be an address of a contract A?

msg.sender will be the address of contract A. If you want to reference the original caller, use tx.origin.

So how do I declare a member variable and then initialize it by address?

You don't need to worry about initialization when you declare the member variable. All variables in Solidity have default values. You can follow something like this:

contract B {
    address sender;

    function B(address addr) {
        sender = addr;
    }
}

contract A {
    B b;

    function A(){
        b = B(msg.sender);
    }
}


来源:https://stackoverflow.com/questions/47858489/questions-about-contract-calling-another-contract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!