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

allowlist_test.gno

package dao

import (
	"testing"

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

// allowedDAOs is the sole authorization for UpdateImpl, memberstore.Get,
// treasury.Send and treasury.SetTokenKeys, and InAllowedDAOs() fails OPEN when
// it is empty — the bootstrap window that lets the genesis MsgRun seed the
// member set before lockdown.
//
// These tests pin that the transition empty -> non-empty is one-way: once the
// DAO is locked down, UpdateImpl cannot put it back into the fail-open state.
// Both paths below reopened the gate before the guard, because
// NewUpdateRequest copies nil into a NON-nil empty slice and the old test was
// `r.AllowedDAOs != nil`.
//
// These call the real UpdateImpl through a code realm rather than replaying
// its logic, so reverting the guard makes them fail.
func TestUpdateImplIgnoresEmptyAllowedDAOs(cur realm, t *testing.T) {
	savedDAOs, savedDAO := allowedDAOs, dao
	defer func() { allowedDAOs, dao = savedDAOs, savedDAO }()

	lock := func() {
		allowedDAOs = nil // reopen so the next UpdateImpl is permitted
		testing.SetRealm(testing.NewCodeRealm(v0))
		UpdateImpl(cross(cur), UpdateRequest{DAO: &dummyDao{}, AllowedDAOs: []string{v0}})
		uassert.False(t, InAllowedDAOs(invalid), "precondition: locked down")
	}

	// Path 1: NewUpdateRequest(d, nil) — "swap the implementation, leave
	// permissions alone", and the form v0/loader uses.
	lock()
	testing.SetRealm(testing.NewCodeRealm(v0))
	UpdateImpl(cross(cur), NewUpdateRequest(&dummyDao{}, nil))
	uassert.False(t, InAllowedDAOs(invalid),
		"a nil AllowedDAOs must not reopen the permission gate")

	// Path 2: an explicitly empty slice via the struct literal.
	lock()
	testing.SetRealm(testing.NewCodeRealm(v0))
	UpdateImpl(cross(cur), UpdateRequest{DAO: &dummyDao{}, AllowedDAOs: []string{}})
	uassert.False(t, InAllowedDAOs(invalid),
		"an empty AllowedDAOs must not reopen the permission gate")

	// A legitimate extension of the list must still apply.
	lock()
	testing.SetRealm(testing.NewCodeRealm(v0))
	UpdateImpl(cross(cur), NewUpdateRequest(&dummyDao{}, []string{v0, v1}))
	uassert.True(t, InAllowedDAOs(v1), "a non-empty AllowedDAOs must still be stored")
	uassert.False(t, InAllowedDAOs(invalid), "and must not admit anyone else")
}

// The bootstrap window itself must survive the guard: with no allowlist
// configured yet, any caller is allowed so the genesis MsgRun can seed the
// member set and then lock down.
func TestBootstrapWindowStillOpen(t *testing.T) {
	saved := allowedDAOs
	defer func() { allowedDAOs = saved }()

	allowedDAOs = nil
	uassert.True(t, InAllowedDAOs("gno.land/r/gov/dao/loader/v0"),
		"an unset allowlist must stay open for genesis bootstrap")
}

// len(AllowedDAOs) != 0 is not sufficient on its own. InAllowedDAOs compares by
// exact string and a user realm's PkgPath() is "", so a single "" entry admits
// any caller whose previous frame is a user realm — the same fail-open outcome
// the guard exists to prevent. NewUpgradeDaoImplRequest passes its realmPkg
// argument straight into the list, so an empty one reaches here.
func TestUpdateImplRejectsBlankAllowedDAOEntry(cur realm, t *testing.T) {
	savedDAOs, savedDAO := allowedDAOs, dao
	defer func() { allowedDAOs, dao = savedDAOs, savedDAO }()

	for _, blank := range []string{"", "   "} {
		allowedDAOs = nil
		testing.SetRealm(testing.NewCodeRealm(v0))
		UpdateImpl(cross(cur), UpdateRequest{DAO: &dummyDao{}, AllowedDAOs: []string{v0}})

		testing.SetRealm(testing.NewCodeRealm(v0))
		urequire.AbortsWithMessage(t, cur,
			"AllowedDAOs entries must be realm paths; got an empty one",
			func() {
				UpdateImpl(cross(cur), UpdateRequest{
					DAO:         &dummyDao{},
					AllowedDAOs: []string{v0, blank},
				})
			})

		uassert.False(t, InAllowedDAOs(""),
			"a blank entry must never make it into the allowlist")
		uassert.True(t, InAllowedDAOs(v0),
			"the rejected request must leave the previous allowlist intact")
	}
}

// A padded entry passes a plain non-blank test but is useless: entries are
// stored exactly as given and InAllowedDAOs compares whole strings, so
// " gno.land/r/x " matches no caller. The list is still non-empty, so the
// bootstrap window is closed. A proposal that padded every entry would lock
// the DAO out of its own allowlist with no way back.
func TestUpdateImplRejectsPaddedAllowedDAOEntry(cur realm, t *testing.T) {
	savedDAOs, savedDAO := allowedDAOs, dao
	defer func() { allowedDAOs, dao = savedDAOs, savedDAO }()

	for _, padded := range []string{" " + v1, v1 + " ", "\t" + v1} {
		allowedDAOs = nil
		testing.SetRealm(testing.NewCodeRealm(v0))
		UpdateImpl(cross(cur), UpdateRequest{DAO: &dummyDao{}, AllowedDAOs: []string{v0}})

		testing.SetRealm(testing.NewCodeRealm(v0))
		urequire.AbortsWithMessage(t, cur,
			"AllowedDAOs entries must not have leading or trailing spaces; entry 1",
			func() {
				UpdateImpl(cross(cur), UpdateRequest{
					DAO:         &dummyDao{},
					AllowedDAOs: []string{v0, padded},
				})
			})

		uassert.False(t, InAllowedDAOs(padded),
			"a padded entry must never make it into the allowlist")
		uassert.True(t, InAllowedDAOs(v0),
			"the rejected request must leave the previous allowlist intact")
	}
}

gnomod.toml

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

[addpkg]
  creator = "g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da"

proxy.gno

package dao

import (
	"chain"
	"errors"
	"strconv"
	"strings"

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

// dao is the actual govDAO implementation, having all the needed business logic
var dao DAO

// allowedDAOs contains realms that can be used to update the actual govDAO implementation,
// and validate Proposals.
// This is like that to be able to rollback using a previous govDAO implementation in case
// the latest implementation has a breaking bug. After a test period, a proposal can be
// executed to remove all previous govDAOs implementations and leave the last one.
var allowedDAOs []string

// proposals contains all the proposals in history.
var proposals *Proposals = NewProposals()

// Render calls directly to Render's DAO implementation.
// This allows to have this realm as the main entry point for everything.
func Render(cur realm, p string) string {
	if dao == nil {
		return "DAO not initialized"
	}
	return dao.Render(cross(cur), cur.PkgPath(), p)
}

// MustCreateProposal is an utility method that does the same as CreateProposal,
// but instead of erroing if something happens, it panics.
func MustCreateProposal(cur realm, r ProposalRequest) ProposalID {
	pid, err := CreateProposal(cur, r)
	if err != nil {
		panic(err.Error())
	}

	return pid
}

// ExecuteProposal will try to execute the proposal with the provided ProposalID.
// If the proposal was denied, it will return false. If the proposal is correctly
// executed, it will return true. If something happens this function will panic.
func ExecuteProposal(cur realm, pid ProposalID) bool {
	return executeProposal(cur, pid, false)
}

// ExecuteOrRejectProposal executes the proposal with the provided ProposalID or rejects
// it when there is an execution error.
// If the proposal was denied, it will return false. If the proposal is correctly
// executed, it will return true, unless execution fails with an error, in which case
// proposal is rejected with the error as the reason.
// This function allows to finish proposals by rejecting them when there is a state
// change or an error in the proposal parameters that makes execution fail, potentially
// leaving the proposal active forever because it can't be successfully executed.
func ExecuteOrRejectProposal(cur realm, pid ProposalID) bool {
	return executeProposal(cur, pid, true)
}

// CreateProposal will try to create a new proposal, that will be validated by the actual
// govDAO implementation. If the proposal cannot be created, an error will be returned.
func CreateProposal(cur realm, r ProposalRequest) (ProposalID, error) {
	if dao == nil {
		return -1, errors.New("DAO not initialized")
	}
	author, err := dao.PreCreateProposal(0, cur, r)
	if err != nil {
		return -1, err
	}

	p := &Proposal{
		author:      author,
		title:       r.title,
		description: r.description,
		executor:    r.executor,
		allowedDAOs: allowedDAOs[:],
	}

	pid := proposals.SetProposal(p)
	dao.PostCreateProposal(0, cur, r, pid)

	chain.Emit("ProposalCreated",
		"id", strconv.FormatInt(int64(pid), 10),
	)

	return pid, nil
}

func MustVoteOnProposal(cur realm, r VoteRequest) {
	if err := VoteOnProposal(cur, r); err != nil {
		panic(err.Error())
	}
}

// VoteOnProposal sends a vote to the actual govDAO implementation.
// If the voter cannot vote the specified proposal, this method will return an error
// with the explanation of why.
func VoteOnProposal(cur realm, r VoteRequest) error {
	if dao == nil {
		return errors.New("DAO not initialized")
	}
	return dao.VoteOnProposal(0, cur, r)
}

// MustVoteOnProposalSimple is like MustVoteOnProposal but intended to be used through gnokey with basic types.
func MustVoteOnProposalSimple(cur realm, pid int64, option string) {
	MustVoteOnProposal(cur, VoteRequest{
		Option:     VoteOption(option),
		ProposalID: ProposalID(pid),
	})
}

func MustGetProposal(pid ProposalID) *Proposal {
	p, err := GetProposal(pid)
	if err != nil {
		panic(err.Error())
	}

	return p
}

// GetProposal gets created proposal by its ID. Non-crossing pure read:
// looks up the proposal in this realm's package var. Callable directly
// from any realm without cross-call syntax.
func GetProposal(pid ProposalID) (*Proposal, error) {
	if dao == nil {
		return nil, errors.New("DAO not initialized")
	}
	prop := proposals.GetProposal(pid)
	if prop == nil {
		return nil, errors.New(ufmt.Sprintf("Proposal %v does not exist.", int64(pid)))
	}
	return prop, nil
}

// UpdateImpl is a method intended to be used on a proposal.
// This method will update the current govDAO implementation
// to a new one. AllowedDAOs are a list of realms that can
// call this method, in case the new DAO implementation had
// a breaking bug. A nil DAO is ignored.
// If AllowedDAOs field is not set correctly, the actual DAO
// implementation wont be able to execute new Proposals!
//
// An empty AllowedDAOs is ignored rather than stored. An empty list makes
// InAllowedDAOs() return true for every caller — the bootstrap-only state that
// lets the genesis MsgRun seed the member set. Since this is the only site that
// assigns allowedDAOs, ignoring empty here makes the transition
// empty -> non-empty one-way: once locked down the DAO cannot be reopened,
// whether the empty value arrives as a literal []string{} or from
// NewUpdateRequest(d, nil), which copies nil into a non-nil empty slice.
// Individual entries must be non-blank realm paths; an empty entry would match
// a user realm's empty PkgPath() and is rejected.
func UpdateImpl(cur realm, r UpdateRequest) {
	// AGENTS.md: in a crossing function, always check IsCurrent() before
	// deriving caller identity from cur.Previous(). Redundant under the
	// crossing-frame guarantee, but mandated, and this is the single most
	// powerful entrypoint (it rewrites the allowlist and swaps the impl).
	if !cur.IsCurrent() {
		panic("UpdateImpl: realm value is not the caller's live cur")
	}
	gRealm := cur.Previous().PkgPath()

	if !InAllowedDAOs(gRealm) {
		panic("permission denied for prev realm: " + gRealm)
	}

	if len(r.AllowedDAOs) != 0 {
		// Every entry must be a real realm path. len() != 0 alone is the wrong
		// invariant: InAllowedDAOs compares by exact string, and a user realm's
		// PkgPath() is "", so a single "" entry admits any caller whose previous
		// frame is a user realm -- the same fail-open outcome this guard exists
		// to prevent, just spelled differently. An empty entry can only be a
		// drafting mistake, so reject the whole request rather than silently
		// dropping it and storing a list the proposal did not describe.
		for i, d := range r.AllowedDAOs {
			trimmed := strings.TrimSpace(d)
			if trimmed == "" {
				panic("AllowedDAOs entries must be realm paths; got an empty one")
			}
			// Entries are stored exactly as given, and InAllowedDAOs compares
			// whole strings, so an entry with surrounding spaces matches no
			// caller at all. A non-empty list also closes the bootstrap
			// window, so a list of only padded entries is locked shut against
			// everyone, the DAO included, with no way to reopen it.
			//
			// This does not make the list typo-proof, and is not meant to be:
			// any wrong path locks the DAO out exactly the same way, and no
			// check here can tell a typo from a realm that does not exist yet.
			// Whitespace is worth rejecting because it is the one spelling a
			// human reviewing the proposal cannot see. Rejected rather than
			// trimmed, so what gets stored is what the proposal said.
			// Reported by position, not by value. A panic message becomes the
			// proposal's DeniedReason, which is stored, and the entry is
			// caller-supplied and unbounded — echoing it would put an
			// arbitrary amount of someone else's text into this realm's
			// storage. The index is enough to find it in a list the proposal
			// author wrote.
			if d != trimmed {
				panic("AllowedDAOs entries must not have leading or trailing spaces; entry " + strconv.Itoa(i))
			}
		}
		// Stored as given. A defensive copy here looks prudent but would
		// guard a write no outside realm can perform, which was checked from
		// a separate realm rather than assumed:
		//
		//   - Building this request as a literal fails outright, with
		//     "cannot allocate gno.land/r/gov/dao.UpdateRequest in realm ...".
		//   - Writing through a request obtained from NewUpdateRequest fails
		//     with "cannot directly modify readonly tainted object".
		//
		// So the only way in is NewUpdateRequest, which copies already. Both
		// checks are language guarantees, not conventions.
		allowedDAOs = r.AllowedDAOs
	}

	if r.DAO != nil {
		dao = r.DAO
	}
}

func AllowedDAOs() []string {
	dup := make([]string, len(allowedDAOs))
	copy(dup, allowedDAOs)
	return dup
}

func InAllowedDAOs(pkg string) bool {
	if len(allowedDAOs) == 0 {
		return true // corner case for initialization
	}
	for _, d := range allowedDAOs {
		if pkg == d {
			return true
		}
	}
	return false
}

func executeProposal(cur realm, pid ProposalID, execErrorRejects bool) bool {
	if dao == nil {
		return false
	}
	execute, err := dao.PreExecuteProposal(0, cur, pid)
	if err != nil {
		panic(err.Error())
	}

	if !execute {
		return false
	}
	prop, err := GetProposal(pid)
	if err != nil {
		panic(err.Error())
	}

	err = dao.ExecuteProposal(0, cur, pid, prop.executor)
	if err != nil {
		if execErrorRejects {
			return false
		}

		panic(err.Error())
	}
	return true
}

proxy_test.gno

package dao

import (
	"chain/runtime/unsafe"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/urequire/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

const (
	v0 = "gno.land/r/gov/dao/impl/v0"
	v1 = "gno.land/r/gov/dao/v1/impl"
	v2 = "gno.land/r/gov/dao/v2/impl"
	v3 = "gno.land/r/gov/dao/v3/impl"
)

const invalid = "gno.land/r/invalid/dao"

var alice = testutils.TestAddress("alice")

func TestProxy_Functions(cur realm, t *testing.T) {
	// initialize tests
	UpdateImpl(cross(cur), UpdateRequest{
		DAO:         &dummyDao{},
		AllowedDAOs: []string{v0},
	})

	// invalid package cannot add a new dao in charge
	testing.SetRealm(testing.NewCodeRealm(invalid))
	urequire.AbortsWithMessage(t, cur, "permission denied for prev realm: gno.land/r/invalid/dao", func() {
		UpdateImpl(cross(cur), UpdateRequest{
			DAO: &dummyDao{},
		})
	})

	// dao in charge can add a new dao
	testing.SetRealm(testing.NewCodeRealm(v0))
	urequire.NotPanics(t, cur, func() {
		UpdateImpl(cross(cur), UpdateRequest{
			DAO: &dummyDao{},
		})
	})

	// v0 that is in charge adds v2 in charge
	testing.SetRealm(testing.NewCodeRealm(v0))
	urequire.NotPanics(t, cur, func() {
		UpdateImpl(cross(cur), UpdateRequest{
			DAO:         &dummyDao{},
			AllowedDAOs: []string{v0, v2},
		})
	})

	// v0 can still do updates
	testing.SetRealm(testing.NewCodeRealm(v0))
	urequire.NotPanics(t, cur, func() {
		UpdateImpl(cross(cur), UpdateRequest{
			AllowedDAOs: []string{v1},
		})
	})

	// not after removing himself from allowedDAOs list
	testing.SetRealm(testing.NewCodeRealm(v0))
	urequire.AbortsWithMessage(t, cur, "permission denied for prev realm: gno.land/r/gov/dao/impl/v0", func() {
		UpdateImpl(cross(cur), UpdateRequest{
			AllowedDAOs: []string{v0},
		})
	})

	var pid ProposalID
	testing.SetRealm(testing.NewUserRealm(alice))
	urequire.NotPanics(t, cur, func() {
		e := NewSimpleExecutor(0, cur,
			func(realm) error {
				return nil
			},
			"",
		)
		pid = MustCreateProposal(cross(cur), NewProposalRequest("Proposal Title", "Description", e))
	})

	p, err := GetProposal(1000)
	if p != nil || err == nil {
		panic("proposal should not exist and should return an error")
	}
	p = MustGetProposal(pid)
	urequire.Equal(t, "Proposal Title", p.Title())
	urequire.Equal(t, p.Author().String(), alice.String())

	// need to switch the context back to v1
	testing.SetRealm(testing.NewCodeRealm(v1))
	urequire.Equal(
		t,
		"Render: gno.land/r/gov/dao/test",
		Render(cross(cur), "test"),
	)

	// reset state
	testing.SetRealm(testing.NewCodeRealm(v1))
	UpdateImpl(cross(cur), UpdateRequest{
		DAO: &dummyDao{},
	})
	// UpdateImpl deliberately ignores an empty AllowedDAOs, so it can no
	// longer be used to restore the bootstrap-open state — that is the point
	// of the guard. Reset the package var directly instead; we are in the
	// same package.
	allowedDAOs = nil
}

type dummyDao struct{}

func (dd *dummyDao) PreCreateProposal(_ int, rlm realm, r ProposalRequest) (address, error) {
	return unsafe.OriginCaller(), nil
}

func (dd *dummyDao) PostCreateProposal(_ int, rlm realm, r ProposalRequest, pid ProposalID) {
}

func (dd *dummyDao) VoteOnProposal(_ int, rlm realm, r VoteRequest) error {
	return nil
}

func (dd *dummyDao) PreExecuteProposal(_ int, rlm realm, pid ProposalID) (bool, error) {
	return true, nil
}

func (dd *dummyDao) ExecuteProposal(_ int, rlm realm, pid ProposalID, e Executor) error {
	return nil
}

func (dd *dummyDao) Render(cur realm, pkgpath string, path string) string {
	return "Render: " + pkgpath + "/" + path
}

types.gno

package dao

import (
	"errors"
	"strings"

	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/seqid/v0"
)

type ProposalID int64

func (pid ProposalID) String() string {
	return seqid.ID(pid).String()
}

// VoteOption is the limited voting option for a DAO proposal
// New govDAOs can create their own VoteOptions if needed in the
// future.
type VoteOption string

const (
	AbstainVote VoteOption = "ABSTAIN" // Side is not chosen
	YesVote     VoteOption = "YES"     // Proposal should be accepted
	NoVote      VoteOption = "NO"      // Proposal should be rejected
)

type VoteRequest struct {
	Option     VoteOption
	ProposalID ProposalID
	Metadata   interface{}
}

func NewVoteRequest(option VoteOption, proposalID ProposalID) VoteRequest {
	return VoteRequest{
		Option:     option,
		ProposalID: proposalID,
	}
}

func NewVoteRequestWithMetadata(option VoteOption, proposalID ProposalID, metadata interface{}) VoteRequest {
	return VoteRequest{
		Option:     option,
		ProposalID: proposalID,
		Metadata:   metadata,
	}
}

func NewProposalRequest(title string, description string, executor Executor) ProposalRequest {
	return ProposalRequest{
		title:       title,
		description: description,
		executor:    executor,
	}
}

func NewProposalRequestWithFilter(title string, description string, executor Executor, filter Filter) ProposalRequest {
	return ProposalRequest{
		title:       title,
		description: description,
		executor:    executor,
		filter:      filter,
	}
}

type Filter interface{}

type ProposalRequest struct {
	title       string
	description string
	executor    Executor
	filter      Filter
}

func (p *ProposalRequest) Title() string {
	return p.title
}

func (p *ProposalRequest) Description() string {
	return p.description
}

func (p *ProposalRequest) Filter() Filter {
	return p.filter
}

type Proposal struct {
	author address

	title       string
	description string

	executor    Executor
	allowedDAOs []string
}

func (p *Proposal) Author() address {
	return p.author
}

func (p *Proposal) Title() string {
	return p.title
}

func (p *Proposal) Description() string {
	return p.description
}

func (p *Proposal) ExecutorString() string {
	if p.executor != nil {
		return p.executor.String()
	}

	return ""
}

func (p *Proposal) ExecutorCreationRealm() string {
	if p.executor != nil {
		return p.executor.CreationRealm()
	}

	return ""
}

func (p *Proposal) AllowedDAOs() []string {
	return append([]string(nil), p.allowedDAOs...)
}

type Proposals struct {
	seq            seqid.ID
	*bptree.BPTree // *bptree.BPTree[ProposalID]*Proposal
}

func NewProposals() *Proposals {
	return &Proposals{BPTree: bptree.NewBPTree32()}
}

func (ps *Proposals) SetProposal(p *Proposal) ProposalID {
	pid := ProposalID(int64(ps.seq))
	updated := ps.Set(pid.String(), p)
	if updated {
		panic("fatal error: Override proposals is not allowed")
	}
	ps.seq = ps.seq.Next()
	return pid
}

func (ps *Proposals) GetProposal(pid ProposalID) *Proposal {
	pv := ps.Get(pid.String())
	if pv == nil {
		return nil
	}

	return pv.(*Proposal)
}

type Executor interface {
	Execute(cur realm) error
	String() string
	CreationRealm() string
}

// NewSimpleExecutor constructs an Executor whose creationRealm is captured
// from rlm.PkgPath() at construction time. The IsCurrent() check rejects
// stale or stashed realm values so the captured value is the authentic
// caller realm. creationRealm is display-only (rendered as "Executor
// created in: ..." in proposal listings) — no auth gate downstream.
func NewSimpleExecutor(_ int, rlm realm, callback func(realm) error, description string) *SimpleExecutor {
	if !rlm.IsCurrent() {
		panic("NewSimpleExecutor: rlm is not the caller's live cur (stale capture or sibling frame)")
	}
	if callback == nil {
		panic("executor callback must not be nil")
	}

	return &SimpleExecutor{
		callback:      callback,
		desc:          description,
		creationRealm: rlm.PkgPath(),
	}
}

// SimpleExecutor implements the Executor interface using
// a callback function and a description string.
type SimpleExecutor struct {
	callback      func(realm) error
	desc          string
	creationRealm string
}

// proxyPkgPath is this package: the realm whose frame Execute mints for a
// callback, and therefore the only realm entitled to invoke one.
const proxyPkgPath = "gno.land/r/gov/dao"

// Execute runs the proposal's callback. Invocable only from this proxy.
//
// SECURITY: Execute is a CROSSING method declared here, so invoking it mints
// a gno.land/r/gov/dao frame for the callback — `cur.Previous()` inside the
// callback is this path whoever called. That is a capability: realms gate on
// it (authz.NewContractAuthority("gno.land/r/gov/dao") + DoByPrevious,
// ownable, anything reading Previous().Address()). Ungated, any realm could
// wrap a reachable `func(realm) error` — including an ordinary exported
// entrypoint of the victim — and run it with governance's identity, with no
// proposal id minted, so nothing to render, audit or deny afterwards.
//
// NOT InAllowedDAOs: that is SafeExecutor's bug. It holds the impl path while
// an executor's caller is the proxy, so it rejects the approved route and
// fails open while empty. Exact path plus subpackages, because
// impl.ExecuteProposal is non-crossing (Previous() is the proxy exactly), so
// a bare prefix would reject every real proposal.
//
// Gates the executor object's INVOCATION only. Keeping a privileged closure,
// or an exported entrypoint shaped like `func(realm) error`, out of reach
// stays the consumer's job — see r/gnops/valopers/admin.gno
// and p/moul/authz's NewContractAuthority godoc.
func (e *SimpleExecutor) Execute(cur realm) error {
	// IsCurrent first, as every other gate here does: otherwise Previous() is
	// read from whatever realm value the caller threaded in.
	if !cur.IsCurrent() {
		return errors.New("execution denied: cur is not the caller's live realm")
	}
	if prev := cur.Previous().PkgPath(); prev != proxyPkgPath &&
		!strings.HasPrefix(prev, proxyPkgPath+"/") {
		return errors.New("execution denied: executors are only invocable by " + proxyPkgPath)
	}

	// Check if executor was created using the constructor func
	if e.callback == nil {
		return nil
	}

	return e.callback(cross(cur))
}

func (e *SimpleExecutor) String() string {
	return e.desc
}

func (e *SimpleExecutor) CreationRealm() string {
	return e.creationRealm
}

func NewSafeExecutor(e Executor) *SafeExecutor {
	return &SafeExecutor{
		e: e,
	}
}

// SafeExecutor wraps an Executor to only allow its execution
// by allowed govDAOs.
type SafeExecutor struct {
	e Executor
}

func (e *SafeExecutor) Execute(cur realm) error {
	// IsCurrent first, matching every other allowlist gate in this tree
	// (proxy.go's UpdateImpl, treasury, memberstore). Without it this method
	// trusts whatever realm value it is handed, so a caller threading a stale
	// or sibling-frame cur would have its Previous() read from that value
	// rather than from the live frame.
	//
	// NewSafeExecutor has no call sites, so this type is currently dead code.
	// Live proposal execution goes through the Executor interface to
	// SimpleExecutor.Execute, which now gates on the invoking realm being the
	// proxy -- deliberately NOT on InAllowedDAOs, which holds the impl path
	// and therefore rejects the approved route and fails open while empty.
	// That is this method's bug; see SimpleExecutor.Execute.
	if !cur.IsCurrent() {
		return errors.New("execution denied: cur is not the caller's live realm")
	}
	// Verify the caller is an adequate Realm
	if !InAllowedDAOs(cur.Previous().PkgPath()) {
		return errors.New("execution only allowed by validated govDAOs")
	}

	return e.e.Execute(cross(cur))
}

func (e *SafeExecutor) String() string {
	return e.e.String()
}

func (e *SafeExecutor) CreationRealm() string {
	return e.e.CreationRealm()
}

// DAO is the govDAO implementation interface. All mutating/auth-gated
// methods take rlm as their realm-typed parameter in the second position
// (the `_ int, rlm realm` non-crossing form): callers thread the proxy's
// cur as data without forcing a realm transition, so the impl's existing
// unsafe.CurrentRealm()-based auth gates (isValidCall, memberstore.Get)
// continue to see the proxy realm. Render stays unchanged.
type DAO interface {
	// PreCreateProposal is called just before creating a new Proposal
	// It is intended to be used to get the address of the proposal, that
	// may vary depending on the DAO implementation, and to validate that
	// the requester is allowed to do a proposal
	PreCreateProposal(_ int, rlm realm, r ProposalRequest) (address, error)

	// PostCreateProposal is called after creating the Proposal. It is
	// intended to be used as a way to store a new proposal status, that
	// depends on the actuall govDAO implementation
	PostCreateProposal(_ int, rlm realm, r ProposalRequest, pid ProposalID)

	// VoteOnProposal will send a petition to vote for a specific proposal
	// to the actual govDAO implementation
	VoteOnProposal(_ int, rlm realm, r VoteRequest) error

	// PreExecuteProposal is called when someone is trying to execute a proposal by ID.
	// Is intended to be used to validate who can trigger the proposal execution.
	PreExecuteProposal(_ int, rlm realm, pid ProposalID) (bool, error)

	// ExecuteProposal executes the proposal executor and on error changes proposal
	// status to denied with the error message being the denial reason.
	// It returns the executor error when it fails.
	ExecuteProposal(_ int, rlm realm, pid ProposalID, e Executor) error

	// Render will return a human-readable string in markdown format that
	// will be used to show new data through the dao proxy entrypoint.
	// Crossing: the chain query layer auto-injects .cur, and
	// implementations forward cur to internal rlm-aware helpers (mux
	// RenderRlm + downstream cross(rlm) reads).
	Render(cur realm, pkgpath string, path string) string
}

type UpdateRequest struct {
	DAO         DAO
	AllowedDAOs []string
}

// NewUpdateRequest copies allowedDAOs into a fresh slice owned by
// /r/gov/dao. Under the storage=authority model, if we stored the
// caller-passed slice directly, the base ArrayValue would retain
// PkgID = caller_realm: storage rent would attribute to caller, and
// /r/gov/dao could not mutate (e.g. append to) its own copy without
// a DidUpdate panic. The internal copy ensures the UpdateRequest
// and its AllowedDAOs both live entirely in /r/gov/dao's authority.
func NewUpdateRequest(d DAO, allowedDAOs []string) UpdateRequest {
	cp := make([]string, len(allowedDAOs))
	copy(cp, allowedDAOs)
	return UpdateRequest{
		DAO:         d,
		AllowedDAOs: cp,
	}
}