Implementing a simple Owned contract pattern in Solidity typically involves the following key steps:
1. Define Owner Variable
First, define a variable to store the current owner's address. This is typically a private address variable.
solidityaddress private _owner;
2. Initialize Owner
Within the contract's constructor, set the deployer's address as the owner. This ensures the contract creator is the initial owner.
solidityconstructor() { _owner = msg.sender; }
3. Owner Permission Check
Create a modifier for functions that should only be callable by the owner. This modifier verifies that the current caller is the owner.
soliditymodifier onlyOwner() { require(msg.sender == _owner, "Caller is not the owner"); _; }
4. Implement Ownership Transfer
Implement a function that enables the current owner to transfer ownership to another address. This function must be called only by the current owner.
solidityfunction transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "New owner cannot be the zero address"); _owner = newOwner; }
Example: Complete Owned Contract Combining the above steps, we get a simple Owned contract, as shown below:
solidity// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Owned { address private _owner; constructor() { _owner = msg.sender; } modifier onlyOwner() { require(msg.sender == _owner, "Caller is not the owner"); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "New owner cannot be the zero address"); _owner = newOwner; } // Example function, callable only by the owner function securedAction() public onlyOwner { // Actions restricted to the owner } }
In this example, the securedAction function serves as an illustrative function demonstrating how to use the onlyOwner modifier to restrict access to functions callable only by the owner. Furthermore, ownership can be securely transferred to another valid address using the transferOwnership function.
This pattern is widely used in real-world applications, particularly for controlling access to critical contract functionalities, ensuring both security and flexibility.