Solidity
ZepplinOS:在哪裡設置合約的所有者?
ZepplinOS 合約在其 zos 實現中不使用建構子,而是使用從包
initialization
中導入的函式。zos-lib/contracts/Initializable.sol
為了使合約具有可升級的狀態,需要在
initialization
函式中聲明狀態變數,如下所示:bytes32[] public data; function initialize(bytes32[] _data) initializer public { data = _data; }
如果我想設置合約的所有者,我會簡單地在函式中設置一個
owner
變數嗎?initialize
不確定這裡的最佳做法是什麼。pragma solidity ^0.5.0; import "zos-lib/contracts/Initializable.sol"; contract Verifications is Initializable { mapping (bytes32 => bytes32) public data; address public owner; function initialize(bytes32[] _data) initializer public { owner = msg.sender; data = _data; } }
想法?這個可以嗎?
我認為最好通過如下輸入參數明確所有者,而不是使用msg.sender因為 msg.sender 可能不是我們打算設置的,因為 zos 使用契約代理使其可升級。
pragma solidity ^0.5.0; import "zos-lib/contracts/Initializable.sol"; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; }