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
ownerof typeaddress, which stores the address of the account that deployed the contract. - The
constructorsets theownervariable to the address that deployed the contract usingmsg.sender. - It defines a
modifier onlyOwnerthat restricts function execution to the owner only, usingrequireto check that the caller is the currentowner. The special symbol_;is where the modified function's code runs. - It defines a
changeOwnerfunction that allows the current owner to assign a new owner address. The function uses theonlyOwnermodifier to enforce access control.
Gno Version
1package onlyownercanchange
2
3import "std"
4
5var owner 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
ownerof typeaddress(an alias forstringin Gno), initialized to the empty string"". This holds the address of the contract owner. - The function
InitOwneris used to initialize theowner. It can only be called once: ifowneris already set (non-empty), it throws an error usingpanic. It sets theownerto the address of the previous realm (the caller) viastd.PreviousRealm().Address(), which is similar tomsg.senderin Solidity. - The helper function
assertOnlyOwnerchecks that the caller is the currentownerby comparingstd.PreviousRealm().Address()withowner. If not, it panics. This is equivalent to a Soliditymodifier onlyOwner. - The function
ChangeOwnerallows the current owner to transfer ownership to a new address. It first callsassertOnlyOwner()to ensure that only the current owner can do this. - All functions are capitalized (exported), meaning they can be called externally. However,
assertOnlyOwneris 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: ****