Owner.sol explained in solidity

In this tutorial, we will learn about one of the default contract owner.sol in remix IDE. Fire your remix IDE to see the contract or you can get the source code from the below gist.

Owner.sol is a simple contract that can be used in any contract where we need to transfer the ownership of the deployed contract to another address (This can be done by owner only). Let’s understand how it works.

As always first we define the version of solidity to be used i.e. greater than or equal to 0.4.22 and smaller than 0.7.0. After that, we define the contract name ‘Owner‘.

address private owner;
A private variable to store the address of the owner of the deployed contract.

event OwnerSet(address indexed oldOwner, address indexed newOwner);
Event OwnerSet with the address of oldOwner and newOwner as an argument. This event will be triggered when the owner of the contract is updated.

modifier isOwner() {
require(msg.sender == owner, “Caller is not owner”);

The modifier in solidity act like a validator i.e. it will check for some conditions defined in its body if those conditions are true then it will execute the body of the function otherwise it will show the error for transaction failure.
Here we have used modifier isOwner to validate that the function must be called by only the owner of the contract whose address is stored in owner variable.
Inside we have used the ‘require‘ statement to check msg.sender (The caller) must be equal to the owner. If this condition fails then the transaction will also fail with the message “Caller is not owner”.
Note ‘_;’ below require statement, It means that the code for the function will be executed at that position.

constructor() public {
owner = msg.sender;
OwnerSet(address(0), owner);

A simple public type constructor will be called at the time of deployment of contract which will set the owner equal to the msg.sender. And an event OwnerSet will be triggered after that.

function changeOwner(address newOwner) public isOwner {
emit OwnerSet(owner, newOwner);
owner = newOwner;

This is a public function that will be called by the owner of the contract to transfer the ownership to another address which will be passed as an argument while calling.
In the body, we can see an event is triggered and the owner is updated.

function getOwner() external view returns (address) {
return owner;

This function will return the owner’s address and is a view type function.

This owner contract can be linked with all the contracts, as ownership can be transferred easily without redeploying the contract and maintaining the same state. Below is an example of an ERC20 token contract in which we have our ownership contract inherited with the token contract. So as to transfer the ownership of our token contract to someone else would be useful. To check the source Click Here!.

Leave a Reply

Your email address will not be published. Required fields are marked *