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 typeaddress
, which stores the address of the account that deployed the contract. - The
constructor
sets theowner
variable to the address that deployed the contract usingmsg.sender
. - It defines a
modifier onlyOwner
that restricts function execution to the owner only, usingrequire
to check that the caller is the currentowner
. 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 theonlyOwner
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 typestd.Address
(an alias forstring
in Gno), initialized to the empty string""
. This holds the address of the contract owner. - The function
InitOwner
is used to initialize theowner
. It can only be called once: ifowner
is already set (non-empty), it throws an error usingpanic
. It sets theowner
to the address of the previous realm (the caller) viastd.PreviousRealm().Address()
, which is similar tomsg.sender
in Solidity. - The helper function
assertOnlyOwner
checks that the caller is the currentowner
by comparingstd.PreviousRealm().Address()
withowner
. If not, it panics. This is equivalent to a Soliditymodifier onlyOwner
. - The function
ChangeOwner
allows 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,
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: ****