Solidity

如何找到合約所有者的地址?

  • May 26, 2020

我的印像是契約的所有者accounts[0]在 Truffle 的測試環境中被簡單地稱為,但是我得到了修飾符的錯誤,即某個函式的呼叫者不是所有者。

我已經實例化了契約A和契約,契約B中包含以下程式碼B

   modifier requireContractOwner() {
       require(msg.sender == contractOwner, "Caller is not contract owner");
       _;
   }

   function _authorizeCaller(address addr)
       external
       requireContractOwner
   {
       authorizedCaller[addr] = true;
   }

我正在從合約中呼叫函式A

   function authorizeCaller(address addr) public {
       B._authorizeCaller(addr);
   }

我實例化的方式A是:

   constructor(address dataContract) public {
       contractOwner = msg.sender;
       B = B(dataContract);
   }

B

  constructor() public {
       contractOwner = msg.sender;
       authorizedCaller[msg.sender] = true;
   }

以下是我如何部署它們:

module.exports = function (deployer, network, accounts) {
 deployer.deploy(B).then(() => {
   return deployer
     .deploy(A, B.address)
     .then(() => {
      // configuration
     });
 });
};

問題是,當我測試與合約所有者呼叫該函式時:

     let B = await B.new();
     let A = await A.new(B.address);
     await A.authorizeCaller(accounts[1], {
       from: accounts[0],
       gasPrice: 0,
     });

測試失敗,accounts[0]說明修改者不是契約的所有者requireContractOwner()

accounts[0]我的印像是,契約的所有者在 Truffle 的測試環境中被簡稱為…

除非您明確指定{from: someAccount},否則預設值確實是{from: accounts[0]}.


我正在從合約中呼叫函式A

function authorizeCaller(address addr) public {
   B._authorizeCaller(addr);
}

在這裡,msg.sender函式_authorizeCaller執行時的值將是合約A的地址,而不是合約部署者的地址A

因此,表達式msg.sender == contractOwner將計算為false

您通常應該requireContractOwner在公用事業契約中實施修改器:

contract Owned {
   address public contractOwner;

   constructor() public {
       contractOwner = msg.sender;
   }

   modifier requireContractOwner() {
       require(msg.sender == contractOwner, "Caller is not contract owner");
       _;
   }
}

然後繼承這個合約並在需要的地方使用它:

import "./Owned.sol";

contract B is Owned {
   constructor() public {
       // constructor of `Owned` has already executed at this point
       ...
   }

   function _authorizeCaller(address addr) external requireContractOwner {
       ...
   }
}

引用自:https://ethereum.stackexchange.com/questions/83717