github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/docs/assets/how-to-guides/write-simple-dapp/poll-2.gno (about) 1 package poll 2 3 import ( 4 "std" 5 6 "gno.land/p/demo/avl" 7 "gno.land/p/demo/poll" 8 "gno.land/p/demo/seqid" 9 "gno.land/p/demo/ufmt" 10 ) 11 12 // state variables 13 var ( 14 polls *avl.Tree // id -> Poll 15 pollIDCounter seqid.ID 16 ) 17 18 func init() { 19 polls = avl.NewTree() 20 } 21 22 // NewPoll - Creates a new Poll instance 23 func NewPoll(title, description string, deadline int64) string { 24 // get block height 25 if deadline <= std.GetHeight() { 26 panic("deadline has to be in the future") 27 } 28 29 // Generate int 30 id := pollIDCounter.Next().String() 31 p := poll.NewPoll(title, description, deadline) 32 33 // add new poll in avl tree 34 polls.Set(id, p) 35 36 return ufmt.Sprintf("Successfully created poll #%s!", id) 37 } 38 39 // Vote - vote for a specific Poll 40 // yes - true, no - false 41 func Vote(id string, vote bool) string { 42 // get txSender 43 txSender := std.GetOrigCaller() 44 45 // get specific Poll from AVL tree 46 pollRaw, exists := polls.Get(id) 47 48 if !exists { 49 panic("poll with specified doesn't exist") 50 } 51 52 // cast Poll into proper format 53 poll, _ := pollRaw.(*poll.Poll) 54 55 voted, _ := poll.HasVoted(txSender) 56 if voted { 57 panic("you've already voted!") 58 } 59 60 if poll.Deadline() <= std.GetHeight() { 61 panic("voting for this poll is closed") 62 } 63 64 // record vote 65 poll.Vote(txSender, vote) 66 67 // update Poll in tree 68 polls.Set(id, poll) 69 70 if vote == true { 71 return ufmt.Sprintf("Successfully voted YAY for poll #%s!", id) 72 } 73 return ufmt.Sprintf("Successfully voted NAY for poll #%s!", id) 74 }