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

assert.gno

package governance

import (
	"errors"

	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/halt/v1"

	"gno.land/r/gnoswap/gov/governance"
)

// assertIsNotHaltedGovernanceForProposalData panics if governance is halted,
// unless the proposal only targets the halt realm.
// This keeps a recovery path open so governance can unhalt itself.
func assertIsNotHaltedGovernanceForProposalData(proposalData *governance.ProposalData) {
	if isHaltRecoveryProposalData(proposalData) {
		return
	}

	halt.AssertIsNotHaltedGovernance()
}

// assertIsNotHaltedGovernanceForProposal panics if governance is halted,
// unless the proposal only targets the halt realm.
func assertIsNotHaltedGovernanceForProposal(gv *governanceV1, proposalID int64) {
	proposal, exists := gv.getProposal(proposalID)
	if !exists {
		halt.AssertIsNotHaltedGovernance()
		return
	}

	assertIsNotHaltedGovernanceForProposalData(proposal.Data())
}

// isHaltRecoveryProposalData returns true if the proposal is a parameter change
// whose every execution targets the halt realm.
func isHaltRecoveryProposalData(proposalData *governance.ProposalData) bool {
	if proposalData == nil || proposalData.ProposalType() != governance.ParameterChange {
		return false
	}

	infos, err := NewProposalDataResolver(proposalData).ParameterChangesInfos()
	if err != nil || len(infos) == 0 {
		return false
	}

	for _, info := range infos {
		if info.PkgPath() != HALT_PATH {
			return false
		}
	}

	return true
}

// assertCallerIsProposer panics if the caller is not the proposer of the given proposal.
func assertCallerIsProposer(gv *governanceV1, proposalID int64, caller address) {
	proposal, exists := gv.getProposal(proposalID)
	if !exists {
		panic(errors.New(errProposalNotFound))
	}

	if !proposal.IsProposer(caller) {
		panic(errors.New(errNotProposer))
	}
}

func assertIsValidSmoothingPeriod(smoothingPeriod int64) {
	if smoothingPeriod < 0 {
		panic(errors.New(errInvalidSmoothingPeriod))
	}

	if smoothingPeriod > maxSmoothingPeriod {
		panic(errors.New(errInvalidSmoothingPeriod))
	}
}

func assertIsValidToken(tokenPath string) {
	if tokenPath == "" {
		panic(makeErrorWithDetails(
			errInvalidInput, "tokenPath is empty"))
	}

	if err := common.IsRegistered(tokenPath); err != nil {
		panic(makeErrorWithDetails(
			errInvalidInput,
			ufmt.Sprintf("token(%s) is not registered", tokenPath),
		))
	}
}

config.gno

package governance

import (
	"chain"
	"time"

	"gno.land/p/gnoswap/utils/v1"

	"gno.land/r/gnoswap/access/v1"
	en "gno.land/r/gnoswap/emission"
	"gno.land/r/gnoswap/halt/v1"

	"gno.land/r/gnoswap/gov/governance"
)

// makeConfig creates a new governance configuration.
func makeConfig(
	votingStartDelay int64,
	votingPeriod int64,
	votingWeightSmoothingDuration int64,
	quorum int64,
	proposalCreationThreshold int64,
	executionDelay int64,
	executionWindow int64,
) governance.Config {
	// Create new configuration with provided parameters. Constructed via the
	// domain constructor so the Config value is allocated inside the governance
	// domain realm (satisfies the realm allocation check).
	return governance.NewConfig(
		votingStartDelay,
		votingPeriod,
		votingWeightSmoothingDuration,
		quorum,
		proposalCreationThreshold,
		executionDelay,
		executionWindow,
	)
}

// Reconfigure updates governance configuration.
// Only admin or governance contract can call this function.
// Updates all governance parameters and emits a "Reconfigure" event.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the governance proxy; validated before external calls.
//   - votingStartDelay: delay in seconds from proposal creation until voting starts
//   - votingPeriod: duration in seconds for which voting remains open
//   - votingWeightSmoothingDuration: duration in seconds used to smooth voting weight snapshots
//   - quorum: quorum percentage applied to the proposal's quorum-weight base
//   - proposalCreationThreshold: minimum voting weight required to create a proposal
//   - executionDelay: delay in seconds from voting end until execution becomes available
//   - executionWindow: duration in seconds during which an executable proposal may run
//
// Returns:
//   - int64: newly stored governance configuration version
func (gv *governanceV1) Reconfigure(
	_ int, rlm realm,
	votingStartDelay int64,
	votingPeriod int64,
	votingWeightSmoothingDuration int64,
	quorum int64,
	proposalCreationThreshold int64,
	executionDelay int64,
	executionWindow int64,
) int64 {
	access.AssertIsRlmCurrent(0, rlm)

	// Check if system is halted before proceeding
	halt.AssertIsNotHaltedGovernance()

	prev := rlm.Previous()
	caller := prev.Address()
	access.AssertIsAdminOrGovernance(caller)

	assertIsValidSmoothingPeriod(votingWeightSmoothingDuration)

	// Create and validate new configuration
	newCfg := makeConfig(
		votingStartDelay,
		votingPeriod,
		votingWeightSmoothingDuration,
		quorum,
		proposalCreationThreshold,
		executionDelay,
		executionWindow,
	)

	currentTime := time.Now().Unix()

	if err := newCfg.IsValid(currentTime); err != nil {
		panic(makeErrorWithDetails(errInvalidConfiguration, err.Error()))
	}

	// Mint and distribute GNS tokens as part of the process
	en.MintAndDistributeGns(cross(rlm))

	// Store previous version for event emission
	previousVersion := gv.getCurrentConfigVersion()

	// Apply the new configuration
	nextVersion := gv.reconfigure(0, rlm, newCfg)

	chain.Emit(
		"Reconfigure",
		"prevAddr", caller.String(),
		"prevRealm", prev.PkgPath(),
		"votingStartDelay", utils.FormatInt(newCfg.VotingStartDelay),
		"votingPeriod", utils.FormatInt(newCfg.VotingPeriod),
		"votingWeightSmoothingDuration", utils.FormatInt(newCfg.VotingWeightSmoothingDuration),
		"quorum", utils.FormatInt(newCfg.Quorum),
		"proposalCreationThreshold", utils.FormatInt(newCfg.ProposalCreationThreshold),
		"executionDelay", utils.FormatInt(newCfg.ExecutionDelay),
		"executionPeriod", utils.FormatInt(newCfg.ExecutionWindow),
		"newConfigVersion", utils.FormatInt(nextVersion),
		"prevConfigVersion", utils.FormatInt(previousVersion),
	)

	return nextVersion
}

// reconfigure stores the validated configuration with incremented version number.
func (gv *governanceV1) reconfigure(_ int, rlm realm, cfg governance.Config) int64 {
	// Generate next version number
	nextVersion := gv.nextConfigVersion(0, rlm)

	// Store the new configuration with version
	err := gv.setConfig(0, rlm, nextVersion, cfg)
	if err != nil {
		panic("failed to set config: " + err.Error())
	}

	return nextVersion
}

consts.gno

package governance

const (
	// Governance can execute multiple messages in a single proposal
	// each message is a string with the following format:
	// <pkgPath>*EXE*<function>*EXE*<params>
	// To execute a message, we need to parse the message and call the corresponding function
	// with the given parameters
	parameterSeparator = "*EXE*"

	messageSeparator = "*GOV*"

	maxTitleLength       = 255
	maxDescriptionLength = 10_000
	maxNumberOfExecution = 10
	maxSmoothingPeriod   = 30 * 60 * 60 * 24 // 30 days
)

doc.gno

package governance

errors.gno

package governance

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

const (
	errInvalidInput                 = "[GNOSWAP-GOVERNANCE-001] invalid input"
	errDataNotFound                 = "[GNOSWAP-GOVERNANCE-002] requested data not found"
	errNotEnoughBalance             = "[GNOSWAP-GOVERNANCE-003] not enough balance"
	errAlreadyVoted                 = "[GNOSWAP-GOVERNANCE-004] cannot vote twice"
	errNotEnoughVotingWeight        = "[GNOSWAP-GOVERNANCE-005] not enough voting power"
	errAlreadyCanceledProposal      = "[GNOSWAP-GOVERNANCE-006] cannot cancel already canceled proposal"
	errUnableToCancelVotingProposal = "[GNOSWAP-GOVERNANCE-007] unable to cancel voting proposal"
	errTextProposalNotExecutable    = "[GNOSWAP-GOVERNANCE-008] cannot execute text proposal"
	errUnableToVoteOutOfPeriod      = "[GNOSWAP-GOVERNANCE-009] unable to vote out of voting period"
	errInvalidMessageFormat         = "[GNOSWAP-GOVERNANCE-010] invalid message format"
	errAlreadyActiveProposal        = "[GNOSWAP-GOVERNANCE-011] already active proposal"
	errProposalNotFound             = "[GNOSWAP-GOVERNANCE-012] proposal not found"
	errProposalNotExecutable        = "[GNOSWAP-GOVERNANCE-013] proposal not executable"
	errNotProposer                  = "[GNOSWAP-GOVERNANCE-014] not proposer"
	errInvalidConfiguration         = "[GNOSWAP-GOVERNANCE-015] invalid configuration"
	errInvalidExecution             = "[GNOSWAP-GOVERNANCE-016] invalid execution: handler not found"
	errInvalidSmoothingPeriod       = "[GNOSWAP-GOVERNANCE-017] invalid smoothing period"
	errProposalIndexNeedsCleanup    = "[GNOSWAP-GOVERNANCE-018] active proposal index requires pruning"
)

// makeErrorWithDetails creates an error with additional context.
func makeErrorWithDetails(message string, detail string) error {
	return ufmt.Errorf("%s || %s", message, detail)
}

getter.gno

package governance

import (
	"errors"
	"time"

	rotree "gno.land/p/nt/bptree/rotree/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/gov/governance"
)

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

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

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

// GetLatestConfig returns the latest governance configuration.
//
// Returns:
//   - governance.Config: latest stored configuration for the current version.
//   - error: nil on success; an error when the current configuration is missing.
func (gv *governanceV1) GetLatestConfig() (governance.Config, error) {
	currentVersion := gv.getCurrentConfigVersion()
	config, ok := gv.getConfig(currentVersion)
	if !ok {
		return governance.NewConfig(0, 0, 0, 0, 0, 0, 0), errors.New(errDataNotFound)
	}

	return config, nil
}

// GetConfig returns a specific governance configuration by version.
//
// Parameters:
//   - configVersion: configuration version to retrieve.
//
// Returns:
//   - governance.Config: configuration stored under configVersion.
//   - error: nil on success; an error when configVersion is not found.
func (gv *governanceV1) GetConfig(configVersion int64) (governance.Config, error) {
	config, ok := gv.getConfig(configVersion)
	if !ok {
		// Construct the zero Config via the domain constructor so it is
		// allocated inside the governance domain realm (realm allocation check).
		return governance.NewConfig(0, 0, 0, 0, 0, 0, 0), ufmt.Errorf("config version %d not found", configVersion)
	}

	return config, nil
}

// GetProposals returns a read-only view of every proposal, keyed by the decimal
// string form of the proposal ID.
//
// Returns:
//   - *rotree.ReadOnlyTree: read-only proposal tree with decimal proposal IDs as keys.
func (gv *governanceV1) GetProposals() *rotree.ReadOnlyTree {
	return rotree.Wrap(gv.store.GetProposals(), cloneProposalEntry)
}

// ExistsProposal checks if a proposal exists.
//
// Parameters:
//   - proposalID: proposal identifier to look up.
//
// Returns:
//   - bool: true when proposalID is stored, otherwise false.
func (gv *governanceV1) ExistsProposal(proposalID int64) bool {
	_, exists := gv.store.GetProposal(proposalID)
	return exists
}

// 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; an error when the proposal does not exist.
func (gv *governanceV1) GetProposerByProposalId(proposalId int64) (address, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return "", ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.Proposer(), nil
}

// GetProposalTypeByProposalId returns the type of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to look up.
//
// Returns:
//   - governance.ProposalType: type recorded for the proposal.
//   - error: nil on success; an error when the proposal does not exist.
func (gv *governanceV1) GetProposalTypeByProposalId(proposalId int64) (governance.ProposalType, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return governance.ProposalType(0), ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.Type(), nil
}

// 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; an error when the proposal does not exist.
func (gv *governanceV1) GetProposalCreatedAt(proposalId int64) (int64, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return 0, ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.CreatedAt(), nil
}

// 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; an error when the proposal does not exist.
func (gv *governanceV1) GetProposalCreatedHeight(proposalId int64) (int64, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return 0, ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.CreatedHeight(), nil
}

// GetProposalCommunityPoolSpendInfo returns the community pool spend info for a proposal.
//
// Parameters:
//   - proposalID: proposal identifier to inspect.
//
// Returns:
//   - *governance.CommunityPoolSpendInfo: spend details stored in the proposal.
//   - error: nil on success; an error when the proposal is missing or is not a
//     community pool spend proposal.
func (gv *governanceV1) GetProposalCommunityPoolSpendInfo(proposalID int64) (*governance.CommunityPoolSpendInfo, error) {
	proposal, exists := gv.store.GetProposal(proposalID)
	if !exists {
		return nil, ufmt.Errorf("proposal %d not found", proposalID)
	}

	proposalData := proposal.Data()
	if proposalData == nil || proposalData.CommunityPoolSpend() == nil {
		return nil, ufmt.Errorf("proposal is not a community pool spend proposal")
	}

	return proposalData.CommunityPoolSpend(), nil
}

// GetProposalExecutionInfo returns the execution info for a proposal.
//
// Parameters:
//   - proposalID: proposal identifier to inspect.
//
// Returns:
//   - *governance.ExecutionInfo: execution messages and count stored in the proposal.
//   - error: nil on success; an error when the proposal is missing or is not a
//     parameter change proposal.
func (gv *governanceV1) GetProposalExecutionInfo(proposalID int64) (*governance.ExecutionInfo, error) {
	proposal, exists := gv.store.GetProposal(proposalID)
	if !exists {
		return nil, ufmt.Errorf("proposal %d not found", proposalID)
	}

	proposalData := proposal.Data()
	if proposalData == nil || proposalData.Execution() == nil {
		return nil, ufmt.Errorf("proposal is not a parameter change proposal")
	}

	return proposalData.Execution(), nil
}

// 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; an error when the proposal does not exist.
func (gv *governanceV1) GetYeaByProposalId(proposalId int64) (int64, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return 0, ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.Status().YesWeight(), nil
}

// 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; an error when the proposal does not exist.
func (gv *governanceV1) GetNayByProposalId(proposalId int64) (int64, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return 0, ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.Status().NoWeight(), nil
}

// 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; an error when the proposal does not exist.
func (gv *governanceV1) GetConfigVersionByProposalId(proposalId int64) (int64, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return 0, ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.ConfigVersion(), nil
}

// 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; an error when the proposal does not exist.
func (gv *governanceV1) GetQuorumAmountByProposalId(proposalId int64) (int64, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return 0, ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.Status().VoteStatus().QuorumAmount(), nil
}

// GetTitleByProposalId returns the title of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect.
//
// Returns:
//   - string: proposal title.
//   - error: nil on success; an error when the proposal does not exist.
func (gv *governanceV1) GetTitleByProposalId(proposalId int64) (string, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return "", ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.Metadata().Title(), nil
}

// GetDescriptionByProposalId returns the description of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect.
//
// Returns:
//   - string: proposal description.
//   - error: nil on success; an error when the proposal does not exist.
func (gv *governanceV1) GetDescriptionByProposalId(proposalId int64) (string, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return "", ufmt.Errorf("proposal %d not found", proposalId)
	}
	return proposal.Metadata().Description(), nil
}

// 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; an error when the proposal does not exist.
func (gv *governanceV1) GetProposalStatusByProposalId(proposalId int64) (string, error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return "", ufmt.Errorf("proposal %d not found", proposalId)
	}
	proposalResolver := NewProposalResolver(proposal)
	return proposalResolver.Status(time.Now().Unix()), nil
}

// GetVoteStatus returns the vote status of a proposal.
//
// Parameters:
//   - proposalId: proposal identifier to inspect.
//
// Returns:
//   - quorum: minimum vote weight required for 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; an error when the proposal does not exist.
func (gv *governanceV1) GetVoteStatus(proposalId int64) (quorum, maxVotingWeight, yesWeight, noWeight int64, err error) {
	proposal, exists := gv.store.GetProposal(proposalId)
	if !exists {
		return 0, 0, 0, 0, ufmt.Errorf("proposal %d not found", proposalId)
	}
	voting := proposal.Status().VoteStatus()
	return voting.QuorumAmount(), voting.MaxVotingWeight(), voting.YesWeight(), voting.NoWeight(), nil
}

// 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 for proposalID.
func (gv *governanceV1) GetVotingInfos(proposalID int64) *rotree.ReadOnlyTree {
	votingInfos, exists := gv.getProposalUserVotingInfos(proposalID)
	if !exists {
		return nil
	}
	return rotree.Wrap(votingInfos, nil)
}

// ExistsVotingInfo checks if a voting info 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 (gv *governanceV1) ExistsVotingInfo(proposalID int64, addr address) bool {
	_, exists := gv.getProposalUserVotingInfo(proposalID, addr)
	return exists
}

// 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; an error when no voting information exists for the
//     proposal and address.
func (gv *governanceV1) GetVoteWeight(proposalID int64, addr address) (int64, error) {
	votingInfo, exists := gv.getProposalUserVotingInfo(proposalID, addr)
	if !exists {
		return 0, ufmt.Errorf("voting info not found for proposal %d and address %s", proposalID, addr.String())
	}
	return votingInfo.VotedWeight(), nil
}

// 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; an error when no voting information exists for the
//     proposal and address.
func (gv *governanceV1) GetVotedHeight(proposalID int64, addr address) (int64, error) {
	votingInfo, exists := gv.getProposalUserVotingInfo(proposalID, addr)
	if !exists {
		return 0, ufmt.Errorf("voting info not found for proposal %d and address %s", proposalID, addr.String())
	}
	return votingInfo.VotedHeight(), nil
}

// 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; an error when no voting information exists for the
//     proposal and address.
func (gv *governanceV1) GetVotedAt(proposalID int64, addr address) (int64, error) {
	votingInfo, exists := gv.getProposalUserVotingInfo(proposalID, addr)
	if !exists {
		return 0, ufmt.Errorf("voting info not found for proposal %d and address %s", proposalID, addr.String())
	}
	return votingInfo.VotedAt(), nil
}

// 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.
//
// Returns:
//   - *rotree.ReadOnlyTree: read-only user-proposal tree keyed by creator address.
func (gv *governanceV1) GetUserProposals() *rotree.ReadOnlyTree {
	return rotree.Wrap(gv.store.GetUserProposals(), cloneProposalIDsEntry)
}

// GetOldestActiveProposalSnapshotTime examines only the first timestamp-ordered index entry.
// If it is inactive, the error identifies the proposal requiring maintenance
// cleanup. An error must never be treated as an empty index when deleting
// delegation history.
//
// 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.
//   - error: nil for an empty index or active entry; an error when the entry's
//     proposal is missing or inactive and the index needs cleanup.
func (gv *governanceV1) GetOldestActiveProposalSnapshotTime() (int64, bool, error) {
	index := gv.store.GetActiveProposalsBySnapshot()
	if index.Size() == 0 {
		return 0, false, nil
	}

	_, value := index.GetByIndex(0)
	proposalID, ok := value.(int64)
	if !ok {
		panic(ufmt.Sprintf("failed to cast active proposal ID to int64: %T", value))
	}

	proposal, exists := gv.getProposal(proposalID)
	if !exists {
		return 0, false, makeErrorWithDetails(
			errProposalNotFound, ufmt.Sprintf("proposalID: %d", proposalID),
		)
	}
	if !NewProposalResolver(proposal).IsActive(time.Now().Unix()) {
		return 0, false, makeErrorWithDetails(
			errProposalIndexNeedsCleanup, ufmt.Sprintf("proposalID: %d", proposalID),
		)
	}

	return proposal.SnapshotTime(), true, nil
}

// GetCurrentVotingWeightSnapshot returns the current total voting weight and
// 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; an error when the current configuration or snapshot
//     data cannot be retrieved.
func (gv *governanceV1) GetCurrentVotingWeightSnapshot() (int64, int64, error) {
	current := time.Now().Unix()
	config, ok := gv.getCurrentConfig()
	if !ok {
		return 0, 0, ufmt.Errorf("current config not found")
	}

	return gv.getVotingWeightSnapshot(current, config.VotingWeightSmoothingDuration)
}

getter_utils.gno

package governance

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

// The functions below are makeEntrySafeFn transformations handed to
// rotree.Wrap. They run on every read through a read-only view, so each one
// returns a value the caller may hold without reaching realm-owned state.

// cloneProposalEntry is the transformation for the proposal tree. Proposal is
// mutable and its setters are declared in /r/gnoswap/gov/governance, so an
// external holder of the stored pointer could write realm state through it.
//
// Proposal.Clone leaves the type-specific data nil; see it for which lookups
// read it instead.
func cloneProposalEntry(value any) any {
	proposal, ok := value.(*governance.Proposal)
	if !ok {
		return nil
	}

	return proposal.Clone()
}

// cloneProposalIDsEntry is the transformation for the user proposal tree. The
// stored value is a slice, so hand out a copy rather than letting a reader
// write through the shared backing array.
func cloneProposalIDsEntry(value any) any {
	proposalIDs, ok := value.([]int64)
	if !ok {
		return nil
	}

	cloned := make([]int64, len(proposalIDs))
	copy(cloned, proposalIDs)

	return cloned
}

gnomod.toml

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

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

governance_execute.gno

package governance

import (
	"chain"
	"chain/runtime"
	"errors"
	"time"

	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/r/gnoswap/access/v1"

	"gno.land/p/gnoswap/utils/v1"

	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/emission"
	"gno.land/r/gnoswap/halt/v1"

	"gno.land/r/gnoswap/gov/governance"
)

// Execute executes an approved proposal.
//
// Processes and implements governance decisions after successful voting.
// Enforces the configured execution delay and execution window.
// Anyone can trigger execution to ensure decentralization.
//
// Parameters:
//   - _: Internal call discriminator; pass 0.
//   - rlm: Propagated realm context; must be current for authorized governance state updates and is crossed into execution-dependent calls.
//   - proposalID: ID of the proposal to execute
//
// Requirements:
//   - Proposal must have passed (quorum and strict yes-over-no majority)
//   - Quorum must be reached using the proposal's stored amount, derived from
//     the total xGNS supply and configured quorum percentage at creation
//   - Execution delay must have elapsed (1 day by default)
//   - Must be within the execution window (30 days by default)
//   - Proposal not already executed or cancelled
//
// Effects:
//   - Executes proposal actions (parameter changes, treasury transfers)
//   - Marks proposal as executed
//   - Emits execution event
//
// Returns:
//   - proposalID: ID of the executed proposal
//
// Callable by anyone once the proposal is executable.
func (gv *governanceV1) Execute(_ int, rlm realm, proposalID int64) int64 {
	access.AssertIsRlmCurrent(0, rlm)

	// Check if execution is allowed (system not halted for execution).
	// Halt recovery proposals remain executable while governance is halted.
	assertIsNotHaltedGovernanceForProposal(gv, proposalID)

	// Get caller information and current blockchain state
	prev := rlm.Previous()
	caller := prev.Address()
	currentHeight := runtime.ChainHeight()
	currentAt := time.Now().Unix()

	// Mint and distribute GNS tokens as part of the execution process
	emission.MintAndDistributeGns(cross(rlm))

	// Attempt to execute the proposal with current context
	proposal, err := gv.executeProposal(
		0, rlm,
		proposalID,
		currentAt,
		currentHeight,
		caller,
	)
	if err != nil {
		panic(err)
	}
	if err := gv.removeActiveProposal(0, rlm, proposal); err != nil {
		panic(err)
	}

	// Emit execution event for tracking and auditing
	chain.Emit(
		"Execute",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"proposalId", utils.FormatInt(proposalID),
	)

	return proposal.ID()
}

// executeProposal handles core logic of proposal execution.
func (gv *governanceV1) executeProposal(
	_ int, rlm realm,
	proposalID int64,
	executedAt int64,
	executedHeight int64,
	executedBy address,
) (*governance.Proposal, error) {
	// Retrieve the proposal from storage
	proposal, ok := gv.getProposal(proposalID)
	if !ok {
		return nil, errors.New(errDataNotFound)
	}

	// Text proposals cannot be executed (they are informational only)
	if proposal.IsTextType() {
		return nil, errors.New(errTextProposalNotExecutable)
	}

	proposalResolver := NewProposalResolver(proposal)

	// Verify proposal is in executable state (timing and voting requirements met)
	if !proposalResolver.IsExecutable(executedAt) {
		return nil, errors.New(errProposalNotExecutable)
	}

	// Mark proposal as executed in its status
	err := proposalResolver.execute(executedAt, executedHeight, executedBy)
	if err != nil {
		return nil, err
	}

	// Execute proposal based on its type
	switch proposal.Type() {
	case governance.CommunityPoolSpend:
		// Execute community pool spending (token transfers)
		err = executeCommunityPoolSpend(0, rlm, proposal, globalParameterRegistry, executedAt, executedHeight, executedBy)
		if err != nil {
			return nil, err
		}
	case governance.ParameterChange:
		// Execute parameter changes (governance configuration updates)
		err = executeParameterChange(0, rlm, proposal, globalParameterRegistry, executedAt, executedHeight, executedBy)
		if err != nil {
			return nil, err
		}
	}

	return proposal, nil
}

// Cancel cancels a proposal in upcoming status.
//
// Allows proposers to withdraw their proposals before voting begins.
// Prevents accidental or malicious proposals from reaching vote.
// Safety mechanism for proposal errors or changed circumstances.
//
// Parameters:
//   - _: Internal call discriminator; pass 0.
//   - rlm: Propagated realm context; must be current for authorized governance state updates and is crossed into reward-distribution calls.
//   - proposalID: ID of the proposal to cancel
//
// Requirements:
//   - Must be called by original proposer
//   - Proposal must be in "upcoming" status
//   - Voting must not have started yet
//   - Proposal not already cancelled or executed
//
// Effects:
//   - Sets proposal status to "cancelled"
//   - Prevents future voting or execution
//   - Emits cancellation event
//   - Frees up proposer's proposal slot
//
// Returns:
//   - proposalID: ID of the cancelled proposal
//
// Only callable by original proposer before voting begins.
func (gv *governanceV1) Cancel(_ int, rlm realm, proposalID int64) int64 {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedGovernance()

	prev := rlm.Previous()
	caller := prev.Address()
	assertCallerIsProposer(gv, proposalID, caller)

	// Get current blockchain state and caller information
	currentHeight := runtime.ChainHeight()
	currentAt := time.Now().Unix()

	// Mint and distribute GNS tokens as part of the process
	emission.MintAndDistributeGns(cross(rlm))

	// Attempt to cancel the proposal
	proposal, err := gv.cancel(proposalID, currentAt, currentHeight, caller)
	if err != nil {
		panic(err)
	}
	if err := gv.removeActiveProposal(0, rlm, proposal); err != nil {
		panic(err)
	}

	// Emit cancellation event for tracking
	chain.Emit(
		"Cancel",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"proposalId", utils.FormatInt(proposalID),
	)

	return proposal.ID()
}

// RemoveInactiveProposalFromIndex removes one inactive proposal from the
// snapshot index without deleting its proposal or voting history.
// Parameters:
//   - _: Internal call discriminator; pass 0.
//   - rlm: Propagated realm context used for the authorized snapshot-index update.
//   - proposalID: Identifier of the inactive proposal to remove from the snapshot index.
func (gv *governanceV1) RemoveInactiveProposalFromIndex(_ int, rlm realm, proposalID int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedGovernance()

	proposal, exists := gv.getProposal(proposalID)
	if !exists {
		panic(makeErrorWithDetails(errProposalNotFound, ufmt.Sprintf("proposalID: %d", proposalID)))
	}
	if NewProposalResolver(proposal).IsActive(time.Now().Unix()) {
		panic(makeErrorWithDetails(errInvalidInput, ufmt.Sprintf("proposal %d is still active", proposalID)))
	}
	if err := gv.removeActiveProposal(0, rlm, proposal); err != nil {
		panic(err)
	}

	prev := rlm.Previous()
	chain.Emit(
		"RemoveInactiveProposalFromIndex",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"proposalId", utils.FormatInt(proposalID),
	)
}

// cancel handles core logic of proposal cancellation.
// Validates proposal state and updates status to canceled.
func (gv *governanceV1) cancel(
	proposalID, canceledAt, canceledHeight int64,
	canceledBy address,
) (proposal *governance.Proposal, err error) {
	// Retrieve the proposal from storage
	proposal, ok := gv.getProposal(proposalID)
	if !ok {
		return nil, errors.New(errDataNotFound)
	}

	proposalResolver := NewProposalResolver(proposal)

	// Attempt to cancel the proposal (this validates cancellation conditions)
	err = proposalResolver.cancel(canceledAt, canceledHeight, canceledBy)
	if err != nil {
		return nil, err
	}

	return proposal, nil
}

// executeCommunityPoolSpend executes community pool spending proposals.
// Handles token transfers from community pool to specified recipients.
func executeCommunityPoolSpend(
	_ int, rlm realm,
	proposal *governance.Proposal,
	parameterRegistry *ParameterRegistry,
	executedAt int64,
	executedHeight int64,
	executedBy address,
) error {
	// Verify token registration for community pool spending
	if proposal.IsCommunityPoolSpendType() {
		common.MustRegistered(proposal.Data().CommunityPoolSpend().TokenPath())
	}

	// Execute all parameter changes defined in the proposal
	dataResolver := NewProposalDataResolver(proposal.Data())
	parameterChangesInfos, err := dataResolver.ParameterChangesInfos()
	if err != nil {
		return err
	}
	for _, parameterChangeInfo := range parameterChangesInfos {
		// Get the appropriate handler for this parameter change
		key := makeHandlerKey(parameterChangeInfo.PkgPath(), parameterChangeInfo.Function())
		handler, err := parameterRegistry.Handler(key)
		if err != nil {
			return err
		}

		// Execute the parameter change with provided parameters
		err = handler.Execute(0, rlm, parameterChangeInfo.Params())
		if err != nil {
			return err
		}
	}

	return nil
}

// executeParameterChange executes parameter change proposals.
// Handles governance configuration updates and system parameter modifications.
func executeParameterChange(
	_ int, rlm realm,
	proposal *governance.Proposal,
	parameterRegistry *ParameterRegistry,
	executedAt int64,
	executedHeight int64,
	executedBy address,
) error {
	// Execute all parameter changes defined in the proposal
	dataResolver := NewProposalDataResolver(proposal.Data())
	parameterChangesInfos, err := dataResolver.ParameterChangesInfos()
	if err != nil {
		return err
	}
	for _, parameterChangeInfo := range parameterChangesInfos {
		// Get the appropriate handler for this parameter change
		key := makeHandlerKey(parameterChangeInfo.PkgPath(), parameterChangeInfo.Function())
		handler, err := parameterRegistry.Handler(key)
		if err != nil {
			return err
		}

		// Execute the parameter change with provided parameters
		err = handler.Execute(0, rlm, parameterChangeInfo.Params())
		if err != nil {
			return err
		}
	}

	return nil
}

governance_propose.gno

package governance

import (
	"chain"
	"chain/runtime"
	"errors"
	"time"

	"gno.land/r/gnoswap/access/v1"

	gnsmath "gno.land/p/gnoswap/gnsmath/v1"
	"gno.land/p/gnoswap/utils/v1"

	"gno.land/r/gnoswap/gov/xgns"
	"gno.land/r/gnoswap/halt/v1"

	"gno.land/r/gnoswap/gov/governance"
)

// ProposeText creates a text proposal for community discussion.
//
// Signal proposals for non-binding community sentiment.
// Used for policy discussions, roadmap planning, and community feedback.
// No on-chain execution, serves as formal governance record.
//
// Parameters:
//
//   - _: Internal call discriminator; pass 0.
//
//   - rlm: Propagated realm context; validated as current before proposal state writes.
//
//   - title: Short, descriptive proposal title (up to 255 characters; 100 is a UX recommendation)
//
//   - description: Full proposal content with rationale and context
//
// Requirements:
//   - Caller must hold at least the configured ProposalCreationThreshold amount in xGNS
//   - No other active proposal from same address
//   - Title and description must be non-empty
//
// Process:
//   - Configured delay before voting starts (1 day by default)
//   - Configured voting period (7 days by default)
//   - Quorum and a strict yes-over-no majority determine the outcome
//   - No execution phase (signal only)
//
// Returns:
//   - newProposalId: ID of the newly created text proposal
func (gv *governanceV1) ProposeText(
	_ int, rlm realm,
	title string,
	description string,
) (newProposalId int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedGovernance()

	prev := rlm.Previous()
	callerAddress := prev.Address()

	createdAt := time.Now().Unix()
	createdHeight := runtime.ChainHeight()
	xgnsBalance := xgns.BalanceOf(callerAddress)

	config, ok := gv.getCurrentConfig()
	if !ok {
		panic(errors.New(errDataNotFound))
	}

	// Clean up inactive user proposals before checking if caller already has an active proposal
	err := gv.removeInactiveUserProposals(0, rlm, callerAddress, createdAt)
	if err != nil {
		panic(err)
	}

	// Check if caller already has an active proposal (one proposal per address)
	if gv.hasActiveProposal(callerAddress) {
		panic(errors.New(errAlreadyActiveProposal))
	}

	// Get timestamp anchor and total voting weight for proposal creation
	maxVotingWeight, snapshotTime, err := gv.getVotingWeightSnapshot(
		createdAt,
		config.VotingWeightSmoothingDuration,
	)
	if err != nil {
		panic(err)
	}
	quorumWeight := gv.stakerAccessor.GetTotalxGnsSupply()

	// Create the text proposal with metadata
	proposal, err := gv.createProposal(
		0, rlm,
		governance.Text,
		config,
		maxVotingWeight,
		quorumWeight,
		snapshotTime,
		governance.NewProposalMetadata(title, description),
		NewProposalTextData(),
		callerAddress,
		xgnsBalance,
		createdAt,
		createdHeight,
	)
	if err != nil {
		panic(err)
	}

	// Initialize empty voting info tree for this proposal (votes will be added as users vote)
	err = gv.updateProposalUserVotes(0, rlm, proposal, governance.NewProposalUserVotingInfoTree())
	if err != nil {
		panic(err)
	}

	// Emit proposal creation event for indexing and tracking
	chain.Emit(
		"ProposeText",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"title", title,
		"proposalId", utils.FormatInt(proposal.ID()),
		"quorumAmount", utils.FormatInt(proposal.VotingQuorumAmount()),
		"maxVotingWeight", utils.FormatInt(proposal.VotingMaxWeight()),
		"configVersion", utils.FormatInt(proposal.ConfigVersion()),
		"createdAt", utils.FormatInt(proposal.CreatedAt()),
	)

	return proposal.ID()
}

// ProposeCommunityPoolSpend creates a treasury disbursement proposal.
//
// Allocates community pool funds for approved purposes.
// Supports grants, development funding, and protocol incentives.
// The transfer is attempted when the approved proposal executes.
//
// Parameters:
//
//   - _: Internal call discriminator; pass 0.
//
//   - rlm: Propagated realm context; validated as current before proposal state writes.
//
//   - title: Proposal title describing purpose
//
//   - description: Detailed justification and budget breakdown
//
//   - to: Recipient address for funds
//
//   - tokenPath: Registered token contract path (e.g., "gno.land/r/gnoswap/gns")
//
//   - amount: Strictly positive amount to transfer (in smallest unit)
//
// Requirements:
//   - Caller must hold at least the configured ProposalCreationThreshold amount in xGNS
//   - Valid recipient address
//   - Registered token path
//   - Community-pool balance is checked at execution, not proposal creation
//
// Security:
//   - Enforces timelock after approval
//   - Single transfer per proposal
//   - Tracks all disbursements on-chain
//
// Returns:
//   - newProposalId: ID of the newly created community-pool-spend proposal
func (gv *governanceV1) ProposeCommunityPoolSpend(
	_ int, rlm realm,
	title string,
	description string,
	to address,
	tokenPath string,
	amount int64,
) (newProposalId int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedGovernance()

	assertIsValidToken(tokenPath)

	createdAt := time.Now().Unix()
	createdHeight := runtime.ChainHeight()

	prev := rlm.Previous()
	callerAddress := prev.Address()
	xgnsBalance := xgns.BalanceOf(callerAddress)

	config, ok := gv.getCurrentConfig()
	if !ok {
		panic(errors.New(errDataNotFound))
	}

	// Clean up inactive user proposals before checking if caller already has an active proposal
	err := gv.removeInactiveUserProposals(0, rlm, callerAddress, createdAt)
	if err != nil {
		panic(err)
	}

	// Check if caller already has an active proposal (one proposal per address)
	if gv.hasActiveProposal(callerAddress) {
		panic(errors.New(errAlreadyActiveProposal))
	}

	// Get timestamp anchor and total voting weight for proposal creation
	maxVotingWeight, snapshotTime, err := gv.getVotingWeightSnapshot(
		createdAt,
		config.VotingWeightSmoothingDuration,
	)
	if err != nil {
		panic(err)
	}
	quorumWeight := gv.stakerAccessor.GetTotalxGnsSupply()

	// Create the community pool spend proposal with execution data
	proposal, err := gv.createProposal(
		0, rlm,
		governance.CommunityPoolSpend,
		config,
		maxVotingWeight,
		quorumWeight,
		snapshotTime,
		governance.NewProposalMetadata(title, description),
		NewProposalCommunityPoolSpendData(tokenPath, to, amount, COMMUNITY_POOL_PATH),
		callerAddress,
		xgnsBalance,
		createdAt,
		createdHeight,
	)
	if err != nil {
		panic(err)
	}

	// Initialize empty voting info tree for this proposal (votes will be added as users vote)
	err = gv.updateProposalUserVotes(0, rlm, proposal, governance.NewProposalUserVotingInfoTree())
	if err != nil {
		panic(err)
	}

	// Emit proposal creation event for indexing and tracking
	chain.Emit(
		"ProposeCommunityPoolSpend",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"title", title,
		"to", to.String(),
		"tokenPath", tokenPath,
		"amount", utils.FormatInt(amount),
		"proposalId", utils.FormatInt(proposal.ID()),
		"quorumAmount", utils.FormatInt(proposal.VotingQuorumAmount()),
		"maxVotingWeight", utils.FormatInt(proposal.VotingMaxWeight()),
		"configVersion", utils.FormatInt(proposal.ConfigVersion()),
		"createdAt", utils.FormatInt(proposal.CreatedAt()),
	)

	return proposal.ID()
}

// ProposeParameterChange creates a protocol parameter update proposal.
//
// Modifies system parameters through governance.
// Supports multiple parameter changes in single proposal.
// Changes apply atomically on execution.
//
// Parameters:
//
//   - _: Internal call discriminator; pass 0.
//
//   - rlm: Propagated realm context; validated as current before proposal state writes.
//
//   - title: Clear description of changes
//
//   - description: Rationale and impact analysis
//
//   - numToExecute: Number of parameter changes
//
//   - executions: Raw execution string encoded as messages separated by *GOV*.
//     Each message is formatted as <pkgPath>*EXE*<function>*EXE*<params>.
//
// Example execution format (one registered handler; all seven arguments are required):
//
//	gno.land/r/gnoswap/gov/governance*EXE*Reconfigure*EXE*86400,604800,86400,50,1000000000,86400,2592000
//
// Requirements:
//   - Caller must hold at least the configured ProposalCreationThreshold amount in xGNS
//   - Encoded execution messages must match numToExecute
//   - Target handlers must exist in the parameter registry
//   - Parameters must match registered function signatures
//
// Returns:
//   - newProposalId: ID of the newly created parameter-change proposal
func (gv *governanceV1) ProposeParameterChange(
	_ int, rlm realm,
	title string,
	description string,
	numToExecute int64,
	executions string,
) (newProposalId int64) {
	access.AssertIsRlmCurrent(0, rlm)

	proposalData := NewProposalExecutionData(numToExecute, executions)
	assertIsNotHaltedGovernanceForProposalData(proposalData)

	prev := rlm.Previous()
	callerAddress := prev.Address()

	createdAt := time.Now().Unix()
	createdHeight := runtime.ChainHeight()
	xgnsBalance := xgns.BalanceOf(callerAddress)

	config, ok := gv.getCurrentConfig()
	if !ok {
		panic(errors.New(errDataNotFound))
	}

	// Clean up inactive user proposals before checking if caller already has an active proposal
	err := gv.removeInactiveUserProposals(0, rlm, callerAddress, createdAt)
	if err != nil {
		panic(err)
	}

	// Check if caller already has an active proposal (one proposal per address)
	if gv.hasActiveProposal(callerAddress) {
		panic(errors.New(errAlreadyActiveProposal))
	}

	// Get timestamp anchor and total voting weight for proposal creation
	maxVotingWeight, snapshotTime, err := gv.getVotingWeightSnapshot(
		createdAt,
		config.VotingWeightSmoothingDuration,
	)
	if err != nil {
		panic(err)
	}
	quorumWeight := gv.stakerAccessor.GetTotalxGnsSupply()

	// Create the parameter change proposal with execution data
	proposal, err := gv.createProposal(
		0, rlm,
		governance.ParameterChange,
		config,
		maxVotingWeight,
		quorumWeight,
		snapshotTime,
		governance.NewProposalMetadata(title, description),
		proposalData,
		callerAddress,
		xgnsBalance,
		createdAt,
		createdHeight,
	)
	if err != nil {
		panic(err)
	}

	// Initialize empty voting info tree for this proposal (votes will be added as users vote)
	err = gv.updateProposalUserVotes(0, rlm, proposal, governance.NewProposalUserVotingInfoTree())
	if err != nil {
		panic(err)
	}

	// Emit proposal creation event for indexing and tracking
	chain.Emit(
		"ProposeParameterChange",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"title", title,
		"numToExecute", utils.FormatInt(numToExecute),
		"proposalId", utils.FormatInt(proposal.ID()),
		"quorumAmount", utils.FormatInt(proposal.VotingQuorumAmount()),
		"maxVotingWeight", utils.FormatInt(proposal.VotingMaxWeight()),
		"configVersion", utils.FormatInt(proposal.ConfigVersion()),
		"createdAt", utils.FormatInt(proposal.CreatedAt()),
	)

	return proposal.ID()
}

// createProposal handles proposal creation logic.
// Validates input data, checks proposer eligibility, and creates proposal object.
func (gv *governanceV1) createProposal(
	_ int, rlm realm,
	proposalType governance.ProposalType,
	config governance.Config,
	maxVotingWeight int64,
	quorumWeight int64,
	snapshotTime int64,
	proposalMetadata *governance.ProposalMetadata,
	proposalData *governance.ProposalData,
	proposerAddress address,
	proposerXGnsBalance int64,
	createdAt int64,
	createdHeight int64,
) (*governance.Proposal, error) {
	// Validate proposal metadata (title and description)
	metadataResolver := NewProposalMetadataResolver(proposalMetadata)
	err := metadataResolver.Validate()
	if err != nil {
		return nil, err
	}

	// Validate proposal data (type-specific validation)
	dataResolver := NewProposalDataResolver(proposalData)
	err = dataResolver.Validate()
	if err != nil {
		return nil, err
	}

	// Check if proposer has enough xGNS balance to create proposal
	if proposerXGnsBalance < config.ProposalCreationThreshold {
		return nil, errors.New(errNotEnoughBalance)
	}

	// Generate unique proposal ID
	proposalID := gv.nextProposalID(0, rlm)

	// Create proposal status with voting schedule and requirements
	proposalStatus := NewProposalStatus(
		config,
		maxVotingWeight,
		proposalType.IsExecutable(),
		createdAt,
		quorumWeight,
	)

	// Get current configuration version for tracking
	configVersion := gv.getCurrentConfigVersion()

	// Create the proposal object with a timestamp anchor for lazy voting-weight lookup
	proposal := governance.NewProposal(
		proposalID,
		proposalStatus,
		proposalMetadata,
		proposalData,
		proposerAddress,
		configVersion,
		snapshotTime,
		createdHeight,
	)

	// Store the proposal in state
	success := gv.addProposal(0, rlm, proposal)
	if !success {
		return nil, errors.New(errDataNotFound)
	}

	return proposal, nil
}

// getVotingWeightSnapshot retrieves the averaged total voting weight for proposal creation.
// It uses two snapshots (current and current - smoothingPeriod) and averages them.
func (gv *governanceV1) getVotingWeightSnapshot(
	current,
	smoothingPeriod int64,
) (int64, int64, error) {
	// Calculate the earlier timestamp by subtracting the smoothing duration
	snapshotTime := current - smoothingPeriod
	if snapshotTime < 0 {
		snapshotTime = 0
	}

	// Get total delegation at the earlier timestamp from staker history
	totalAtSnapshot, ok := gv.stakerAccessor.GetTotalDelegationAmountAtSnapshot(snapshotTime)
	if !ok {
		totalAtSnapshot = 0
	}

	totalAtCurrent, ok := gv.stakerAccessor.GetTotalDelegationAmountAtSnapshot(current)
	if !ok {
		totalAtCurrent = 0
	}

	totalVotingWeight := gnsmath.SafeAddInt64(totalAtSnapshot, totalAtCurrent) / 2
	if totalVotingWeight <= 0 {
		return 0, snapshotTime, errors.New(errNotEnoughVotingWeight)
	}

	return totalVotingWeight, snapshotTime, nil
}

governance_vote.gno

package governance

import (
	"chain"
	"chain/runtime"
	"time"

	"gno.land/r/gnoswap/access/v1"

	gnsmath "gno.land/p/gnoswap/gnsmath/v1"
	"gno.land/p/gnoswap/utils/v1"

	"gno.land/r/gnoswap/emission"

	"gno.land/r/gnoswap/gov/governance"
)

// Vote casts a vote on a proposal.
//
// Records an on-chain vote with weight based on delegated xGNS.
// Uses the proposal's timestamp anchors and configured smoothing duration to
// prevent manipulation. Votes are final and cannot be changed.
//
// Parameters:
//   - _: leading realm-call discriminator; callers pass 0 while threading the realm context
//   - rlm: current realm context; implementation validates it before reading or writing governance state
//   - proposalID: ID of the proposal to vote on
//   - yes: true for yes vote, false for no vote
//
// Vote Weight Calculation:
//   - Based on the voter's delegated xGNS amount
//   - Averages delegation at the stored smoothing timestamp and proposal creation time
//   - Uses Unix timestamp history, not a block-height snapshot
//   - Includes self-delegation and delegations received by the voter
//
// Requirements:
//   - Proposal must be in voting period
//   - Voter must have xGNS delegated at one of the lookup timestamps
//   - Cannot vote twice on same proposal
//   - Voting period is 7 days by default and is configurable
//
// Returns:
//   - voteWeight: voting weight applied to the caller's vote, formatted as a string
func (gv *governanceV1) Vote(_ int, rlm realm, proposalID int64, yes bool) string {
	access.AssertIsRlmCurrent(0, rlm)

	assertIsNotHaltedGovernanceForProposal(gv, proposalID)

	// Get current blockchain state and caller information
	currentHeight := runtime.ChainHeight()
	currentAt := time.Now()

	// Mint and distribute GNS tokens as part of the voting process
	emission.MintAndDistributeGns(cross(rlm))

	// Extract voter address from realm context
	voterRealm := rlm.Previous()
	voter := voterRealm.Address()

	// Process the vote and get updated vote tallies
	userVote, totalYesVoteWeight, totalNoVoteWeight, err := gv.vote(
		0, rlm,
		proposalID,
		voter,
		yes,
		currentHeight,
		currentAt.Unix(),
	)
	if err != nil {
		panic(err)
	}

	// Emit voting event for tracking and transparency
	voteWeight := utils.FormatInt(userVote.VotedWeight())
	voterStr := voter.String()

	chain.Emit(
		"Vote",
		"prevAddr", voterStr,
		"prevPkgPath", voterRealm.PkgPath(),
		"proposalId", utils.FormatInt(proposalID),
		"voter", voterStr,
		"yes", userVote.VotingType(),
		"voteWeight", voteWeight,
		"voteYes", utils.FormatInt(totalYesVoteWeight),
		"voteNo", utils.FormatInt(totalNoVoteWeight),
	)

	return voteWeight
}

// vote handles core voting logic.
func (gv *governanceV1) vote(
	_ int, rlm realm,
	proposalID int64,
	voterAddress address,
	votedYes bool,
	votedHeight,
	votedAt int64,
) (governance.VotingInfo, int64, int64, error) {
	// Retrieve the proposal from storage
	proposal, ok := gv.getProposal(proposalID)
	if !ok {
		return governance.DefaultVotingInfo(), 0, 0, makeErrorWithDetails(errDataNotFound, "not found proposal")
	}

	proposalResolver := NewProposalResolver(proposal)

	// Check if current time is within voting period
	if !proposalResolver.IsVotingPeriod(votedAt) {
		return governance.DefaultVotingInfo(), 0, 0, makeErrorWithDetails(errUnableToVoteOutOfPeriod, "cannot vote out of voting period")
	}

	// Get user's voting weight by averaging timestamp-history values at the
	// proposal's stored smoothing anchor and creation time.
	snapshotTime := proposal.SnapshotTime()
	createdAt := proposal.CreatedAt()

	weightAtSnapshot, ok := gv.stakerAccessor.GetUserDelegationAmountAtSnapshot(voterAddress, snapshotTime)
	if !ok {
		weightAtSnapshot = 0
	}

	weightAtCreated, ok := gv.stakerAccessor.GetUserDelegationAmountAtSnapshot(voterAddress, createdAt)
	if !ok {
		weightAtCreated = 0
	}

	votingWeight := gnsmath.SafeAddInt64(weightAtSnapshot, weightAtCreated) / 2
	if votingWeight <= 0 {
		return governance.DefaultVotingInfo(), 0, 0, makeErrorWithDetails(
			errNotEnoughVotingWeight, "no voting weight at snapshot time")
	}

	userVote, exists := gv.getProposalUserVotingInfo(proposalID, voterAddress)
	if !exists {
		userVote = governance.NewVotingInfo(votingWeight)
	}

	if userVote.IsVoted() {
		return governance.DefaultVotingInfo(), 0, 0, makeErrorWithDetails(errAlreadyVoted, "user has already voted")
	}
	userVote = governance.NewVotedVotingInfo(votingWeight, votedYes, votingWeight, votedHeight, votedAt)

	votingInfosTree, _ := gv.getProposalUserVotingInfos(proposalID)
	if votingInfosTree == nil {
		return governance.DefaultVotingInfo(), 0, 0, makeErrorWithDetails(
			errDataNotFound, "voting infos tree not found for proposal")
	}

	votingInfosTree.Set(voterAddress.String(), userVote)
	err := gv.store.SetProposalVotingInfos(0, rlm, proposalID, votingInfosTree)
	if err != nil {
		return governance.DefaultVotingInfo(), 0, 0, err
	}

	// Update proposal vote tallies
	err = proposalResolver.Vote(votedYes, votingWeight)
	if err != nil {
		return governance.DefaultVotingInfo(), 0, 0, err
	}

	return userVote, proposal.VotingYesWeight(), proposal.VotingNoWeight(), nil
}

init.gno

package governance

import (
	"strconv"

	"gno.land/r/gnoswap/gov/governance"
)

func init(cur realm) {
	registerGovernanceV1(cur)
}

func registerGovernanceV1(cur realm) {
	governance.RegisterInitializer(cross(cur), func(_ int, rlm realm, governanceStore governance.IGovernanceStore, stakerAccessor governance.GovStakerAccessor) governance.IGovernance {
		// `rlm` here is the governance proxy realm threaded in by
		// governance.RegisterInitializer. Per-version store bootstrap
		// writes therefore pass the proxy's KV-store ACL.
		err := initStoreData(0, rlm, governanceStore)
		if err != nil {
			panic(err)
		}

		return NewGovernanceV1(governanceStore, stakerAccessor)
	})
}

func initStoreData(_ int, rlm realm, governanceStore governance.IGovernanceStore) error {
	// Initialize counters if not already set
	if !governanceStore.HasConfigCounterStoreKey() {
		err := governanceStore.SetConfigCounter(0, rlm, governance.NewCounter())
		if err != nil {
			return err
		}
	}

	if !governanceStore.HasProposalCounterStoreKey() {
		err := governanceStore.SetProposalCounter(0, rlm, governance.NewCounter())
		if err != nil {
			return err
		}
	}

	// Initialize Configs with default configuration if not already set
	if !governanceStore.HasConfigsStoreKey() {
		configs := governance.NewConfigTree()
		counter := governanceStore.GetConfigCounter()
		nextConfigVersion := counter.Next()

		configs.Set(formatConfigKey(nextConfigVersion), governance.NewDefaultConfig())

		err := governanceStore.SetConfigs(0, rlm, configs)
		if err != nil {
			return err
		}
		// Persist the mutated counter so the bumped version survives the
		// boundary into the proxy's KV store.
		if err := governanceStore.SetConfigCounter(0, rlm, counter); err != nil {
			return err
		}
	}

	if !governanceStore.HasProposalsStoreKey() {
		err := governanceStore.SetProposals(0, rlm, governance.NewProposalTree())
		if err != nil {
			return err
		}
	}

	if !governanceStore.HasActiveProposalsBySnapshotStoreKey() {
		if err := governanceStore.SetActiveProposalsBySnapshot(0, rlm, governance.NewProposalTree()); err != nil {
			return err
		}
	}

	if !governanceStore.HasProposalUserVotingInfosStoreKey() {
		err := governanceStore.SetProposalUserVotingInfos(0, rlm, governance.NewProposalUserVotingInfoTree())
		if err != nil {
			return err
		}
	}

	if !governanceStore.HasUserProposalsStoreKey() {
		err := governanceStore.SetUserProposals(0, rlm, governance.NewUserProposalTree())
		if err != nil {
			return err
		}
	}

	return nil
}

func formatConfigKey(version int64) string {
	return strconv.FormatInt(version, 10)
}

instance.gno

package governance

import (
	"gno.land/p/gnoswap/utils/v1"
	bptree "gno.land/p/nt/bptree/v0"
	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/r/gnoswap/gov/governance"
)

type governanceV1 struct {
	store          governance.IGovernanceStore
	stakerAccessor governance.GovStakerAccessor
}

// NewGovernanceV1 creates a governance v1 implementation backed by the supplied
// state store and staker voting-weight accessor.
//
// Parameters:
//   - governanceStore: persistence adapter for configuration, proposals, counters, and voting information
//   - stakerAccessor: accessor that supplies delegation snapshots and total xGNS supply for governance decisions
//
// Returns:
//   - governance.IGovernance: governance manager and getter implementation using the supplied dependencies
func NewGovernanceV1(
	governanceStore governance.IGovernanceStore,
	stakerAccessor governance.GovStakerAccessor,
) governance.IGovernance {
	return &governanceV1{
		store:          governanceStore,
		stakerAccessor: stakerAccessor,
	}
}

// Config version methods
func (g *governanceV1) getCurrentConfigVersion() int64 {
	return g.store.GetConfigCounter().Get()
}

// nextConfigVersion increments and persists the config counter. It mutates the
// underlying KV store, so it requires a realm value that resolves to the
// governance proxy realm (the only writer-permitted address).
func (g *governanceV1) nextConfigVersion(_ int, rlm realm) int64 {
	counter := g.store.GetConfigCounter()
	next := counter.Next()
	if err := g.store.SetConfigCounter(0, rlm, counter); err != nil {
		panic(err)
	}
	return next
}

// Proposal ID methods
func (g *governanceV1) getCurrentProposalID() int64 {
	return g.store.GetProposalCounter().Get()
}

// nextProposalID increments and persists the proposal counter. Same realm
// rules as nextConfigVersion.
func (g *governanceV1) nextProposalID(_ int, rlm realm) int64 {
	counter := g.store.GetProposalCounter()
	next := counter.Next()
	if err := g.store.SetProposalCounter(0, rlm, counter); err != nil {
		panic(err)
	}
	return next
}

// Config methods
func (g *governanceV1) getConfig(version int64) (governance.Config, bool) {
	return g.store.GetConfig(version)
}

func (g *governanceV1) setConfig(_ int, rlm realm, version int64, config governance.Config) error {
	return g.store.SetConfig(0, rlm, version, config)
}

func (g *governanceV1) getCurrentConfig() (governance.Config, bool) {
	return g.getConfig(g.getCurrentConfigVersion())
}

// Proposal methods
func (g *governanceV1) getProposal(id int64) (*governance.Proposal, bool) {
	proposal, exists := g.store.GetProposal(id)
	if !exists {
		return nil, false
	}

	return proposal, true
}

func activeProposalSnapshotKey(proposal *governance.Proposal) string {
	return utils.EncodeUint64(uint64(proposal.SnapshotTime())) + utils.EncodeUint64(uint64(proposal.ID()))
}

func (g *governanceV1) addProposal(_ int, rlm realm, proposal *governance.Proposal) bool {
	// Set the proposal (ID already set in proposal)
	err := g.store.SetProposal(0, rlm, proposal.ID(), proposal)
	if err != nil {
		return false
	}

	// Add to the active snapshot index.
	snapshotIndex := g.store.GetActiveProposalsBySnapshot()
	snapshotIndex.Set(activeProposalSnapshotKey(proposal), proposal.ID())
	if err := g.store.SetActiveProposalsBySnapshot(0, rlm, snapshotIndex); err != nil {
		return false
	}

	// Add to user proposals
	err = g.store.AddUserProposal(0, rlm, proposal.Proposer().String(), proposal.ID())
	if err != nil {
		return false
	}

	return true
}

// removeActiveProposal removes a proposal from the active snapshot index.
func (g *governanceV1) removeActiveProposal(_ int, rlm realm, proposal *governance.Proposal) error {
	snapshotIndex := g.store.GetActiveProposalsBySnapshot()
	key := activeProposalSnapshotKey(proposal)
	if !snapshotIndex.Has(key) {
		return makeErrorWithDetails(errDataNotFound, ufmt.Sprintf("active proposal index entry not found, proposalID: %d", proposal.ID()))
	}
	snapshotIndex.Remove(key)

	return g.store.SetActiveProposalsBySnapshot(0, rlm, snapshotIndex)
}

// User proposals methods
func (g *governanceV1) getUserProposals(user string) []*governance.Proposal {
	proposalIDs, exists := g.store.GetUserProposalIDs(user)
	if !exists {
		return []*governance.Proposal{}
	}

	proposals := make([]*governance.Proposal, 0)

	for _, id := range proposalIDs {
		proposal, exists := g.store.GetProposal(id)
		if !exists {
			continue
		}

		proposals = append(proposals, proposal)
	}

	return proposals
}

// hasActiveProposal assumes removeInactiveUserProposals has already pruned stale proposals.
func (g *governanceV1) hasActiveProposal(proposerAddress address) bool {
	proposals := g.getUserProposals(proposerAddress.String())

	return len(proposals) > 0
}

// Remove inactive user proposals
// This function is used to remove inactive proposals from the user proposals list.
// It is used to clean up user's active proposal list when creating a new proposal.
func (g *governanceV1) removeInactiveUserProposals(_ int, rlm realm, proposerAddress address, current int64) error {
	proposals := g.getUserProposals(proposerAddress.String())

	for _, proposal := range proposals {
		proposalResolver := NewProposalResolver(proposal)

		if !proposalResolver.IsActive(current) {
			err := g.store.RemoveUserProposal(0, rlm, proposerAddress.String(), proposal.ID())
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// Proposal voting info methods
func (g *governanceV1) getProposalUserVotingInfos(proposalID int64) (*bptree.BPTree, bool) {
	return g.store.GetProposalVotingInfos(proposalID)
}

func (g *governanceV1) updateProposalUserVotes(_ int, rlm realm, proposal *governance.Proposal, userVotingInfos *bptree.BPTree) error {
	return g.store.SetProposalVotingInfos(0, rlm, proposal.ID(), userVotingInfos)
}

// Helper methods for API
func (g *governanceV1) mustGetProposal(id int64) *governance.Proposal {
	proposal, exists := g.getProposal(id)
	if !exists {
		panic(makeErrorWithDetails(errProposalNotFound, ufmt.Sprintf("proposal(%d) not found", id)))
	}
	return proposal
}

func (g *governanceV1) getProposalUserVotingInfo(proposalID int64, addr address) (governance.VotingInfo, bool) {
	votingInfosTree, exists := g.getProposalUserVotingInfos(proposalID)
	if !exists {
		return governance.DefaultVotingInfo(), false
	}

	votingInfoRaw := votingInfosTree.Get(addr.String())
	if votingInfoRaw == nil {
		return governance.DefaultVotingInfo(), false
	}
	votingInfo, ok := votingInfoRaw.(governance.VotingInfo)
	return votingInfo, ok
}

parameter_registry.gno

package governance

import (
	"strings"

	prbac "gno.land/p/gnoswap/rbac/v1"
	ufmt "gno.land/p/nt/ufmt/v0"

	cm "gno.land/r/gnoswap/common"
	cp "gno.land/r/gnoswap/community_pool/v1"
	en "gno.land/r/gnoswap/emission"
	"gno.land/r/gnoswap/rbac/v1"

	"gno.land/r/gnoswap/gov/governance"
	gs "gno.land/r/gnoswap/gov/staker"
	lp "gno.land/r/gnoswap/launchpad"
	pl "gno.land/r/gnoswap/pool"
	pos "gno.land/r/gnoswap/position"
	pf "gno.land/r/gnoswap/protocol_fee"
	rr "gno.land/r/gnoswap/router"
	sr "gno.land/r/gnoswap/staker"

	"gno.land/r/gnoswap/halt/v1"
)

// globalParameterRegistry is initialized once and reused for all validation and execution.
// This provides consistent validation at proposal creation time and execution time.
var globalParameterRegistry *ParameterRegistry

func init() {
	globalParameterRegistry = CreateParameterHandlers()
}

// Package paths
const (
	GNS_TOKEN_KEY       = "gno.land/r/gnoswap/gns.GNS"
	HALT_PATH           = "gno.land/r/gnoswap/halt/v1"
	RBAC_PATH           = "gno.land/r/gnoswap/rbac/v1"
	ACCESS_PATH         = "gno.land/r/gnoswap/access/v1"
	EMISSION_PATH       = "gno.land/r/gnoswap/emission"
	COMMON_PATH         = "gno.land/r/gnoswap/common"
	POOL_PATH           = "gno.land/r/gnoswap/pool"
	POSITION_PATH       = "gno.land/r/gnoswap/position"
	ROUTER_PATH         = "gno.land/r/gnoswap/router"
	STAKER_PATH         = "gno.land/r/gnoswap/staker"
	LAUNCHPAD_PATH      = "gno.land/r/gnoswap/launchpad"
	PROTOCOL_FEE_PATH   = "gno.land/r/gnoswap/protocol_fee"
	COMMUNITY_POOL_PATH = "gno.land/r/gnoswap/community_pool/v1"
	GOV_GOVERNANCE_PATH = "gno.land/r/gnoswap/gov/governance"
	GOV_STAKER_PATH     = "gno.land/r/gnoswap/gov/staker"
)

// ParameterHandler interface defines the contract for parameter execution handlers.
// Each handler is responsible for executing specific parameter changes in the system.
type ParameterHandler interface {
	// Execute processes the parameters and applies the changes to the system.
	// The `_ int, rlm realm` discriminator pair forwards the governance proxy's
	// realm value into the handler so any cross-realm calls inside the closure
	// run under the proxy's identity (the only address with caller-allowlist
	// permission against the targeted /r/ realms).
	//
	// Parameters:
	//   - _: integer discriminator required by the crossing entrypoint; callers use 0
	//   - rlm: current governance proxy realm context forwarded to the handler
	//   - params: serialized parameter values to validate and apply in handler order
	//
	// Returns:
	//   - error: nil when the parameter change succeeds, or an execution/validation error
	Execute(_ int, rlm realm, params []string) error
}

// ParameterHandlerOptions contains the configuration and execution logic for a parameter handler.
// This struct encapsulates all information needed to identify and execute a parameter change.
//
// NOTE: handlerFunc uses `rlm realm` (rather than `cur realm`) as the realm
// parameter name. The v2 preprocessor reserves the `cur` name for the first
// realm-type parameter of top-level crossing function declarations and
// `t.Run` closures only; using it as the realm-parameter name on a
// multi-parameter struct-field function value trips a parser check
// ("only the first realm type argument of a crossing function may have name
// `cur`"). Naming it `rlm` keeps the lowering identical without the syntax
// constraint.
type ParameterHandlerOptions struct {
	pkgPath            string                                   // Package path of the target contract
	function           string                                   // Function name to be called
	paramCount         int                                      // Expected number of parameters
	handlerFunc        func(_ int, rlm realm, _ []string) error // Function that executes the parameter change
	paramValidators    []paramValidator                         // Optional per-parameter validators for proposal-time checks
	compositeValidator compositeValidator                       // Optional cross-parameter validator for static business rules
}

// paramValidator validates a single parameter value and returns an error on failure.
type paramValidator func(string) error

// compositeValidator validates relationships between a handler's parameters.
// It must only enforce deterministic, state-independent rules so that a
// proposal is not rejected merely because on-chain state changes while voting.
type compositeValidator func([]string) error

// NewParameterHandlerOptions creates a new parameter handler with the specified configuration.
//
// Parameters:
//   - pkgPath: package path of the target contract
//   - function: function name to be called
//   - paramCount: expected number of parameters
//   - handlerFunc: callback receiving the discriminator, propagated realm, and serialized parameters to execute the change
//   - paramValidators: optional validators for each parameter (must match paramCount if provided)
//
// Returns:
//   - ParameterHandler: configured parameter handler interface
func NewParameterHandlerOptions(
	pkgPath,
	function string,
	paramCount int,
	handlerFunc func(_ int, rlm realm, _ []string) error,
	paramValidators ...paramValidator,
) ParameterHandler {
	if len(paramValidators) > 0 && len(paramValidators) != paramCount {
		panic(ufmt.Sprintf(
			"invalid validator count for %s:%s: expected %d, got %d",
			pkgPath, function, paramCount, len(paramValidators),
		))
	}

	return &ParameterHandlerOptions{
		pkgPath:         pkgPath,
		function:        function,
		paramCount:      paramCount,
		handlerFunc:     handlerFunc,
		paramValidators: paramValidators,
	}
}

// HandlerKey generates a unique key for this handler based on package path and function name.
//
// Returns:
//   - string: unique identifier for the handler
func (h *ParameterHandlerOptions) HandlerKey() string {
	return makeHandlerKey(h.pkgPath, h.function)
}

// Execute validates parameter count and executes the handler function.
// This method ensures the correct number of parameters are provided before execution.
//
// Parameters:
//   - _: integer discriminator required by the crossing entrypoint; callers use 0
//   - rlm: governance proxy realm threaded into the wrapped handler
//   - params: serialized parameter values to pass to the handler
//
// Returns:
//   - error: parameter-count error or the error returned by the wrapped handler
func (h *ParameterHandlerOptions) Execute(_ int, rlm realm, params []string) error {
	if len(params) != h.paramCount {
		return ufmt.Errorf("expected %d parameters, got %d", h.paramCount, len(params))
	}

	return h.handlerFunc(0, rlm, params)
}

// ValidateParams checks the parameter count and runs configured individual and composite validators without executing the handler.
//
// Parameters:
//   - params: serialized parameter values to validate in handler order
//
// Returns:
//   - error: nil when all configured checks pass, or the first count/type/business-rule validation error
func (h *ParameterHandlerOptions) ValidateParams(params []string) error {
	if len(params) != h.paramCount {
		return ufmt.Errorf(
			"expected %d parameters for %s, got %d",
			h.paramCount, h.HandlerKey(), len(params),
		)
	}

	if len(h.paramValidators) > 0 {
		if len(h.paramValidators) != h.paramCount {
			return ufmt.Errorf(
				"validator count mismatch for %s: expected %d validator(s), got %d",
				h.HandlerKey(), h.paramCount, len(h.paramValidators),
			)
		}

		for i, validator := range h.paramValidators {
			if validator == nil {
				continue
			}

			if err := validator(params[i]); err != nil {
				return ufmt.Errorf("param[%d]: %v", i, err)
			}
		}
	}

	if h.compositeValidator != nil {
		if err := h.compositeValidator(params); err != nil {
			return err
		}
	}

	return nil
}

// ParameterRegistry manages the collection of parameter handlers for governance execution.
// This registry allows proposals to execute parameter changes across different system contracts.
type ParameterRegistry struct {
	handlers map[string]ParameterHandlerOptions // Map storing handler configurations keyed by package:function
}

// Register adds a new parameter handler to the registry.
// Each handler is identified by a unique combination of package path and function name.
//
// Parameters:
//   - handler: parameter handler configuration to register
func (r *ParameterRegistry) Register(handler ParameterHandlerOptions) {
	r.handlers[handler.HandlerKey()] = handler
}

// Handler retrieves a parameter handler by its package:function key.
// This method is used during proposal execution to find the appropriate handler.
//
// Parameters:
//   - key: handler key returned by HandlerKey, in "pkgPath:function" format
//
// Returns:
//   - ParameterHandler: the matching parameter handler
//   - error: error if the key has no registered handler
func (r *ParameterRegistry) Handler(key string) (ParameterHandler, error) {
	// Retrieve handler from registry
	handler, exists := r.handlers[key]
	if !exists {
		return nil, ufmt.Errorf("handler not found for %s", key)
	}

	return &handler, nil
}

// NewParameterRegistry creates a new empty parameter registry.
//
// Returns:
//   - *ParameterRegistry: new registry instance
func NewParameterRegistry() *ParameterRegistry {
	return &ParameterRegistry{handlers: make(map[string]ParameterHandlerOptions)}
}

// makeHandlerKey creates a unique identifier for a handler based on package path and function.
//
// Parameters:
//   - pkgPath: package path of the target contract
//   - function: function name to be called
//
// Returns:
//   - string: unique key in format "pkgPath:function"
func makeHandlerKey(pkgPath, function string) string {
	return pkgPath + ":" + function
}

// CreateParameterHandlers initializes and configures all supported parameter handlers.
// This function defines all the parameter changes that can be executed through governance proposals.
// It covers configuration changes for various system components including pools, staking, fees, etc.
//
// Returns:
//   - *ParameterRegistry: fully configured registry with all supported handlers
func CreateParameterHandlers() *ParameterRegistry {
	registry := NewParameterRegistry()

	// Define all handler configurations for different system components.
	//
	// Each closure receives `(_ int, rlm realm, params []string)` and threads
	// `rlm` into the targeted /r/ realm call. The closure is invoked from
	// ParameterHandlerOptions.Execute which forwards the governance proxy's
	// realm value, so cross-realm calls land on the targeted realm with the
	// governance proxy as the immediate caller.
	handlers := []*ParameterHandlerOptions{
		// Community pool token transfers
		{
			pkgPath:    COMMUNITY_POOL_PATH,
			function:   "TransferToken",
			paramCount: 3,
			paramValidators: []paramValidator{
				stringValidator,  // pkgPath
				addressValidator, // to
				positiveInt64Validator("amount"),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Transfer tokens from community pool to specified address
				cp.TransferToken(
					cross(rlm),
					params[0],          // pkgPath
					address(params[1]), // to
					parseNumber(params[2], kindInt64).(int64), // amount
				)

				return nil
			},
		},
		// Emission distribution configuration
		{
			pkgPath:    EMISSION_PATH,
			function:   "SetDistributionStartTime",
			paramCount: 1,
			paramValidators: []paramValidator{
				numberValidator(kindInt64), // start time
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set distribution start time
				en.SetDistributionStartTime(cross(rlm), parseInt64(params[0]))

				return nil
			},
		},
		{
			pkgPath:    EMISSION_PATH,
			function:   "ChangeDistributionPct",
			paramCount: 4,
			paramValidators: []paramValidator{
				numberValidator(kindInt64), // liquidityStakerPct
				numberValidator(kindInt64), // devOpsPct
				numberValidator(kindInt64), // communityPoolPct
				numberValidator(kindInt64), // govStakerPct
			},
			compositeValidator: distributionPctCompositeValidator,
			handlerFunc: func(_ int, rlm realm, params []string) error {
				liquidityStakerPct := parseNumber(params[0], kindInt64).(int64)
				devOpsPct := parseNumber(params[1], kindInt64).(int64)
				communityPoolPct := parseNumber(params[2], kindInt64).(int64)
				govStakerPct := parseNumber(params[3], kindInt64).(int64)

				en.ChangeDistributionPct(
					cross(rlm),
					liquidityStakerPct,
					devOpsPct,
					communityPoolPct,
					govStakerPct,
				)

				return nil
			},
		},
		// Governance configuration changes
		{
			pkgPath:    GOV_GOVERNANCE_PATH,
			function:   "Reconfigure",
			paramCount: 7,
			paramValidators: []paramValidator{
				numberValidator(kindInt64), // votingStartDelay
				numberValidator(kindInt64), // votingPeriod
				numberValidator(kindInt64), // votingWeightSmoothingDuration
				numberValidator(kindInt64), // quorum
				numberValidator(kindInt64), // proposalCreationThreshold
				numberValidator(kindInt64), // executionDelay
				numberValidator(kindInt64), // executionWindow
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Parse governance configuration parameters
				votingStartDelay := parseInt64(params[0])
				votingPeriod := parseInt64(params[1])
				votingWeightSmoothingDuration := parseInt64(params[2])
				quorum := parseInt64(params[3])
				proposalCreationThreshold := parseInt64(params[4])
				executionDelay := parseInt64(params[5])
				executionWindow := parseInt64(params[6])

				// Reconfigure governance parameters through governance process
				governance.Reconfigure(
					cross(rlm),
					votingStartDelay,
					votingPeriod,
					votingWeightSmoothingDuration,
					quorum,
					proposalCreationThreshold,
					executionDelay,
					executionWindow,
				)

				return nil
			},
		},

		// Pool protocol fee configuration
		{
			pkgPath:    POOL_PATH,
			function:   "CollectProtocol",
			paramCount: 6,
			paramValidators: []paramValidator{
				stringValidator,  // token0Path
				stringValidator,  // token1Path
				uint64Validator,  // fee
				addressValidator, // recipient
				nonNegativeInt64Validator("amount0Requested"),
				nonNegativeInt64Validator("amount1Requested"),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				pl.CollectProtocol(
					cross(rlm),
					params[0],                      // token0Path
					params[1],                      // token1Path
					uint32(parseUint64(params[2])), // fee
					address(params[3]),             // recipient
					params[4],                      // amount0Requested
					params[5],                      // amount1Requested
				)

				return nil
			},
		},
		{
			pkgPath:    POOL_PATH,
			function:   "SetFeeProtocol",
			paramCount: 2,
			paramValidators: []paramValidator{
				uint8RangeValidator("feeProtocol0"),
				uint8RangeValidator("feeProtocol1"),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Parse and validate fee protocol values
				feeProtocol0 := parseInt64(params[0])
				feeProtocol1 := parseInt64(params[1])

				// Validate fee protocol values are within uint8 range
				if feeProtocol0 > 255 {
					panic(ufmt.Sprintf("feeProtocol0 out of range: %d", feeProtocol0))
				}

				if feeProtocol1 > 255 {
					panic(ufmt.Sprintf("feeProtocol1 out of range: %d", feeProtocol1))
				}

				// Set protocol fee percentages
				pl.SetFeeProtocol(
					cross(rlm),
					uint8(feeProtocol0), // feeProtocol0
					uint8(feeProtocol1), // feeProtocol1
				)

				return nil
			},
		},
		// Pool creation fee
		{
			pkgPath:    POOL_PATH,
			function:   "SetPoolCreationFee",
			paramCount: 1,
			paramValidators: []paramValidator{
				nonNegativeInt64Validator("fee"),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set fee required to create new pools
				pl.SetPoolCreationFee(cross(rlm), parseInt64(params[0])) // fee
				return nil
			},
		},
		// Pool withdrawal fee
		{
			pkgPath:    POOL_PATH,
			function:   "SetWithdrawalFee",
			paramCount: 1,
			paramValidators: []paramValidator{
				uint64RangeValidator("fee", 1000),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set fee for withdrawing from pools
				pl.SetWithdrawalFee(cross(rlm), parseUint64(params[0])) // fee
				return nil
			},
		},

		// Protocol fee distribution
		{
			pkgPath:    PROTOCOL_FEE_PATH,
			function:   "SetDevOpsPct",
			paramCount: 1,
			paramValidators: []paramValidator{
				int64RangeValidator("pct", 0, 10000),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set percentage of protocol fees going to development operations
				pf.SetDevOpsPct(cross(rlm), parseInt64(params[0])) // pct
				return nil
			},
		},

		// Router swap fee
		{
			pkgPath:    ROUTER_PATH,
			function:   "SetSwapFee",
			paramCount: 1,
			paramValidators: []paramValidator{
				uint64RangeValidator("fee", 1000),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set fee charged for token swaps
				rr.SetSwapFee(cross(rlm), parseUint64(params[0])) // fee
				return nil
			},
		},

		// Staker configuration handlers
		{
			pkgPath:    STAKER_PATH,
			function:   "SetDepositGnsAmount",
			paramCount: 1,
			paramValidators: []paramValidator{
				nonNegativeInt64Validator("amount"),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set minimum GNS amount required for staking deposits
				sr.SetDepositGnsAmount(cross(rlm), parseInt64(params[0])) // amount
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "SetMinimumRewardAmount",
			paramCount: 1,
			paramValidators: []paramValidator{
				nonNegativeInt64Validator("amount"),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set minimum GNS amount required for staking deposits
				sr.SetMinimumRewardAmount(cross(rlm), parseInt64(params[0])) // amount
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "SetTokenMinimumRewardAmount",
			paramCount: 1,
			paramValidators: []paramValidator{
				tokenMinimumRewardAmountValidator,
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set minimum GNS amount required for staking deposits
				// params[0] is a string in the format "tokenPath:amount"
				sr.SetTokenMinimumRewardAmount(cross(rlm), params[0]) // amount
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "SetPoolTier",
			paramCount: 2,
			paramValidators: []paramValidator{
				stringValidator, // pool
				uint64RangeValidator("tier", sr.AllTierCount-1),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Assign tier level to a specific pool
				sr.SetPoolTier(
					cross(rlm),
					params[0],              // pool
					parseUint64(params[1]), // tier
				)
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "ChangePoolTier",
			paramCount: 2,
			paramValidators: []paramValidator{
				stringValidator, // pool
				uint64RangeValidator("tier", sr.AllTierCount-1),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Change existing pool's tier level
				sr.ChangePoolTier(
					cross(rlm),
					params[0],              // pool
					parseUint64(params[1]), // tier
				)
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "RemovePoolTier",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // pool
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Remove tier assignment from a pool
				sr.RemovePoolTier(cross(rlm), params[0]) // pool
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "SetUnStakingFee",
			paramCount: 1,
			paramValidators: []paramValidator{
				uint64RangeValidator("fee", 1000),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set fee charged for unstaking operations
				fee := parseUint64(params[0])
				sr.SetUnStakingFee(cross(rlm), fee)
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "SetWarmUp",
			paramCount: 2,
			paramValidators: []paramValidator{
				numberValidator(kindInt64), // percent
				numberValidator(kindInt64), // block
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set warm-up period configuration for staking
				percent := parseInt64(params[0])
				block := parseNumber(params[1], kindInt64).(int64)
				sr.SetWarmUp(cross(rlm), percent, block)

				return nil
			},
		},

		// System halt controls
		{
			pkgPath:    HALT_PATH,
			function:   "SetHaltLevel",
			paramCount: 1,
			paramValidators: []paramValidator{
				haltLevelValidator,
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set system-wide halt status
				halt.SetHaltLevel(cross(rlm), halt.HaltLevel(params[0])) // true = halt, false = no halt

				return nil
			},
		},
		{
			pkgPath:    HALT_PATH,
			function:   "SetOperationStatus",
			paramCount: 2,
			paramValidators: []paramValidator{
				haltOperationTypeValidator,
				boolValidator, // allowed
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Enable or disable specific operation types
				opType := halt.OpType(params[0])
				allowed := parseBool(params[1])

				halt.SetOperationStatus(cross(rlm), opType, allowed)

				return nil
			},
		},

		// RBAC configuration
		{
			pkgPath:    RBAC_PATH,
			function:   "RegisterRole",
			paramCount: 2,
			paramValidators: []paramValidator{
				roleNameValidator,
				addressValidator, // roleAddress
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				roleName := params[0]
				roleAddress := address(params[1])

				// Register a new role
				rbac.RegisterRole(cross(rlm), roleName, roleAddress)

				return nil
			},
		},
		{
			pkgPath:    RBAC_PATH,
			function:   "UpdateRoleAddress",
			paramCount: 2,
			paramValidators: []paramValidator{
				updatableRoleNameValidator,
				addressValidator, // roleAddress
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				roleName := params[0]
				roleAddress := address(params[1])

				// Update role address
				rbac.UpdateRoleAddress(cross(rlm), roleName, roleAddress)

				return nil
			},
		},
		{
			pkgPath:    RBAC_PATH,
			function:   "RemoveRole",
			paramCount: 1,
			paramValidators: []paramValidator{
				removableRoleNameValidator,
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				roleName := params[0]

				// Remove role
				rbac.RemoveRole(cross(rlm), roleName)

				return nil
			},
		},

		// Protocol fee - SetGovStakerPct
		{
			pkgPath:    PROTOCOL_FEE_PATH,
			function:   "SetGovStakerPct",
			paramCount: 1,
			paramValidators: []paramValidator{
				int64RangeValidator("pct", 0, 10000),
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Set percentage of protocol fees going to governance stakers
				pf.SetGovStakerPct(cross(rlm), parseInt64(params[0])) // pct
				return nil
			},
		},

		// Staker - Token list management
		{
			pkgPath:    STAKER_PATH,
			function:   "AddToken",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // tokenPath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Add token to allowed token list for external incentives
				sr.AddToken(cross(rlm), params[0]) // tokenPath
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "RemoveToken",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // tokenPath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Remove token from allowed token list
				sr.RemoveToken(cross(rlm), params[0]) // tokenPath
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "SetDeniedRewardToken",
			paramCount: 2,
			paramValidators: []paramValidator{
				stringValidator, // tokenPath
				boolValidator,   // denied
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Deny or re-allow a token as an external incentive reward token
				sr.SetDeniedRewardToken(cross(rlm), params[0], parseBool(params[1]))
				return nil
			},
		},

		// Staker - External incentive recovery
		{
			pkgPath:    STAKER_PATH,
			function:   "CancelExternalIncentive",
			paramCount: 2,
			paramValidators: []paramValidator{
				stringValidator, // targetPoolPath
				stringValidator, // incentiveId
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Cancel a not-yet-started external incentive; the reward tokens
				// and the GNS deposit are refunded to the incentive creator
				sr.CancelExternalIncentive(
					cross(rlm),
					params[0], // targetPoolPath
					params[1], // incentiveId
				)
				return nil
			},
		},

		// Launchpad - Project management
		{
			pkgPath:    LAUNCHPAD_PATH,
			function:   "CreateProject",
			paramCount: 10,
			paramValidators: []paramValidator{
				stringValidator,            // name
				stringValidator,            // tokenPath
				addressValidator,           // recipient
				numberValidator(kindInt64), // depositAmount
				stringValidator,            // conditionTokens
				stringValidator,            // conditionAmounts
				numberValidator(kindInt64), // tier30Ratio
				numberValidator(kindInt64), // tier90Ratio
				numberValidator(kindInt64), // tier180Ratio
				numberValidator(kindInt64), // startTime
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Create a new launchpad project
				lp.CreateProject(
					cross(rlm),
					params[0],          // name
					params[1],          // tokenPath
					address(params[2]), // recipient
					parseNumber(params[3], kindInt64).(int64), // depositAmount
					params[4], // conditionTokens
					params[5], // conditionAmounts
					parseNumber(params[6], kindInt64).(int64), // tier30Ratio
					parseNumber(params[7], kindInt64).(int64), // tier90Ratio
					parseNumber(params[8], kindInt64).(int64), // tier180Ratio
					parseNumber(params[9], kindInt64).(int64), // startTime
				)
				return nil
			},
		},
		// Upgrade handlers for various domains
		{
			pkgPath:    POOL_PATH,
			function:   "UpgradeImpl",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // packagePath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Upgrade pool implementation
				pl.UpgradeImpl(cross(rlm), params[0]) // packagePath
				return nil
			},
		},
		{
			pkgPath:    POSITION_PATH,
			function:   "UpgradeImpl",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // packagePath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Upgrade position implementation
				pos.UpgradeImpl(cross(rlm), params[0]) // packagePath
				return nil
			},
		},
		{
			pkgPath:    STAKER_PATH,
			function:   "UpgradeImpl",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // packagePath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Upgrade staker implementation
				sr.UpgradeImpl(cross(rlm), params[0]) // packagePath
				return nil
			},
		},
		{
			pkgPath:    LAUNCHPAD_PATH,
			function:   "UpgradeImpl",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // packagePath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Upgrade launchpad implementation
				lp.UpgradeImpl(cross(rlm), params[0]) // packagePath
				return nil
			},
		},
		{
			pkgPath:    GOV_GOVERNANCE_PATH,
			function:   "UpgradeImpl",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // targetPackagePath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Upgrade governance implementation
				governance.UpgradeImpl(cross(rlm), params[0]) // packagePath
				return nil
			},
		},
		{
			pkgPath:    GOV_STAKER_PATH,
			function:   "UpgradeImpl",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // packagePath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Upgrade gov staker implementation
				gs.UpgradeImpl(cross(rlm), params[0]) // packagePath
				return nil
			},
		},
		{
			pkgPath:    ROUTER_PATH,
			function:   "UpgradeImpl",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // packagePath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Upgrade router implementation
				rr.UpgradeImpl(cross(rlm), params[0]) // packagePath
				return nil
			},
		},
		{
			pkgPath:    PROTOCOL_FEE_PATH,
			function:   "UpgradeImpl",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // packagePath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Upgrade protocol fee implementation
				pf.UpgradeImpl(cross(rlm), params[0]) // packagePath
				return nil
			},
		},
		{
			pkgPath:    COMMON_PATH,
			function:   "UpgradeImpl",
			paramCount: 1,
			paramValidators: []paramValidator{
				stringValidator, // packagePath
			},
			handlerFunc: func(_ int, rlm realm, params []string) error {
				// Upgrade common (token resolution) implementation
				cm.UpgradeImpl(cross(rlm), params[0]) // packagePath
				return nil
			},
		},
	}

	// Register all configured handlers in the registry
	registerHandlers(registry, handlers)

	return registry
}

// registerHandlers batch registers all configured handlers into the registry.
// This helper function processes the handler configuration array and adds each handler to the registry.
//
// Parameters:
//   - registry: the parameter registry to add handlers to
//   - handlerOptions: slice of handler configurations to register
func registerHandlers(registry *ParameterRegistry, handlerOptions []*ParameterHandlerOptions) {
	for _, handlerOption := range handlerOptions {
		registry.Register(*handlerOption)
	}
}

// runValidator executes a validator function and converts panics to errors.
func runValidator(fn func()) (err error) {
	defer func() {
		if r := recover(); r != nil {
			if e, ok := r.(error); ok {
				err = e
				return
			}
			err = ufmt.Errorf("%v", r)
		}
	}()

	fn()
	return nil
}

// Basic reusable validators for proposal-time type checking.
var (
	stringValidator = func(s string) error {
		return nil
	}
	boolValidator = func(s string) error {
		return runValidator(func() {
			parseBool(s)
		})
	}
	uint64Validator = func(s string) error {
		return runValidator(func() {
			parseUint64(s)
		})
	}
	addressValidator = func(s string) error {
		return runValidator(func() {
			addr := address(s)
			if !addr.IsValid() {
				panic(ufmt.Sprintf("invalid address: %s", addr))
			}
		})
	}
)

func numberValidator(kind numberKind) paramValidator {
	return func(s string) error {
		return runValidator(func() {
			parseNumber(s, kind)
		})
	}
}

func uint8RangeValidator(name string) paramValidator {
	return func(s string) error {
		return runValidator(func() {
			value := parseInt64(s)
			if value < 0 || value > 255 {
				panic(ufmt.Sprintf("%s out of range: %d", name, value))
			}
		})
	}
}

func roleNameValidator(s string) error {
	return runValidator(func() {
		roleName := strings.TrimSpace(s)
		if roleName == "" {
			panic(ufmt.Sprintf("role name is empty: %q", s))
		}
	})
}

func updatableRoleNameValidator(s string) error {
	return runValidator(func() {
		roleName := strings.TrimSpace(s)
		if err := roleNameValidator(roleName); err != nil {
			panic(err)
		}

		if roleName == prbac.ROLE_ADMIN.String() {
			panic(ufmt.Sprintf("admin role cannot be updated: %s", roleName))
		}
	})
}

func removableRoleNameValidator(s string) error {
	return runValidator(func() {
		roleName := strings.TrimSpace(s)
		if err := roleNameValidator(roleName); err != nil {
			panic(err)
		}

		if prbac.IsSystemRole(roleName) {
			panic(ufmt.Sprintf("system role cannot be removed: %s", roleName))
		}
	})
}

func nonNegativeInt64Validator(name string) paramValidator {
	return func(s string) error {
		return runValidator(func() {
			value := parseInt64(s)
			if value < 0 {
				panic(ufmt.Sprintf("%s must be non-negative: %d", name, value))
			}
		})
	}
}

func positiveInt64Validator(name string) paramValidator {
	return func(s string) error {
		return runValidator(func() {
			value := parseInt64(s)
			if value <= 0 {
				panic(ufmt.Sprintf("%s must be positive: %d", name, value))
			}
		})
	}
}

func int64RangeValidator(name string, min, max int64) paramValidator {
	return func(s string) error {
		return runValidator(func() {
			value := parseInt64(s)
			if value < min || value > max {
				panic(ufmt.Sprintf("%s must be in range %d to %d: %d", name, min, max, value))
			}
		})
	}
}

func uint64RangeValidator(name string, max uint64) paramValidator {
	return func(s string) error {
		return runValidator(func() {
			value := parseUint64(s)
			if value > max {
				panic(ufmt.Sprintf("%s must be in range 0 to %d: %d", name, max, value))
			}
		})
	}
}

func haltLevelValidator(s string) error {
	return runValidator(func() {
		if !halt.HaltLevel(s).IsValid() {
			panic(ufmt.Sprintf("invalid halt level: %s", s))
		}
	})
}

func haltOperationTypeValidator(s string) error {
	return runValidator(func() {
		if !halt.OpType(s).IsValid() {
			panic(ufmt.Sprintf("invalid operation type: %s", s))
		}
	})
}

func tokenMinimumRewardAmountValidator(s string) error {
	return runValidator(func() {
		parts := strings.SplitN(s, ":", 2)
		if len(parts) != 2 || parts[0] == "" {
			panic("token minimum reward amount must be tokenPath:amount")
		}
		amount := parseInt64(parts[1])
		if amount < 0 {
			panic(ufmt.Sprintf("minimum reward amount must be non-negative: %d", amount))
		}
	})
}

func distributionPctCompositeValidator(params []string) error {
	return runValidator(func() {
		sum := int64(0)
		for i, param := range params {
			pct := parseInt64(param)
			if pct < 0 || pct > 10000 {
				panic(ufmt.Sprintf("percentage %d must be in range 0 to 10000: %d", i+1, pct))
			}
			sum += pct
		}
		if sum != 10000 {
			panic(ufmt.Sprintf("sum of percentages must be 10000, got %d", sum))
		}
	})
}

func splitExecutionsRaw(executions string) []string {
	if executions == "" {
		return []string{}
	}

	return strings.Split(executions, messageSeparator)
}

func parseExecutionMessage(msg string) (pkgPath string, function string, params []string, partCount int) {
	parts := strings.Split(msg, parameterSeparator)
	partCount = len(parts)
	if partCount != 3 {
		return "", "", nil, partCount
	}

	pkgPath = parts[0]
	function = parts[1]
	if parts[2] == "" {
		return pkgPath, function, []string{}, partCount
	}

	return pkgPath, function, strings.Split(parts[2], ","), partCount
}

// validateExecutions validates that all executions in a parameter change proposal
// correspond to registered handlers in the global parameter registry.
// This function performs comprehensive validation including:
// - Basic format validation (count, structure)
// - Handler existence verification in the registry
// - Parameter count validation against handler expectations
//
// Parameters:
//   - numToExecute: number of parameter changes to execute
//   - msgs: pre-split slice of execution messages, where each message
//     is formatted as <pkgPath>*EXE*<function>*EXE*<params>
//
// Returns:
//   - error: validation error if any execution is invalid
func validateExecutions(numToExecute int64, msgs []string) error {
	// Validate execution count is positive
	if numToExecute <= 0 {
		return makeErrorWithDetails(
			errInvalidInput,
			"numToExecute is less than or equal to 0",
		)
	}

	// Check if executions are empty
	if len(msgs) == 0 {
		return makeErrorWithDetails(
			errInvalidInput,
			"executions is empty",
		)
	}

	// Validate execution count doesn't exceed maximum
	if numToExecute > maxNumberOfExecution {
		return makeErrorWithDetails(
			errInvalidInput,
			ufmt.Sprintf("numToExecute is greater than %d", maxNumberOfExecution),
		)
	}

	msgCount := len(msgs)
	// Validate execution count matches message count
	if msgCount != int(numToExecute) {
		return makeErrorWithDetails(
			errInvalidInput,
			ufmt.Sprintf("executions count (%d) does not match numToExecute (%d)", len(msgs), numToExecute),
		)
	}

	// Parse and validate each execution message
	for i, execution := range msgs {
		pkgPath, function, params, partCount := parseExecutionMessage(execution)
		if partCount != 3 {
			// Provide more helpful error message based on what's wrong
			detail := ufmt.Sprintf("execution[%d]: expected 3 parts (pkgPath, function, params), got %d", i, partCount)
			return makeErrorWithDetails(
				errInvalidMessageFormat,
				detail,
			)
		}

		// Validate package path and function are not empty
		if pkgPath == "" {
			return makeErrorWithDetails(
				errInvalidInput,
				ufmt.Sprintf("execution[%d]: package path is empty", i),
			)
		}

		if function == "" {
			return makeErrorWithDetails(
				errInvalidInput,
				ufmt.Sprintf("execution[%d]: function name is empty", i),
			)
		}

		// Check if handler exists in registry
		key := makeHandlerKey(pkgPath, function)
		handler, err := globalParameterRegistry.Handler(key)
		if err != nil {
			return makeErrorWithDetails(
				errInvalidExecution,
				ufmt.Sprintf("execution[%d]: %s (key: %s)", i, err.Error(), key),
			)
		}

		// Get expected parameter count from handler
		handlerOpts, ok := handler.(*ParameterHandlerOptions)
		if !ok {
			return makeErrorWithDetails(
				errInvalidExecution,
				ufmt.Sprintf("execution[%d]: failed to get handler options", i),
			)
		}

		// Validate parameter types/format ahead of proposal creation
		if err := handlerOpts.ValidateParams(params); err != nil {
			return makeErrorWithDetails(
				errInvalidInput,
				ufmt.Sprintf("execution[%d]: %v", i, err),
			)
		}
	}

	return nil
}

proposal.gno

package governance

import (
	"errors"

	"gno.land/r/gnoswap/gov/governance"
)

type ProposalResolver struct {
	*governance.Proposal
	statusResolver   *ProposalStatusResolver
	dataResolver     *ProposalDataResolver
	metadataResolver *ProposalMetadataResolver
}

// NewProposalResolver wraps a persisted governance proposal and initializes
// resolvers for its status, type-specific data, and metadata.
//
// Parameters:
//   - proposal: persisted proposal to resolve
//
// Returns:
//   - *ProposalResolver: resolver backed by proposal and its nested state
func NewProposalResolver(proposal *governance.Proposal) *ProposalResolver {
	statusResolver := NewProposalStatusResolver(proposal.Status())
	dataResolver := NewProposalDataResolver(proposal.Data())
	metadataResolver := NewProposalMetadataResolver(proposal.Metadata())
	return &ProposalResolver{
		Proposal:         proposal,
		statusResolver:   statusResolver,
		dataResolver:     dataResolver,
		metadataResolver: metadataResolver,
	}
}

// VotingTotalWeight returns the total weight of all votes cast by combining
// the proposal's yes and no tallies.
//
// Returns:
//   - int64: combined weight of all recorded votes
func (r *ProposalResolver) VotingTotalWeight() int64 {
	return r.statusResolver.TotalVoteWeight()
}

// IsActive determines whether the proposal is active at current.
// Upcoming, voting, and passed executable proposals are active; rejected,
// expired, executed, canceled, and passed text proposals are inactive.
//
// Parameters:
//   - current: timestamp at which the proposal status is evaluated
//
// Returns:
//   - bool: true when the proposal can still be voted on or executed at current
func (r *ProposalResolver) IsActive(current int64) bool {
	// Calculate status once and reuse to avoid redundant computations
	status := r.statusResolver.StatusType(current)

	switch status {
	case governance.StatusRejected,
		governance.StatusExpired,
		governance.StatusExecuted,
		governance.StatusCanceled:
		return false
	case governance.StatusPassed:
		// Text proposals become inactive once they pass (no execution needed)
		return !r.IsTextType()
	default:
		// StatusUpcoming, StatusActive, StatusExecutable are considered active
		return true
	}
}

// Validate performs comprehensive validation of the proposal's type-specific
// data and metadata before the proposal is stored.
//
// Returns:
//   - error: nil when both data and metadata validate; the first validation error otherwise
func (r *ProposalResolver) Validate() error {
	// Validate type-specific proposal data
	if err := r.dataResolver.Validate(); err != nil {
		return err
	}

	// Validate proposal metadata (title and description)
	if err := r.metadataResolver.Validate(); err != nil {
		return err
	}

	return nil
}

// Status returns the current status string of the proposal at current.
//
// Parameters:
//   - current: timestamp at which the proposal status is evaluated
//
// Returns:
//   - string: human-readable status name for the proposal at current
func (r *ProposalResolver) Status(current int64) string {
	return r.statusResolver.StatusType(current).String()
}

// StatusType returns the current status type of the proposal at current.
//
// Parameters:
//   - current: timestamp at which the proposal status is evaluated
//
// Returns:
//   - governance.ProposalStatusType: lifecycle status at current
func (r *ProposalResolver) StatusType(current int64) governance.ProposalStatusType {
	return r.statusResolver.StatusType(current)
}

// IsVotingPeriod reports whether votedAt falls within the proposal's active
// voting status.
//
// Parameters:
//   - votedAt: timestamp at which voting eligibility is checked
//
// Returns:
//   - bool: true when the proposal status at votedAt is StatusActive
func (r *ProposalResolver) IsVotingPeriod(votedAt int64) bool {
	return r.StatusType(votedAt) == governance.StatusActive
}

// IsExecutable determines whether the proposal can be executed at current.
// The proposal type must support execution and its status must be executable.
//
// Parameters:
//   - current: timestamp at which execution eligibility is evaluated
//
// Returns:
//   - bool: true when this type and current lifecycle state permit execution
func (r *ProposalResolver) IsExecutable(current int64) bool {
	// Only certain proposal types can be executed
	if !r.dataResolver.ProposalType().IsExecutable() {
		return false
	}

	return r.statusResolver.IsExecutable(current)
}

// CommunityPoolSpendTokenPath returns the token path for a community pool spend proposal.
// It returns an empty string when the proposal has no community-pool spend data.
//
// Returns:
//   - string: token package path to spend, or empty string for other proposal types
func (r *ProposalResolver) CommunityPoolSpendTokenPath() string {
	if r.Data() == nil {
		return ""
	}

	communityPoolSpend := r.dataResolver.CommunityPoolSpend()
	if communityPoolSpend == nil {
		return ""
	}

	return communityPoolSpend.TokenPath()
}

// Vote records a vote for this proposal and updates its yes or no tally.
// This is an internal method called during the voting process.
//
// Parameters:
//   - votedYes: true to add weight to the yes tally; false to add it to no
//   - weight: voting weight to add to the selected tally
//
// Returns:
//   - error: nil when the selected tally is updated; an error from vote-status validation otherwise
func (r *ProposalResolver) Vote(votedYes bool, weight int64) error {
	return r.statusResolver.vote(votedYes, weight)
}

// execute marks the proposal as executed and records execution details.
// This method validates execution conditions before proceeding.
func (r *ProposalResolver) execute(
	executedAt, executedHeight int64,
	executedBy address,
) error {
	// Verify proposal is in executable state
	if !r.IsExecutable(executedAt) {
		return errors.New(errProposalNotExecutable)
	}

	// Mark proposal as executed
	return r.statusResolver.execute(executedAt, executedHeight, executedBy)
}

// cancel marks the proposal as canceled and records cancellation details.
// This method validates cancellation conditions before proceeding.
func (r *ProposalResolver) cancel(
	canceledAt, canceledHeight int64,
	canceledBy address,
) error {
	if r.statusResolver.IsCanceled(canceledAt) {
		return errors.New(errAlreadyCanceledProposal)
	}

	if !r.statusResolver.IsUpcoming(canceledAt) {
		return errors.New(errUnableToCancelVotingProposal)
	}

	// Mark proposal as canceled
	return r.statusResolver.cancel(canceledAt, canceledHeight, canceledBy)
}

proposal_action_status.gno

package governance

import (
	"errors"

	"gno.land/r/gnoswap/gov/governance"
)

type ProposalActionStatusResolver struct {
	*governance.ProposalActionStatus
}

// NewProposalActionStatusResolver wraps a proposal action status for mutation
// and execution-state queries.
//
// Parameters:
//   - status: proposal action status to resolve and update.
//
// Returns:
//   - *ProposalActionStatusResolver: resolver backed by status.
func NewProposalActionStatusResolver(status *governance.ProposalActionStatus) *ProposalActionStatusResolver {
	return &ProposalActionStatusResolver{status}
}

// cancel marks the proposal as canceled and records cancellation details.
// This method validates that the proposal is eligible for cancellation.
//
// Parameters:
//   - canceledAt: timestamp when cancellation occurred
//   - canceledHeight: block height when cancellation occurred
//   - canceledBy: address performing the cancellation
//
// Returns:
//   - error: already canceled error if proposal action status is already canceled
func (p *ProposalActionStatusResolver) cancel(
	canceledAt, canceledHeight int64,
	canceledBy address,
) error {
	if p.Canceled() {
		return errors.New(errAlreadyCanceledProposal)
	}

	// Record cancellation details
	p.SetCanceled(true)
	p.SetCanceledAt(canceledAt)
	p.SetCanceledHeight(canceledHeight)
	p.SetCanceledBy(canceledBy)

	return nil
}

// Execute marks the proposal as executed and records execution details.
// This method validates that the proposal is eligible for execution.
//
// Parameters:
//   - executedAt: Unix timestamp when execution occurred.
//   - executedHeight: block height when execution occurred.
//   - executedBy: address performing the execution.
//
// Returns:
//   - error: nil on success; an error when the proposal is not executable or
//     has already been canceled.
func (p *ProposalActionStatusResolver) Execute(
	executedAt, executedHeight int64,
	executedBy address,
) error {
	// Only executable proposals can be executed (text proposals cannot)
	if !p.IsExecutable() {
		return errors.New(errProposalNotExecutable)
	}

	if p.Canceled() {
		return errors.New(errAlreadyCanceledProposal)
	}

	// Record execution details
	p.SetExecuted(true)
	p.SetExecutedAt(executedAt)
	p.SetExecutedHeight(executedHeight)
	p.SetExecutedBy(executedBy)

	return nil
}

proposal_data.gno

package governance

import (
	"strings"

	"gno.land/p/gnoswap/utils/v1"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/gov/governance"
)

type ProposalMetadataResolver struct {
	*governance.ProposalMetadata
}

// NewProposalMetadataResolver wraps proposal metadata for validation.
//
// Parameters:
//   - metadata: proposal title and description to validate.
//
// Returns:
//   - *ProposalMetadataResolver: resolver backed by metadata.
func NewProposalMetadataResolver(metadata *governance.ProposalMetadata) *ProposalMetadataResolver {
	return &ProposalMetadataResolver{
		ProposalMetadata: metadata,
	}
}

// Validate performs comprehensive validation of the proposal metadata.
// Checks title and description length and content requirements.
//
// Returns:
//   - error: validation error if metadata is invalid
func (r *ProposalMetadataResolver) Validate() error {
	// Validate title meets requirements
	if err := r.validateTitle(r.Title()); err != nil {
		return err
	}

	// Validate description meets requirements
	if err := r.validateDescription(r.Description()); err != nil {
		return err
	}

	return nil
}

// validateTitle checks if the proposal title meets length and content requirements.
//
// Parameters:
//   - title: title string to validate
//
// Returns:
//   - error: validation error if title is invalid
func (r *ProposalMetadataResolver) validateTitle(title string) error {
	// Title cannot be empty
	if title == "" {
		return makeErrorWithDetails(errInvalidInput, "title is empty")
	}

	// Title cannot exceed maximum length
	if len(title) > maxTitleLength {
		return makeErrorWithDetails(
			errInvalidInput,
			"title is too long, max length is 255 characters",
		)
	}

	return nil
}

// validateDescription checks if the proposal description meets length and content requirements.
//
// Parameters:
//   - description: description string to validate
//
// Returns:
//   - error: validation error if description is invalid
func (r *ProposalMetadataResolver) validateDescription(description string) error {
	// Description cannot be empty
	if description == "" {
		return makeErrorWithDetails(
			errInvalidInput,
			"description is empty",
		)
	}

	// Description cannot exceed maximum length
	if len(description) > maxDescriptionLength {
		return makeErrorWithDetails(
			errInvalidInput,
			"description is too long, max length is 10,000 characters",
		)
	}

	return nil
}

// ProposalDataResolver handles business logic for proposal data.
type ProposalDataResolver struct {
	*governance.ProposalData
}

// NewProposalDataResolver wraps proposal data for type-specific validation and
// execution-message parsing.
//
// Parameters:
//   - proposalData: proposal data to resolve and validate.
//
// Returns:
//   - *ProposalDataResolver: resolver backed by proposalData.
func NewProposalDataResolver(proposalData *governance.ProposalData) *ProposalDataResolver {
	return &ProposalDataResolver{
		ProposalData: proposalData,
	}
}

// Validate performs type-specific validation of the proposal data.
// Different proposal types have different validation requirements.
//
// Returns:
//   - error: validation error if data is invalid
func (r *ProposalDataResolver) Validate() error {
	switch r.ProposalType() {
	case governance.Text:
		return r.validateText()
	case governance.CommunityPoolSpend:
		return r.validateCommunityPoolSpend()
	case governance.ParameterChange:
		return r.validateParameterChange()
	}
	return nil
}

// validateText validates text proposal data.
// Text proposals have no additional validation requirements.
//
// Returns:
//   - error: always nil for text proposals
func (r *ProposalDataResolver) validateText() error {
	return nil
}

// validateCommunityPoolSpend validates community pool spend proposal data.
// Checks recipient address, token path, and amount validity.
//
// Returns:
//   - error: validation error if community pool spend data is invalid
func (r *ProposalDataResolver) validateCommunityPoolSpend() error {
	// Validate recipient address
	communityPoolSpend := r.ProposalData.CommunityPoolSpend()
	if communityPoolSpend == nil {
		return makeErrorWithDetails(
			errInvalidInput, "community pool spend info is missing")
	}

	if !communityPoolSpend.To().IsValid() {
		return makeErrorWithDetails(
			errInvalidInput, "to is invalid address")
	}

	// Validate amount is greater than 0
	if communityPoolSpend.Amount() <= 0 {
		return makeErrorWithDetails(
			errInvalidInput, "amount is not positive")
	}

	return nil
}

// validateParameterChange validates parameter change proposal data.
// Delegates to validateExecutions for full validation including count checks,
// message format, handler existence, and parameter type validation.
//
// Returns:
//   - error: validation error if parameter change data is invalid
func (r *ProposalDataResolver) validateParameterChange() error {
	execution := r.Execution()
	if execution == nil {
		return makeErrorWithDetails(
			errInvalidInput,
			"execution info is missing",
		)
	}
	return validateExecutions(execution.Num(), execution.Msgs())
}

// ParameterChangesInfos parses the execution messages and returns structured parameter change information.
// Each message is expected to be in format: pkgPath*EXE*function*EXE*params
//
// Returns:
//   - []ParameterChangeInfo: slice of parsed parameter change information
//   - error: validation error if any execution message is malformed
func (r *ProposalDataResolver) ParameterChangesInfos() ([]governance.ParameterChangeInfo, error) {
	infos := make([]governance.ParameterChangeInfo, 0)

	// Return empty slice if no executions
	execution := r.Execution()
	if execution == nil || execution.Num() <= 0 {
		return infos, nil
	}

	// Parse each execution message
	for _, msg := range execution.Msgs() {
		pkgPath, function, params, partCount := parseExecutionMessage(msg)
		if partCount != 3 {
			return nil, makeErrorWithDetails(
				errInvalidMessageFormat,
				ufmt.Sprintf("malformed execution message: expected 3 parts (pkgPath, function, params), got %d", partCount),
			)
		}

		// Create parameter change info structure
		info := governance.NewParameterChangeInfo(pkgPath, function, params)
		infos = append(infos, info)
	}

	return infos, nil
}

// NewProposalTextData creates proposal data for a text proposal.
// Text proposals have no additional data requirements.
//
// Returns:
//   - *ProposalData: proposal data configured for text proposal
func NewProposalTextData() *governance.ProposalData {
	return governance.NewProposalData(governance.Text, nil, nil)
}

// NewProposalCommunityPoolSpendData creates proposal data for a community pool spend proposal.
// Automatically generates the execution message for the token transfer.
//
// Parameters:
//   - tokenPath: path of the token to transfer
//   - to: recipient address for the transfer
//   - amount: amount of tokens to transfer
//   - communityPoolPackagePath: package path of the community pool contract
//
// Returns:
//   - *ProposalData: proposal data configured for community pool spending
func NewProposalCommunityPoolSpendData(
	tokenPath string,
	to address,
	amount int64,
	communityPoolPackagePath string,
) *governance.ProposalData {
	// Create execution message for the token transfer
	executionInfoMessage := makeExecuteMessage(
		communityPoolPackagePath,
		"TransferToken",
		[]string{tokenPath, to.String(), utils.FormatInt(amount)},
	)

	return governance.NewProposalData(
		governance.CommunityPoolSpend,
		governance.NewCommunityPoolSpendInfo(to, tokenPath, amount),
		governance.NewExecutionInfo(1, []string{executionInfoMessage}),
	)
}

// NewProposalExecutionData creates proposal data for a parameter change proposal.
// Each message in executions should be formatted as <pkgPath>*EXE*<function>*EXE*<params>,
// separated by *GOV* when there are multiple messages.
//
// Parameters:
//   - numToExecute: number of parameter changes to execute
//   - executions: raw encoded execution string with parameter changes
//
// Returns:
//   - *ProposalData: proposal data configured for parameter changes
func NewProposalExecutionData(numToExecute int64, executions string) *governance.ProposalData {
	return governance.NewProposalData(
		governance.ParameterChange,
		nil,
		governance.NewExecutionInfo(numToExecute, splitExecutionsRaw(executions)),
	)
}

// makeExecuteMessage creates a message to execute a function.
// Message format: <pkgPath>*EXE*<function>*EXE*<params>.
func makeExecuteMessage(pkgPath, function string, params []string) string {
	messageParams := []string{
		pkgPath,
		function,
		strings.Join(params, ","),
	}
	return strings.Join(messageParams, parameterSeparator)
}

proposal_schedule_status.gno

package governance

import (
	gnsmath "gno.land/p/gnoswap/gnsmath/v1"

	"gno.land/r/gnoswap/gov/governance"
)

type ProposalScheduleStatusResolver struct {
	*governance.ProposalScheduleStatus
}

// NewProposalScheduleStatusResolver wraps a proposal schedule for phase-boundary queries.
//
// Parameters:
//   - status: proposal schedule containing creation, voting, and execution timestamps
//
// Returns:
//   - *ProposalScheduleStatusResolver: resolver backed by status
func NewProposalScheduleStatusResolver(status *governance.ProposalScheduleStatus) *ProposalScheduleStatusResolver {
	return &ProposalScheduleStatusResolver{status}
}

// IsPassedCreatedAt checks if the current time has passed the proposal creation time.
// This is always true once a proposal exists.
//
// Parameters:
//   - current: timestamp to check against
//
// Returns:
//   - bool: true if current time is at or after creation time
func (p *ProposalScheduleStatusResolver) IsPassedCreatedAt(current int64) bool {
	return p.CreateTime() <= current
}

// IsPassedActiveAt checks if the current time has passed the voting start time.
// When true, the proposal enters its active voting period.
//
// Parameters:
//   - current: timestamp to check against
//
// Returns:
//   - bool: true if voting period has started
func (p *ProposalScheduleStatusResolver) IsPassedActiveAt(current int64) bool {
	return p.ActiveTime() <= current
}

// IsPassedVotingEndedAt checks if the current time has passed the voting end time.
// When true, no more votes can be cast on the proposal.
//
// Parameters:
//   - current: timestamp to check against
//
// Returns:
//   - bool: true if voting period has ended
func (p *ProposalScheduleStatusResolver) IsPassedVotingEndedAt(current int64) bool {
	return p.VotingEndTime() <= current
}

// IsPassedExecutableAt checks if the current time has passed the execution start time.
// When true, approved proposals can be executed (after execution delay).
//
// Parameters:
//   - current: timestamp to check against
//
// Returns:
//   - bool: true if execution window has started
func (p *ProposalScheduleStatusResolver) IsPassedExecutableAt(current int64) bool {
	return p.ExecutableTime() <= current
}

// IsPassedExpiredAt checks if the current time has passed the execution expiration time.
// When true, the proposal can no longer be executed and has expired.
//
// Parameters:
//   - current: timestamp to check against
//
// Returns:
//   - bool: true if execution window has expired
func (p *ProposalScheduleStatusResolver) IsPassedExpiredAt(current int64) bool {
	return p.ExpiredTime() <= current
}

// NewProposalScheduleStatus creates a new schedule status with calculated timestamps.
// This constructor takes the governance timing parameters and calculates all
// important timestamps for the proposal's lifecycle.
//
// Parameters:
//   - votingStartDelay: delay before voting starts (seconds)
//   - votingPeriod: duration of voting period (seconds)
//   - executionDelay: delay before execution can start (seconds)
//   - executionWindow: window during which execution is allowed (seconds)
//   - createdAt: timestamp when proposal was created
//
// Returns:
//   - *ProposalScheduleStatus: new schedule status with calculated times
func NewProposalScheduleStatus(
	votingStartDelay,
	votingPeriod,
	executionDelay,
	executionWindow,
	createdAt int64,
) *governance.ProposalScheduleStatus {
	// Calculate all phase timestamps based on creation time and configuration
	createTime := createdAt
	activeTime := gnsmath.SafeAddInt64(createTime, votingStartDelay)      // When voting can start
	votingEndTime := gnsmath.SafeAddInt64(activeTime, votingPeriod)       // When voting ends
	executableTime := gnsmath.SafeAddInt64(votingEndTime, executionDelay) // When execution can start
	expiredTime := gnsmath.SafeAddInt64(executableTime, executionWindow)  // When execution window closes

	return governance.NewProposalScheduleStatus(createTime, activeTime, votingEndTime, executableTime, expiredTime)
}

proposal_status.gno

package governance

import (
	gnsmath "gno.land/p/gnoswap/gnsmath/v1"

	"gno.land/r/gnoswap/gov/governance"
)

type ProposalStatusResolver struct {
	*governance.ProposalStatus
	scheduleResolver     *ProposalScheduleStatusResolver
	actionStatusResolver *ProposalActionStatusResolver
	voteStatusResolver   *ProposalVoteStatusResolver
}

// NewProposalStatusResolver wraps proposal status components for lifecycle and vote queries.
//
// Parameters:
//   - status: proposal status containing schedule, action, and vote state
//
// Returns:
//   - *ProposalStatusResolver: resolver backed by status
func NewProposalStatusResolver(status *governance.ProposalStatus) *ProposalStatusResolver {
	return &ProposalStatusResolver{
		ProposalStatus:       status,
		scheduleResolver:     NewProposalScheduleStatusResolver(status.Schedule()),
		actionStatusResolver: NewProposalActionStatusResolver(status.ActionStatus()),
		voteStatusResolver:   NewProposalVoteStatusResolver(status.VoteStatus()),
	}
}

// TotalVoteWeight returns the total weight of all votes cast.
//
// Returns:
//   - int64: total vote weight
func (p *ProposalStatusResolver) TotalVoteWeight() int64 {
	return p.voteStatusResolver.TotalVoteWeight()
}

// StatusType determines the current status of the proposal based on timing, voting, and actions.
// This is the main status calculation method that considers all factors.
//
// Parameters:
//   - current: current timestamp to evaluate status at
//
// Returns:
//   - ProposalStatusType: current status of the proposal
func (p *ProposalStatusResolver) StatusType(current int64) governance.ProposalStatusType {
	actionStatus := p.ActionStatus()

	// Check action-based statuses first (these override time-based statuses)
	if actionStatus.IsExecuted() {
		return governance.StatusExecuted
	}

	if actionStatus.Canceled() {
		return governance.StatusCanceled
	}

	// Check time-based statuses
	if !p.scheduleResolver.IsPassedActiveAt(current) {
		return governance.StatusUpcoming
	}

	if !p.scheduleResolver.IsPassedVotingEndedAt(current) {
		return governance.StatusActive
	}

	// Check voting outcome after voting period ends
	if !p.voteStatusResolver.IsPassed() {
		return governance.StatusRejected
	}

	// For passed proposals, check execution status
	if !p.ActionStatus().IsExecutable() || !p.scheduleResolver.IsPassedExecutableAt(current) {
		return governance.StatusPassed
	}

	if !p.scheduleResolver.IsPassedExpiredAt(current) {
		return governance.StatusExecutable
	}

	return governance.StatusExpired
}

// IsUpcoming checks if the proposal is in upcoming status.
//
// Parameters:
//   - current: timestamp to check status at
//
// Returns:
//   - bool: true if proposal is upcoming
func (p *ProposalStatusResolver) IsUpcoming(current int64) bool {
	return p.StatusType(current) == governance.StatusUpcoming
}

// IsActive checks if the proposal is in active voting status.
//
// Parameters:
//   - current: timestamp to check status at
//
// Returns:
//   - bool: true if proposal is active (voting period)
func (p *ProposalStatusResolver) IsActive(current int64) bool {
	return p.StatusType(current) == governance.StatusActive
}

// IsPassed checks if the proposal has passed voting.
//
// Parameters:
//   - current: timestamp to check status at
//
// Returns:
//   - bool: true if proposal has passed
func (p *ProposalStatusResolver) IsPassed(current int64) bool {
	return p.StatusType(current) == governance.StatusPassed
}

// IsRejected checks if the proposal has been rejected by voting.
//
// Parameters:
//   - current: timestamp to check status at
//
// Returns:
//   - bool: true if proposal was rejected
func (p *ProposalStatusResolver) IsRejected(current int64) bool {
	return p.StatusType(current) == governance.StatusRejected
}

// IsExecutable checks if the proposal is in executable status.
//
// Parameters:
//   - current: timestamp to check status at
//
// Returns:
//   - bool: true if proposal can be executed
func (p *ProposalStatusResolver) IsExecutable(current int64) bool {
	return p.StatusType(current) == governance.StatusExecutable
}

// IsExpired checks if the proposal execution window has expired.
//
// Parameters:
//   - current: timestamp to check status at
//
// Returns:
//   - bool: true if proposal has expired
func (p *ProposalStatusResolver) IsExpired(current int64) bool {
	return p.StatusType(current) == governance.StatusExpired
}

// IsExecuted checks if the proposal has been executed.
//
// Parameters:
//   - current: timestamp to check status at
//
// Returns:
//   - bool: true if proposal has been executed
func (p *ProposalStatusResolver) IsExecuted(current int64) bool {
	return p.StatusType(current) == governance.StatusExecuted
}

// IsCanceled checks if the proposal has been canceled.
//
// Parameters:
//   - current: timestamp to check status at
//
// Returns:
//   - bool: true if proposal has been canceled
func (p *ProposalStatusResolver) IsCanceled(current int64) bool {
	return p.StatusType(current) == governance.StatusCanceled
}

// cancel marks the proposal as canceled with the provided details.
// This delegates to the action status for actual cancellation logic.
//
// Parameters:
//   - canceledAt: timestamp when proposal was canceled
//   - canceledHeight: block height when proposal was canceled
//   - canceledBy: address that canceled the proposal
//
// Returns:
//   - error: cancellation error if operation fails
func (p *ProposalStatusResolver) cancel(canceledAt int64, canceledHeight int64, canceledBy address) error {
	return p.actionStatusResolver.cancel(canceledAt, canceledHeight, canceledBy)
}

// execute marks the proposal as executed with the provided details.
// This delegates to the action status for actual execution logic.
//
// Parameters:
//   - executedAt: timestamp when proposal was executed
//   - executedHeight: block height when proposal was executed
//   - executedBy: address that executed the proposal
//
// Returns:
//   - error: execution error if operation fails
func (p *ProposalStatusResolver) execute(executedAt int64, executedHeight int64, executedBy address) error {
	return p.actionStatusResolver.Execute(executedAt, executedHeight, executedBy)
}

// vote records a vote on the proposal and updates vote tallies.
// This delegates to the vote status for actual vote recording.
//
// Parameters:
//   - votedYes: true for "yes" vote, false for "no" vote
//   - weight: voting weight to apply
//
// Returns:
//   - error: voting error if operation fails
func (p *ProposalStatusResolver) vote(votedYes bool, weight int64) error {
	if votedYes {
		return p.voteStatusResolver.AddYesVoteWeight(weight)
	}

	return p.voteStatusResolver.AddNoVoteWeight(weight)
}

// NewProposalStatus creates a new proposal status with the specified configuration.
// This initializes all status components with the governance configuration and timing.
//
// Parameters:
//   - config: governance configuration to use
//   - maxVotingWeight: maximum voting weight for this proposal
//   - executable: whether this proposal type can be executed
//   - createdAt: timestamp when proposal was created
//   - quorumWeight: total xGNS supply at proposal creation, used as the quorum base
//
// Returns:
//   - *ProposalStatus: new proposal status instance
func NewProposalStatus(
	config governance.Config,
	maxVotingWeight int64,
	executable bool,
	createdAt int64,
	quorumWeight int64,
) *governance.ProposalStatus {
	schedule := NewProposalScheduleStatus(
		config.VotingStartDelay,
		config.VotingPeriod,
		config.ExecutionDelay,
		config.ExecutionWindow,
		createdAt,
	)
	actionStatus := governance.NewProposalActionStatus(executable)

	// Calculate the quorum amount from the current xGNS supply, not the smoothed voting weight.
	quorumAmount := gnsmath.SafeMulDivInt64(quorumWeight, config.Quorum, 100)
	voteStatus := governance.NewProposalVoteStatus(maxVotingWeight, quorumAmount)

	return governance.NewProposalStatusBy(schedule, actionStatus, voteStatus)
}

proposal_vote_status.gno

package governance

import (
	gnsmath "gno.land/p/gnoswap/gnsmath/v1"

	"gno.land/r/gnoswap/gov/governance"
)

type ProposalVoteStatusResolver struct {
	*governance.ProposalVoteStatus
}

// NewProposalVoteStatusResolver wraps persisted vote status for vote tally
// calculations and mutation.
//
// Parameters:
//   - voteStatus: persisted proposal vote status to resolve
//
// Returns:
//   - *ProposalVoteStatusResolver: resolver backed by voteStatus
func NewProposalVoteStatusResolver(voteStatus *governance.ProposalVoteStatus) *ProposalVoteStatusResolver {
	return &ProposalVoteStatusResolver{voteStatus}
}

// TotalVoteWeight returns the total weight of all votes cast (yes + no).
//
// Returns:
//   - int64: combined "yes" and "no" vote weight
func (p *ProposalVoteStatusResolver) TotalVoteWeight() int64 {
	return gnsmath.SafeAddInt64(p.YesWeight(), p.NoWeight())
}

// IsPassed determines if the proposal has passed the voting requirements.
// A proposal passes when total vote weight reaches quorum and "yes" votes
// strictly exceed "no" votes.
//
// Returns:
//   - bool: true when quorum is met and yes weight is greater than no weight
func (p *ProposalVoteStatusResolver) IsPassed() bool {
	if p.TotalVoteWeight() < p.QuorumAmount() {
		return false
	}

	return p.YesWeight() > p.NoWeight()
}

// addYesVoteWeight adds the specified weight to the "yes" vote tally.
// This is called when a user votes "yes" on the proposal.
//
// Parameters:
//   - yea: vote weight to add to "yes" votes
//
// Returns:
//   - error: always nil (reserved for future validation)
func (p *ProposalVoteStatusResolver) AddYesVoteWeight(yea int64) error {
	p.SetYesWeight(gnsmath.SafeAddInt64(p.YesWeight(), yea))
	return nil
}

// addNoVoteWeight adds the specified weight to the "no" vote tally.
// This is called when a user votes "no" on the proposal.
//
// Parameters:
//   - nay: vote weight to add to "no" votes
//
// Returns:
//   - error: always nil (reserved for future validation)
func (p *ProposalVoteStatusResolver) AddNoVoteWeight(nay int64) error {
	p.SetNoWeight(gnsmath.SafeAddInt64(p.NoWeight(), nay))
	return nil
}

render.gno

package governance

import (
	"strings"

	"gno.land/p/moul/md/v0"
	"gno.land/p/moul/mdtable/v0"
	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/r/gnoswap/gov/governance"
)

func (g *governanceV1) Render(path string) string {
	if path != "" {
		return "404\n"
	}

	implementation := governance.GetImplementationPackagePath()

	out := md.H1("Gnoswap Governance")
	out += md.H2("Governance configuration")
	configurationTable := mdtable.Table{
		Headers: []string{"Field", "Value"},
		Rows: [][]string{
			{"Active implementation", md.Link(implementation, strings.TrimPrefix(implementation, "gno.land"))},
			{"Latest configuration version", ufmt.Sprintf("%d", governance.GetLatestConfigVersion())},
			{"Current proposal ID", ufmt.Sprintf("%d", governance.GetCurrentProposalID())},
			{"Maximum smoothing period", ufmt.Sprintf("%d", governance.GetMaxSmoothingPeriod())},
		},
	}
	out += configurationTable.String()

	return out
}

utils.gno

package governance

import (
	"strconv"
	"strings"

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

// numberKind represents the type of number to parse.
type numberKind int

const (
	kindInt numberKind = iota
	kindInt64
	kindUint64
)

// parseNumber parses a string to a number (int, int64, or uint64) with proper validation.
func parseNumber(s string, kind numberKind) any {
	if len(strings.TrimSpace(s)) == 0 {
		panic(ufmt.Sprint("invalid number value: empty or whitespace string"))
	}

	switch kind {
	case kindInt:
		num, err := strconv.ParseInt(s, 10, 64)
		if err != nil {
			panic(ufmt.Sprintf("invalid int value: %s", s))
		}
		return int(num)
	case kindInt64:
		num, err := strconv.ParseInt(s, 10, 64)
		if err != nil {
			panic(ufmt.Sprintf("invalid int64 value: %s", s))
		}
		return num
	case kindUint64:
		num, err := strconv.ParseUint(s, 10, 64)
		if err != nil {
			panic(ufmt.Sprintf("invalid uint64 value: %s", s))
		}
		return num
	default:
		panic(ufmt.Sprintf("unsupported number kind: %v", kind))
	}
}

// parseBool parses a string to a boolean.
func parseBool(s string) bool {
	if len(strings.TrimSpace(s)) == 0 {
		panic(ufmt.Sprint("invalid bool value: empty or whitespace string"))
	}

	switch s {
	case "true":
		return true
	case "false":
		return false
	default:
		panic(ufmt.Sprintf("invalid bool value: %s", s))
	}
}

// parseInt parses a string to int with proper validation and overflow checking.
func parseInt(s string) int {
	if len(strings.TrimSpace(s)) == 0 {
		panic(ufmt.Sprint("invalid int value: empty or whitespace string"))
	}

	num, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		panic(ufmt.Sprintf("invalid int value: %s", s))
	}

	const maxInt = int(^uint(0) >> 1)
	const minInt = -maxInt - 1

	if num > int64(maxInt) || num < int64(minInt) {
		panic(ufmt.Sprintf("int overflow: value %d exceeds int range [%d, %d]", num, minInt, maxInt))
	}

	return int(num)
}

// parseInt64 parses a string to int64 with proper validation.
func parseInt64(s string) int64 {
	if len(strings.TrimSpace(s)) == 0 {
		panic(ufmt.Sprint("invalid int64 value: empty or whitespace string"))
	}

	num, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		panic(ufmt.Sprintf("invalid int64 value: %s", s))
	}

	return num
}

// parseUint64 parses a string to uint64 with proper validation.
func parseUint64(s string) uint64 {
	if len(strings.TrimSpace(s)) == 0 {
		panic(ufmt.Sprint("invalid uint64 value: empty or whitespace string"))
	}

	num, err := strconv.ParseUint(s, 10, 64)
	if err != nil {
		panic(ufmt.Sprintf("invalid uint64 value: %s", s))
	}

	return num
}