Ownable

This Solidity contract defines a counter that can be incremented or decremented by anyone.


Solidity Version

 1contract OnlyOwnerCanChange {
 2    address private owner;
 3
 4    constructor() {
 5        owner = msg.sender;
 6    }
 7
 8    modifier onlyOwner {
 9        require(msg.sender == owner, "Not owner");
10        _;
11    }
12
13    function changeOwner(address memory newOwner) public onlyOwner {
14        owner = newOwner
15    }
16}
  • It declares a state variable owner of type address, which stores the address of the account that deployed the contract.
  • The constructor sets the owner variable to the address that deployed the contract using msg.sender.
  • It defines a modifier onlyOwner that restricts function execution to the owner only, using require to check that the caller is the current owner. The special symbol _; is where the modified function's code runs.
  • It defines a changeOwner function that allows the current owner to assign a new owner address. The function uses the onlyOwner modifier to enforce access control.

Gno Version

 1package onlyownercanchange
 2
 3import "std"
 4
 5var owner std.Address = ""
 6
 7func InitOwner(cur realm) {
 8	if len(owner) != 0 {
 9		panic("owner already defined")
10	}
11	owner = std.PreviousRealm().Address()
12}
13
14func assertOnlyOwner() {
15	if std.PreviousRealm().Address() != owner {
16		panic("caller isn't the owner")
17	}
18}
19
20func ChangeOwner(cur realm, newOwner address) {
21	assertOnlyOwner()
22	owner = newOwner
23}
  • We declare a persistent global variable owner of type std.Address (an alias for string in Gno), initialized to the empty string "". This holds the address of the contract owner.
  • The function InitOwner is used to initialize the owner. It can only be called once: if owner is already set (non-empty), it throws an error using panic. It sets the owner to the address of the previous realm (the caller) via std.PreviousRealm().Address(), which is similar to msg.sender in Solidity.
  • The helper function assertOnlyOwner checks that the caller is the current owner by comparing std.PreviousRealm().Address() with owner. If not, it panics. This is equivalent to a Solidity modifier onlyOwner.
  • The function ChangeOwner allows the current owner to transfer ownership to a new address. It first calls assertOnlyOwner() to ensure that only the current owner can do this.
  • All functions are capitalized (exported), meaning they can be called externally. However, assertOnlyOwner is unexported (lowercase), meaning it's only usable within the package.
Note

For a library that handles this for you, check out /p/demo/ownable.


Live Demo

Owner address: ****

InitOwner

ChangeOwner