// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
// A contract where ownership can be transferred
contract TransferOwnership{
event ownershipTransferred(address indexed previousOwner, address indexed newOwner);
// Declaring a state varible
address public owner;
// Declaring mapping from address to uint
mapping(address => uint) amount;
// Defining a constructor
constructor() public {
owner = msg.sender;
}
// Defining a modifier
modifier onlyOwner(){
require(owner == msg.sender);
_;
}
// Defining a function to transfer ownership
function transferOwnership(address _newOwner) public onlyOwner{
require (_newOwner != address(0));
emit ownershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
-
In ownable_smart_contract.sol first we need have declared SPDX license that simply means that your smart contract is public can be used by anyone without your permission.
-
In the second line of code i.e. pragma solidity ^0.6.0; we have declared the compiler version.
-
Declaring a contract name TransferOwnership using keyword contract.
-
event are used to inform the calling application about the current state of the contract.
-
Then declaring state variable owner whose visibility has been set to public and it is storing the address of owner.
-
After that mapping has been used declared to store the balance of particular address. Mapping are similar to dictionaries in python which stores keys and values.
-
A constructor in solidity is used to initialize values to state variables. But there is a catch we can declare only one constructor in one smart contract, it can't be more than one.
-
A modifier in solidity becomes important since we need to spend ether to deploy our smart contract we need to be extra careful that our code doesn't have any bugs. Modifier checks if the required condition is fulfilled or not before the function is executed. And don't forget to add _; .
-
Now coming to the ending part we have to defined function. The function would be named transferOwnership and it is taking one argument _newOwner of type address. We are setting this function to be public which literally means anyone can call it. Finally adding a modifier to the very end with opening and closing curly braces.
-
The body of the function looks something like this. Using a require function to check if our new owner address is not equal to 0. Then we are firing our event ownershipTransferred and assigning owner (which is a state varible) equal to _newOwner(which is a local variable) will change the state of the contract.