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 Stateis declared with three possible values:Active,Locked, andDisabled. - A
publicstate variablestateis declared to hold the current state. It can be read externally thanks to thepublickeyword. - A
modifier inStateis defined to restrict function execution based on the currentstate. It checks thatstate == _stateusingrequire, and then allows the function body to continue. - The
lockfunction can only be called if the contract is in theCreatedstate. 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
Stateas astringto simulate enum-like behavior. - We declare a
constblock listing all valid states:StateActive,StateLocked, andStateDisabled. These are as the SolidityEnum. - A global variable
stateof typeStateis initialized toStateActive. - The helper function
assertInStateensures 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
Lockfunction changes the state fromActivetoLocked. It first ensures the state is currentlyActiveusingassertInState. - The
Unlockfunction reverses the state fromLockedtoActive, again checking the current state before proceeding.
Live Demo
Contract State : Active