Playground
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/polls/v1" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914308 max_deposit = "8000000ugnot"
polls.gno
// Package polls is an on-chain poll / voting realm for gno.land.
//
// Anyone can create a poll with a question and a comma-separated list of
// options. Each caller address may cast exactly one vote per poll. Render
// draws every poll with its options, tallies as ▓░ bar charts, percentages
// and the total vote count.
package polls
import (
"chain"
"chain/markdown"
"strconv"
"strings"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/nt/avl/v0"
)
// selfPath is this realm's own page. A root-relative link resolves against
// the domain, not the realm, so every link back into it names it in full.
const selfPath = "/r/moul/x/daily/polls/v1"
// Poll is a single question with its options and per-address vote tracking.
type Poll struct {
ID int
Question string
Options []string
Tallies []int
Creator string // bech32 address of the poll creator
voted *avl.Tree // address string -> struct{}{}, one vote per address
}
var (
polls []*Poll // index i holds the poll with ID i
nextID int
)
// CreatePoll registers a new poll. options is a comma-separated list; blank
// entries are dropped. Returns the new poll's id. Crossing function: an EOA
// invokes it via MsgCall; another realm via polls.CreatePoll(cross, q, opts).
func CreatePoll(cur realm, question string, options string) int {
creator := caller(cur).String()
q := strings.TrimSpace(question)
if strings.TrimSpace(markdown.StripBidiAndZeroWidth(q)) == "" {
panic("question must not be empty")
}
if len(q) > MaxQuestionLen {
panic("question too long")
}
opts := parseOptions(options)
if len(opts) < 2 {
panic("a poll needs at least 2 options")
}
if len(opts) > MaxOptions {
panic("a poll takes at most " + strconv.Itoa(MaxOptions) + " options")
}
for _, o := range opts {
if len(o) > MaxOptionLen {
panic("option too long")
}
}
if len(polls) >= MaxPolls {
panic("polls is full at " + strconv.Itoa(MaxPolls) + " polls")
}
id := nextID
nextID++
p := &Poll{
ID: id,
Question: q,
Options: opts,
Tallies: make([]int, len(opts)),
Creator: creator,
voted: avl.NewTree(),
}
polls = append(polls, p)
chain.Emit("PollCreated",
"id", strconv.Itoa(id),
"creator", creator,
"options", strconv.Itoa(len(opts)),
)
return id
}
// Vote casts one vote for optionIndex on poll pollID. Each caller address may
// vote at most once per poll. Crossing function.
func Vote(cur realm, pollID int, optionIndex int) {
voter := caller(cur).String()
p := getPoll(pollID)
if optionIndex < 0 || optionIndex >= len(p.Options) {
panic("option index out of range")
}
if p.voted.Has(voter) {
panic("address already voted on this poll")
}
p.voted.Set(voter, struct{}{})
p.Tallies[optionIndex]++
chain.Emit("Voted",
"id", strconv.Itoa(pollID),
"voter", voter,
"option", strconv.Itoa(optionIndex),
)
}
// parseOptions splits a comma-separated option string, trimming whitespace and
// dropping empties. Pure logic — no realm state.
func parseOptions(options string) []string {
var out []string
for _, raw := range strings.Split(options, ",") {
o := strings.TrimSpace(raw)
if strings.TrimSpace(markdown.StripBidiAndZeroWidth(o)) != "" {
out = append(out, o)
}
}
return out
}
// getPoll returns the poll with the given id or panics if it does not exist.
func getPoll(id int) *Poll {
if id < 0 || id >= len(polls) {
panic("poll not found")
}
return polls[id]
}
// PollCount returns the number of polls created so far (read-only helper).
func PollCount() int {
return len(polls)
}
const barWidth = 20
// The bounds on what a creator may store. Anyone may create a poll, and the
// root page renders the newest ones.
const (
MaxPolls = 500
MaxQuestionLen = 200
MaxOptions = 10
MaxOptionLen = 64
IndexRecent = 20 // polls the root page shows, newest first
)
// bar renders a proportional ▓░ bar of fixed width for count out of total.
func bar(count, total int) string {
filled := 0
if total > 0 {
filled = count * barWidth / total
}
if filled > barWidth {
filled = barWidth
}
return strings.Repeat("▓", filled) + strings.Repeat("░", barWidth-filled)
}
// percent returns the integer percentage of count out of total.
func percent(count, total int) int {
if total == 0 {
return 0
}
return count * 100 / total
}
// total sums a tally slice.
func total(tallies []int) int {
sum := 0
for _, t := range tallies {
sum += t
}
return sum
}
// renderPoll writes one poll's Markdown block into b.
func renderPoll(b *strings.Builder, p *Poll) {
sum := total(p.Tallies)
b.WriteString("## Poll #")
b.WriteString(strconv.Itoa(p.ID))
b.WriteString(": ")
b.WriteString(ui.Inline(p.Question))
b.WriteString("\n\n")
for i, opt := range p.Options {
c := p.Tallies[i]
b.WriteString("- **")
b.WriteString(ui.Inline(opt))
b.WriteString("** `")
b.WriteString(bar(c, sum))
b.WriteString("` ")
b.WriteString(strconv.Itoa(percent(c, sum)))
b.WriteString("% (")
b.WriteString(strconv.Itoa(c))
if c == 1 {
b.WriteString(" vote)")
} else {
b.WriteString(" votes)")
}
b.WriteString("\n")
}
b.WriteString("\n_Total votes: ")
b.WriteString(strconv.Itoa(sum))
b.WriteString("_\n\n")
}
// Render produces the Markdown page for gnoweb. It is NOT a crossing function.
//
// - "" -> the IndexRecent newest polls
// - "page/<n>" -> the n-th page of IndexRecent, newest first (page/1 is "")
// - "<id>" -> a single poll by id
func Render(path string) string {
var b strings.Builder
path = strings.TrimSpace(path)
page := 1
if rest, ok := strings.CutPrefix(path, "page/"); ok {
n, err := strconv.Atoi(rest)
// Bounded before any multiply: the page comes from the URL.
if err != nil || n < 1 || n > 1+(len(polls)-1)/IndexRecent {
return "# Polls\n\nNo such page.\n\n[← all polls](" + selfPath + ")\n"
}
page, path = n, ""
}
if path != "" {
id, err := strconv.Atoi(path)
if err != nil || id < 0 || id >= len(polls) {
return "# Polls\n\nPoll not found.\n"
}
b.WriteString("# Polls\n\n")
renderPoll(&b, polls[id])
b.WriteString("[← all polls](" + selfPath + ")\n")
return b.String()
}
b.WriteString("# Polls & Voting\n\n")
if len(polls) == 0 {
b.WriteString("_No polls yet. Create one with `CreatePoll(question, \"a,b,c\")`._\n")
return b.String()
}
pages := 1 + (len(polls)-1)/IndexRecent
b.WriteString("Total polls: ")
b.WriteString(strconv.Itoa(len(polls)))
if pages > 1 {
b.WriteString(", page " + strconv.Itoa(page) + " of " + strconv.Itoa(pages))
}
b.WriteString("\n\n")
//gnovet:ignore page-offset-overflow page is bounded by pages above
top := len(polls) - 1 - (page-1)*IndexRecent
for i := top; i >= 0 && i > top-IndexRecent; i-- {
renderPoll(&b, polls[i])
}
if page < pages {
b.WriteString("[older polls →](" + selfPath + ":page/" + strconv.Itoa(page+1) + ")\n")
}
return b.String()
}
// caller is the address that crossed into this realm, after checking that the
// realm token is this frame's own.
func caller(cur realm) address {
if !cur.IsCurrent() {
panic("polls: spoofed realm")
}
return cur.Previous().Address()
}
polls_test.gno
package polls
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
carol = testutils.TestAddress("carol")
)
// resetState clears package-level state between tests so cases are independent.
func resetState() {
polls = nil
nextID = 0
}
func TestParseOptions(t *testing.T) {
tests := []struct {
name string
input string
want []string
}{
{"simple", "a,b,c", []string{"a", "b", "c"}},
{"trims spaces", " yes , no ", []string{"yes", "no"}},
{"drops empties", "a,,b, ,c", []string{"a", "b", "c"}},
{"single", "only", []string{"only"}},
{"all blank", " , ,", nil},
}
for _, tt := range tests {
got := parseOptions(tt.input)
if len(got) != len(tt.want) {
t.Errorf("%s: len = %d, want %d (%v)", tt.name, len(got), len(tt.want), got)
continue
}
for i := range got {
if got[i] != tt.want[i] {
t.Errorf("%s: [%d] = %q, want %q", tt.name, i, got[i], tt.want[i])
}
}
}
}
func TestCreateAndVote(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
id := CreatePoll(cross(cur), "Best chain?", "gno,eth,btc")
if id != 0 {
t.Fatalf("first poll id = %d, want 0", id)
}
if PollCount() != 1 {
t.Fatalf("PollCount = %d, want 1", PollCount())
}
// alice votes gno.
Vote(cross(cur), id, 0)
// bob votes eth.
testing.SetRealm(testing.NewUserRealm(bob))
Vote(cross(cur), id, 1)
// carol votes gno.
testing.SetRealm(testing.NewUserRealm(carol))
Vote(cross(cur), id, 0)
p := getPoll(id)
if p.Tallies[0] != 2 {
t.Errorf("gno tally = %d, want 2", p.Tallies[0])
}
if p.Tallies[1] != 1 {
t.Errorf("eth tally = %d, want 1", p.Tallies[1])
}
if total(p.Tallies) != 3 {
t.Errorf("total = %d, want 3", total(p.Tallies))
}
}
func TestDoubleVotePanics(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
id := CreatePoll(cross(cur), "Coffee or tea?", "coffee,tea")
Vote(cross(cur), id, 0)
// A second vote by the same address aborts (cross-realm panic).
uassert.AbortsWithMessage(t, cur, "address already voted on this poll", func() {
Vote(cross(cur), id, 1)
})
}
func TestVoteBounds(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
id := CreatePoll(cross(cur), "A or B?", "a,b")
uassert.AbortsWithMessage(t, cur, "option index out of range", func() {
Vote(cross(cur), id, 5)
})
}
func TestCreatePollNeedsTwoOptions(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsWithMessage(t, cur, "a poll needs at least 2 options", func() {
CreatePoll(cross(cur), "One?", "only")
})
}
func TestRender(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
// Empty index.
if got := Render(""); !strings.Contains(got, "No polls yet") {
t.Errorf("empty Render should mention no polls, got:\n%s", got)
}
id := CreatePoll(cross(cur), "Pick one", "x,y")
Vote(cross(cur), id, 0)
// Index lists the poll and bar chart glyphs.
idx := Render("")
if !strings.Contains(idx, "Pick one") {
t.Errorf("index missing question:\n%s", idx)
}
if !strings.Contains(idx, "▓") || !strings.Contains(idx, "░") {
t.Errorf("index missing bar glyphs:\n%s", idx)
}
if !strings.Contains(idx, "Total votes: 1") {
t.Errorf("index missing total votes:\n%s", idx)
}
if !strings.Contains(idx, "100%") {
t.Errorf("index missing 100%% for the sole vote:\n%s", idx)
}
// Single-poll path.
single := Render("0")
if !strings.Contains(single, "Poll #0") {
t.Errorf("single Render missing poll header:\n%s", single)
}
// Unknown path.
if got := Render("99"); !strings.Contains(got, "not found") {
t.Errorf("unknown poll should say not found, got:\n%s", got)
}
}
zz_bounds_test.gno
package polls
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// What a creator may store is bounded, and the root page renders a fixed
// window of the newest polls whatever the count.
func TestPollsAreBounded(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("bounded")))
uassert.AbortsContains(t, cur, "question too long", func() { CreatePoll(cross(cur), strings.Repeat("q", MaxQuestionLen+1), "a,b") })
uassert.AbortsContains(t, cur, "at most", func() { CreatePoll(cross(cur), "many", strings.Repeat("o,", MaxOptions)+"o") })
for len(polls) < IndexRecent+3 {
CreatePoll(cross(cur), "filler", "a,b")
}
uassert.Equal(t, IndexRecent, strings.Count(Render(""), "## Poll #"))
}
// The poll count is bounded globally.
func TestPollCountIsBounded(cur realm, t *testing.T) {
before := len(polls)
for len(polls) < MaxPolls {
polls = append(polls, &Poll{ID: len(polls), Question: "q", Options: []string{"a", "b"}, Tallies: []int{0, 0}})
}
defer func() { polls = polls[:before] }()
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("latecomer")))
uassert.AbortsContains(t, cur, "polls is full", func() { CreatePoll(cross(cur), "one more", "a,b") })
}
// Polls past the newest page stay reachable: the index links to the next
// page, and a page past the end says so instead of wrapping.
func TestOlderPollsArePaged(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("pager")))
for len(polls) < IndexRecent+1 {
CreatePoll(cross(cur), "filler", "a,b")
}
idx := Render("")
uassert.True(t, strings.Contains(idx, "(/r/moul/x/daily/polls/v1:page/2)"), idx)
p2 := Render("page/2")
uassert.True(t, strings.Contains(p2, "## Poll #0:"), p2)
uassert.True(t, strings.Contains(Render("page/9223372036854775807"), "No such page"))
}
zz_escape_test.gno
package polls
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// A question and its options are the creator's text: escaped.
func TestQuestionAndOptionsAreEscaped(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("escaper")))
id := CreatePoll(cross(cur), "[claim](https://evil.example)", "[claim](https://evil.example)"+",no")
page := Render(itoaTest(id))
uassert.False(t, strings.Contains(page, "[claim](https://evil.example)"), page)
uassert.False(t, strings.Contains(Render(""), "[claim](https://evil.example)"), Render(""))
}
zz_links_test.gno
package polls
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// A poll page links back to this realm. It once linked to
// /r/REPLACE_ADDR/polls.
func TestPollPageLinksBackToThisRealm(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("linker")))
id := CreatePoll(cross(cur), "Linked?", "yes,no")
page := Render(itoaTest(id))
uassert.True(t, strings.Contains(page, "[← all polls](/r/moul/x/daily/polls/v1)"), page)
}
func itoaTest(n int) string {
if n == 0 {
return "0"
}
s := ""
for n > 0 {
s = string(rune(byte(n%10)+byte(48))) + s
n /= 10
}
return s
}
zz_zerowidth_test.gno
package polls
import (
"testing"
)
// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth
// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix
// with real spaces. strings.TrimSpace keeps every one of them and the render
// strips them all, so each must be refused.
var zwBlank = []string{
"\u200b\u200b\u200b", // ZWSP
"\u200d", // ZWJ
"\u200e", // LRM
"\u202e", // RLO
"\u2066\u2069", // LRI PDI
"\ufeff", // BOM
" \u200b \u200b ", // mixed with real spaces
}
// zwOK must stay accepted: the stripper removes the marks and leaves text.
var zwOK = []string{"a", "a\u200bb", " padded "}
func TestZeroWidthQuestionIsRefused(cur realm, t *testing.T) {
resetState()
defer resetState()
testing.SetRealm(testing.NewUserRealm(alice))
for _, s := range zwBlank {
if revive(func() { CreatePoll(cross(cur), s, "x,y") }) == nil {
t.Errorf("CreatePoll accepted question %q, which the render strips to blank", s)
}
}
for _, s := range zwOK {
if r := revive(func() { CreatePoll(cross(cur), s, "x,y") }); r != nil {
t.Errorf("CreatePoll refused question %q: %v", s, r)
}
}
if PollCount() != len(zwOK) {
t.Errorf("PollCount = %d, want %d", PollCount(), len(zwOK))
}
}
func TestZeroWidthOptionIsDropped(t *testing.T) {
for _, s := range zwBlank {
if got := parseOptions("x," + s); len(got) != 1 {
t.Errorf("parseOptions kept option %q, which the render strips to blank: %q", s, got)
}
}
for _, s := range zwOK {
if got := parseOptions("x," + s); len(got) != 2 {
t.Errorf("parseOptions dropped option %q, which renders as text: %q", s, got)
}
}
}