Playground
gnomod.toml
module = "gno.land/r/nym-mnsrehearsal001/nsvote/v1" gno = "0.9" [addpkg] creator = "g1lh4rrf9pq9k9tvka9p6vwhyv70e4h09szap6zu" height = 452730 max_deposit = "10000000ugnot"
read.gno
package nsvote
import (
"strings"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
)
// Everything a caller needs about one request, on one line. Fields are
// separated by "|" rather than "," because a reason may well contain a
// comma; it may not contain "|" or a newline, which Propose enforces.
func row(id int64, p *Proposal) string {
kind := p.kind
if kind == "" {
kind = "domain" // anything written before kinds existed
}
return ufmt.Sprintf("%d|%s|%s|%s|%s|%d|%d|%d|%s|%d",
id, kind, p.label, p.proposer.String(), p.reason,
p.created, p.yes, p.no, p.status, p.decided)
}
// ListProposals pages newest first, which is the order anybody actually
// wants to read them in.
func ListProposals(after string, limit int) (rows, next string) {
if limit <= 0 || limit > maxPage {
limit = maxPage
}
var keys []string
proposals.Iterate("", "", func(k string, _ any) bool {
keys = append(keys, k)
return false
})
var b strings.Builder
n := 0
last := ""
started := after == ""
// Walk backwards for newest-first; `after` is the last key returned.
for i := len(keys) - 1; i >= 0; i-- {
k := keys[i]
if !started {
if k == after {
started = true
}
continue
}
if n >= limit {
return b.String(), last
}
v := proposals.Get(k)
if v == nil {
continue
}
if b.Len() > 0 {
b.WriteString("\n")
}
p := v.(*Proposal)
b.WriteString(row(parseKey(k), p))
last = k
n++
}
return b.String(), ""
}
func parseKey(k string) int64 {
var out int64
for i := 0; i < len(k); i++ {
if k[i] < '0' || k[i] > '9' {
return 0
}
out = out*10 + int64(k[i]-'0')
}
return out
}
func GetProposal(id int64) string {
v := proposals.Get(key(id))
if v == nil {
return ""
}
return row(id, v.(*Proposal))
}
func CountProposals() int64 { return int64(proposals.Size()) }
// HasVoted lets the page grey out a button instead of letting somebody
// sign a transaction that is certain to be rejected.
func HasVoted(id int64, voter address) string {
v := votes.Get(voteKey(id, voter))
if v == nil {
return ""
}
return v.(string)
}
// CanTakePart answers the one question the page needs before it offers
// any of this: does this address hold a name.
func CanTakePart(who address) bool { return nsdata.BalanceOf(who) > 0 }
// Roster is the raw material for the leaderboards: one line per name,
// owner first, so the caller can aggregate however it likes.
//
// It lives here rather than in nslogic because this realm is being
// deployed anyway and nslogic is not — adding it there would have cost
// a fresh deployment of the largest realm we have, for a read.
//
// Paged, and the page walks every name in it. That is fine at the scale
// this registry is at and it will not be fine at fifty thousand names;
// at that point the aggregate belongs somewhere it is kept as it
// changes rather than recomputed on every read.
func Roster(after string, limit int) (rows, next string) {
if limit <= 0 || limit > maxPage {
limit = maxPage
}
keys, nxt := nsdata.ExportNames("", after, limit)
var b strings.Builder
for _, k := range strings.Split(keys, ",") {
if k == "" {
continue
}
at := strings.Index(k, "*")
if at < 0 {
continue
}
domainLabel, label := k[:at], k[at+1:]
owner, registered, expires, streak, frozen, _ := nsdata.GetNameInfo(label, domainLabel)
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString(ufmt.Sprintf("%s|%s*%s|%d|%d|%d|%t",
owner.String(), label, domainLabel, registered, expires, streak, frozen))
}
return b.String(), nxt
}
// Version lets a caller find out what it is talking to BEFORE it sends a
// transaction that would be rejected for having the wrong number of
// arguments.
//
// v1 has no such function, so a nil answer is itself the answer: an
// older realm. That is cheaper and more honest than the site assuming
// the newest shape and failing at signing time, which is exactly what
// happened when Propose grew a `kind`.
func Version() string { return "v2" }
types.gno
// Package nsvote holds domain requests and the votes on them.
//
// A SEPARATE REALM, and deliberately so. It never writes to nsdata: it
// only reads it, to answer two questions — does this address hold a
// name, and who is the admin. So it needs no trusted-logic grant, it
// cannot corrupt the registry however wrong its own logic turns out to
// be, and it can be replaced or abandoned without touching a single
// name anybody owns.
//
// WHAT IT DOES NOT DO
//
// It does not create domains. A vote is advice; creating the domain
// stays a deliberate admin call in nslogic. Wiring the two together
// would mean a majority could add a domain nobody had looked at, and
// the vault has no undo.
//
// It holds no funds, at any point, for anybody. The only cost of
// proposing or voting is the storage each writer pays for their own
// bytes, which the chain moves directly and which comes back if the
// record is ever deleted.
package nsvote
import (
"gno.land/p/nt/avl/v0"
)
// Two things get asked for here, and they are not the same request.
//
// domain a new *domain to sell names under
// chain a new blockchain to accept an address for on profiles
//
// The kind is stored rather than inferred from the label, because
// "solana" is a plausible request of either sort and guessing wrong
// files somebody's vote under the wrong question.
type Proposal struct {
kind string // "domain" | "chain"
label string // the domain, or the chain's ticker
reason string // why, capped: this is storage somebody is paying for
proposer address
created int64 // unix seconds
yes int64
no int64
status string // "open" | "accepted" | "rejected" | "withdrawn"
decided int64 // unix seconds, 0 while open
}
var (
proposals avl.Tree // id (zero-padded) -> *Proposal
votes avl.Tree // id + "/" + voter -> "y" | "n"
nextID int64 = 1
// A reason is a sentence, not an essay. Every character is storage
// the proposer pays for and the chain keeps.
maxReason = 280
// Reading a page walks every name in it, so the ceiling protects the
// node rather than the caller.
maxPage = 200
)
vote.gno
package nsvote
import (
"chain/runtime/unsafe"
"strconv"
"strings"
"time"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
)
// A name is the ballot. Not a token balance and not a GNOT balance:
// holding a name is the one thing that cannot be borrowed for an
// afternoon, and it is the population this actually concerns.
func assertHolder(caller address) {
if nsdata.BalanceOf(caller) <= 0 {
panic("nsvote: only a name holder may take part")
}
}
/*
assertNoSend refuses coins, on every entry point.
types.gno states "It holds no funds, at any point, for anybody" — and
until now nothing enforced it. This package contained no banker, no
OriginSend and no withdrawal path of any kind, so ugnot attached to a
Propose or a Vote landed at the realm's address and stayed there
forever, unreachable even by a successor realm. Nobody would do it on
purpose; a fat-fingered wallet or a script reusing a payment helper
would.
The early return matters: a call arriving from another realm carries no
OriginSend of its own to inspect, and treating that as an error would
break composition for a check that has nothing to look at.
*/
func assertNoSend(cur realm) {
if !cur.Previous().IsUserCall() {
return
}
if len(unsafe.OriginSend()) > 0 {
panic("nsvote: this call takes no payment")
}
}
// The admin is READ FROM THE VAULT rather than stored here. Two copies
// of "who is in charge" is how a revoked admin keeps power somewhere
// nobody remembered to look.
func assertIsAdmin(caller address) {
if caller != nsdata.GetAdmin() {
panic("nsvote: admin only")
}
}
// Sortable keys, so paging is in creation order rather than the order
// the strings happen to compare in. 000000001 sorts before 000000010.
func key(id int64) string {
s := strconv.FormatInt(id, 10)
for len(s) < 9 {
s = "0" + s
}
return s
}
func voteKey(id int64, voter address) string { return key(id) + "/" + voter.String() }
// The same shape a domain must have. A chain is asked for by its ticker,
// which fits the same rule, so one check covers both — and it keeps a
// proposal from asking for something that could never be created.
func assertLabel(label string) {
if len(label) < 1 || len(label) > 63 {
panic("nsvote: a domain is 1 to 63 characters")
}
for i := 0; i < len(label); i++ {
c := label[i]
ok := (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-'
if !ok {
panic("nsvote: lowercase letters, digits and hyphens only")
}
}
if label[0] == '-' || label[len(label)-1] == '-' {
panic("nsvote: a domain cannot start or end with a hyphen")
}
}
// Propose asks for a domain or for a chain. Anyone holding a name may ask.
//
// The proposer pays the storage for their own proposal, and nothing
// else. That cost is the whole of the spam control: it is small enough
// that a real request is nothing to think about and large enough that
// filling the tree with rubbish is not free.
func Propose(cur realm, kind, label, reason string) int64 {
assertNoSend(cur)
caller := cur.Previous().Address()
assertHolder(caller)
if kind != "domain" && kind != "chain" {
panic("nsvote: kind is domain or chain")
}
assertLabel(label)
if len(reason) > maxReason {
panic(ufmt.Sprintf("nsvote: a reason is at most %d characters", maxReason))
}
/* NEITHER A NEWLINE NOR A PIPE. read.gno joins a proposal's fields
with "|" and its comment claimed Propose enforced this; it did
not. A reason carrying pipes arrived at the site as extra fields,
and the site's parser accepted any row with AT LEAST ten — so the
reason's own pipes became the created/yes/no/status/decided
columns. One cheap name bought a permanent card reading
"9412 for / 3 against · accepted" on a proposal with no votes.
The chain state was always correct; the forgery lived entirely in
the rendering, which is what makes an unchecked separator in a
packed row worth a panic rather than an escape. */
if strings.ContainsAny(reason, "|\n\r") {
panic("nsvote: a reason may not contain '|' or a newline")
}
// Only a DOMAIN request can be checked against the registry. Whether
// a chain is already supported on profiles is a fact about the
// website, which this realm has no way to know and should not
// pretend to.
if kind == "domain" && nsdata.DomainExists(label) {
panic("nsvote: that domain already exists")
}
// One open request per label PER KIND. Two identical proposals split
// the vote and neither ever looks convincing — but a domain called
// solana and a chain called solana are different questions and must
// not block each other.
dup := false
proposals.Iterate("", "", func(k string, v any) bool {
p := v.(*Proposal)
if p.status == "open" && p.kind == kind && p.label == label {
dup = true
return true
}
return false
})
if dup {
panic("nsvote: there is already an open request for that")
}
id := nextID
nextID++
proposals.Set(key(id), &Proposal{
kind: kind, label: label, reason: reason, proposer: caller,
created: time.Now().Unix(), status: "open",
})
return id
}
// Vote records a yes or no. One per address per proposal, and it cannot
// be changed: a vote that can be switched turns the count into a race
// against whoever is watching, and there is no deadline here to make
// that fair.
func Vote(cur realm, id int64, yes bool) {
assertNoSend(cur)
caller := cur.Previous().Address()
assertHolder(caller)
v := proposals.Get(key(id))
if v == nil {
panic("nsvote: no such request")
}
p := v.(*Proposal)
if p.status != "open" {
panic("nsvote: that request is closed")
}
if votes.Get(voteKey(id, caller)) != nil {
panic("nsvote: you have already voted on this one")
}
mark := "n"
if yes {
mark = "y"
p.yes++
} else {
p.no++
}
votes.Set(voteKey(id, caller), mark)
}
// Withdraw closes a request the proposer no longer wants. The votes
// already cast stay: deleting them would refund their storage to
// whoever called this, which is not the person who paid it.
func Withdraw(cur realm, id int64) {
assertNoSend(cur)
caller := cur.Previous().Address()
v := proposals.Get(key(id))
if v == nil {
panic("nsvote: no such request")
}
p := v.(*Proposal)
if p.proposer != caller {
panic("nsvote: only the proposer may withdraw it")
}
if p.status != "open" {
panic("nsvote: that request is already closed")
}
p.status = "withdrawn"
p.decided = time.Now().Unix()
}
// Resolve records what was decided. It does NOT create the domain —
// that stays a separate, deliberate call in nslogic. A vote is advice,
// and the vault has no undo.
func Resolve(cur realm, id int64, accepted bool) {
assertNoSend(cur)
assertIsAdmin(cur.Previous().Address())
v := proposals.Get(key(id))
if v == nil {
panic("nsvote: no such request")
}
p := v.(*Proposal)
if p.status != "open" {
panic("nsvote: that request is already closed")
}
if accepted {
p.status = "accepted"
} else {
p.status = "rejected"
}
p.decided = time.Now().Unix()
}
// Purge deletes a closed request and its votes, releasing the storage.
//
// The refund goes to WHOEVER SIGNS THIS, which is not the people who
// paid — so it is admin-only and it is not a tidying operation to run
// casually. It exists because a registry that can only ever grow is
// worse, not because reclaiming somebody else's deposit is free money.
func Purge(cur realm, id int64) int64 {
assertNoSend(cur)
assertIsAdmin(cur.Previous().Address())
v := proposals.Get(key(id))
if v == nil {
panic("nsvote: no such request")
}
p := v.(*Proposal)
if p.status == "open" {
panic("nsvote: an open request cannot be purged")
}
// Collect first, mutate after: removing during an iteration walks a
// tree that is changing underneath the walk.
prefix := key(id) + "/"
var doomed []string
votes.Iterate(prefix, prefix+"\xff", func(k string, _ any) bool {
doomed = append(doomed, k)
return false
})
for _, k := range doomed {
votes.Remove(k)
}
proposals.Remove(key(id))
return int64(len(doomed))
}