Solidity
如何找到合約所有者的地址?
我的印像是契約的所有者
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 { ... } }