Playground
binding.gno
package sharedpoll
import (
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/core/v1"
"gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/sharedmembers"
)
// sharedPath is the reviewed shared membership realm this app is bound to.
const sharedPath = "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/sharedmembers"
// sharedReader adapts the shared membership realm to core.MembershipReader.
// It is read-only: it can look roles up and take snapshots, nothing else.
type sharedReader struct{}
func (sharedReader) RoleOf(addr address) core.Role { return sharedmembers.RoleOf(addr) }
func (sharedReader) Size() int { return sharedmembers.Size() }
func (sharedReader) Snapshot(minRole core.Role, max int) ([]address, bool) {
return sharedmembers.Snapshot(minRole, max)
}
// electorate is the membership source for poll electorates. Tests replace
// it with a local fake; production code never reassigns it.
var electorate core.MembershipReader = sharedReader{}
gnomod.toml
module = "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/sharedpoll" gno = "0.9" [addpkg] creator = "g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm" height = 246771 max_deposit = "100000000ugnot"
render.gno
package sharedpoll
import (
"strconv"
"strings"
"time"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/core/v1"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/render/v1"
)
// Render serves the overview, the poll list and single polls.
func Render(path string) string {
if admins == nil {
return render.Heading(1, "Shared-membership poll") + "This app is not initialized.\n"
}
segs, q := render.ParsePath(path)
switch {
case len(segs) == 0:
return renderHome()
case segs[0] == "polls" && len(segs) == 1:
pages := render.PageCount(polls.Count(), pageSize)
page := render.Page(q, pages)
return render.Heading(1, "Polls") +
renderPollTable(polls.List((page-1)*pageSize, pageSize)) +
render.Pager(pkgPath, "polls", page, pages)
case segs[0] == "polls" && len(segs) == 2:
id, err := strconv.ParseUint(segs[1], 10, 64)
if err == nil {
if v, ok := polls.Ballot(id); ok {
return renderPoll(v)
}
}
}
return render.Heading(1, "Not found") + render.Link("Back", render.RealmURL(pkgPath, "")) + "\n"
}
func renderHome() string {
var sb strings.Builder
sb.WriteString(render.Heading(1, "Shared-membership poll"))
sb.WriteString("Voters come from " + render.Link(sharedPath, render.RealmURL(sharedPath, "")) +
", snapshotted when each poll opens. Join or leave there.\n\n")
sb.WriteString(renderPollTable(polls.List(0, 5)))
sb.WriteString(render.Link("All polls", render.RealmURL(pkgPath, "polls")) + "\n")
return sb.String()
}
func renderPollTable(list []core.BallotView) string {
if len(list) == 0 {
return "No polls yet.\n\n"
}
var rows [][]string
for _, v := range list {
id := strconv.FormatUint(v.ID, 10)
rows = append(rows, render.TrustedRow(
render.Link("#"+id, render.RealmURL(pkgPath, "polls/"+id)),
render.Text(v.Title),
render.Text(v.Status.String()),
strconv.Itoa(v.Turnout),
))
}
return render.Table([]string{"Poll", "Title", "Status", "Ballots"}, rows)
}
func renderPoll(v core.BallotView) string {
now := time.Now().Unix()
id := strconv.FormatUint(v.ID, 10)
var sb strings.Builder
sb.WriteString(render.Heading(1, v.Title))
sb.WriteString("Status: **" + render.Text(v.Status.String()) + "** · electorate " + strconv.Itoa(v.ElectorateSize) + "\n\n")
var rows [][]string
for i, opt := range v.Options {
action := ""
if v.Status == core.BallotOpen && now < v.Deadline {
action = render.TxLink("vote", pkgPath, "Vote", "id", id, "choice", strconv.Itoa(i))
}
rows = append(rows, render.TrustedRow(render.Text(opt), strconv.Itoa(v.Counts[i]), action))
}
sb.WriteString(render.Table([]string{"Option", "Votes", ""}, rows))
if v.Status == core.BallotFinalized {
res := v.Outcome.String()
if v.Outcome == core.OutcomeWinner {
res = "winner: " + v.Options[v.Winner]
}
sb.WriteString("Result: **" + render.Text(res) + "**\n")
} else if v.Status == core.BallotOpen && now >= v.Deadline {
sb.WriteString(render.TxLink("Finalize result", pkgPath, "Finalize", "id", id) + "\n")
}
return sb.String()
}
sharedpoll.gno
// Package sharedpoll is the Remix Lab shared-membership composition demo: a
// poll app whose electorate comes from an existing shared membership realm
// instead of its own member list.
//
// The shared realm is consulted read-only, when a poll opens, to snapshot
// its members. People join or leave through the shared realm's own
// interface. This app's administrators (who may create and open polls) are
// a separate, local set seeded with the deployer.
package sharedpoll
import (
"strings"
"time"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/ballots/v1"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/core/v1"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/membership/v1"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/policies/v1"
)
const (
pkgPath = "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/remixlab/sharedpoll"
recipeID = "shared-poll-demo"
recipeVersion = "1.0.0"
pageSize = 25
optionSep = "|"
configDigest = "unset"
)
const (
opAdmins = "admins.manage"
opCreate = "poll.create"
opOpen = "poll.open"
opPolicy = "policy.set"
)
var (
admins *membership.Set
policy *policies.Policy
polls *ballots.Box
)
func init(cur realm) {
deployer := cur.Previous()
if deployer.IsUser() && deployer.Address().IsValid() {
setup(deployer.Address())
}
}
func setup(owner address) {
admins = membership.New(membership.Config{
JoinMode: membership.JoinInvitation,
MaxMembers: 10,
}, owner)
policy = policies.New(admins)
policy.Define(opAdmins, policies.RuleOwner, policies.RuleOwner)
policy.Define(opCreate, policies.RuleOwner, policies.RuleReviewer)
policy.Define(opOpen, policies.RuleOwner, policies.RuleReviewer)
policy.Define(opPolicy, policies.RuleOwner, policies.RuleOwner)
polls = ballots.NewBox(ballots.Config{
MaxBallots: 100,
MaxOptions: 20,
MaxElectorate: 100,
QuorumPercent: 0,
AllowAbstain: false,
MinDuration: 60,
MaxDuration: 2592000,
MaxTitleBytes: 140,
MaxOptionBytes: 80,
})
}
// Descriptor identifies this app's recipe, components and bindings.
func Descriptor() core.AppDescriptor {
return core.AppDescriptor{
Recipe: recipeID,
RecipeVersion: recipeVersion,
Components: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
ConfigDigest: configDigest,
ViewSchemaVersion: core.ViewSchemaVersion,
Bindings: []string{"membership.read/v1=" + sharedPath},
}
}
// AddAdmin grants addr a local administrative role ("reviewer" or "owner").
func AddAdmin(cur realm, addr address, role string) {
authorize(cur, opAdmins)
r, err := core.ParseRole(role)
must(err)
if r != core.RoleReviewer && r != core.RoleOwner {
panic(core.Errorf(core.ErrInvalidInput, "admins are reviewers or owners").Error())
}
must(admins.Add(addr, r))
}
// RemoveAdmin removes a local administrator.
func RemoveAdmin(cur realm, addr address) {
authorize(cur, opAdmins)
must(admins.Remove(addr))
}
// CreatePoll creates a draft poll. options are separated by "|".
func CreatePoll(cur realm, title string, options string, durationSeconds int64) uint64 {
actor := authorize(cur, opCreate)
id, err := polls.Create(actor, title, strings.Split(options, optionSep), durationSeconds)
must(err)
return id
}
// CancelPoll deletes a draft poll that was never opened. The poll's creator
// may cancel it, and so may anyone allowed to open polls.
func CancelPoll(cur realm, id uint64) {
ready()
actor := cur.Previous().Address()
if creator, ok := polls.Creator(id); ok && creator == actor {
must(policy.Authorize(opCreate, actor))
} else {
must(policy.Authorize(opOpen, actor))
}
must(polls.CancelDraft(id))
}
// OpenPoll snapshots the shared realm's current members as the electorate.
func OpenPoll(cur realm, id uint64) {
authorize(cur, opOpen)
voters, ok := electorate.Snapshot(core.RoleMember, polls.Config().MaxElectorate)
if !ok {
panic(core.Errorf(core.ErrLimitExceeded, "electorate too large").Error())
}
must(polls.OpenWithElectorate(id, time.Now().Unix(), voters))
}
// Vote casts the caller's vote for option index choice.
func Vote(cur realm, id uint64, choice int) {
ready()
must(polls.Vote(id, cur.Previous().Address(), choice, time.Now().Unix()))
}
// Finalize commits a poll's result once its deadline has passed.
func Finalize(cur realm, id uint64) {
ready()
_, err := polls.Finalize(id, time.Now().Unix())
must(err)
}
// SetRule changes the rule for an operation, within its floor.
func SetRule(cur realm, op string, rule string) {
authorize(cur, opPolicy)
r, err := policies.ParseRule(rule)
must(err)
must(policy.Set(op, r))
}
// Poll returns an inert summary of poll id.
func Poll(id uint64) (core.BallotView, bool) {
ready()
return polls.Ballot(id)
}
// Polls pages through polls, newest first.
func Polls(offset, limit int) []core.BallotView {
ready()
if limit < 1 || limit > pageSize {
limit = pageSize
}
return polls.List(offset, limit)
}
// AdminRole returns addr's local administrative role name ("none" when
// addr is not an administrator).
func AdminRole(addr address) string {
ready()
return admins.RoleOf(addr).String()
}
// HasVoted reports whether addr voted in poll id.
func HasVoted(id uint64, addr address) bool {
ready()
return polls.HasVoted(id, addr)
}
func authorize(cur realm, op string) address {
ready()
actor := cur.Previous().Address()
must(policy.Authorize(op, actor))
return actor
}
func ready() {
if admins == nil {
panic(core.Errorf(core.ErrInvalidState, "app is not initialized").Error())
}
}
func must(err error) {
if err != nil {
panic(err.Error())
}
}