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

Playground

clamp.gno

package impl

// Attacker-controlled strings are clamped before they reach the sanitizer, so
// escaping costs a bounded constant rather than scaling with input.
//
// Sanitizing runs ~11,310 gas/byte (InlineCode) against ~31 for the raw
// concatenation it replaced, and Render is reachable unauthenticated through
// vm/qrender under maxGasQuery = 3_000_000_000. ExecutorCreationRealm is
// dispatched through the public dao.Executor interface, so a hostile executor
// computes it per call while storing almost nothing. Measured on the real
// render path: a 250KB value costs 2,839,117,770 gas unclamped against
// 18,749,984 clamped. 250KB is just under the cap; about 265KB crosses it
// (3,008,818,394), and past that the page cannot be rendered at all by
// anyone. Choosing the larger number costs the attacker nothing, since the
// value is computed per call and almost nothing is stored. Removing that
// amplification is the point of this file.
//
// It does NOT make the page safe, and nothing here should be read as claiming
// so. The executor's method body runs inside the same query and is unbounded:
// an executor that simply burns CPU before returning a short string still
// renders the proposal page permanently un-queryable, for a few hundred bytes
// of on-chain storage. That predates this change — Render has always called
// ExecutorString() and ExecutorCreationRealm() through the public interface —
// and bounding it needs a gas budget around executor dispatch, not a clamp.
const (
	// A realm path. The longest deployable realm path in examples/ is 35 bytes
	// (gno.land/r/gov/dao/treasury/test/v0), so this leaves about seven times
	// the room anything real needs. A hostile executor returns any length it
	// likes, which is the reason to clamp at all. It is headroom, not a
	// guarantee: the package-path grammar puts no ceiling on how many segments
	// a path may have, so a deeply nested realm could still be cut. That costs
	// a truncation marker on the page and nothing else.
	maxRenderedRealm = 256
	// "execution failed: " plus an executor's error message. Also bounds what
	// govdao.gno stores, so the realm never holds a reason it cannot show.
	maxRenderedReason = 1024
	// A strconv error that echoes the caller's own path segment. Everything in
	// it is fixed text except the quoted segment, whose length the caller picks.
	maxRenderedError = 256
	// A proposal title. The longest in examples/ is about 40 bytes, so this is
	// roughly nine times anything real, and long for a heading. Titles are
	// escaped on both the proposal page and the list page, and the list page
	// escapes one per proposal shown, so this is the bound that keeps a single
	// oversized title from pricing the whole list out of the query cap.
	maxRenderedTitle = 512
	// A Payment's String(). The canonical impls render a coin set or an
	// amount plus a token key, then " to " and a bech32 address; a coin set
	// is bounded by the number of denoms a proposer cares to list and each
	// denom's length is unbounded, which is the reason to clamp at all.
	maxRenderedPayment = 512
)

// Always clamp first — before escaping, and before any other pass over the
// value. Trimming used to run before the clamp, which meant it walked every
// byte the executor returned: 250KB of spaces cost 1,368,719,824 gas to render
// nothing, and 560KB cost 3,048,904,520, past the query cap. Clamping first
// bounds that scan and brought the same 560KB down to 16,657,792.
//
// Never clamp after escaping either. The escapers size their wrapper
// from the string they are handed — InlineCode picks a fence long enough to
// outscan the backticks it can see. Cutting a value that has already been
// escaped can slice the closing fence off and leave the span hanging open,
// which is worse than not clamping at all. Both call sites read
// InlineCode(clampField(...)) for that reason, and the enormous-value case in
// filetests/executor_disclosure_filetest.gno fails if the two are swapped.
//
// clampField cuts s to at most max bytes, backing off to a rune boundary so a
// well-formed multi-byte character is not split, and marks the result so a
// reader can tell it was cut. Input that is already invalid UTF-8 can still
// leave a dangling lead byte; the sanitizer tolerates that. The marker avoids markdown punctuation:
// these values are escaped downstream, and parentheses would come back as
// "\(truncated\)".
func clampField(s string, max int) string {
	if len(s) <= max {
		return s
	}

	end := max
	// UTF-8 continuation bytes are 0b10xxxxxx.
	for end > 0 && s[end]&0xC0 == 0x80 {
		end--
	}

	return s[:end] + "… truncated"
}

clamp_test.gno

package impl

import (
	"strings"
	"testing"

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

// Sanitizing costs ~11,310 gas/byte, and rendering is reachable unauthenticated
// through vm/qrender under a 3,000,000,000 gas cap. ExecutorCreationRealm is
// dispatched through the public dao.Executor interface, so a hostile executor
// computes it per call and stores almost nothing: unclamped, a ~250KB value
// costs over 3G gas in one render and bricks the proposal page for everyone.
// Measured on the real render path: 2,839,117,770 gas unclamped versus
// 18,749,984 clamped. About 265KB of input crosses the query cap entirely.
func TestClampFieldBoundsSanitizerInput(t *testing.T) {
	uassert.Equal(t, "short", clampField("short", maxRenderedRealm),
		"a value within the bound must pass through untouched")

	huge := strings.Repeat("a", 250000)
	got := clampField(huge, maxRenderedRealm)
	uassert.True(t, len(got) < maxRenderedRealm+32,
		"the clamped value must be bounded by the limit, not by the input")
	uassert.True(t, strings.HasSuffix(got, "… truncated"),
		"a clamped value must say it was cut rather than look authored short")
}

// Cutting at a byte offset can land inside a multi-byte rune; the sanitizer
// tolerates invalid UTF-8, but handing it a split rune is sloppy and would
// render a replacement character mid-path.
func TestClampFieldCutsOnRuneBoundary(t *testing.T) {
	// 3-byte runes, so a 256-byte cut lands mid-rune (256 = 85*3 + 1).
	got := clampField(strings.Repeat("世", 200), maxRenderedRealm)
	body := strings.TrimSuffix(got, "… truncated")

	uassert.True(t, len(body)%3 == 0,
		"the cut must land on a rune boundary")
	uassert.Equal(t, strings.Repeat("世", len(body)/3), body,
		"every retained rune must be intact")
}

// Boundary and malformed input. clampField does byte arithmetic and backs off
// over UTF-8 continuation bytes, so the interesting cases are the ones where
// that loop has nowhere to back off to.
func TestClampFieldBoundaries(t *testing.T) {
	exact := strings.Repeat("a", maxRenderedRealm)
	uassert.Equal(t, exact, clampField(exact, maxRenderedRealm),
		"a value exactly at the bound must not be marked truncated")

	over := strings.Repeat("a", maxRenderedRealm+1)
	uassert.True(t, strings.HasSuffix(clampField(over, maxRenderedRealm), "… truncated"),
		"one byte over the bound must be cut")

	// Already-invalid UTF-8: every byte is a continuation, so the backoff
	// walks to zero. Must degrade to the marker rather than panic or loop.
	cont := strings.Repeat("\x80", maxRenderedRealm+10)
	uassert.Equal(t, "… truncated", clampField(cont, maxRenderedRealm),
		"an all-continuation string must degrade to just the marker")

	uassert.Equal(t, "… truncated", clampField("abc", 0),
		"a zero bound must still terminate")
}

denied_reason_test.gno

package impl

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
	"gno.land/r/gov/dao/memberstore/v0"
)

// DeniedReason is "execution failed: " + err.Error() (govdao.gno), and that
// error comes from the proposal's executor callback — which any third-party
// realm can supply (see govdao_execute_reject_proposal.txtar, where the
// executor lives in gno.land/r/test/request). Rendered raw it let a failing
// proposal write markdown straight beneath the "PROPOSAL HAS BEEN DENIED"
// line, including a forged heading and vote tally.
//
// Operates on proposalStatus.String directly rather than through a real
// proposal, so it does not disturb the proposal ids and counts that the other
// tests in this package assert against shared realm state.
func TestDeniedReasonCannotForgePageStructure(cur realm, t *testing.T) {
	ps := newProposalStatus([]string{memberstore.T1})
	ps.Denied = true
	ps.DeniedReason = "execution failed: boom\n\n### Stats\n\n- **PROPOSAL HAS BEEN ACCEPTED**\n\n---\n<div>swallow the tally"

	out := ps.String(0, cur)

	uassert.False(t, strings.Contains(out, "\n### Stats"),
		"an injected heading must not survive into the rendered stats block")
	uassert.False(t, strings.Contains(out, "\n- **PROPOSAL HAS BEEN ACCEPTED**"),
		"an injected list item must not forge an acceptance line")
	uassert.False(t, strings.Contains(out, "\n---\n"),
		"an injected horizontal rule must not survive")

	// Emphasis and raw HTML are residue that sanitize.Block would have left
	// live; InlineText escapes both. A reader must not see a bold
	// "ACCEPTED" on a denied proposal, and a <div> must not open an HTML
	// block that swallows the vote tally rendered after it.
	uassert.False(t, strings.Contains(out, "**PROPOSAL HAS BEEN ACCEPTED**"),
		"injected bold text must not forge an acceptance line")
	uassert.False(t, strings.Contains(out, "<div>"),
		"injected raw HTML must not open a block that swallows the tally")

	// Folding is the property InlineText adds over the alternatives: the whole
	// reason must land on the REASON: line, so nothing after a newline can be
	// read as new top-level markdown. Asserted by requiring the payload's LAST
	// segment on the same line as its first.
	reason := out[strings.Index(out, "REASON: "):]
	firstLine := reason[:strings.Index(reason, "\n")]
	uassert.True(t, strings.Contains(firstLine, "swallow the tally"),
		"the entire reason must be folded onto the REASON line")
}

// ...and ordinary error text stays readable. InlineText backslash-escapes
// markdown punctuation, so the raw output carries "Boom\!" — but a
// backslash-escaped punctuation mark renders as the bare character, so a
// reader sees "Boom!". Words and spacing are untouched.
func TestDeniedReasonKeepsPlainTextIntact(cur realm, t *testing.T) {
	ps := newProposalStatus([]string{memberstore.T1})
	ps.Denied = true
	ps.DeniedReason = "execution failed: Boom!"

	uassert.True(t, strings.Contains(ps.String(0, cur), `REASON: execution failed: Boom\!`),
		"a plain denial reason must stay on the REASON line, escaped but readable")
}

// The reason reaches an unauthenticated render path and InlineText costs
// ~6,990 gas/byte, so it must be bounded before it is escaped, not after.
// Asserts the clamp at the call site, not clampField in isolation.
//
// The payload is exclamation marks, not letters, and that choice is the whole
// test. InlineText escapes "!" to "\!" but leaves letters alone, so with a
// letter payload the escaped text is the same length as the raw text and both
// orderings produce identical output — the test would pass either way and
// prove nothing. With punctuation, escaping doubles the length, and the two
// orderings become tellable apart.
func TestDeniedReasonIsClampedBeforeSanitizing(cur realm, t *testing.T) {
	ps := newProposalStatus([]string{memberstore.T1})
	ps.Denied = true
	ps.DeniedReason = strings.Repeat("!", 50000)

	out := ps.String(0, cur)

	// The clamp bounds what goes INTO the escaper, so a full maxRenderedReason
	// characters survive and the escaped output is about twice that. Clamping
	// the escaped text instead would leave only half as many, and the escaper
	// would still have processed all 50,000 characters — exactly the cost the
	// clamp exists to avoid.
	uassert.True(t, strings.Count(out, "!") >= maxRenderedReason,
		"the clamp must bound the escaper's input, not its output")
	uassert.True(t, len(out) < 4*maxRenderedReason,
		"the rendered stats block must still be bounded by the clamp")
	uassert.True(t, strings.Contains(out, "… truncated"),
		"a clamped reason must be marked as cut")
}

filter.gno

package impl

type FilterByTier struct {
	Tier string
}

func NewFilterByTier(tier string) FilterByTier {
	return FilterByTier{Tier: tier}
}

gnomod.toml

module = "gno.land/r/gov/dao/impl/v0"
gno = "0.9"

[addpkg]
  creator = "g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da"

govdao.gno

package impl

import (
	"chain"
	"chain/runtime/unsafe"
	"errors"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/gov/dao"
	"gno.land/r/gov/dao/memberstore/v0"
)

var ErrMemberNotFound = errors.New("member not found")

type GovDAO struct {
	pss    ProposalsStatuses
	render *render
}

func NewGovDAO() *GovDAO {
	pss := NewProposalsStatuses()
	d := &GovDAO{
		pss: pss,
	}

	d.render = NewRender(d)

	// Attach to package var (impl owns _govdao). Plain assignment is
	// fine — we're in impl's package, no realm transition needed.
	// TODO: replace with future attach().
	_govdao = d

	return d
}

// Setting this to a global variable forces attaching the GovDAO struct to this
// realm. TODO replace with future `attach()`.
var _govdao *GovDAO

func (g *GovDAO) PreCreateProposal(_ int, rlm realm, r dao.ProposalRequest) (address, error) {
	if !g.isValidCall(0, rlm) {
		return "", errors.New(ufmt.Sprintf("proposal creation must be done directly by a user or through the r/gov/dao proxy. caller realm: %v; caller's previous: %v",
			rlm, rlm.Previous()))
	}

	// Verify that the one creating the proposal is a member.
	caller := unsafe.OriginCaller()
	mem, _ := getMembers(cross(rlm)).GetMember(caller)
	if mem == nil {
		return caller, errors.New("only members can create new proposals")
	}

	return caller, nil
}

func (g *GovDAO) PostCreateProposal(_ int, rlm realm, r dao.ProposalRequest, pid dao.ProposalID) {
	// Tiers Allowed to Vote
	tatv := []string{memberstore.T1, memberstore.T2, memberstore.T3}
	switch v := r.Filter().(type) {
	case FilterByTier:
		// only members from T1 are allowed to vote when adding new members to T1
		if v.Tier == memberstore.T1 {
			tatv = []string{memberstore.T1}
		}
		// only members from T1 and T2 are allowed to vote when adding new members to T2
		if v.Tier == memberstore.T2 {
			tatv = []string{memberstore.T1, memberstore.T2}
		}
	}
	g.pss.Set(pid.String(), newProposalStatus(tatv))
}

func (g *GovDAO) VoteOnProposal(_ int, rlm realm, r dao.VoteRequest) error {
	if !g.isValidCall(0, rlm) {
		return errors.New("proposal voting must be done directly by a user")
	}

	caller := unsafe.OriginCaller()
	mem, tie := getMembers(cross(rlm)).GetMember(caller)
	if mem == nil {
		return ErrMemberNotFound
	}

	status := g.pss.GetStatus(r.ProposalID)
	if status == nil {
		return errors.New("proposal not found")
	}

	if status.Denied || status.Accepted {
		return errors.New(ufmt.Sprintf("proposal closed. Accepted: %v", status.Accepted))
	}

	if !status.IsAllowed(tie) {
		return errors.New("member on specified tier is not allowed to vote on this proposal")
	}

	mVoted, _ := status.AllVotes.GetMember(caller)
	if mVoted != nil {
		return errors.New("already voted on proposal")
	}

	switch r.Option {
	case dao.YesVote:
		status.AllVotes.SetMember(tie, caller, mem)
		status.YesVotes.SetMember(tie, caller, mem)
	case dao.NoVote:
		status.AllVotes.SetMember(tie, caller, mem)
		status.NoVotes.SetMember(tie, caller, mem)
	case dao.AbstainVote:
		status.AllVotes.SetMember(tie, caller, mem)
		status.AbstainVotes.SetMember(tie, caller, mem)
	default:
		return errors.New("voting can only be YES, NO, or ABSTAIN")
	}

	return nil
}

func (g *GovDAO) PreExecuteProposal(_ int, rlm realm, pid dao.ProposalID) (bool, error) {
	if !g.isValidCall(0, rlm) {
		return false, errors.New("proposal execution must be done directly by a user")
	}
	status := g.pss.GetStatus(pid)
	if status == nil {
		// Unknown to this implementation: either an unknown id, or a
		// proposal created before a DAO upgrade replaced this GovDAO
		// (statuses live on the instance, so a fresh instance has none).
		// Mirrors VoteOnProposal above, which returns this same error for
		// the same lookup. Without it the nil deref panics with an opaque
		// "runtime error: nil pointer dereference" that reads like a VM
		// fault. It reports the condition only — see the ADR for why the
		// proposal still cannot be resolved.
		return false, errors.New("proposal not found")
	}
	if status.Denied || status.Accepted {
		return false, errors.New(ufmt.Sprintf("proposal already executed. Accepted: %v", status.Accepted))
	}

	if status.YesPercent(0, rlm) >= law.Supermajority {
		status.Accepted = true
		return true, nil
	}

	if status.NoPercent(0, rlm) >= law.Supermajority {
		status.Denied = true
		return false, nil
	}

	return false, errors.New(ufmt.Sprintf("proposal didn't reach supermajority yet: %v", law.Supermajority))
}

func (g *GovDAO) ExecuteProposal(_ int, rlm realm, pid dao.ProposalID, e dao.Executor) error {
	if e == nil {
		panic("an executor is required to execute the proposal")
	}

	status := g.pss.GetStatus(pid)
	if status == nil {
		panic("proposal not found")
	}

	err := e.Execute(cross(rlm))
	if err != nil {
		status.Accepted = false
		status.Denied = true
		// Clamped on the way in, not just on the way out. The error comes from
		// the proposal's executor — third-party code — and this assignment is a
		// write to realm storage, paid for by whoever executes the proposal
		// rather than by whoever wrote the executor. Bounding it here means the
		// realm never stores a reason larger than it can display. The clamp at
		// the render site stays, because reasons stored before this change are
		// still unbounded.
		status.DeniedReason = "execution failed: " + clampField(err.Error(), maxRenderedReason)
	}
	return err
}

func (g *GovDAO) Render(cur realm, pkgPath string, path string) string {
	// Same-realm dispatch: pass cur through as data (non-crossing).
	return g.render.Render(0, cur, pkgPath, path)
}

// isValidCall verifies that the impl method is being invoked from the
// r/gov/dao proxy via a legitimate user transaction (MsgCall or MsgRun).
//
// The proxy passes its own crossing-frame Cur as rlm when calling the
// impl methods. rlm.IsCurrent() rejects stale or stashed realm values —
// a malicious realm cannot replay a captured proxy cur to impersonate
// the proxy. After the IsCurrent() check:
//   - rlm.PkgPath() == "gno.land/r/gov/dao" identifies the proxy
//     unforgeably (pkg path is set at mint time by installCrossingCur).
//   - rlm.Previous() is the caller of the proxy.
//
// The proxy is the only legitimate entrypoint. The impl methods are
// non-crossing and take rlm as a regular argument, so a direct user
// MsgCall to them cannot supply a valid rlm: the IsCurrent() check
// rejects any forged or stashed realm value.
//
// This is also what makes the unsafe.OriginCaller()-based membership
// checks safe. Those key on the transaction origin (an EOA), which is
// correct only if the origin is the immediate caller. isValidCall
// guarantees exactly that: it admits prev only when prev.IsUser() (a
// direct EOA call or the origin's own ephemeral run realm) or when
// prev's package address equals the origin — never a third-party realm
// in the middle. Relaxing this to allow realm intermediaries would let
// one member's vote be cast under another origin: keep the two in sync.
func (g *GovDAO) isValidCall(_ int, rlm realm) bool {
	if !rlm.IsCurrent() {
		return false
	}
	if rlm.PkgPath() != "gno.land/r/gov/dao" {
		return false
	}
	prev := rlm.Previous()
	// MsgCall: proxy was called directly by an EOA (UserRealm).
	if prev.IsUser() {
		return true
	}
	// MsgRun: proxy was called from the ephemeral run realm; that
	// realm's package address equals the EOA OriginCaller.
	return chain.PackageAddress(prev.PkgPath()) == unsafe.OriginCaller()
}

govdao_test.gno

package impl

import (
	"fmt"
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/urequire/v0"
	"gno.land/r/gov/dao"
	"gno.land/r/gov/dao/memberstore/v0"
)

// cur is a zero-value realm used as a placeholder when forwarding to
// uassert/urequire dispatch helpers that gained an `rlm realm` param.
// These tests pass `func()` callbacks (no crossing inside the callback),
// so rlm is ignored — a nil realm here is safe.
var cur realm

func init(cur realm) {
	loadMembers(cur)

	dao.UpdateImpl(cross(cur), dao.NewUpdateRequest(govDAO, []string{"gno.land/r/gov/dao/impl/v0"}))
}

var (
	m1    = testutils.TestAddress("m1")
	m11   = testutils.TestAddress("m1.1")
	m111  = testutils.TestAddress("m1.1.1")
	m1111 = testutils.TestAddress("m1.1.1.1")
	m2    = testutils.TestAddress("m2")
	m3    = testutils.TestAddress("m3")
	m4    = testutils.TestAddress("m4")
	m5    = testutils.TestAddress("m5")
	m6    = testutils.TestAddress("m6")

	noMember = testutils.TestAddress("nm1")
)

func loadMembers(cur realm) {
	// This is needed because state is saved between unit tests,
	// and we want to avoid having real members used on tests
	mstore := memberstore.Get(0, cur)
	mstore.DeleteAll()

	mstore.SetTier(memberstore.T1)
	mstore.SetTier(memberstore.T2)
	mstore.SetTier(memberstore.T3)

	mstore.SetMember(memberstore.T1, m1, memberByTier(memberstore.T1))
	mstore.SetMember(memberstore.T1, m11, memberByTier(memberstore.T1))
	mstore.SetMember(memberstore.T1, m111, memberByTier(memberstore.T1))
	mstore.SetMember(memberstore.T1, m1111, memberByTier(memberstore.T1))

	mstore.SetMember(memberstore.T2, m2, memberByTier(memberstore.T2))
	mstore.SetMember(memberstore.T2, m3, memberByTier(memberstore.T2))
	mstore.SetMember(memberstore.T3, m4, memberByTier(memberstore.T3))
	mstore.SetMember(memberstore.T3, m5, memberByTier(memberstore.T3))
	mstore.SetMember(memberstore.T3, m6, memberByTier(memberstore.T3))
}

func TestCreateProposalAndVote(cur realm, t *testing.T) {
	loadMembers(cur)

	portfolio := "# This is my portfolio:\n\n- THINGS"

	testing.SetOriginCaller(noMember)
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))

	nm1 := testutils.TestAddress("nm1")

	urequire.AbortsWithMessage(t, cur, "Only T1 and T2 members can be added by proposal. To add a T3 member use AddMember function directly.", func(cur realm) {
		dao.MustCreateProposal(cross(cur), NewAddMemberRequest(cur, nm1, memberstore.T3, portfolio))
	})

	urequire.AbortsWithMessage(t, cur, "proposer is not a member", func(cur realm) {
		dao.MustCreateProposal(cross(cur), NewAddMemberRequest(cur, nm1, memberstore.T2, portfolio))
	})

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))

	proposalRequest := NewAddMemberRequest(cur, nm1, memberstore.T2, portfolio)

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))
	pid := dao.MustCreateProposal(cross(cur), proposalRequest)
	urequire.Equal(t, int(pid), 0)

	// m1 votes yes because that member is interested on it
	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(0)))

	testing.SetOriginCaller(m11)

	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))

	testing.SetOriginCaller(m2)

	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))

	testing.SetOriginCaller(m3)

	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))

	testing.SetOriginCaller(m4)

	urequire.AbortsWithMessage(t, cur, "member on specified tier is not allowed to vote on this proposal", func() {
		dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))
	})

	testing.SetOriginCaller(m111)

	// Same effect as:
	// dao.MustVoteOnProposal(dao.VoteRequest{
	// 	Option:     dao.NoVote,
	// 	ProposalID: dao.ProposalID(0),
	// })
	dao.MustVoteOnProposalSimple(cross(cur), 0, "NO")

	urequire.Equal(t, true, strings.Contains(dao.Render(cross(cur), ""), "Prop #0 - New T2 Member Proposal"))
	// urequire.Equal(t, true, strings.Contains(dao.Render(cross(cur), ""), "Author: "+m1.String()))

	urequire.AbortsWithMessage(t, cur, "proposal didn't reach supermajority yet: 66.66", func() {
		dao.ExecuteProposal(cross(cur), dao.ProposalID(0))
	})

	testing.SetOriginCaller(m1111)
	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))

	accepted := dao.ExecuteProposal(cross(cur), dao.ProposalID(0))
	urequire.Equal(t, false, accepted)

	urequire.Equal(t, true, contains(dao.Render(cross(cur), "0"), "**PROPOSAL HAS BEEN DENIED**"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), "0"), "NO PERCENT: 81.25%"))
}

func TestExecutorCreationRealm(cur realm, t *testing.T) {
	loadMembers(cur)

	// Test that executor creation realm is captured correctly
	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/template/contract"))

	// Create executor in the template contract realm
	executor := dao.NewSimpleExecutor(0, cur, func(realm) error { return nil }, "Test executor from template")

	proposalRequest := dao.NewProposalRequest(
		"Test Proposal",
		"This proposal tests executor creation realm tracking",
		executor,
	)

	// Create proposal from user realm (user can call DAO directly)
	testing.SetRealm(testing.NewUserRealm(m1))
	pid := dao.MustCreateProposal(cross(cur), proposalRequest)

	// Get the proposal
	prop := dao.MustGetProposal(pid)

	// Verify the author is m1
	urequire.Equal(t, m1, prop.Author())

	// Verify the executor creation realm is captured correctly
	urequire.Equal(t, "gno.land/r/template/contract", prop.ExecutorCreationRealm())

	// Check that it's displayed in the individual proposal render output
	individualRendered := dao.Render(cross(cur), pid.String())
	// Rendered as a code span: CreationRealm() is interface-dispatched and so
	// third-party controlled, and InlineCode neutralizes it while reading
	// naturally for a realm path.
	urequire.Equal(t, true, contains(individualRendered, "Executor created in: `gno.land/r/template/contract`"))
	urequire.Equal(t, true, contains(individualRendered, "Test executor from template"))

	// Also verify the main content is there
	urequire.Equal(t, true, contains(individualRendered, "Test Proposal"))
	urequire.Equal(t, true, contains(individualRendered, "This proposal tests executor creation realm tracking"))
}

func TestProposalPagination(cur realm, t *testing.T) {
	loadMembers(cur)
	portfolio := "### This is my portfolio:\n\n- THINGS"

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))

	nm1 := testutils.TestAddress("nm1")

	var pid dao.ProposalID

	proposalRequest := NewAddMemberRequest(cur, nm1, memberstore.T2, portfolio)

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))
	pid = dao.MustCreateProposal(cross(cur), proposalRequest)

	// TODO: tests keep the same vm state: https://github.com/gnolang/gno/issues/1982
	urequire.Equal(t, 2, int(pid))

	testing.SetRealm(testing.NewUserRealm(m1))
	pid = dao.MustCreateProposal(cross(cur), proposalRequest)
	urequire.Equal(t, 3, int(pid))

	testing.SetRealm(testing.NewUserRealm(m1))
	pid = dao.MustCreateProposal(cross(cur), proposalRequest)
	urequire.Equal(t, 4, int(pid))

	testing.SetRealm(testing.NewUserRealm(m1))
	pid = dao.MustCreateProposal(cross(cur), proposalRequest)
	urequire.Equal(t, 5, int(pid))

	testing.SetRealm(testing.NewUserRealm(m1))
	pid = dao.MustCreateProposal(cross(cur), proposalRequest)
	urequire.Equal(t, 6, int(pid))

	testing.SetRealm(testing.NewUserRealm(m1))
	pid = dao.MustCreateProposal(cross(cur), proposalRequest)
	urequire.Equal(t, 7, int(pid))

	fmt.Println(dao.Render(cross(cur), ""))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), ""), "### [Prop #7 - New T2 Member Proposal](/r/gov/dao:7)"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), ""), "### [Prop #6 - New T2 Member Proposal](/r/gov/dao:6)"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), ""), "### [Prop #5 - New T2 Member Proposal](/r/gov/dao:5)"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), ""), "### [Prop #4 - New T2 Member Proposal](/r/gov/dao:4)"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), ""), "### [Prop #3 - New T2 Member Proposal](/r/gov/dao:3)"))

	urequire.Equal(t, true, contains(dao.Render(cross(cur), "?page=2"), "### [Prop #2 - New T2 Member Proposal](/r/gov/dao:2)"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), "?page=2"), "### [Prop #1 - Test Proposal](/r/gov/dao:1)"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), "?page=2"), "### [Prop #0 - New T2 Member Proposal](/r/gov/dao:0)"))
}

func TestUpgradeDaoImplementation(cur realm, t *testing.T) {
	loadMembers(cur)

	testing.SetOriginCaller(noMember)
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))

	urequire.PanicsWithMessage(t, cur, "proposer is not a member", func() {
		NewUpgradeDaoImplRequest(cur, govDAO, "gno.land/r/gov/dao/v1/impl", "Something happened and we have to fix it.")
	})

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))

	preq := NewUpgradeDaoImplRequest(cur, govDAO, "gno.land/r/gov/dao/v1/impl", "Something happened and we have to fix it.")

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))
	pid := dao.MustCreateProposal(cross(cur), preq)
	urequire.Equal(t, int(pid), 8)

	// m1 votes yes because that member is interested on it
	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))

	testing.SetOriginCaller(m11)

	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))

	testing.SetOriginCaller(m2)

	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))

	testing.SetOriginCaller(m3)

	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))

	testing.SetOriginCaller(m111)

	// Same effect as:
	// dao.MustVoteOnProposal(dao.VoteRequest{
	// 	Option:     dao.YesVote,
	// 	ProposalID: dao.ProposalID(pid),
	// })
	dao.MustVoteOnProposalSimple(cross(cur), int64(pid), "YES")

	urequire.Equal(t, true, contains(dao.Render(cross(cur), "8"), "**Proposal is open for votes**"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), "8"), "68.42105263157895%"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), "8"), "0%"))

	accepted := dao.ExecuteProposal(cross(cur), dao.ProposalID(pid))
	urequire.Equal(t, true, accepted)
	urequire.Equal(t, true, contains(dao.Render(cross(cur), "8"), "**PROPOSAL HAS BEEN ACCEPTED**"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), "8"), "YES PERCENT: 68.42105263157895%"))
}

func TestAbstainVote(cur realm, t *testing.T) {
	loadMembers(cur)

	portfolio := "# This is my portfolio:\n\n- THINGS"

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))

	nm1 := testutils.TestAddress("nm1")
	proposalRequest := NewAddMemberRequest(cur, nm1, memberstore.T2, portfolio)

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))
	pid := dao.MustCreateProposal(cross(cur), proposalRequest)

	// m1 votes abstain
	dao.MustVoteOnProposalSimple(cross(cur), int64(pid), "ABSTAIN")

	// Other members vote YES to reach supermajority
	testing.SetOriginCaller(m11)
	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))

	testing.SetOriginCaller(m111)
	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))

	testing.SetOriginCaller(m1111)
	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))

	testing.SetOriginCaller(m2)
	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))

	testing.SetOriginCaller(m3)
	dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))

	// Verify render shows correct percentages
	urequire.Equal(t, true, contains(dao.Render(cross(cur), pid.String()), "YES PERCENT: 81.25%"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), pid.String()), "NO PERCENT: 0%"))
	urequire.Equal(t, true, contains(dao.Render(cross(cur), pid.String()), "ABSTAIN PERCENT: 18.75%"))

	// Supermajority reached despite one abstain voter
	accepted := dao.ExecuteProposal(cross(cur), pid)
	urequire.Equal(t, true, accepted)
	urequire.Equal(t, true, contains(dao.Render(cross(cur), pid.String()), "**PROPOSAL HAS BEEN ACCEPTED**"))

	// Abstain voter appears in vote list
	urequire.Equal(t, true, contains(dao.Render(cross(cur), fmt.Sprintf("%v/votes", int64(pid))), "ABSTAIN"))
}

func contains(s, substr string) bool {
	return strings.Index(s, substr) >= 0
}

// TestAddMemberKeepsInvitationPointWhenAddFails covers the executor's ordering.
//
// The executor spends the proposer's invitation point and adds the member. If
// the add fails, a returned executor error does NOT revert: ExecuteProposal
// marks the proposal denied and ExecuteOrRejectProposal still commits the
// transaction. So with the old order the point was gone and the member was not
// added, permanently.
//
// The failure is reachable: SetMember refuses an address that is already a
// member, and AddMember enrols T3 members directly, so proposing an existing
// member to another tier is an ordinary mistake rather than a contrived one.
//
// Uses ExecuteOrRejectProposal deliberately. ExecuteProposal panics on an
// executor error, and a panic aborts the transaction, which would revert the
// spend and hide the bug.
func TestAddMemberKeepsInvitationPointWhenAddFails(cur realm, t *testing.T) {
	loadMembers(cur)

	// m4 is already a T3 member, so adding it to T2 must fail in SetMember.
	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))
	preq := NewAddMemberRequest(cur, m4, memberstore.T2, "# Portfolio\n\n- things")

	// memberstore.Get requires an allowed-DAO caller, so read under the impl
	// realm rather than whatever the previous step left in place.
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))
	before, tier := memberstore.Get(0, cur).GetMember(m1)
	urequire.Equal(t, memberstore.T1, tier)
	pointsBefore := before.InvitationPoints
	urequire.Equal(t, true, pointsBefore > 0, "premise: the proposer must have a point to lose")

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))
	pid := dao.MustCreateProposal(cross(cur), preq)

	// A T2 addition is voted on by T1 and T2. Every one of them votes yes, so
	// the proposal certainly passes and the executor certainly runs -- if it did
	// not, this test would prove nothing.
	for _, voter := range []address{m1, m11, m111, m1111, m2, m3} {
		testing.SetOriginCaller(voter)
		dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))
	}

	accepted := dao.ExecuteOrRejectProposal(cross(cur), dao.ProposalID(pid))
	urequire.Equal(t, false, accepted, "the add must fail, since m4 is already a member")

	// Proves the executor ran and returned an error, rather than the vote
	// failing to reach a threshold -- only GovDAO.ExecuteProposal writes this.
	rendered := dao.Render(cross(cur), fmt.Sprintf("%d", int(pid)))
	urequire.Equal(t, true, contains(rendered, "execution failed"),
		"the proposal must have been denied by the executor, not by the vote")

	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))
	after, _ := memberstore.Get(0, cur).GetMember(m1)
	urequire.Equal(t, pointsBefore, after.InvitationPoints,
		"a failed add must not spend the proposer's invitation point")
}

// TestPromoteToTierMissingFromStoreKeepsTheMember covers the remove-then-add
// hazard in the promotion executor.
//
// The executor removes the member and re-adds them at the new tier. SetMember
// returns an error rather than panicking when the store has no bucket for that
// tier, and a returned executor error does not revert -- the proposal is marked
// rejected and the transaction still commits -- so the member would be removed
// and not re-added.
//
// The two tier registries are separate. GetTier reads the global definitions,
// which always hold T1/T2/T3; SetMember checks whether this store has a bucket,
// and DeleteAll empties the buckets while leaving the definitions intact. So a
// destination can pass the first check and fail the second, which is what this
// sets up.
func TestPromoteToTierMissingFromStoreKeepsTheMember(cur realm, t *testing.T) {
	loadMembers(cur)

	// Drop the T3 bucket while the global definition of T3 survives.
	mstore := memberstore.Get(0, cur)
	mstore.DeleteAll()
	mstore.SetTier(memberstore.T1)
	mstore.SetTier(memberstore.T2)
	mstore.SetMember(memberstore.T1, m1, memberByTier(memberstore.T1))
	mstore.SetMember(memberstore.T1, m11, memberByTier(memberstore.T1))
	mstore.SetMember(memberstore.T1, m111, memberByTier(memberstore.T1))
	mstore.SetMember(memberstore.T1, m1111, memberByTier(memberstore.T1))
	mstore.SetMember(memberstore.T2, m2, memberByTier(memberstore.T2))
	mstore.SetMember(memberstore.T2, m3, memberByTier(memberstore.T2))

	// Premise: T3 is defined globally but absent from this store.
	_, defined := memberstore.GetTier(memberstore.T3)
	urequire.Equal(t, true, defined, "premise: T3 must still be a defined tier")
	urequire.Equal(t, false, mstore.Has(memberstore.T3),
		"premise: this store must have no T3 bucket, or the test proves nothing")

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))
	preq := NewPromoteMemberRequest(cur, m1, memberstore.T1, memberstore.T3)

	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))
	pid := dao.MustCreateProposal(cross(cur), preq)

	for _, voter := range []address{m1, m11, m111, m1111, m2, m3} {
		testing.SetOriginCaller(voter)
		dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))
	}

	// The executor refuses before removing anything, and returns rather than
	// panicking. That rejects the proposal and closes it, and since nothing was
	// written, committing the rejection loses nothing.
	//
	// So the assertion below is about the chain, not the harness: the member
	// survives because no write happened, not because a panic reverted one.
	// Under the earlier panic-after-removal shape it held only because gno test
	// does not revert an abort, which proved nothing about production.
	accepted := dao.ExecuteOrRejectProposal(cross(cur), dao.ProposalID(pid))
	urequire.Equal(t, false, accepted, "the promotion must be rejected")

	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))
	after, tier := memberstore.Get(0, cur).GetMember(m1)
	urequire.Equal(t, true, after != nil, "the member must survive a refused promotion")
	urequire.Equal(t, memberstore.T1, tier, "and must still be on their original tier")

	loadMembers(cur)
}

impl.gno

package impl

import (
	"gno.land/r/gov/dao/memberstore/v0"
)

var (
	law    *Law
	govDAO *GovDAO = NewGovDAO()
)

func init() {
	law = &Law{
		Supermajority: 66.66, // Two thirds
	}
}

func Render(cur realm, in string) string {
	// Same-realm: pass cur to govDAO.Render (also crossing, but same realm
	// so use the literal cur form rather than cross(cur)).
	return govDAO.Render(cur, cur.PkgPath(), in)
}

// AddMember allows T1 and T2 members to freely add T3 members using their invitation points.
func AddMember(cur realm, addr address) {
	// AGENTS.md: check IsCurrent() before cur.Previous() in a crossing function.
	if !cur.IsCurrent() {
		panic("AddMember: realm value is not the caller's live cur")
	}
	// address args are not VM-validated (the raw MsgCall string is stored), so
	// reject a non-bech32 addr here — matching InitWithUsers. This keeps the
	// member store free of unauthenticable keys and of markdown/pipe/HTML
	// metachars that would otherwise inject into the members render table.
	if !addr.IsValid() {
		panic("invalid member address: " + addr.String())
	}
	caller := cur.Previous()
	if !caller.IsUser() {
		panic("this function must be called by an EOA through msg call or msg run")
	}
	m, t := memberstore.Get(0, cur).GetMember(caller.Address())
	if m == nil {
		panic("caller is not a member")
	}

	if t != memberstore.T1 && t != memberstore.T2 {
		panic("caller is not on T1 or T2. To add members, propose them through proposals")
	}

	m.RemoveInvitationPoint()

	if err := memberstore.Get(0, cur).SetMember(memberstore.T3, addr, memberByTier(memberstore.T3)); err != nil {
		panic(err.Error())
	}
}

// GetInstance returns the singleton *GovDAO. Only the loader realm may
// call it (used during the bootstrap UpdateImpl handoff). The
// IsCurrent() check rejects stale or stashed realm values; PkgPath()
// after the check is the authentic immediate caller.
func GetInstance(_ int, rlm realm) *GovDAO {
	if !rlm.IsCurrent() {
		panic("GetInstance: rlm is not the caller's live cur (stale capture or sibling frame)")
	}
	if rlm.PkgPath() != "gno.land/r/gov/dao/loader/v0" {
		panic("not allowed")
	}

	return govDAO
}

prop_requests.gno

package impl

import (
	"chain/runtime/unsafe"
	"strings"

	"gno.land/p/aeddi/panictoerr/v0"
	"gno.land/p/moul/md/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
	trs_pkg "gno.land/p/nt/treasury/v0"
	"gno.land/p/nt/ufmt/v0"

	"gno.land/r/gov/dao"
	"gno.land/r/gov/dao/memberstore/v0"
	"gno.land/r/gov/dao/treasury/v0"
)

func NewChangeLawRequest(cur realm, newLaw Law) dao.ProposalRequest {
	member, _ := memberstore.Get(0, cur).GetMember(unsafe.OriginCaller())
	if member == nil {
		panic("proposer is not a member")
	}

	cb := func(cur realm) error {
		law = &newLaw
		return nil
	}

	e := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf("A new Law is proposed:\n %v", newLaw))

	return dao.NewProposalRequest("Change Law Proposal", "This proposal is looking to change the actual govDAO Law", e)
}

func NewUpgradeDaoImplRequest(cur realm, newDao dao.DAO, realmPkg, reason string) dao.ProposalRequest {
	// Rejected here as well as in UpdateImpl so the mistake surfaces when the
	// proposal is written, not when it executes. An empty realmPkg would be
	// stored as an allowlist entry matching every user realm's empty
	// PkgPath(), and would render as a blank name in the grant sentence below.
	if strings.TrimSpace(realmPkg) == "" {
		panic("realmPkg must be the realm path being granted govDAO authority")
	}
	// Padding is rejected for the same reason UpdateImpl rejects it: the entry
	// is stored as given and matched whole, so a padded path grants nobody
	// anything. Caught here so the author sees it, not the voters.
	if realmPkg != strings.TrimSpace(realmPkg) {
		panic("realmPkg must not have leading or trailing spaces")
	}

	member, _ := memberstore.Get(0, cur).GetMember(unsafe.OriginCaller())
	if member == nil {
		panic("proposer is not a member")
	}

	cb := func(cur realm) error {
		// dao.UpdateImpl() must be cross-called from v0/impl but
		// what calls this cb function is r/gov/dao.
		// therefore we must cross back into v0/impl and then
		// cross call dao.UpdateRequest().
		dao.UpdateImpl(cross(cur), dao.NewUpdateRequest(newDao, []string{"gno.land/r/gov/dao/impl/v0", realmPkg}))
		return nil
	}

	// State the grant: this executor rewrites AllowedDAOs, and previously
	// rendered nothing at all. realmPkg is caller-supplied and lands in a code
	// span, so it is wrapped with sanitize.InlineCode — which emits its own
	// fence, so do not add backticks around it. (md.EscapeText is wrong here:
	// CommonMark 6.1 does not process backslash escapes inside code spans.)
	// Nothing ties realmPkg to newDao, which is why the text says so.
	e := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf(
		"Replaces the govDAO implementation with the DAO carried by this proposal.\n\n"+
			"After execution, only `gno.land/r/gov/dao/impl/v0` and %s may replace the "+
			"implementation, mutate the member store, or move treasury funds.\n\n"+
			"This grant is stated by the proposer: the incoming implementation is passed "+
			"as a value and is not verified to belong to the realm named above.",
		sanitize.InlineCode(realmPkg)))

	return dao.NewProposalRequest("Change DAO implementation", "This proposal is looking to change the actual govDAO implementation. Reason: "+reason, e)
}

func NewAddMemberRequest(cur realm, addr address, tier string, portfolio string) dao.ProposalRequest {
	// Reject a non-bech32 address at proposal-build time (see AddMember): keeps
	// an unauthenticable / injection-bearing key out of the member store.
	if !addr.IsValid() {
		panic("invalid member address: " + addr.String())
	}
	_, ok := memberstore.GetTier(tier)
	if !ok {
		panic("provided tier does not exists")
	}

	if tier != memberstore.T1 && tier != memberstore.T2 {
		panic("Only T1 and T2 members can be added by proposal. To add a T3 member use AddMember function directly.")
	}

	if portfolio == "" {
		panic("A portfolio for the proposed member is required")
	}

	member, _ := memberstore.Get(0, cur).GetMember(unsafe.OriginCaller())
	if member == nil {
		panic("proposer is not a member")
	}

	if member.InvitationPoints <= 0 {
		panic("proposer does not have enough invitation points for inviting new people to the board")
	}

	cb := func(cur realm) error {
		// Add the member first, spend the proposer's invitation point second.
		//
		// SetMember RETURNS an error when the address is already a member --
		// easy to reach, since AddMember enrols T3 members directly. A returned
		// executor error does not revert: ExecuteOrRejectProposal marks the
		// proposal rejected and the transaction still commits. So with the old
		// order the point was spent and the member was not added.
		//
		// RemoveInvitationPoint can still fail, despite the build-time check
		// above: it panics at zero, and AddMember spends points from this same
		// captured member, so a proposer can drain their own between creation
		// and execution. That panics and reverts, which loses nothing.
		if err := memberstore.Get(0, cur).SetMember(tier, addr, memberByTier(tier)); err != nil {
			return err
		}
		member.RemoveInvitationPoint()

		return nil
	}

	e := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf("A new member with address %v is proposed to be on tier %v. Provided Portfolio information:\n\n%v", addr, tier, portfolio))

	name := tryResolveAddr(addr)
	return dao.NewProposalRequestWithFilter(
		ufmt.Sprintf("New %s Member Proposal", tier),
		ufmt.Sprintf("This is a proposal to add `%s` to **%s**.\n#### `%s`'s Portfolio:\n\n%s\n", name, tier, name, portfolio),
		e,
		FilterByTier{Tier: tier},
	)
}

func NewWithdrawMemberRequest(cur realm, addr address, reason string) dao.ProposalRequest {
	member, tier := memberstore.Get(0, cur).GetMember(addr)
	if member == nil {
		panic("user we want to remove not found")
	}

	reason = strings.TrimSpace(reason)
	if tier == memberstore.T1 && reason == "" {
		panic("T1 user removals must contains a reason.")
	}

	cb := func(cur realm) error {
		memberstore.Get(0, cur).RemoveMember(addr)
		return nil
	}

	e := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf("Member with address %v will be withdrawn.\n\n REASON: %v.", addr, reason))

	return dao.NewProposalRequest(
		"Member Withdrawal Proposal",
		ufmt.Sprintf("This is a proposal to remove %s from the GovDAO", tryResolveAddr(addr)),
		e,
	)
}

func NewPromoteMemberRequest(cur realm, addr address, fromTier string, toTier string) dao.ProposalRequest {
	cb := func(cur realm) error {
		// Fail on an unknown destination tier before touching the member.
		//
		// Everything that can be checked before a write is checked here, and
		// RETURNS. A returned executor error rejects the proposal and closes it,
		// and since nothing has been mutated yet that commits nothing.
		//
		// After RemoveMember the policy inverts: a return would commit a member
		// who was removed and not re-added, so everything below panics instead,
		// which reverts the whole transaction.
		// A tier dropped from the global table. NewChangeTiersRequest replaces
		// that table wholesale, so a proposal listing only T1 and T2 removes T3
		// for good. memberByTier would not notice: it switches on the constant
		// and ignores GetTier's ok, so the promotion would succeed and hand the
		// member zero invitation points. Untested -- reaching it needs a passed
		// tier-change proposal, which rewrites state every other test shares.
		if _, ok := memberstore.GetTier(toTier); !ok {
			return ufmt.Errorf("unknown destination tier: %s", toTier)
		}

		mbt := memberstore.Get(0, cur)

		// SetMember consults the store's own index, not the global tier table
		// above: DeleteAll empties the buckets and leaves the definitions.
		if !mbt.Has(toTier) {
			return ufmt.Errorf("destination tier is missing from the member store: %s", toTier)
		}

		prevTier := mbt.RemoveMember(addr)
		if prevTier == "" {
			panic("member not found, so cannot be promoted")
		}

		if prevTier != fromTier {
			panic("previous tier changed from the one indicated in the proposal")
		}

		if err := mbt.SetMember(toTier, addr, memberByTier(toTier)); err != nil {
			// Unreachable: both of SetMember's failures are ruled out above.
			// Panicking is what makes it safe to be wrong about that.
			panic("promotion failed after removal: " + err.Error())
		}

		return nil
	}

	e := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf("A new member with address %v will be promoted from tier %v to tier %v.", addr, fromTier, toTier))

	return dao.NewProposalRequestWithFilter(
		"Member Promotion Proposal",
		ufmt.Sprintf("This is a proposal to promote %s from **%s** to **%s**.", tryResolveAddr(addr), fromTier, toTier),
		e,
		FilterByTier{Tier: toTier},
	)
}

func NewTreasuryPaymentRequest(cur realm, payment trs_pkg.Payment, reason string) dao.ProposalRequest {
	// A foreign impl renders a Payment line no Banker will process, so it would
	// fail only at execution, after the vote. Rejected here so the proposer
	// sees it, not the voters. See IsCanonicalPayment.
	if !trs_pkg.IsCanonicalPayment(payment) {
		panic("payment must be built by treasury.NewCoinsPayment or treasury.NewGRC20Payment")
	}
	if !treasury.HasBanker(payment.BankerID()) {
		panic("banker not registered in treasury with ID: " + payment.BankerID())
	}

	reason = strings.TrimSpace(reason)
	if reason == "" {
		panic("treasury payment request requires a reason")
	}

	cb := func(cur realm) error {
		return panictoerr.PanicToError(func() {
			treasury.Send(cross(cur), payment)
		})
	}

	// Both are caller-supplied and land in the same body as the Payment line a
	// member votes on, which render.gno emits raw. InlineText folds newlines to
	// spaces, so neither can start a line of its own and forge that label.
	// Clamp before escaping, per clamp.gno.
	safeReason := sanitize.InlineText(clampField(reason, maxRenderedReason))
	safePayment := sanitize.InlineText(clampField(payment.String(), maxRenderedPayment))

	e := dao.NewSimpleExecutor(0, cur,
		cb,
		ufmt.Sprintf(
			"A payment will be sent by the GovDAO treasury.\n\nReason: %s\n\nPayment: %s.",
			safeReason,
			safePayment,
		),
	)

	return dao.NewProposalRequest(
		"Treasury Payment",
		ufmt.Sprintf(
			"This proposal is looking to send a payment using the treasury.\n\nReason: %s\n\nPayment: %s",
			safeReason,
			safePayment,
		),
		e,
	)
}

// NewTreasuryGRC20TokensUpdate creates a proposal request to update the list of GRC20 tokens registry
// keys used by the treasury. The new list, if voted and accepted, will overwrite the current one.
func NewTreasuryGRC20TokensUpdate(cur realm, newTokenKeys []string) dao.ProposalRequest {
	if len(newTokenKeys) == 0 {
		panic("the list of new tokens is empty")
	}

	// Copied for the same reason NewCoinsPayment copies its coins: the bullet
	// list below is rendered once at creation, but the executor closure
	// re-reads the slice at execution, so the caller could otherwise install a
	// token set the board never saw.
	keys := make([]string, len(newTokenKeys))
	copy(keys, newTokenKeys)

	cb := func(cur realm) error {
		return panictoerr.PanicToError(func() {
			// NOTE:: Consider checking if the keys are already registered
			// in the grc20reg before updating the treasury tokens keys.
			treasury.SetTokenKeys(cross(cur), keys)
		})
	}

	bulletList := md.BulletList(keys)

	e := dao.NewSimpleExecutor(0, cur,
		cb,
		ufmt.Sprintf(
			"The list of GRC20 tokens used by the treasury will be updated.\n\nNew Token Keys:\n%s.\n",
			bulletList,
		),
	)

	return dao.NewProposalRequest(
		"Treasury GRC20 Tokens Update",
		ufmt.Sprintf(
			"This proposal is looking to update the list of GRC20 tokens used by the treasury.\n\nNew Token Keys:\n%s",
			bulletList,
		),
		e,
	)
}

func memberByTier(tier string) *memberstore.Member {
	switch tier {
	case memberstore.T1:
		t, _ := memberstore.GetTier(memberstore.T1)
		return memberstore.NewMember(t.InvitationPoints)
	case memberstore.T2:
		t, _ := memberstore.GetTier(memberstore.T2)
		return memberstore.NewMember(t.InvitationPoints)
	case memberstore.T3:
		t, _ := memberstore.GetTier(memberstore.T3)
		return memberstore.NewMember(t.InvitationPoints)
	default:
		panic("member not found by the specified tier")
	}
}

render.gno

package impl

import (
	"chain/runtime"
	"strconv"
	"strings"

	"gno.land/p/moul/helplink/v0"
	"gno.land/p/moul/md/v0"
	"gno.land/p/nt/bptree/pager/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/mux/v0"
	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/gov/dao"
	"gno.land/r/sys/users"
)

type render struct {
	relativeRealmPath string
	router            *mux.Router
	pssPager          *pager.Pager
}

func NewRender(d *GovDAO) *render {
	ren := &render{
		pssPager: pager.NewPager(d.pss.BPTree, 5, true),
	}

	r := mux.NewRouter()

	// Handlers use mux's rlm-aware shape: rlm is supplied at RenderRlm
	// dispatch time rather than captured at NewRender time. This lets
	// downstream crossing reads (dao.GetProposal etc.) use cross(rlm)
	// without relying on bare cross or restructuring the router.
	r.HandleFuncRlm("", func(_ int, rlm realm, rw *mux.ResponseWriter, req *mux.Request) {
		rw.Write(ren.renderActiveProposals(0, rlm, req.RawPath, d))
	})

	r.HandleFuncRlm("{pid}", func(_ int, rlm realm, rw *mux.ResponseWriter, req *mux.Request) {
		rw.Write(ren.renderProposalPage(0, rlm, req.GetVar("pid"), d))
	})

	r.HandleFuncRlm("{pid}/votes", func(_ int, rlm realm, rw *mux.ResponseWriter, req *mux.Request) {
		rw.Write(ren.renderVotesForProposal(0, rlm, req.GetVar("pid"), d))
	})

	ren.router = r

	return ren
}

func (ren *render) Render(_ int, rlm realm, pkgPath string, path string) string {
	relativePath, found := strings.CutPrefix(pkgPath, runtime.ChainDomain())
	if !found {
		panic(ufmt.Sprintf(
			"realm package with unexpected name found: %v in chain domain %v",
			pkgPath, runtime.ChainDomain()))
	}
	ren.relativeRealmPath = relativePath
	return ren.router.RenderRlm(0, rlm, path)
}

func (ren *render) renderActiveProposals(_ int, rlm realm, url string, d *GovDAO) string {
	out := "# GovDAO\n"
	out += "## Members\n"
	out += "[> Go to Memberstore <](/r/gov/dao/memberstore/v0)\n"
	out += "## Proposals\n"
	page, perr := ren.pssPager.GetPageByPath(url)
	if perr != nil {
		// A query url.Parse rejects (e.g. a control byte) is the caller's own
		// malformed input; render the default first page instead of aborting
		// this read-only render. ParseQuery already tolerates bad page/size
		// values, so every currently-working input is unaffected.
		page = ren.pssPager.GetPage(1)
	}
	if len(page.Items) == 0 {
		out += "\nNo proposals yet.\n\n"
		return out
	}

	for _, item := range page.Items {
		seqpid, err := seqid.FromString(item.Key)
		if err != nil {
			continue
		}
		out += ren.renderProposalListItem(0, rlm, ufmt.Sprintf("%v", int64(seqpid)), d)
		out += "---\n\n"
	}

	out += page.Picker("")

	return out
}

func (ren *render) renderProposalPage(_ int, rlm realm, sPid string, d *GovDAO) string {
	pid, err := strconv.ParseInt(sPid, 10, 64)
	if err != nil {
		// err echoes the caller's raw pid segment (strconv quotes it but leaves
		// markdown/HTML metachars); escape+clamp it like every other untrusted
		// slot on this page, since Render is reachable unauthenticated.
		return ufmt.Sprintf("# Error: Invalid proposal ID format.\n\n\n%s\n\n", md.EscapeText(clampField(err.Error(), maxRenderedError)))
	}

	p, err := dao.GetProposal(dao.ProposalID(pid))
	if err != nil {
		return ufmt.Sprintf("# Proposal not found\n\n%s", err.Error())
	}

	// pid is user-supplied and the proposal itself lives on the proxy, so
	// GetProposal can succeed for a proposal this implementation has no status
	// for — the same post-upgrade case PreExecuteProposal guards (statuses live
	// on the instance, so a fresh instance has none). Without this the page
	// panics at ps.String below. renderProposalListItem needs no such guard:
	// its pids are iterated out of pss itself, so a status always exists.
	ps := d.pss.GetStatus(dao.ProposalID(pid))
	if ps == nil {
		return ufmt.Sprintf("# Proposal #%v not available\n\nThis proposal was not created by the current govDAO implementation, so it has no voting status here.", pid)
	}

	out := ufmt.Sprintf("## Prop #%v - %v\n", pid, md.EscapeText(clampField(p.Title(), maxRenderedTitle)))
	out += "Author: " + tryResolveAddr(p.Author()) + "\n\n"

	out += p.Description()
	out += "\n\n"

	// Add executor metadata if available
	if p.ExecutorString() != "" {
		out += ufmt.Sprintf(`This proposal contains the following metadata:

%s

`, p.ExecutorString())
	}

	// Disclosed independently of the description: this names the realm whose
	// code runs if the proposal passes. Sharing the gate above hid it for every
	// proposal built with an empty executor description — 16 call sites across
	// 7 production realms, nearly all r/sys/* governance actions.
	//
	// Escaped, not trusted: CreationRealm() is dispatched through the public
	// dao.Executor interface, so only SimpleExecutor's value is VM-captured;
	// a third-party executor returns any string it likes.
	// Guarded on the sanitized value, not the raw one: InlineCode returns ""
	// for input that strips to nothing (bidi/zero-width only), and TrimSpace
	// catches plain whitespace, so neither prints a label with nothing after
	// it. This is tidiness, not a boundary: a zero-width/space mixture still
	// renders an empty-looking span, and a hostile executor can always return
	// a plausible-looking lie. The security property is the escaping below.
	if cr := sanitize.InlineCode(strings.TrimSpace(clampField(p.ExecutorCreationRealm(), maxRenderedRealm))); cr != "" {
		out += ufmt.Sprintf("Executor created in: %s\n", cr)
		out += "\n\n"
	}

	out += "\n\n---\n\n"
	out += ps.String(0, rlm)
	out += "\n"
	out += ufmt.Sprintf("[Detailed voting list](%v:%v/votes)", ren.relativeRealmPath, pid)
	out += "\n\n---\n\n"

	out += renderActionBar(ufmt.Sprintf("%v", pid))

	return out
}

func (ren *render) renderProposalListItem(_ int, rlm realm, sPid string, d *GovDAO) string {
	pid, err := strconv.ParseInt(sPid, 10, 64)
	if err != nil {
		// err echoes the caller's raw pid segment (strconv quotes it but leaves
		// markdown/HTML metachars); escape+clamp it like every other untrusted
		// slot on this page, since Render is reachable unauthenticated.
		return ufmt.Sprintf("# Error: Invalid proposal ID format.\n\n\n%s\n\n", md.EscapeText(clampField(err.Error(), maxRenderedError)))
	}

	p, err := dao.GetProposal(dao.ProposalID(pid))
	if err != nil {
		return ufmt.Sprintf("# Proposal not found\n\n%s\n\n", err.Error())
	}

	ps := d.pss.GetStatus(dao.ProposalID(pid))
	out := ufmt.Sprintf("### [Prop #%v - %v](%v:%v)\n", pid, md.EscapeText(clampField(p.Title(), maxRenderedTitle)), ren.relativeRealmPath, pid)
	out += ufmt.Sprintf("Author: %s\n\n", tryResolveAddr(p.Author()))

	out += "Status: " + getPropStatus(ps)
	out += "\n\n"

	out += "Tiers eligible to vote: "
	out += strings.Join(ps.TiersAllowedToVote, ", ")

	out += "\n\n"
	return out
}

func (ren *render) renderVotesForProposal(_ int, rlm realm, sPid string, d *GovDAO) string {
	pid, err := strconv.ParseInt(sPid, 10, 64)
	if err != nil {
		// err echoes the caller's raw pid segment (strconv quotes it but leaves
		// markdown/HTML metachars); escape+clamp it like every other untrusted
		// slot on this page, since Render is reachable unauthenticated.
		return ufmt.Sprintf("# Error: Invalid proposal ID format.\n\n\n%s\n\n", md.EscapeText(clampField(err.Error(), maxRenderedError)))
	}

	ps := d.pss.GetStatus(dao.ProposalID(pid))
	if ps == nil {
		return ufmt.Sprintf("# Proposal not found\n\nProposal %v does not exist.", pid)
	}

	out := ""
	out += ufmt.Sprintf("# Proposal #%v - Vote List\n\n", pid)
	out += StringifyVotes(0, rlm, ps)

	return out
}

func isPropActive(ps *proposalStatus) bool {
	return !ps.Accepted && !ps.Denied
}

func getPropStatus(ps *proposalStatus) string {
	if ps == nil {
		return "UNKNOWN"
	}
	if ps.Accepted {
		return "ACCEPTED"
	} else if ps.Denied {
		return "REJECTED"
	}
	return "ACTIVE"
}

func renderActionBar(sPid string) string {
	out := "### Actions\n"

	proxy := helplink.Realm("gno.land/r/gov/dao")
	out += proxy.Func("Vote YES", "MustVoteOnProposalSimple", "pid", sPid, "option", "YES") + " | "
	out += proxy.Func("Vote NO", "MustVoteOnProposalSimple", "pid", sPid, "option", "NO") + " | "
	out += proxy.Func("Vote ABSTAIN", "MustVoteOnProposalSimple", "pid", sPid, "option", "ABSTAIN")

	out += "\n\n"
	out += "WARNING: Please double check transaction data before voting."
	return out
}

// tryResolveAddr renders the author/voter as a username link. RenderLink
// interpolates the username raw into "[@name](/u/name)" (r/sys/users), so this
// is markdown-safe ONLY because r/sys/users validateName restricts names to
// ^[a-z][a-z0-9]*([_-][a-z0-9]+)*$ (max 64) — no markdown/HTML metachar. If that
// charset ever loosens, this line and writeVotes in types.gno need escaping.
func tryResolveAddr(addr address) string {
	userData := users.ResolveAddress(addr)
	if userData == nil {
		return addr.String()
	}
	return userData.RenderLink("")
}

types.gno

package impl

import (
	"strings"

	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/gov/dao"
	"gno.land/r/gov/dao/memberstore/v0"
)

type Law struct {
	Supermajority float64
}

func NewLaw(supermajority float64) Law {
	return Law{Supermajority: supermajority}
}

func (l *Law) String() string {
	return ufmt.Sprintf("This law contains the following data:\n\n- Supermajority: %v%%", l.Supermajority)
}

// ProposalsStatuses contains the status of all the proposals indexed by the proposal ID.
type ProposalsStatuses struct {
	*bptree.BPTree // map[int]*proposalStatus
}

func NewProposalsStatuses() ProposalsStatuses {
	return ProposalsStatuses{bptree.NewBPTree32()}
}

func (pss ProposalsStatuses) GetStatus(id dao.ProposalID) *proposalStatus {
	if pss.BPTree == nil {
		return nil
	}

	pids := id.String()
	psv := pss.Get(pids)
	if psv == nil {
		return nil
	}

	ps, ok := psv.(*proposalStatus)
	if !ok {
		panic("ProposalsStatuses must contains only proposalStatus types")
	}

	return ps
}

type proposalStatus struct {
	YesVotes     memberstore.MembersByTier
	NoVotes      memberstore.MembersByTier
	AbstainVotes memberstore.MembersByTier
	AllVotes     memberstore.MembersByTier

	Accepted bool
	Denied   bool

	DeniedReason string

	TiersAllowedToVote []string
}

func getMembers(cur realm) memberstore.MembersByTier {
	return memberstore.Get(0, cur)
}

func newEmptyVoteStore() memberstore.MembersByTier {
	mbt := memberstore.NewMembersByTier()
	mbt.SetTier(memberstore.T1)
	mbt.SetTier(memberstore.T2)
	mbt.SetTier(memberstore.T3)
	return mbt
}

func newProposalStatus(allowedToVote []string) *proposalStatus {
	return &proposalStatus{
		YesVotes:           newEmptyVoteStore(),
		NoVotes:            newEmptyVoteStore(),
		AbstainVotes:       newEmptyVoteStore(),
		AllVotes:           newEmptyVoteStore(),
		TiersAllowedToVote: allowedToVote,
	}
}

// totalPower computes the total voting power dynamically from current members
// rather than using a snapshot. See https://github.com/gnolang/gno/pull/5271#discussion_r2952523023
//
// Non-crossing: rlm is threaded into the crossing getMembers(cross(rlm))
// call. The proposalStatus methods that compose this (votePowerPercent,
// YesPercent etc., String) all take `_ int, rlm realm` for the same reason.
func (ps *proposalStatus) totalPower(_ int, rlm realm) float64 {
	members := getMembers(cross(rlm))
	var tp float64
	for _, tn := range ps.TiersAllowedToVote {
		power := memberstore.GetTierPower(tn, members)
		tp += power * float64(members.GetTierSize(tn))
	}
	return tp
}

func (ps *proposalStatus) votePowerPercent(_ int, rlm realm, votes memberstore.MembersByTier) float64 {
	members := getMembers(cross(rlm))
	var vp float64
	memberstore.IterateTiers(func(tn string, tier memberstore.Tier) bool {
		power := memberstore.GetTierPower(tn, members)
		ts := votes.GetTierSize(tn)
		vp = vp + (power * float64(ts))
		return false
	})
	tp := ps.totalPower(0, rlm)
	if tp == 0 {
		return 0
	}
	return (vp / tp) * 100
}

func (ps *proposalStatus) YesPercent(_ int, rlm realm) float64 {
	return ps.votePowerPercent(0, rlm, ps.YesVotes)
}

func (ps *proposalStatus) NoPercent(_ int, rlm realm) float64 {
	return ps.votePowerPercent(0, rlm, ps.NoVotes)
}

func (ps *proposalStatus) AbstainPercent(_ int, rlm realm) float64 {
	return ps.votePowerPercent(0, rlm, ps.AbstainVotes)
}

func (ps *proposalStatus) IsAllowed(tier string) bool {
	for _, ta := range ps.TiersAllowedToVote {
		if ta == tier {
			return true
		}
	}

	return false
}

// XXX: can be optimized by passing down total power to Yes/No/Abstain percent fn to avoid re-computing
func (ps *proposalStatus) String(_ int, rlm realm) string {
	var sb strings.Builder
	sb.WriteString("### Stats\n")

	if ps.Accepted {
		sb.WriteString("- **PROPOSAL HAS BEEN ACCEPTED**\n")
	} else if ps.Denied {
		sb.WriteString("- **PROPOSAL HAS BEEN DENIED**\n")
		if ps.DeniedReason != "" {
			sb.WriteString("REASON: ")
			// DeniedReason is "execution failed: " + err.Error() from the
			// proposal's executor callback, which any third-party realm can
			// supply. Raw, it wrote attacker-controlled markdown directly beneath
			// the "PROPOSAL HAS BEEN DENIED" line. InlineText folds newlines, so
			// the reason cannot leave the REASON: line, and escapes emphasis and
			// raw HTML.
			sb.WriteString(sanitize.InlineText(clampField(ps.DeniedReason, maxRenderedReason)))
			sb.WriteString("\n")
		}
	} else {
		sb.WriteString("- **Proposal is open for votes**\n")
	}

	sb.WriteString("- Tiers eligible to vote: ")
	sb.WriteString(strings.Join(ps.TiersAllowedToVote, ", "))
	sb.WriteString("\n")

	sb.WriteString(ufmt.Sprintf("- YES PERCENT: %v%%\n", ps.YesPercent(0, rlm)))
	sb.WriteString(ufmt.Sprintf("- NO PERCENT: %v%%\n", ps.NoPercent(0, rlm)))
	sb.WriteString(ufmt.Sprintf("- ABSTAIN PERCENT: %v%%\n", ps.AbstainPercent(0, rlm)))

	return sb.String()
}

func StringifyVotes(_ int, rlm realm, ps *proposalStatus) string {
	var sb strings.Builder

	writeVotes(0, rlm, &sb, ps.YesVotes, "YES")
	writeVotes(0, rlm, &sb, ps.NoVotes, "NO")
	writeVotes(0, rlm, &sb, ps.AbstainVotes, "ABSTAIN")

	if sb.String() == "" {
		return "No one voted yet."
	}

	return sb.String()
}

func writeVotes(_ int, rlm realm, sb *strings.Builder, t memberstore.MembersByTier, title string) {
	if t.Size() == 0 {
		return
	}
	members := getMembers(cross(rlm))
	t.Iterate("", "", func(tn string, value interface{}) bool {
		_, ok := memberstore.GetTier(tn)
		if !ok {
			panic("tier not found")
		}

		power := memberstore.GetTierPower(tn, members)

		sb.WriteString(ufmt.Sprintf("%v from %v (VPPM %v):\n\n", title, tn, power))
		ms, _ := value.(*bptree.BPTree)
		ms.Iterate("", "", func(addr string, _ interface{}) bool {
			sb.WriteString("- " + tryResolveAddr(address(addr)) + "\n")
			return false
		})

		sb.WriteString("\n")

		return false
	})
}

func StringifyProposal(p *dao.Proposal) string {
	out := ufmt.Sprintf(`
### Title: %s

### Proposed by: %s

%s
`, p.Title(), p.Author(), p.Description())

	if p.ExecutorString() != "" {
		out += ufmt.Sprintf(`
This proposal contains the following metadata:

%s
`, p.ExecutorString())
	}

	// Disclosed independently of the metadata string, and escaped, for the
	// same reasons as render.renderProposalPage.
	if cr := sanitize.InlineCode(strings.TrimSpace(clampField(p.ExecutorCreationRealm(), maxRenderedRealm))); cr != "" {
		out += ufmt.Sprintf("\nExecutor created in: %s\n", cr)
	}

	return out
}

z_addr_validation_test.gno

package impl

import (
	"testing"

	"gno.land/p/nt/urequire/v0"
	"gno.land/r/gov/dao/memberstore/v0"
)

// Member addresses arrive as raw MsgCall strings (the VM does not validate an
// `address` arg), so a non-bech32 value — blank, oversized, or carrying
// markdown/pipe/HTML metachars — would otherwise be stored and then injected
// into the members render table. Both admission points reject it, matching the
// InitWithUsers precedent.
func TestNewAddMemberRequestRejectsInvalidAddress(cur realm, t *testing.T) {
	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))

	for _, bad := range []string{"evil|**pwn**", "", "not-an-address"} {
		urequire.PanicsWithMessage(t, cur,
			"invalid member address: "+bad,
			func() {
				NewAddMemberRequest(cur, address(bad), memberstore.T2, "portfolio")
			})
	}
}

z_denied_reason_store_test.gno

package impl

import (
	"errors"
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
	"gno.land/r/gov/dao"
	"gno.land/r/gov/dao/memberstore/v0"
)

// Named z_* so it sorts after govdao_test.gno, whose TestUpgradeDaoImplementation
// asserts a hard-coded proposal id. This builds its own GovDAO instance and
// registers a status directly, so it never touches the shared one.

type hugeErrExecutor struct{ msg string }

func (e *hugeErrExecutor) Execute(cur realm) error { return errors.New(e.msg) }

func (e *hugeErrExecutor) String() string { return "" }

func (e *hugeErrExecutor) CreationRealm() string { return "gno.land/r/test/hugeerr" }

// The denial reason is stored, not just shown. It is "execution failed: " plus
// whatever error the proposal's executor returned, and the executor is
// third-party code. Whoever executes the proposal pays the storage deposit for
// it, and that need not be the person who wrote the executor.
//
// This has to read the stored value rather than the rendered page. The render
// clamps to the same bound, so a page rendered from an unclamped store looks
// exactly like one rendered from a clamped store — testing through Render would
// pass whether or not the write is bounded.
func TestDeniedReasonIsClampedBeforeStoring(cur realm, t *testing.T) {
	g := NewGovDAO()
	pid := dao.ProposalID(987654)
	g.pss.Set(pid.String(), newProposalStatus([]string{memberstore.T1}))

	g.ExecuteProposal(0, cur, pid, &hugeErrExecutor{msg: strings.Repeat("E", 50000)})

	stored := g.pss.GetStatus(pid).DeniedReason
	uassert.True(t, len(stored) < maxRenderedReason+64,
		"the realm must not store a reason larger than it can display")
	uassert.True(t, strings.Contains(stored, "… truncated"),
		"a stored reason that was cut must say so")
	uassert.True(t, strings.HasPrefix(stored, "execution failed: E"),
		"the prefix and the start of the error must survive")
}

z_treasury_payment_request_test.gno

package impl

import (
	"testing"

	trs_pkg "gno.land/p/nt/treasury/v0"
	"gno.land/p/nt/urequire/v0"
)

// Named z_* for the same reason as z_upgrade_request_test.gno: govdao_test.gno
// asserts hard-coded proposal ids, and this test creates no proposal.

// foreignPayment satisfies trs_pkg.Payment without being one of treasury's own
// impls. BankerID names a banker the treasury really has registered, and
// String says whatever this realm likes.
type foreignPayment struct{}

func (foreignPayment) BankerID() string { return "Coins" }

func (foreignPayment) String() string { return "42ugnot to g1nobody" }

// The immutability NewCoinsPayment provides is a property of the concrete
// type, not of the Payment interface: a foreign impl renders a payment line
// members vote on and then fails CoinsBanker.Send's type assertion at
// execution, spending a whole vote cycle on a proposal that can never
// execute. Rejected at construction so the proposer sees it, not the voters.
func TestTreasuryPaymentRequestRejectsForeignPayment(cur realm, t *testing.T) {
	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))

	// PanicsWithMessage, not AbortsWithMessage: same-realm call, so the guard
	// raises a plain panic rather than a cross-realm abort.
	urequire.PanicsWithMessage(t, cur,
		"payment must be built by treasury.NewCoinsPayment or treasury.NewGRC20Payment",
		func() {
			NewTreasuryPaymentRequest(cur, foreignPayment{}, "a reason")
		})
}

// The check must not reject the real thing. GRC20 is used here because the
// Coins banker is the one govdao_test.gno's shared state leaves funded; both
// are canonical, and only the canonicality gate is under test.
func TestTreasuryPaymentRequestAcceptsCanonicalPayment(cur realm, t *testing.T) {
	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))

	urequire.NotPanics(t, cur, func() {
		NewTreasuryPaymentRequest(cur, trs_pkg.NewGRC20Payment("TOK", 1, m1), "a reason")
	})
}

z_unknown_proposal_test.gno

package impl

import (
	"testing"

	"gno.land/p/nt/urequire/v0"
	"gno.land/r/gov/dao"
)

// Named z_* so it sorts after govdao_test.gno, whose TestUpgradeDaoImplementation
// swaps the DAO implementation and asserts a hard-coded proposal id. This test
// creates no proposal, so it is safe to run against the shared state.

// A proposal id this implementation has no status for — an unknown id, or a
// proposal that outlived the GovDAO instance that created it (statuses live on
// the instance). The nil deref this used to hit surfaced as "runtime error:
// nil pointer dereference", which reads like a VM fault rather than a bad
// request.
//
// Note what this does NOT assert: that the proposal becomes rejectable.
// dao.executeProposal panics on ANY error from PreExecuteProposal, ahead of
// its execErrorRejects branch, so the guard buys a named error and nothing
// more.
func TestExecuteUnknownProposalNamesTheError(cur realm, t *testing.T) {
	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))

	urequire.AbortsWithMessage(t, cur, "proposal not found", func() {
		dao.ExecuteProposal(cross(cur), dao.ProposalID(999999))
	})
}

z_upgrade_request_test.gno

package impl

import (
	"testing"

	"gno.land/p/nt/urequire/v0"
	"gno.land/r/gov/dao"
)

// Named z_* so it sorts after govdao_test.gno, whose TestUpgradeDaoImplementation
// swaps the DAO implementation and asserts a hard-coded proposal id. This test
// creates no proposal, so it is safe to run against the shared state.

// An empty realmPkg would be stored verbatim as an allowlist entry, and
// InAllowedDAOs compares by exact string against a caller's PkgPath() — which
// is "" for a user realm. It would also render as a blank name in the grant
// sentence, so the proposal would not say who it was empowering. Rejected at
// proposal-construction time so the mistake surfaces to the author rather than
// at execution. UpdateImpl rejects it too; see r/gov/dao/allowlist_test.gno.
func TestUpgradeRequestRejectsBlankRealmPkg(cur realm, t *testing.T) {
	testing.SetOriginCaller(m1)
	testing.SetRealm(testing.NewUserRealm(m1))

	for _, padded := range []string{" gno.land/r/x", "gno.land/r/x "} {
		urequire.PanicsWithMessage(t, cur,
			"realmPkg must not have leading or trailing spaces",
			func() {
				NewUpgradeDaoImplRequest(cur, &mockDAO{}, padded, "reason")
			})
	}

	for _, blank := range []string{"", "   "} {
		// PanicsWithMessage, not AbortsWithMessage: this is a same-realm call,
		// so the guard raises a plain panic rather than a cross-realm abort.
		urequire.PanicsWithMessage(t, cur,
			"realmPkg must be the realm path being granted govDAO authority",
			func() {
				NewUpgradeDaoImplRequest(cur, &mockDAO{}, blank, "reason")
			})
	}
}

type mockDAO struct{}

func (d *mockDAO) PreCreateProposal(_ int, rlm realm, r dao.ProposalRequest) (address, error) {
	return m1, nil
}

func (d *mockDAO) PostCreateProposal(_ int, rlm realm, r dao.ProposalRequest, pid dao.ProposalID) {}

func (d *mockDAO) VoteOnProposal(_ int, rlm realm, r dao.VoteRequest) error { return nil }

func (d *mockDAO) PreExecuteProposal(_ int, rlm realm, pid dao.ProposalID) (bool, error) {
	return true, nil
}

func (d *mockDAO) ExecuteProposal(_ int, rlm realm, pid dao.ProposalID, e dao.Executor) error {
	return nil
}

func (d *mockDAO) Render(cur realm, pkgpath string, path string) string { return "" }