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

accessor.gno

package governance

import (
	"gno.land/r/gnoswap/gov/staker"
)

type govStakerAccessor struct{}

// GetTotalDelegationAmountAtSnapshot forwards an aggregate delegation-history lookup.
//
// Parameters:
//   - snapshotTime: Unix timestamp at or before which to select the latest total-delegation entry.
//
// Returns:
//   - int64: aggregate delegated amount at or before snapshotTime.
//   - bool: true when a qualifying history entry exists; false otherwise.
func (g *govStakerAccessor) GetTotalDelegationAmountAtSnapshot(snapshotTime int64) (int64, bool) {
	return staker.GetTotalDelegationAmountAtSnapshot(snapshotTime)
}

// GetUserDelegationAmountAtSnapshot forwards a user's delegation-history lookup.
//
// Parameters:
//   - userAddr: Delegator address whose historical amount is queried.
//   - snapshotTime: Unix timestamp at or before which to select the latest user entry.
//
// Returns:
//   - int64: user's delegated amount at or before snapshotTime.
//   - bool: true when a qualifying history entry exists; false otherwise.
func (g *govStakerAccessor) GetUserDelegationAmountAtSnapshot(userAddr address, snapshotTime int64) (int64, bool) {
	return staker.GetUserDelegationAmountAtSnapshot(userAddr, snapshotTime)
}

// GetTotalxGnsSupply returns the total xGNS supply reported by the staker realm.
//
// Returns:
//   - int64: total xGNS supply, including launchpad-held xGNS.
func (g *govStakerAccessor) GetTotalxGnsSupply() int64 {
	return staker.GetTotalxGnsSupply()
}

func newGovStakerAccessor() GovStakerAccessor {
	return &govStakerAccessor{}
}

config.gno

package governance

import (
	"errors"

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

// Config represents the configuration of the governor contract.
// All parameters can be modified through Reconfigure by admin or governance.
type Config struct {
	// VotingStartDelay is the delay before voting starts after proposal creation (in seconds)
	VotingStartDelay int64
	// VotingPeriod is the duration during which votes are collected (in seconds)
	VotingPeriod int64
	// VotingWeightSmoothingDuration is the period over which voting weight is averaged
	// for proposal creation and cancellation threshold calculations (in seconds).
	VotingWeightSmoothingDuration int64
	// Quorum is the percentage of total xGNS supply required for proposal approval.
	// Total supply includes xGNS held by the launchpad.
	Quorum int64
	// ProposalCreationThreshold is the minimum xGNS amount required to create a proposal
	ProposalCreationThreshold int64
	// ExecutionDelay is the waiting period after voting ends before a proposal can be executed (in seconds)
	ExecutionDelay int64
	// ExecutionWindow is the time window during which an approved proposal can be executed (in seconds)
	ExecutionWindow int64
}

// IsValid reports whether the configuration's durations, threshold, quorum, and
// cumulative schedule values satisfy the governance validation constraints.
//
// Parameters:
//   - currentTime: current time value included when checking that the cumulative schedule does not become negative
//
// Returns:
//   - error: nil when all fields and cumulative values are valid; otherwise an error describing the first invalid value
func (c Config) IsValid(currentTime int64) error {
	if c.VotingStartDelay < 0 {
		return errors.New("votingStartDelay cannot be negative")
	}

	if c.VotingPeriod < 0 {
		return errors.New("votingPeriod cannot be negative")
	}

	if c.ExecutionDelay < 0 {
		return errors.New("executionDelay cannot be negative")
	}

	if c.ExecutionWindow < 0 {
		return errors.New("executionWindow cannot be negative")
	}

	if c.VotingWeightSmoothingDuration < 0 {
		return errors.New("votingWeightSmoothingDuration cannot be negative")
	}

	if c.ProposalCreationThreshold < 0 {
		return errors.New("proposalCreationThreshold cannot be negative")
	}

	if c.Quorum < 0 || c.Quorum > 100 {
		return errors.New("quorum must be between 0 and 100")
	}

	sum := int64(0)

	sum += c.VotingStartDelay
	if sum < 0 {
		return errors.New("votingStartDelay cannot be negative")
	}

	sum += c.VotingPeriod
	if sum < 0 {
		return errors.New("votingPeriod cannot be negative")
	}

	sum += c.ExecutionDelay
	if sum < 0 {
		return errors.New("executionDelay cannot be negative")
	}

	sum += c.ExecutionWindow
	if sum < 0 {
		return errors.New("executionWindow cannot be negative")
	}

	sum += currentTime
	if sum < 0 {
		return errors.New("total delay cannot be negative")
	}

	return nil
}

// NewConfig constructs a governance configuration from the supplied delays,
// thresholds, quorum percentage, and execution window.
//
// Parameters:
//   - votingStartDelay: delay from proposal creation until voting opens, in seconds
//   - votingPeriod: duration for which voting remains open, in seconds
//   - votingWeightSmoothingDuration: interval used to smooth delegation weight, in seconds
//   - quorum: required approval percentage of total xGNS supply, from 0 through 100
//   - proposalCreationThreshold: minimum xGNS amount required to create a proposal
//   - executionDelay: delay after voting ends before execution, in seconds
//   - executionWindow: duration after the execution delay during which execution is allowed, in seconds
//
// Returns:
//   - Config: configuration value populated with the supplied governance parameters
func NewConfig(
	votingStartDelay,
	votingPeriod,
	votingWeightSmoothingDuration,
	quorum,
	proposalCreationThreshold,
	executionDelay,
	executionWindow int64,
) Config {
	return Config{
		VotingStartDelay:              votingStartDelay,
		VotingPeriod:                  votingPeriod,
		VotingWeightSmoothingDuration: votingWeightSmoothingDuration,
		Quorum:                        quorum,
		ProposalCreationThreshold:     proposalCreationThreshold,
		ExecutionDelay:                executionDelay,
		ExecutionWindow:               executionWindow,
	}
}

// NewConfigPtr constructs a Config and returns a pointer to it. The Config is
// allocated within the governance domain realm, satisfying realm allocation
// checks for callers (such as tests) that require a *Config value.
//
// Parameters:
//   - votingStartDelay: delay from proposal creation until voting opens, in seconds
//   - votingPeriod: duration for which voting remains open, in seconds
//   - votingWeightSmoothingDuration: interval used to smooth delegation weight, in seconds
//   - quorum: required approval percentage of total xGNS supply, from 0 through 100
//   - proposalCreationThreshold: minimum xGNS amount required to create a proposal
//   - executionDelay: delay after voting ends before execution, in seconds
//   - executionWindow: duration after the execution delay during which execution is allowed, in seconds
//
// Returns:
//   - *Config: pointer to a configuration value populated with the supplied governance parameters
func NewConfigPtr(
	votingStartDelay,
	votingPeriod,
	votingWeightSmoothingDuration,
	quorum,
	proposalCreationThreshold,
	executionDelay,
	executionWindow int64,
) *Config {
	c := NewConfig(
		votingStartDelay,
		votingPeriod,
		votingWeightSmoothingDuration,
		quorum,
		proposalCreationThreshold,
		executionDelay,
		executionWindow,
	)
	return &c
}

// NewDefaultConfig returns the governance configuration's built-in defaults:
// one day before voting, seven days of voting, one day of weight smoothing,
// 50% quorum, a 1-billion-xGNS creation threshold, one day execution delay,
// and a 30-day execution window.
//
// Returns:
//   - Config: default governance configuration value
func NewDefaultConfig() Config {
	return Config{
		VotingStartDelay:              86400,         // 1 day - delay before voting starts
		VotingPeriod:                  604800,        // 7 days - duration for collecting votes
		VotingWeightSmoothingDuration: 86400,         // 1 day - period for averaging voting weight
		Quorum:                        50,            // 50% of total xGNS supply required
		ProposalCreationThreshold:     1_000_000_000, // 1 billion xGNS - minimum amount to create proposals
		ExecutionDelay:                86400,         // 1 day - waiting period before execution
		ExecutionWindow:               2592000,       // 30 days - window for executing proposals
	}
}

// NewConfigTree creates an empty BPTree used to index configuration values by
// their encoded int64 version.
//
// Returns:
//   - *bptree.BPTree: empty configuration index tree
func NewConfigTree() *bptree.BPTree {
	return bptree.NewBPTreeN(16)
}

counter.gno

package governance

// Counter manages unique incrementing IDs.
type Counter struct {
	id int64
}

// NewCounter creates a new Counter whose current ID is initialized to zero.
//
// Returns:
//   - *Counter: counter initialized with current ID 0
func NewCounter() *Counter {
	return &Counter{
		id: 0,
	}
}

// Get returns the counter's current ID without changing it.
//
// Returns:
//   - int64: currently stored counter ID
func (c *Counter) Get() int64 { return c.id }

// Set replaces the counter's current ID with id.
//
// Parameters:
//   - id: new current ID to store; the value is not incremented
func (c *Counter) Set(id int64) { c.id = id }

// Next increments the counter and returns the resulting ID.
//
// Returns:
//   - int64: incremented counter ID after the update
func (c *Counter) Next() int64 {
	c.id++
	return c.id
}

doc.gno

// Package governance implements proposal lifecycle management and voting.
// It supports text proposals, parameter changes, and community-pool spending.
// Voting uses timestamped delegation history and quorum from total xGNS supply
// (including launchpad-held xGNS); proposal timing and thresholds are configurable.
package governance

getters.gno

package governance

import (
	rotree "gno.land/p/nt/bptree/rotree/v0"
)

// ==================================
// Store Data Getters
// ==================================

// GetLatestConfigVersion returns the current governance configuration version.
//
// Returns:
//   - int64: latest configuration version stored by governance
func GetLatestConfigVersion() int64 {
	return getImplementation().GetLatestConfigVersion()
}

// GetCurrentProposalID returns the current proposal ID counter.
//
// Returns:
//   - int64: current proposal ID counter used for newly created proposals
func GetCurrentProposalID() int64 {
	return getImplementation().GetCurrentProposalID()
}

// GetMaxSmoothingPeriod returns the maximum smoothing period for delegation history cleanup.
//
// Returns:
//   - int64: maximum permitted smoothing period in seconds
func GetMaxSmoothingPeriod() int64 {
	return getImplementation().GetMaxSmoothingPeriod()
}

// ==================================
// Config Getters
// ==================================

// GetLatestConfig returns the latest governance configuration.
//
// Returns:
//   - Config: latest stored configuration for the current version
//   - error: nil on success, or an error when the current configuration is missing
func GetLatestConfig() (Config, error) {
	return getImplementation().GetLatestConfig()
}

// GetConfig returns a specific governance configuration by version.
//
// Parameters:
//   - configVersion: configuration version to retrieve
//
// Returns:
//   - Config: configuration stored under configVersion
//   - error: nil on success, or an error when configVersion is not found
func GetConfig(configVersion int64) (Config, error) {
	return getImplementation().GetConfig(configVersion)
}

// ==================================
// Proposal Getters
// ==================================

// GetProposals returns a read-only view of every proposal, keyed by the decimal
// string form of the proposal ID. Callers paginate it themselves through
// IterateByOffset. Reading an entry yields a clone, so the view cannot mutate
// realm state.
//
// Returns:
//   - *rotree.ReadOnlyTree: read-only proposal tree keyed by decimal proposal ID
func GetProposals() *rotree.ReadOnlyTree {
	return getImplementation().GetProposals()
}

// ExistsProposal checks whether a proposal is stored.
//
// Parameters:
//   - proposalID: proposal identifier to look up
//
// Returns:
//   - bool: true when proposalID is stored, otherwise false
func ExistsProposal(proposalID int64) bool {
	return getImplementation().ExistsProposal(proposalID)
}

// GetProposerByProposalId returns the proposer address of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to look up
//
// Returns:
//   - address: address that submitted the proposal
//   - error: nil on success, or an error when the proposal does not exist
func GetProposerByProposalId(proposalId int64) (address, error) {
	return getImplementation().GetProposerByProposalId(proposalId)
}

// GetProposalTypeByProposalId returns the type of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to look up
//
// Returns:
//   - ProposalType: type recorded for the proposal
//   - error: nil on success, or an error when the proposal does not exist
func GetProposalTypeByProposalId(proposalId int64) (ProposalType, error) {
	return getImplementation().GetProposalTypeByProposalId(proposalId)
}

// GetYeaByProposalId returns the yes vote weight of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect
//
// Returns:
//   - int64: total voting weight recorded for yes votes
//   - error: nil on success, or an error when the proposal does not exist
func GetYeaByProposalId(proposalId int64) (int64, error) {
	return getImplementation().GetYeaByProposalId(proposalId)
}

// GetNayByProposalId returns the no vote weight of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect
//
// Returns:
//   - int64: total voting weight recorded for no votes
//   - error: nil on success, or an error when the proposal does not exist
func GetNayByProposalId(proposalId int64) (int64, error) {
	return getImplementation().GetNayByProposalId(proposalId)
}

// GetConfigVersionByProposalId returns the config version used by a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect
//
// Returns:
//   - int64: governance configuration version captured by the proposal
//   - error: nil on success, or an error when the proposal does not exist
func GetConfigVersionByProposalId(proposalId int64) (int64, error) {
	return getImplementation().GetConfigVersionByProposalId(proposalId)
}

// GetQuorumAmountByProposalId returns the quorum requirement for a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect
//
// Returns:
//   - int64: minimum voting weight required for the proposal's quorum
//   - error: nil on success, or an error when the proposal does not exist
func GetQuorumAmountByProposalId(proposalId int64) (int64, error) {
	return getImplementation().GetQuorumAmountByProposalId(proposalId)
}

// GetTitleByProposalId returns the title of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect
//
// Returns:
//   - string: proposal title
//   - error: nil on success, or an error when the proposal does not exist
func GetTitleByProposalId(proposalId int64) (string, error) {
	return getImplementation().GetTitleByProposalId(proposalId)
}

// GetDescriptionByProposalId returns the description of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect
//
// Returns:
//   - string: proposal description
//   - error: nil on success, or an error when the proposal does not exist
func GetDescriptionByProposalId(proposalId int64) (string, error) {
	return getImplementation().GetDescriptionByProposalId(proposalId)
}

// GetProposalStatusByProposalId returns the current status of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect
//
// Returns:
//   - string: status computed from the proposal and the current Unix time
//   - error: nil on success, or an error when the proposal does not exist
func GetProposalStatusByProposalId(proposalId int64) (string, error) {
	return getImplementation().GetProposalStatusByProposalId(proposalId)
}

// GetProposalCreatedAt returns the creation timestamp of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to look up
//
// Returns:
//   - int64: Unix timestamp at which the proposal was created
//   - error: nil on success, or an error when the proposal does not exist
func GetProposalCreatedAt(proposalId int64) (int64, error) {
	return getImplementation().GetProposalCreatedAt(proposalId)
}

// GetProposalCreatedHeight returns the creation block height of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to look up
//
// Returns:
//   - int64: block height at which the proposal was created
//   - error: nil on success, or an error when the proposal does not exist
func GetProposalCreatedHeight(proposalId int64) (int64, error) {
	return getImplementation().GetProposalCreatedHeight(proposalId)
}

// ==================================
// Vote Getters
// ==================================

// GetVoteStatus returns the vote status of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect
//
// Returns:
//   - quorum: minimum vote weight required for the proposal to pass
//   - maxVotingWeight: maximum possible voting weight recorded for the proposal
//   - yesWeight: total weight of yes votes
//   - noWeight: total weight of no votes
//   - err: nil on success, or an error when the proposal does not exist
func GetVoteStatus(proposalId int64) (quorum, maxVotingWeight, yesWeight, noWeight int64, err error) {
	return getImplementation().GetVoteStatus(proposalId)
}

// GetVotingInfos returns a read-only view of a proposal's value-backed voting
// infos, keyed by voter address. Existing proposals have an empty view before
// the first vote; nil is returned only when the stored voting-info tree is absent.
//
// Parameters:
//   - proposalID: proposal identifier whose voting information is requested
//
// Returns:
//   - *rotree.ReadOnlyTree: read-only voting-info tree keyed by voter address, or nil when no tree is stored
func GetVotingInfos(proposalID int64) *rotree.ReadOnlyTree {
	return getImplementation().GetVotingInfos(proposalID)
}

// ExistsVotingInfo checks whether voting information exists for a user on a proposal.
//
// Parameters:
//   - proposalID: proposal identifier to inspect
//   - addr: voter address to look up within proposalID
//
// Returns:
//   - bool: true when voting information exists for the proposal and address
func ExistsVotingInfo(proposalID int64, addr address) bool {
	return getImplementation().ExistsVotingInfo(proposalID, addr)
}

// GetVoteWeight returns the voting weight of an address for a proposal.
//
// Parameters:
//   - proposalID: proposal identifier to inspect
//   - addr: voter address whose recorded vote weight is requested
//
// Returns:
//   - int64: weight recorded for addr's vote
//   - error: nil on success, or an error when no voting information exists for the proposal and address
func GetVoteWeight(proposalID int64, addr address) (int64, error) {
	return getImplementation().GetVoteWeight(proposalID, addr)
}

// GetVotedHeight returns the block height when an address voted on a proposal.
//
// Parameters:
//   - proposalID: proposal identifier to inspect
//   - addr: voter address whose vote height is requested
//
// Returns:
//   - int64: block height recorded for addr's vote
//   - error: nil on success, or an error when no voting information exists for the proposal and address
func GetVotedHeight(proposalID int64, addr address) (int64, error) {
	return getImplementation().GetVotedHeight(proposalID, addr)
}

// GetVotedAt returns the timestamp when an address voted on a proposal.
//
// Parameters:
//   - proposalID: proposal identifier to inspect
//   - addr: voter address whose vote timestamp is requested
//
// Returns:
//   - int64: Unix timestamp recorded for addr's vote
//   - error: nil on success, or an error when no voting information exists for the proposal and address
func GetVotedAt(proposalID int64, addr address) (int64, error) {
	return getImplementation().GetVotedAt(proposalID, addr)
}

// GetProposalCommunityPoolSpendInfo returns a cloned copy of the community pool spend info for a proposal.
//
// Parameters:
//   - proposalID: proposal identifier to inspect
//
// Returns:
//   - *CommunityPoolSpendInfo: cloned community-pool spend details, or nil when an error occurs
//   - error: nil on success, or an error when the proposal is missing or has no spend data
func GetProposalCommunityPoolSpendInfo(proposalID int64) (*CommunityPoolSpendInfo, error) {
	info, err := getImplementation().GetProposalCommunityPoolSpendInfo(proposalID)
	if err != nil {
		return nil, err
	}

	return info.Clone(), nil
}

// GetProposalExecutionInfo returns a cloned copy of the execution info for a proposal.
//
// Parameters:
//   - proposalID: proposal identifier to inspect
//
// Returns:
//   - *ExecutionInfo: cloned parameter-change execution messages and count, or nil when an error occurs
//   - error: nil on success, or an error when the proposal is missing or has no execution data
func GetProposalExecutionInfo(proposalID int64) (*ExecutionInfo, error) {
	info, err := getImplementation().GetProposalExecutionInfo(proposalID)
	if err != nil {
		return nil, err
	}

	return info.Clone(), nil
}

// ==================================
// User Proposal Getters
// ==================================

// GetUserProposals returns a read-only view of the proposals created per user,
// keyed by creator address with the creator's proposal IDs as the value.
// Reading an entry yields a copy of the ID slice, so the view cannot mutate
// realm state.
//
// Returns:
//   - *rotree.ReadOnlyTree: read-only user-proposal tree keyed by creator address
func GetUserProposals() *rotree.ReadOnlyTree {
	return getImplementation().GetUserProposals()
}

// ==================================
// Active Proposal Query
// ==================================

// GetOldestActiveProposalSnapshotTime returns the oldest active proposal's
// timestamp anchor. An empty index returns no active proposal; a stale or
// missing first entry returns an error so cleanup cannot silently skip it.
//
// Returns:
//   - int64: snapshot timestamp of the oldest active proposal, or zero when the index is empty or an error occurs
//   - bool: true when an active proposal was found at the oldest index entry, otherwise false
//   - error: nil for an empty index or active entry, or an error when the entry is missing or inactive
func GetOldestActiveProposalSnapshotTime() (int64, bool, error) {
	return getImplementation().GetOldestActiveProposalSnapshotTime()
}

// ==================================
// Voting weight snapshot getters
// ==================================

// GetCurrentVotingWeightSnapshot returns the current total voting weight and its
// timestamp anchor computed with the configured smoothing duration.
//
// Returns:
//   - int64: total voting weight averaged over the configured smoothing window
//   - int64: Unix timestamp used as the snapshot history anchor
//   - error: nil on success, or an error when the current configuration or snapshot data cannot be retrieved
func GetCurrentVotingWeightSnapshot() (int64, int64, error) {
	return getImplementation().GetCurrentVotingWeightSnapshot()
}

gnomod.toml

module = "gno.land/r/gnoswap/gov/governance"
gno = "0.9"

[addpkg]
  creator = "g1q5tjjv3kkslzwf2na9y9wk7e5a8ugph8xfsk04"
  height = 77261
  max_deposit = "100000000ugnot"

proposal.gno

package governance

import bptree "gno.land/p/nt/bptree/v0"

// Proposal represents a governance proposal with all its associated data and state.
// This is the core structure that tracks proposal lifecycle from creation to execution.
type Proposal struct {
	id            int64             // Unique identifier for the proposal
	proposer      address           // The address of the proposer
	configVersion int64             // The version of the governance config used
	status        *ProposalStatus   // Current status and voting information
	metadata      *ProposalMetadata // Title and description
	data          *ProposalData     // Type-specific proposal data
	snapshotTime  int64             // Timestamp for voting weight snapshot lookup
	createdHeight int64             // Block height at creation
}

// ID returns the unique identifier assigned to the proposal.
//
// Returns:
//   - int64: proposal identifier used as its storage key
func (p *Proposal) ID() int64 {
	return p.id
}

// Type returns the proposal's type discriminator from its type-specific data.
//
// Returns:
//   - ProposalType: proposal kind, such as text, community-pool spend, or parameter change
func (p *Proposal) Type() ProposalType {
	return p.data.ProposalType()
}

// Title returns the proposal title stored in its metadata.
//
// Returns:
//   - string: proposal title
func (p *Proposal) Title() string {
	return p.metadata.Title()
}

// Description returns the proposal description stored in its metadata.
//
// Returns:
//   - string: proposal description
func (p *Proposal) Description() string {
	return p.metadata.Description()
}

// Proposer returns the address that created the proposal.
//
// Returns:
//   - address: proposal creator's address
func (p *Proposal) Proposer() address {
	return p.proposer
}

// CreatedHeight returns the block height at which the proposal was created.
//
// Returns:
//   - int64: proposal creation block height
func (p *Proposal) CreatedHeight() int64 {
	return p.createdHeight
}

// CreatedAt returns the proposal creation timestamp recorded in its schedule.
//
// Returns:
//   - int64: proposal creation timestamp
func (p *Proposal) CreatedAt() int64 {
	return p.status.schedule.createTime
}

// VotingYesWeight returns the total weight recorded for "yes" votes.
//
// Returns:
//   - int64: current "yes" vote weight
func (p *Proposal) VotingYesWeight() int64 {
	return p.status.voteStatus.yea
}

// VotingNoWeight returns the total weight recorded for "no" votes.
//
// Returns:
//   - int64: current "no" vote weight
func (p *Proposal) VotingNoWeight() int64 {
	return p.status.voteStatus.nay
}

// VotingQuorumAmount returns the minimum total vote weight required to pass.
//
// Returns:
//   - int64: quorum vote weight required by this proposal's configuration
func (p *Proposal) VotingQuorumAmount() int64 {
	return p.status.voteStatus.quorumAmount
}

// VotingMaxWeight returns the maximum voting weight recorded for this proposal.
//
// Returns:
//   - int64: maximum voting weight used for the proposal's quorum calculation
func (p *Proposal) VotingMaxWeight() int64 {
	return p.status.voteStatus.maxVotingWeight
}

// ConfigVersion returns the governance configuration version used by the proposal.
//
// Returns:
//   - int64: configuration version captured when the proposal was created
func (p *Proposal) ConfigVersion() int64 {
	return p.configVersion
}

// SnapshotTime returns the timestamp used to look up historical voting weight.
//
// Returns:
//   - int64: voting-weight snapshot timestamp
func (p *Proposal) SnapshotTime() int64 {
	return p.snapshotTime
}

// Data returns the proposal's type-specific data.
//
// Returns:
//   - *ProposalData: type-specific proposal data stored on the proposal
func (p *Proposal) Data() *ProposalData {
	return p.data
}

// Status returns the proposal's schedule, vote, and action status.
//
// Returns:
//   - *ProposalStatus: mutable aggregate status associated with the proposal
func (p *Proposal) Status() *ProposalStatus {
	return p.status
}

// Metadata returns the proposal's title and description metadata.
//
// Returns:
//   - *ProposalMetadata: metadata stored on the proposal
func (p *Proposal) Metadata() *ProposalMetadata {
	return p.metadata
}

// IsTextType reports whether the proposal is a text proposal.
//
// Returns:
//   - bool: true when the proposal type is Text
func (p *Proposal) IsTextType() bool {
	return p.Type() == Text
}

// IsCommunityPoolSpendType reports whether the proposal spends community-pool funds.
//
// Returns:
//   - bool: true when the proposal type is CommunityPoolSpend
func (p *Proposal) IsCommunityPoolSpendType() bool {
	return p.Type() == CommunityPoolSpend
}

// IsParameterChangeType reports whether the proposal changes governance parameters.
//
// Returns:
//   - bool: true when the proposal type is ParameterChange
func (p *Proposal) IsParameterChangeType() bool {
	return p.Type() == ParameterChange
}

// IsProposer reports whether addr matches the proposal's proposer address.
//
// Parameters:
//   - addr: address to compare with the proposal proposer
//
// Returns:
//   - bool: true when addr is the proposal proposer
func (p *Proposal) IsProposer(addr address) bool {
	return p.proposer == addr
}

// NewProposal creates a new proposal instance with the supplied identity,
// lifecycle, metadata, and type-specific data.
//
// Parameters:
//   - proposalID: unique identifier assigned to the proposal
//   - status: initial schedule, action, and voting status
//   - metadata: proposal title and description metadata
//   - data: type-specific proposal data
//   - proposerAddress: address of the proposal creator
//   - configVersion: governance configuration version captured for the proposal
//   - snapshotTime: timestamp anchor for historical voting-weight lookup
//   - createdHeight: block height at which the proposal was created
//
// Returns:
//   - *Proposal: newly initialized proposal containing the supplied fields
func NewProposal(
	proposalID int64,
	status *ProposalStatus,
	metadata *ProposalMetadata,
	data *ProposalData,
	proposerAddress address,
	configVersion int64,
	snapshotTime int64,
	createdHeight int64,
) *Proposal {
	return &Proposal{
		id:            proposalID,
		proposer:      proposerAddress,
		status:        status,
		metadata:      metadata,
		data:          data,
		configVersion: configVersion,
		snapshotTime:  snapshotTime,
		createdHeight: createdHeight,
	}
}

// Clone returns a deep copy of the proposal, including its type-specific data
// and nested execution messages.
//
// The returned proposal and all nested status, metadata, data, and message
// values are independent copies; mutating the clone does not mutate realm state.
//
// Returns:
//   - *Proposal: independent proposal copy, or nil when the receiver is nil
func (p *Proposal) Clone() *Proposal {
	if p == nil {
		return nil
	}

	return &Proposal{
		id:            p.id,
		proposer:      p.proposer,
		configVersion: p.configVersion,
		status:        p.status.Clone(),
		metadata:      p.metadata.Clone(),
		data:          p.data.Clone(),
		snapshotTime:  p.snapshotTime,
		createdHeight: p.createdHeight,
	}
}

// NewProposalTree creates an empty B+ tree for proposals keyed by proposal ID.
//
// Returns:
//   - *bptree.BPTree: empty 16-way proposal tree
func NewProposalTree() *bptree.BPTree {
	return bptree.NewBPTreeN(16)
}

// NewUserProposalTree creates an empty B+ tree mapping users to proposal IDs.
//
// Returns:
//   - *bptree.BPTree: empty 16-way user-proposal index tree
func NewUserProposalTree() *bptree.BPTree {
	return bptree.NewBPTreeN(16)
}

// NewVotingInfoTree creates an empty B+ tree for per-user voting information.
//
// Returns:
//   - *bptree.BPTree: empty 16-way voting-information tree
func NewVotingInfoTree() *bptree.BPTree {
	return bptree.NewBPTreeN(16)
}

// NewProposalUserVotingInfoTree creates an empty B+ tree mapping proposal IDs
// to their per-user voting-information trees.
//
// Returns:
//   - *bptree.BPTree: empty 16-way proposal voting-information index tree
func NewProposalUserVotingInfoTree() *bptree.BPTree {
	return bptree.NewBPTreeN(16)
}

proposal_action_status.gno

package governance

// ProposalActionStatus tracks the execution and cancellation status of a proposal.
// This structure manages the action-related state including who performed actions and when.
type ProposalActionStatus struct {
	canceled       bool    // Whether the proposal has been canceled
	canceledAt     int64   // Timestamp when proposal was canceled
	canceledHeight int64   // Block height when proposal was canceled
	canceledBy     address // Who canceled the proposal

	executed       bool    // Whether the proposal has been executed
	executedAt     int64   // Timestamp when proposal was executed
	executedHeight int64   // Block height when proposal was executed
	executedBy     address // Who executed the proposal

	executable bool // Whether this proposal type supports execution
}

/* Getter methods */
// Canceled reports whether this proposal has been marked canceled.
//
// Returns:
//   - bool: true when cancellation has been recorded
func (p *ProposalActionStatus) Canceled() bool { return p.canceled }

// CanceledAt returns the timestamp recorded when the proposal was canceled.
//
// Returns:
//   - int64: cancellation timestamp, or zero when none has been recorded
func (p *ProposalActionStatus) CanceledAt() int64 { return p.canceledAt }

// CanceledHeight returns the block height recorded when the proposal was canceled.
//
// Returns:
//   - int64: cancellation block height, or zero when none has been recorded
func (p *ProposalActionStatus) CanceledHeight() int64 { return p.canceledHeight }

// Executed reports whether this proposal has been marked executed.
//
// Returns:
//   - bool: true when execution has been recorded
func (p *ProposalActionStatus) Executed() bool { return p.executed }

// ExecutedAt returns the timestamp recorded when the proposal was executed.
//
// Returns:
//   - int64: execution timestamp, or zero when none has been recorded
func (p *ProposalActionStatus) ExecutedAt() int64 { return p.executedAt }

// ExecutedHeight returns the block height recorded when the proposal was executed.
//
// Returns:
//   - int64: execution block height, or zero when none has been recorded
func (p *ProposalActionStatus) ExecutedHeight() int64 { return p.executedHeight }

// Executable reports whether this proposal type supports execution.
//
// Returns:
//   - bool: true when the proposal's action can be executed
func (p *ProposalActionStatus) Executable() bool { return p.executable }

/* Setter methods */
// SetCanceled records whether the proposal is canceled.
//
// Parameters:
//   - canceled: cancellation state to store
func (p *ProposalActionStatus) SetCanceled(canceled bool) {
	p.canceled = canceled
}

// SetCanceledAt records the timestamp associated with proposal cancellation.
//
// Parameters:
//   - canceledAt: cancellation timestamp to store
func (p *ProposalActionStatus) SetCanceledAt(canceledAt int64) {
	p.canceledAt = canceledAt
}

// SetCanceledHeight records the block height associated with proposal cancellation.
//
// Parameters:
//   - canceledHeight: cancellation block height to store
func (p *ProposalActionStatus) SetCanceledHeight(canceledHeight int64) {
	p.canceledHeight = canceledHeight
}

// SetCanceledBy records the address that canceled the proposal.
//
// Parameters:
//   - canceledBy: address of the actor that canceled the proposal
func (p *ProposalActionStatus) SetCanceledBy(canceledBy address) {
	p.canceledBy = canceledBy
}

// SetExecuted records whether the proposal is executed.
//
// Parameters:
//   - executed: execution state to store
func (p *ProposalActionStatus) SetExecuted(executed bool) {
	p.executed = executed
}

// SetExecutedAt records the timestamp associated with proposal execution.
//
// Parameters:
//   - executedAt: execution timestamp to store
func (p *ProposalActionStatus) SetExecutedAt(executedAt int64) {
	p.executedAt = executedAt
}

// SetExecutedHeight records the block height associated with proposal execution.
//
// Parameters:
//   - executedHeight: execution block height to store
func (p *ProposalActionStatus) SetExecutedHeight(executedHeight int64) {
	p.executedHeight = executedHeight
}

// SetExecutedBy records the address that executed the proposal.
//
// Parameters:
//   - executedBy: address of the actor that executed the proposal
func (p *ProposalActionStatus) SetExecutedBy(executedBy address) {
	p.executedBy = executedBy
}

// SetExecutable records whether this proposal type supports execution.
//
// Parameters:
//   - executable: execution capability to store for the proposal type
func (p *ProposalActionStatus) SetExecutable(executable bool) {
	p.executable = executable
}

// CanceledBy returns the address recorded as having canceled the proposal.
// The value is meaningful when Canceled() is true; before then it is the
// zero address unless a caller has explicitly stored another value.
//
// Returns:
//   - address: address recorded for the cancellation actor
func (p *ProposalActionStatus) CanceledBy() address {
	return p.canceledBy
}

// IsExecuted reports whether execution has been recorded for the proposal.
//
// Returns:
//   - bool: true when the proposal has been marked executed
func (p *ProposalActionStatus) IsExecuted() bool {
	return p.executed
}

// ExecutedBy returns the address recorded as having executed the proposal.
// The value is meaningful when IsExecuted() is true; before then it is the
// zero address unless a caller has explicitly stored another value.
//
// Returns:
//   - address: address recorded for the execution actor
func (p *ProposalActionStatus) ExecutedBy() address {
	return p.executedBy
}

// IsExecutable reports whether this proposal type can be executed.
//
// Returns:
//   - bool: true when execution is supported for the proposal type
func (p *ProposalActionStatus) IsExecutable() bool {
	return p.executable
}

// NewProposalActionStatus creates a new action status for a proposal.
// Initializes the status with default values and the executable flag.
//
// Parameters:
//   - executable: whether this proposal type can be executed
//
// Returns:
//   - *ProposalActionStatus: new action status instance
func NewProposalActionStatus(executable bool) *ProposalActionStatus {
	return &ProposalActionStatus{
		canceled:   false,      // Proposal starts as not canceled
		executed:   false,      // Proposal starts as not executed
		executable: executable, // Set based on proposal type
	}
}

// Clone creates a deep copy of the ProposalActionStatus, or nil when the
// receiver is nil.
//
// Returns:
//   - *ProposalActionStatus: independent copy of the status, or nil for a nil receiver
func (p *ProposalActionStatus) Clone() *ProposalActionStatus {
	if p == nil {
		return nil
	}

	return &ProposalActionStatus{
		canceled:       p.canceled,
		canceledAt:     p.canceledAt,
		canceledHeight: p.canceledHeight,
		canceledBy:     p.canceledBy,
		executed:       p.executed,
		executedAt:     p.executedAt,
		executedHeight: p.executedHeight,
		executedBy:     p.executedBy,
		executable:     p.executable,
	}
}

proposal_data.gno

package governance

import (
	"strings"
)

// ProposalMetadata contains descriptive information about a proposal.
// This includes the title and description that are displayed to voters.
type ProposalMetadata struct {
	title       string // Proposal title (max 255 characters)
	description string // Detailed proposal description (max 10,000 characters)
}

// Title returns the proposal title.
//
// Returns:
//   - string: proposal title
func (p *ProposalMetadata) Title() string {
	return p.title
}

// Description returns the proposal description.
//
// Returns:
//   - string: proposal description
func (p *ProposalMetadata) Description() string {
	return p.description
}

// NewProposalMetadata creates a new proposal metadata instance with trimmed input.
//
// Parameters:
//   - title: proposal title
//   - description: proposal description
//
// Returns:
//   - *ProposalMetadata: new metadata instance with trimmed whitespace
func NewProposalMetadata(title string, description string) *ProposalMetadata {
	return &ProposalMetadata{
		title:       strings.TrimSpace(title),
		description: strings.TrimSpace(description),
	}
}

// ProposalData contains the type-specific data for a proposal.
// This structure holds different data depending on the proposal type.
type ProposalData struct {
	proposalType       ProposalType            // Type of proposal (Text, CommunityPoolSpend, ParameterChange)
	communityPoolSpend *CommunityPoolSpendInfo // Data for community pool spending proposals
	execution          *ExecutionInfo          // Data for parameter change proposals
}

// ProposalType returns the type of this proposal.
//
// Returns:
//   - ProposalType: the proposal type
func (p *ProposalData) ProposalType() ProposalType {
	return p.proposalType
}

// CommunityPoolSpend returns the community pool spending information.
//
// Returns:
//   - *CommunityPoolSpendInfo: community pool spending details
func (p *ProposalData) CommunityPoolSpend() *CommunityPoolSpendInfo {
	return p.communityPoolSpend
}

// Execution returns the execution information for parameter changes.
//
// Returns:
//   - *ExecutionInfo: parameter change execution details
func (p *ProposalData) Execution() *ExecutionInfo {
	return p.execution
}

// NewProposalData creates a new proposal data instance with the specified components.
//
// Parameters:
//   - proposalType: type of the proposal
//   - communityPoolSpend: community pool spending information
//   - execution: parameter change execution information
//
// Returns:
//   - *ProposalData: new proposal data instance
func NewProposalData(proposalType ProposalType, communityPoolSpend *CommunityPoolSpendInfo, execution *ExecutionInfo) *ProposalData {
	return &ProposalData{
		proposalType:       proposalType,
		communityPoolSpend: communityPoolSpend,
		execution:          execution,
	}
}

// CommunityPoolSpendInfo contains information for community pool spending proposals.
type CommunityPoolSpendInfo struct {
	to        address // Recipient address for token transfer
	tokenPath string  // Path of the token to transfer
	amount    int64   // Amount of tokens to transfer
}

// NewCommunityPoolSpendInfo creates community-pool spend data.
//
// Parameters:
//   - to: Recipient address that receives the community-pool transfer.
//   - tokenPath: Registered token path of the asset to transfer.
//   - amount: Transfer amount in the token's smallest unit.
//
// Returns:
//   - *CommunityPoolSpendInfo: spend data containing the recipient, token path, and amount.
func NewCommunityPoolSpendInfo(to address, tokenPath string, amount int64) *CommunityPoolSpendInfo {
	return &CommunityPoolSpendInfo{
		to:        to,
		tokenPath: tokenPath,
		amount:    amount,
	}
}

/* Getter methods */
// Returns:
//   - address: recipient address configured for the community-pool spend.
//
func (i *CommunityPoolSpendInfo) To() address { return i.to }

// Returns:
//   - string: registered token path configured for the community-pool spend.
func (i *CommunityPoolSpendInfo) TokenPath() string { return i.tokenPath }

// Returns:
//   - int64: transfer amount in the token's smallest unit.
func (i *CommunityPoolSpendInfo) Amount() int64 { return i.amount }

// ExecutionInfo contains information for parameter change execution.
// Messages are encoded strings that specify function calls and parameters.
type ExecutionInfo struct {
	num  int64    // Number of parameter changes to execute
	msgs []string // Execution messages separated by messageSeparator (*GOV*)
}

// NewExecutionInfo creates execution data for a parameter-change proposal.
//
// Parameters:
//   - num: Number of encoded parameter-change messages to execute.
//   - msgs: Encoded parameter-change messages, one message per execution.
//
// Returns:
//   - *ExecutionInfo: execution data containing the declared count and messages.
func NewExecutionInfo(num int64, msgs []string) *ExecutionInfo {
	return &ExecutionInfo{
		num:  num,
		msgs: msgs,
	}
}

/* Getter methods */
// Returns:
//   - int64: declared number of parameter-change messages.
//
func (i *ExecutionInfo) Num() int64 { return i.num }

// Returns:
//   - []string: encoded parameter-change messages in execution order.
func (i *ExecutionInfo) Msgs() []string { return i.msgs }

// ParameterChangeInfo represents a single parameter change to be executed.
type ParameterChangeInfo struct {
	pkgPath  string   // Package path of the target contract
	function string   // Function name to call
	params   []string // Parameters to pass to the function
}

// NewParameterChangeInfo creates one encoded parameter-change target description.
//
// Parameters:
//   - pkgPath: Package path containing the parameter-change handler.
//   - function: Handler function name to invoke.
//   - params: String arguments passed to the handler in order.
//
// Returns:
//   - ParameterChangeInfo: parameter-change target and its encoded arguments.
func NewParameterChangeInfo(pkgPath string, function string, params []string) ParameterChangeInfo {
	return ParameterChangeInfo{
		pkgPath:  pkgPath,
		function: function,
		params:   params,
	}
}

/* Getter methods */
// Returns:
//   - string: package path of the parameter-change handler.
//
func (i *ParameterChangeInfo) PkgPath() string { return i.pkgPath }

// Returns:
//   - string: function name of the parameter-change handler.
func (i *ParameterChangeInfo) Function() string { return i.function }

// Returns:
//   - []string: encoded arguments passed to the parameter-change handler.
func (i *ParameterChangeInfo) Params() []string { return i.params }

// Clone creates a deep copy of the ProposalMetadata.
// Returns:
//   - *ProposalMetadata: independent metadata copy, or nil when the receiver is nil.
func (p *ProposalMetadata) Clone() *ProposalMetadata {
	if p == nil {
		return nil
	}

	return &ProposalMetadata{
		title:       p.title,
		description: p.description,
	}
}

// Clone creates a deep copy of the CommunityPoolSpendInfo.
// Returns:
//   - *CommunityPoolSpendInfo: independent spend-data copy, or nil when the receiver is nil.
func (i *CommunityPoolSpendInfo) Clone() *CommunityPoolSpendInfo {
	if i == nil {
		return nil
	}

	return &CommunityPoolSpendInfo{
		to:        i.to,
		tokenPath: i.tokenPath,
		amount:    i.amount,
	}
}

// Clone creates a deep copy of the ExecutionInfo.
// Returns:
//   - *ExecutionInfo: independent execution-data copy including a copied message slice, or nil when the receiver is nil.
func (i *ExecutionInfo) Clone() *ExecutionInfo {
	if i == nil {
		return nil
	}

	clonedMsgs := make([]string, len(i.msgs))
	copy(clonedMsgs, i.msgs)

	return &ExecutionInfo{
		num:  i.num,
		msgs: clonedMsgs,
	}
}

// Clone creates a deep copy of the ProposalData.
// Returns:
//   - *ProposalData: independent proposal-data copy with cloned nested values, or nil when the receiver is nil.
func (p *ProposalData) Clone() *ProposalData {
	if p == nil {
		return nil
	}

	return &ProposalData{
		proposalType:       p.proposalType,
		communityPoolSpend: p.communityPoolSpend.Clone(),
		execution:          p.execution.Clone(),
	}
}

proposal_schedule_status.gno

package governance

// ProposalScheduleStatus represents the pre-calculated time schedule for a proposal.
// This structure defines all the important timestamps in a proposal's lifecycle,
// from creation through voting to execution and expiration.
type ProposalScheduleStatus struct {
	createTime     int64 // When the proposal was created
	activeTime     int64 // When voting starts (CreateTime + VotingStartDelay)
	votingEndTime  int64 // When voting ends (ActiveTime + VotingPeriod)
	executableTime int64 // When execution window starts (VotingEndTime + ExecutionDelay)
	expiredTime    int64 // When execution window ends (ExecutableTime + ExecutionWindow)
}

// NewProposalScheduleStatus creates a proposal schedule from its lifecycle timestamps.
//
// Parameters:
//   - createTime: Unix timestamp when the proposal was created
//   - activeTime: Unix timestamp when voting starts
//   - votingEndTime: Unix timestamp when voting ends
//   - executableTime: Unix timestamp when the execution window starts
//   - expiredTime: Unix timestamp when the execution window closes
//
// Returns:
//   - *ProposalScheduleStatus: schedule containing the supplied lifecycle timestamps
func NewProposalScheduleStatus(
	createTime int64,
	activeTime int64,
	votingEndTime int64,
	executableTime int64,
	expiredTime int64,
) *ProposalScheduleStatus {
	return &ProposalScheduleStatus{
		createTime:     createTime,
		activeTime:     activeTime,
		votingEndTime:  votingEndTime,
		executableTime: executableTime,
		expiredTime:    expiredTime,
	}
}

/* Getter methods */
// CreateTime returns the Unix timestamp when the proposal was created.
//
// Returns:
//   - int64: proposal creation timestamp
func (p *ProposalScheduleStatus) CreateTime() int64 { return p.createTime }

// ActiveTime returns the Unix timestamp when proposal voting starts.
//
// Returns:
//   - int64: voting start timestamp
func (p *ProposalScheduleStatus) ActiveTime() int64 { return p.activeTime }

// VotingEndTime returns the Unix timestamp when proposal voting ends.
//
// Returns:
//   - int64: voting end timestamp
func (p *ProposalScheduleStatus) VotingEndTime() int64 { return p.votingEndTime }

// ExecutableTime returns the Unix timestamp when the execution window starts.
//
// Returns:
//   - int64: execution start timestamp
func (p *ProposalScheduleStatus) ExecutableTime() int64 { return p.executableTime }

// ExpiredTime returns the Unix timestamp when the execution window closes.
//
// Returns:
//   - int64: execution expiration timestamp
func (p *ProposalScheduleStatus) ExpiredTime() int64 { return p.expiredTime }

/* Setter methods */
// SetCreateTime updates the proposal creation timestamp.
//
// Parameters:
//   - createTime: Unix timestamp when the proposal was created
func (p *ProposalScheduleStatus) SetCreateTime(createTime int64) {
	p.createTime = createTime
}

// SetActiveTime updates the timestamp when proposal voting starts.
//
// Parameters:
//   - activeTime: Unix timestamp when voting starts
func (p *ProposalScheduleStatus) SetActiveTime(activeTime int64) {
	p.activeTime = activeTime
}

// SetVotingEndTime updates the timestamp when proposal voting ends.
//
// Parameters:
//   - votingEndTime: Unix timestamp when voting ends
func (p *ProposalScheduleStatus) SetVotingEndTime(votingEndTime int64) {
	p.votingEndTime = votingEndTime
}

// SetExecutableTime updates the timestamp when proposal execution can start.
//
// Parameters:
//   - executableTime: Unix timestamp when the execution window starts
func (p *ProposalScheduleStatus) SetExecutableTime(executableTime int64) {
	p.executableTime = executableTime
}

// SetExpiredTime updates the timestamp when proposal execution expires.
//
// Parameters:
//   - expiredTime: Unix timestamp when the execution window closes
func (p *ProposalScheduleStatus) SetExpiredTime(expiredTime int64) {
	p.expiredTime = expiredTime
}

// Clone creates a deep copy of the ProposalScheduleStatus.
//
// Returns:
//   - *ProposalScheduleStatus: copied schedule, or nil when the receiver is nil
func (p *ProposalScheduleStatus) Clone() *ProposalScheduleStatus {
	if p == nil {
		return nil
	}

	return &ProposalScheduleStatus{
		createTime:     p.createTime,
		activeTime:     p.activeTime,
		votingEndTime:  p.votingEndTime,
		executableTime: p.executableTime,
		expiredTime:    p.expiredTime,
	}
}

proposal_status.gno

package governance

// ProposalStatusType represents the current status of a proposal in its lifecycle.
// These statuses determine what actions are available for a proposal.
type ProposalStatusType int

const (
	_                ProposalStatusType = iota
	StatusUpcoming                      // Proposal created but voting hasn't started yet
	StatusActive                        // Proposal is in voting period
	StatusPassed                        // Proposal has passed but hasn't been executed (or is text proposal)
	StatusRejected                      // Proposal failed to meet voting requirements
	StatusExecutable                    // Proposal can be executed (passed and in execution window)
	StatusExecuted                      // Proposal has been successfully executed
	StatusExpired                       // Proposal execution window has passed
	StatusCanceled                      // Proposal has been canceled
)

// String returns the string representation of ProposalStatusType for display purposes.
//
// Returns:
//   - string: lowercase status name, or "unknown" for an unrecognized value
func (s ProposalStatusType) String() string {
	switch s {
	case StatusUpcoming:
		return "upcoming"
	case StatusActive:
		return "active"
	case StatusPassed:
		return "passed"
	case StatusRejected:
		return "rejected"
	case StatusExecutable:
		return "executable"
	case StatusExecuted:
		return "executed"
	case StatusExpired:
		return "expired"
	case StatusCanceled:
		return "canceled"
	default:
		return "unknown"
	}
}

// ProposalStatus manages the complete status of a proposal including scheduling, voting, and actions.
// This is the central status tracking structure that coordinates different aspects of proposal state.
type ProposalStatus struct {
	schedule     *ProposalScheduleStatus // Time-based scheduling information
	actionStatus *ProposalActionStatus   // Execution and cancellation status
	voteStatus   *ProposalVoteStatus     // Voting tallies and requirements
}

// NewProposalStatusBy combines schedule, action, and vote state into a proposal status.
//
// Parameters:
//   - schedule: time-based lifecycle schedule for the proposal
//   - actionStatus: execution and cancellation state for the proposal
//   - voteStatus: vote tallies and voting requirements for the proposal
//
// Returns:
//   - *ProposalStatus: status object containing the supplied lifecycle components
func NewProposalStatusBy(
	schedule *ProposalScheduleStatus,
	actionStatus *ProposalActionStatus,
	voteStatus *ProposalVoteStatus,
) *ProposalStatus {
	return &ProposalStatus{
		schedule:     schedule,
		actionStatus: actionStatus,
		voteStatus:   voteStatus,
	}
}

/* Getter methods */
// Schedule returns the proposal's time-based scheduling state.
//
// Returns:
//   - *ProposalScheduleStatus: schedule containing proposal lifecycle timestamps
func (s *ProposalStatus) Schedule() *ProposalScheduleStatus { return s.schedule }

// ActionStatus returns the proposal's execution and cancellation state.
//
// Returns:
//   - *ProposalActionStatus: action state associated with the proposal
func (s *ProposalStatus) ActionStatus() *ProposalActionStatus { return s.actionStatus }

// VoteStatus returns the proposal's vote tallies and voting requirements.
//
// Returns:
//   - *ProposalVoteStatus: vote state associated with the proposal
func (s *ProposalStatus) VoteStatus() *ProposalVoteStatus { return s.voteStatus }

/* Delegation getters for vote data */

// YesWeight returns the total weight of "yes" votes.
//
// Returns:
//   - int64: total "yes" vote weight
func (s *ProposalStatus) YesWeight() int64 {
	return s.voteStatus.YesWeight()
}

// NoWeight returns the total weight of "no" votes.
//
// Returns:
//   - int64: total "no" vote weight
func (s *ProposalStatus) NoWeight() int64 {
	return s.voteStatus.NoWeight()
}

// Clone creates a deep copy of the ProposalStatus, or nil when the
// receiver is nil.
//
// Returns:
//   - *ProposalStatus: independent copy of the status, or nil for a nil receiver
func (s *ProposalStatus) Clone() *ProposalStatus {
	if s == nil {
		return nil
	}

	return &ProposalStatus{
		schedule:     s.schedule.Clone(),
		actionStatus: s.actionStatus.Clone(),
		voteStatus:   s.voteStatus.Clone(),
	}
}

proposal_type.gno

package governance

// ProposalType defines the different types of proposals supported by the governance system.
// Each type has different execution behavior and validation requirements.
type ProposalType string

const (
	Text               ProposalType = "TEXT"                 // Informational proposals for community discussion
	CommunityPoolSpend ProposalType = "COMMUNITY_POOL_SPEND" // Proposals to spend community pool funds
	ParameterChange    ProposalType = "PARAMETER_CHANGE"     // Proposals to modify system parameters
)

// String returns the human-readable string representation of the proposal type.
//
// Returns:
//   - string: "Text", "CommunityPoolSpend", or "ParameterChange" for a known type; "Unknown" otherwise
func (p ProposalType) String() string {
	switch p {
	case Text:
		return "Text"
	case CommunityPoolSpend:
		return "CommunityPoolSpend"
	case ParameterChange:
		return "ParameterChange"
	default:
		return "Unknown"
	}
}

// IsExecutable determines whether this proposal type can be executed.
// Text proposals are informational only and cannot be executed.
//
// Returns:
//   - bool: true for executable CommunityPoolSpend or ParameterChange types; false for Text and unknown types
func (p ProposalType) IsExecutable() bool {
	switch p {
	case Text:
		return false
	case CommunityPoolSpend, ParameterChange:
		return true
	default:
		return false
	}
}

proposal_vote_status.gno

package governance

// ProposalVoteStatus tracks the voting tallies and requirements for a proposal.
// This structure manages vote counting, quorum calculation, and voting outcome determination.
type ProposalVoteStatus struct {
	yea             int64 // Total weight of "yes" votes collected
	nay             int64 // Total weight of "no" votes collected
	maxVotingWeight int64 // The max voting weight at the time of proposal creation
	quorumAmount    int64 // How many total votes must be collected for the proposal to be valid
}

/* Getter methods */
// MaxVotingWeight returns the maximum voting weight captured for the proposal.
//
// Returns:
//   - int64: maximum voting weight used when evaluating the proposal's quorum.
func (p *ProposalVoteStatus) MaxVotingWeight() int64 { return p.maxVotingWeight }

// QuorumAmount returns the voting weight required for the proposal to satisfy quorum.
//
// Returns:
//   - int64: minimum total vote weight required by this proposal.
func (p *ProposalVoteStatus) QuorumAmount() int64 { return p.quorumAmount }

// YesWeight returns the total weight of "yes" votes.
//
// Returns:
//   - int64: total "yes" vote weight
func (p *ProposalVoteStatus) YesWeight() int64 {
	return p.yea
}

// NoWeight returns the total weight of "no" votes.
//
// Returns:
//   - int64: total "no" vote weight
func (p *ProposalVoteStatus) NoWeight() int64 {
	return p.nay
}

/* Setter methods */
// SetYesWeight replaces the proposal's accumulated yes-vote weight.
//
// Parameters:
//   - yes: total weight to record for affirmative votes.
func (p *ProposalVoteStatus) SetYesWeight(yes int64) {
	p.yea = yes
}

// SetNoWeight replaces the proposal's accumulated no-vote weight.
//
// Parameters:
//   - no: total weight to record for negative votes.
func (p *ProposalVoteStatus) SetNoWeight(no int64) {
	p.nay = no
}

// SetMaxVotingWeight records the proposal's maximum voting-weight snapshot.
//
// Parameters:
//   - maxVotingWeight: maximum voting weight available when the proposal was created.
func (p *ProposalVoteStatus) SetMaxVotingWeight(maxVotingWeight int64) {
	p.maxVotingWeight = maxVotingWeight
}

// SetQuorumAmount records the proposal's quorum requirement.
//
// Parameters:
//   - quorumAmount: minimum total vote weight required for this proposal.
func (p *ProposalVoteStatus) SetQuorumAmount(quorumAmount int64) {
	p.quorumAmount = quorumAmount
}

// NewProposalVoteStatus creates a new vote status for a proposal.
// Initializes vote tallies to zero and calculates the quorum requirement.
//
// Parameters:
//   - maxVotingWeight: maximum possible voting weight for this proposal
//   - quorumAmount: quorum amount required for passage
//
// Returns:
//   - *ProposalVoteStatus: new vote status instance
func NewProposalVoteStatus(
	maxVotingWeight int64,
	quorumAmount int64,
) *ProposalVoteStatus {
	return &ProposalVoteStatus{
		yea:             0,               // Start with no "yes" votes
		nay:             0,               // Start with no "no" votes
		maxVotingWeight: maxVotingWeight, // Set maximum possible votes
		quorumAmount:    quorumAmount,    // Set required votes for passage
	}
}

// Clone returns an independent copy of the vote status, or nil when the receiver is nil.
//
// Returns:
//   - *ProposalVoteStatus: copied vote tallies and requirements, or nil for a nil receiver.
func (p *ProposalVoteStatus) Clone() *ProposalVoteStatus {
	if p == nil {
		return nil
	}

	return &ProposalVoteStatus{
		yea:             p.yea,
		nay:             p.nay,
		maxVotingWeight: p.maxVotingWeight,
		quorumAmount:    p.quorumAmount,
	}
}

proxy.gno

package governance

// ProposeText creates a new text proposal with the provided data.
//
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - title: The title of the proposal.
//   - description: The description of the proposal.
//
// Returns:
//   - proposalId: The ID of the proposal.
//
// Halt check: reverts while the Governance halt scope is active.
func ProposeText(
	cur realm,
	title string,
	description string,
) int64 {
	return getImplementation().ProposeText(
		0, cur,
		title,
		description,
	)
}

// ProposeCommunityPoolSpend creates a CommunityPoolSpend proposal with the provided data.
// The transfer is attempted when an approved proposal executes.
//
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - title: The title of the proposal.
//   - description: The description of the proposal.
//   - to: A valid address to receive the spent token.
//   - tokenPath: A registered token path.
//   - amount: A strictly positive amount in the token's smallest unit.
//
// The community-pool balance is checked at execution, not proposal creation.
//
// Returns:
//   - proposalId: The ID of the proposal.
//
// Halt check: reverts while the Governance halt scope is active.
func ProposeCommunityPoolSpend(
	cur realm,
	title string,
	description string,
	to address,
	tokenPath string,
	amount int64,
) int64 {
	return getImplementation().ProposeCommunityPoolSpend(
		0, cur,
		title,
		description,
		to,
		tokenPath,
		amount,
	)
}

// ProposeParameterChange creates a ParameterChange proposal with the provided data.
//
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - title: The title of the proposal.
//   - description: The description of the proposal.
//   - numToExecute: The number of changes to execute.
//   - executions: The list of changes to execute.
//
// Returns:
//   - proposalId: The ID of the proposal.
//
// Halt check: reverts while the Governance halt scope is active, except for halt-recovery proposals that only target the halt realm.
func ProposeParameterChange(
	cur realm,
	title string,
	description string,
	numToExecute int64,
	executions string,
) int64 {
	return getImplementation().ProposeParameterChange(
		0, cur,
		title,
		description,
		numToExecute,
		executions,
	)
}

// Vote allows a user to vote on a given proposal.
//
// The proposal's timestamp-based smoothing calculation determines the applied
// weight. A vote cannot be changed after it is recorded.
//
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - proposalId: The ID of the proposal to vote.
//   - yes: The flag to vote as yes or not.
//
// Returns:
//   - voteWeight: The caller's calculated vote weight, formatted as a decimal string.
//
// Halt check: reverts while the Governance halt scope is active, except for halt-recovery proposals that only target the halt realm.
func Vote(
	cur realm,
	proposalId int64,
	yes bool,
) string {
	return getImplementation().Vote(
		0, cur,
		proposalId,
		yes,
	)
}

// Execute executes the given proposal.
//
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - proposalId: The ID of the proposal to execute.
//
// Returns:
//   - proposalId: The ID of the proposal.
//
// Halt check: reverts while the Governance halt scope is active, except for halt-recovery proposals that only target the halt realm.
func Execute(
	cur realm,
	proposalId int64,
) int64 {
	return getImplementation().Execute(0, cur, proposalId)
}

// Cancel cancels the proposal with the given ID.
//
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - proposalId: The ID of the proposal to cancel.
//
// Returns:
//   - proposalId: The ID of the proposal.
//
// Halt check: reverts while the Governance halt scope is active.
func Cancel(
	cur realm,
	proposalId int64,
) int64 {
	return getImplementation().Cancel(0, cur, proposalId)
}

// RemoveInactiveProposalFromIndex removes an inactive proposal from the
// timestamp-ordered index without deleting its proposal or voting history.
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - proposalID: Identifier of the inactive proposal to remove from the active index.
//
// Halt check: reverts while the Governance halt scope is active.
func RemoveInactiveProposalFromIndex(cur realm, proposalID int64) {
	getImplementation().RemoveInactiveProposalFromIndex(0, cur, proposalID)
}

// Reconfigure updates the governance configuration parameters.
// Only callable by admin or governance.
//
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - votingStartDelay: delay before voting starts (seconds)
//   - votingPeriod: voting duration (seconds)
//   - votingWeightSmoothingDuration: weight smoothing duration (seconds)
//   - quorum: minimum voting weight required (percentage)
//   - proposalCreationThreshold: minimum weight to create proposal
//   - executionDelay: delay before execution (seconds)
//   - executionWindow: execution time window (seconds)
//
// Returns:
//   - int64: new configuration version
//
// Halt check: reverts while the Governance halt scope is active.
func Reconfigure(
	cur realm,
	votingStartDelay int64,
	votingPeriod int64,
	votingWeightSmoothingDuration int64,
	quorum int64,
	proposalCreationThreshold int64,
	executionDelay int64,
	executionWindow int64,
) int64 {
	return getImplementation().Reconfigure(
		0, cur,
		votingStartDelay,
		votingPeriod,
		votingWeightSmoothingDuration,
		quorum,
		proposalCreationThreshold,
		executionDelay,
		executionWindow,
	)
}

render.gno

package governance

// Render delegates web rendering to the active implementation.
func Render(path string) string {
	return getImplementation().Render(path)
}

state.gno

package governance

import (
	"errors"

	_ "gno.land/r/gnoswap/rbac/v1" // initialize readable contract role(s)

	"gno.land/p/gnoswap/store/v1"
	"gno.land/p/gnoswap/version_manager/v1"
)

const ErrSpoofedRealm = "rlm does not match the current crossing frame"

var (
	// currentAddress and domainPath describe the governance realm itself.
	// They are captured from the `cur realm` parameter in init(cur realm),
	// which resolves to this governance domain realm.
	currentAddress address
	domainPath     string

	kvStore store.KVStore

	versionManager version_manager.VersionManager
	implementation IGovernance
)

func init(cur realm) {
	currentAddress = cur.Address()
	domainPath = cur.PkgPath()

	kvStore = store.NewKVStore(currentAddress)
	versionManager = version_manager.NewVersionManager(domainPath, kvStore, initializeDomainStore)

	implementation = nil
}

func initializeDomainStore(_ int, rlm realm, kvStore store.KVStore) any {
	return NewGovernanceStore(kvStore)
}

func getImplementation() IGovernance {
	if implementation == nil {
		panic("implementation is not initialized")
	}

	return implementation
}

func updateImplementation() error {
	result := versionManager.GetCurrentImplementation()
	if result == nil {
		return errors.New("implementation is not initialized")
	}

	impl, ok := result.(IGovernance)
	if !ok {
		return errors.New("impl is not an IGovernance")
	}

	implementation = impl

	return nil
}

store.gno

package governance

import (
	"errors"
	"strconv"

	"gno.land/p/gnoswap/store/v1"
	bptree "gno.land/p/nt/bptree/v0"
	ufmt "gno.land/p/nt/ufmt/v0"
)

type StoreKey string

// String returns the storage-key text represented by s.
//
// Returns:
//   - string: underlying string used as the KV-store key
func (s StoreKey) String() string {
	return string(s)
}

const (
	StoreKeyConfigCounter   StoreKey = "configCounter"   // Config version counter
	StoreKeyProposalCounter StoreKey = "proposalCounter" // Proposal ID counter

	StoreKeyConfigs StoreKey = "configs" // Configurations BPTree

	StoreKeyProposals StoreKey = "proposals" // Proposals BPTree

	StoreKeyActiveProposalsBySnapshot StoreKey = "activeProposalsBySnapshot"

	StoreKeyProposalUserVotingInfos StoreKey = "proposalUserVotingInfos" // Proposal voting infos BPTree

	StoreKeyUserProposals StoreKey = "userProposals" // User proposals mapping BPTree
)

type governanceStore struct {
	kvStore store.KVStore
}

// Counter methods
// HasConfigCounterStoreKey reports whether the configuration-version counter
// is present in the KV store.
//
// Returns:
//   - bool: true when the configuration counter storage key exists
func (s *governanceStore) HasConfigCounterStoreKey() bool {
	return s.kvStore.Has(StoreKeyConfigCounter.String())
}

// GetConfigCounter retrieves the persisted configuration-version counter.
// Storage or type-cast failures panic.
//
// Returns:
//   - *Counter: counter stored under the configuration counter key
func (s *governanceStore) GetConfigCounter() *Counter {
	result, err := s.kvStore.Get(StoreKeyConfigCounter.String())
	if err != nil {
		panic(err)
	}

	counter, ok := result.(*Counter)
	if !ok {
		panic(ufmt.Sprintf("failed to cast result to *Counter: %T", result))
	}

	return counter
}

// SetConfigCounter persists the configuration-version counter after checking
// the supplied realm context.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - counter: counter value to persist under the configuration counter key
//
// Returns:
//   - error: nil when the counter is persisted; ErrSpoofedRealm or the KV-store write error otherwise
func (s *governanceStore) SetConfigCounter(_ int, rlm realm, counter *Counter) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	return s.kvStore.Set(0, rlm, StoreKeyConfigCounter.String(), counter)
}

// HasProposalCounterStoreKey reports whether the proposal-ID counter is
// present in the KV store.
//
// Returns:
//   - bool: true when the proposal counter storage key exists
func (s *governanceStore) HasProposalCounterStoreKey() bool {
	return s.kvStore.Has(StoreKeyProposalCounter.String())
}

// GetProposalCounter retrieves the persisted proposal-ID counter.
// Storage or type-cast failures panic.
//
// Returns:
//   - *Counter: counter stored under the proposal counter key
func (s *governanceStore) GetProposalCounter() *Counter {
	result, err := s.kvStore.Get(StoreKeyProposalCounter.String())
	if err != nil {
		panic(err)
	}

	counter, ok := result.(*Counter)
	if !ok {
		panic(ufmt.Sprintf("failed to cast result to int64: %T", result))
	}

	return counter
}

// SetProposalCounter persists the proposal-ID counter after checking the
// supplied realm context.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - counter: counter value to persist under the proposal counter key
//
// Returns:
//   - error: nil when the counter is persisted; ErrSpoofedRealm or the KV-store write error otherwise
func (s *governanceStore) SetProposalCounter(_ int, rlm realm, counter *Counter) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	return s.kvStore.Set(0, rlm, StoreKeyProposalCounter.String(), counter)
}

// Configs methods
// HasConfigsStoreKey reports whether the configurations tree is present in the
// KV store.
//
// Returns:
//   - bool: true when the configurations storage key exists
func (s *governanceStore) HasConfigsStoreKey() bool {
	return s.kvStore.Has(StoreKeyConfigs.String())
}

// GetConfigs retrieves the persisted configurations tree.
// Storage or type-cast failures panic.
//
// Returns:
//   - *bptree.BPTree: tree containing governance configurations keyed by version
func (s *governanceStore) GetConfigs() *bptree.BPTree {
	result, err := s.kvStore.Get(StoreKeyConfigs.String())
	if err != nil {
		panic(err)
	}

	configs, ok := result.(*bptree.BPTree)
	if !ok {
		panic(ufmt.Sprintf("failed to cast result to *bptree.BPTree: %T", result))
	}

	return configs
}

// SetConfigs persists the configurations tree after checking the supplied
// realm context.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - configs: configurations tree to persist
//
// Returns:
//   - error: nil when the tree is persisted; ErrSpoofedRealm or the KV-store write error otherwise
func (s *governanceStore) SetConfigs(_ int, rlm realm, configs *bptree.BPTree) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	return s.kvStore.Set(0, rlm, StoreKeyConfigs.String(), configs)
}

// GetConfig retrieves one governance configuration by version.
// A missing version returns the zero Config and false.
//
// Parameters:
//   - version: configuration version used to form the tree key
//
// Returns:
//   - Config: configuration stored for version, or zero Config when absent
//   - bool: true when version was found; false when no configuration is stored
func (s *governanceStore) GetConfig(version int64) (Config, bool) {
	configs := s.GetConfigs()
	result := configs.Get(formatInt64Key(version))
	if result == nil {
		return Config{}, false
	}

	config, ok := result.(Config)
	if !ok {
		panic(ufmt.Sprintf("failed to cast result to Config: %T", result))
	}

	return config, true
}

// SetConfig stores config under version after checking the supplied realm
// context and the configurations storage key.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - version: configuration version used as the tree key
//   - config: configuration value to store for version
//
// Returns:
//   - error: nil when config is stored; an authorization, missing-key, or KV-store error otherwise
func (s *governanceStore) SetConfig(_ int, rlm realm, version int64, config Config) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	if !s.HasConfigsStoreKey() {
		return errors.New("configs store key not found")
	}

	configs := s.GetConfigs()
	configs.Set(formatInt64Key(version), config)

	return s.kvStore.Set(0, rlm, StoreKeyConfigs.String(), configs)
}

// Proposals methods
// HasProposalsStoreKey reports whether the proposals tree is present in the KV
// store.
//
// Returns:
//   - bool: true when the proposals storage key exists
func (s *governanceStore) HasProposalsStoreKey() bool {
	return s.kvStore.Has(StoreKeyProposals.String())
}

// GetProposals retrieves the persisted proposals tree.
// Storage or type-cast failures panic.
//
// Returns:
//   - *bptree.BPTree: tree containing proposals keyed by formatted proposal ID
func (s *governanceStore) GetProposals() *bptree.BPTree {
	result, err := s.kvStore.Get(StoreKeyProposals.String())
	if err != nil {
		panic(err)
	}

	proposals, ok := result.(*bptree.BPTree)
	if !ok {
		panic(ufmt.Sprintf("failed to cast result to *bptree.BPTree: %T", result))
	}

	return proposals
}

// SetProposals persists the proposals tree after checking the supplied realm
// context.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - proposals: proposals tree to persist
//
// Returns:
//   - error: nil when the tree is persisted; ErrSpoofedRealm or the KV-store write error otherwise
func (s *governanceStore) SetProposals(_ int, rlm realm, proposals *bptree.BPTree) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	return s.kvStore.Set(0, rlm, StoreKeyProposals.String(), proposals)
}

// GetProposal retrieves a proposal by its identifier.
// A missing entry or a value of the wrong type returns nil and false.
//
// Parameters:
//   - proposalID: proposal identifier used to form the tree key
//
// Returns:
//   - *Proposal: stored proposal, or nil when absent or not a Proposal
//   - bool: true when a Proposal was found at proposalID
func (s *governanceStore) GetProposal(proposalID int64) (*Proposal, bool) {
	proposals := s.GetProposals()
	result := proposals.Get(formatInt64Key(proposalID))
	if result == nil {
		return nil, false
	}

	proposal, ok := result.(*Proposal)
	if !ok {
		return nil, false
	}
	return proposal, true
}

// SetProposal stores proposal under proposalID after checking realm
// authorization, storage initialization, and ID consistency.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - proposalID: storage identifier that must equal proposal.ID()
//   - proposal: proposal value to persist; nil or an ID mismatch returns an error
//
// Returns:
//   - error: nil when stored; an authorization, missing-key, ID-mismatch, or KV-store error otherwise
func (s *governanceStore) SetProposal(_ int, rlm realm, proposalID int64, proposal *Proposal) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	if !s.HasProposalsStoreKey() {
		return errors.New("proposals store key not found")
	}

	if proposal == nil || proposal.ID() != proposalID {
		return errors.New("proposal ID does not match the storage key")
	}

	proposals := s.GetProposals()
	proposals.Set(formatInt64Key(proposalID), proposal)

	return s.kvStore.Set(0, rlm, StoreKeyProposals.String(), proposals)
}

// HasActiveProposalsBySnapshotStoreKey reports whether the active-proposal
// snapshot index is present in the KV store.
//
// Returns:
//   - bool: true when the active snapshot index storage key exists
func (s *governanceStore) HasActiveProposalsBySnapshotStoreKey() bool {
	return s.kvStore.Has(StoreKeyActiveProposalsBySnapshot.String())
}

// GetActiveProposalsBySnapshot retrieves the active-proposal snapshot index.
// Storage or type-cast failures panic.
//
// Returns:
//   - *bptree.BPTree: tree indexing active proposals by snapshot key
func (s *governanceStore) GetActiveProposalsBySnapshot() *bptree.BPTree {
	result, err := s.kvStore.Get(StoreKeyActiveProposalsBySnapshot.String())
	if err != nil {
		panic(err)
	}
	tree, ok := result.(*bptree.BPTree)
	if !ok {
		panic(ufmt.Sprintf("failed to cast active proposal snapshot index: %T", result))
	}
	return tree
}

// SetActiveProposalsBySnapshot persists the active-proposal snapshot index
// after checking the supplied realm context.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - tree: active-proposal snapshot index tree to persist
//
// Returns:
//   - error: nil when the index is persisted; ErrSpoofedRealm or the KV-store write error otherwise
func (s *governanceStore) SetActiveProposalsBySnapshot(_ int, rlm realm, tree *bptree.BPTree) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}
	return s.kvStore.Set(0, rlm, StoreKeyActiveProposalsBySnapshot.String(), tree)
}

// Proposal User Voting Infos methods
// HasProposalUserVotingInfosStoreKey reports whether the proposal voting-info
// index is present in the KV store.
//
// Returns:
//   - bool: true when the proposal voting-info storage key exists
func (s *governanceStore) HasProposalUserVotingInfosStoreKey() bool {
	return s.kvStore.Has(StoreKeyProposalUserVotingInfos.String())
}

// GetProposalUserVotingInfos retrieves the persisted proposal voting-info
// index tree. Storage or type-cast failures panic.
//
// Returns:
//   - *bptree.BPTree: tree mapping proposal IDs to per-user voting-info trees
func (s *governanceStore) GetProposalUserVotingInfos() *bptree.BPTree {
	result, err := s.kvStore.Get(StoreKeyProposalUserVotingInfos.String())
	if err != nil {
		panic(err)
	}

	votingInfos, ok := result.(*bptree.BPTree)
	if !ok {
		panic(ufmt.Sprintf("failed to cast result to *bptree.BPTree: %T", result))
	}

	return votingInfos
}

// SetProposalUserVotingInfos persists the proposal voting-info index after
// checking the supplied realm context.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - votingInfos: proposal voting-info index tree to persist
//
// Returns:
//   - error: nil when the index is persisted; ErrSpoofedRealm or the KV-store write error otherwise
func (s *governanceStore) SetProposalUserVotingInfos(_ int, rlm realm, votingInfos *bptree.BPTree) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	return s.kvStore.Set(0, rlm, StoreKeyProposalUserVotingInfos.String(), votingInfos)
}

// GetProposalVotingInfos retrieves the per-user voting-info tree for a
// proposal. A missing entry or wrong type returns nil and false.
//
// Parameters:
//   - proposalID: proposal identifier used to select its voting-info tree
//
// Returns:
//   - *bptree.BPTree: per-user voting-info tree for proposalID, or nil when absent or invalid
//   - bool: true when a correctly typed voting-info tree was found
func (s *governanceStore) GetProposalVotingInfos(proposalID int64) (*bptree.BPTree, bool) {
	votingInfos := s.GetProposalUserVotingInfos()
	votingInfo := votingInfos.Get(formatInt64Key(proposalID))
	if votingInfo == nil {
		return nil, false
	}

	votingInfoTree, ok := votingInfo.(*bptree.BPTree)
	if !ok {
		return nil, false
	}

	return votingInfoTree, true
}

// SetProposalVotingInfos stores votingInfos under proposalID after checking
// realm authorization and index initialization.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - proposalID: proposal identifier used as the nested tree key
//   - votingInfos: per-user voting-info tree to store for proposalID
//
// Returns:
//   - error: nil when stored; an authorization, missing-key, or KV-store error otherwise
func (s *governanceStore) SetProposalVotingInfos(_ int, rlm realm, proposalID int64, votingInfos *bptree.BPTree) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	if !s.HasProposalUserVotingInfosStoreKey() {
		return errors.New("proposal user voting infos store key not found")
	}

	allVotingInfos := s.GetProposalUserVotingInfos()
	allVotingInfos.Set(formatInt64Key(proposalID), votingInfos)

	return s.kvStore.Set(0, rlm, StoreKeyProposalUserVotingInfos.String(), allVotingInfos)
}

// User Proposals methods
// HasUserProposalsStoreKey reports whether the user-to-proposals index is
// present in the KV store.
//
// Returns:
//   - bool: true when the user proposals storage key exists
func (s *governanceStore) HasUserProposalsStoreKey() bool {
	return s.kvStore.Has(StoreKeyUserProposals.String())
}

// GetUserProposals retrieves the persisted user-to-proposals index.
// Storage or type-cast failures panic.
//
// Returns:
//   - *bptree.BPTree: tree mapping user strings to proposal ID slices
func (s *governanceStore) GetUserProposals() *bptree.BPTree {
	result, err := s.kvStore.Get(StoreKeyUserProposals.String())
	if err != nil {
		panic(err)
	}

	userProposals, ok := result.(*bptree.BPTree)
	if !ok {
		panic(ufmt.Sprintf("failed to cast result to *bptree.BPTree: %T", result))
	}

	return userProposals
}

// SetUserProposals persists the user-to-proposals index after checking the
// supplied realm context.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - userProposals: user-to-proposals index tree to persist
//
// Returns:
//   - error: nil when the index is persisted; ErrSpoofedRealm or the KV-store write error otherwise
func (s *governanceStore) SetUserProposals(_ int, rlm realm, userProposals *bptree.BPTree) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	return s.kvStore.Set(0, rlm, StoreKeyUserProposals.String(), userProposals)
}

// GetUserProposalIDs retrieves the proposal IDs indexed for user.
// A missing user returns nil and false; a wrong stored type panics.
//
// Parameters:
//   - user: user-string key in the user-to-proposals index
//
// Returns:
//   - []int64: proposal IDs currently indexed for user
//   - bool: true when user has an index entry; false when user is absent
func (s *governanceStore) GetUserProposalIDs(user string) ([]int64, bool) {
	userProposals := s.GetUserProposals()
	result := userProposals.Get(user)
	if result == nil {
		return nil, false
	}

	proposalIDs, ok := result.([]int64)
	if !ok {
		panic(ufmt.Sprintf("failed to cast result to []int64: %T", result))
	}

	return proposalIDs, true
}

// AddUserProposal appends proposalID to the IDs indexed for user and persists
// the updated user-to-proposals tree.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - user: user-string key whose proposal list is updated
//   - proposalID: proposal identifier to append to user's list
//
// Returns:
//   - error: nil when the list is persisted; an authorization, missing-key, or KV-store error otherwise
func (s *governanceStore) AddUserProposal(_ int, rlm realm, user string, proposalID int64) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	if !s.HasUserProposalsStoreKey() {
		return errors.New("user proposals store key not found")
	}

	userProposals := s.GetUserProposals()

	// Get existing proposals for user
	var proposalIDs []int64
	if existing := userProposals.Get(user); existing != nil {
		var ok bool
		proposalIDs, ok = existing.([]int64)
		if !ok {
			panic(ufmt.Sprintf("failed to cast result to []int64: %T", existing))
		}
	}

	// Add new proposal ID
	proposalIDs = append(proposalIDs, proposalID)
	userProposals.Set(user, proposalIDs)

	return s.kvStore.Set(0, rlm, StoreKeyUserProposals.String(), userProposals)
}

// RemoveUserProposal removes every occurrence of proposalID from user's
// indexed proposal IDs and persists the resulting tree. Missing users are a
// no-op.
//
// Parameters:
//   - _: leading integer discriminator for the authorized store call; callers pass 0
//   - rlm: propagated realm context; it must satisfy rlm.IsCurrent() or ErrSpoofedRealm is returned
//   - user: user-string key whose proposal list is updated
//   - proposalID: proposal identifier to remove from the user's list
//
// Returns:
//   - error: nil when removed or already absent; an authorization, missing-key, or KV-store error otherwise
func (s *governanceStore) RemoveUserProposal(_ int, rlm realm, user string, proposalID int64) error {
	if !rlm.IsCurrent() {
		return errors.New(ErrSpoofedRealm)
	}

	if !s.HasUserProposalsStoreKey() {
		return errors.New("user proposals store key not found")
	}

	userProposals := s.GetUserProposals()
	proposalIDsRaw := userProposals.Get(user)
	// proposal already removed
	if proposalIDsRaw == nil {
		return nil
	}

	proposalIDs, ok := proposalIDsRaw.([]int64)
	if !ok {
		panic(ufmt.Sprintf("failed to cast result to []int64: %T", proposalIDs))
	}

	newProposalIDs := make([]int64, 0)

	for _, id := range proposalIDs {
		if id != proposalID {
			newProposalIDs = append(newProposalIDs, id)
		}
	}

	if len(newProposalIDs) == 0 {
		userProposals.Remove(user)
	} else {
		userProposals.Set(user, newProposalIDs)
	}

	return s.kvStore.Set(0, rlm, StoreKeyUserProposals.String(), userProposals)
}

// NewGovernanceStore creates a governance store backed by the provided KV store.
// The returned interface is used by governance implementations and upgrades.
//
// Parameters:
//   - kvStore: KV store used for governance counters, trees, and records
//
// Returns:
//   - IGovernanceStore: governance store implementation backed by kvStore
func NewGovernanceStore(kvStore store.KVStore) IGovernanceStore {
	return &governanceStore{
		kvStore: kvStore,
	}
}

// formatInt64Key formats int64 identifiers for storage keys.
func formatInt64Key(id int64) string {
	return strconv.FormatInt(id, 10)
}

types.gno

package governance

import (
	rotree "gno.land/p/nt/bptree/rotree/v0"
	bptree "gno.land/p/nt/bptree/v0"
)

type IGovernance interface {
	IGovernanceManager
	IGovernanceGetter
	Render(path string) string
}

type IGovernanceManager interface {
	// Proposal management
	// ProposeText creates a non-executable proposal for community discussion.
	//
	// Parameters:
	//   - _: Noncrossing implementation-call discriminator; pass 0.
	//   - rlm: Current realm context forwarded unchanged by the governance proxy.
	//   - title: short, non-empty title describing the proposal.
	//   - description: non-empty proposal rationale and discussion text.
	//
	// Returns:
	//   - int64: ID assigned to the newly created text proposal.
	ProposeText(
		_ int, rlm realm,
		title string,
		description string,
	) int64

	// ProposeCommunityPoolSpend creates a proposal to transfer registered tokens from the community pool.
	//
	// Parameters:
	//   - _: Noncrossing implementation-call discriminator; pass 0.
	//   - rlm: Current realm context forwarded unchanged by the governance proxy.
	//   - title: short title describing the requested disbursement.
	//   - description: rationale and budget details for the disbursement.
	//   - to: recipient address for the community-pool transfer.
	//   - tokenPath: registered token realm path to transfer.
	//   - amount: positive transfer amount in the token's smallest unit.
	//
	// Returns:
	//   - int64: ID assigned to the newly created community-pool-spend proposal.
	ProposeCommunityPoolSpend(
		_ int, rlm realm,
		title string,
		description string,
		to address,
		tokenPath string,
		amount int64,
	) int64

	// ProposeParameterChange creates a proposal containing registered parameter-handler executions.
	//
	// Parameters:
	//   - _: Noncrossing implementation-call discriminator; pass 0.
	//   - rlm: Current realm context forwarded unchanged by the governance proxy.
	//   - title: short title describing the parameter changes.
	//   - description: rationale and impact details for the changes.
	//   - numToExecute: number of encoded parameter-change executions expected.
	//   - executions: execution messages encoded with the governance execution delimiters.
	//
	// Returns:
	//   - int64: ID assigned to the newly created parameter-change proposal.
	ProposeParameterChange(
		_ int, rlm realm,
		title string,
		description string,
		numToExecute int64,
		executions string,
	) int64

	// Voting
	// Vote records the caller's final yes or no vote on a proposal.
	//
	// Parameters:
	//   - _: Noncrossing implementation-call discriminator; pass 0.
	//   - rlm: Current realm context forwarded unchanged by the governance proxy.
	//   - proposalId: ID of the proposal to vote on.
	//   - yes: true to cast an affirmative vote, false to cast a negative vote.
	//
	// Returns:
	//   - string: caller's applied voting weight formatted as a decimal string.
	Vote(
		_ int, rlm realm,
		proposalId int64,
		yes bool,
	) string

	// Execution
	// Execute applies an approved executable proposal within its delay and execution window.
	//
	// Parameters:
	//   - _: Noncrossing implementation-call discriminator; pass 0.
	//   - rlm: Current realm context forwarded unchanged by the governance proxy.
	//   - proposalId: ID of the proposal to execute.
	//
	// Returns:
	//   - int64: ID of the proposal successfully executed.
	Execute(
		_ int, rlm realm,
		proposalId int64,
	) int64

	// Cancel marks an upcoming proposal as cancelled at the request of its proposer.
	//
	// Parameters:
	//   - _: Noncrossing implementation-call discriminator; pass 0.
	//   - rlm: Current realm context forwarded unchanged by the governance proxy.
	//   - proposalId: ID of the proposal to cancel.
	//
	// Returns:
	//   - int64: ID of the proposal successfully cancelled.
	Cancel(
		_ int, rlm realm,
		proposalId int64,
	) int64

	// RemoveInactiveProposalFromIndex removes an inactive proposal from the snapshot index.
	//
	// Parameters:
	//   - _: Noncrossing implementation-call discriminator; pass 0.
	//   - rlm: Current realm context forwarded unchanged by the governance proxy.
	//   - proposalID: ID of the inactive proposal index entry to remove.
	RemoveInactiveProposalFromIndex(_ int, rlm realm, proposalID int64)

	// Configuration
	// Reconfigure validates and stores a new governance configuration version.
	//
	// Parameters:
	//   - _: Noncrossing implementation-call discriminator; pass 0.
	//   - rlm: Current realm context forwarded unchanged by the governance proxy.
	//   - votingStartDelay: seconds from proposal creation until voting opens.
	//   - votingPeriod: seconds for which voting remains open.
	//   - votingWeightSmoothingDuration: seconds used to smooth delegation history for voting weight.
	//   - quorum: required approval percentage of total xGNS supply, from 0 through 100.
	//   - proposalCreationThreshold: minimum xGNS amount required to create a proposal.
	//   - executionDelay: seconds required between approval and execution.
	//   - executionWindow: seconds after the delay during which execution is allowed.
	//
	// Returns:
	//   - int64: newly stored governance configuration version.
	Reconfigure(
		_ int, rlm realm,
		votingStartDelay int64,
		votingPeriod int64,
		votingWeightSmoothingDuration int64,
		quorum int64,
		proposalCreationThreshold int64,
		executionDelay int64,
		executionWindow int64,
	) int64
}

// IGovernanceGetter provides read-only access to governance data.
type IGovernanceGetter interface {
	// Store data getters
	// GetLatestConfigVersion returns the version number of the current governance configuration.
	//
	// Returns:
	//   - int64: current configuration version used for new proposals.
	GetLatestConfigVersion() int64
	// GetCurrentProposalID returns the current proposal ID counter value.
	//
	// Returns:
	//   - int64: current proposal identifier counter value.
	GetCurrentProposalID() int64
	// GetMaxSmoothingPeriod returns the upper bound for the voting-weight smoothing period.
	//
	// Returns:
	//   - int64: fixed maximum smoothing duration of 30 days (2,592,000 seconds).
	GetMaxSmoothingPeriod() int64

	// Config getters
	// GetLatestConfig returns the current governance configuration.
	//
	// Returns:
	//   - Config: latest stored configuration, or a zero configuration when unavailable.
	//   - error: nil when found; otherwise an error indicating that the configuration is unavailable.
	GetLatestConfig() (Config, error)
	// GetConfig returns a governance configuration by version.
	//
	// Parameters:
	//   - configVersion: configuration version to retrieve.
	//
	// Returns:
	//   - Config: configuration stored at the requested version, or a zero configuration when absent.
	//   - error: nil when found; otherwise an error identifying the missing version.
	GetConfig(configVersion int64) (Config, error)

	// GetProposals returns a read-only view of stored proposals keyed by decimal proposal ID.
	//
	// Returns:
	//   - *rotree.ReadOnlyTree: read-only proposal tree with cloned proposal values.
	GetProposals() *rotree.ReadOnlyTree
	// ExistsProposal reports whether a proposal is stored for an ID.
	//
	// Parameters:
	//   - proposalID: proposal identifier to look up.
	//
	// Returns:
	//   - bool: true when a proposal exists for proposalID.
	ExistsProposal(proposalID int64) bool
	// GetProposerByProposalId returns the address that created a proposal.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - address: proposer address recorded on the proposal.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetProposerByProposalId(proposalId int64) (address, error)
	// GetProposalTypeByProposalId returns the type discriminator of a proposal.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - ProposalType: proposal type stored on the proposal.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetProposalTypeByProposalId(proposalId int64) (ProposalType, error)
	// GetProposalCreatedAt returns a proposal's creation timestamp.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - int64: creation time as a Unix timestamp in seconds.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetProposalCreatedAt(proposalId int64) (int64, error)
	// GetProposalCreatedHeight returns the block height at which a proposal was created.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - int64: creation block height.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetProposalCreatedHeight(proposalId int64) (int64, error)
	// GetProposalCommunityPoolSpendInfo returns the treasury-transfer payload of a proposal.
	//
	// Parameters:
	//   - proposalID: proposal identifier to look up.
	//
	// Returns:
	//   - *CommunityPoolSpendInfo: spend payload, or nil when the proposal is absent or another type.
	//   - error: nil for a community-pool-spend proposal; otherwise a not-found or wrong-type error.
	GetProposalCommunityPoolSpendInfo(proposalID int64) (*CommunityPoolSpendInfo, error)
	// GetProposalExecutionInfo returns the parameter-execution payload of a proposal.
	//
	// Parameters:
	//   - proposalID: proposal identifier to look up.
	//
	// Returns:
	//   - *ExecutionInfo: execution payload, or nil when the proposal is absent or another type.
	//   - error: nil for a parameter-change proposal; otherwise a not-found or wrong-type error.
	GetProposalExecutionInfo(proposalID int64) (*ExecutionInfo, error)
	// GetYeaByProposalId returns the affirmative vote weight recorded on a proposal.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - int64: total yes-vote weight.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetYeaByProposalId(proposalId int64) (int64, error)
	// GetNayByProposalId returns the negative vote weight recorded on a proposal.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - int64: total no-vote weight.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetNayByProposalId(proposalId int64) (int64, error)
	// GetConfigVersionByProposalId returns the configuration version captured by a proposal.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - int64: configuration version used to create the proposal.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetConfigVersionByProposalId(proposalId int64) (int64, error)
	// GetQuorumAmountByProposalId returns the proposal's stored quorum requirement.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - int64: minimum vote weight required for quorum.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetQuorumAmountByProposalId(proposalId int64) (int64, error)
	// GetTitleByProposalId returns a proposal's title.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - string: title stored in proposal metadata.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetTitleByProposalId(proposalId int64) (string, error)
	// GetDescriptionByProposalId returns a proposal's full description.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - string: description stored in proposal metadata.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetDescriptionByProposalId(proposalId int64) (string, error)
	// GetProposalStatusByProposalId returns the current status string for a proposal.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - string: status computed from the proposal state and current time.
	//   - error: nil when found; otherwise an error indicating the proposal is missing.
	GetProposalStatusByProposalId(proposalId int64) (string, error)

	// Vote getters
	// GetVoteStatus returns the quorum and vote tallies stored for a proposal.
	//
	// Parameters:
	//   - proposalId: proposal identifier to look up.
	//
	// Returns:
	//   - quorum: minimum vote weight required for quorum.
	//   - maxVotingWeight: maximum voting weight captured at proposal creation.
	//   - yesWeight: total affirmative vote weight.
	//   - noWeight: total negative vote weight.
	//   - err: nil when found; otherwise an error indicating the proposal is missing.
	GetVoteStatus(proposalId int64) (quorum, maxVotingWeight, yesWeight, noWeight int64, err error)
	// GetVotingInfos returns a read-only view of a proposal's voter records.
	//
	// Parameters:
	//   - proposalID: proposal identifier whose voting records should be viewed.
	//
	// Returns:
	//   - *rotree.ReadOnlyTree: read-only voter-info tree, or nil when its stored tree is absent.
	GetVotingInfos(proposalID int64) *rotree.ReadOnlyTree
	// ExistsVotingInfo reports whether an address has a voting record for a proposal.
	//
	// Parameters:
	//   - proposalID: proposal identifier to inspect.
	//   - addr: voter address to look up.
	//
	// Returns:
	//   - bool: true when a voting record exists for the proposal and address.
	ExistsVotingInfo(proposalID int64, addr address) bool
	// GetVoteWeight returns the recorded voting weight for an address.
	//
	// Parameters:
	//   - proposalID: proposal identifier to inspect.
	//   - addr: voter address to look up.
	//
	// Returns:
	//   - int64: weight applied to the address's vote.
	//   - error: nil when a voting record exists; otherwise an error identifying the missing record.
	GetVoteWeight(proposalID int64, addr address) (int64, error)
	// GetVotedHeight returns the block height at which an address voted.
	//
	// Parameters:
	//   - proposalID: proposal identifier to inspect.
	//   - addr: voter address to look up.
	//
	// Returns:
	//   - int64: block height recorded for the vote.
	//   - error: nil when a voting record exists; otherwise an error identifying the missing record.
	GetVotedHeight(proposalID int64, addr address) (int64, error)
	// GetVotedAt returns the timestamp at which an address voted.
	//
	// Parameters:
	//   - proposalID: proposal identifier to inspect.
	//   - addr: voter address to look up.
	//
	// Returns:
	//   - int64: vote timestamp as Unix seconds.
	//   - error: nil when a voting record exists; otherwise an error identifying the missing record.
	GetVotedAt(proposalID int64, addr address) (int64, error)

	// GetUserProposals returns a read-only view of proposal IDs grouped by creator address.
	//
	// Returns:
	//   - *rotree.ReadOnlyTree: read-only creator-to-proposal-ID tree with copied ID slices.
	GetUserProposals() *rotree.ReadOnlyTree

	// Active proposal query
	// GetOldestActiveProposalSnapshotTime inspects the first timestamp-ordered active-proposal index entry.
	//
	// Returns:
	//   - snapshotTime: snapshot timestamp of the oldest active proposal.
	//   - hasActive: true when an active indexed proposal was found; false when the index is empty.
	//   - error: nil on success; otherwise an error when the index entry is missing or needs cleanup.
	GetOldestActiveProposalSnapshotTime() (int64, bool, error)

	// Voting weight snapshot getters
	// GetCurrentVotingWeightSnapshot computes the current total voting weight and its smoothed timestamp anchor.
	//
	// Returns:
	//   - totalVotingWeight: total delegation weight at the computed snapshot.
	//   - snapshotTime: Unix timestamp used as the snapshot anchor.
	//   - error: nil when the current configuration and snapshot are available; otherwise the lookup error.
	GetCurrentVotingWeightSnapshot() (int64, int64, error)
}

type IGovernanceStore interface {
	// Counter methods
	// HasConfigCounterStoreKey reports whether the configuration counter key exists.
	//
	// Returns:
	//   - bool: true when the configuration counter is present in persistent storage.
	HasConfigCounterStoreKey() bool
	// GetConfigCounter returns the persisted configuration-version counter.
	//
	// Returns:
	//   - *Counter: stored configuration counter; underlying storage/type failures panic.
	GetConfigCounter() *Counter
	// SetConfigCounter persists the configuration-version counter.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - counter: counter value to store.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm or key-value store error.
	SetConfigCounter(_ int, rlm realm, counter *Counter) error

	// HasProposalCounterStoreKey reports whether the proposal counter key exists.
	//
	// Returns:
	//   - bool: true when the proposal counter is present in persistent storage.
	HasProposalCounterStoreKey() bool
	// GetProposalCounter returns the persisted proposal-ID counter.
	//
	// Returns:
	//   - *Counter: stored proposal counter; underlying storage/type failures panic.
	GetProposalCounter() *Counter
	// SetProposalCounter persists the proposal-ID counter.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - counter: counter value to store.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm or key-value store error.
	SetProposalCounter(_ int, rlm realm, counter *Counter) error

	// Config methods
	// HasConfigsStoreKey reports whether the configurations tree key exists.
	//
	// Returns:
	//   - bool: true when the configurations tree is present in persistent storage.
	HasConfigsStoreKey() bool
	// SetConfigs replaces the persisted configuration-version tree.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - configs: configuration-version tree to store.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm or key-value store error.
	SetConfigs(_ int, rlm realm, configs *bptree.BPTree) error
	// SetConfig stores one configuration under its version key.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - version: configuration version key.
	//   - config: configuration value to store.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm, missing-tree, or key-value store error.
	SetConfig(_ int, rlm realm, version int64, config Config) error
	// GetConfig retrieves one configuration from the persisted version tree.
	//
	// Parameters:
	//   - version: configuration version key to look up.
	//
	// Returns:
	//   - Config: stored configuration, or its zero value when absent; wrong stored types panic.
	//   - bool: true when a configuration exists for version.
	GetConfig(version int64) (Config, bool)

	// Proposal methods
	// HasProposalsStoreKey reports whether the proposals tree key exists.
	//
	// Returns:
	//   - bool: true when the proposals tree is present in persistent storage.
	HasProposalsStoreKey() bool
	// GetProposals returns the mutable domain-owned proposals tree.
	//
	// Returns:
	//   - *bptree.BPTree: stored proposal tree keyed by proposal ID string; storage/type failures panic.
	GetProposals() *bptree.BPTree
	// GetProposal retrieves a proposal by numeric ID.
	//
	// Parameters:
	//   - proposalID: proposal identifier used as the tree key.
	//
	// Returns:
	//   - *Proposal: stored proposal when present and correctly typed.
	//   - bool: true when a valid proposal exists for proposalID.
	GetProposal(proposalID int64) (*Proposal, bool)
	// SetProposal stores a proposal under its matching numeric ID.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - proposalID: storage key that must match proposal.ID().
	//   - proposal: proposal value to persist.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm, missing-tree, or ID-mismatch error.
	SetProposal(_ int, rlm realm, proposalID int64, proposal *Proposal) error
	// SetProposals replaces the persisted proposals tree.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - proposals: proposal tree to persist.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm or key-value store error.
	SetProposals(_ int, rlm realm, proposals *bptree.BPTree) error

	// HasActiveProposalsBySnapshotStoreKey reports whether the active-proposal snapshot index exists.
	//
	// Returns:
	//   - bool: true when the timestamp-ordered active-proposal index is present.
	HasActiveProposalsBySnapshotStoreKey() bool
	// GetActiveProposalsBySnapshot returns the domain-owned active-proposal snapshot index.
	//
	// Returns:
	//   - *bptree.BPTree: index keyed by snapshot timestamp and containing proposal IDs; storage/type failures panic.
	GetActiveProposalsBySnapshot() *bptree.BPTree
	// SetActiveProposalsBySnapshot replaces the active-proposal snapshot index.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - tree: timestamp-ordered active-proposal index to persist.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm or key-value store error.
	SetActiveProposalsBySnapshot(_ int, rlm realm, tree *bptree.BPTree) error

	// Proposal voting info methods
	// HasProposalUserVotingInfosStoreKey reports whether the root voting-info tree exists.
	//
	// Returns:
	//   - bool: true when proposal voting-info storage is present.
	HasProposalUserVotingInfosStoreKey() bool
	// GetProposalUserVotingInfos returns the root proposal-to-voter-info tree.
	//
	// Returns:
	//   - *bptree.BPTree: stored tree containing one voter-info tree per proposal; storage/type failures panic.
	GetProposalUserVotingInfos() *bptree.BPTree
	// SetProposalUserVotingInfos replaces the root proposal-to-voter-info tree.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - votingInfos: root proposal-to-voter-info tree to persist.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm or key-value store error.
	SetProposalUserVotingInfos(_ int, rlm realm, votingInfos *bptree.BPTree) error
	// GetProposalVotingInfos returns the voter-info tree for one proposal.
	//
	// Parameters:
	//   - proposalID: proposal identifier used as the root-tree key.
	//
	// Returns:
	//   - *bptree.BPTree: voter-address-to-voting-info tree when present.
	//   - bool: true when the proposal has a correctly typed voter-info tree.
	GetProposalVotingInfos(proposalID int64) (*bptree.BPTree, bool)
	// SetProposalVotingInfos stores one proposal's voter-info tree.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - proposalID: proposal identifier used as the root-tree key.
	//   - votingInfos: voter-address-to-voting-info tree to persist.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm, missing-tree, or key-value store error.
	SetProposalVotingInfos(_ int, rlm realm, proposalID int64, votingInfos *bptree.BPTree) error

	// User proposals methods
	// HasUserProposalsStoreKey reports whether the user-to-proposal index exists.
	//
	// Returns:
	//   - bool: true when user proposal storage is present.
	HasUserProposalsStoreKey() bool
	// GetUserProposals returns the domain-owned user-to-proposal index tree.
	//
	// Returns:
	//   - *bptree.BPTree: tree mapping user strings to proposal-ID slices; storage/type failures panic.
	GetUserProposals() *bptree.BPTree
	// GetUserProposalIDs returns proposal IDs currently indexed for a user.
	//
	// Parameters:
	//   - user: user-string key in the user-to-proposals index.
	//
	// Returns:
	//   - []int64: proposal IDs indexed for user, or nil when absent; wrong stored types panic.
	//   - bool: true when the user has an index entry.
	GetUserProposalIDs(user string) ([]int64, bool)
	// SetUserProposals replaces the persisted user-to-proposal index.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - userProposals: user-to-proposal index tree to persist.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm or key-value store error.
	SetUserProposals(_ int, rlm realm, userProposals *bptree.BPTree) error
	// AddUserProposal appends a proposal ID to a user's indexed list.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - user: user-string key whose proposal list is updated.
	//   - proposalID: proposal identifier to append.
	//
	// Returns:
	//   - error: nil when persisted; otherwise a spoofed-realm, missing-key, or key-value store error.
	AddUserProposal(_ int, rlm realm, user string, proposalID int64) error
	// RemoveUserProposal removes every occurrence of a proposal ID from a user's list.
	// A missing user entry is treated as an already-complete no-op.
	//
	// Parameters:
	//   - _: leading realm-call discriminator for the internal store method; callers pass 0.
	//   - rlm: forwarded realm context for the persistent write; the store validates it as current.
	//   - user: user-string key whose proposal list is updated.
	//   - proposalID: proposal identifier to remove.
	//
	// Returns:
	//   - error: nil when removed or already absent; otherwise a spoofed-realm, missing-key, or key-value store error.
	RemoveUserProposal(_ int, rlm realm, user string, proposalID int64) error
}

// GovStakerAccessor provides an interface for accessing gov staker functionality.
// This abstraction allows for easier testing by enabling mock implementations.
type GovStakerAccessor interface {
	// GetTotalDelegationAmountAtSnapshot returns the total delegation amount at a specific snapshot time.
	//
	// Parameters:
	//   - snapshotTime: Unix timestamp at which delegation history is sampled.
	//
	// Returns:
	//   - int64: total delegated amount at snapshotTime.
	//   - bool: true when a snapshot value exists at that timestamp.
	GetTotalDelegationAmountAtSnapshot(snapshotTime int64) (int64, bool)

	// GetUserDelegationAmountAtSnapshot returns the user delegation amount at a specific snapshot time.
	//
	// Parameters:
	//   - userAddr: user address whose delegated amount is sampled.
	//   - snapshotTime: Unix timestamp at which the user's history is sampled.
	//
	// Returns:
	//   - int64: user's delegated amount at snapshotTime.
	//   - bool: true when a snapshot value exists for the user and timestamp.
	GetUserDelegationAmountAtSnapshot(userAddr address, snapshotTime int64) (int64, bool)

	// GetTotalxGnsSupply returns the total xGNS supply used as the quorum base.
	//
	// Returns:
	//   - int64: total xGNS supply used as the governance quorum base.
	GetTotalxGnsSupply() int64
}

upgrade.gno

package governance

import (
	"gno.land/r/gnoswap/access/v1"
)

// RegisterInitializer registers a version-specific initializer. Each version
// (e.g. v1, v2) calls this function from its init body to plug itself into
// the proxy.
//
// The initializer constructs the version's IGovernance from the supplied
// IGovernanceStore and GovStakerAccessor. It receives a realm value that
// resolves to the governance proxy realm — the only address with write
// permission on the shared KV store — so any per-version store bootstrap
// performed inside the initializer passes the proxy's authorization check.
//
// Security: Only contracts within the domain path can register initializers.
// Each package path can only register once to prevent duplicate registrations.
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - initializer: Callback that receives the proxy-authorized realm context, governance store, and staker accessor and returns the versioned implementation.
func RegisterInitializer(cur realm, initializer func(_ int, rlm realm, governanceStore IGovernanceStore, stakerAccessor GovStakerAccessor) IGovernance) {
	// `cur` captured here is the governance crossing frame. The wrapping
	// closure forwards it to the version initializer so any store writes
	// the initializer performs run under the proxy's identity rather than
	// the version package's, which would fail the kvStore ACL.
	initializerFunc := func(_ int, rlm realm, domainStore any) any {
		access.AssertIsRlmCurrent(0, rlm)

		currentGovernanceStore, ok := domainStore.(IGovernanceStore)
		if !ok {
			panic("domainStore is not an IGovernanceStore")
		}
		return initializer(0, rlm, currentGovernanceStore, newGovStakerAccessor())
	}

	err := versionManager.RegisterInitializer(0, cur, initializerFunc)
	if err != nil {
		panic(err)
	}

	err = updateImplementation()
	if err != nil {
		panic(err)
	}
}

// UpgradeImpl switches the active governance implementation to a different version.
// This function allows seamless upgrades from one version to another without
// data migration or downtime.
//
// Security: Only admin or governance can perform upgrades.
// The new implementation must have been previously registered via RegisterInitializer.
// Parameters:
//   - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//   - targetPackagePath: Registered implementation package path to activate.
func UpgradeImpl(cur realm, targetPackagePath string) {
	// Ensure only admin or governance can perform upgrades
	prev := cur.Previous()
	access.AssertIsAdminOrGovernance(prev.Address())

	err := versionManager.ChangeImplementation(0, cur, targetPackagePath)
	if err != nil {
		panic(err)
	}

	err = updateImplementation()
	if err != nil {
		panic(err)
	}
}

// GetImplementationPackagePath returns the package path of the currently active implementation.
//
// Returns:
//   - packagePath: package path of the active implementation
func GetImplementationPackagePath() string {
	return versionManager.GetCurrentPackagePath()
}

voting_info.gno

package governance

// VotingInfo tracks voting-related information for a specific user on a specific proposal.
// This structure maintains the user's voting eligibility, voting history, and voting power.
type VotingInfo struct {
	availableVoteWeight int64 // Total voting weight available to this user for this proposal
	votedWeight         int64 // Actual weight used when voting (0 if not voted)
	votedHeight         int64 // Block height when vote was cast
	votedAt             int64 // Timestamp when vote was cast
	votedYes            bool  // True if voted "yes", false if voted "no"
	voted               bool  // True if user has already voted
}

// NewVotingInfo creates a new voting information structure for a user.
// This constructor initializes the voting eligibility based on delegation snapshots.
//
// Parameters:
//   - availableVoteWeight: total voting weight available to this user
//
// Returns:
//   - VotingInfo: newly created voting information value
func NewVotingInfo(availableVoteWeight int64) VotingInfo {
	return VotingInfo{
		availableVoteWeight: availableVoteWeight,
		// Other fields are initialized to zero values (false, 0)
		// voted starts as false, indicating no vote has been cast
	}
}

// DefaultVotingInfo creates an empty voting information value.
//
// Returns:
//   - VotingInfo: zero-valued voting record with no available weight and no vote recorded
func DefaultVotingInfo() VotingInfo {
	return VotingInfo{}
}

// NewVotedVotingInfo creates a voting information value with a recorded vote.
//
// Parameters:
//   - availableVoteWeight: total voting weight available to the user for this proposal
//   - votedYes: true when the recorded vote is yes, false when it is no
//   - votedWeight: voting weight applied to the recorded vote
//   - votedHeight: block height at which the vote was recorded
//   - votedAt: Unix timestamp at which the vote was recorded
//
// Returns:
//   - VotingInfo: voting record populated with the supplied weight, choice, height, and timestamp and marked as voted
func NewVotedVotingInfo(availableVoteWeight int64, votedYes bool, votedWeight, votedHeight, votedAt int64) VotingInfo {
	return VotingInfo{
		availableVoteWeight: availableVoteWeight,
		votedWeight:         votedWeight,
		votedHeight:         votedHeight,
		votedAt:             votedAt,
		votedYes:            votedYes,
		voted:               true,
	}
}

// VotingType returns a human-readable string representation of the vote choice.
//
// Returns:
//   - string: "yes" or "no" based on voting choice
func (v VotingInfo) VotingType() string {
	if v.votedYes {
		return "yes"
	}

	return "no"
}

// IsVoted checks if the user has already cast their vote.
//
// Returns:
//   - bool: true if user has voted on this proposal
func (v VotingInfo) IsVoted() bool {
	return v.voted
}

// VotedYes checks if the user voted "yes" on the proposal.
// Only meaningful if IsVoted() returns true.
//
// Returns:
//   - bool: true if user voted "yes"
func (v VotingInfo) VotedYes() bool {
	return v.votedYes
}

// VotedNo checks if the user voted "no" on the proposal.
// Only meaningful if IsVoted() returns true.
//
// Returns:
//   - bool: true if user voted "no"
func (v VotingInfo) VotedNo() bool {
	return !v.votedYes
}

// AvailableVoteWeight returns the total voting weight available to this user.
// This weight is determined at proposal creation time based on delegation snapshots.
//
// Returns:
//   - int64: available voting weight
func (v VotingInfo) AvailableVoteWeight() int64 {
	return v.availableVoteWeight
}

// VotedWeight returns the weight actually used when voting.
// Returns 0 if the user hasn't voted yet.
//
// Returns:
//   - int64: weight used for voting, or 0 if not voted
func (v VotingInfo) VotedWeight() int64 {
	if !v.voted {
		return 0
	}

	return v.votedWeight
}

// VotedHeight returns the block height when the vote was cast.
// Returns 0 if the user hasn't voted yet.
//
// Returns:
//   - int64: block height when vote was cast
func (v VotingInfo) VotedHeight() int64 {
	if !v.voted {
		return 0
	}

	return v.votedHeight
}

// VotedAt returns the timestamp when the vote was cast.
// Returns 0 if the user hasn't voted yet.
//
// Returns:
//   - int64: timestamp when vote was cast
func (v VotingInfo) VotedAt() int64 {
	if !v.voted {
		return 0
	}

	return v.votedAt
}