options.gno
2.19 Kb · 84 lines
1package definition
2
3import (
4 "strconv"
5 "time"
6
7 "gno.land/p/nt/commondao/v0"
8)
9
10// Option configures CommonDAO proposal definitions.
11type Option func(*Definition)
12
13// WithVoteChoices configures a proposal to use custom voting choices.
14// It panics when there are less than two choices or when a voting choice is duplicated.
15func WithVoteChoices(choices []commondao.VoteChoice) Option {
16 count := len(choices)
17 if count < 2 {
18 panic("proposal requires at least two voting choices: got " + strconv.Itoa(count))
19 }
20
21 return func(d *Definition) {
22 seen := make(map[commondao.VoteChoice]struct{}, count)
23 d.voteChoices = make([]commondao.VoteChoice, count)
24 for i, choice := range choices {
25 if _, found := seen[choice]; found {
26 panic("proposal voting choice is duplicated: " + string(choice))
27 }
28
29 seen[choice] = struct{}{}
30 d.voteChoices[i] = choice
31 }
32 }
33}
34
35// WithVotingPeriod configures the voting period of a proposal.
36// It panics when voting period is negative.
37func WithVotingPeriod(period time.Duration) Option {
38 if period < 0 {
39 // Zero allows unit testing of proposals
40 panic("voting period of proposal must be greater or equal to zero")
41 }
42
43 return func(d *Definition) {
44 d.votingPeriod = period
45 }
46}
47
48// WithTally configures a proposal definition to use a custom vote tallying.
49// New definitions tally using simple majority (51%) by default.
50// It panics when tally callback is nil.
51func WithTally(cb TallyFunc) Option {
52 if cb == nil {
53 panic("proposal tally callback is nil")
54 }
55
56 return func(d *Definition) {
57 d.tallyCb = cb
58 }
59}
60
61// WithValidation configures a proposal definition to support proposal validation.
62// Validation is done before execution and normally also during proposal rendering.
63// It panics when validation callback is nil.
64func WithValidation(cb func() error) Option {
65 if cb == nil {
66 panic("proposal validation callback is nil")
67 }
68
69 return func(d *Definition) {
70 d.validateCb = cb
71 }
72}
73
74// WithExecutor configures a proposal definition to support proposal execution.
75// It panics when executor callback is nil.
76func WithExecutor(cb commondao.ExecFunc) Option {
77 if cb == nil {
78 panic("proposal executor callback is nil")
79 }
80
81 return func(d *Definition) {
82 d.executeCb = cb
83 }
84}