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, and Disabled.
  • A public state variable state is declared to hold the current state. It can be read externally thanks to the public keyword.
  • A modifier inState is defined to restrict function execution based on the current state. It checks that state == _state using require, and then allows the function body to continue.
  • The lock function can only be called if the contract is in the Created state. When called, it changes the state to Locked.

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 a string to simulate enum-like behavior.
  • We declare a const block listing all valid states: StateActive, StateLocked, and StateDisabled. These are as the Solidity Enum.
  • A global variable state of type State is initialized to StateActive.
  • The helper function assertInState ensures that the contract is in the expected state. If not, it throws an error using panic, showing both the expected and actual state values. This is equivalent to a Solidity modifier.
  • The Lock function changes the state from Active to Locked. It first ensures the state is currently Active using assertInState.
  • The Unlock function reverses the state from Locked to Active, again checking the current state before proceeding.

Live Demo

Contract State : Active

Lock

Unlock