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 staker

import (
	"errors"
	"time"

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

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

// assertIsValidDelegateAmount validates that the delegation amount meets system requirements.
// This function checks minimum amount and multiple requirements.
//
// Parameters:
//   - amount: amount to validate
//
// Returns:
//   - error: nil if valid, error describing validation failure
func assertIsValidDelegateAmount(amount int64) {
	if amount < minimumAmount {
		panic(makeErrorWithDetails(
			errLessThanMinimum,
			ufmt.Sprintf("minimum amount to delegate is %d (requested:%d)", minimumAmount, amount),
		))
	}

	if amount%minimumAmount != 0 {
		panic(makeErrorWithDetails(
			errInvalidAmount,
			ufmt.Sprintf("amount must be multiple of %d", minimumAmount),
		))
	}
}

func assertIsValidSnapshotTime(snapshotTime int64) {
	if snapshotTime < 0 {
		panic(makeErrorWithDetails(
			errInvalidSnapshotTime,
			ufmt.Sprintf("snapshot time must be greater than 0 (requested:%d)", snapshotTime),
		))
	}

	currentTime := time.Now().Unix()
	maxSmoothingPeriod := governance.GetMaxSmoothingPeriod()

	if snapshotTime > currentTime-maxSmoothingPeriod {
		panic(makeErrorWithDetails(
			errInvalidSnapshotTime,
			ufmt.Sprintf("snapshot time must be less than %d (requested:%d)", currentTime-maxSmoothingPeriod, snapshotTime),
		))
	}
}

// assertIsAvailableCleanupSnapshotTime checks that no active proposals need
func assertIsAvailableCleanupSnapshotTime(cleanupSnapshotTime int64) {
	oldestActiveSnapshotTime, hasActiveProposal, err := governance.GetOldestActiveProposalSnapshotTime()
	if err != nil {
		panic(err)
	}
	if !hasActiveProposal {
		// No active proposals, cleanup is safe
		return
	}

	if cleanupSnapshotTime > oldestActiveSnapshotTime {
		panic(makeErrorWithDetails(
			errInvalidSnapshotTime,
			ufmt.Sprintf(
				"cannot cleanup delegation history: active proposal requires data from snapshot time %d, but cleanup would remove data before %d",
				oldestActiveSnapshotTime,
				cleanupSnapshotTime,
			),
		))
	}
}

func assertNoSameDelegatee(delegatee, newDelegatee address) {
	if delegatee == newDelegatee {
		panic(errors.New(errSameDelegatee))
	}
}

func assertNotImplementYet() {
	panic("NotImplementYet")
}

consts.gno

package staker

const (
	minimumAmount = 1_000_000 // 1 GNS

	// maxAccrualBucketsPerCollect bounds how many pending accrual buckets one
	// single-token collect folds. Whatever is left stays pending for the next collect.
	maxAccrualBucketsPerCollect = 256
	// maxStakeEventsPerCollect bounds how many of the staker's own stake events one
	// single-token collect settles. Whatever is left stays pending for the next collect.
	maxStakeEventsPerCollect = 256
)

delegation.gno

package staker

import (
	"errors"

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

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

const errCollectAmountExceedsCollectable = "amount to collect is greater than collectable amount"

type DelegationResolver struct {
	delegation *staker.Delegation
}

// NewDelegationResolver wraps a delegation in a resolver for derived amounts and withdrawals.
//
// Parameters:
//   - delegation: delegation state to resolve
//
// Returns:
//   - *DelegationResolver: resolver backed by delegation
func NewDelegationResolver(delegation *staker.Delegation) *DelegationResolver {
	return &DelegationResolver{delegation}
}

// Get returns the underlying delegation state.
//
// Returns:
//   - *staker.Delegation: wrapped delegation instance
func (r *DelegationResolver) Get() *staker.Delegation {
	return r.delegation
}

// DelegatedAmount returns total delegated amount minus amount already undelegated.
//
// Returns:
//   - int64: amount still delegated
func (r *DelegationResolver) DelegatedAmount() int64 {
	return gnsmath.SafeSubInt64(r.delegation.TotalDelegatedAmount(), r.delegation.UnDelegatedAmount())
}

// LockedAmount returns total delegated amount minus amount already collected.
//
// Returns:
//   - int64: amount still locked in the delegation
func (r *DelegationResolver) LockedAmount() int64 {
	return gnsmath.SafeSubInt64(r.delegation.TotalDelegatedAmount(), r.delegation.CollectedAmount())
}

// IsEmpty reports whether no locked delegation amount remains.
//
// Returns:
//   - bool: true when LockedAmount is zero, otherwise false
func (r *DelegationResolver) IsEmpty() bool {
	return r.LockedAmount() == 0
}

// CollectableAmount calculates the total amount that can be collected at the given time.
//
// Parameters:
//   - currentTime: current Unix timestamp used to evaluate each withdrawal's lockup
//
// Returns:
//   - total: sum of all withdrawal amounts currently available for collection
func (r *DelegationResolver) CollectableAmount(currentTime int64) (total int64) {
	for _, withdraw := range r.delegation.Withdraws() {
		total = gnsmath.SafeAddInt64(total, NewDelegationWithdrawResolver(&withdraw).CollectableAmount(currentTime))
	}

	return total
}

// UnDelegate processes an undelegation with a time-based lockup period.
//
// Parameters:
//   - amount: amount to undelegate and place into a withdrawal
//   - currentHeight: block height at which the undelegation is recorded
//   - currentTimestamp: Unix timestamp at which the undelegation is recorded
//   - unDelegationLockupPeriod: lockup duration in seconds before the withdrawal is collectible
func (r *DelegationResolver) UnDelegate(
	amount, currentHeight, currentTimestamp, unDelegationLockupPeriod int64,
) {
	r.delegation.SetUnDelegateAmount(gnsmath.SafeAddInt64(r.delegation.UnDelegatedAmount(), amount))

	withdraw := NewDelegationWithdraw(
		r.delegation.ID(),
		amount,
		currentHeight,
		currentTimestamp,
		unDelegationLockupPeriod,
	)
	r.delegation.AddWithdraw(withdraw)
}

// UnDelegateWithoutLockup processes an immediate undelegation without lockup.
//
// Parameters:
//   - amount: amount to undelegate and mark as collected immediately
//   - currentHeight: current block height context; retained for API symmetry and unused by this immediate path
//   - currentTime: current Unix timestamp context; retained for API symmetry and unused by this immediate path
func (r *DelegationResolver) UnDelegateWithoutLockup(
	amount, currentHeight, currentTime int64,
) {
	r.delegation.SetUnDelegateAmount(gnsmath.SafeAddInt64(r.delegation.UnDelegatedAmount(), amount))
	r.delegation.SetCollectedAmount(gnsmath.SafeAddInt64(r.delegation.CollectedAmount(), amount))
}

// processCollection handles the actual collection logic
func (r *DelegationResolver) processCollection(currentTime int64) (int64, error) {
	collectedAmount := int64(0)
	withdraws := r.delegation.Withdraws()

	for i := range withdraws {
		resolver := NewDelegationWithdrawResolver(&withdraws[i])

		collectableAmount := resolver.CollectableAmount(currentTime)
		if collectableAmount <= 0 {
			continue
		}

		err := resolver.Collect(collectableAmount, currentTime)
		if err != nil {
			return 0, err
		}

		updatedAmount, err := addToCollectedAmount(r.delegation.CollectedAmount(), collectableAmount)
		if err != nil {
			return 0, err
		}

		r.delegation.SetCollectedAmount(updatedAmount)
		collectedAmount = gnsmath.SafeAddInt64(collectedAmount, collectableAmount)
	}

	// Skip filtering if nothing was collected
	if collectedAmount == 0 {
		return collectedAmount, nil
	}

	currentIndex := 0

	for i := range withdraws {
		if !withdraws[i].IsCollected() {
			r.delegation.SetWithdraw(currentIndex, withdraws[i])
			currentIndex++
		}
	}

	r.delegation.SetWithdraws(withdraws[:currentIndex])

	return collectedAmount, nil
}

func addToCollectedAmount(collectedAmount, amount int64) (int64, error) {
	if amount < 0 {
		return 0, errors.New(errAmountMustBeNonNegative)
	}
	return gnsmath.SafeAddInt64(collectedAmount, amount), nil
}

// NewDelegation creates a new delegation.
// This is a convenience wrapper around staker.NewDelegation.
//
// Parameters:
//   - id: delegation ID
//   - delegateFrom: delegator's address
//   - delegateTo: delegatee's address
//   - delegateAmount: amount to delegate
//   - createdHeight: creation block height
//   - createdAt: creation timestamp
//
// Returns:
//   - *staker.Delegation: new delegation instance
func NewDelegation(
	id int64,
	delegateFrom, delegateTo address,
	delegateAmount, createdHeight, createdAt int64,
) *staker.Delegation {
	return staker.NewDelegation(
		id,
		delegateFrom,
		delegateTo,
		delegateAmount,
		createdHeight,
		createdAt,
	)
}

delegation_manager.gno

package staker

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

type DelegationManagerResolver struct {
	*staker.DelegationManager
}

// NewDelegationManagerResolver creates a resolver over an existing delegation manager.
//
// Parameters:
//   - delegationManager: manager whose domain-owned delegation trees will be queried or updated.
//
// Returns:
//   - *DelegationManagerResolver: resolver exposing address-typed delegation operations.
func NewDelegationManagerResolver(delegationManager *staker.DelegationManager) *DelegationManagerResolver {
	return &DelegationManagerResolver{delegationManager}
}

// GetUserDelegationIDsWithDelegatee retrieves all delegation IDs for a specific delegator-delegatee pair.
// This method is used to find delegations from a specific user to a specific delegate.
//
// Parameters:
//   - delegator: address of the user who delegated tokens
//   - delegatee: address of the user who received the delegation
//
// Returns:
//   - []int64: matching delegation IDs, or an empty slice when no pair is stored.
func (dm *DelegationManagerResolver) GetUserDelegationIDsWithDelegatee(delegator, delegatee address) []int64 {
	delegatorAddress := delegator.String()
	delegateeAddress := delegatee.String()

	ids, exists := dm.GetDelegationIDs(delegatorAddress, delegateeAddress)
	if !exists {
		return []int64{}
	}
	return ids
}

// GetUserDelegationIDs retrieves all delegation IDs for a specific delegator across all delegatees.
// This method is used to find all delegations made by a specific user.
//
// Parameters:
//   - delegator: address of the user whose delegations to retrieve
//
// Returns:
//   - []int64: concatenated delegation IDs from every stored delegatee entry, or an empty slice when absent.
func (dm *DelegationManagerResolver) GetUserDelegationIDs(delegator address) []int64 {
	delegatorAddress := delegator.String()
	delegationIDs := make([]int64, 0)

	// Get all delegations for this delegator
	delegations, exists := dm.GetDelegatorDelegations(delegatorAddress)
	if !exists {
		return delegationIDs
	}

	// Collect delegation IDs from all delegatees by iterating the BPTree
	delegations.Iterate("", "", func(key string, value interface{}) bool {
		if toDelegations, ok := value.([]int64); ok {
			delegationIDs = append(delegationIDs, toDelegations...)
		}
		return false
	})

	return delegationIDs
}

// addDelegation adds a delegation ID to the manager's tracking system.
// This method creates the necessary nested map structure if it doesn't exist
// and ensures no duplicate delegation IDs are stored.
//
// Parameters:
//   - delegator: address of the user who made the delegation
//   - delegatee: address of the user who received the delegation
//   - delegationID: unique identifier for the delegation
func (dm *DelegationManagerResolver) addDelegation(delegator, delegatee address, delegationID int64) {
	// Delegate the read-modify-write to the domain method so the nested BPTree
	// mutation stays within the owning realm; splitting the get and set across
	// the realm boundary here would taint the re-fetched inner tree.
	dm.AddDelegationID(delegator.String(), delegatee.String(), delegationID)
}

// removeDelegation removes a delegation ID from the manager's tracking system.
// This method finds and removes the specified delegation ID from the appropriate slice.
//
// Parameters:
//   - delegator: address of the user who made the delegation
//   - delegatee: address of the user who received the delegation
//   - delegationID: unique identifier for the delegation to remove
func (dm *DelegationManagerResolver) removeDelegation(delegator, delegatee address, delegationID int64) {
	// Delegate the read-modify-write to the domain method so the nested BPTree
	// mutation stays within the owning realm.
	dm.RemoveDelegationID(delegator.String(), delegatee.String(), delegationID)
}

delegation_withdraw.gno

package staker

import (
	"errors"

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

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

type DelegationWithdrawResolver struct {
	withdraw *staker.DelegationWithdraw
}

// NewDelegationWithdrawResolver wraps a delegation withdrawal for collection
// state and lockup calculations.
//
// Parameters:
//   - withdraw: delegation withdrawal state to resolve
//
// Returns:
//   - *DelegationWithdrawResolver: resolver retaining the supplied withdrawal pointer
func NewDelegationWithdrawResolver(withdraw *staker.DelegationWithdraw) *DelegationWithdrawResolver {
	return &DelegationWithdrawResolver{withdraw}
}

// Get returns the wrapped delegation withdrawal value.
//
// Returns:
//   - *staker.DelegationWithdraw: wrapped withdrawal pointer, or nil when the resolver was constructed with nil
func (r *DelegationWithdrawResolver) Get() *staker.DelegationWithdraw {
	return r.withdraw
}

// CollectableAmount calculates the amount available for collection at the given time.
// Returns zero if the withdrawal is not yet collectable or has been fully collected.
//
// Parameters:
//   - currentTime: current timestamp to check collectability against
//
// Returns:
//   - int64: amount available for collection
func (r *DelegationWithdrawResolver) CollectableAmount(currentTime int64) int64 {
	if r.IsCollectable(currentTime) {
		return gnsmath.SafeSubInt64(r.withdraw.UnDelegateAmount(), r.withdraw.CollectedAmount())
	}

	return 0
}

// IsCollectable determines whether the withdrawal can be collected at the given time.
// A withdrawal is collectable if:
// - The undelegated amount is positive
// - There is remaining uncollected amount
// - The current time is at or after the collectable time
//
// Parameters:
//   - currentTime: current timestamp to check against
//
// Returns:
//   - bool: true if the withdrawal can be collected, false otherwise
func (r *DelegationWithdrawResolver) IsCollectable(currentTime int64) bool {
	if r.withdraw.UnDelegateAmount() <= 0 {
		return false
	}

	remaining := gnsmath.SafeSubInt64(r.withdraw.UnDelegateAmount(), r.withdraw.CollectedAmount())
	if remaining <= 0 {
		return false
	}

	if currentTime < r.withdraw.CollectableTime() {
		return false
	}

	return true
}

// IsCollected returns whether the withdrawal has been fully collected.
//
// Returns:
//   - bool: true if fully collected, false otherwise
func (r *DelegationWithdrawResolver) IsCollected() bool {
	return r.withdraw.IsCollected()
}

// collect processes the collection of the specified amount from this withdrawal.
// This method validates collectability and updates the collection state.
//
// Parameters:
//   - amount: GNS amount to add to this withdrawal's collected amount
//   - currentTime: Unix timestamp used to check lockup expiry and record collection time
//
// Returns:
//   - error: nil after the collection state is updated; errWithdrawNotCollectable when the withdrawal is not collectable
func (r *DelegationWithdrawResolver) Collect(amount int64, currentTime int64) error {
	if !r.IsCollectable(currentTime) {
		return errors.New(errWithdrawNotCollectable)
	}

	r.withdraw.SetCollectedAmount(gnsmath.SafeAddInt64(r.withdraw.CollectedAmount(), amount))

	if r.withdraw.UnDelegateAmount() == r.withdraw.CollectedAmount() {
		r.withdraw.SetCollected(true)
		r.withdraw.SetCollectedAt(currentTime)
	}

	return nil
}

// NewDelegationWithdraw creates a new delegation withdrawal with lockup period.
// This is a convenience wrapper around staker.NewDelegationWithdraw.
//
// Parameters:
//   - delegationID: unique identifier of the associated delegation
//   - unDelegateAmount: amount being withdrawn
//   - createdHeight: height when the withdrawal was created
//   - createdAt: timestamp when the withdrawal was created
//   - unDelegationLockupPeriod: duration of the lockup period in seconds
//
// Returns:
//   - staker.DelegationWithdraw: new withdrawal instance with lockup
func NewDelegationWithdraw(
	delegationID,
	unDelegateAmount,
	createdHeight,
	createdAt,
	unDelegationLockupPeriod int64,
) staker.DelegationWithdraw {
	return staker.NewDelegationWithdraw(
		delegationID,
		unDelegateAmount,
		createdHeight,
		createdAt,
		unDelegationLockupPeriod,
	)
}

// NewDelegationWithdrawWithoutLockup creates a new delegation withdrawal that is immediately collectable.
// This is a convenience wrapper around staker.NewDelegationWithdrawWithoutLockup.
//
// Parameters:
//   - delegationID: unique identifier of the associated delegation
//   - unDelegateAmount: amount being withdrawn
//   - createdHeight: height when the withdrawal was created
//   - createdAt: timestamp when the withdrawal was created
//
// Returns:
//   - staker.DelegationWithdraw: new withdrawal instance that is immediately collectable
func NewDelegationWithdrawWithoutLockup(
	delegationID,
	unDelegateAmount,
	createdHeight,
	createdAt int64,
) staker.DelegationWithdraw {
	return staker.NewDelegationWithdrawWithoutLockup(
		delegationID,
		unDelegateAmount,
		createdHeight,
		createdAt,
	)
}

doc.gno

// Package v1 manages GNS delegation and xGNS accounting.
// It maintains timestamped delegation history, distributes GNS emission and
// protocol-fee rewards, and enforces a configurable undelegation lockup
// (7 days by default; xGNS is burned when undelegated GNS is collected).
package staker

emission_reward_manager.gno

package staker

import (
	"errors"
	"math"

	gnsmath "gno.land/p/gnoswap/gnsmath/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	"gno.land/r/gnoswap/gov/staker"
)

type EmissionRewardManagerResolver struct {
	*staker.EmissionRewardManager
}

// NewEmissionRewardManagerResolver wraps an emission reward manager with reward
// calculation and stake-accounting helpers.
//
// Parameters:
//   - emissionRewardManager: manager state to resolve and mutate.
//
// Returns:
//   - *EmissionRewardManagerResolver: resolver backed by emissionRewardManager.
func NewEmissionRewardManagerResolver(emissionRewardManager *staker.EmissionRewardManager) *EmissionRewardManagerResolver {
	return &EmissionRewardManagerResolver{emissionRewardManager}
}

// GetClaimableRewardAmount calculates the claimable reward amount for a specific address.
//
// Parameters:
//   - currentDistributedAmount: total emission amount distributed to the staker
//     manager at the current observation point.
//   - address: reward-state identifier whose claimable amount is requested.
//   - currentTimestamp: Unix timestamp used to settle the address's reward state.
//
// Returns:
//   - int64: emission reward currently claimable by address, or zero when no
//     reward state exists.
//   - error: nil on success; an error from accumulated-reward or reward-state
//     resolution when calculation fails.
func (self *EmissionRewardManagerResolver) GetClaimableRewardAmount(
	currentDistributedAmount int64,
	address string,
	currentTimestamp int64,
) (int64, error) {
	rewardState, ok, err := self.GetRewardState(address)
	if !ok {
		return 0, nil
	}

	accumulatedRewardX128PerStake, err := self.calculateAccumulatedRewardX128PerStake(
		currentDistributedAmount,
		currentTimestamp,
	)
	if err != nil {
		return 0, err
	}

	resolvedState := NewEmissionRewardStateResolver(rewardState)
	return resolvedState.GetClaimableRewardAmount(accumulatedRewardX128PerStake, currentTimestamp)
}

// calculateAccumulatedRewardX128PerStake calculates the updated accumulated reward per stake.
func (self *EmissionRewardManagerResolver) calculateAccumulatedRewardX128PerStake(
	currentDistributedAmount int64,
	currentTimestamp int64,
) (*u256.Uint, error) {
	// If we're looking at a past timestamp, return current state
	if currentTimestamp < self.GetAccumulatedTimestamp() {
		return self.GetAccumulatedRewardX128PerStake(), nil
	}

	// With no stake there is nobody to credit, so the delta accrued over that window is
	// dropped and the caller advances the cursor past it. The protocol fee accumulator
	// applies the same policy, see ProtocolFeeRewardManagerResolver.
	totalStakedAmount := self.GetTotalStakedAmount()
	if totalStakedAmount == 0 {
		return self.GetAccumulatedRewardX128PerStake(), nil
	}

	// Newly distributed rewards since last update
	distributedAmountDelta := gnsmath.SafeSubInt64(currentDistributedAmount, self.GetDistributedAmount())
	if distributedAmountDelta <= 0 {
		// Non-positive delta. nothing to do more.
		return self.GetAccumulatedRewardX128PerStake(), nil
	}

	// Reward per stake for the new distribution
	distributedAmountDeltaX128PerStake := u256.Zero().Div(
		u256.Zero().Lsh(u256.NewUintFromInt64(distributedAmountDelta), 128),
		u256.NewUintFromInt64(totalStakedAmount),
	)

	// Add to accumulated reward per stake
	accumulatedReward := u256.Zero().Add(self.GetAccumulatedRewardX128PerStake(), distributedAmountDeltaX128PerStake)
	return accumulatedReward, nil
}

// updateAccumulatedRewardX128PerStake updates the internal accumulated reward state.
// This method should be called before any stake changes to ensure accurate reward calculations.
// Updates accumulated reward per stake with current distribution data.
func (self *EmissionRewardManagerResolver) updateAccumulatedRewardX128PerStake(
	currentDistributedAmount int64,
	currentTimestamp int64,
) error {
	// DO NOT apply out-of-order timestamps
	if currentTimestamp < self.GetAccumulatedTimestamp() {
		return nil
	}

	// Update accumulated reward state
	accumulatedRewardX128PerStake, err := self.calculateAccumulatedRewardX128PerStake(
		currentDistributedAmount,
		currentTimestamp,
	)
	if err != nil {
		return err
	}

	self.setAccumulatedRewardX128PerStake(accumulatedRewardX128PerStake.Clone())
	self.setDistributedAmount(currentDistributedAmount)
	self.setAccumulatedTimestamp(currentTimestamp)

	return nil
}

// addStake adds a stake for an address and updates their reward state.
// This method ensures rewards are properly calculated before the stake change.
// Adds stake for specified address and updates reward calculations.
func (self *EmissionRewardManagerResolver) addStake(address string, amount int64, currentTimestamp int64) error {
	if amount < 0 {
		return errors.New(errAmountMustBeNonNegative)
	}

	accumulatedReward := self.GetAccumulatedRewardX128PerStake()

	rewardState, ok, err := self.GetRewardState(address)
	if err != nil {
		return err
	}
	if !ok {
		rewardState = staker.NewEmissionRewardState(accumulatedReward)
	}

	resolvedState := NewEmissionRewardStateResolver(rewardState)
	err = resolvedState.addStakeWithUpdateRewardDebtX128(amount, accumulatedReward, currentTimestamp)
	if err != nil {
		return err
	}

	self.setRewardStates(address, rewardState)

	currentTotal := self.GetTotalStakedAmount()
	if amount > 0 && currentTotal > math.MaxInt64-amount {
		return errors.New(errTotalStakedAmountOverflow)
	}
	self.SetTotalStakedAmount(gnsmath.SafeAddInt64(currentTotal, amount))
	return nil
}

// removeStake removes a stake for an address and updates their reward state.
// This method ensures rewards are properly calculated before the stake change.
// Removes stake for specified address and updates reward calculations.
func (self *EmissionRewardManagerResolver) removeStake(address string, amount int64, currentTimestamp int64) error {
	if amount < 0 {
		return errors.New(errAmountMustBeNonNegative)
	}

	updatedTotalStakedAmount := gnsmath.SafeSubInt64(self.GetTotalStakedAmount(), amount)
	if updatedTotalStakedAmount < 0 {
		return errors.New(errRemoveAmountExceedsTotalStaked)
	}

	accumulatedReward := self.GetAccumulatedRewardX128PerStake()

	rewardState, ok, err := self.GetRewardState(address)
	if err != nil {
		return err
	}
	if !ok {
		rewardState = staker.NewEmissionRewardState(accumulatedReward)
	}

	resolvedState := NewEmissionRewardStateResolver(rewardState)

	err = resolvedState.removeStakeWithUpdateRewardDebtX128(amount, accumulatedReward, currentTimestamp)
	if err != nil {
		return err
	}

	// persist updated state
	self.setRewardStates(address, rewardState)

	self.SetTotalStakedAmount(updatedTotalStakedAmount)

	return nil
}

// claimRewards processes reward claiming for an address.
// This method calculates and returns the amount of rewards claimed.
// Claims available rewards for specified address.
func (self *EmissionRewardManagerResolver) claimRewards(address string, currentTimestamp int64) (claimedRewardAmount int64, err error) {
	rewardState, ok, err := self.GetRewardState(address)
	if err != nil || !ok {
		return 0, err
	}

	resolvedState := NewEmissionRewardStateResolver(rewardState)
	claimedRewardAmount, cErr := resolvedState.claimRewardsWithUpdateRewardDebtX128(self.GetAccumulatedRewardX128PerStake(), currentTimestamp)
	if cErr != nil {
		return 0, cErr
	}

	self.setRewardStates(address, rewardState)
	return claimedRewardAmount, nil
}

func (self *EmissionRewardManagerResolver) setRewardStates(address string, rewardState *staker.EmissionRewardState) {
	self.SetRewardState(address, rewardState)
}

func (self *EmissionRewardManagerResolver) setAccumulatedRewardX128PerStake(accumulatedRewardX128PerStake *u256.Uint) {
	self.SetAccumulatedRewardX128PerStake(accumulatedRewardX128PerStake)
}

func (self *EmissionRewardManagerResolver) setDistributedAmount(distributedAmount int64) {
	self.SetDistributedAmount(distributedAmount)
}

func (self *EmissionRewardManagerResolver) setAccumulatedTimestamp(accumulatedTimestamp int64) {
	self.SetAccumulatedTimestamp(accumulatedTimestamp)
}

emission_reward_state.gno

package staker

import (
	"errors"

	"gno.land/p/gnoswap/consts/v1"
	gnsmath "gno.land/p/gnoswap/gnsmath/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	"gno.land/r/gnoswap/gov/staker"
)

type EmissionRewardStateResolver struct {
	*staker.EmissionRewardState
}

// NewEmissionRewardStateResolver wraps an on-chain emission reward state for
// reward calculation and stake/claim updates.
//
// Parameters:
//   - emissionRewardState: persisted reward state to expose through the resolver
//
// Returns:
//   - *EmissionRewardStateResolver: resolver backed by emissionRewardState
func NewEmissionRewardStateResolver(emissionRewardState *staker.EmissionRewardState) *EmissionRewardStateResolver {
	return &EmissionRewardStateResolver{emissionRewardState}
}

// IsClaimable checks if rewards can be claimed at the given timestamp.
// Rewards are claimable only when currentTimestamp is later than the stored
// claimed timestamp.
//
// Parameters:
//   - currentTimestamp: timestamp at which claimability is evaluated
//
// Returns:
//   - bool: true when currentTimestamp is greater than the last claimed timestamp
func (self *EmissionRewardStateResolver) IsClaimable(currentTimestamp int64) bool {
	return self.GetClaimedTimestamp() < currentTimestamp
}

// GetClaimableRewardAmount calculates the total amount of rewards that can be claimed.
// It combines newly earned rewards with accumulated rewards not yet claimed.
//
// Parameters:
//   - accumulatedRewardX128PerStake: system-wide accumulated reward per stake, scaled by 2^128
//   - currentTimestamp: timestamp through which newly earned rewards are calculated
//
// Returns:
//   - int64: total claimable amount, including accumulated-but-unclaimed and newly earned rewards
//   - error: nil on success; an error propagated from reward calculation otherwise
func (self *EmissionRewardStateResolver) GetClaimableRewardAmount(
	accumulatedRewardX128PerStake *u256.Uint,
	currentTimestamp int64,
) (int64, error) {
	rewardAmount, err := self.calculateClaimableRewards(accumulatedRewardX128PerStake, currentTimestamp)
	if err != nil {
		return 0, err
	}

	accumulatedUnclaimedReward := gnsmath.SafeSubInt64(
		self.GetAccumulatedRewardAmount(),
		self.GetClaimedRewardAmount(),
	)

	return gnsmath.SafeAddInt64(accumulatedUnclaimedReward, rewardAmount), nil
}

// calculateClaimableRewards calculates newly earned rewards since the last update.
// Uses the difference between current and stored reward debt to calculate earnings.
//
// Parameters:
//   - accumulatedRewardX128PerStake: current system-wide accumulated reward per stake
//   - currentTimestamp: current timestamp
//
// Returns:
//   - int64: newly earned reward amount since last update
//   - error: nil on success, error if calculation fails
func (self *EmissionRewardStateResolver) calculateClaimableRewards(
	accumulatedRewardX128PerStake *u256.Uint,
	currentTimestamp int64,
) (int64, error) {
	stakedAmount := self.GetStakedAmount()

	// Don't calculate rewards for past timestamps or when nothing is staked
	if currentTimestamp < self.GetAccumulatedTimestamp() || stakedAmount == 0 {
		return 0, nil
	}

	// Calculate the difference in accumulated rewards per stake since last update
	// Using modular arithmetic for accumulator values - underflow is allowed and handled correctly
	rewardDebtDeltaX128 := u256.Zero().Sub(
		accumulatedRewardX128PerStake,
		self.GetRewardDebtX128(),
	)

	// Calculate reward amount by multiplying reward debt delta by staked amount and dividing by Q128
	// rewardAmount = (rewardDebtDeltaX128 * stakedAmount) / Q128
	rewardAmount := u256.MulDiv(
		rewardDebtDeltaX128,
		u256.NewUintFromInt64(stakedAmount),
		consts.Q128(),
	)
	return gnsmath.SafeConvertToInt64(rewardAmount), nil
}

// addStake increases the staked amount for this address.
// This method should be called when a user increases their stake.
//
// Parameters:
//   - amount: amount of stake to add
func (self *EmissionRewardStateResolver) addStake(amount int64) error {
	if amount < 0 {
		return errors.New(errAmountMustBeNonNegative)
	}
	self.SetStakedAmount(gnsmath.SafeAddInt64(self.GetStakedAmount(), amount))
	return nil
}

// removeStake decreases the staked amount for this address.
// This method should be called when a user decreases their stake.
//
// Parameters:
//   - amount: amount of stake to remove
func (self *EmissionRewardStateResolver) removeStake(amount int64) error {
	if amount < 0 {
		return errors.New(errAmountMustBeNonNegative)
	}
	if amount > self.GetStakedAmount() {
		return errors.New(errRemoveAmountExceedsStaked)
	}
	self.SetStakedAmount(gnsmath.SafeSubInt64(self.GetStakedAmount(), amount))
	return nil
}

// claimRewards processes reward claiming and updates the claim state.
// This method validates claimability and transfers accumulated rewards to claimed status.
//
// Parameters:
//   - currentTimestamp: current timestamp
//
// Returns:
//   - int64: amount of rewards claimed (0 if already claimed at this timestamp)
//   - error: always nil in the current implementation
func (self *EmissionRewardStateResolver) claimRewards(currentTimestamp int64) (int64, error) {
	if !self.IsClaimable(currentTimestamp) {
		return 0, nil
	}

	accumulatedRewardAmount := self.GetAccumulatedRewardAmount()
	previousClaimedAmount := self.GetClaimedRewardAmount()
	claimableAmount := gnsmath.SafeSubInt64(accumulatedRewardAmount, previousClaimedAmount)

	self.SetClaimedRewardAmount(accumulatedRewardAmount)
	self.SetClaimedTimestamp(currentTimestamp)

	return claimableAmount, nil
}

// updateRewardDebtX128 updates the reward debt and accumulates new rewards.
// This method should be called before any stake changes to ensure accurate reward tracking.
//
// Parameters:
//   - accumulatedRewardX128PerStake: current system-wide accumulated reward per stake
//   - currentTimestamp: current timestamp
func (self *EmissionRewardStateResolver) updateRewardDebtX128(
	accumulatedRewardX128PerStake *u256.Uint,
	currentTimestamp int64,
) error {
	rewardAmount, err := self.calculateClaimableRewards(accumulatedRewardX128PerStake, currentTimestamp)
	if err != nil {
		return err
	}

	// Accumulate newly earned rewards
	if rewardAmount != 0 {
		self.SetAccumulatedRewardAmount(gnsmath.SafeAddInt64(self.GetAccumulatedRewardAmount(), rewardAmount))
	}

	// Deep copy to avoid aliasing with external state
	self.SetRewardDebtX128(accumulatedRewardX128PerStake.Clone())
	self.SetAccumulatedTimestamp(currentTimestamp)
	return nil
}

// addStakeWithUpdateRewardDebtX128 adds stake and updates reward debt in one operation.
// This ensures rewards are properly calculated before the stake change takes effect.
//
// Parameters:
//   - amount: amount of stake to add
//   - accumulatedRewardX128PerStake: current system-wide accumulated reward per stake
//   - currentTimestamp: current timestamp
func (self *EmissionRewardStateResolver) addStakeWithUpdateRewardDebtX128(
	amount int64,
	accumulatedRewardX128PerStake *u256.Uint,
	currentTimestamp int64,
) error {
	if err := self.updateRewardDebtX128(accumulatedRewardX128PerStake, currentTimestamp); err != nil {
		return err
	}
	return self.addStake(amount)
}

// removeStakeWithUpdateRewardDebtX128 removes stake and updates reward debt in one operation.
// This ensures rewards are properly calculated before the stake change takes effect.
//
// Parameters:
//   - amount: amount of stake to remove
//   - accumulatedRewardX128PerStake: current system-wide accumulated reward per stake
//   - currentTimestamp: current timestamp
func (self *EmissionRewardStateResolver) removeStakeWithUpdateRewardDebtX128(
	amount int64,
	accumulatedRewardX128PerStake *u256.Uint,
	currentTimestamp int64,
) error {
	if err := self.updateRewardDebtX128(accumulatedRewardX128PerStake, currentTimestamp); err != nil {
		return err
	}
	return self.removeStake(amount)
}

// claimRewardsWithUpdateRewardDebtX128 claims rewards and updates reward debt in one operation.
// This ensures all rewards are properly calculated before claiming.
//
// Parameters:
//   - accumulatedRewardX128PerStake: current system-wide accumulated reward per stake
//   - currentTimestamp: current timestamp
//
// Returns:
//   - int64: amount of rewards claimed
//   - error: nil on success, error if claiming fails
func (self *EmissionRewardStateResolver) claimRewardsWithUpdateRewardDebtX128(
	accumulatedRewardX128PerStake *u256.Uint,
	currentTimestamp int64,
) (int64, error) {
	if err := self.updateRewardDebtX128(accumulatedRewardX128PerStake, currentTimestamp); err != nil {
		return 0, err
	}
	return self.claimRewards(currentTimestamp)
}

emits.gno

package staker

import (
	"chain"

	"gno.land/p/gnoswap/utils/v1"
	"gno.land/r/gnoswap/gov/staker"
)

// emitUpdateEmissionRewardAccumulation emits the persisted global emission reward
// accumulation state so that off-chain indexers can consume the authoritative
// accumulator instead of re-deriving it. It must be emitted after every path that
// calls updateAccumulatedRewardX128PerStake (add/remove/claim), otherwise the
// off-chain accumulator drifts from the contract.
//
// All values are read from the manager's persisted state (post-update):
//   - distributedAmount is GetDistributedAmount() (the stored baseline the contract
//     will use for the next delta), not the live emission distribution snapshot.
//   - totalStakedAmount reflects the current total after the stake change and is the
//     divisor for the next accumulation delta.
func emitUpdateEmissionRewardAccumulation(manager *staker.EmissionRewardManager) {
	chain.Emit(
		"UpdateEmissionRewardAccumulation",
		"totalStakedAmount", utils.FormatInt(manager.GetTotalStakedAmount()),
		"distributedAmount", utils.FormatInt(manager.GetDistributedAmount()),
		"accumulatedRewardX128PerStake", manager.GetAccumulatedRewardX128PerStake().ToString(),
		"accumulatedTimestamp", utils.FormatInt(manager.GetAccumulatedTimestamp()),
	)
}

// emitUpdateProtocolFeeStakeAccrual emits the accrual epoch opened by a stake change
// together with the total stake in force from it, so that off-chain indexers can
// attribute fees bucketed under that epoch without re-deriving the stake history.
func emitUpdateProtocolFeeStakeAccrual(manager *staker.ProtocolFeeRewardManager) {
	chain.Emit(
		"UpdateProtocolFeeStakeAccrual",
		"epoch", utils.FormatInt(manager.GetCurrentEpoch()),
		"totalStakedAmount", utils.FormatInt(manager.GetTotalStakedAmount()),
	)
}

// emitUpdateProtocolFeeRewardAccumulation emits the persisted accumulation state of
// every token that was just folded. Like the emission variant it must be emitted after
// every path that folds accrual buckets, otherwise the off-chain accumulator drifts
// from the contract.
func emitUpdateProtocolFeeRewardAccumulation(manager *staker.ProtocolFeeRewardManager, tokenPaths []string) {
	for _, tokenPath := range tokenPaths {
		accumulatedProtocolFeeX128PerStake := "0"
		foldedEpoch := int64(-1)
		if accumulator, ok := manager.GetTokenAccumulator(tokenPath); ok {
			accumulatedProtocolFeeX128PerStake = accumulator.GetAccumulatedX128PerStake().ToString()
			foldedEpoch = accumulator.GetFoldedEpoch()
		}

		chain.Emit(
			"UpdateProtocolFeeRewardAccumulation",
			"tokenPath", tokenPath,
			"totalStakedAmount", utils.FormatInt(manager.GetTotalStakedAmount()),
			"protocolFeeAmount", utils.FormatInt(manager.GetProtocolFeeAmount(tokenPath)),
			"accumulatedProtocolFeeX128PerStake", accumulatedProtocolFeeX128PerStake,
			"foldedEpoch", utils.FormatInt(foldedEpoch),
			"accumulatedTimestamp", utils.FormatInt(manager.GetAccumulatedTimestamp()),
		)
	}
}

errors.gno

package staker

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

const (
	errDataNotFound                   = "[GNOSWAP-GOV_STAKER-001] requested data not found"
	errInvalidAmount                  = "[GNOSWAP-GOV_STAKER-002] invalid amount"
	errNoDelegatedAmount              = "[GNOSWAP-GOV_STAKER-003] zero delegated amount"
	errNotEnoughDelegated             = "[GNOSWAP-GOV_STAKER-004] not enough delegated"
	errInvalidAddress                 = "[GNOSWAP-GOV_STAKER-005] invalid address"
	errNotEnoughBalance               = "[GNOSWAP-GOV_STAKER-006] not enough balance"
	errLessThanMinimum                = "[GNOSWAP-GOV_STAKER-007] cannot delegate less than minimum amount"
	errInvalidSnapshotTime            = "[GNOSWAP-GOV_STAKER-008] invalid snapshot time"
	errSameDelegatee                  = "[GNOSWAP-GOV_STAKER-009] cannot redelegate to same address"
	errWithdrawNotCollectable         = "[GNOSWAP-GOV_STAKER-010] withdraw is not collectable"
	errAmountMustBeNonNegative        = "[GNOSWAP-GOV_STAKER-011] amount must be non-negative"
	errTotalStakedAmountOverflow      = "[GNOSWAP-GOV_STAKER-012] total staked amount would overflow"
	errRemoveAmountExceedsTotalStaked = "[GNOSWAP-GOV_STAKER-013] remove amount exceeds total staked amount"
	errRemoveAmountExceedsStaked      = "[GNOSWAP-GOV_STAKER-014] remove amount exceeds staked amount"
	errAmountMustBePositive           = "[GNOSWAP-GOV_STAKER-015] amount must be positive"
	errRewardDebtUpdateRequired       = "[GNOSWAP-GOV_STAKER-016] must update reward debt before claiming rewards"
	errDelegatedAmountNegative        = "[GNOSWAP-GOV_STAKER-017] delegated amount cannot be negative"
	errUndelegationAmountNegative     = "[GNOSWAP-GOV_STAKER-018] undelegation amount cannot be negative"
	errDelegationNotFound             = "[GNOSWAP-GOV_STAKER-019] delegation not found"
	errInvalidAccrualEpoch            = "[GNOSWAP-GOV_STAKER-020] accrual epoch is older than the epoch in force"
	errInvalidAccrualBuckets          = "[GNOSWAP-GOV_STAKER-021] invalid accrual buckets"
)

func makeErrorWithDetails(message string, detail string) error {
	return ufmt.Errorf("%s || %s", message, detail)
}

getter.gno

package staker

import (
	"time"

	gnsmath "gno.land/p/gnoswap/gnsmath/v1"
	"gno.land/p/gnoswap/uint256/v1"
	rotree "gno.land/p/nt/bptree/rotree/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/emission"
	"gno.land/r/gnoswap/gov/staker"
	"gno.land/r/gnoswap/gov/xgns"
)

// GetTotalxGnsSupply returns the total amount of xGNS supply, including
// xGNS held by the launchpad.
//
// Returns:
//   - int64: total xGNS supply, including the launchpad balance.
func (gs *govStakerV1) GetTotalxGnsSupply() int64 {
	return xgns.TotalSupply()
}

// GetTotalDelegated returns the total amount of xGNS delegated.
//
// Returns:
//   - int64: total xGNS amount currently delegated.
func (gs *govStakerV1) GetTotalDelegated() int64 {
	return gs.store.GetTotalDelegatedAmount()
}

// GetTotalLockedAmount returns the total amount of locked GNS.
//
// Returns:
//   - int64: total GNS amount currently locked.
func (gs *govStakerV1) GetTotalLockedAmount() int64 {
	return gs.store.GetTotalLockedAmount()
}

// GetUnDelegationLockupPeriod returns the undelegation lockup period in seconds.
//
// Returns:
//   - int64: number of seconds an undelegation remains locked.
func (gs *govStakerV1) GetUnDelegationLockupPeriod() int64 {
	return gs.store.GetUnDelegationLockupPeriod()
}

// GetDelegations returns a read-only view of every delegation, keyed by the
// decimal string form of the delegation ID.
//
// Returns:
//   - *rotree.ReadOnlyTree: read-only delegation tree keyed by decimal ID.
func (gs *govStakerV1) GetDelegations() *rotree.ReadOnlyTree {
	return rotree.Wrap(gs.store.GetAllDelegations(), cloneDelegationEntry)
}

// ExistsDelegation checks if a delegation exists.
//
// Parameters:
//   - delegationID: delegation identifier to look up.
//
// Returns:
//   - bool: true when delegationID is stored, otherwise false.
func (gs *govStakerV1) ExistsDelegation(delegationID int64) bool {
	return gs.store.HasDelegation(delegationID)
}

// GetDelegatorDelegations returns a read-only view of a delegator's delegations,
// keyed by delegatee address with that pair's delegation IDs as the value.
// nil is returned when the delegator has no delegations.
//
// Parameters:
//   - delegator: address whose outgoing delegations are requested.
//
// Returns:
//   - *rotree.ReadOnlyTree: read-only tree keyed by delegatee address, or nil
//     when delegator has no delegation entries.
func (gs *govStakerV1) GetDelegatorDelegations(delegator address) *rotree.ReadOnlyTree {
	delegationManager := gs.store.GetDelegationManager()
	delegatorTree, exists := delegationManager.GetDelegatorDelegations(delegator.String())
	if !exists {
		return nil
	}
	return rotree.Wrap(delegatorTree, cloneDelegationIDsEntry)
}

// GetUserDelegationIDs returns the delegation IDs for a specific delegator and
// delegatee.
//
// Parameters:
//   - delegator: address that created the delegations.
//   - delegatee: address receiving the delegations.
//
// Returns:
//   - []int64: delegation IDs for the delegator/delegatee pair, or an empty
//     slice when no pair is stored.
func (gs *govStakerV1) GetUserDelegationIDs(delegator address, delegatee address) []int64 {
	delegationManager := gs.store.GetDelegationManager()

	delegationIDs, exists := delegationManager.GetDelegationIDs(delegator.String(), delegatee.String())
	if !exists {
		return []int64{}
	}

	return delegationIDs
}

// HasDelegationSnapshotsKey reports whether delegation history has been stored.
//
// Returns:
//   - bool: true when the total delegation history storage key exists.
func (gs *govStakerV1) HasDelegationSnapshotsKey() bool {
	return gs.store.HasTotalDelegationHistoryStoreKey()
}

// GetTotalDelegationAmountAtSnapshot returns the total delegation amount at a
// Unix timestamp. It uses ReverseIterate to find the most recent history entry
// at or before that timestamp; this is a timestamp lookup, not a block snapshot.
//
// Parameters:
//   - snapshotTime: Unix timestamp to retrieve the history value for
//
// Returns:
//   - int64: total delegation amount at the specified time
//   - bool: true when a history entry exists at or before the timestamp
func (gs *govStakerV1) GetTotalDelegationAmountAtSnapshot(snapshotTime int64) (int64, bool) {
	history := gs.store.GetTotalDelegationHistory()
	if history.Size() == 0 {
		return 0, false
	}

	var (
		totalAmount int64
		exists      bool
	)

	// ReverseIterate from 0 to snapshotTime to find the most recent entry at or before snapshotTime
	history.ReverseIterate(0, snapshotTime, func(key int64, value any) bool {
		amountInt, ok := value.(int64)
		if !ok {
			panic(ufmt.Sprintf("invalid amount type: %T", value))
		}

		totalAmount = amountInt
		exists = true

		return true // stop after first (most recent) entry
	})

	return totalAmount, exists
}

// GetUserDelegationAmountAtSnapshot returns one user's delegation amount at a
// Unix timestamp. The history is keyed by address and timestamp, and the
// lookup returns the most recent entry at or before the requested time.
//
// Parameters:
//   - userAddr: address of the user
//   - snapshotTime: Unix timestamp to retrieve
//
// Returns:
//   - int64: user delegation amount at the specified time
//   - bool: true when a history entry exists at or before the timestamp
func (gs *govStakerV1) GetUserDelegationAmountAtSnapshot(userAddr address, snapshotTime int64) (int64, bool) {
	history := gs.store.GetUserDelegationHistory()

	addrStr := userAddr.String()
	lo, _ := userHistoryKeyRange(addrStr)
	// Inclusive upper bound: largest key for this address at or before snapshotTime.
	hi := makeUserHistoryKey(addrStr, snapshotTime)

	var (
		userAmount int64
		exists     bool
	)

	// ReverseIterate from hi down to lo to find the most recent entry at or before snapshotTime
	history.ReverseIterate(lo, hi, func(_ string, value any) bool {
		amountInt, ok := value.(int64)
		if !ok {
			panic(ufmt.Sprintf("invalid amount type: %T", value))
		}

		userAmount = amountInt
		exists = true

		return true // stop after first (most recent) entry
	})

	return userAmount, exists
}

// GetClaimableRewardByAddress returns the claimable rewards for an address.
//
// Parameters:
//   - addr: staker address whose emission and protocol fee rewards are requested.
//
// Returns:
//   - int64: claimable emission reward amount.
//   - map[string]int64: claimable protocol fee amounts keyed by token path.
//   - error: nil on success; an error when emission or protocol fee reward
//     resolution fails.
func (gs *govStakerV1) GetClaimableRewardByAddress(addr address) (int64, map[string]int64, error) {
	return gs.GetClaimableRewardByRewardID(addr.String())
}

// GetClaimableRewardByLaunchpad returns the claimable rewards for a launchpad
// project address.
//
// Parameters:
//   - addr: launchpad project address used to derive its reward ID.
//
// Returns:
//   - int64: claimable emission reward amount for the launchpad project.
//   - map[string]int64: claimable protocol fee amounts keyed by token path.
//   - error: nil on success; an error when emission or protocol fee reward
//     resolution fails.
func (gs *govStakerV1) GetClaimableRewardByLaunchpad(addr address) (int64, map[string]int64, error) {
	return gs.GetClaimableRewardByRewardID(gs.makeLaunchpadRewardID(addr.String()))
}

// GetClaimableRewardByRewardID returns the claimable rewards for a reward ID.
//
// Parameters:
//   - rewardID: emission/protocol-fee reward state identifier to inspect.
//
// Returns:
//   - int64: claimable emission reward amount.
//   - map[string]int64: claimable protocol fee amounts keyed by token path.
//   - error: nil on success; an error when emission or protocol fee reward
//     resolution fails.
func (gs *govStakerV1) GetClaimableRewardByRewardID(rewardID string) (int64, map[string]int64, error) {
	emissionDistributedAmount := emission.GetAccuDistributedToGovStaker()
	emissionRewardManager := gs.store.GetEmissionRewardManager()
	emissionResolver := NewEmissionRewardManagerResolver(emissionRewardManager)
	emissionReward, err := emissionResolver.GetClaimableRewardAmount(emissionDistributedAmount, rewardID, time.Now().Unix())
	if err != nil {
		return 0, make(map[string]int64), err
	}

	protocolFeeRewards, err := gs.getClaimableProtocolFeeRewards(rewardID)
	if err != nil {
		return 0, make(map[string]int64), err
	}

	return emissionReward, protocolFeeRewards, nil
}

// GetLaunchpadProjectDeposit returns the deposit amount for a launchpad project.
//
// Parameters:
//   - projectAddr: launchpad project address used to derive its reward ID.
//
// Returns:
//   - int64: stored launchpad project deposit amount.
//   - bool: true when a deposit exists for projectAddr, otherwise false.
func (gs *govStakerV1) GetLaunchpadProjectDeposit(projectAddr string) (int64, bool) {
	launchpadDeposits := gs.store.GetLaunchpadProjectDeposits()
	return launchpadDeposits.GetDeposit(gs.makeLaunchpadRewardID(projectAddr))
}

// GetDelegationWithdrawCount returns the total number of delegation withdraws
// for a specific delegation.
//
// Parameters:
//   - delegationID: delegation identifier whose withdrawals are counted.
//
// Returns:
//   - int: number of withdrawals recorded for delegationID, or zero when the
//     delegation does not exist.
func (gs *govStakerV1) GetDelegationWithdrawCount(delegationID int64) int {
	delegation, exists := gs.store.GetDelegation(delegationID)
	if !exists {
		return 0
	}
	return len(delegation.Withdraws())
}

// GetDelegationWithdraws returns a paginated list of delegation withdraws for a
// specific delegation.
//
// Parameters:
//   - delegationID: delegation identifier whose withdrawals are requested.
//   - offset: zero-based index of the first withdrawal to return.
//   - count: maximum number of withdrawals to return.
//
// Returns:
//   - []staker.DelegationWithdraw: withdrawals in the requested range, or an
//     empty slice when the delegation or page is absent.
//   - error: nil; this accessor currently has no error path.
func (gs *govStakerV1) GetDelegationWithdraws(delegationID int64, offset, count int) ([]staker.DelegationWithdraw, error) {
	delegation, exists := gs.store.GetDelegation(delegationID)
	if !exists {
		return []staker.DelegationWithdraw{}, nil
	}

	withdraws := delegation.Withdraws()
	size := len(withdraws)
	if offset >= size {
		return []staker.DelegationWithdraw{}, nil
	}

	end := offset + count
	if end > size {
		end = size
	}

	return withdraws[offset:end], nil
}

// GetCollectableWithdrawAmount returns the collectable withdraw amount for a
// specific delegation as of the current Unix time.
//
// Parameters:
//   - delegationID: delegation identifier whose matured withdrawals are summed.
//
// Returns:
//   - int64: total amount currently collectable, or zero when the delegation
//     does not exist.
func (gs *govStakerV1) GetCollectableWithdrawAmount(delegationID int64) int64 {
	delegation, exists := gs.store.GetDelegation(delegationID)
	if !exists {
		return 0
	}

	totalAmount := int64(0)
	currentTime := time.Now().Unix()
	for _, withdraw := range delegation.Withdraws() {
		resolver := NewDelegationWithdrawResolver(&withdraw)
		totalAmount = gnsmath.SafeAddInt64(totalAmount, resolver.CollectableAmount(currentTime))
	}

	return totalAmount
}

// GetProtocolFeeAccumulatedX128PerStake returns the accumulated protocol fee per
// stake (Q128) for a token path.
//
// Parameters:
//   - tokenPath: token identifier/path whose accumulator is requested.
//
// Returns:
//   - *uint256.Uint: accumulated protocol fee per stake scaled by 2^128, or a
//     zero value when no accumulator exists for tokenPath.
func (gs *govStakerV1) GetProtocolFeeAccumulatedX128PerStake(tokenPath string) *uint256.Uint {
	protocolFeeRewardManager := gs.store.GetProtocolFeeRewardManager()
	accumulatedFee := protocolFeeRewardManager.GetAccumulatedProtocolFeeX128PerStake(tokenPath)
	if accumulatedFee == nil {
		return uint256.NewUint(0)
	}

	return accumulatedFee
}

// GetProtocolFeeAmount returns the protocol fee amount accumulated for a token
// path.
//
// Parameters:
//   - tokenPath: token identifier/path whose folded fee amount is requested.
//
// Returns:
//   - int64: accumulated protocol fee amount for tokenPath.
func (gs *govStakerV1) GetProtocolFeeAmount(tokenPath string) int64 {
	protocolFeeRewardManager := gs.store.GetProtocolFeeRewardManager()
	return protocolFeeRewardManager.GetProtocolFeeAmount(tokenPath)
}

// GetProtocolFeeAccumulatedTimestamp returns the accumulated timestamp for
// protocol fee rewards.
//
// Returns:
//   - int64: Unix timestamp represented by protocol fee accumulation state.
func (gs *govStakerV1) GetProtocolFeeAccumulatedTimestamp() int64 {
	protocolFeeRewardManager := gs.store.GetProtocolFeeRewardManager()
	return protocolFeeRewardManager.GetAccumulatedTimestamp()
}

// GetEmissionAccumulatedX128PerStake returns the accumulated emission per stake
// (Q128).
//
// Returns:
//   - *uint256.Uint: accumulated emission reward per stake scaled by 2^128.
func (gs *govStakerV1) GetEmissionAccumulatedX128PerStake() *uint256.Uint {
	emissionRewardManager := gs.store.GetEmissionRewardManager()
	return emissionRewardManager.GetAccumulatedRewardX128PerStake()
}

// GetEmissionDistributedAmount returns the total distributed emission amount.
//
// Returns:
//   - int64: total emission amount recorded as distributed to governance stakers.
func (gs *govStakerV1) GetEmissionDistributedAmount() int64 {
	emissionRewardManager := gs.store.GetEmissionRewardManager()
	return emissionRewardManager.GetDistributedAmount()
}

// GetEmissionAccumulatedTimestamp returns the accumulated timestamp for emission
// rewards.
//
// Returns:
//   - int64: Unix timestamp represented by emission accumulation state.
func (gs *govStakerV1) GetEmissionAccumulatedTimestamp() int64 {
	emissionRewardManager := gs.store.GetEmissionRewardManager()
	return emissionRewardManager.GetAccumulatedTimestamp()
}

getter_utils.gno

package staker

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

// cloneDelegationEntry is the transformation for the delegation tree.
// Delegation is mutable and its setters are declared in /r/gnoswap/gov/staker,
// so an external holder of the stored pointer could write realm state through
// it.
func cloneDelegationEntry(value any) any {
	delegation, ok := value.(*staker.Delegation)
	if !ok {
		return nil
	}

	return delegation.Clone()
}

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

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

	return cloned
}

gnomod.toml

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

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

init.gno

package staker

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

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

func registerGovStakerV1(cur realm) {
	staker.RegisterInitializer(cross(cur), func(_ int, rlm realm, store staker.IGovStakerStore) staker.IGovStaker {
		// `rlm` here is the gov/staker proxy realm threaded in by
		// staker.RegisterInitializer. Per-version store bootstrap writes
		// therefore pass the proxy's KV-store ACL.
		err := initStoreData(0, rlm, store)
		if err != nil {
			panic(err)
		}

		return NewGovStakerV1(store)
	})
}

func initStoreData(_ int, rlm realm, store staker.IGovStakerStore) error {
	// Initialize basic configuration
	if !store.HasUnDelegationLockupPeriodStoreKey() {
		err := store.SetUnDelegationLockupPeriod(0, rlm, int64(7*24*60*60)) // 7 days default
		if err != nil {
			return err
		}
	}

	if !store.HasTotalDelegatedAmountStoreKey() {
		err := store.SetTotalDelegatedAmount(0, rlm, int64(0))
		if err != nil {
			return err
		}
	}

	if !store.HasTotalLockedAmountStoreKey() {
		err := store.SetTotalLockedAmount(0, rlm, int64(0))
		if err != nil {
			return err
		}
	}

	// Initialize delegation management
	if !store.HasDelegationCounterStoreKey() {
		err := store.SetDelegationCounter(0, rlm, staker.NewCounter())
		if err != nil {
			return err
		}
	}

	if !store.HasDelegationsStoreKey() {
		err := store.SetDelegations(0, rlm, staker.NewDelegationTree())
		if err != nil {
			return err
		}
	}

	// Initialize total delegation history (timestamp -> int64)
	if !store.HasTotalDelegationHistoryStoreKey() {
		err := store.SetTotalDelegationHistory(0, rlm, staker.NewUintTree())
		if err != nil {
			return err
		}
	}

	// Initialize user delegation history (address -> *UintTree[timestamp -> int64])
	if !store.HasUserDelegationHistoryStoreKey() {
		err := store.SetUserDelegationHistory(0, rlm, staker.NewUserDelegationTree())
		if err != nil {
			return err
		}
	}

	// Initialize EmissionRewardManager
	if !store.HasEmissionRewardManagerStoreKey() {
		emissionRewardManager := staker.NewEmissionRewardManager()
		err := store.SetEmissionRewardManager(0, rlm, emissionRewardManager)
		if err != nil {
			return err
		}
	}

	// Initialize ProtocolFeeRewardManager
	if !store.HasProtocolFeeRewardManagerStoreKey() {
		protocolFeeRewardManager := staker.NewProtocolFeeRewardManager()
		err := store.SetProtocolFeeRewardManager(0, rlm, protocolFeeRewardManager)
		if err != nil {
			return err
		}
	}

	// Initialize LaunchpadProjectDeposits
	if !store.HasLaunchpadProjectDepositsStoreKey() {
		launchpadDeposits := staker.NewLaunchpadProjectDeposits()
		err := store.SetLaunchpadProjectDeposits(0, rlm, launchpadDeposits)
		if err != nil {
			return err
		}
	}

	// Initialize DelegationManager
	if !store.HasDelegationManagerStoreKey() {
		delegationManager := staker.NewDelegationManager()
		err := store.SetDelegationManager(0, rlm, delegationManager)
		if err != nil {
			return err
		}
	}

	return nil
}

instance.gno

package staker

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

type govStakerV1 struct {
	store staker.IGovStakerStore
}

// NewGovStakerV1 creates the governance staker v1 implementation backed by store.
//
// Parameters:
//   - store: governance-staker storage interface used by the implementation.
//
// Returns:
//   - staker.IGovStaker: governance staker API backed by store.
func NewGovStakerV1(store staker.IGovStakerStore) staker.IGovStaker {
	return &govStakerV1{store}
}

launchpad_project_deposits.gno

package staker

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

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

type LaunchpadProjectDepositsResolver struct {
	*staker.LaunchpadProjectDeposits
}

// NewLaunchpadProjectDepositsResolver wraps launchpad project deposit state.
//
// Parameters:
//   - launchpadProjectDeposits: project deposit state to resolve and mutate
//
// Returns:
//   - *LaunchpadProjectDepositsResolver: resolver retaining the supplied deposit state pointer
func NewLaunchpadProjectDepositsResolver(launchpadProjectDeposits *staker.LaunchpadProjectDeposits) *LaunchpadProjectDepositsResolver {
	return &LaunchpadProjectDepositsResolver{launchpadProjectDeposits}
}

// getLaunchpadProjectDeposit retrieves the deposit amount for a launchpad project.
//
// Parameters:
//   - ownerAddress: project owner's address identifier
//
// Returns:
//   - int64: deposit amount
//   - bool: true if project exists, false otherwise
func (lpdr *LaunchpadProjectDepositsResolver) getLaunchpadProjectDeposit(ownerAddress string) (int64, bool) {
	return lpdr.LaunchpadProjectDeposits.GetDeposit(ownerAddress)
}

// setLaunchpadProjectDeposit sets the deposit amount for a launchpad project.
//
// Parameters:
//   - ownerAddress: project owner's address identifier
//   - deposit: deposit amount to set
//
// Returns:
//   - bool: true if successfully set
func (lpdr *LaunchpadProjectDepositsResolver) setLaunchpadProjectDeposit(ownerAddress string, deposit int64) bool {
	lpdr.LaunchpadProjectDeposits.SetDeposit(ownerAddress, deposit)
	return true
}

// addDeposit adds to the deposit amount for a launchpad project.
// This method ensures the deposit doesn't go negative.
//
// Parameters:
//   - ownerAddress: project owner's address identifier
//   - amount: amount to add to the deposit
func (lpdr *LaunchpadProjectDepositsResolver) addDeposit(ownerAddress string, amount int64) {
	currentDeposit, _ := lpdr.LaunchpadProjectDeposits.GetDeposit(ownerAddress)
	newDeposit := gnsmath.SafeAddInt64(currentDeposit, amount)
	if newDeposit < 0 {
		newDeposit = 0
	}
	lpdr.LaunchpadProjectDeposits.SetDeposit(ownerAddress, newDeposit)
}

// removeDeposit removes from the deposit amount for a launchpad project.
// This method ensures the deposit doesn't go negative.
//
// Parameters:
//   - ownerAddress: project owner's address identifier
//   - amount: amount to remove from the deposit
func (lpdr *LaunchpadProjectDepositsResolver) removeDeposit(ownerAddress string, amount int64) {
	currentDeposit, exists := lpdr.LaunchpadProjectDeposits.GetDeposit(ownerAddress)
	if !exists {
		return
	}
	newDeposit := gnsmath.SafeSubInt64(currentDeposit, amount)
	if newDeposit < 0 {
		newDeposit = 0
	}
	lpdr.LaunchpadProjectDeposits.SetDeposit(ownerAddress, newDeposit)
}

protocol_fee_reward_manager.gno

package staker

import (
	"errors"
	"math"

	"gno.land/p/gnoswap/gnsmath/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"

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

// ProtocolFeeRewardManagerResolver drives the ProtocolFeeRewardManager.
//
// Stake changes only move the epoch, the total stake history and the staker's own
// event list. Fees are folded into a token's accumulator when that token is collected,
// each accrual bucket against the total stake in force during its epoch.
type ProtocolFeeRewardManagerResolver struct {
	*staker.ProtocolFeeRewardManager
}

// NewProtocolFeeRewardManagerResolver wraps the shared protocol-fee reward manager.
//
// Parameters:
//   - manager: Protocol-fee reward state to resolve and mutate.
//
// Returns:
//   - *ProtocolFeeRewardManagerResolver: resolver operating on manager's accounting state.
func NewProtocolFeeRewardManagerResolver(manager *staker.ProtocolFeeRewardManager) *ProtocolFeeRewardManagerResolver {
	return &ProtocolFeeRewardManagerResolver{
		ProtocolFeeRewardManager: manager,
	}
}

// addStake records that rewardID staked amount more from epoch on.
//
// epoch is the accrual epoch protocol_fee just opened for this change, so it must not
// be older than the epoch in force.
func (self *ProtocolFeeRewardManagerResolver) addStake(rewardID string, amount int64, epoch int64) error {
	if amount <= 0 {
		return errors.New(errAmountMustBePositive)
	}
	if epoch < self.GetCurrentEpoch() {
		return errors.New(errInvalidAccrualEpoch)
	}

	currentTotal := self.GetTotalStakedAmount()
	if currentTotal > math.MaxInt64-amount {
		return errors.New(errTotalStakedAmountOverflow)
	}

	rewardState, ok, err := self.GetRewardState(rewardID)
	if err != nil {
		return err
	}
	if !ok {
		rewardState = staker.NewProtocolFeeRewardState()
	}

	resolvedState := NewProtocolFeeRewardStateResolver(rewardState)
	if err := resolvedState.addStake(amount, epoch); err != nil {
		return err
	}

	self.recordTotalStakedAmount(epoch, gnsmath.SafeAddInt64(currentTotal, amount))
	self.SetRewardState(rewardID, rewardState)

	return nil
}

// removeStake records that rewardID staked amount less from epoch on.
func (self *ProtocolFeeRewardManagerResolver) removeStake(rewardID string, amount int64, epoch int64) error {
	if amount < 0 {
		return errors.New(errAmountMustBeNonNegative)
	}
	if epoch < self.GetCurrentEpoch() {
		return errors.New(errInvalidAccrualEpoch)
	}

	updatedTotal := gnsmath.SafeSubInt64(self.GetTotalStakedAmount(), amount)
	if updatedTotal < 0 {
		return errors.New(errRemoveAmountExceedsTotalStaked)
	}

	rewardState, ok, err := self.GetRewardState(rewardID)
	if err != nil {
		return err
	}
	if !ok {
		rewardState = staker.NewProtocolFeeRewardState()
	}

	resolvedState := NewProtocolFeeRewardStateResolver(rewardState)
	if err := resolvedState.removeStake(amount, epoch); err != nil {
		return err
	}

	self.recordTotalStakedAmount(epoch, updatedTotal)
	self.SetRewardState(rewardID, rewardState)

	return nil
}

func (self *ProtocolFeeRewardManagerResolver) recordTotalStakedAmount(epoch int64, totalStakedAmount int64) {
	self.SetCurrentEpoch(epoch)
	self.SetTotalStakedAmount(totalStakedAmount)
	self.SetTotalStakedAmountAt(epoch, totalStakedAmount)
}

// applyAccrualBuckets folds consumed accrual buckets of tokenPath into its accumulator.
//
// epochs and amounts are parallel and in ascending epoch order. Each amount is divided
// by the total stake in force during its epoch; with nothing staked the amount is
// dropped, the same policy the emission accumulator applies. exhausted reports that
// no bucket is left pending, which lets the accumulator mark every closed epoch as
// fully folded.
func (self *ProtocolFeeRewardManagerResolver) applyAccrualBuckets(
	tokenPath string,
	epochs []int64,
	amounts []int64,
	exhausted bool,
	currentTimestamp int64,
) error {
	if len(epochs) != len(amounts) {
		return errors.New(errInvalidAccrualBuckets)
	}

	accumulator, ok := self.GetTokenAccumulator(tokenPath)
	if !ok {
		if len(epochs) == 0 {
			return nil
		}
		accumulator = staker.NewProtocolFeeTokenAccumulator()
		self.SetTokenAccumulator(tokenPath, accumulator)
	}

	currentX128 := accumulator.GetAccumulatedX128PerStake().Clone()
	feeAmount := accumulator.GetProtocolFeeAmount()
	lastEpoch := int64(-1)

	for i, epoch := range epochs {
		if epoch < lastEpoch || epoch > self.GetCurrentEpoch() {
			return errors.New(errInvalidAccrualBuckets)
		}
		lastEpoch = epoch

		amount := amounts[i]
		if amount < 0 {
			return errors.New(errInvalidAccrualBuckets)
		}
		feeAmount = gnsmath.SafeAddInt64(feeAmount, amount)

		totalStakedAmount := self.GetTotalStakedAmountAt(epoch)
		if totalStakedAmount <= 0 || amount == 0 {
			continue
		}

		// Scale the amount by 2^128 before dividing by the total stake. The amount
		// fits in 63 bits, so the product fits in 191 bits and cannot overflow.
		amountX128 := u256.Zero().Lsh(u256.NewUintFromInt64(amount), 128)
		perStakeX128 := u256.Zero().Div(amountX128, u256.NewUintFromInt64(totalStakedAmount))
		currentX128 = u256.Zero().Add(currentX128, perStakeX128)

		accumulator.SetAccumulatedX128PerStakeAt(epoch, currentX128)
	}

	accumulator.SetProtocolFeeAmount(feeAmount)

	// Every epoch before the one in force is closed, so it is fully folded once no bucket
	// is left. Otherwise only the epochs up to the last consumed bucket are complete.
	foldedEpoch := accumulator.GetFoldedEpoch()
	if exhausted {
		foldedEpoch = maxInt64(foldedEpoch, self.GetCurrentEpoch()-1)
	} else if lastEpoch >= 0 {
		foldedEpoch = maxInt64(foldedEpoch, minInt64(lastEpoch, self.GetCurrentEpoch()-1))
	}
	accumulator.SetFoldedEpoch(foldedEpoch)

	self.SetAccumulatedTimestamp(currentTimestamp)

	return nil
}

// accumulatorView returns a read view of tokenPath's accumulator.
//
// With pendingComplete false the view reflects the accumulator exactly as folded so
// far, which is what a collect must settle against. With pendingComplete true the
// given buckets are the whole pending set of the token: they are projected on top, as
// applyAccrualBuckets would fold them, and every closed epoch counts as folded, which
// is what an exhaustive fold would leave behind. A query uses the latter so that it
// reports what a collect would pay even when a previous bounded fold consumed exactly
// its limit and left foldedEpoch behind the epoch in force.
func (self *ProtocolFeeRewardManagerResolver) accumulatorView(tokenPath string, pendingEpochs []int64, pendingAmounts []int64, pendingComplete bool) *protocolFeeAccumulatorView {
	view := &protocolFeeAccumulatorView{
		extraEpochs:  []int64{},
		extraValues:  []*u256.Uint{},
		current:      u256.Zero(),
		firstEpoch:   -1,
		foldedEpoch:  -1,
		currentEpoch: self.GetCurrentEpoch(),
	}

	if accumulator, ok := self.GetTokenAccumulator(tokenPath); ok {
		view.accumulator = accumulator
		view.current = accumulator.GetAccumulatedX128PerStake().Clone()
		view.firstEpoch = accumulator.GetFirstEpoch()
		view.foldedEpoch = accumulator.GetFoldedEpoch()
	}

	if pendingComplete {
		// Projecting the whole pending set folds every closed epoch.
		view.foldedEpoch = maxInt64(view.foldedEpoch, view.currentEpoch-1)
	}

	for i, epoch := range pendingEpochs {
		totalStakedAmount := self.GetTotalStakedAmountAt(epoch)
		if totalStakedAmount <= 0 || pendingAmounts[i] <= 0 {
			continue
		}

		amountX128 := u256.Zero().Lsh(u256.NewUintFromInt64(pendingAmounts[i]), 128)
		perStakeX128 := u256.Zero().Div(amountX128, u256.NewUintFromInt64(totalStakedAmount))
		view.current = u256.Zero().Add(view.current, perStakeX128)
		view.extraEpochs = append(view.extraEpochs, epoch)
		view.extraValues = append(view.extraValues, view.current.Clone())
		if view.firstEpoch < 0 {
			view.firstEpoch = epoch
		}
	}

	return view
}

// claimTokenReward settles tokenPath for rewardID and returns the reward collected.
// See ProtocolFeeRewardStateResolver.claimTokenReward for the maxEvents bound.
func (self *ProtocolFeeRewardManagerResolver) claimTokenReward(rewardID string, tokenPath string, maxEvents int64) (int64, error) {
	rewardState, ok, err := self.GetRewardState(rewardID)
	if err != nil {
		return 0, err
	}
	if !ok {
		return 0, nil
	}

	resolvedState := NewProtocolFeeRewardStateResolver(rewardState)
	reward, err := resolvedState.claimTokenReward(tokenPath, self.accumulatorView(tokenPath, nil, nil, false), maxEvents)
	if err != nil {
		return 0, err
	}

	self.SetRewardState(rewardID, rewardState)

	return reward, nil
}

// claimRewards settles every folded token for rewardID and returns the reward
// collected per token. Its cost grows with the number of tokens that ever collected a
// fee; claimTokenReward is the bounded alternative.
func (self *ProtocolFeeRewardManagerResolver) claimRewards(rewardID string, currentTimestamp int64) (map[string]int64, error) {
	rewards := make(map[string]int64)

	rewardState, ok, err := self.GetRewardState(rewardID)
	if err != nil {
		return nil, err
	}
	if !ok {
		return rewards, nil
	}

	resolvedState := NewProtocolFeeRewardStateResolver(rewardState)
	if !resolvedState.IsClaimable(currentTimestamp) {
		return rewards, nil
	}

	for _, tokenPath := range self.GetTokenPaths() {
		reward, err := resolvedState.claimTokenReward(tokenPath, self.accumulatorView(tokenPath, nil, nil, false), 0)
		if err != nil {
			return nil, err
		}
		rewards[tokenPath] = reward
	}

	resolvedState.SetClaimedTimestamp(currentTimestamp)
	self.SetRewardState(rewardID, rewardState)

	return rewards, nil
}

// GetClaimableRewardAmount returns what collecting tokenPath for rewardID would pay,
// with the given pending buckets projected on top of the accumulator.
// Parameters:
//   - rewardID: Identifier of the staker whose claimable reward is quoted.
//   - tokenPath: Token path whose claimable protocol-fee reward is quoted.
//   - pendingEpochs: Pending bucket epochs projected on the accumulator.
//   - pendingAmounts: Pending fee amounts parallel to pendingEpochs.
//
// Returns:
//   - int64: protocol-fee amount that collecting tokenPath would pay in token base units.
//   - error: nil on success; non-nil when reward-state lookup or projection fails.
func (self *ProtocolFeeRewardManagerResolver) GetClaimableRewardAmount(rewardID string, tokenPath string, pendingEpochs []int64, pendingAmounts []int64) (int64, error) {
	rewardState, ok, err := self.GetRewardState(rewardID)
	if err != nil {
		return 0, err
	}
	if !ok {
		return 0, nil
	}

	resolvedState := NewProtocolFeeRewardStateResolver(rewardState)

	return resolvedState.getClaimableReward(tokenPath, self.accumulatorView(tokenPath, pendingEpochs, pendingAmounts, true)), nil
}

func maxInt64(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

func minInt64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

protocol_fee_reward_state.gno

package staker

import (
	"errors"

	"gno.land/p/gnoswap/consts/v1"
	"gno.land/p/gnoswap/gnsmath/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"

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

// ProtocolFeeRewardStateResolver settles one staker's protocol fee rewards.
//
// A staker's reward for a token is the sum, over the segments between their stake
// events, of the stake held during the segment times the growth of the token's
// accumulated fee per stake across it. Segments are folded in event order, so the work
// of settling a token is proportional to the staker's own stake changes since the token
// was last settled, never to the number of tokens.
type ProtocolFeeRewardStateResolver struct {
	*staker.ProtocolFeeRewardState
}

// NewProtocolFeeRewardStateResolver wraps one staker's protocol fee reward state
// with settlement operations.
//
// Parameters:
//   - protocolFeeRewardState: staker reward state to resolve and mutate.
//
// Returns:
//   - *ProtocolFeeRewardStateResolver: resolver backed by protocolFeeRewardState.
func NewProtocolFeeRewardStateResolver(protocolFeeRewardState *staker.ProtocolFeeRewardState) *ProtocolFeeRewardStateResolver {
	return &ProtocolFeeRewardStateResolver{
		ProtocolFeeRewardState: protocolFeeRewardState,
	}
}

// protocolFeeAccumulatorView reads a token accumulator as it stands, optionally
// extended in memory with buckets that are still pending on the protocol fee realm.
// The extension lets a query report what a collect would pay without folding anything.
type protocolFeeAccumulatorView struct {
	accumulator *staker.ProtocolFeeTokenAccumulator // nil when the token was never folded
	// extraEpochs and extraValues hold projected history entries, in ascending epoch order
	extraEpochs []int64
	extraValues []*u256.Uint
	// current is the latest accumulated value, projection included
	current *u256.Uint
	// firstEpoch is the first epoch a fee was folded for, projection included, or -1
	firstEpoch int64
	// foldedEpoch is the last epoch whose fees are known to be fully folded, or -1
	foldedEpoch int64
	// currentEpoch is the accrual epoch in force on the manager
	currentEpoch int64
}

// at returns the accumulated value after the fees of the latest known epoch at or
// before epoch.
func (v *protocolFeeAccumulatorView) at(epoch int64) *u256.Uint {
	for i := len(v.extraEpochs) - 1; i >= 0; i-- {
		if v.extraEpochs[i] <= epoch {
			return v.extraValues[i]
		}
	}

	if v.accumulator == nil {
		return u256.Zero()
	}

	return v.accumulator.GetAccumulatedX128PerStakeAt(epoch)
}

// protocolFeeTokenSettlement is the in-memory working copy of a token's settlement
// state. It is written back only on a collect, so queries never touch storage.
type protocolFeeTokenSettlement struct {
	eventCursor         int64
	segmentStakedAmount int64
	segmentStartX128    *u256.Uint
	earnedX128          *u256.Uint
}

// loadTokenSettlement returns the settlement state of tokenPath, initialising it when
// the token was never settled for this staker.
//
// A fresh state skips every stake event at or before the accumulator's first epoch:
// the accumulator was zero throughout, so those segments earned nothing and the open
// segment can start at the last of them. When no fee was folded at all, the skip
// covers every event, but only once every closed epoch is known to be folded: a
// bucket still pending from a closed epoch could later credit one of those events,
// so until then they are settled one by one through settleEvents, which is gated by
// foldedEpoch and yields nothing while the accumulator stays at zero.
func (p *ProtocolFeeRewardStateResolver) loadTokenSettlement(tokenPath string, view *protocolFeeAccumulatorView) *protocolFeeTokenSettlement {
	if tokenState, ok := p.GetTokenState(tokenPath); ok {
		return &protocolFeeTokenSettlement{
			eventCursor:         tokenState.GetEventCursor(),
			segmentStakedAmount: tokenState.GetSegmentStakedAmount(),
			segmentStartX128:    tokenState.GetSegmentStartX128().Clone(),
			earnedX128:          tokenState.GetEarnedX128().Clone(),
		}
	}

	settlement := &protocolFeeTokenSettlement{
		eventCursor:         0,
		segmentStakedAmount: 0,
		segmentStartX128:    u256.Zero(),
		earnedX128:          u256.Zero(),
	}

	eventCount := p.GetStakeEventCount()
	if view.firstEpoch < 0 {
		if view.foldedEpoch >= view.currentEpoch-1 {
			// No fee was ever folded and nothing from a closed epoch is pending, so
			// every recorded event earned nothing.
			settlement.eventCursor = eventCount
			settlement.segmentStakedAmount = p.GetStakedAmount()
		}
		return settlement
	}

	// Stake events are appended in epoch order, so the last event at or before
	// firstEpoch is found by binary search: the lookup costs O(log n) reads no matter
	// how many stake changes the staker made since the token's first fee.
	lo, hi := int64(0), eventCount
	for lo < hi {
		mid := lo + (hi-lo)/2
		event, ok := p.GetStakeEvent(mid)
		if !ok {
			break
		}
		if event.GetEpoch() <= view.firstEpoch {
			lo = mid + 1
		} else {
			hi = mid
		}
	}

	if lo > 0 {
		if event, ok := p.GetStakeEvent(lo - 1); ok {
			settlement.eventCursor = lo
			settlement.segmentStakedAmount = event.GetStakedAmount()
		}
	}

	return settlement
}

// settleEvents folds up to maxEvents pending stake events into the settlement. An
// event can only be folded once the epoch before it is fully folded on the
// accumulator, because the segment it closes ends at that epoch's value. A maxEvents
// of zero or less folds every event it can. Returns true when no event is left pending.
func (p *ProtocolFeeRewardStateResolver) settleEvents(settlement *protocolFeeTokenSettlement, view *protocolFeeAccumulatorView, maxEvents int64) bool {
	eventCount := p.GetStakeEventCount()
	processed := int64(0)

	for settlement.eventCursor < eventCount {
		if maxEvents > 0 && processed >= maxEvents {
			return false
		}

		event, ok := p.GetStakeEvent(settlement.eventCursor)
		if !ok {
			return false
		}
		if event.GetEpoch()-1 > view.foldedEpoch {
			return false
		}

		segmentEndX128 := view.at(event.GetEpoch() - 1)
		settlement.earnedX128 = u256.Zero().Add(
			settlement.earnedX128,
			segmentRewardX128(settlement.segmentStakedAmount, settlement.segmentStartX128, segmentEndX128),
		)
		settlement.segmentStartX128 = segmentEndX128.Clone()
		settlement.segmentStakedAmount = event.GetStakedAmount()
		settlement.eventCursor++
		processed++
	}

	return true
}

// closeOpenSegment folds the open segment up to the accumulator's latest value. It may
// only be called once every stake event is settled, so that the open segment really
// ends at the present.
func closeOpenSegment(settlement *protocolFeeTokenSettlement, view *protocolFeeAccumulatorView) {
	settlement.earnedX128 = u256.Zero().Add(
		settlement.earnedX128,
		segmentRewardX128(settlement.segmentStakedAmount, settlement.segmentStartX128, view.current),
	)
	settlement.segmentStartX128 = view.current.Clone()
}

// takeReward removes the whole-unit part of the earned reward from the settlement and
// returns it. The sub-unit remainder stays earned so that no fee share is lost.
func takeReward(settlement *protocolFeeTokenSettlement) int64 {
	rewardX128 := u256.Zero().Rsh(settlement.earnedX128, 128)
	reward := gnsmath.SafeConvertToInt64(rewardX128)
	settlement.earnedX128 = u256.Zero().Sub(settlement.earnedX128, u256.Zero().Lsh(rewardX128, 128))

	return reward
}

// segmentRewardX128 returns stakedAmount times the accumulator growth across a segment.
func segmentRewardX128(stakedAmount int64, startX128, endX128 *u256.Uint) *u256.Uint {
	if stakedAmount <= 0 || !endX128.Gt(startX128) {
		return u256.Zero()
	}

	growthX128 := u256.Zero().Sub(endX128, startX128)

	return u256.Zero().Mul(growthX128, u256.NewUintFromInt64(stakedAmount))
}

// storeTokenSettlement writes the settlement back to the staker's state.
func (p *ProtocolFeeRewardStateResolver) storeTokenSettlement(tokenPath string, settlement *protocolFeeTokenSettlement) {
	tokenState, ok := p.GetTokenState(tokenPath)
	if !ok {
		tokenState = staker.NewProtocolFeeTokenRewardState(settlement.eventCursor, settlement.segmentStakedAmount, settlement.segmentStartX128)
		tokenState.SetEarnedX128(settlement.earnedX128)
		p.SetTokenState(tokenPath, tokenState)
		return
	}

	tokenState.SetSegment(settlement.eventCursor, settlement.segmentStakedAmount, settlement.segmentStartX128)
	tokenState.SetEarnedX128(settlement.earnedX128)
}

// claimTokenReward settles tokenPath and returns the reward collected.
//
// Up to maxEvents stake events are folded; whatever is settled by then is paid, and
// the rest stays pending for a later collect. A maxEvents of zero or less folds
// everything.
func (p *ProtocolFeeRewardStateResolver) claimTokenReward(tokenPath string, view *protocolFeeAccumulatorView, maxEvents int64) (int64, error) {
	// A token that never collected a fee has nothing to settle; skipping it keeps the
	// staker's state free of an entry per token merely queried.
	if _, ok := p.GetTokenState(tokenPath); !ok && view.firstEpoch < 0 {
		return 0, nil
	}

	settlement := p.loadTokenSettlement(tokenPath, view)

	if p.settleEvents(settlement, view, maxEvents) {
		closeOpenSegment(settlement, view)
	}

	reward := takeReward(settlement)
	p.storeTokenSettlement(tokenPath, settlement)

	if reward > 0 {
		if tokenState, ok := p.GetTokenState(tokenPath); ok {
			tokenState.SetClaimedReward(gnsmath.SafeAddInt64(tokenState.GetClaimedReward(), reward))
		}
	}

	return reward, nil
}

// getClaimableReward returns what a collect of tokenPath would pay right now, without
// changing any state.
func (p *ProtocolFeeRewardStateResolver) getClaimableReward(tokenPath string, view *protocolFeeAccumulatorView) int64 {
	settlement := p.loadTokenSettlement(tokenPath, view)

	if p.settleEvents(settlement, view, 0) {
		closeOpenSegment(settlement, view)
	}

	return gnsmath.SafeConvertToInt64(u256.Zero().Div(settlement.earnedX128, consts.Q128()))
}

// addStake increases the staked amount and records the change from epoch on.
func (p *ProtocolFeeRewardStateResolver) addStake(amount int64, epoch int64) error {
	if amount <= 0 {
		return errors.New(errAmountMustBePositive)
	}

	stakedAmount := gnsmath.SafeAddInt64(p.GetStakedAmount(), amount)
	p.SetStakedAmount(stakedAmount)
	p.AppendStakeEvent(epoch, stakedAmount)

	return nil
}

// removeStake decreases the staked amount and records the change from epoch on.
func (p *ProtocolFeeRewardStateResolver) removeStake(amount int64, epoch int64) error {
	if amount < 0 {
		return errors.New(errAmountMustBeNonNegative)
	}
	if amount > p.GetStakedAmount() {
		return errors.New(errRemoveAmountExceedsStaked)
	}

	stakedAmount := gnsmath.SafeSubInt64(p.GetStakedAmount(), amount)
	p.SetStakedAmount(stakedAmount)
	p.AppendStakeEvent(epoch, stakedAmount)

	return nil
}

// IsClaimable reports whether every token may be collected at once at currentTimestamp.
//
// Parameters:
//   - currentTimestamp: current Unix timestamp used to compare the last collection.
//
// Returns:
//   - bool: true when currentTimestamp is later than the state's claimed timestamp.
func (p *ProtocolFeeRewardStateResolver) IsClaimable(currentTimestamp int64) bool {
	return p.GetClaimedTimestamp() < currentTimestamp
}

render.gno

package staker

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/staker"
)

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

	implementation := staker.GetImplementationPackagePath()

	out := md.H1("Gnoswap Governance Staker")
	out += md.H2("Staking overview")
	overviewTable := mdtable.Table{
		Headers: []string{"Field", "Value"},
		Rows: [][]string{
			{"Active implementation", md.Link(implementation, strings.TrimPrefix(implementation, "gno.land"))},
			{"Total xGNS supply", ufmt.Sprintf("%d", staker.GetTotalxGnsSupply())},
			{"Total delegated GNS", ufmt.Sprintf("%d", staker.GetTotalDelegated())},
			{"Total locked GNS", ufmt.Sprintf("%d", staker.GetTotalLockedAmount())},
			{"Undelegation lockup period", ufmt.Sprintf("%d", staker.GetUnDelegationLockupPeriod())},
			{"Protocol-fee accumulation timestamp", ufmt.Sprintf("%d", staker.GetProtocolFeeAccumulatedTimestamp())},
		},
	}
	out += overviewTable.String()

	return out
}

staker_delegate.gno

package staker

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

	gnsmath "gno.land/p/gnoswap/gnsmath/v1"
	"gno.land/p/gnoswap/utils/v1"
	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/emission"
	"gno.land/r/gnoswap/gns"

	"gno.land/r/gnoswap/gov/staker"
	"gno.land/r/gnoswap/gov/xgns"
	"gno.land/r/gnoswap/halt/v1"
	"gno.land/r/gnoswap/referral/v1"
)

// Spoofed-realm guards on entry points reject any caller that fabricates a
// realm value distinct from the current crossing frame. The proxy in
// gno.land/r/gnoswap/gov/staker always forwards its own `cur`, so a mismatch
// here means somebody bypassed the proxy and threaded a fake realm directly
// into the implementation.

// Delegate delegates GNS tokens to an address.
//
// Converts GNS to xGNS and assigns voting power.
// Primary mechanism for participating in governance.
// Can delegate to self or any other address.
//
// Parameters:
//
//   - _: Noncrossing implementation-call discriminator; pass 0.
//
//   - rlm: Current realm context forwarded unchanged by the governance-staker proxy.
//
//   - to: Address to receive voting power (can be self)
//
//   - amount: Amount of GNS to stake and delegate
//
//   - referrer: Optional referral address for tracking
//
// Process:
//  1. Transfers GNS from caller
//  2. Mints equivalent xGNS (1:1 ratio)
//  3. Assigns voting power to target address
//  4. Creates delegation snapshot for voting
//
// Requirements:
//   - Minimum 1 GNS delegation
//   - Valid target address
//   - Sufficient GNS balance
//   - Approval for GNS transfer
//
// Returns:
//   - delegatedAmount: amount of GNS delegated and mirrored as xGNS
func (gs *govStakerV1) Delegate(
	_ int,
	rlm realm,
	to address,
	amount int64,
	referrer string,
) int64 {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedGovStaker()

	prev := rlm.Previous()
	access.AssertIsValidAddress(to)

	assertIsValidDelegateAmount(amount)

	caller := prev.Address()
	from := caller
	currentHeight := runtime.ChainHeight()
	currentTimestamp := time.Now().Unix()

	emission.MintAndDistributeGns(cross(rlm))

	delegation, err := gs.delegate(
		0,
		rlm,
		from,
		to,
		amount,
		currentHeight,
		currentTimestamp,
	)
	if err != nil {
		panic(err)
	}

	if err := gs.increaseTotalDelegatedAmount(0, rlm, amount); err != nil {
		panic(err)
	}
	if err := gs.increaseTotalLockedAmount(0, rlm, amount); err != nil {
		panic(err)
	}

	gns.TransferFrom(cross(rlm), from, rlm.Address(), amount)
	xgns.Mint(cross(rlm), from, amount)

	registeredReferrer := referral.TryRegister(cross(rlm), caller, referrer)

	resolver := NewDelegationResolver(delegation)

	chain.Emit(
		"Delegate",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"from", resolver.delegation.DelegateFrom().String(),
		"to", resolver.delegation.DelegateTo().String(),
		"amount", utils.FormatInt(resolver.DelegatedAmount()),
		"totalDelegatedAmount", utils.FormatInt(gs.store.GetTotalDelegatedAmount()),
		"referrer", registeredReferrer,
	)

	return amount
}

// Undelegate undelegates xGNS from the existing delegate.
//
// Initiates withdrawal of staked GNS with lockup period.
// Voting power removed immediately, tokens locked for configurable period.
// Prevents governance attacks through time delay.
//
// Parameters:
//
//   - _: Noncrossing implementation-call discriminator; pass 0.
//
//   - rlm: Current realm context forwarded unchanged by the governance-staker proxy.
//
//   - from: Address currently delegated to
//
//   - amount: Amount of xGNS to undelegate
//
// Process:
//  1. Removes voting power immediately
//  2. Creates withdrawal request with timestamp
//  3. Locks GNS for configurable cooldown period
//
// Requirements:
//   - Must have delegated to target address
//   - Sufficient delegated amount
//
// After lockup period ends, use CollectUndelegatedGns() to claim GNS.
//
// Returns:
//   - undelegatedAmount: amount moved out of active delegation into undelegation lockup
func (gs *govStakerV1) Undelegate(
	_ int,
	rlm realm,
	from address,
	amount int64,
) int64 {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	prev := rlm.Previous()
	caller := prev.Address()
	access.AssertIsValidAddress(from)

	assertIsValidDelegateAmount(amount)

	currentHeight := runtime.ChainHeight()
	currentTimestamp := time.Now().Unix()

	emission.MintAndDistributeGns(cross(rlm))

	unDelegationAmount, err := gs.unDelegate(
		0,
		rlm,
		caller,
		from,
		amount,
		currentHeight,
		currentTimestamp,
	)
	if err != nil {
		panic(err)
	}

	if err := gs.decreaseTotalDelegatedAmount(0, rlm, unDelegationAmount); err != nil {
		panic(err)
	}

	chain.Emit(
		"Undelegate",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"from", caller.String(),
		"to", from.String(),
		"amount", utils.FormatInt(unDelegationAmount),
		"totalDelegatedAmount", utils.FormatInt(gs.store.GetTotalDelegatedAmount()),
	)

	return unDelegationAmount
}

// Redelegate redelegates xGNS from an existing delegate to another.
//
// Atomic operation to change delegation target.
// Maintains voting power continuity without unstaking.
// Useful for vote delegation services and DAO coordination.
//
// Parameters:
//
//   - _: Noncrossing implementation-call discriminator; pass 0.
//
//   - rlm: Current realm context forwarded unchanged by the governance-staker proxy.
//
//   - delegatee: Current address delegated to
//
//   - newDelegatee: New address to delegate to
//
//   - amount: Amount of xGNS to redelegate
//
// Process:
//  1. Validates current delegation exists
//  2. Removes voting power from the old delegatee without a lockup
//  3. Assigns the same amount to the new delegatee
//  4. Updates delegation history and reward stake events
//
// Requirements:
//   - Must have active delegation to current delegatee
//   - Both addresses must be valid
//   - Amount must not exceed current delegation
//   - Cannot redelegate to same address
//
// No user-facing lockup period; reward accounting records one removal and one
// addition across the corresponding accrual epochs.
//
// Returns:
//   - redelegatedAmount: amount moved from the current delegatee to the new delegatee
func (gs *govStakerV1) Redelegate(
	_ int,
	rlm realm,
	delegatee,
	newDelegatee address,
	amount int64,
) int64 {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedGovStaker()

	prev := rlm.Previous()
	caller := prev.Address()
	access.AssertIsValidAddress(delegatee)
	access.AssertIsValidAddress(newDelegatee)

	assertIsValidDelegateAmount(amount)
	assertNoSameDelegatee(delegatee, newDelegatee)

	currentHeight := runtime.ChainHeight()
	currentTimestamp := time.Now().Unix()
	delegator := caller

	emission.MintAndDistributeGns(cross(rlm))

	unDelegationAmount, err := gs.unDelegateWithoutLockup(
		0,
		rlm,
		delegator,
		delegatee,
		amount,
		currentHeight,
		currentTimestamp,
	)
	if err != nil {
		panic(err)
	}

	delegation, err := gs.delegate(
		0,
		rlm,
		delegator,
		newDelegatee,
		unDelegationAmount,
		currentHeight,
		currentTimestamp,
	)
	if err != nil {
		panic(err)
	}

	resolver := NewDelegationResolver(delegation)
	chain.Emit(
		"Redelegate",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"from", delegator.String(),
		"previousDelegatee", delegatee.String(),
		"newDelegatee", newDelegatee.String(),
		"amount", utils.FormatInt(resolver.DelegatedAmount()),
	)

	return amount
}

// CollectUndelegatedGns collects undelegated GNS tokens.
// Allows users to collect GNS tokens that completed undelegation lockup period.
// Burns xGNS and returns GNS tokens.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the governance-staker proxy.
//
// Returns:
//   - collectedAmount: amount of undelegated GNS released to the caller after lockup expiry
func (gs *govStakerV1) CollectUndelegatedGns(_ int, rlm realm) int64 {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	prev := rlm.Previous()
	caller := prev.Address()
	currentTime := time.Now().Unix()

	emission.MintAndDistributeGns(cross(rlm))

	collectedAmount, err := gs.collectDelegations(0, rlm, caller, currentTime)
	if err != nil {
		panic(err)
	}

	if collectedAmount == 0 {
		return 0
	}

	if err := gs.decreaseTotalLockedAmount(0, rlm, collectedAmount); err != nil {
		panic(err)
	}

	xgns.Burn(cross(rlm), caller, collectedAmount)
	gns.Transfer(cross(rlm), caller, collectedAmount)

	chain.Emit(
		"CollectUndelegatedGns",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"from", prev.Address().String(),
		"to", caller.String(),
		"collectedAmount", utils.FormatInt(collectedAmount),
	)

	return collectedAmount
}

// delegate processes delegation operations.
// Validates delegation amount, creates delegation records, and updates reward tracking.
func (gs *govStakerV1) delegate(
	_ int,
	rlm realm,
	from address,
	to address,
	amount,
	currentHeight,
	currentTimestamp int64,
) (*staker.Delegation, error) {
	delegationID := gs.nextDelegationID()
	delegation := staker.NewDelegation(
		delegationID,
		from,
		to,
		amount,
		currentHeight,
		currentTimestamp,
	)
	delegationResolver := NewDelegationResolver(delegation)
	delegatedAmount := delegationResolver.DelegatedAmount()
	if delegatedAmount < 0 {
		return nil, errors.New(errDelegatedAmountNegative)
	}

	if err := gs.addDelegation(0, rlm, delegationID, delegation); err != nil {
		return nil, err
	}
	gs.addDelegationRecord(0, rlm, to, delegatedAmount, currentTimestamp)
	if err := gs.addStakeEmissionReward(0, rlm, from.String(), amount, currentTimestamp); err != nil {
		return nil, err
	}
	if err := gs.addStakeProtocolFeeReward(0, rlm, from.String(), amount, currentTimestamp); err != nil {
		return nil, err
	}

	return delegation, nil
}

// unDelegate processes undelegation operations with lockup.
// Validates undelegation amount, processes withdrawals, and updates reward tracking.
func (gs *govStakerV1) unDelegate(
	_ int,
	rlm realm,
	delegator,
	delegatee address,
	amount,
	currentHeight,
	currentTimestamp int64,
) (int64, error) {
	delegationIDs := gs.getUserDelegationIDsWithDelegatee(delegator, delegatee)
	if len(delegationIDs) == 0 {
		return 0, nil
	}

	unDelegationAmount := amount
	lockupPeriod := gs.store.GetUnDelegationLockupPeriod()
	totalDelegated := int64(0)
	delegations := make([]*staker.Delegation, 0, len(delegationIDs))

	for _, id := range delegationIDs {
		delegation, exists := gs.store.GetDelegation(id)
		if !exists {
			continue
		}

		totalDelegated = gnsmath.SafeAddInt64(totalDelegated, NewDelegationResolver(delegation).DelegatedAmount())
		delegations = append(delegations, delegation)
	}

	if amount > totalDelegated {
		return 0, errors.New(errNotEnoughDelegated)
	}

	// Process undelegation across multiple delegation records if necessary
	for _, delegation := range delegations {
		resolver := NewDelegationResolver(delegation)
		if resolver.IsEmpty() {
			if err := gs.removeDelegation(0, rlm, delegation.ID()); err != nil {
				return 0, err
			}
			continue
		}

		currentUnDelegationAmount := unDelegationAmount

		if currentUnDelegationAmount > resolver.DelegatedAmount() {
			currentUnDelegationAmount = resolver.DelegatedAmount()
		}

		if currentUnDelegationAmount < 0 {
			return 0, errors.New(errUndelegationAmountNegative)
		}

		if currentUnDelegationAmount == 0 {
			continue
		}

		resolver.UnDelegate(
			currentUnDelegationAmount,
			currentHeight,
			currentTimestamp,
			lockupPeriod,
		)

		if err := gs.setDelegation(0, rlm, delegation.ID(), delegation); err != nil {
			return 0, err
		}
		gs.addDelegationRecord(0, rlm, delegatee, -currentUnDelegationAmount, currentTimestamp)
		if err := gs.removeStakeEmissionReward(0, rlm, delegator.String(), currentUnDelegationAmount, currentTimestamp); err != nil {
			return 0, err
		}
		if err := gs.removeStakeProtocolFeeReward(0, rlm, delegator.String(), currentUnDelegationAmount, currentTimestamp); err != nil {
			return 0, err
		}

		unDelegationAmount = gnsmath.SafeSubInt64(unDelegationAmount, currentUnDelegationAmount)
		if unDelegationAmount <= 0 {
			break
		}
	}

	return amount, nil
}

// unDelegateWithoutLockup processes undelegation without lockup.
// Used for redelegation where tokens are immediately available.
func (gs *govStakerV1) unDelegateWithoutLockup(
	_ int,
	rlm realm,
	delegator,
	delegatee address,
	amount,
	currentHeight,
	currentTime int64,
) (int64, error) {
	delegationIDs := gs.getUserDelegationIDsWithDelegatee(delegator, delegatee)
	if len(delegationIDs) == 0 {
		return 0, errors.New(errNotEnoughDelegated)
	}

	unDelegationAmount := amount
	totalDelegated := int64(0)
	delegations := make([]*staker.Delegation, 0, len(delegationIDs))

	for _, id := range delegationIDs {
		delegation, exists := gs.store.GetDelegation(id)
		if !exists {
			continue
		}

		totalDelegated = gnsmath.SafeAddInt64(totalDelegated, NewDelegationResolver(delegation).DelegatedAmount())
		delegations = append(delegations, delegation)
	}

	if amount > totalDelegated {
		return 0, errors.New(errNotEnoughDelegated)
	}

	// Process undelegation across multiple delegation records if necessary
	for _, delegation := range delegations {
		resolver := NewDelegationResolver(delegation)
		if resolver.IsEmpty() {
			if err := gs.removeDelegation(0, rlm, delegation.ID()); err != nil {
				return 0, err
			}
			continue
		}

		currentUnDelegationAmount := unDelegationAmount

		if currentUnDelegationAmount > resolver.DelegatedAmount() {
			currentUnDelegationAmount = resolver.DelegatedAmount()
		}

		if currentUnDelegationAmount == 0 {
			continue
		}

		resolver.UnDelegateWithoutLockup(
			currentUnDelegationAmount,
			currentHeight,
			currentTime,
		)

		if resolver.IsEmpty() {
			if err := gs.removeDelegation(0, rlm, delegation.ID()); err != nil {
				return 0, err
			}
		} else if err := gs.setDelegation(0, rlm, delegation.ID(), delegation); err != nil {
			return 0, err
		}
		gs.addDelegationRecord(0, rlm, delegatee, -currentUnDelegationAmount, currentTime)
		if err := gs.removeStakeEmissionReward(0, rlm, delegator.String(), currentUnDelegationAmount, currentTime); err != nil {
			return 0, err
		}
		if err := gs.removeStakeProtocolFeeReward(0, rlm, delegator.String(), currentUnDelegationAmount, currentTime); err != nil {
			return 0, err
		}

		unDelegationAmount = gnsmath.SafeSubInt64(unDelegationAmount, currentUnDelegationAmount)
		if unDelegationAmount <= 0 {
			break
		}
	}

	return amount, nil
}

func (gs *govStakerV1) increaseTotalDelegatedAmount(_ int, rlm realm, amount int64) error {
	currentDelegated := gs.store.GetTotalDelegatedAmount()

	if err := gs.store.SetTotalDelegatedAmount(0, rlm, gnsmath.SafeAddInt64(currentDelegated, amount)); err != nil {
		return err
	}

	return nil
}

func (gs *govStakerV1) decreaseTotalDelegatedAmount(_ int, rlm realm, amount int64) error {
	currentDelegated := gs.store.GetTotalDelegatedAmount()

	newDelegated := gnsmath.SafeSubInt64(currentDelegated, amount)
	if newDelegated < 0 {
		newDelegated = 0
	}
	if err := gs.store.SetTotalDelegatedAmount(0, rlm, newDelegated); err != nil {
		return err
	}

	return nil
}

func (gs *govStakerV1) increaseTotalLockedAmount(_ int, rlm realm, amount int64) error {
	currentLocked := gs.store.GetTotalLockedAmount()

	if err := gs.store.SetTotalLockedAmount(0, rlm, gnsmath.SafeAddInt64(currentLocked, amount)); err != nil {
		return err
	}

	return nil
}

func (gs *govStakerV1) decreaseTotalLockedAmount(_ int, rlm realm, amount int64) error {
	currentLocked := gs.store.GetTotalLockedAmount()

	newLocked := gnsmath.SafeSubInt64(currentLocked, amount)
	if newLocked < 0 {
		newLocked = 0
	}
	if err := gs.store.SetTotalLockedAmount(0, rlm, newLocked); err != nil {
		return err
	}

	return nil
}

// collectDelegations processes collection of undelegated tokens.
// Iterates through user delegations and collects available amounts.
func (gs *govStakerV1) collectDelegations(_ int, rlm realm, user address, currentTime int64) (int64, error) {
	totalCollectedAmount := int64(0)

	delegationTree := gs.getUserDelegations(user)

	var err error
	var idsToRemove []int64
	allDelegations := gs.store.GetAllDelegations()

	// Collect from all available delegations
	delegationTree.Iterate("", "", func(delegatee string, value any) bool {
		delegationIDs, ok := value.([]int64)
		if !ok {
			return false
		}

		if len(delegationIDs) == 0 {
			return false
		}
		for _, id := range delegationIDs {
			delegationRaw := allDelegations.Get(utils.FormatInt(id))
			if delegationRaw == nil {
				continue
			}
			delegation, ok := delegationRaw.(*staker.Delegation)
			if !ok {
				continue
			}

			resolver := NewDelegationResolver(delegation)

			collectedAmount, iErr := resolver.processCollection(currentTime)
			if iErr != nil {
				err = iErr
				return true
			}

			// Simple addition since addToCollectedAmount was removed
			totalCollectedAmount = gnsmath.SafeAddInt64(totalCollectedAmount, collectedAmount)

			// Save updated delegation state after collection
			if resolver.IsEmpty() {
				idsToRemove = append(idsToRemove, delegation.ID())
			} else {
				if iErr := gs.setDelegation(0, rlm, delegation.ID(), delegation); iErr != nil {
					err = iErr
					return true
				}
			}
		}

		return false
	})

	if err != nil {
		return totalCollectedAmount, makeErrorWithDetails(errInvalidAmount, err.Error())
	}

	for _, id := range idsToRemove {
		if err := gs.removeDelegation(0, rlm, id); err != nil {
			return totalCollectedAmount, err
		}
	}

	return totalCollectedAmount, nil
}

staker_delegation_snapshot.gno

package staker

import (
	"chain"

	"gno.land/p/gnoswap/utils/v1"
	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/halt/v1"
)

// SetUnDelegationLockupPeriodByAdmin sets the undelegation lockup period.
// This administrative function configures the time period that undelegated tokens
// must wait before they can be collected by users.
//
// The lockup period serves as a security mechanism to:
// - Prevent rapid delegation/undelegation cycles
// - Provide time for governance decisions to take effect
// - Maintain system stability during volatile periods
//
// Parameters:
//   - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
//   - rlm: propagated current realm context validated before administrative state updates
//   - period: lockup period in seconds (must be non-negative)
//
// Panics:
//   - if caller is not admin
//   - if period is negative
//
// Note: This change affects all future undelegation operations
func (gs *govStakerV1) SetUnDelegationLockupPeriodByAdmin(_ int, rlm realm, period int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedGovStaker()

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

	if period < 0 {
		panic("period must be greater than 0")
	}

	gs.setUnDelegationLockupPeriod(0, rlm, period)

	chain.Emit(
		"SetUnDelegationLockupPeriod",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"period", utils.FormatInt(period),
	)
}

// CleanStakerDelegationSnapshotByAdmin cleans old delegation history records.
// This administrative function removes delegation history records older than the specified threshold
// to prevent unlimited growth of historical data and optimize storage usage.
//
// The cleanup process:
// 1. Validates the snapshot time is within allowed range
// 2. Checks that no active proposals need data older than the cleanup threshold
// 3. Filters delegation history to keep only records after cutoff time
// 4. Updates the delegation history with filtered records
//
// Parameters:
//   - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
//   - rlm: propagated current realm context validated before administrative state updates
//   - snapshotTime: cutoff timestamp (records older than this will be removed)
//   - target: the user address whose delegation history should be cleaned
//
// Panics:
//   - if caller is not admin
//   - if snapshotTime is invalid (negative or too recent)
//   - if active proposals have snapshotTime older than the cleanup threshold
func (gs *govStakerV1) CleanStakerDelegationSnapshotByAdmin(_ int, rlm realm, snapshotTime int64, target address) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedGovStaker()

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

	assertIsValidSnapshotTime(snapshotTime)
	assertIsAvailableCleanupSnapshotTime(snapshotTime)

	// Clean total delegation history
	gs.cleanTotalDelegationHistory(0, rlm, snapshotTime)

	// Clean user delegation history
	gs.cleanUserDelegationHistoryForAddress(0, rlm, target, snapshotTime)

	chain.Emit(
		"CleanStakerDelegationSnapshot",
		"prevAddr", prev.Address().String(),
		"prevRealm", prev.PkgPath(),
		"snapshotTime", utils.FormatInt(snapshotTime),
		"target", target.String(),
	)
}

// cleanTotalDelegationHistory removes total delegation history entries older than cutoff time.
// Keeps the most recent entry before cutoff to preserve state continuity.
func (gs *govStakerV1) cleanTotalDelegationHistory(_ int, rlm realm, cutoffTimestamp int64) {
	history := gs.store.GetTotalDelegationHistory()

	// First, find the most recent entry before cutoff to preserve state
	var lastValue any

	hasLastValue := false

	history.ReverseIterate(0, cutoffTimestamp, func(timestamp int64, value any) bool {
		lastValue = value
		hasLastValue = true

		return true // stop after first (most recent)
	})

	// If there was a value before cutoff, set it at cutoff time to preserve continuity
	if hasLastValue && !history.Has(cutoffTimestamp) {
		history.Set(cutoffTimestamp, lastValue)
	}

	// Collect keys to remove (cannot modify tree during iteration)
	var keysToRemove []int64
	history.Iterate(0, cutoffTimestamp, func(timestamp int64, _ any) bool {
		keysToRemove = append(keysToRemove, timestamp)
		return false // continue
	})
	for _, key := range keysToRemove {
		history.Remove(key)
	}

	if err := gs.store.SetTotalDelegationHistory(0, rlm, history); err != nil {
		panic(err)
	}
}

// cleanUserDelegationHistoryForAddress removes user delegation history entries
// older than cutoff time for a single target address.
// Keeps the most recent entry strictly before cutoff
// in place so range-based snapshot lookups continue to resolve correctly.
func (gs *govStakerV1) cleanUserDelegationHistoryForAddress(_ int, rlm realm, target address, cutoffTimestamp int64) {
	if cutoffTimestamp <= 0 {
		return
	}

	history := gs.store.GetUserDelegationHistory()

	addrStr := target.String()
	iterationStartKey, _ := userHistoryKeyRange(addrStr)
	iterationEndKey := makeUserHistoryKey(addrStr, cutoffTimestamp)

	// First, find the most recent entry before cutoff to preserve state
	var lastValue any

	hasLastValue := false

	history.ReverseIterate(iterationStartKey, iterationEndKey, func(key string, value any) bool {
		lastValue = value
		hasLastValue = true

		return true // stop after first (most recent)
	})

	if hasLastValue && !history.Has(iterationEndKey) {
		history.Set(iterationEndKey, lastValue)
	}

	// Collect all keys strictly before preserveKey within this address prefix.
	// Iterate's end is exclusive, so [lo, preserveKey) skips the preserved entry.
	var keysToRemove []string

	history.Iterate(iterationStartKey, iterationEndKey, func(key string, _ any) bool {
		keysToRemove = append(keysToRemove, key)

		return false
	})

	for _, key := range keysToRemove {
		history.Remove(key)
	}

	if err := gs.store.SetUserDelegationHistory(0, rlm, history); err != nil {
		panic(err)
	}
}

staker_reward.gno

package staker

import (
	"chain"
	"time"

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

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/gns"
	"gno.land/r/gnoswap/gov/xgns"
	"gno.land/r/gnoswap/halt/v1"
)

// CollectReward claims all rewards for the caller.
//
// It settles both reward streams:
//  1. GNS emission rewards from the emission accumulator.
//  2. Protocol-fee rewards for every known token path.
//
// Protocol-fee rewards are divided by the total stake in force for each
// accrual epoch and settled across the caller's stake-event segments. They
// are not calculated from one current xGNS/total-xGNS ratio. Q128 fractional
// remainders remain in state for later collection.
//
// The all-token path intentionally grows with the number of known fee tokens.
// Use the token-specific entry point when bounded work is required.
//
// No business parameters are required; the caller's reward ID is used.
// Rewards are transferred directly to the caller.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded by the governance-staker proxy; validated before settlement and transfers.
func (gs *govStakerV1) CollectReward(_ int, rlm realm) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	prev := rlm.Previous()
	caller := prev.Address()
	from := rlm.Address()
	currentTimestamp := time.Now().Unix()

	emissionReward, protocolFeeRewards, err := gs.claimRewards(0, rlm, caller.String(), currentTimestamp)
	if err != nil {
		panic(err)
	}

	// Transfer emission rewards (GNS tokens) if any
	if emissionReward > 0 {
		gns.Transfer(cross(rlm), caller, emissionReward)

		chain.Emit(
			"CollectEmissionReward",
			"prevAddr", prev.Address().String(),
			"prevRealm", prev.PkgPath(),
			"from", from.String(),
			"to", caller.String(),
			"emissionRewardAmount", utils.FormatInt(emissionReward),
		)
	}

	// Transfer protocol fee rewards for each token type
	for tokenPath, amount := range protocolFeeRewards {
		if amount > 0 {
			err := transferToken(0, rlm, tokenPath, from, caller, amount)
			if err != nil {
				panic(err)
			}

			chain.Emit(
				"CollectProtocolFeeReward",
				"prevAddr", prev.Address().String(),
				"prevRealm", prev.PkgPath(),
				"tokenPath", tokenPath,
				"from", from.String(),
				"to", caller.String(),
				"collectedAmount", utils.FormatInt(amount),
			)
		}
	}
}

// CollectEmissionReward collects accumulated GNS emission rewards only.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded by the governance-staker proxy; validated before settlement and transfer.
func (gs *govStakerV1) CollectEmissionReward(_ int, rlm realm) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	prev := rlm.Previous()
	caller := prev.Address()
	from := rlm.Address()
	currentTimestamp := time.Now().Unix()

	emissionReward, err := gs.claimRewardsEmissionReward(0, rlm, caller.String(), currentTimestamp)
	if err != nil {
		panic(err)
	}

	if emissionReward > 0 {
		gns.Transfer(cross(rlm), caller, emissionReward)

		chain.Emit(
			"CollectEmissionReward",
			"prevAddr", prev.Address().String(),
			"prevRealm", prev.PkgPath(),
			"from", from.String(),
			"to", caller.String(),
			"emissionRewardAmount", utils.FormatInt(emissionReward),
		)
	}
}

// CollectProtocolFeeReward collects accumulated protocol fee rewards for the provided token path.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded by the governance-staker proxy; validated before settlement and transfer.
//   - tokenPath: registered fee-token path whose reward should be collected
func (gs *govStakerV1) CollectProtocolFeeReward(_ int, rlm realm, tokenPath string) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	prev := rlm.Previous()
	caller := prev.Address()
	from := rlm.Address()
	currentTimestamp := time.Now().Unix()

	amount, err := gs.claimRewardProtocolFeeRewardByTokenPath(0, rlm, caller.String(), tokenPath, currentTimestamp)
	if err != nil {
		panic(err)
	}

	if amount > 0 {
		err := transferToken(0, rlm, tokenPath, from, caller, amount)
		if err != nil {
			panic(err)
		}

		chain.Emit(
			"CollectProtocolFeeReward",
			"prevAddr", prev.Address().String(),
			"prevRealm", prev.PkgPath(),
			"tokenPath", tokenPath,
			"from", from.String(),
			"to", caller.String(),
			"collectedAmount", utils.FormatInt(amount),
		)
	}
}

// CollectRewardFromLaunchPad collects rewards for launchpad project wallets.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded by the governance-staker proxy; validated before launchpad reward settlement.
//   - to: project wallet address receiving its emission and protocol-fee rewards
//
// Only callable by launchpad contract.
func (gs *govStakerV1) CollectRewardFromLaunchPad(_ int, rlm realm, to address) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

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

	from := rlm.Address()
	currentTimestamp := time.Now().Unix()

	launchpadRewardID := gs.makeLaunchpadRewardID(to.String())
	_, exists := gs.getLaunchpadProjectDeposit(launchpadRewardID)
	if !exists {
		panic(makeErrorWithDetails(
			errNoDelegatedAmount,
			ufmt.Sprintf("%s is not project wallet from launchpad", to.String()),
		))
	}

	emissionReward, protocolFeeRewards, err := gs.claimRewardsFromLaunchpad(0, rlm, to.String(), currentTimestamp)
	if err != nil {
		panic(err)
	}

	// Transfer emission rewards (GNS tokens) to project wallet if any
	if emissionReward > 0 {
		gns.Transfer(cross(rlm), to, emissionReward)

		chain.Emit(
			"CollectEmissionFromLaunchPad",
			"prevAddr", prev.Address().String(),
			"prevRealm", prev.PkgPath(),
			"from", from.String(),
			"to", to.String(),
			"emissionRewardAmount", utils.FormatInt(emissionReward),
		)
	}

	// Transfer protocol fee rewards to project wallet for each token type
	for tokenPath, amount := range protocolFeeRewards {
		if amount > 0 {
			err := transferToken(0, rlm, tokenPath, from, to, amount)
			if err != nil {
				panic(err)
			}

			chain.Emit(
				"CollectProtocolFeeFromLaunchPad",
				"prevAddr", prev.Address().String(),
				"prevRealm", prev.PkgPath(),
				"tokenPath", tokenPath,
				"from", from.String(),
				"to", to.String(),
				"collectedAmount", utils.FormatInt(amount),
			)
		}
	}
}

// CollectEmissionRewardFromLaunchPad collects emission rewards only for launchpad project wallets.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded by the governance-staker proxy; validated before launchpad reward settlement.
//   - to: project wallet address receiving its emission reward
func (gs *govStakerV1) CollectEmissionRewardFromLaunchPad(_ int, rlm realm, to address) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

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

	from := rlm.Address()
	currentTimestamp := time.Now().Unix()

	launchpadRewardID := gs.makeLaunchpadRewardID(to.String())
	_, exists := gs.getLaunchpadProjectDeposit(launchpadRewardID)
	if !exists {
		panic(makeErrorWithDetails(
			errNoDelegatedAmount,
			ufmt.Sprintf("%s is not project wallet from launchpad", to.String()),
		))
	}

	emissionReward, err := gs.claimRewardsEmissionReward(0, rlm, launchpadRewardID, currentTimestamp)
	if err != nil {
		panic(err)
	}

	if emissionReward > 0 {
		gns.Transfer(cross(rlm), to, emissionReward)

		chain.Emit(
			"CollectEmissionFromLaunchPad",
			"prevAddr", prev.Address().String(),
			"prevRealm", prev.PkgPath(),
			"from", from.String(),
			"to", to.String(),
			"emissionRewardAmount", utils.FormatInt(emissionReward),
		)
	}
}

// CollectProtocolFeeRewardFromLaunchPad collects one token path of protocol fee rewards for launchpad project wallets.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded by the governance-staker proxy; validated before launchpad reward settlement.
//   - to: project wallet address receiving the protocol-fee reward
//   - tokenPath: registered fee-token path whose reward should be collected
func (gs *govStakerV1) CollectProtocolFeeRewardFromLaunchPad(_ int, rlm realm, to address, tokenPath string) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

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

	from := rlm.Address()
	currentTimestamp := time.Now().Unix()

	launchpadRewardID := gs.makeLaunchpadRewardID(to.String())
	_, exists := gs.getLaunchpadProjectDeposit(launchpadRewardID)
	if !exists {
		panic(makeErrorWithDetails(
			errNoDelegatedAmount,
			ufmt.Sprintf("%s is not project wallet from launchpad", to.String()),
		))
	}

	amount, err := gs.claimRewardProtocolFeeRewardByTokenPath(0, rlm, launchpadRewardID, tokenPath, currentTimestamp)
	if err != nil {
		panic(err)
	}

	if amount > 0 {
		err := transferToken(0, rlm, tokenPath, from, to, amount)
		if err != nil {
			panic(err)
		}

		chain.Emit(
			"CollectProtocolFeeFromLaunchPad",
			"prevAddr", prev.Address().String(),
			"prevRealm", prev.PkgPath(),
			"tokenPath", tokenPath,
			"from", from.String(),
			"to", to.String(),
			"collectedAmount", utils.FormatInt(amount),
		)
	}
}

// SetAmountByProjectWallet sets the amount of reward stake for the project wallet.
// This function is exclusively callable by the launchpad contract to manage
// xGNS balances for project wallets that participate in launchpad offerings.
//
// The function handles both adding and removing stakes:
// - When adding: mints xGNS to launchpad address and starts reward accumulation
// - When removing: burns xGNS from launchpad address and stops reward accumulation
// Adjusts stake amount for project wallet address.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded by the governance-staker proxy; validated before launchpad authorization and staking changes.
//   - addr: project wallet address whose launchpad-backed stake should be adjusted
//   - amount: amount of stake to add or remove
//   - add: true to add stake and mint xGNS to launchpad, false to remove stake and burn xGNS from launchpad
//
// Panics:
//   - if caller is not the launchpad contract
//   - if system is halted for withdrawals
//   - if access control operations fail
func (gs *govStakerV1) SetAmountByProjectWallet(_ int, rlm realm, addr address, amount int64, add bool) {
	access.AssertIsRlmCurrent(0, rlm)

	if add {
		halt.AssertIsNotHaltedGovStaker()
	} else {
		halt.AssertIsNotHaltedWithdraw()
	}

	prev := rlm.Previous()
	caller := prev.Address()
	currentTimestamp := time.Now().Unix()

	access.AssertIsLaunchpad(caller)

	launchpadAddr := access.MustGetAddress(prbac.ROLE_LAUNCHPAD.String())

	if add {
		// Add stake for the project wallet and mint xGNS to launchpad
		err := gs.addStakeFromLaunchpad(0, rlm, addr.String(), amount, currentTimestamp)
		if err != nil {
			panic(err)
		}

		xgns.Mint(cross(rlm), launchpadAddr, amount)
	} else {
		// Remove stake for the project wallet and burn xGNS from launchpad
		err := gs.removeStakeFromLaunchpad(0, rlm, addr.String(), amount, currentTimestamp)
		if err != nil {
			panic(err)
		}

		xgns.Burn(cross(rlm), launchpadAddr, amount)
	}
}

// claimRewards claims both emission and protocol fee rewards.
// Coordinates claiming process for both reward types.
func (gs *govStakerV1) claimRewards(_ int, rlm realm, rewardID string, currentTimestamp int64) (int64, map[string]int64, error) {
	emissionReward, err := gs.claimRewardsEmissionReward(0, rlm, rewardID, currentTimestamp)
	if err != nil {
		return 0, nil, err
	}

	protocolFeeRewards, err := gs.claimRewardsProtocolFeeReward(0, rlm, rewardID, currentTimestamp)
	if err != nil {
		return 0, nil, err
	}

	return emissionReward, protocolFeeRewards, nil
}

// claimRewardsFromLaunchpad claims rewards for launchpad project wallets.
// Uses special reward ID format for launchpad integration.
func (gs *govStakerV1) claimRewardsFromLaunchpad(_ int, rlm realm, address string, currentTimestamp int64) (int64, map[string]int64, error) {
	launchpadRewardID := gs.makeLaunchpadRewardID(address)

	return gs.claimRewards(0, rlm, launchpadRewardID, currentTimestamp)
}

// transferToken transfers tokens from the staker contract to a recipient address.
// transferToken handles token transfers for reward distribution.
//
// Non-crossing helper: takes `_ int, rlm realm` so the realm token threaded
// in by the public reward-collection entry points reaches the underlying
// GRC-20 transfer without forcing each caller to recompute it.
func transferToken(
	_ int,
	rlm realm,
	tokenPath string,
	from, to address,
	amount int64,
) error {
	common.MustRegistered(tokenPath)

	// Validate recipient address
	if !to.IsValid() {
		return makeErrorWithDetails(
			errInvalidAddress,
			ufmt.Sprintf("invalid address %s to transfer protocol fee", to.String()),
		)
	}

	// Validate transfer amount
	if amount < 0 {
		return makeErrorWithDetails(
			errInvalidAmount,
			ufmt.Sprintf("invalid amount %d to transfer protocol fee", amount),
		)
	}

	// Check sufficient balance
	balance := common.BalanceOf(tokenPath, from)
	if balance < amount {
		return makeErrorWithDetails(
			errNotEnoughBalance,
			ufmt.Sprintf("not enough %s balance(%d) to collect(%d)", tokenPath, balance, amount),
		)
	}

	common.SafeGRC20Transfer(0, rlm, tokenPath, to, amount)

	return nil
}

state.gno

package staker

import (
	"errors"
	"math"

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

	"gno.land/r/gnoswap/emission"
	"gno.land/r/gnoswap/gov/staker"
	pf "gno.land/r/gnoswap/protocol_fee"
)

// setUnDelegationLockupPeriod updates the undelegation lockup period.
// This affects all future undelegation operations.
//
// Parameters:
//   - period: new lockup period in seconds
func (g *govStakerV1) setUnDelegationLockupPeriod(_ int, rlm realm, period int64) {
	if err := g.store.SetUnDelegationLockupPeriod(0, rlm, period); err != nil {
		panic(err)
	}
}

// nextDelegationID generates and returns the next unique delegation ID.
//
// Returns:
//   - int64: next available delegation ID
func (g *govStakerV1) nextDelegationID() int64 {
	counter := g.store.GetDelegationCounter()

	return counter.Next()
}

// getDelegation retrieves a delegation by its ID.
//
// Parameters:
//   - delegationID: unique identifier of the delegation
//
// Returns:
//   - *Delegation: delegation instance or nil if not found
func (g *govStakerV1) getDelegation(delegationID int64) *staker.Delegation {
	delegation, exists := g.store.GetDelegation(delegationID)
	if !exists {
		return nil
	}
	return delegation
}

// setDelegation stores or updates a delegation in the storage tree.
//
// Parameters:
//   - delegationID: unique identifier of the delegation
//   - delegation: delegation instance to store
//
// Returns:
//   - error: nil on success, otherwise the storage write error
func (g *govStakerV1) setDelegation(_ int, rlm realm, delegationID int64, delegation *staker.Delegation) error {
	return g.store.SetDelegation(0, rlm, delegationID, delegation)
}

// addDelegation adds a new delegation to storage and updates the delegation manager.
//
// Parameters:
//   - delegationID: unique identifier of the delegation to add
//   - delegation: delegation instance to add
//
// Returns:
//   - error: nil on success, otherwise the delegation or manager storage error
func (g *govStakerV1) addDelegation(_ int, rlm realm, delegationID int64, delegation *staker.Delegation) error {
	if err := g.setDelegation(0, rlm, delegationID, delegation); err != nil {
		return err
	}

	delegationManager := g.store.GetDelegationManager()
	resolvedManager := NewDelegationManagerResolver(delegationManager)
	resolvedManager.addDelegation(
		delegation.DelegateFrom(),
		delegation.DelegateTo(),
		delegationID,
	)

	return g.store.SetDelegationManager(0, rlm, delegationManager)
}

// removeDelegation removes a delegation from storage and updates the delegation manager.
//
// Parameters:
//   - delegationID: unique identifier of the delegation to remove
//
// Returns:
//   - error: nil on success, otherwise an error when the delegation is absent or storage fails
func (g *govStakerV1) removeDelegation(_ int, rlm realm, delegationID int64) error {
	delegation := g.getDelegation(delegationID)
	if delegation == nil {
		return errors.New(errDelegationNotFound)
	}

	if err := g.store.RemoveDelegation(0, rlm, delegationID); err != nil {
		return err
	}

	delegationManager := g.store.GetDelegationManager()
	resolvedManager := NewDelegationManagerResolver(delegationManager)
	resolvedManager.removeDelegation(
		delegation.DelegateFrom(),
		delegation.DelegateTo(),
		delegationID,
	)

	return g.store.SetDelegationManager(0, rlm, delegationManager)
}

// getUserDelegations retrieves all delegations for a specific user.
//
// Parameters:
//   - user: user's address
//
// Returns:
//   - *bptree.BPTree: tree of user's delegations
func (g *govStakerV1) getUserDelegations(user address) *bptree.BPTree {
	delegationManager := g.store.GetDelegationManager()

	userDelegations, exists := delegationManager.GetDelegatorDelegations(user.String())
	if !exists {
		return staker.NewUserDelegationTree()
	}

	return userDelegations
}

// getUserDelegationsWithDelegatee retrieves all delegations from a user to a specific delegatee.
//
// Parameters:
//   - user: user's address
//   - delegatee: delegatee's address
//
// Returns:
//   - []int64: list of user's delegation IDs to the delegatee
func (g *govStakerV1) getUserDelegationIDsWithDelegatee(user address, delegatee address) []int64 {
	delegationManager := g.store.GetDelegationManager()

	userDelegations, exists := delegationManager.GetDelegatorDelegations(user.String())
	if !exists {
		return nil
	}

	delegateeStr := delegatee.String()
	delegationIDs := userDelegations.Get(delegateeStr)
	if delegationIDs == nil {
		return nil
	}

	ids, ok := delegationIDs.([]int64)
	if !ok {
		return nil
	}

	return ids
}

// addDelegationRecord records a delegation change in the history.
// Updates both total and user delegation histories with cumulative values.
//
// Parameters:
//   - delegateeAddr: address of the delegatee
//   - amount: amount change (positive for delegate, negative for undelegate)
//   - timestamp: timestamp of the delegation change
func (g *govStakerV1) addDelegationRecord(_ int, rlm realm, delegateeAddr address, amount int64, timestamp int64) {
	// Update total delegation history
	g.updateTotalDelegationHistory(0, rlm, amount, timestamp)

	// Update user delegation history
	g.updateUserDelegationHistory(0, rlm, delegateeAddr, amount, timestamp)
}

// updateTotalDelegationHistory updates the total delegation history with cumulative value.
//
// Parameters:
//   - amount: amount change (positive for delegate, negative for undelegate)
//   - timestamp: timestamp of the change
func (g *govStakerV1) updateTotalDelegationHistory(_ int, rlm realm, amount int64, timestamp int64) {
	history := g.store.GetTotalDelegationHistory()

	// Get current total from the most recent entry
	currentTotal := g.getLatestTotalDelegation(history)
	newTotal := gnsmath.SafeAddInt64(currentTotal, amount)

	if newTotal < 0 {
		newTotal = 0
	}

	history.Set(timestamp, newTotal)

	if err := g.store.SetTotalDelegationHistory(0, rlm, history); err != nil {
		panic(err)
	}
}

// updateUserDelegationHistory updates the user delegation history with cumulative values.
// Structure: single BPTree keyed by composite key "addrStr|paddedTimestamp" -> int64
//
// Parameters:
//   - delegateeAddr: address of the delegatee
//   - amount: amount change (positive for delegate, negative for undelegate)
//   - timestamp: timestamp of the change
func (g *govStakerV1) updateUserDelegationHistory(_ int, rlm realm, delegateeAddr address, amount int64, timestamp int64) {
	history := g.store.GetUserDelegationHistory()
	addrStr := delegateeAddr.String()

	// Get current amount from the most recent entry for this user
	currentAmount := g.getLatestUserDelegationByAddress(history, addrStr)
	newAmount := gnsmath.SafeAddInt64(currentAmount, amount)
	if newAmount < 0 {
		newAmount = 0
	}

	// Store new cumulative value under composite key
	history.Set(makeUserHistoryKey(addrStr, timestamp), newAmount)

	if err := g.store.SetUserDelegationHistory(0, rlm, history); err != nil {
		panic(err)
	}
}

// getLatestTotalDelegation gets the latest total delegation amount from history.
func (g *govStakerV1) getLatestTotalDelegation(history *staker.UintTree) int64 {
	if history.Size() == 0 {
		return 0
	}

	latestTotal := int64(0)

	history.ReverseIterate(0, math.MaxInt64, func(key int64, value any) bool {
		totalInt, ok := value.(int64)
		if !ok {
			panic(ufmt.Sprintf("invalid total type: %T", value))
		}

		latestTotal = totalInt

		return true // stop after first (most recent) entry
	})

	return latestTotal
}

// getLatestUserDelegationByAddress gets the latest delegation amount for a user
// from the composite-keyed user delegation history.
func (g *govStakerV1) getLatestUserDelegationByAddress(history *bptree.BPTree, addrStr string) int64 {
	lo, hi := userHistoryKeyRange(addrStr)

	latestAmount := int64(0)

	history.ReverseIterate(lo, hi, func(_ string, value any) bool {
		amountInt, ok := value.(int64)
		if !ok {
			panic(ufmt.Sprintf("invalid amount type: %T", value))
		}

		latestAmount = amountInt

		return true // stop after first (most recent) entry
	})

	return latestAmount
}

// addStakeEmissionReward adds stake to emission reward tracking for an address.
// This method updates the emission reward distribution state and adds stake for the specified address.
//
// Parameters:
//   - address: staker's address
//   - amount: amount of stake to add
//   - currentTimestamp: current timestamp
func (g *govStakerV1) addStakeEmissionReward(_ int, rlm realm, address string, amount int64, currentTimestamp int64) error {
	distributedAmount := emission.GetAccuDistributedToGovStaker()

	emissionRewardManager := g.store.GetEmissionRewardManager()
	resolvedManager := NewEmissionRewardManagerResolver(emissionRewardManager)

	if err := resolvedManager.updateAccumulatedRewardX128PerStake(distributedAmount, currentTimestamp); err != nil {
		return err
	}

	if err := resolvedManager.addStake(address, amount, currentTimestamp); err != nil {
		return err
	}

	err := g.store.SetEmissionRewardManager(0, rlm, emissionRewardManager)
	if err != nil {
		return err
	}

	// Emit the emission reward accumulation
	emitUpdateEmissionRewardAccumulation(emissionRewardManager)

	return nil
}

// removeStakeEmissionReward removes stake from emission reward tracking for an address.
// This method updates the emission reward distribution state and removes stake for the specified address.
//
// Parameters:
//   - address: staker's address
//   - amount: amount of stake to remove
//   - currentTimestamp: current timestamp
func (g *govStakerV1) removeStakeEmissionReward(_ int, rlm realm, address string, amount int64, currentTimestamp int64) error {
	distributedAmount := emission.GetAccuDistributedToGovStaker()

	emissionRewardManager := g.store.GetEmissionRewardManager()
	resolvedManager := NewEmissionRewardManagerResolver(emissionRewardManager)

	if err := resolvedManager.updateAccumulatedRewardX128PerStake(distributedAmount, currentTimestamp); err != nil {
		return err
	}

	if err := resolvedManager.removeStake(address, amount, currentTimestamp); err != nil {
		return err
	}

	if err := g.store.SetEmissionRewardManager(0, rlm, emissionRewardManager); err != nil {
		return err
	}

	// Emit the emission reward accumulation
	emitUpdateEmissionRewardAccumulation(emissionRewardManager)

	return nil
}

// claimRewardsEmissionReward claims emission rewards for an address.
// This method updates the emission reward distribution state and processes reward claiming.
//
// Parameters:
//   - address: staker's address claiming rewards
//   - currentTimestamp: current timestamp
//
// Returns:
//   - int64: amount of emission rewards claimed
//   - error: nil on success, error if claiming fails
func (g *govStakerV1) claimRewardsEmissionReward(_ int, rlm realm, address string, currentTimestamp int64) (int64, error) {
	distributedAmount := emission.GetAccuDistributedToGovStaker()

	emissionRewardManager := g.store.GetEmissionRewardManager()
	resolvedManager := NewEmissionRewardManagerResolver(emissionRewardManager)

	if err := resolvedManager.updateAccumulatedRewardX128PerStake(distributedAmount, currentTimestamp); err != nil {
		return 0, err
	}

	amount, err := resolvedManager.claimRewards(address, currentTimestamp)
	if err != nil {
		return 0, err
	}

	if err := g.store.SetEmissionRewardManager(0, rlm, emissionRewardManager); err != nil {
		return 0, err
	}

	// Emit the emission reward accumulation
	emitUpdateEmissionRewardAccumulation(emissionRewardManager)

	return amount, nil
}

// removeLaunchpadProjectDeposit removes a launchpad project deposit record.
//
// Parameters:
//   - ownerAddress: project owner's address identifier
//
// Returns:
//   - bool: true if successfully removed
func (g *govStakerV1) removeLaunchpadProjectDeposit(ownerAddress string) bool {
	launchpadProjectDeposits := g.store.GetLaunchpadProjectDeposits()
	return launchpadProjectDeposits.RemoveDeposit(ownerAddress)
}

// addStakeProtocolFeeReward records a stake increase for protocol fee rewards.
//
// The change only opens a new accrual epoch and appends one stake event, so its cost
// does not depend on how many tokens collected fees.
//
// Parameters:
//   - address: staker's address
//   - amount: amount of stake to add
//   - currentTimestamp: current timestamp
func (g *govStakerV1) addStakeProtocolFeeReward(_ int, rlm realm, address string, amount int64, currentTimestamp int64) error {
	epoch := pf.AdvanceAccrualEpoch(cross(rlm))

	protocolFeeRewardManager := g.store.GetProtocolFeeRewardManager()
	resolvedManager := NewProtocolFeeRewardManagerResolver(protocolFeeRewardManager)

	if err := resolvedManager.addStake(address, amount, epoch); err != nil {
		return err
	}
	resolvedManager.SetAccumulatedTimestamp(currentTimestamp)

	if err := g.store.SetProtocolFeeRewardManager(0, rlm, protocolFeeRewardManager); err != nil {
		return err
	}

	emitUpdateProtocolFeeStakeAccrual(protocolFeeRewardManager)

	return nil
}

// removeStakeProtocolFeeReward records a stake decrease for protocol fee rewards.
// Like addStakeProtocolFeeReward it never folds fees, so a withdrawal never pays for
// the reward calculation; that happens on collect, one token at a time if need be.
//
// Parameters:
//   - address: staker's address
//   - amount: amount of stake to remove
//   - currentTimestamp: current timestamp
func (g *govStakerV1) removeStakeProtocolFeeReward(_ int, rlm realm, address string, amount int64, currentTimestamp int64) error {
	epoch := pf.AdvanceAccrualEpoch(cross(rlm))

	protocolFeeRewardManager := g.store.GetProtocolFeeRewardManager()
	resolvedManager := NewProtocolFeeRewardManagerResolver(protocolFeeRewardManager)

	if err := resolvedManager.removeStake(address, amount, epoch); err != nil {
		return err
	}
	resolvedManager.SetAccumulatedTimestamp(currentTimestamp)

	if err := g.store.SetProtocolFeeRewardManager(0, rlm, protocolFeeRewardManager); err != nil {
		return err
	}

	emitUpdateProtocolFeeStakeAccrual(protocolFeeRewardManager)

	return nil
}

// foldProtocolFeeAccrual consumes up to limit pending accrual buckets of tokenPath from
// the protocol fee realm and folds them into the token's accumulator. A limit of zero
// or less consumes every pending bucket.
func (g *govStakerV1) foldProtocolFeeAccrual(_ int, rlm realm, resolvedManager *ProtocolFeeRewardManagerResolver, tokenPath string, limit int, currentTimestamp int64) error {
	epochs, amounts := pf.ConsumeAccrualBuckets(cross(rlm), tokenPath, limit)
	exhausted := limit <= 0 || len(epochs) < limit

	return resolvedManager.applyAccrualBuckets(tokenPath, epochs, amounts, exhausted, currentTimestamp)
}

// claimRewardsProtocolFeeReward claims protocol fee rewards for an address in every token.
// It folds every pending token first, so its cost grows with the number of tokens
// that collected a fee. claimRewardProtocolFeeRewardByTokenPath is the bounded path.
//
// Parameters:
//   - address: staker's address claiming rewards
//   - currentTimestamp: current timestamp
//
// Returns:
//   - map[string]int64: protocol fee rewards claimed by token
//   - error: nil on success, error if claiming fails
func (g *govStakerV1) claimRewardsProtocolFeeReward(_ int, rlm realm, address string, currentTimestamp int64) (map[string]int64, error) {
	// Claiming pays out of gov/staker's own balance, so the reserved fees are pulled in
	// from the protocol fee realm first.
	pf.DistributeProtocolFee(cross(rlm))

	protocolFeeRewardManager := g.store.GetProtocolFeeRewardManager()
	resolvedManager := NewProtocolFeeRewardManagerResolver(protocolFeeRewardManager)

	// Every pending token is consumed from the protocol fee realm. A known token with
	// nothing pending has no bucket in any epoch since its last fold, so an empty
	// exhaustive fold is enough to mark every closed epoch as settled for it.
	pendingTokenPaths := pf.GetAccrualPendingTokens()
	pending := make(map[string]bool, len(pendingTokenPaths))
	for _, tokenPath := range pendingTokenPaths {
		pending[tokenPath] = true
		if err := g.foldProtocolFeeAccrual(0, rlm, resolvedManager, tokenPath, 0, currentTimestamp); err != nil {
			return nil, err
		}
	}

	foldedTokenPaths := pendingTokenPaths
	for _, tokenPath := range protocolFeeRewardManager.GetTokenPaths() {
		if pending[tokenPath] {
			continue
		}
		if err := resolvedManager.applyAccrualBuckets(tokenPath, []int64{}, []int64{}, true, currentTimestamp); err != nil {
			return nil, err
		}
		foldedTokenPaths = append(foldedTokenPaths, tokenPath)
	}

	rewards, err := resolvedManager.claimRewards(address, currentTimestamp)
	if err != nil {
		return nil, err
	}

	if err := g.store.SetProtocolFeeRewardManager(0, rlm, protocolFeeRewardManager); err != nil {
		return nil, err
	}

	emitUpdateProtocolFeeRewardAccumulation(protocolFeeRewardManager, foldedTokenPaths)

	return rewards, nil
}

// claimRewardProtocolFeeRewardByTokenPath claims one protocol fee reward token for an address.
//
// Both the fold and the settlement are bounded per call (maxAccrualBucketsPerCollect,
// maxStakeEventsPerCollect); a token with more pending work pays what is settled and
// keeps the rest for a later collect.
func (g *govStakerV1) claimRewardProtocolFeeRewardByTokenPath(_ int, rlm realm, address string, tokenPath string, currentTimestamp int64) (int64, error) {
	pf.DistributeProtocolFeeByTokenPath(cross(rlm), tokenPath)

	protocolFeeRewardManager := g.store.GetProtocolFeeRewardManager()
	resolvedManager := NewProtocolFeeRewardManagerResolver(protocolFeeRewardManager)

	if err := g.foldProtocolFeeAccrual(0, rlm, resolvedManager, tokenPath, maxAccrualBucketsPerCollect, currentTimestamp); err != nil {
		return 0, err
	}

	reward, err := resolvedManager.claimTokenReward(address, tokenPath, maxStakeEventsPerCollect)
	if err != nil {
		return 0, err
	}

	if err := g.store.SetProtocolFeeRewardManager(0, rlm, protocolFeeRewardManager); err != nil {
		return 0, err
	}

	emitUpdateProtocolFeeRewardAccumulation(protocolFeeRewardManager, []string{tokenPath})

	return reward, nil
}

// getClaimableProtocolFeeRewards reports what collecting every token would pay for a
// reward ID right now, pending accrual buckets included, without changing any state.
func (g *govStakerV1) getClaimableProtocolFeeRewards(rewardID string) (map[string]int64, error) {
	protocolFeeRewardManager := g.store.GetProtocolFeeRewardManager()
	resolvedManager := NewProtocolFeeRewardManagerResolver(protocolFeeRewardManager)

	rewards := make(map[string]int64)
	tokenPaths := protocolFeeRewardManager.GetTokenPaths()
	for _, tokenPath := range pf.GetAccrualPendingTokens() {
		if _, ok := protocolFeeRewardManager.GetTokenAccumulator(tokenPath); !ok {
			tokenPaths = append(tokenPaths, tokenPath)
		}
	}

	for _, tokenPath := range tokenPaths {
		pendingEpochs, pendingAmounts := pf.GetAccrualBuckets(tokenPath, 0)
		reward, err := resolvedManager.GetClaimableRewardAmount(rewardID, tokenPath, pendingEpochs, pendingAmounts)
		if err != nil {
			return nil, err
		}
		rewards[tokenPath] = reward
	}

	return rewards, nil
}

// getLaunchpadProjectDeposit retrieves the deposit amount for a launchpad project.
//
// Parameters:
//   - ownerAddress: project owner's address identifier
//
// Returns:
//   - int64: deposit amount
//   - bool: true if project exists, false otherwise
func (g *govStakerV1) getLaunchpadProjectDeposit(ownerAddress string) (int64, bool) {
	launchpadDeposits := g.store.GetLaunchpadProjectDeposits()
	resolvedDeposits := NewLaunchpadProjectDepositsResolver(launchpadDeposits)
	return resolvedDeposits.getLaunchpadProjectDeposit(ownerAddress)
}

// setLaunchpadProjectDeposit sets the deposit amount for a launchpad project.
//
// Parameters:
//   - ownerAddress: project owner's address identifier
//   - deposit: deposit amount to set
//
// Returns:
//   - error: nil on success, otherwise the storage write error
func (g *govStakerV1) setLaunchpadProjectDeposit(_ int, rlm realm, ownerAddress string, deposit int64) error {
	launchpadDeposits := g.store.GetLaunchpadProjectDeposits()
	resolvedDeposits := NewLaunchpadProjectDepositsResolver(launchpadDeposits)
	resolvedDeposits.setLaunchpadProjectDeposit(ownerAddress, deposit)

	return g.store.SetLaunchpadProjectDeposits(0, rlm, launchpadDeposits)
}

// addStakeFromLaunchpad adds stake for a launchpad project and updates reward tracking.
// This method creates a special reward ID for launchpad projects and manages their deposit tracking.
//
// Parameters:
//   - address: project wallet address
//   - amount: amount of stake to add
//   - currentTimestamp: current timestamp
func (g *govStakerV1) addStakeFromLaunchpad(_ int, rlm realm, address string, amount int64, currentTimestamp int64) error {
	launchpadRewardID := g.makeLaunchpadRewardID(address)
	err := g.addStakeEmissionReward(0, rlm, launchpadRewardID, amount, currentTimestamp)
	if err != nil {
		return err
	}

	err = g.addStakeProtocolFeeReward(0, rlm, launchpadRewardID, amount, currentTimestamp)
	if err != nil {
		return err
	}

	deposit, exists := g.getLaunchpadProjectDeposit(launchpadRewardID)
	if !exists {
		deposit = 0
	}

	deposit = gnsmath.SafeAddInt64(deposit, amount)
	if err := g.setLaunchpadProjectDeposit(0, rlm, launchpadRewardID, deposit); err != nil {
		return err
	}

	return nil
}

// removeStakeFromLaunchpad removes stake for a launchpad project and updates reward tracking.
// This method manages launchpad project deposit tracking and ensures non-negative deposits.
//
// Parameters:
//   - address: project wallet address
//   - amount: amount of stake to remove
//   - currentTimestamp: current timestamp
func (g *govStakerV1) removeStakeFromLaunchpad(_ int, rlm realm, address string, amount int64, currentTimestamp int64) error {
	launchpadRewardID := g.makeLaunchpadRewardID(address)
	err := g.removeStakeEmissionReward(0, rlm, launchpadRewardID, amount, currentTimestamp)
	if err != nil {
		return err
	}

	err = g.removeStakeProtocolFeeReward(0, rlm, launchpadRewardID, amount, currentTimestamp)
	if err != nil {
		return err
	}

	deposit, exists := g.getLaunchpadProjectDeposit(launchpadRewardID)
	if !exists {
		deposit = 0
	}

	deposit = gnsmath.SafeSubInt64(deposit, amount)
	if deposit < 0 {
		deposit = 0
	}

	if err := g.setLaunchpadProjectDeposit(0, rlm, launchpadRewardID, deposit); err != nil {
		return err
	}

	return nil
}

// makeLaunchpadRewardID creates a special reward identifier for launchpad projects.
// This ensures launchpad project rewards are tracked separately from regular user stakes.
//
// Parameters:
//   - address: project wallet address
//
// Returns:
//   - string: formatted launchpad reward ID
func (g *govStakerV1) makeLaunchpadRewardID(address string) string {
	return "launchpad:" + address
}

util.gno

package staker

import (
	"strconv"

	gnsmath "gno.land/p/gnoswap/gnsmath/v1"
	bptree "gno.land/p/nt/bptree/v0"
	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/p/onbloc/json/v0"
)

// marshal data to json string
func marshal(data *json.Node) string {
	b, err := json.Marshal(data)
	if err != nil {
		panic(err.Error())
	}

	return string(b)
}

// getUint64FromTree returns the uint64 value from the tree
func getUint64FromTree(tree *bptree.BPTree, key string) uint64 {
	value := tree.Get(key)
	if value == nil {
		return 0
	}

	v, ok := value.(uint64)
	if !ok {
		panic(ufmt.Sprintf("failed to cast value to uint64: %T", value))
	}

	return v
}

// updateUint64InTree updates the uint64 value in the tree
func updateUint64InTree(tree *bptree.BPTree, key string, delta uint64, add bool) uint64 {
	current := getUint64FromTree(tree, key)
	var newValue uint64
	if add {
		newValue = gnsmath.SafeAddUint64(current, delta)
	} else {
		if current < delta {
			panic(makeErrorWithDetails(
				errNotEnoughBalance,
				ufmt.Sprintf("not enough balance: current(%d) < requested(%d)", current, delta),
			))
		}
		newValue = gnsmath.SafeSubUint64(current, delta)
	}

	tree.Set(key, newValue)

	return newValue
}

// milliToSec converts milliseconds to seconds
func milliToSec(ms int64) int64 {
	var msPerSec int64 = 1000
	return ms / msPerSec
}

// userHistoryKeySeparator is chosen to be lexicographically smaller than any
const (
	userHistoryKeySeparator         = "|"
	userHistoryKeySeparatorNextWord = string(int32('|') + 1)
)

// userHistoryTimestampWidth is the zero-padded width that fits the maximum
const userHistoryTimestampWidth = 20

// makeUserHistoryKey builds the composite key "addr|paddedTimestamp" used in the user delegation history BPTree.
func makeUserHistoryKey(addrStr string, timestamp int64) string {
	return addrStr + userHistoryKeySeparator + padTimestamp(timestamp)
}

// userHistoryKeyRange returns the half-open prefix range that covers all composite keys belonging to addrStr.
func userHistoryKeyRange(addrStr string) (lo, hi string) {
	lo = addrStr + userHistoryKeySeparator
	hi = addrStr + userHistoryKeySeparatorNextWord

	return lo, hi
}

// padTimestamp left-pads timestamp with zeros to userHistoryTimestampWidth so
// that lexicographic ordering of the resulting strings matches numeric order.
func padTimestamp(timestamp int64) string {
	s := strconv.FormatInt(timestamp, 10)
	if len(s) >= userHistoryTimestampWidth {
		return s
	}

	pad := make([]byte, userHistoryTimestampWidth-len(s))
	for i := range pad {
		pad[i] = '0'
	}

	return string(pad) + s
}

// parseUserHistoryKey splits a composite key produced by makeUserHistoryKey back into its address and timestamp components.
func parseUserHistoryKey(key string) (addrStr string, timestamp int64, ok bool) {
	for i := len(key) - 1; i >= 0; i-- {
		if key[i] == userHistoryKeySeparator[0] {
			ts, err := strconv.ParseInt(key[i+1:], 10, 64)
			if err != nil {
				return "", 0, false
			}

			return key[:i], ts, true
		}
	}

	return "", 0, false
}