Playground
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/qvote/v1" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914308 max_deposit = "8000000ugnot"
qvote.gno
// Package qvote is a quadratic-voting poll board, a Gno take on the classic
// Solidity "Ballot" voting contract with one twist borrowed from mechanism
// design instead of one-address-one-vote: every voter gets a fixed voice-
// credit budget per poll, and piling votes onto a single option costs the
// square of how many votes they stack there. Buying your 1st vote on an
// option costs 1 credit, the 2nd costs 3 more (4 total), the 3rd costs 5
// more (9 total) -- so spreading conviction across options is cheap, but
// dominating one option gets expensive fast. Votes can also be pulled back
// for a matching credit refund.
package qvote
import (
"strconv"
"strings"
"chain"
"chain/markdown"
"chain/runtime"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/nt/avl/v0"
)
// InitialCredits is the fixed voice-credit budget every address gets to
// spend on each poll (shared across all of that poll's options).
const InitialCredits int64 = 100
const (
minOptions = 2
maxOptions = 8
)
type poll struct {
ID string
Creator address
Question string
Options []string
Tally []int64
CreatedHeight int64
Closed bool
}
// voterState is one address's standing inside one poll: how many credits
// they've spent so far and how many votes that bought them on each option.
type voterState struct {
CreditsUsed int64
Votes []int64
}
var (
polls avl.Tree // poll ID -> *poll
voters avl.Tree // "<pollID>:<addr>" -> *voterState
nextID int
)
func voterKey(pollID string, addr address) string {
return pollID + ":" + addr.String()
}
func getPoll(pollID string) *poll {
p, ok := polls.Get(pollID).(*poll)
if !ok {
panic("no such poll: " + pollID)
}
return p
}
func getOrCreateVoter(pollID string, addr address, numOptions int) *voterState {
key := voterKey(pollID, addr)
if v, ok := voters.Get(key).(*voterState); ok {
return v
}
vs := &voterState{Votes: make([]int64, numOptions)}
voters.Set(key, vs)
return vs
}
// square is the quadratic-voting cost curve: N votes on one option cost
// N*N credits in total.
func square(n int64) int64 {
return n * n
}
// CreatePoll opens a new poll with the given question and comma-separated
// options (at least 2, at most 8), returning its ID.
func CreatePoll(cur realm, question string, optionsCSV string) string {
creator := cur.Previous().Address()
question = strings.TrimSpace(question)
if strings.TrimSpace(markdown.StripBidiAndZeroWidth(question)) == "" {
panic("question must not be empty")
}
var options []string
for _, raw := range strings.Split(optionsCSV, ",") {
opt := strings.TrimSpace(raw)
if strings.TrimSpace(markdown.StripBidiAndZeroWidth(opt)) == "" {
continue
}
options = append(options, opt)
}
if len(options) < minOptions {
panic("need at least " + strconv.Itoa(minOptions) + " non-empty options")
}
if len(options) > maxOptions {
panic("at most " + strconv.Itoa(maxOptions) + " options are allowed")
}
nextID++
id := strconv.Itoa(nextID)
p := &poll{
ID: id,
Creator: creator,
Question: question,
Options: options,
Tally: make([]int64, len(options)),
CreatedHeight: runtime.ChainHeight(),
}
polls.Set(id, p)
chain.Emit("PollCreated", "id", id, "creator", creator.String(), "question", question)
return "poll #" + id + " created with " + strconv.Itoa(len(options)) + " options"
}
// Vote adjusts the caller's votes on one option of a poll by delta (positive
// to buy more, negative to sell some back for a credit refund). The credit
// cost of holding N votes on an option is N*N, taken from the caller's fixed
// per-poll budget of InitialCredits.
func Vote(cur realm, pollID string, optionIdx int, delta int64) string {
caller := cur.Previous().Address()
p := getPoll(pollID)
if p.Closed {
panic("poll #" + pollID + " is closed")
}
if optionIdx < 0 || optionIdx >= len(p.Options) {
panic("invalid option index")
}
if delta == 0 {
panic("delta must be non-zero")
}
vs := getOrCreateVoter(pollID, caller, len(p.Options))
current := vs.Votes[optionIdx]
updated := current + delta
if updated < 0 {
panic("cannot remove more votes than you hold on this option")
}
cost := square(updated) - square(current)
newCreditsUsed := vs.CreditsUsed + cost
if newCreditsUsed > InitialCredits {
panic("exceeds your voice-credit budget of " + strconv.FormatInt(InitialCredits, 10) +
" for this poll (would need " + strconv.FormatInt(newCreditsUsed, 10) + ")")
}
vs.Votes[optionIdx] = updated
vs.CreditsUsed = newCreditsUsed
p.Tally[optionIdx] += delta
chain.Emit("VoteCast",
"pollID", pollID,
"voter", caller.String(),
"option", p.Options[optionIdx],
"votes", strconv.FormatInt(updated, 10),
)
verb := "bought"
n := delta
if delta < 0 {
verb = "sold back"
n = -delta
}
return "you " + verb + " " + strconv.FormatInt(n, 10) + " vote(s) on \"" + p.Options[optionIdx] +
"\" -- now holding " + strconv.FormatInt(updated, 10) + " (credits used: " +
strconv.FormatInt(vs.CreditsUsed, 10) + "/" + strconv.FormatInt(InitialCredits, 10) + ")"
}
// ClosePoll ends voting on a poll. Only its creator may close it.
func ClosePoll(cur realm, pollID string) string {
caller := cur.Previous().Address()
p := getPoll(pollID)
if caller != p.Creator {
panic("only the poll creator can close it")
}
if p.Closed {
panic("poll #" + pollID + " is already closed")
}
p.Closed = true
chain.Emit("PollClosed", "id", pollID)
return "poll #" + pollID + " closed"
}
func leadingOption(p *poll) (string, int64) {
best := -1
var bestVotes int64 = -1
for i, v := range p.Tally {
if v > bestVotes {
bestVotes = v
best = i
}
}
if best < 0 {
return "", 0
}
return p.Options[best], bestVotes
}
func renderHome() string {
var b strings.Builder
b.WriteString("# Quadratic Voting\n\n")
b.WriteString("Create a poll, then spend voice credits on the options you care about -- " +
"the Nth vote you stack on one option costs N^2 credits out of a fixed budget of " +
strconv.FormatInt(InitialCredits, 10) + " per poll, so spreading support across " +
"options is cheap but dominating one gets steep fast.\n\n")
b.WriteString("## Polls\n\n")
count := 0
polls.Iterate("", "", func(key string, value interface{}) bool {
count++
p := value.(*poll)
status := "open"
if p.Closed {
status = "closed"
}
lead, votes := leadingOption(p)
line := "- #" + p.ID + " (" + status + "): " + ui.Inline(p.Question)
if lead != "" {
line += " -- leading: \"" + ui.Inline(lead) + "\" (" + strconv.FormatInt(votes, 10) + ")"
}
b.WriteString(line + "\n")
return false
})
if count == 0 {
b.WriteString("_no polls yet -- call `CreatePoll(question, \"opt1,opt2,...\")` to start one._\n")
}
b.WriteString("\n## How to use\n\n")
b.WriteString("1. `CreatePoll(\"Best pizza topping?\", \"pineapple,mushroom,pepperoni\")` -- returns a poll ID.\n")
b.WriteString("2. `Vote(pollID, optionIdx, delta)` -- e.g. `Vote(\"1\", 0, 3)` buys 3 votes on option 0 " +
"(costs 9 credits); a negative delta sells votes back for a refund.\n")
b.WriteString("3. `ClosePoll(pollID)` -- the creator ends voting.\n\n")
b.WriteString("View a poll at this realm's path plus its ID (e.g. `.../qvote:1`), " +
"or one voter's standing in it with `.../qvote:1/g1youraddress...`.\n")
return b.String()
}
func renderPoll(id string) string {
p, ok := polls.Get(id).(*poll)
if !ok {
return "# Poll #" + ui.Inline(id) + "\n\nNo such poll.\n"
}
var b strings.Builder
b.WriteString("# Poll #" + p.ID + ": " + ui.Inline(p.Question) + "\n\n")
status := "open"
if p.Closed {
status = "closed"
}
b.WriteString("- Status: " + status + "\n")
b.WriteString("- Creator: `" + p.Creator.String() + "`\n\n")
b.WriteString("## Results\n\n")
var total int64
for _, v := range p.Tally {
total += v
}
for i, opt := range p.Options {
b.WriteString(strconv.Itoa(i) + ". " + ui.Inline(opt) + " -- " +
strconv.FormatInt(p.Tally[i], 10) + " vote(s)\n")
}
b.WriteString("\nTotal votes cast: " + strconv.FormatInt(total, 10) + "\n")
return b.String()
}
func renderVoter(pollID, rawAddr string) string {
safeAddr := ui.Inline(strings.TrimSpace(rawAddr))
p, ok := polls.Get(pollID).(*poll)
if !ok {
return "# Poll #" + ui.Inline(pollID) + "\n\nNo such poll.\n"
}
var b strings.Builder
b.WriteString("# " + safeAddr + " in poll #" + p.ID + "\n\n")
state, ok := voters.Get(voterKey(pollID, address(strings.TrimSpace(rawAddr)))).(*voterState)
if !ok {
b.WriteString("No votes cast yet.\n")
return b.String()
}
b.WriteString("- Credits used: " + strconv.FormatInt(state.CreditsUsed, 10) + "/" +
strconv.FormatInt(InitialCredits, 10) + "\n\n")
for i, opt := range p.Options {
if state.Votes[i] == 0 {
continue
}
b.WriteString("- " + ui.Inline(opt) + ": " + strconv.FormatInt(state.Votes[i], 10) + " vote(s)\n")
}
return b.String()
}
// Render shows the poll board at "", one poll's results at "<pollID>", or
// one voter's standing in a poll at "<pollID>/<addr>".
func Render(path string) string {
path = strings.TrimPrefix(strings.TrimSpace(path), "/")
if path == "" {
return renderHome()
}
if idx := strings.IndexByte(path, '/'); idx >= 0 {
return renderVoter(path[:idx], path[idx+1:])
}
return renderPoll(path)
}
qvote_test.gno
package qvote
import (
"strings"
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
)
func resetState() {
polls = avl.Tree{}
voters = avl.Tree{}
nextID = 0
}
func TestSquare(t *testing.T) {
cases := []struct {
n, want int64
}{
{0, 0}, {1, 1}, {2, 4}, {3, 9}, {10, 100},
}
for _, c := range cases {
if got := square(c.n); got != c.want {
t.Fatalf("square(%d) = %d, want %d", c.n, got, c.want)
}
}
}
// Crossing: CreatePoll mutates realm state, so the test needs `cur realm`.
func TestCreatePollValidatesOptions(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
testing.SetRealm(testing.NewUserRealm(alice))
id := CreatePoll(cross(cur), "best color?", "red, green , blue")
if id != "poll #1 created with 3 options" {
t.Fatalf("unexpected message: %q", id)
}
p := getPoll("1")
if len(p.Options) != 3 || p.Options[0] != "red" || p.Options[2] != "blue" {
t.Fatalf("options not parsed/trimmed correctly: %#v", p.Options)
}
if rec := revive(func() { CreatePoll(cross(cur), "one option?", "only-one") }); rec == nil {
t.Fatal("expected panic for too few options")
}
if rec := revive(func() { CreatePoll(cross(cur), " ", "a,b") }); rec == nil {
t.Fatal("expected panic for empty question")
}
}
func TestVoteQuadraticCostAndBudget(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
testing.SetRealm(testing.NewUserRealm(alice))
CreatePoll(cross(cur), "pizza topping?", "pineapple,mushroom,pepperoni")
// 1st vote costs 1, 2nd costs 3 more (4 total), 3rd costs 5 more (9 total).
Vote(cross(cur), "1", 0, 1)
vs := getOrCreateVoter("1", alice, 3)
if vs.CreditsUsed != 1 {
t.Fatalf("credits used = %d, want 1", vs.CreditsUsed)
}
Vote(cross(cur), "1", 0, 2)
if vs.CreditsUsed != 9 || vs.Votes[0] != 3 {
t.Fatalf("after buying to 3 votes: credits=%d votes=%d, want 9/3", vs.CreditsUsed, vs.Votes[0])
}
// Spending the rest of the 100-credit budget on another option should work
// right up to the edge, then fail past it.
Vote(cross(cur), "1", 1, 9) // 81 credits, total 90
if vs.CreditsUsed != 90 {
t.Fatalf("credits used = %d, want 90", vs.CreditsUsed)
}
if rec := revive(func() { Vote(cross(cur), "1", 2, 4) }); rec == nil { // would cost 16 more, total 106 > 100
t.Fatal("expected panic for exceeding voice-credit budget")
}
p := getPoll("1")
if p.Tally[0] != 3 || p.Tally[1] != 9 {
t.Fatalf("unexpected tally: %#v", p.Tally)
}
}
func TestVoteSellBackRefundsCredits(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
testing.SetRealm(testing.NewUserRealm(alice))
CreatePoll(cross(cur), "best sea?", "north,baltic")
Vote(cross(cur), "1", 0, 4) // 16 credits, 4 votes
Vote(cross(cur), "1", 0, -1) // back to 3 votes: cost delta = 9-16 = -7
vs := getOrCreateVoter("1", alice, 2)
if vs.Votes[0] != 3 {
t.Fatalf("votes = %d, want 3", vs.Votes[0])
}
if vs.CreditsUsed != 9 {
t.Fatalf("credits used = %d, want 9", vs.CreditsUsed)
}
if getPoll("1").Tally[0] != 3 {
t.Fatalf("tally = %d, want 3", getPoll("1").Tally[0])
}
if rec := revive(func() { Vote(cross(cur), "1", 0, -10) }); rec == nil {
t.Fatal("expected panic for selling more votes than held")
}
}
func TestClosePollOnlyCreator(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
testing.SetRealm(testing.NewUserRealm(alice))
CreatePoll(cross(cur), "close me?", "yes,no")
testing.SetRealm(testing.NewUserRealm(bob))
if rec := revive(func() { ClosePoll(cross(cur), "1") }); rec == nil {
t.Fatal("expected panic when a non-creator closes the poll")
}
testing.SetRealm(testing.NewUserRealm(alice))
ClosePoll(cross(cur), "1")
if !getPoll("1").Closed {
t.Fatal("poll should be closed")
}
if rec := revive(func() { Vote(cross(cur), "1", 0, 1) }); rec == nil {
t.Fatal("expected panic when voting on a closed poll")
}
}
func TestRenderNoPolls(t *testing.T) {
resetState()
out := Render("")
if !strings.Contains(out, "no polls yet") {
t.Fatalf("expected empty-state message, got: %s", out)
}
}
func TestRenderPollNotFound(t *testing.T) {
resetState()
out := Render("42")
if !strings.Contains(out, "No such poll") {
t.Fatalf("expected not-found message, got: %s", out)
}
}
zz_zerowidth_test.gno
package qvote
import (
"testing"
"gno.land/p/nt/testutils/v0"
)
// 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 TestZeroWidthQuestionAndOptionAreRefused(cur realm, t *testing.T) {
resetState()
defer resetState()
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("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)
}
// With the blank option dropped, one option is left and the poll is refused.
if revive(func() { CreatePoll(cross(cur), "q", "x,"+s) }) == nil {
t.Errorf("CreatePoll kept option %q, which the render strips to blank", s)
}
}
for _, s := range zwOK {
if r := revive(func() { CreatePoll(cross(cur), s, "x,"+s) }); r != nil {
t.Errorf("CreatePoll refused question and option %q: %v", s, r)
}
}
if nextID != len(zwOK) {
t.Errorf("%d poll(s) created, want %d", nextID, len(zwOK))
}
}