Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

ballot.gno

// Package ballot is a Gno port of the classic Solidity "Ballot" voting
// contract from the Solidity docs. A chairperson seeds a fixed list of
// proposals and grants specific addresses the right to vote; each voter can
// either cast a direct vote or delegate their weight to another voter, and
// delegation follows a chain so a delegate who later delegates further still
// carries every accumulated weight. The winning proposal is whichever has
// the most accumulated weight at query time.
package ballot

import (
	"errors"
	"strconv"
	"strings"

	"gno.land/p/nt/avl/v0"
)

// proposal is one of the fixed choices set up at Init time.
type proposal struct {
	name  string
	votes uint64
}

// voterInfo tracks one address's voting rights and delegation state.
type voterInfo struct {
	weight   uint64  // 0 means "no right to vote"
	voted    bool    // true once the weight has been cast (directly or delegated away)
	delegate address // set only when voted == true and this voter delegated
	vote     int     // proposal index this voter's weight ended up on, valid once tallied
}

// Package-level persistent state.
var (
	chairperson address
	initialized bool
	proposals   []proposal
	voters      *avl.Tree // address string -> *voterInfo
)

var (
	errAlreadyInit    = errors.New("ballot: already initialized")
	errNotInit        = errors.New("ballot: not initialized yet")
	errNotChairperson = errors.New("ballot: only the chairperson may do this")
	errNoProposals    = errors.New("ballot: at least one proposal name is required")
	errInvalidAddr    = errors.New("ballot: invalid address")
	errAlreadyRight   = errors.New("ballot: voter already has the right to vote")
	errAlreadyVoted   = errors.New("ballot: voter already voted")
	errNoRight        = errors.New("ballot: caller has no right to vote")
	errSelfDelegate   = errors.New("ballot: self-delegation is not allowed")
	errDelegateLoop   = errors.New("ballot: found a loop in the delegation chain")
	errDelegateNoRight = errors.New("ballot: delegate has no right to vote")
	errBadProposal    = errors.New("ballot: invalid proposal index")
)

func init() {
	voters = avl.NewTree()
}

func requireInit() {
	if !initialized {
		panic(errNotInit)
	}
}

func getOrCreateVoter(addr address) *voterInfo {
	if v := voters.Get(addr.String()); v != nil {
		return v.(*voterInfo)
	}
	v := &voterInfo{}
	voters.Set(addr.String(), v)
	return v
}

// Init configures the ballot exactly once: the caller becomes the
// chairperson (and is immediately given the right to vote), and
// proposalNamesCSV — a comma-separated list — seeds the fixed set of
// proposals. It panics if called twice or with no usable proposal names.
func Init(cur realm, proposalNamesCSV string) {
	if initialized {
		panic(errAlreadyInit)
	}

	for _, raw := range strings.Split(proposalNamesCSV, ",") {
		name := strings.TrimSpace(raw)
		if name == "" {
			continue
		}
		proposals = append(proposals, proposal{name: name})
	}
	if len(proposals) == 0 {
		panic(errNoProposals)
	}

	chairperson = cur.Previous().Address()
	voters.Set(chairperson.String(), &voterInfo{weight: 1})
	initialized = true
}

// GiveRightToVote grants voterAddr a voting weight of 1. Only the
// chairperson may call this, and only for voters who haven't voted yet.
func GiveRightToVote(cur realm, voterAddr string) {
	requireInit()
	if cur.Previous().Address() != chairperson {
		panic(errNotChairperson)
	}

	addr := address(voterAddr)
	if !addr.IsValid() {
		panic(errInvalidAddr)
	}

	v := getOrCreateVoter(addr)
	if v.voted {
		panic(errAlreadyVoted)
	}
	if v.weight != 0 {
		panic(errAlreadyRight)
	}
	v.weight = 1
}

// Delegate hands the caller's voting weight to toAddr. If toAddr has
// already voted, the weight is added directly to that proposal's tally;
// otherwise it accumulates on toAddr's own weight, ready to be cast (or
// delegated further) later. Mirrors Solidity's delegation-chain-following
// with a loop guard.
func Delegate(cur realm, toAddr string) {
	requireInit()

	sender := cur.Previous().Address()
	from := getOrCreateVoter(sender)
	if from.weight == 0 {
		panic(errNoRight)
	}
	if from.voted {
		panic(errAlreadyVoted)
	}

	to := address(toAddr)
	if !to.IsValid() {
		panic(errInvalidAddr)
	}
	if to == sender {
		panic(errSelfDelegate)
	}

	var zero address
	maxSteps := voters.Size() + 1
	for steps := 0; ; steps++ {
		v := voters.Get(to.String())
		if v == nil {
			break
		}
		next := v.(*voterInfo).delegate
		if next == zero {
			break
		}
		to = next
		if to == sender {
			panic(errDelegateLoop)
		}
		if steps > maxSteps {
			panic(errDelegateLoop)
		}
	}

	delegateVoter := getOrCreateVoter(to)
	if delegateVoter.weight == 0 {
		panic(errDelegateNoRight)
	}

	from.voted = true
	from.delegate = to

	if delegateVoter.voted {
		proposals[delegateVoter.vote].votes += from.weight
	} else {
		delegateVoter.weight += from.weight
	}
}

// Vote casts the caller's full weight for proposals[proposalIndex].
func Vote(cur realm, proposalIndex int) {
	requireInit()

	sender := cur.Previous().Address()
	v := getOrCreateVoter(sender)
	if v.weight == 0 {
		panic(errNoRight)
	}
	if v.voted {
		panic(errAlreadyVoted)
	}
	if proposalIndex < 0 || proposalIndex >= len(proposals) {
		panic(errBadProposal)
	}

	v.voted = true
	v.vote = proposalIndex
	proposals[proposalIndex].votes += v.weight
}

// WinningProposal returns the index of the proposal with the most
// accumulated weight, breaking ties in favor of the lowest index.
func WinningProposal() int {
	winner := 0
	best := uint64(0)
	for i, p := range proposals {
		if p.votes > best {
			best = p.votes
			winner = i
		}
	}
	return winner
}

// WinnerName returns the name of the current winning proposal, or "" if
// the ballot hasn't been initialized.
func WinnerName() string {
	if len(proposals) == 0 {
		return ""
	}
	return proposals[WinningProposal()].name
}

func Render(path string) string {
	var b strings.Builder
	b.WriteString("# Ballot\n\n")

	if !initialized {
		b.WriteString("Not initialized yet. The first caller to run `Init` becomes the " +
			"chairperson and seeds the proposal list, e.g.:\n\n")
		b.WriteString("```\nInit(\"Alice,Bob,Carol\")\n```\n")
		return b.String()
	}

	b.WriteString("Chairperson: `" + chairperson.String() + "`\n\n")
	b.WriteString("| # | Proposal | Votes |\n")
	b.WriteString("|---|---|---|\n")
	for i, p := range proposals {
		b.WriteString("| " + strconv.Itoa(i) + " | " + p.name + " | " +
			strconv.FormatUint(p.votes, 10) + " |\n")
	}

	b.WriteString("\nCurrent winner: **" + WinnerName() + "** (index " +
		strconv.Itoa(WinningProposal()) + ")\n\n")
	b.WriteString("Registered voters: " + strconv.Itoa(voters.Size()) + "\n")
	return b.String()
}

ballot_test.gno

package ballot

import (
	"strings"
	"testing"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/testutils/v0"
)

func resetState() {
	var zero address
	chairperson = zero
	initialized = false
	proposals = nil
	voters = avl.NewTree()
}

// Crossing: Init/Vote/Delegate/GiveRightToVote mutate realm state, so tests
// that call them need `cur realm`.
func TestInitSetsChairpersonAndProposals(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")

	testing.SetRealm(testing.NewUserRealm(alice))
	Init(cross(cur), "Alice, Bob , Carol")

	if chairperson != alice {
		t.Fatal("chairperson should be the Init caller")
	}
	if len(proposals) != 3 {
		t.Fatalf("len(proposals) = %d, want 3", len(proposals))
	}
	if proposals[0].name != "Alice" || proposals[1].name != "Bob" || proposals[2].name != "Carol" {
		t.Fatal("proposal names should be trimmed and in order")
	}

	rec := revive(func() { Init(cross(cur), "X") })
	if rec == nil {
		t.Fatal("expected panic on double Init")
	}
}

func TestGiveRightToVoteOnlyChairperson(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")
	mallory := testutils.TestAddress("mallory")

	testing.SetRealm(testing.NewUserRealm(alice))
	Init(cross(cur), "A,B")

	testing.SetRealm(testing.NewUserRealm(mallory))
	rec := revive(func() { GiveRightToVote(cross(cur), bob.String()) })
	if rec == nil {
		t.Fatal("expected panic when a non-chairperson grants voting rights")
	}

	testing.SetRealm(testing.NewUserRealm(alice))
	GiveRightToVote(cross(cur), bob.String())

	v := voters.Get(bob.String())
	if v == nil || v.(*voterInfo).weight != 1 {
		t.Fatal("bob should now have voting weight 1")
	}
}

func TestVoteDirectly(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")

	testing.SetRealm(testing.NewUserRealm(alice))
	Init(cross(cur), "A,B")
	Vote(cross(cur), 1)

	if proposals[1].votes != 1 {
		t.Fatalf("proposals[1].votes = %d, want 1", proposals[1].votes)
	}
	if WinnerName() != "B" {
		t.Fatalf("WinnerName() = %q, want B", WinnerName())
	}

	rec := revive(func() { Vote(cross(cur), 0) })
	if rec == nil {
		t.Fatal("expected panic on double vote")
	}
}

func TestDelegateToUnvotedAccumulatesWeight(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")

	testing.SetRealm(testing.NewUserRealm(alice))
	Init(cross(cur), "A,B")
	GiveRightToVote(cross(cur), bob.String())

	testing.SetRealm(testing.NewUserRealm(bob))
	Delegate(cross(cur), alice.String())

	aliceVoter := voters.Get(alice.String())
	if aliceVoter.(*voterInfo).weight != 2 {
		t.Fatalf("alice.weight = %d, want 2", aliceVoter.(*voterInfo).weight)
	}

	testing.SetRealm(testing.NewUserRealm(alice))
	Vote(cross(cur), 0)

	if proposals[0].votes != 2 {
		t.Fatalf("proposals[0].votes = %d, want 2 (alice's own weight + bob's delegation)", proposals[0].votes)
	}
}

func TestDelegateToAlreadyVotedAddsDirectly(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")

	testing.SetRealm(testing.NewUserRealm(alice))
	Init(cross(cur), "A,B")
	GiveRightToVote(cross(cur), bob.String())
	Vote(cross(cur), 1)

	testing.SetRealm(testing.NewUserRealm(bob))
	Delegate(cross(cur), alice.String())

	if proposals[1].votes != 2 {
		t.Fatalf("proposals[1].votes = %d, want 2 (alice's vote + bob's delegated weight)", proposals[1].votes)
	}
}

func TestSelfDelegatePanics(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")

	testing.SetRealm(testing.NewUserRealm(alice))
	Init(cross(cur), "A,B")

	rec := revive(func() { Delegate(cross(cur), alice.String()) })
	if rec == nil {
		t.Fatal("expected panic on self-delegation")
	}
}

func TestDelegateLoopPanics(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")
	carol := testutils.TestAddress("carol")

	testing.SetRealm(testing.NewUserRealm(alice))
	Init(cross(cur), "A,B")
	GiveRightToVote(cross(cur), bob.String())
	GiveRightToVote(cross(cur), carol.String())

	// alice -> bob
	testing.SetRealm(testing.NewUserRealm(alice))
	Delegate(cross(cur), bob.String())

	// carol -> alice would close the loop carol -> alice -> bob if bob then
	// delegated back to carol; instead exercise the direct A -> B -> A cycle:
	testing.SetRealm(testing.NewUserRealm(carol))
	rec := revive(func() {
		// bob has no delegate yet (he's an accumulation point), so seed a
		// cycle by having carol delegate to bob, then bob delegate to carol.
		Delegate(cross(cur), bob.String())
	})
	if rec != nil {
		t.Fatal("carol -> bob should succeed (bob hasn't voted or delegated)")
	}

	testing.SetRealm(testing.NewUserRealm(bob))
	rec = revive(func() { Delegate(cross(cur), carol.String()) })
	if rec == nil {
		t.Fatal("expected panic when closing a delegation loop (bob -> carol -> bob)")
	}
}

func TestWinningProposalTieBreaksLowestIndex(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")

	testing.SetRealm(testing.NewUserRealm(alice))
	Init(cross(cur), "A,B,C")
	GiveRightToVote(cross(cur), bob.String())
	Vote(cross(cur), 1)

	testing.SetRealm(testing.NewUserRealm(bob))
	Vote(cross(cur), 0)

	if WinningProposal() != 0 {
		t.Fatalf("WinningProposal() = %d, want 0 (tie broken toward lowest index)", WinningProposal())
	}
}

// Non-crossing: Render is a plain read.
func TestRenderBeforeInit(t *testing.T) {
	resetState()
	if out := Render(""); out == "" {
		t.Fatal(`Render("") should not be empty before Init`)
	}
}

func TestRenderAfterInit(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")

	testing.SetRealm(testing.NewUserRealm(alice))
	Init(cross(cur), "A,B")
	Vote(cross(cur), 0)

	out := Render("")
	if !strings.Contains(out, "A") || !strings.Contains(out, alice.String()) {
		t.Fatal("Render should include the proposal names and the chairperson address")
	}
}

gnomod.toml

module = "gno.land/r/nym-moultest123/x/daily/ballot/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186407
  max_deposit = "7000000ugnot"