Transaction
68B699265C6752…DD1B4B804BC9
Block 923,229 · index 0 · indexed
Summary
- Hash
- 68B699265C6752116DD741174F40C91CADA16E9CBB9B9CCEE1B9DD1B4B804BC9
- Block
- 923,229
- Size
- 20161 bytes
- Gas used
- 28,027,357 / 63,435,800
- Fee
- 190307 ugnot
- Status
- success
Messages
- Attached funds
- 8000000 ugnot
Arguments · 17
- #1polls
- #2README.md
- #3# Polls & Voting > ⚠️ **Experimental — generated with no human supervision.** This realm was > produced automatically by an MCP-driven agent to exercise the gno MCP server > and tooling, and to generate test content for gno compilers, linters and > formatters. **Not audited. Not for production.** Full context & folder README: > [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md) --- An on-chain poll and voting realm for gno.land (gno 0.9). Anyone can create a poll with a question and a comma-separated set of options; every caller address may cast exactly one vote per poll. The realm's `Render` page lists each poll with its options, live tallies drawn as `▓░` bar charts, per-option percentages, and the total number of votes. ## Realm path `gno.land/r/moul/x/daily/polls/v1` ## Exported transactions - `CreatePoll(question string, options string) int` — create a poll. `options` is a comma-separated list (blank entries are dropped; at least 2 required). Returns the new poll's id. - `Vote(pollID int, optionIndex int)` — cast one vote for `optionIndex` on poll `pollID`. One vote per caller address per poll; a second vote aborts. Both are gno 0.9 crossing functions (first parameter `cur realm`); the caller address is read via `runtime.PreviousRealm().Address()`. ## Read path - `Render("")` — index of all polls with bar-chart tallies. - `Render("<id>")` — a single poll by id. ## Example calls ```sh # create a poll (returns its id, e.g. 0) gnokey maketx call -pkgpath "gno.land/r/moul/x/daily/polls/v1" \ -func CreatePoll -args "Best L1 for smart contracts?" -args "gno,eth,sol" \ -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 mykey # vote for option index 0 on poll 0 gnokey maketx call -pkgpath "gno.land/r/moul/x/daily/polls/v1" \ -func Vote -args 0 -args 0 \ -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 mykey # view results in gnoweb # https://gno.land/r/moul/x/daily/polls/v1 # https://gno.land/r/moul/x/daily/polls/v1:0 ``` ## Testing ```sh gno test . ``` <!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --> --- Part of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage. **On mainnet:** [](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) [](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) [](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) [](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) **Dependency graph:**  > 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md). <!-- END GNOCONTRACTS FOOTER -->
- #4gnomod.toml
- #5module = "gno.land/r/moul/x/daily/polls/v1" gno = "0.9" private = true [source] repository = "https://github.com/moul/gno-contracts" path = "r/moul/x/daily/polls" revision = "507056d812b505ad16a009f0d60786644ceeb19d"
- #6polls.gno
- #7// 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/moul/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() }
- #8polls_test.gno
- #9package 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) } }
- #10zz_bounds_test.gno
- #11package 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")) }
- #12zz_escape_test.gno
- #13package 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("")) }
- #14zz_links_test.gno
- #15package 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 }
- #16zz_zerowidth_test.gno
- #17package 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) } } }
Result log
msg:0,success:true,log:,events:[]