State Lock
This example showcases how a Solidity modifier might be implemented in Gno.
In Solidity
1contract StateLock {
2 enum State { Active, Locked, Disabled }
3
4 State public state = State.Active;
5
6 modifier inState(State _state) {
7 require(state == _state);
8 _;
9 }
10
11 function lock() public inState(State.Active) {
12 state = State.Locked;
13 }
14
15 function unlock() public inState(State.Locked) {
16 state = State.Active;
17 }
18}
- An
enum State
is declared with three possible values:Active
,Locked
, andDisabled
. - A
public
state variablestate
is declared to hold the current state. It can be read externally thanks to thepublic
keyword. - A
modifier inState
is defined to restrict function execution based on the currentstate
. It checks thatstate == _state
usingrequire
, and then allows the function body to continue. - The
lock
function can only be called if the contract is in theCreated
state. When called, it changes the state toLocked
.
Gno Version
1type State string
2
3const (
4 StateActive State = "Active"
5 StateLocked State = "Locked"
6 StateDisabled State = "Disabled"
7)
8
9var state State = StateActive
10
11func assertInState(expected State) {
12 if state != expected {
13 panic("invalid state: expected " + expected + ", got " + state)
14 }
15}
16
17func Lock(cur realm) {
18 assertInState(StateActive)
19 state = StateLocked
20}
21
22func Unlock(cur realm) {
23 assertInState(StateLocked)
24 state = StateActive
25}
- We define a custom type
State
as astring
to simulate enum-like behavior. - We declare a
const
block listing all valid states:StateActive
,StateLocked
, andStateDisabled
. These are as the SolidityEnum
. - A global variable
state
of typeState
is initialized toStateActive
. - The helper function
assertInState
ensures that the contract is in the expected state. If not, it throws an error usingpanic
, showing both the expected and actual state values. This is equivalent to a Soliditymodifier
. - The
Lock
function changes the state fromActive
toLocked
. It first ensures the state is currentlyActive
usingassertInState
. - The
Unlock
function reverses the state fromLocked
toActive
, again checking the current state before proceeding.
Live Demo
Contract State : Active