Loading...
contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @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; }}
As a constructor defined in smart contract runs only once while deploying we can set our owner variable to the msg.sender , or it you want to define a custom owner to your smart contract you can directly get address as an argument from the constructor
address public owner;constructor() public { owner = msg.sender; } // this sets the contract deployer as the owner of contract/* constructor(address _owner) public { owner = _owner; } // this sets the custom address(_owner) as the owner of smart contract*/
modifier onlyOwner() { require(msg.sender == owner); _; }
We can use this modifier to restrict the function access to only owner and not for public. we can directly define modifier in function viewports
function WithDrawToken() public payable Onlyowner {} // this function is only acessasible to the msg.sender who has the ower account
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; }
The function transferOwnership is used to change the owner , since its secured with modifier only existing owner can change the owner of the smart contract.