render.gno
2.41 Kb ยท 85 lines
1package statelock
2
3import "strings"
4
5func Render(path string) string {
6 content := `
7# State Lock
8
9This example showcases how a Solidity modifier might be implemented in Gno.
10
11---
12
13## In Solidity
14
15^^^solidity
16contract StateLock {
17 enum State { Active, Locked, Disabled }
18
19 State public state = State.Active;
20
21 modifier inState(State _state) {
22 require(state == _state);
23 _;
24 }
25
26 function lock() public inState(State.Active) {
27 state = State.Locked;
28 }
29
30 function unlock() public inState(State.Locked) {
31 state = State.Active;
32 }
33}
34^^^
35
36* An ^enum State^ is declared with three possible values: ^Active^, ^Locked^, and ^Disabled^.
37* A ^public^ state variable ^state^ is declared to hold the current state. It can be read externally thanks to the ^public^ keyword.
38* 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.
39* The ^lock^ function can only be called if the contract is in the ^Created^ state. When called, it changes the state to ^Locked^.
40
41
42---
43
44## Gno Version
45
46^^^go
47type State string
48
49const (
50 StateActive State = "Active"
51 StateLocked State = "Locked"
52 StateDisabled State = "Disabled"
53)
54
55var state State = StateActive
56
57func assertInState(expected State) {
58 if state != expected {
59 panic("invalid state: expected " + expected + ", got " + state)
60 }
61}
62
63func Lock(cur realm) {
64 assertInState(StateActive)
65 state = StateLocked
66}
67
68func Unlock(cur realm) {
69 assertInState(StateLocked)
70 state = StateActive
71}
72^^^
73
74* We define a custom type ^State^ as a ^string^ to simulate enum-like behavior.
75* We declare a ^const^ block listing all valid states: ^StateActive^, ^StateLocked^, and ^StateDisabled^. These are as the Solidity ^Enum^.
76* A global variable ^state^ of type ^State^ is initialized to ^StateActive^.
77* 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^.
78* The ^Lock^ function changes the state from ^Active^ to ^Locked^. It first ensures the state is currently ^Active^ using ^assertInState^.
79* The ^Unlock^ function reverses the state from ^Locked^ to ^Active^, again checking the current state before proceeding.
80
81---
82
83`
84 return strings.ReplaceAll(content+RenderDemo(), "^", "`")
85}