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 (
	"math"
	"strconv"
	"strings"
	"time"

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

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

const (
	TIMESTAMP_90DAYS  = int64(7776000)
	TIMESTAMP_180DAYS = int64(15552000)
	TIMESTAMP_365DAYS = int64(31536000)

	maxIncentiveStartDelay = 7 * 24 * time.Hour

	MAX_UNIX_EPOCH_TIME = 253402300799 // 9999-12-31 23:59:59

	maxUnstakingFee = uint64(1000) // 10%
)

// assertIsValidAmount ensures the amount is non-negative.
func assertIsValidAmount(amount int64) {
	if amount < 0 {
		panic(makeErrorWithDetails(
			errInvalidInput,
			ufmt.Sprintf("amount(%d) must be positive", amount),
		))
	}
}

// assertIsValidRewardAmountFormat ensures the reward amount string is formatted as "tokenPath:amount".
func assertIsValidRewardAmountFormat(rewardAmountStr string) {
	parts := strings.SplitN(rewardAmountStr, ":", 2)
	if len(parts) != 2 {
		panic(makeErrorWithDetails(
			errInvalidInput,
			ufmt.Sprintf("invalid format for SetTokenMinimumRewardAmount params: expected 'tokenPath:amount', got '%s'", rewardAmountStr),
		))
	}
}

// assertIsDepositor ensures the caller is the owner of the deposit.
func assertIsDepositor(s *stakerV1, caller address, positionId uint64) {
	deposit := s.getDeposits().get(positionId)
	if deposit == nil {
		panic(makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("positionId(%d) not found", positionId),
		))
	}

	if caller != deposit.Owner() {
		panic(makeErrorWithDetails(
			errNoPermission,
			ufmt.Sprintf("caller(%s) is not depositor(%s)", caller.String(), deposit.Owner().String()),
		))
	}
}

// assertIsIncentiveOfDeposit ensures the incentive exists and targets the pool the position is staked
// in, so a caller cannot ask a deposit to collect an incentive that can never pay it.
// assertIsIncentiveOfPool ensures the incentive targets the pool the position is staked in.
func assertIsIncentiveOfPool(s *stakerV1, poolPath string, positionId uint64, incentiveId string) {
	// get panics with errDataNotFound when the incentive does not exist.
	incentive := s.getExternalIncentives().get(incentiveId)

	if incentive.TargetPoolPath() != poolPath {
		panic(makeErrorWithDetails(
			errInvalidInput,
			ufmt.Sprintf(
				"incentiveId(%s) targets pool(%s), but positionId(%d) is staked in pool(%s)",
				incentiveId, incentive.TargetPoolPath(), positionId, poolPath,
			),
		))
	}
}

// assertHasNoExitCheckpoint ensures the position carries no reward from a previous stake.
// Collecting it here would smuggle an unbounded calculation into staking, and leaving it would
// let the next unstake overwrite the checkpoint.
func assertHasNoExitCheckpoint(s *stakerV1, positionId uint64) {
	if s.HasUnstakedPosition(positionId) {
		panic(makeErrorWithDetails(
			errUncollectedPosition,
			ufmt.Sprintf("positionId(%d) cannot be staked while its exit checkpoint owes rewards; collect after emission resumes if emission is halted", positionId),
		))
	}
}

// assertHasNoUncollectedIncentive ensures no unstaked position still owes a reward from this
// incentive, which has not been drawn down from it yet.
func assertHasNoUncollectedIncentive(s *stakerV1, incentiveId string) {
	count := s.uncollectedIncentiveCountOf(incentiveId)
	if count > 0 {
		panic(makeErrorWithDetails(
			errUncollectedPosition,
			ufmt.Sprintf("incentive(%s) is owed to %d unstaked position(s)", incentiveId, count),
		))
	}
}

// assertIsNotStaked ensures the position is not already staked.
func assertIsNotStaked(s *stakerV1, positionId uint64) {
	if s.getDeposits().Has(positionId) {
		panic(makeErrorWithDetails(
			errAlreadyStaked,
			ufmt.Sprintf("positionId(%d) already staked", positionId),
		))
	}
}

// assertIsPoolExists ensures the pool exists.
func assertIsPoolExists(s *stakerV1, poolPath string) {
	if !s.poolAccessor.ExistsPoolPath(poolPath) {
		panic(makeErrorWithDetails(
			errInvalidPoolPath,
			ufmt.Sprintf("pool(%s) does not exist", poolPath),
		))
	}
}

// assertIsValidPoolTier ensures the tier is within valid range.
func assertIsValidPoolTier(tier uint64) {
	if tier >= AllTierCount {
		panic(makeErrorWithDetails(
			errInvalidPoolTier,
			ufmt.Sprintf("tier(%d) must be less than %d", tier, AllTierCount),
		))
	}
}

// assertTier1HasSparePool ensures tier 1 keeps at least one pool after a tier change.
func assertTier1HasSparePool(currentTier, tier1Count uint64) {
	if currentTier == Tier1 && tier1Count == 1 {
		panic(makeErrorWithDetails(errInvalidPoolTier, "tier 1 must have at least one pool"))
	}
}

// assertIsGreaterThanMinimumRewardAmount ensures the reward amount meets minimum requirements.
func assertIsGreaterThanMinimumRewardAmount(s *stakerV1, rewardToken string, rewardAmount int64) {
	minReward := s.getMinimumRewardAmount()

	if minRewardInt64, found := s.store.GetTokenSpecificMinimumRewards()[rewardToken]; found {
		minReward = minRewardInt64
	}

	if rewardAmount < minReward {
		panic(makeErrorWithDetails(
			errInvalidInput,
			ufmt.Sprintf("rewardAmount(%d) is less than minimum required amount(%d)", rewardAmount, minReward),
		))
	}
}

// assertIsAllowedForExternalReward ensures the token is allowed for external rewards.
func assertIsAllowedForExternalReward(s *stakerV1, poolPath, tokenPath string) {
	// Operational stop switch: a denied token can never start a NEW incentive,
	// whether it qualifies as a pool-pair token or through the governance
	// allowlist. Collection of already-created incentives is deliberately
	// unaffected; the delivery guard in deliverExternalIncentiveReward bounds
	// that blast radius instead.
	if contains(s.store.GetDeniedRewardTokens(), tokenPath) {
		panic(makeErrorWithDetails(
			errDeniedRewardToken,
			ufmt.Sprintf("tokenPath(%s) is denied as an external reward token", tokenPath),
		))
	}

	token0, token1, _ := poolPathDivide(poolPath)

	if tokenPath == token0 || tokenPath == token1 {
		return
	}

	allowed := contains(s.store.GetAllowedTokens(), tokenPath)
	if allowed {
		return
	}

	panic(makeErrorWithDetails(
		errNotAllowedForExternalReward,
		ufmt.Sprintf("tokenPath(%s) is not allowed for external reward for poolPath(%s)", tokenPath, poolPath),
	))
}

// assertIsExternalRewardTokenAvailable ensures a pool has no unfinished incentive for the token.
func assertIsExternalRewardTokenAvailable(s *stakerV1, poolPath, tokenPath string, currentTime int64) {
	pool := s.getPools().GetPoolOrNil(poolPath)
	if pool == nil || pool.Incentives() == nil {
		return
	}

	minimumActiveIncentiveStartTime := currentTime - TIMESTAMP_365DAYS
	if minimumActiveIncentiveStartTime < 0 {
		minimumActiveIncentiveStartTime = 0
	}

	pool.Incentives().IterateIncentiveIdsByTime(minimumActiveIncentiveStartTime, math.MaxInt64, func(incentiveID string) bool {
		incentive := s.getExternalIncentives().get(incentiveID)
		if incentive == nil {
			return false
		}

		if incentive.RewardToken() != tokenPath || NewExternalIncentiveResolver(incentive).IsEnded(currentTime) {
			return false
		}

		panic(makeErrorWithDetails(
			errIncentiveAlreadyExists,
			ufmt.Sprintf(
				"rewardToken(%s) already has unfinished incentive(%s) for poolPath(%s)",
				tokenPath,
				incentiveID,
				poolPath,
			),
		))
	})
}

// assertIsValidFeeRate ensures the fee rate is within valid range (0-1000 basis points).
func assertIsValidFeeRate(fee uint64) {
	if fee > maxUnstakingFee {
		panic(makeErrorWithDetails(
			errInvalidUnstakingFee,
			ufmt.Sprintf("fee(%d) must be in range 0 ~ %d", fee, maxUnstakingFee),
		))
	}
}

// assertIsValidIncentiveStartTime ensures the incentive starts at midnight no earlier than 24 hours after creation
// and no later than 7 days after the first eligible midnight.
func assertIsValidIncentiveStartTime(startTimestamp int64) {
	// must be in seconds format, not milliseconds
	// REF: https://stackoverflow.com/a/23982005
	numStr := strconv.Itoa(int(startTimestamp))

	if len(numStr) >= 13 {
		panic(makeErrorWithDetails(
			errInvalidIncentiveStartTime,
			ufmt.Sprintf("startTimestamp(%d) must be in seconds format, not milliseconds", startTimestamp),
		))
	}

	// must be at least 24 hours from now
	minimumStartTimestamp := getMinimumIncentiveStartTimestamp()
	if startTimestamp < minimumStartTimestamp {
		panic(makeErrorWithDetails(
			errInvalidIncentiveStartTime,
			ufmt.Sprintf("startTimestamp(%d) must be at least 24 hours later", startTimestamp),
		))
	}

	maximumStartTimestamp := getMaximumIncentiveStartTimestamp()
	if startTimestamp > maximumStartTimestamp {
		panic(makeErrorWithDetails(
			errInvalidIncentiveStartTime,
			ufmt.Sprintf("startTimestamp(%d) exceeds the maximum start time policy", startTimestamp),
		))
	}

	// must be midnight of the day
	startTime := time.Unix(startTimestamp, 0)
	if !isMidnight(startTime) {
		panic(makeErrorWithDetails(
			errInvalidIncentiveStartTime,
			ufmt.Sprintf("startTime(%d = %s) must be midnight of the day", startTimestamp, startTime.String()),
		))
	}
}

// assertIsAdminGovernanceOrCreator ensures the caller may act on an incentive:
// admin and governance are the protocol-level operators, and the creator is the
// address that funded the incentive in CreateExternalIncentive.
func assertIsAdminGovernanceOrCreator(caller, creator address) {
	if caller == creator {
		return
	}
	if access.IsAuthorized(prbac.ROLE_ADMIN.String(), caller) ||
		access.IsAuthorized(prbac.ROLE_GOVERNANCE.String(), caller) {
		return
	}

	panic(makeErrorWithDetails(
		errNoPermission,
		ufmt.Sprintf(
			"caller(%s) must be admin, governance, or the incentive creator(%s)",
			caller.String(), creator.String(),
		),
	))
}

// assertIsNotStartedIncentive ensures the incentive can still be cancelled, i.e.
// it has not started and nothing has been distributed from it. Only such an
// incentive may be removed outright; anything that already emitted rewards has
// to be finalized through EndExternalIncentive so the refund accounting and the
// penalty balance stay reachable.
func assertIsNotStartedIncentive(incentiveResolver *ExternalIncentiveResolver, currentTime int64) {
	if incentiveResolver.IsStarted(currentTime) {
		panic(makeErrorWithDetails(
			errCannotCancelIncentive,
			ufmt.Sprintf(
				"incentive(%s) already started at %d, current(%d)",
				incentiveResolver.IncentiveId(), incentiveResolver.StartTimestamp(), currentTime,
			),
		))
	}

	if incentiveResolver.Refunded() {
		panic(makeErrorWithDetails(
			errCannotCancelIncentive,
			ufmt.Sprintf("incentive(%s) has already been refunded", incentiveResolver.IncentiveId()),
		))
	}

	// Defensive: a not-yet-started incentive can never have distributed a reward
	// or accrued a warmup penalty. Removing a record that carries either would
	// strand those tokens in the staker, so refuse instead of dropping it.
	if incentiveResolver.DistributedRewardAmount() != 0 || incentiveResolver.AccumulatedPenaltyAmount() != 0 {
		panic(makeErrorWithDetails(
			errCannotCancelIncentive,
			ufmt.Sprintf(
				"incentive(%s) has already accrued rewards: distributed(%d), penalty(%d)",
				incentiveResolver.IncentiveId(),
				incentiveResolver.DistributedRewardAmount(),
				incentiveResolver.AccumulatedPenaltyAmount(),
			),
		))
	}
}

// getMinimumIncentiveStartTimestamp returns after 24 hours from now.
func getMinimumIncentiveStartTimestamp() int64 {
	return time.Now().Add(24 * time.Hour).Unix()
}

// getMaximumIncentiveStartTimestamp returns 7 days after the first midnight that satisfies
// the minimum 24-hour delay.
func getMaximumIncentiveStartTimestamp() int64 {
	minimumStartTimestamp := getMinimumIncentiveStartTimestamp()
	firstEligibleMidnight := time.Unix(minimumStartTimestamp, 0).Truncate(24 * time.Hour)
	if firstEligibleMidnight.Unix() < minimumStartTimestamp {
		firstEligibleMidnight = firstEligibleMidnight.Add(24 * time.Hour)
	}

	return firstEligibleMidnight.Add(maxIncentiveStartDelay).Unix()
}

// assertIsValidIncentiveEndTime ensures the end timestamp is within valid epoch range.
func assertIsValidIncentiveEndTime(endTimestamp int64) {
	if endTimestamp >= MAX_UNIX_EPOCH_TIME {
		panic(makeErrorWithDetails(
			errInvalidInput,
			ufmt.Sprintf("endTimestamp(%d) cannot be later than 253402300799 (9999-12-31 23:59:59)", endTimestamp),
		))
	}
}

// assertIsValidIncentiveDuration ensures the duration is 90, 180, or 365 days.
func assertIsValidIncentiveDuration(externalDuration int64) {
	switch externalDuration {
	case TIMESTAMP_90DAYS, TIMESTAMP_180DAYS, TIMESTAMP_365DAYS:
		return
	}

	panic(makeErrorWithDetails(
		errInvalidIncentiveDuration,
		ufmt.Sprintf("externalDuration(%d) must be 90, 180, 365 days", externalDuration),
	))
}

// AssertIsValidAddress panics if the provided address is invalid.
func assertIsValidAddress(addr address) {
	if addr == "" || !addr.IsValid() {
		panic(makeErrorWithDetails(
			errInvalidAddress,
			ufmt.Sprintf("address(%s) is invalid", addr.String()),
		))
	}
}

// isMidnight checks if a time represents midnight (00:00:00).
func isMidnight(startTime time.Time) bool {
	hour := startTime.Hour()
	minute := startTime.Minute()
	second := startTime.Second()

	return hour == 0 && minute == 0 && second == 0
}

// assertIsPositionOwner validates that the caller has permission to operate the token.
func assertIsPositionOwner(owner, caller address) {
	if owner != caller {
		panic(makeErrorWithDetails(
			errNoPermission,
			ufmt.Sprintf("caller(%s) is not owner of positionId(%s)", caller, owner),
		))
	}
}

calculate_pool_position_reward.gno

package staker

import (
	"time"

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

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

// Reward is a struct for storing reward for a position.
// Internal reward is the GNS reward, external reward is the reward for other incentives.
// Penalties are the amount that is deducted from the reward due to the position's warmup.
type Reward struct {
	Internal        int64
	InternalPenalty int64
	External        map[string]int64 // Incentive ID -> TokenAmount
	ExternalPenalty map[string]int64 // Incentive ID -> TokenAmount
}

// aggregateRewards sums the per-warmup rewards/penalties into a single Reward.
func aggregateRewards(rewards []Reward) Reward {
	internal := int64(0)
	internalPenalty := int64(0)

	rewardLen := len(rewards)
	externalReward := make(map[string]int64, rewardLen)
	externalPenalty := make(map[string]int64, rewardLen)

	for _, reward := range rewards {
		internal = gnsmath.SafeAddInt64(internal, reward.Internal)
		internalPenalty = gnsmath.SafeAddInt64(internalPenalty, reward.InternalPenalty)

		for incentive, amount := range reward.External {
			externalReward[incentive] = gnsmath.SafeAddInt64(externalReward[incentive], amount)
		}

		for incentive, penalty := range reward.ExternalPenalty {
			externalPenalty[incentive] = gnsmath.SafeAddInt64(externalPenalty[incentive], penalty)
		}
	}

	return Reward{
		Internal:        internal,
		InternalPenalty: internalPenalty,
		External:        externalReward,
		ExternalPenalty: externalPenalty,
	}
}

// calculatePositionRewardParam is a struct for calculating position reward
type calculatePositionRewardParam struct {
	// Environmental variables
	CurrentHeight int64
	CurrentTime   int64
	Deposits      *Deposits
	Pools         *Pools
	PoolTier      *PoolTier

	// Position variables
	PositionId uint64

	// Deposit overrides the Deposits lookup for a deposit that is no longer in the tree.
	Deposit *sr.Deposit
	// Exit pins the pool state to the moment the position left the pool; nil while staked.
	Exit *sr.UnstakedPosition
}

// deposit resolves the deposit the calculation runs against.
func (self *calculatePositionRewardParam) deposit() *sr.Deposit {
	if self.Deposit != nil {
		return self.Deposit
	}

	return self.Deposits.get(self.PositionId)
}

// positionRewardUpdate carries the persisted-state changes produced (but not applied) by a calculation.
// They are applied by the update* functions, so that only the collect path mutates state while the
// calculation stays pure.
type positionRewardUpdate struct {
	poolPath    string
	pool        *sr.Pool
	poolExisted bool

	// External incentive ids discovered as newly created since the deposit's last update; they must be
	// added to the deposit's incentive index.
	newExternalIncentiveIds []string
	// Whether the deposit's LastExternalIncentiveUpdatedAt cursor should be advanced to CurrentTime.
	advanceExternalIncentiveCursor bool

	// Incentive ids the calculation actually produced a reward for, in calculation order. The collect
	// path walks this instead of iterating the reward map, so delivery order is deterministic.
	externalIncentiveIds []string
}

// positionRewardContext carries the per-position state that both the internal (GNS emission) and the
// external (incentive) reward calculations need. Resolving it once lets each path be calculated on its
// own without duplicating the deposit/pool/reward-state setup.
type positionRewardContext struct {
	deposit         *sr.Deposit
	depositResolver *DepositResolver
	poolResolver    *PoolResolver
	rewardState     *RewardState
	warmupLen       int

	update positionRewardUpdate
}

// newPositionRewardContext resolves the deposit, its pool and a fresh RewardState WITHOUT mutating
// persisted state. A missing pool is created ephemerally and its persistence is deferred to the
// update path.
func (s *stakerV1) newPositionRewardContext(param *calculatePositionRewardParam) *positionRewardContext {
	deposit := param.deposit()
	poolPath := deposit.TargetPoolPath()

	pool, poolExisted := param.Pools.Get(poolPath)
	if !poolExisted {
		// Read-only: use an ephemeral pool; persistence is deferred to updatePositionReward.
		pool = sr.NewPool(poolPath, param.CurrentTime)
	}
	poolResolver := newPoolResolverWithExit(pool, param.Exit)

	return &positionRewardContext{
		deposit:         deposit,
		depositResolver: NewDepositResolver(deposit),
		poolResolver:    poolResolver,
		rewardState:     poolResolver.RewardStateOf(deposit),
		warmupLen:       len(deposit.Warmups()),
		update: positionRewardUpdate{
			poolPath:    poolPath,
			pool:        pool,
			poolExisted: poolExisted,
		},
	}
}

// newRewards allocates the empty per-warmup reward slice the compute* methods write into.
func (self *positionRewardContext) newRewards() []Reward {
	rewards := make([]Reward, self.warmupLen)
	for i := 0; i < self.warmupLen; i++ {
		rewards[i] = Reward{
			External:        make(map[string]int64),
			ExternalPenalty: make(map[string]int64),
		}
	}

	return rewards
}

// computeInternalRewards writes the GNS emission reward and penalty of each warmup into rewards.
//
// The per-second emission-rate schedule is resolved up-front (resolveInternalRewardSegments) and fed to
// the single internal-reward calculator, so the calculation needs no reward-cache update.
func (self *positionRewardContext) computeInternalRewards(param *calculatePositionRewardParam, rewards []Reward) error {
	lastCollectTime := self.depositResolver.InternalRewardLastCollectTime()

	// Resolve the per-second reward-rate schedule (pure) and calculate internal rewards from it.
	internalSegments, err := self.poolResolver.resolveInternalRewardSegments(param.PoolTier, self.update.poolPath, lastCollectTime, param.CurrentTime)
	if err != nil {
		return err
	}
	calculatedInternalRewards, calculatedInternalPenalties := self.rewardState.calculateInternalReward(internalSegments)

	for i := 0; i < self.warmupLen; i++ {
		rewards[i].Internal = calculatedInternalRewards[i]
		rewards[i].InternalPenalty = calculatedInternalPenalties[i]
	}

	self.rewardState.reset()

	return nil
}

// discoverExternalIncentives records the incentives created since the deposit's last update on the
// update, WITHOUT mutating the deposit. The collect path adds them to the deposit's incentive index.
//
// ExternalRewardLastCollectTime falls back to StakeTime for ids not yet persisted, so a newly-discovered
// incentive yields the same calculation whether or not it is written to the deposit.
func (self *positionRewardContext) discoverExternalIncentives(param *calculatePositionRewardParam) {
	lastExternalIncentiveUpdatedAt := self.depositResolver.LastExternalIncentiveUpdatedAt()
	if lastExternalIncentiveUpdatedAt >= param.CurrentTime {
		return
	}

	// Discover incentives from this pool's own start-time index. Using the
	// local resolver keeps calculation read-only even for an ephemeral pool
	// that has not yet been persisted in param.Pools.
	newIds := make([]string, 0)
	self.poolResolver.IncentivesResolver().IterateIncentiveIdsByTime(lastExternalIncentiveUpdatedAt, param.CurrentTime, func(incentiveId string) bool {
		newIds = append(newIds, incentiveId)
		return false
	})

	self.update.newExternalIncentiveIds = newIds
	self.update.advanceExternalIncentiveCursor = true
}

// externalIncentiveIds returns the deposit's effective incentive-id set: the ids stored on the deposit
// plus the ones discoverExternalIncentives found. Call it after discoverExternalIncentives.
func (self *positionRewardContext) externalIncentiveIds() []string {
	seen := make(map[string]bool)
	incentiveIds := make([]string, 0)

	self.deposit.IterateExternalIncentiveIds(func(incentiveId string) bool {
		if !seen[incentiveId] {
			seen[incentiveId] = true
			incentiveIds = append(incentiveIds, incentiveId)
		}
		return false
	})

	for _, incentiveId := range self.update.newExternalIncentiveIds {
		if !seen[incentiveId] {
			seen[incentiveId] = true
			incentiveIds = append(incentiveIds, incentiveId)
		}
	}

	return incentiveIds
}

// computeExternalReward writes one incentive's external reward and penalty of each warmup into rewards.
// An incentive that does not exist on the pool or has not started yet contributes nothing.
func (self *positionRewardContext) computeExternalReward(param *calculatePositionRewardParam, rewards []Reward, incentiveId string) {
	incentive, ok := self.poolResolver.IncentivesResolver().Get(incentiveId)
	if !ok {
		return
	}

	incentiveResolver := NewExternalIncentiveResolver(incentive)

	// Check if incentive is active during this specific collection period
	if !incentiveResolver.IsStarted(param.CurrentTime) {
		return
	}

	// External incentivized pool.
	// Calculate reward for each warmup using per-incentive lastCollectTime
	externalLastCollectTime := self.depositResolver.ExternalRewardLastCollectTime(incentiveId)
	externalReward, externalPenalty := self.rewardState.calculateExternalReward(externalLastCollectTime, param.CurrentTime, incentive)

	for i := range externalReward {
		if externalReward[i] > 0 || externalPenalty[i] > 0 {
			rewards[i].External[incentiveId] = externalReward[i]
			rewards[i].ExternalPenalty[incentiveId] = externalPenalty[i]
		}
	}

	self.update.externalIncentiveIds = append(self.update.externalIncentiveIds, incentiveId)
	self.rewardState.reset()
}

// computeExternalRewards writes every incentive of the deposit into rewards.
func (self *positionRewardContext) computeExternalRewards(param *calculatePositionRewardParam, rewards []Reward) {
	self.discoverExternalIncentives(param)

	for _, incentiveId := range self.externalIncentiveIds() {
		self.computeExternalReward(param, rewards, incentiveId)
	}
}

// calculateCollectablePositionReward calculates the aggregated position reward WITHOUT mutating any persisted state.
//
// It is the shared, read-only entry point used by the Collectable* view getters.
// This keeps the calculation identical for every caller and guarantees views never write.
func (s *stakerV1) calculateCollectablePositionReward(currentHeight, currentTimestamp int64, positionId uint64) (Reward, error) {
	param := &calculatePositionRewardParam{
		CurrentHeight: currentHeight,
		CurrentTime:   currentTimestamp,
		Deposits:      s.getDeposits(),
		Pools:         s.getPools(),
		PoolTier:      s.getPoolTier(),
		PositionId:    positionId,
	}

	// An unstaked position quotes against its exit checkpoint, at its exit time.
	if checkpoint := s.getUnstakedPositions().get(positionId); checkpoint != nil {
		param.CurrentTime = checkpoint.ExitTime()
		param.Deposit = checkpoint.Deposit()
		param.Exit = checkpoint
	}

	rewards, _, err := s.calculatePositionReward(param)
	if err != nil {
		return Reward{}, err
	}

	return aggregateRewards(rewards), nil
}

// calculatePositionReward computes a position's per-warmup internal AND external rewards WITHOUT
// mutating persisted state. All would-be state changes are returned as a positionRewardUpdate for the
// caller to apply (collect only).
func (s *stakerV1) calculatePositionReward(param *calculatePositionRewardParam) ([]Reward, positionRewardUpdate, error) {
	ctx := s.newPositionRewardContext(param)
	rewards := ctx.newRewards()

	if err := ctx.computeInternalRewards(param, rewards); err != nil {
		return nil, positionRewardUpdate{}, err
	}
	ctx.computeExternalRewards(param, rewards)

	return rewards, ctx.update, nil
}

// calculateExternalPositionRewards computes all of a position's external incentive rewards WITHOUT
// mutating persisted state. Used by the combined collect path while GNS emission is halted.
func (s *stakerV1) calculateExternalPositionRewards(param *calculatePositionRewardParam) ([]Reward, positionRewardUpdate) {
	ctx := s.newPositionRewardContext(param)
	rewards := ctx.newRewards()

	ctx.computeExternalRewards(param, rewards)

	return rewards, ctx.update
}

// calculateInternalPositionReward computes only a position's per-warmup GNS emission rewards, WITHOUT
// mutating persisted state. Used by the emission collect path.
func (s *stakerV1) calculateInternalPositionReward(param *calculatePositionRewardParam) ([]Reward, positionRewardUpdate, error) {
	ctx := s.newPositionRewardContext(param)
	rewards := ctx.newRewards()

	if err := ctx.computeInternalRewards(param, rewards); err != nil {
		return nil, positionRewardUpdate{}, err
	}

	return rewards, ctx.update, nil
}

// calculateExternalPositionReward computes a position's per-warmup reward for one external incentive,
// WITHOUT mutating persisted state. Used by the external incentive collect path.
//
// Incentive discovery still runs over every incentive, so the deposit's incentive index stays complete
// no matter which incentive the caller asked for.
func (s *stakerV1) calculateExternalPositionReward(param *calculatePositionRewardParam, incentiveId string) ([]Reward, positionRewardUpdate) {
	ctx := s.newPositionRewardContext(param)
	rewards := ctx.newRewards()

	ctx.discoverExternalIncentives(param)
	ctx.computeExternalReward(param, rewards, incentiveId)

	return rewards, ctx.update
}

// persistLazyPool persists a pool that calculation created ephemerally because it did not exist yet.
func (s *stakerV1) persistLazyPool(param *calculatePositionRewardParam, updateParams positionRewardUpdate) {
	if !updateParams.poolExisted {
		param.Pools.set(updateParams.poolPath, updateParams.pool)
	}
}

// updateInternalRewardCache advances the reward cache up to CurrentTime (halving boundaries). The
// calculation itself no longer needs this, but downstream unclaimable processing (which reads
// CurrentReward) and off-chain history rely on the cache, so it is advanced on the emission collect path.
func (s *stakerV1) updateInternalRewardCache(param *calculatePositionRewardParam, updateParams positionRewardUpdate) {
	// Always at the current time, never at param.CurrentTime: the cache and the unclaimable
	// tracking it drives are pool-global, and a checkpoint collect would rewind them to its exit
	// timestamp, where the pool may have had no staked liquidity.
	param.PoolTier.cacheRewardForPool(time.Now().Unix(), param.Pools, updateParams.poolPath)
}

// applyExternalIncentiveIndex persists the deposit incentive-index updates discovered during calculation.
func (s *stakerV1) applyExternalIncentiveIndex(param *calculatePositionRewardParam, updateParams positionRewardUpdate) {
	if len(updateParams.newExternalIncentiveIds) == 0 && !updateParams.advanceExternalIncentiveCursor {
		return
	}

	deposit := param.deposit()
	for _, incentiveId := range updateParams.newExternalIncentiveIds {
		deposit.AddExternalIncentiveId(incentiveId)
	}
	if updateParams.advanceExternalIncentiveCursor {
		deposit.SetLastExternalIncentiveUpdatedAt(param.CurrentTime)
	}
}

// updatePositionReward applies the persisted-state changes produced by calculatePositionReward.
// It is called ONLY by the collect path; the Collectable* view getters discard the update.
func (s *stakerV1) updatePositionReward(param *calculatePositionRewardParam, updateParams positionRewardUpdate) {
	s.persistLazyPool(param, updateParams)
	s.updateInternalRewardCache(param, updateParams)
	s.applyExternalIncentiveIndex(param, updateParams)
}

// updateInternalPositionReward applies the state changes belonging to the emission collect path only.
func (s *stakerV1) updateInternalPositionReward(param *calculatePositionRewardParam, updateParams positionRewardUpdate) {
	s.persistLazyPool(param, updateParams)
	s.updateInternalRewardCache(param, updateParams)
}

// updateExternalPositionReward applies the state changes belonging to the external collect path only.
func (s *stakerV1) updateExternalPositionReward(param *calculatePositionRewardParam, updateParams positionRewardUpdate) {
	s.persistLazyPool(param, updateParams)
	s.applyExternalIncentiveIndex(param, updateParams)
}

// internalRewardSegment is a [start, end) span over which the per-second emission reward rate is constant.
type internalRewardSegment struct {
	start           int64
	end             int64
	rewardPerSecond int64
}

// resolveInternalRewardSegments builds the per-second reward-rate schedule over [startTime, endTime]
// WITHOUT mutating state.
//
// Persisted reward-cache entries cover the historical portion: they record tier/count changes and any
// halvings already materialized by past collects, so no un-materialized halving exists strictly between
// two persisted entries. The tail beyond the last persisted entry is split by halvings using the current
// tier ratio/count, which are necessarily constant there (a change would have written a cache entry). The
// tail rate is recomputed with the same calculatePoolReward arithmetic the cache writer uses, so a
// schedule resolved from a fully materialized cache and one resolved from the emission halvings are
// identical.
func (self *PoolResolver) resolveInternalRewardSegments(poolTier *PoolTier, poolPath string, startTime, endTime int64) ([]internalRewardSegment, error) {
	segments := make([]internalRewardSegment, 0)
	if startTime >= endTime {
		return segments, nil
	}

	currentReward := self.CurrentReward(startTime)
	cursor := startTime

	self.RewardCache().Iterate(startTime, endTime, func(key int64, value any) bool {
		reward, ok := value.(int64)
		if !ok {
			panic(ufmt.Sprintf("failed to cast value to int64: %T", value))
		}

		segments = append(segments, internalRewardSegment{start: cursor, end: key, rewardPerSecond: currentReward})
		cursor = key
		currentReward = reward
		return false
	})

	if cursor < endTime {
		var err error
		segments, err = appendInternalRewardTailSegments(segments, poolTier, poolPath, cursor, endTime, currentReward, self.exit)
		if err != nil {
			return nil, err
		}
	}

	return segments, nil
}

// appendInternalRewardTailSegments appends the schedule for the tail [startTime, endTime], where no
// persisted cache entry exists beyond startTime. Over this span tier/count are constant, so the rate
// changes only at halving boundaries.
func appendInternalRewardTailSegments(segments []internalRewardSegment, poolTier *PoolTier, poolPath string, startTime, endTime, baseReward int64, exit *sr.UnstakedPosition) ([]internalRewardSegment, error) {
	// A checkpoint reads the tier context it exited under: this window closed at the exit, and
	// the live lookup is skipped so a checkpoint collect never depends on live tier state.
	var tier, ratio, count uint64
	if exit != nil {
		tier, ratio, count = exit.Tier(), exit.TierRatio(), exit.TierCount()
	} else {
		var err error
		tier, ratio, count, err = poolTier.tierContextOf(poolPath)
		if err != nil {
			return nil, err
		}
	}

	if tier == 0 || tier >= AllTierCount {
		// Not currently tiered: the rate cannot increase; the base is 0 after de-tier.
		return append(segments, internalRewardSegment{start: startTime, end: endTime, rewardPerSecond: baseReward}), nil
	}

	tierRatioInt64 := int64(ratio)
	tierCount := int64(count)

	halvingTimestamps, halvingEmissions, err := poolTier.getHalvingBlocksInRange(startTime, endTime)
	if err != nil {
		return nil, err
	}

	segStart := startTime
	rate := baseReward
	for i, hv := range halvingTimestamps {
		if hv <= segStart {
			// Halving effective at/before the segment start: only switch the rate.
			rate, err = calculatePoolReward(halvingEmissions[i], tierRatioInt64, tierCount)
			if err != nil {
				return nil, err
			}
			continue
		}
		if hv >= endTime {
			break
		}

		segments = append(segments, internalRewardSegment{start: segStart, end: hv, rewardPerSecond: rate})
		rate, err = calculatePoolReward(halvingEmissions[i], tierRatioInt64, tierCount)
		if err != nil {
			return nil, err
		}
		segStart = hv
	}

	return append(segments, internalRewardSegment{start: segStart, end: endTime, rewardPerSecond: rate}), nil
}

// calculates internal unclaimable reward for the pool
func (s *stakerV1) processUnClaimableReward(poolPath string, endTimestamp int64) int64 {
	pool, ok := s.getPools().Get(poolPath)
	if !ok {
		return 0
	}
	poolResolver := NewPoolResolver(pool)

	return poolResolver.processUnclaimableReward(endTimestamp)
}

// update deposit's incentive list with new incentives created since last update
func (s *stakerV1) getExternalIncentiveIdsBy(poolPath string, startTime, endTime int64) []string {
	currentIncentiveIds := make([]string, 0)

	pool, ok := s.getPools().Get(poolPath)
	if !ok {
		return currentIncentiveIds
	}
	poolResolver := NewPoolResolver(pool)

	// Look up the pool's own start-time index instead of a global
	// creation-time index. The index is scoped to this pool's incentives, so
	// discovery cost is bounded by the number of incentives for this pool
	// within the queried range, and no longer grows with the total number of
	// incentives system-wide.
	poolResolver.IncentivesResolver().IterateIncentiveIdsByTime(startTime, endTime, func(incentiveId string) bool {
		currentIncentiveIds = append(currentIncentiveIds, incentiveId)
		return false
	})

	return currentIncentiveIds
}

// getInitialCollectTime determines the initial collection time for an incentive
// by taking the maximum of the deposit's stake time and the incentive's start time.
// This ensures rewards are only calculated from when both conditions are met:
// - The position must be staked (deposit.stakeTime)
// - The incentive must be active (incentive.startTimestamp)
//
// This function is used for lazy initialization when a position collects
// from an incentive for the first time, avoiding the need to iterate through
// all deposits when a new incentive is created.
func getInitialCollectTime(deposit *sr.Deposit, incentive *sr.ExternalIncentive) int64 {
	if deposit.StakeTime() > incentive.StartTimestamp() {
		return deposit.StakeTime()
	}
	return incentive.StartTimestamp()
}

consts.gno

package staker

const (
	GNS_TOKEN_KEY    string = "gno.land/r/gnoswap/gns.GNS"
	WUGNOT_TOKEN_KEY string = "gno.land/r/gnoland/wugnot.wugnot"
)

doc.gno

// package staker manages liquidity mining rewards for GnoSwap positions.
//
// The staker distributes GNS emissions and external incentives to liquidity
// providers based on their position size, price range, and staking duration.
// It supports both internal GNS rewards and external token incentives.
//
// Reward calculations combine elapsed-time rates with tick/range accumulation, and
// collection flows are integrated into the staking lifecycle.
package staker

emits.gno

package staker

import (
	"chain"
	"chain/runtime"

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

func emitSetPoolTier(
	prevAddr string,
	prevRealm string,
	poolPath string,
	tier uint64,
	rewardPerSecond int64,
	tierRewards map[uint64]int64,
	counts [AllTierCount]uint64,
	currentTime int64,
) {
	chain.Emit(
		"SetPoolTier",
		"prevAddr", prevAddr,
		"prevRealm", prevRealm,
		"poolPath", poolPath,
		"tier", utils.FormatUint(tier),
		"rewardPerSecond", utils.FormatInt(rewardPerSecond),
		"tier1RewardPerSecond", utils.FormatInt(tierRewards[Tier1]),
		"tier2RewardPerSecond", utils.FormatInt(tierRewards[Tier2]),
		"tier3RewardPerSecond", utils.FormatInt(tierRewards[Tier3]),
		"tier1Count", utils.FormatUint(counts[Tier1]),
		"tier2Count", utils.FormatUint(counts[Tier2]),
		"tier3Count", utils.FormatUint(counts[Tier3]),
		"currentTime", utils.FormatInt(currentTime),
		"currentHeight", utils.FormatInt(runtime.ChainHeight()),
	)
}

errors.gno

package staker

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

const (
	errNoPermission                   = "[GNOSWAP-STAKER-001] caller has no permission"
	errPoolNotFound                   = "[GNOSWAP-STAKER-002] pool not found"
	errNotAvailableUpdateCollectTime  = "[GNOSWAP-STAKER-003] not available to update collect time"
	errInvalidInput                   = "[GNOSWAP-STAKER-004] invalid input data"
	errInvalidUnstakingFee            = "[GNOSWAP-STAKER-005] invalid unstaking fee"
	errAlreadyStaked                  = "[GNOSWAP-STAKER-006] already staked position"
	errNonIncentivizedPool            = "[GNOSWAP-STAKER-007] pool is not incentivized"
	errCannotEndIncentive             = "[GNOSWAP-STAKER-008] cannot end incentive"
	errInvalidIncentiveStartTime      = "[GNOSWAP-STAKER-009] invalid incentive start time"
	errDefaultExternalToken           = "[GNOSWAP-STAKER-010] cannot delete default external token"
	errInvalidPoolPath                = "[GNOSWAP-STAKER-011] invalid pool path"
	errInvalidPoolTier                = "[GNOSWAP-STAKER-012] invalid pool tier"
	errDataNotFound                   = "[GNOSWAP-STAKER-013] requested data not found"
	errCalculationError               = "[GNOSWAP-STAKER-014] unexpected calculation error"
	errZeroLiquidity                  = "[GNOSWAP-STAKER-015] zero liquidity"
	errInvalidIncentiveDuration       = "[GNOSWAP-STAKER-016] invalid incentive duration"
	errNotAllowedForExternalReward    = "[GNOSWAP-STAKER-017] not allowed for external reward"
	errIncentiveAlreadyExists         = "[GNOSWAP-STAKER-018] incentive already exists"
	errOverflow                       = "[GNOSWAP-STAKER-019] overflow"
	errAddExistingToken               = "[GNOSWAP-STAKER-020] cannot add existing token"
	errInvalidAddress                 = "[GNOSWAP-STAKER-021] invalid address"
	errIsNotEndedIncentive            = "[GNOSWAP-STAKER-022] incentive is not ended yet"
	errCannotCancelIncentive          = "[GNOSWAP-STAKER-023] cannot cancel incentive"
	errUncollectedPosition            = "[GNOSWAP-STAKER-024] position has uncollected rewards"
	errDeniedRewardToken              = "[GNOSWAP-STAKER-025] denied reward token"
	errCannotDenyDefaultToken         = "[GNOSWAP-STAKER-026] cannot deny default token"
	errInsufficientRewardTokenBalance = "[GNOSWAP-STAKER-027] insufficient reward token balance"
)

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

event_info.gno

package staker

import (
	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	"gno.land/p/gnoswap/utils/v1"
)

type tickCrossEventInfo struct {
	tickID               int32
	stakedLiquidityGross *u256.Uint
	stakedLiquidityDelta *i256.Int
	outsideAccumulation  *u256.Uint
}

// ToString serializes tick-cross information as a compact JSON object for event emission.
// - t: Tick ID
// - slg: Staked Liquidity Gross
// - sld: Staked Liquidity Delta
// - oa: Outside Accumulation
//
// Returns:
//   - json: JSON object string containing the tick ID and the three encoded liquidity/accumulation values.
func (t *tickCrossEventInfo) ToString() string {
	return "{\"t\":" + utils.FormatInt(t.tickID) +
		",\"slg\":\"" + t.stakedLiquidityGross.ToString() + "\"" +
		",\"sld\":\"" + t.stakedLiquidityDelta.ToString() + "\"" +
		",\"oa\":\"" + t.outsideAccumulation.ToString() + "\"}"
}

// NewTickCrossEventInfo captures the values emitted when a swap crosses a tick.
//
// Parameters:
//   - tickID: Tick index crossed during the swap.
//   - stakedLiquidityGross: Total staked liquidity at the crossed tick.
//   - stakedLiquidityDelta: Net staked liquidity change applied at the crossed tick.
//   - outsideAccumulation: Reward-ratio accumulation outside the crossed tick.
//
// Returns:
//   - info: Event payload containing the supplied tick-cross values.
func NewTickCrossEventInfo(tickID int32, stakedLiquidityGross *u256.Uint, stakedLiquidityDelta *i256.Int, outsideAccumulation *u256.Uint) *tickCrossEventInfo {
	return &tickCrossEventInfo{
		tickID:               tickID,
		stakedLiquidityGross: stakedLiquidityGross,
		stakedLiquidityDelta: stakedLiquidityDelta,
		outsideAccumulation:  outsideAccumulation,
	}
}

external_deposit_fee.gno

package staker

import (
	"chain"
	"strconv"
	"strings"

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

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

// GetDepositGnsAmount returns the current GNS deposit amount required for each external incentive.
//
// Returns:
//   - amount: GNS deposit amount required per external incentive, in token smallest units.
func (s *stakerV1) GetDepositGnsAmount() int64 {
	return s.store.GetDepositGnsAmount()
}

// GetMinimumRewardAmount returns the default minimum reward amount required for external incentives.
//
// Returns:
//   - amount: Default minimum external-incentive reward amount in token smallest units.
func (s *stakerV1) GetMinimumRewardAmount() int64 {
	return s.store.GetMinimumRewardAmount()
}

// GetMinimumRewardAmountForToken returns the minimum reward amount for a specific token.
//
// Parameters:
//   - tokenPath: Token path whose configured minimum reward amount should be read.
//
// Returns:
//   - amount: Token-specific minimum reward amount when configured, otherwise the default minimum amount.
func (s *stakerV1) GetMinimumRewardAmountForToken(tokenPath string) int64 {
	amount, found := s.store.GetTokenSpecificMinimumRewards()[tokenPath]
	if found {
		return amount
	}
	// Fallback to default if not found
	return s.GetMinimumRewardAmount()
}

// GetSpecificTokenMinimumRewardAmount returns the explicitly set minimum reward amount for a token.
//
// Parameters:
//   - tokenPath: Token path whose explicit minimum reward override should be read.
//
// Returns:
//   - amount: Explicit minimum reward amount in token smallest units, or 0 when no override is configured.
//   - found: True when tokenPath has an explicit override; false when the default would be used.
func (s *stakerV1) GetSpecificTokenMinimumRewardAmount(tokenPath string) (int64, bool) {
	amount, found := s.store.GetTokenSpecificMinimumRewards()[tokenPath]
	if !found {
		return 0, false
	}
	return amount, true
}

// SetDepositGnsAmount sets the GNS deposit amount required for creating external incentives.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - amount: Non-negative GNS deposit amount in token smallest units to require per external incentive.
func (s *stakerV1) SetDepositGnsAmount(_ int, rlm realm, amount int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	assertIsValidAmount(amount)

	prevDepositGnsAmount := s.store.GetDepositGnsAmount()
	s.setDepositGnsAmount(0, rlm, amount)

	chain.Emit(
		"SetDepositGnsAmount",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"prevAmount", utils.FormatInt(prevDepositGnsAmount),
		"newAmount", utils.FormatInt(amount),
	)
}

// SetMinimumRewardAmount sets the default minimum reward amount for external incentives.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - amount: Non-negative default minimum reward amount in token smallest units for external incentives.
func (s *stakerV1) SetMinimumRewardAmount(_ int, rlm realm, amount int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	assertIsValidAmount(amount)

	prevMinimumRewardAmount := s.getMinimumRewardAmount()
	s.setMinimumRewardAmount(0, rlm, amount)

	chain.Emit(
		"SetMinimumRewardAmount",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"prevAmount", utils.FormatInt(prevMinimumRewardAmount),
		"newAmount", utils.FormatInt(amount),
	)
}

// SetTokenMinimumRewardAmount sets the minimum reward amount for a specific token.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - paramsStr: Reward override specification in the form "tokenPath:amount"; amount 0 removes an existing token-specific override, while a nonzero amount stores it.
func (s *stakerV1) SetTokenMinimumRewardAmount(_ int, rlm realm, paramsStr string) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	assertIsValidRewardAmountFormat(paramsStr)

	// Parse the paramsStr
	parts := strings.SplitN(paramsStr, ":", 2)
	tokenPath := parts[0]
	amountStr := parts[1]
	amount64, err := strconv.ParseInt(amountStr, 10, 64)
	if err != nil {
		panic(makeErrorWithDetails(
			errInvalidInput,
			ufmt.Sprintf("invalid amount format in params '%s': %v", paramsStr, err),
		))
	}

	prevAmount, found := s.store.GetTokenSpecificMinimumRewards()[tokenPath]

	// If amount is 0, remove the entry; otherwise, set it.
	if amount64 == 0 {
		// Only attempt removal if an entry actually existed
		if found {
			if err := s.store.RemoveTokenSpecificMinimumRewardItem(0, rlm, tokenPath); err != nil {
				panic(err)
			}
		}
	} else {
		if err := s.store.SetTokenSpecificMinimumRewardItem(0, rlm, tokenPath, amount64); err != nil {
			panic(err)
		}
	}

	chain.Emit(
		"SetTokenMinimumRewardAmount",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"tokenPath", tokenPath,
		"prevAmountFound", utils.FormatBool(found),
		"prevAmount", utils.FormatInt(prevAmount), // Will be 0 if !found
		"newAmount", utils.FormatInt(amount64),
	)
}

// setDepositGnsAmount internally updates the deposit GNS amount.
func (s *stakerV1) setDepositGnsAmount(_ int, rlm realm, amount int64) {
	s.store.SetDepositGnsAmount(0, rlm, amount)
}

// setMinimumRewardAmount internally updates the minimum reward amount.
func (s *stakerV1) setMinimumRewardAmount(_ int, rlm realm, amount int64) {
	s.store.SetMinimumRewardAmount(0, rlm, amount)
}

// getMinimumRewardAmount internally retrieves the minimum reward amount.
func (s *stakerV1) getMinimumRewardAmount() int64 {
	return s.store.GetMinimumRewardAmount()
}

external_incentive.gno

package staker

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

	"gno.land/p/gnoswap/gnsmath/v1"
	prbac "gno.land/p/gnoswap/rbac/v1"
	u256 "gno.land/p/gnoswap/uint256/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"
	en "gno.land/r/gnoswap/emission"
	"gno.land/r/gnoswap/halt/v1"
	sr "gno.land/r/gnoswap/staker"
)

// CreateExternalIncentive creates an external incentive program for a pool.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - targetPoolPath: Pool path to incentivize.
//   - rewardToken: Registered reward-token path.
//   - rewardAmount: Total reward amount deposited, in reward-token units.
//   - startTimestamp: Incentive start time as Unix seconds.
//   - endTimestamp: Incentive end time as Unix seconds; it must follow startTimestamp by a valid duration.
//
// Any caller may create an incentive after satisfying token, duration, start-time, reward-minimum,
// and GNS-deposit checks.
func (s *stakerV1) CreateExternalIncentive(
	_ int,
	rlm realm,
	targetPoolPath string,
	rewardToken string, // token path should be registered
	rewardAmount int64,
	startTimestamp int64,
	endTimestamp int64,
) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	assertIsPoolExists(s, targetPoolPath)

	assertIsGreaterThanMinimumRewardAmount(s, rewardToken, rewardAmount)
	assertIsAllowedForExternalReward(s, targetPoolPath, rewardToken)
	assertIsExternalRewardTokenAvailable(s, targetPoolPath, rewardToken, currentTime)
	assertIsValidIncentiveStartTime(startTimestamp)
	assertIsValidIncentiveEndTime(endTimestamp)
	assertIsValidIncentiveDuration(gnsmath.SafeSubInt64(endTimestamp, startTimestamp))
	// assert that the user has sent the correct amount of native coin
	common.AssertIsNotHandleNativeCoin()

	en.MintAndDistributeGns(cross(rlm))

	stakerAddr := access.MustGetAddress(prbac.ROLE_STAKER.String())

	// transfer reward token from user to staker
	common.SafeGRC20TransferFrom(0, rlm, rewardToken, caller, stakerAddr, rewardAmount)

	depositGnsAmount := s.store.GetDepositGnsAmount()

	// deposit gns amount
	common.SafeGRC20TransferFrom(0, rlm, GNS_TOKEN_KEY, caller, stakerAddr, depositGnsAmount)

	currentHeight := runtime.ChainHeight()
	incentiveId := s.store.NextIncentiveID(caller, currentTime)
	pool := s.getPools().GetPoolOrNil(targetPoolPath)
	if pool == nil {
		pool = sr.NewPool(targetPoolPath, currentTime)
		s.getPools().set(targetPoolPath, pool)
	}

	incentive := sr.NewExternalIncentive(
		incentiveId,
		targetPoolPath,
		rewardToken,
		rewardAmount,
		startTimestamp,
		endTimestamp,
		caller,
		depositGnsAmount,
		currentHeight,
		currentTime,
	)

	externalIncentives := s.store.GetExternalIncentives()
	if externalIncentives.Has(incentiveId) {
		panic(makeErrorWithDetails(
			errIncentiveAlreadyExists,
			ufmt.Sprintf("incentiveId(%s)", incentiveId),
		))
	}
	// store external incentive information for each incentiveId
	externalIncentives.Set(incentiveId, incentive)

	poolResolver := NewPoolResolver(pool)
	poolResolver.IncentivesResolver().create(incentive)

	chain.Emit(
		"CreateExternalIncentive",
		"prevAddr", caller.String(),
		"prevRealm", prevRealm.PkgPath(),
		"incentiveId", incentiveId,
		"targetPoolPath", targetPoolPath,
		"rewardToken", rewardToken,
		"rewardAmount", utils.FormatInt(rewardAmount),
		"startTimestamp", utils.FormatInt(startTimestamp),
		"endTimestamp", utils.FormatInt(endTimestamp),
		"depositGnsAmount", utils.FormatInt(depositGnsAmount),
		"currentHeight", utils.FormatInt(currentHeight),
		"currentTime", utils.FormatInt(currentTime),
	)
}

// EndExternalIncentive ends an external incentive after its end timestamp and finalizes the
// refundable unclaimable/remainder amount.
//
// The reward-token refund and GNS deposit are sent to the caller-supplied refundAddress. Rewards
// still owed by live positions remain claimable, and the incentive record is retained for that
// accounting. Accumulated warmup penalties are collected separately with
// CollectExternalIncentivePenalty after this function succeeds.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - targetPoolPath: Pool containing the incentive to end.
//   - incentiveId: Unique identifier of the incentive to finalize.
//   - refundAddress: Address receiving the refundable reward amount and GNS deposit.
//
// Process:
//  1. Validates that the incentive end time has been reached and no exit checkpoint still owes it.
//  2. Calculates unclaimable/remainder rewards.
//  3. Marks the incentive refunded and retains its record.
//  4. Transfers the refundable rewards and deposited GNS to refundAddress.
//
// Only callable by the incentive creator or admin.
func (s *stakerV1) EndExternalIncentive(_ int, rlm realm, targetPoolPath, incentiveId string, refundAddress address) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	// checks pool registry
	assertIsPoolExists(s, targetPoolPath)
	assertIsValidAddress(refundAddress)
	assertHasNoUncollectedIncentive(s, incentiveId)

	// checks if the pool has been incentivized
	pool, ok := s.getPools().Get(targetPoolPath)
	if !ok {
		panic(makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("targetPoolPath(%s) not found", targetPoolPath),
		))
	}

	poolResolver := NewPoolResolver(pool)
	incentivesResolver := poolResolver.IncentivesResolver()

	// Get incentive to check if GNS already refunded
	incentiveResolver, exists := incentivesResolver.GetIncentiveResolver(incentiveId)
	if !exists {
		panic(makeErrorWithDetails(
			errCannotEndIncentive,
			ufmt.Sprintf("cannot end non existent incentive(%s)", incentiveId),
		))
	}

	// Check if incentive has already been refunded
	if incentiveResolver.Refunded() {
		panic(makeErrorWithDetails(
			errCannotEndIncentive,
			ufmt.Sprintf("incentive(%s) has already been refunded", incentiveId),
		))
	}

	caller := rlm.Previous().Address()

	// Process ending
	incentive, refund, err := s.endExternalIncentive(poolResolver, incentiveResolver, caller, time.Now().Unix())
	if err != nil {
		panic(err)
	}

	stakerAddr := access.MustGetAddress(prbac.ROLE_STAKER.String())
	poolLeftExternalRewardAmount := common.BalanceOf(incentiveResolver.RewardToken(), stakerAddr)
	if poolLeftExternalRewardAmount < refund {
		previousRealm := rlm.Previous()
		chain.Emit(
			"EndExternalIncentiveShortfall",
			"prevAddr", previousRealm.Address().String(),
			"prevRealm", previousRealm.PkgPath(),
			"incentiveId", incentiveId,
			"targetPoolPath", targetPoolPath,
			"refundee", refundAddress.String(),
			"refundToken", incentiveResolver.RewardToken(),
			"expectedRefundAmount", utils.FormatInt(refund),
			"actualRefundAmount", utils.FormatInt(poolLeftExternalRewardAmount),
			"creator", incentiveResolver.Creator().String(),
		)
		refund = poolLeftExternalRewardAmount
	}

	// Mark incentive as refunded and update
	// After this update, attempts to re-claim GNS or rewards that were deposited
	// through the `endExternalIncentive` function will be blocked.
	incentiveResolver.SetRefunded(true)
	incentiveResolver.SetRewardAmount(gnsmath.SafeSubInt64(incentiveResolver.RewardAmount(), refund))
	incentiveResolver.addDistributedRewardAmount(refund)
	incentivesResolver.update(incentive)

	// refund reward token to refundee
	common.SafeGRC20Transfer(0, rlm, incentiveResolver.RewardToken(), refundAddress, refund)

	// Transfer GNS deposit back to refundee
	common.SafeGRC20Transfer(0, rlm, GNS_TOKEN_KEY, refundAddress, incentiveResolver.DepositGnsAmount())

	previousRealm := rlm.Previous()
	chain.Emit(
		"EndExternalIncentive",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"incentiveId", incentiveId,
		"targetPoolPath", targetPoolPath,
		"refundee", refundAddress.String(),
		"refundToken", incentiveResolver.RewardToken(),
		"refundAmount", utils.FormatInt(refund),
		"refundGnsAmount", utils.FormatInt(incentiveResolver.DepositGnsAmount()),
		"externalIncentiveEndBy", previousRealm.Address().String(),
		"creator", incentiveResolver.Creator().String(),
	)
}

// endExternalIncentive processes the end of an external incentive program.
func (s *stakerV1) endExternalIncentive(resolver *PoolResolver, incentiveResolver *ExternalIncentiveResolver, caller address, currentTime int64) (*sr.ExternalIncentive, int64, error) {
	if currentTime < incentiveResolver.EndTimestamp() {
		return nil, 0, makeErrorWithDetails(
			errCannotEndIncentive,
			ufmt.Sprintf("cannot end incentive before endTime(%d), current(%d)", incentiveResolver.EndTimestamp(), currentTime),
		)
	}

	// only creator or admin can end incentive
	if !access.IsAuthorized(prbac.ROLE_ADMIN.String(), caller) && caller != incentiveResolver.Creator() {
		adminAddr := access.MustGetAddress(prbac.ROLE_ADMIN.String())
		return nil, 0, makeErrorWithDetails(
			errNoPermission,
			ufmt.Sprintf(
				"only creator(%s) or admin(%s) can end incentive, but called from %s",
				incentiveResolver.Creator(), adminAddr.String(), caller,
			),
		)
	}

	// refund = unclaimableReward + remainder. Accumulated warmup penalties are tracked separately
	// and collected through CollectExternalIncentivePenalty after the incentive is ended.
	incentivesResolver := resolver.IncentivesResolver()
	unclaimableReward := incentivesResolver.calculateUnclaimableReward(incentiveResolver.IncentiveId())
	duration := gnsmath.SafeSubInt64(incentiveResolver.EndTimestamp(), incentiveResolver.StartTimestamp())
	distributableU256 := u256.MulDiv(
		incentiveResolver.RewardPerSecondX128(),
		u256.NewUintFromInt64(duration),
		q128,
	)

	distributable := gnsmath.SafeConvertToInt64(distributableU256)
	remainder := gnsmath.SafeSubInt64(incentiveResolver.TotalRewardAmount(), distributable)

	refund := gnsmath.SafeAddInt64(unclaimableReward, remainder)

	maxRefund := incentiveResolver.RewardAmount()
	if refund > maxRefund {
		refund = maxRefund
	}

	if refund < 0 {
		return nil, 0, makeErrorWithDetails(
			errCalculationError,
			ufmt.Sprintf("refund should never be negative: Got %d", refund),
		)
	}

	return incentiveResolver.ExternalIncentive, refund, nil
}

// CancelExternalIncentive cancels an external incentive before it starts and
// removes it entirely.
//
// EndExternalIncentive is the counterpart for an incentive whose end timestamp
// has passed: it keeps the record so the penalty accounting and the deposits
// that already collected from it stay resolvable. Cancelling is only allowed
// strictly before startTimestamp, where nothing has accrued yet - no deposit
// references the incentive (both StakeToken and the lazy reward discovery only
// look at incentives whose start timestamp is already in the past), so the
// record can be dropped from the incentive tree and the start-time index
// instead of being marked refunded.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - targetPoolPath: Pool path for which the incentive was created.
//   - incentiveId: Unique identifier of the incentive to cancel.
//
// Process:
//  1. Validates the incentive exists and has not started.
//  2. Removes it from the incentive tree and the start-time index.
//  3. Refunds the available reward-token balance (capped by the staker balance) and the GNS deposit to the creator.
//
// Only callable by admin, governance, or the incentive creator. The permission
// check runs after the incentive is resolved because the creator identity comes
// from the stored record; every step before it is read-only, so no unauthorized
// side effect can occur ahead of the check.
func (s *stakerV1) CancelExternalIncentive(_ int, rlm realm, targetPoolPath, incentiveId string) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	assertIsPoolExists(s, targetPoolPath)

	prevRealm := rlm.Previous()
	caller := prevRealm.Address()

	pool, ok := s.getPools().Get(targetPoolPath)
	if !ok {
		panic(makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("targetPoolPath(%s) not found", targetPoolPath),
		))
	}

	poolResolver := NewPoolResolver(pool)
	incentivesResolver := poolResolver.IncentivesResolver()

	incentiveResolver, exists := incentivesResolver.GetIncentiveResolver(incentiveId)
	if !exists {
		panic(makeErrorWithDetails(
			errCannotCancelIncentive,
			ufmt.Sprintf("cannot cancel non existent incentive(%s)", incentiveId),
		))
	}

	// Admin, governance, or the incentive creator may cancel it.
	assertIsAdminGovernanceOrCreator(caller, incentiveResolver.Creator())

	currentTime := time.Now().Unix()
	assertIsNotStartedIncentive(incentiveResolver, currentTime)

	rewardToken := incentiveResolver.RewardToken()
	depositGnsAmount := incentiveResolver.DepositGnsAmount()
	refundAmount := incentiveResolver.RewardAmount()

	// The reward tokens and the GNS deposit are always returned to the incentive
	// creator - the address that funded them in CreateExternalIncentive - so the
	// refund destination is never caller-controlled.
	creator := incentiveResolver.Creator()

	// Cap the refund by the balance actually held, mirroring
	// EndExternalIncentive: a short balance must not abort the cancellation and
	// strand the GNS deposit as well.
	stakerAddr := access.MustGetAddress(prbac.ROLE_STAKER.String())
	rewardBalance := common.BalanceOf(rewardToken, stakerAddr)
	if rewardBalance < refundAmount {
		chain.Emit(
			"CancelExternalIncentiveShortfall",
			"prevAddr", caller.String(),
			"prevRealm", prevRealm.PkgPath(),
			"incentiveId", incentiveId,
			"targetPoolPath", targetPoolPath,
			"refundToken", rewardToken,
			"expectedRefundAmount", utils.FormatInt(refundAmount),
			"actualRefundAmount", utils.FormatInt(rewardBalance),
			"refundee", creator.String(),
			"creator", creator.String(),
		)
		refundAmount = rewardBalance
	}

	// Effects before interactions: once removed, no stake, collect or discovery
	// path can resolve the incentive, so the refund cannot be replayed.
	incentivesResolver.remove(incentiveResolver.ExternalIncentive)
	s.getExternalIncentives().remove(incentiveId)

	if refundAmount > 0 {
		// transfer reward token back to creator
		common.SafeGRC20Transfer(0, rlm, rewardToken, creator, refundAmount)
	}

	if depositGnsAmount > 0 {
		// transfer GNS deposit back to creator
		common.SafeGRC20Transfer(0, rlm, GNS_TOKEN_KEY, creator, depositGnsAmount)
	}

	chain.Emit(
		"CancelExternalIncentive",
		"prevAddr", caller.String(),
		"prevRealm", prevRealm.PkgPath(),
		"incentiveId", incentiveId,
		"targetPoolPath", targetPoolPath,
		"refundToken", rewardToken,
		"refundAmount", utils.FormatInt(refundAmount),
		"refundGnsAmount", utils.FormatInt(depositGnsAmount),
		"startTimestamp", utils.FormatInt(incentiveResolver.StartTimestamp()),
		"endTimestamp", utils.FormatInt(incentiveResolver.EndTimestamp()),
		"externalIncentiveCancelBy", caller.String(),
		"creator", creator.String(),
		"currentTime", utils.FormatInt(currentTime),
	)
}

// CollectExternalIncentivePenalty collects accumulated warmup penalties for a specific ended
// external incentive. The incentive must first be finalized with EndExternalIncentive.
// Penalties are accumulated during CollectReward and stored in the incentive.
// This function transfers the accumulated penalty to the specified refund address.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - targetPoolPath: Pool containing the ended incentive.
//   - incentiveId: Unique identifier of the ended incentive whose penalty is collected.
//   - refundAddress: Address receiving the transferred penalty amount.
//
// Returns:
//   - penaltyAmount: Accumulated warmup penalty transferred, capped by the staker's available reward-token balance.
//
// Only callable by the incentive creator or admin.
func (s *stakerV1) CollectExternalIncentivePenalty(
	_ int,
	rlm realm,
	targetPoolPath string,
	incentiveId string,
	refundAddress address,
) int64 {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	assertIsPoolExists(s, targetPoolPath)
	assertIsValidAddress(refundAddress)

	pool, ok := s.getPools().Get(targetPoolPath)
	if !ok {
		panic(makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("targetPoolPath(%s) not found", targetPoolPath),
		))
	}

	poolResolver := NewPoolResolver(pool)
	incentivesResolver := poolResolver.IncentivesResolver()

	incentiveResolver, exists := incentivesResolver.GetIncentiveResolver(incentiveId)
	if !exists {
		panic(makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("incentive(%s) not found", incentiveId),
		))
	}

	if !incentiveResolver.Refunded() {
		panic(makeErrorWithDetails(
			errIsNotEndedIncentive,
			ufmt.Sprintf("incentive(%s) must be ended first (call EndExternalIncentive)", incentiveId),
		))
	}

	caller := rlm.Previous().Address()
	if !access.IsAuthorized(prbac.ROLE_ADMIN.String(), caller) && caller != incentiveResolver.Creator() {
		adminAddr := access.MustGetAddress(prbac.ROLE_ADMIN.String())
		panic(makeErrorWithDetails(
			errNoPermission,
			ufmt.Sprintf("only creator(%s) or admin(%s) can collect penalty, but called from %s", incentiveResolver.Creator(), adminAddr.String(), caller),
		))
	}

	penaltyAmount := incentiveResolver.AccumulatedPenaltyAmount()
	if penaltyAmount == 0 {
		return 0
	}

	// Cap by actual staker balance
	stakerAddr := access.MustGetAddress(prbac.ROLE_STAKER.String())
	balance := common.BalanceOf(incentiveResolver.RewardToken(), stakerAddr)
	if balance < penaltyAmount {
		previousRealm := rlm.Previous()
		chain.Emit(
			"CollectExternalIncentivePenaltyShortfall",
			"prevAddr", previousRealm.Address().String(),
			"prevRealm", previousRealm.PkgPath(),
			"targetPoolPath", targetPoolPath,
			"incentiveId", incentiveId,
			"refundAddress", refundAddress.String(),
			"refundToken", incentiveResolver.RewardToken(),
			"expectedPenaltyAmount", utils.FormatInt(penaltyAmount),
			"actualPenaltyAmount", utils.FormatInt(balance),
			"creator", incentiveResolver.Creator().String(),
		)
		penaltyAmount = balance
	}

	// Reset accumulated penalty
	incentiveResolver.SetAccumulatedPenaltyAmount(gnsmath.SafeSubInt64(incentiveResolver.AccumulatedPenaltyAmount(), penaltyAmount))
	incentivesResolver.update(incentiveResolver.ExternalIncentive)

	// Transfer penalty to refund address
	common.SafeGRC20Transfer(0, rlm, incentiveResolver.RewardToken(), refundAddress, penaltyAmount)

	previousRealm := rlm.Previous()
	chain.Emit(
		"CollectExternalIncentivePenalty",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"targetPoolPath", targetPoolPath,
		"incentiveId", incentiveId,
		"refundAddress", refundAddress.String(),
		"penaltyAmount", utils.FormatInt(penaltyAmount),
	)

	return penaltyAmount
}

external_token_list.gno

package staker

import (
	"chain"

	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/halt/v1"
	sr "gno.land/r/gnoswap/staker"
)

// AddToken adds a registered token key to the list of allowed tokens.
// Only admin or governance can add a token.
//
// Parameters:
//   - _: Leading realm-call discriminator; callers pass 0.
//   - rlm: Current staker realm context, validated before storage is changed.
//   - tokenPath: Registered token path to add to the allowed-token list.
//
// Panics:
//   - If the caller is not admin or governance, or the token key is not registered.
func (s *stakerV1) AddToken(_ int, rlm realm, tokenPath string) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	if err := checkCannotAddDefaultToken(tokenPath); err != nil {
		panic(err.Error())
	}

	common.MustRegistered(tokenPath)

	if err := s.store.AddAllowedToken(0, rlm, tokenPath); err != nil {
		panic(err.Error())
	}

	chain.Emit(
		"AddToken",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"tokenPath", tokenPath,
	)
}

// RemoveToken removes a token path from the list of allowed tokens.
// Only the admin can remove a token.
//
// Default tokens cannot be removed.
//
// Parameters:
//   - _: Leading realm-call discriminator; callers pass 0.
//   - rlm: Current staker realm context, validated before storage is changed.
//   - tokenPath: Token path to remove from the allowed-token list.
//
// Panics:
//   - If the caller is not admin or governance, or the token path is a protected default token.
func (s *stakerV1) RemoveToken(_ int, rlm realm, tokenPath string) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	if err := checkCannotRemoveDefaultToken(tokenPath); err != nil {
		panic(err.Error())
	}

	if err := s.store.RemoveAllowedToken(0, rlm, tokenPath); err != nil {
		panic(err.Error())
	}

	chain.Emit(
		"RemoveToken",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"tokenPath", tokenPath,
	)
}

func checkCannotAddDefaultToken(tokenPath string) error {
	if contains(sr.DefaultAllowedTokens(), tokenPath) {
		return ufmt.Errorf("%v: cannot add existing token(%s)", errAddExistingToken, tokenPath)
	}

	return nil
}

func checkCannotRemoveDefaultToken(tokenPath string) error {
	if contains(sr.DefaultAllowedTokens(), tokenPath) {
		return ufmt.Errorf("%v: cannot remove default token(%s)", errDefaultExternalToken, tokenPath)
	}

	return nil
}

// SetDeniedRewardToken sets or clears the operational deny flag for an external
// incentive reward token.
//
// Pool-pair tokens qualify as reward tokens for their own pool without the
// governance allowlist (a product policy), so the deny flag is the only lever
// to stop NEW incentives in a pair token whose issuer turned hostile. The flag
// is checked at incentive creation only: collection of already-created
// incentives is deliberately unaffected, because the ledger-level delivery
// guard in deliverExternalIncentiveReward already bounds their blast radius to
// the hostile token itself.
//
// Default protocol tokens (GNS, WUGNOT) cannot be denied.
//
// Only the admin or governance can set the flag.
//
// Parameters:
//   - _: Leading realm-call discriminator; callers pass 0.
//   - rlm: Current staker realm context, validated before the deny list is changed.
//   - tokenPath: Reward-token path whose denied status is being changed.
//   - denied: True to add tokenPath to the deny list, false to remove it.
func (s *stakerV1) SetDeniedRewardToken(_ int, rlm realm, tokenPath string, denied bool) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	if denied {
		if err := checkCannotDenyDefaultToken(tokenPath); err != nil {
			panic(err.Error())
		}

		if err := s.store.AddDeniedRewardToken(0, rlm, tokenPath); err != nil {
			panic(err.Error())
		}
	} else {
		if err := s.store.RemoveDeniedRewardToken(0, rlm, tokenPath); err != nil {
			panic(err.Error())
		}
	}

	deniedStr := "false"
	if denied {
		deniedStr = "true"
	}

	chain.Emit(
		"SetDeniedRewardToken",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"tokenPath", tokenPath,
		"denied", deniedStr,
	)
}

func checkCannotDenyDefaultToken(tokenPath string) error {
	if contains(sr.DefaultAllowedTokens(), tokenPath) {
		return ufmt.Errorf("%v: cannot deny default token(%s)", errCannotDenyDefaultToken, tokenPath)
	}

	return nil
}

getter.gno

package staker

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

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

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

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

// findPoolByPoolPath retrieves the pool by its path, or nil when it does not
// exist. Read-only views use it so a missing pool reads as nil rather than
// aborting the caller's transaction.
func (s *stakerV1) findPoolByPoolPath(poolPath string) *sr.Pool {
	result := s.store.GetPools().Get(poolPath)
	if result == nil {
		return nil
	}

	pool, ok := result.(*sr.Pool)
	if !ok {
		return nil
	}

	return pool
}

// getPoolByPoolPath retrieves the pool by its path.
func (s *stakerV1) getPoolByPoolPath(poolPath string) (*sr.Pool, error) {
	result := s.store.GetPools().Get(poolPath)
	if result == nil {
		return nil, makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("poolPath(%s) pool does not exist", poolPath),
		)
	}

	pool, ok := result.(*sr.Pool)
	if !ok {
		return nil, makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("poolPath(%s) pool does not exist", poolPath),
		)
	}

	return pool, nil
}

// GetPool returns the pool for the given path.
//
// Parameters:
//   - poolPath: Pool path whose pool entry is queried.
//
// Returns:
//   - *sr.Pool: Pool registered at poolPath, or nil when the lookup fails.
//   - error: Non-nil when poolPath has no valid pool entry; nil on success.
func (s *stakerV1) GetPool(poolPath string) (*sr.Pool, error) {
	pool, err := s.getPoolByPoolPath(poolPath)
	if err != nil {
		return nil, err
	}
	return pool, nil
}

// getIncentive retrieves an external incentive by ID.
func (s *stakerV1) getIncentive(poolPath string, incentiveId string) (*sr.ExternalIncentive, error) {
	pool, err := s.getPoolByPoolPath(poolPath)
	if err != nil {
		return nil, err
	}

	incentives := pool.Incentives()
	incentive := incentives.IncentiveTrees().Get(incentiveId)
	if incentive == nil {
		return nil, ufmt.Errorf("incentiveId(%s) incentive does not exist", incentiveId)
	}

	ictv, ok := incentive.(*sr.ExternalIncentive)
	if !ok {
		return nil, ufmt.Errorf("failed to cast incentive to *ExternalIncentive: %T", incentive)
	}
	return ictv, nil
}

// GetIncentiveStartTimestamp returns the start timestamp of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose start time is queried.
//
// Returns:
//   - int64: Incentive start timestamp in Unix seconds.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveStartTimestamp(poolPath string, incentiveId string) (int64, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return 0, err
	}

	return incentive.StartTimestamp(), nil
}

// GetIncentiveEndTimestamp returns the end timestamp of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose end time is queried.
//
// Returns:
//   - int64: Incentive end timestamp in Unix seconds.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveEndTimestamp(poolPath string, incentiveId string) (int64, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return 0, err
	}

	return incentive.EndTimestamp(), nil
}

// GetTargetPoolPathByIncentiveId returns the target pool path of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose target pool is queried.
//
// Returns:
//   - string: Pool path targeted by the incentive.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetTargetPoolPathByIncentiveId(poolPath string, incentiveId string) (string, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return "", err
	}

	return incentive.TargetPoolPath(), nil
}

// GetCreatedHeightOfIncentive returns the creation height of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose creation height is queried.
//
// Returns:
//   - int64: Chain height at which the incentive was created.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetCreatedHeightOfIncentive(poolPath string, incentiveId string) (int64, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return 0, err
	}

	return incentive.CreatedHeight(), nil
}

// GetIncentiveCreatedTimestamp returns the creation timestamp of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose creation time is queried.
//
// Returns:
//   - int64: Incentive creation timestamp in Unix seconds.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveCreatedTimestamp(poolPath string, incentiveId string) (int64, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return 0, err
	}

	return incentive.CreatedTimestamp(), nil
}

// GetIncentiveTotalRewardAmount returns the total reward amount of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose configured reward is queried.
//
// Returns:
//   - int64: Total reward amount configured for the incentive, in reward-token units.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveTotalRewardAmount(poolPath string, incentiveId string) (int64, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return 0, err
	}

	return incentive.TotalRewardAmount(), nil
}

// GetIncentiveDistributedRewardAmount returns the distributed reward amount of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose distribution total is queried.
//
// Returns:
//   - int64: Reward amount already distributed by the incentive, in reward-token units.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveDistributedRewardAmount(poolPath string, incentiveId string) (int64, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return 0, err
	}

	return incentive.DistributedRewardAmount(), nil
}

// GetIncentiveRemainingRewardAmount returns the remaining reward amount of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose remaining balance is queried.
//
// Returns:
//   - int64: Reward amount still available for collection, in reward-token units.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveRemainingRewardAmount(poolPath string, incentiveId string) (int64, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return 0, err
	}

	return incentive.RewardAmount(), nil
}

// GetIncentiveAccumulatedPenaltyAmount returns the accumulated warmup penalty amount of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose penalties are queried.
//
// Returns:
//   - int64: Warm-up penalty accumulated for the incentive, in reward-token units.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveAccumulatedPenaltyAmount(poolPath string, incentiveId string) (int64, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return 0, err
	}

	return incentive.AccumulatedPenaltyAmount(), nil
}

// GetIncentiveDepositGnsAmount returns the deposit GNS amount of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose GNS deposit is queried.
//
// Returns:
//   - int64: GNS amount deposited when the incentive was created.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveDepositGnsAmount(poolPath string, incentiveId string) (int64, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return 0, err
	}

	return incentive.DepositGnsAmount(), nil
}

// GetIncentiveRefunded returns whether an incentive has been refunded.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose refund state is queried.
//
// Returns:
//   - bool: true when the incentive has been finalized/refunded; false while it remains unrefunded.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveRefunded(poolPath string, incentiveId string) (bool, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return false, err
	}

	return incentive.Refunded(), nil
}

// IsIncentiveActive reports whether an unrefunded incentive is active, including both start and end timestamps.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose activity is queried.
//
// Returns:
//   - bool: true when the current Unix time is within the incentive's start/end window and it is unrefunded; false otherwise.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) IsIncentiveActive(poolPath string, incentiveId string) (bool, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return false, err
	}
	currentTime := time.Now().Unix()

	resolver := NewExternalIncentiveResolver(incentive)
	return resolver.isActive(currentTime) && !resolver.Refunded(), nil
}

// GetIncentiveRewardToken returns the reward token of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose reward token is queried.
//
// Returns:
//   - string: Reward-token package path configured for the incentive.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveRewardToken(poolPath string, incentiveId string) (string, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return "", err
	}

	return incentive.RewardToken(), nil
}

// GetIncentiveRewardAmount returns the remaining reward amount of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose remaining reward is queried.
//
// Returns:
//   - *u256.Uint: Remaining reward amount as a uint256 value, or nil when lookup fails.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveRewardAmount(poolPath string, incentiveId string) (*u256.Uint, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return nil, err
	}

	return u256.NewUintFromInt64(incentive.RewardAmount()), nil
}

// GetIncentiveRewardAmountAsString returns the remaining reward amount of an incentive as string.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose remaining reward is formatted.
//
// Returns:
//   - string: Remaining reward amount encoded as a decimal string.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveRewardAmountAsString(poolPath string, incentiveId string) (string, error) {
	rewardAmount, err := s.GetIncentiveRewardAmount(poolPath, incentiveId)
	if err != nil {
		return "", err
	}

	return rewardAmount.ToString(), nil
}

// GetIncentiveRewardPerSecondX128 returns the Q128-scaled reward per second of
// an incentive (i.e. actual rate = value / 2^128). The Q128 form preserves
// sub-second precision that would otherwise be lost to int64 truncation.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose reward rate is queried.
//
// Returns:
//   - *u256.Uint: Q128-scaled reward-per-second value; divide by 2^128 for the unscaled rate.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveRewardPerSecondX128(poolPath string, incentiveId string) (*u256.Uint, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return nil, err
	}

	return incentive.RewardPerSecondX128(), nil
}

// GetIncentiveCreator returns the creator address of an incentive.
//
// Parameters:
//   - poolPath: Pool path containing the incentive.
//   - incentiveId: External incentive identifier whose creator is queried.
//
// Returns:
//   - address: Address that created the incentive.
//   - error: Non-nil when poolPath or incentiveId cannot be resolved; nil on success.
func (s *stakerV1) GetIncentiveCreator(poolPath string, incentiveId string) (address, error) {
	incentive, err := s.getIncentive(poolPath, incentiveId)
	if err != nil {
		return address(""), err
	}

	return incentive.Creator(), nil
}

// getDeposit retrieves a deposit by LP token ID.
func (s *stakerV1) getDeposit(lpTokenId uint64) (*sr.Deposit, error) {
	deposits := s.getDeposits()
	if !deposits.Has(lpTokenId) {
		return nil, makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("lpTokenId(%d) deposit does not exist", lpTokenId),
		)
	}

	return deposits.get(lpTokenId), nil
}

// assertIsCollectablePosition ensures the position is staked or holds an exit checkpoint.
func (s *stakerV1) assertIsCollectablePosition(positionId uint64) error {
	if s.getDeposits().Has(positionId) || s.getUnstakedPositions().Has(positionId) {
		return nil
	}

	return makeErrorWithDetails(
		errDataNotFound,
		ufmt.Sprintf("lpTokenId(%d) deposit does not exist", positionId),
	)
}

// GetDeposit returns the deposit for the given LP token ID.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose live deposit is queried.
//
// Returns:
//   - *sr.Deposit: Stored live deposit, or nil when lookup fails.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDeposit(lpTokenId uint64) (*sr.Deposit, error) {
	return s.getDeposit(lpTokenId)
}

// CollectableEmissionReward returns the claimable internal reward amount for a position.
// calculateCollectablePositionReward is read-only, so querying a collectable amount never mutates state.
//
// Parameters:
//   - positionId: LP position NFT token ID or exit-checkpoint ID whose accrued GNS reward is estimated.
//
// Returns:
//   - int64: Currently collectable GNS emission amount in GNS units; zero may be a valid accrued amount.
//   - error: Non-nil when positionId is not staked/checked out or reward calculation fails; nil on success.
func (s *stakerV1) CollectableEmissionReward(positionId uint64) (int64, error) {
	currentTime := time.Now().Unix()
	currentHeight := runtime.ChainHeight()
	if err := s.assertIsCollectablePosition(positionId); err != nil {
		return 0, err
	}
	reward, err := s.calculateCollectablePositionReward(currentHeight, currentTime, positionId)
	if err != nil {
		return 0, err
	}
	return reward.Internal, nil
}

// CollectableExternalIncentiveReward returns the claimable external reward amount for an incentive.
// calculateCollectablePositionReward is read-only, so querying a collectable amount never mutates state.
//
// Parameters:
//   - positionId: LP position NFT token ID or exit-checkpoint ID whose external reward is estimated.
//   - incentiveId: External incentive identifier to inspect; an absent reward entry yields zero without error.
//
// Returns:
//   - int64: Currently collectable reward amount for incentiveId, in that incentive's token units.
//   - error: Non-nil when positionId is not staked/checked out or reward calculation fails; nil on success.
func (s *stakerV1) CollectableExternalIncentiveReward(positionId uint64, incentiveId string) (int64, error) {
	currentTime := time.Now().Unix()
	currentHeight := runtime.ChainHeight()
	if err := s.assertIsCollectablePosition(positionId); err != nil {
		return 0, err
	}
	reward, err := s.calculateCollectablePositionReward(currentHeight, currentTime, positionId)
	if err != nil {
		return 0, err
	}
	amount, ok := reward.External[incentiveId]
	if !ok {
		return 0, nil
	}
	return amount, nil
}

// GetDepositOwner returns the owner of a deposit.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose owner is queried.
//
// Returns:
//   - address: Address recorded as the deposit owner.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositOwner(lpTokenId uint64) (address, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return address(""), err
	}

	return deposit.Owner(), nil
}

// GetDepositStakeTime returns the Unix timestamp at which a position was staked.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose stake time is queried.
//
// Returns:
//   - int64: Unix timestamp at which the position was staked.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositStakeTime(lpTokenId uint64) (int64, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return 0, err
	}

	return deposit.StakeTime(), nil
}

// GetDepositTargetPoolPath returns the target pool path of a deposit.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose pool target is queried.
//
// Returns:
//   - string: Pool path targeted by the deposit.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositTargetPoolPath(lpTokenId uint64) (string, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return "", err
	}

	return deposit.TargetPoolPath(), nil
}

// GetDepositTickLower returns the lower tick of a deposit.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose lower tick is queried.
//
// Returns:
//   - int32: Signed lower tick boundary recorded by the deposit.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositTickLower(lpTokenId uint64) (int32, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return 0, err
	}

	return deposit.TickLower(), nil
}

// GetDepositTickUpper returns the upper tick of a deposit.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose upper tick is queried.
//
// Returns:
//   - int32: Signed upper tick boundary recorded by the deposit.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositTickUpper(lpTokenId uint64) (int32, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return 0, err
	}

	return deposit.TickUpper(), nil
}

// GetDepositLiquidity returns the liquidity of a deposit.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose liquidity is queried.
//
// Returns:
//   - *u256.Uint: Position liquidity as an unsigned 256-bit value, or nil when lookup fails.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositLiquidity(lpTokenId uint64) (*u256.Uint, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return nil, err
	}

	return deposit.Liquidity(), nil
}

// GetDepositLiquidityAsString returns the liquidity of a deposit as string.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose liquidity is formatted.
//
// Returns:
//   - string: Position liquidity encoded as a decimal string.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositLiquidityAsString(lpTokenId uint64) (string, error) {
	liquidity, err := s.GetDepositLiquidity(lpTokenId)
	if err != nil {
		return "", err
	}

	return liquidity.ToString(), nil
}

// GetDepositInternalRewardLastCollectTimestamp returns the last collect timestamp of a deposit.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose internal-reward cursor is queried.
//
// Returns:
//   - int64: Unix timestamp of the deposit's last internal GNS reward collection.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositInternalRewardLastCollectTimestamp(lpTokenId uint64) (int64, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return 0, err
	}

	return deposit.InternalRewardLastCollectTime(), nil
}

// GetDepositCollectedInternalReward returns the collected internal reward amount.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose collected GNS amount is queried.
//
// Returns:
//   - int64: Cumulative internal GNS reward already collected for the deposit.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositCollectedInternalReward(lpTokenId uint64) (int64, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return 0, err
	}

	return deposit.CollectedInternalReward(), nil
}

// GetDepositCollectedExternalReward returns the collected external reward amount for an incentive.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose external-reward history is queried.
//   - incentiveId: External incentive identifier whose collected amount is queried.
//
// Returns:
//   - int64: Cumulative reward collected from incentiveId, in its reward-token units.
//   - error: Non-nil when the position deposit or its checkpoint data cannot be resolved; nil on success.
func (s *stakerV1) GetDepositCollectedExternalReward(lpTokenId uint64, incentiveId string) (int64, error) {
	depositResolver, err := s.getDepositResolver(lpTokenId)
	if err != nil {
		return 0, err
	}
	return depositResolver.CollectedExternalReward(incentiveId), nil
}

// GetDepositExternalRewardLastCollectTimestamp returns the last collect timestamp of a deposit.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose external-reward cursor is queried.
//   - incentiveId: External incentive identifier whose collection time is queried.
//
// Returns:
//   - int64: Unix timestamp of the deposit's last collection for incentiveId.
//   - error: Non-nil when the position deposit or its checkpoint data cannot be resolved; nil on success.
func (s *stakerV1) GetDepositExternalRewardLastCollectTimestamp(lpTokenId uint64, incentiveId string) (int64, error) {
	depositResolver, err := s.getDepositResolver(lpTokenId)
	if err != nil {
		return 0, err
	}
	return depositResolver.ExternalRewardLastCollectTime(incentiveId), nil
}

// GetDepositWarmUp returns the warm-up records of a deposit.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose warm-up records are queried.
//
// Returns:
//   - []sr.Warmup: Warm-up reward records currently associated with the deposit.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositWarmUp(lpTokenId uint64) ([]sr.Warmup, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return nil, err
	}

	return deposit.Warmups(), nil
}

// GetDepositExternalIncentiveIdList returns external incentive IDs for a deposit.
//
// Parameters:
//   - lpTokenId: LP position NFT token ID whose incentive index is queried.
//
// Returns:
//   - []string: External incentive identifiers tracked by the deposit.
//   - error: Non-nil data-not-found error when lpTokenId is not currently deposited; nil on success.
func (s *stakerV1) GetDepositExternalIncentiveIdList(lpTokenId uint64) ([]string, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return nil, err
	}

	return deposit.GetExternalIncentiveIdList(), nil
}

// GetPoolTier returns the tier of a pool.
//
// Parameters:
//   - poolPath: Pool path whose current emission tier is queried.
//
// Returns:
//   - uint64: Current tier number; zero means the pool is not an internal-emission target.
func (s *stakerV1) GetPoolTier(poolPath string) uint64 {
	return s.getPoolTier().CurrentTier(poolPath)
}

// GetPoolTierRatio returns the current reward ratio for a pool's tier.
//
// Parameters:
//   - poolPath: Pool path whose current tier ratio is queried.
//
// Returns:
//   - uint64: Configured percentage weight (0-100) associated with the pool's current tier.
//   - error: Non-nil when the pool's current tier has no configured ratio; nil on success.
func (s *stakerV1) GetPoolTierRatio(poolPath string) (uint64, error) {
	tier := s.GetPoolTier(poolPath)
	ratio, err := s.getPoolTier().tierRatio.Get(tier)
	if err != nil {
		return 0, makeErrorWithDetails(errInvalidPoolTier, err.Error())
	}

	return ratio, nil
}

// GetPoolTierCount returns the number of pools in a tier.
//
// Parameters:
//   - tier: Tier number whose current pool membership count is queried.
//
// Returns:
//   - uint64: Number of pools currently assigned to tier; zero is returned for tier zero.
func (s *stakerV1) GetPoolTierCount(tier uint64) uint64 {
	if tier == 0 {
		return 0
	}
	return uint64(s.getPoolTier().CurrentCount(tier))
}

// GetPoolReward returns the current reward amount for a tier.
//
// Parameters:
//   - tier: Emission tier whose current per-pool reward is queried.
//
// Returns:
//   - int64: Current GNS reward allocation per second for one pool in tier.
//   - error: Non-nil when tier is outside the configured range or the emission rate cannot be read; nil on success.
func (s *stakerV1) GetPoolReward(tier uint64) (int64, error) {
	if tier == 0 || tier >= AllTierCount {
		return 0, makeErrorWithDetails(
			errInvalidPoolTier,
			ufmt.Sprintf("tier(%d) must be between 1 and %d", tier, AllTierCount-1),
		)
	}
	return s.getPoolTier().CurrentReward(tier)
}

// GetPoolStakedLiquidity returns the current total staked liquidity of a pool.
//
// Parameters:
//   - poolPath: Pool path whose current staked liquidity is queried.
//
// Returns:
//   - string: Current staked liquidity encoded as a decimal unsigned-integer string.
//   - error: Non-nil when poolPath has no registered pool; nil on success.
func (s *stakerV1) GetPoolStakedLiquidity(poolPath string) (string, error) {
	pool, err := s.getPoolByPoolPath(poolPath)
	if err != nil {
		return "", err
	}
	liquidity := NewPoolResolver(pool).CurrentStakedLiquidity(time.Now().Unix())
	if liquidity == nil {
		return u256.Zero().ToString(), nil
	}

	return liquidity.ToString(), nil
}

// GetPoolsByTier returns the list of pools in a tier.
//
// Parameters:
//   - tier: Tier number whose pool membership is listed.
//
// Returns:
//   - []string: Pool paths currently assigned to tier, or an empty slice for tier zero.
//   - error: Non-nil when stored tier membership cannot be cast to uint64; nil on success.
func (s *stakerV1) GetPoolsByTier(tier uint64) ([]string, error) {
	if tier == 0 {
		return []string{}, nil
	}

	pools := make([]string, 0)
	var iterErr error
	s.getPoolTier().membership.Iterate("", "", func(poolPath string, value any) bool {
		currentTier, ok := value.(uint64)
		if !ok {
			iterErr = errors.New("failed to cast tier to uint64")
			return true
		}
		if currentTier == tier {
			pools = append(pools, poolPath)
		}
		return false
	})
	if iterErr != nil {
		return nil, iterErr
	}

	return pools, nil
}

// GetTotalEmissionSent returns the total GNS emission sent.
//
// Returns:
//   - int64: Cumulative GNS emission amount sent by the staker.
func (s *stakerV1) GetTotalEmissionSent() int64 {
	return s.store.GetTotalEmissionSent()
}

// GetAllowedTokens returns the allowed external incentive token list.
//
// Returns:
//   - []string: Token paths currently allowed for external incentives.
func (s *stakerV1) GetAllowedTokens() []string {
	return s.store.GetAllowedTokens()
}

// GetDeniedRewardTokens returns the denied external incentive reward token list.
//
// Returns:
//   - []string: Token paths currently denied for newly created external incentives.
func (s *stakerV1) GetDeniedRewardTokens() []string {
	return s.store.GetDeniedRewardTokens()
}

// GetWarmupTemplate returns the current warmup template.
//
// Returns:
//   - []sr.Warmup: Current warm-up percentage and duration records used for reward calculations.
func (s *stakerV1) GetWarmupTemplate() []sr.Warmup {
	return s.store.GetWarmupTemplate()
}

// IsStaked returns whether a position is staked.
//
// Parameters:
//   - positionId: LP position NFT token ID whose live-staking status is queried.
//
// Returns:
//   - bool: true when positionId has a live deposit; false when it is not staked.
func (s *stakerV1) IsStaked(positionId uint64) bool {
	return s.getDeposits().Has(positionId)
}

// GetExternalIncentiveByPoolPath returns all external incentives for a pool.
//
// Parameters:
//   - poolPath: Pool path whose external incentives are listed.
//
// Returns:
//   - []sr.ExternalIncentive: External incentives targeting poolPath, or an empty slice when none exist.
//   - error: Non-nil when an external-incentive entry has an incompatible stored type; nil on success.
func (s *stakerV1) GetExternalIncentiveByPoolPath(poolPath string) ([]sr.ExternalIncentive, error) {
	incentives := make([]sr.ExternalIncentive, 0)
	var iterErr error

	s.store.GetExternalIncentives().Iterate("", "", func(_ string, value any) bool {
		incentive, ok := value.(*sr.ExternalIncentive)
		if !ok {
			iterErr = errors.New("failed to cast value to *ExternalIncentive")
			return true
		}
		if incentive.TargetPoolPath() == poolPath {
			incentives = append(incentives, *incentive)
		}
		return false
	})
	if iterErr != nil {
		return nil, iterErr
	}

	return incentives, nil
}

// GetPoolRewardCaches returns a read-only view of a pool's reward cache, keyed
// by the encoded block timestamp. nil is returned when the pool does not exist.
//
// Parameters:
//   - poolPath: Pool path whose reward-cache view is requested.
//
// Returns:
//   - *rotree.ReadOnlyTree: Read-only tree keyed by encoded Unix timestamps with int64 reward rates; nil when poolPath is absent or malformed.
func (s *stakerV1) GetPoolRewardCaches(poolPath string) *rotree.ReadOnlyTree {
	pool := s.findPoolByPoolPath(poolPath)
	if pool == nil {
		return nil
	}

	return pool.RewardCache().ReadOnly(rewardCacheEntry)
}

// GetPoolIncentives returns a read-only view of a pool's external incentives,
// keyed by incentive ID. nil is returned when the pool does not exist.
//
// Parameters:
//   - poolPath: Pool path whose external-incentive view is requested.
//
// Returns:
//   - *rotree.ReadOnlyTree: Read-only tree keyed by incentive ID with cloned external-incentive values; nil when poolPath is absent or malformed.
func (s *stakerV1) GetPoolIncentives(poolPath string) *rotree.ReadOnlyTree {
	pool := s.findPoolByPoolPath(poolPath)
	if pool == nil {
		return nil
	}

	return rotree.Wrap(pool.Incentives().IncentiveTrees(), cloneExternalIncentiveEntry)
}

// GetPoolGlobalRewardRatioAccumulations returns a read-only view of a pool's
// global reward ratio accumulation, keyed by the encoded block timestamp.
// nil is returned when the pool does not exist.
//
// Parameters:
//   - poolPath: Pool path whose global reward-ratio history is requested.
//
// Returns:
//   - *rotree.ReadOnlyTree: Read-only tree keyed by encoded Unix timestamps with string-encoded accumulations; nil when poolPath is absent or malformed.
func (s *stakerV1) GetPoolGlobalRewardRatioAccumulations(poolPath string) *rotree.ReadOnlyTree {
	pool := s.findPoolByPoolPath(poolPath)
	if pool == nil {
		return nil
	}

	return pool.GlobalRewardRatioAccumulation().ReadOnly(accumulationEntry)
}

// GetPoolHistoricalTicks returns a read-only view of a pool's historical ticks,
// keyed by the encoded block timestamp with the int32 tick as the value.
// nil is returned when the pool does not exist.
//
// Parameters:
//   - poolPath: Pool path whose historical tick view is requested.
//
// Returns:
//   - *rotree.ReadOnlyTree: Read-only tree keyed by encoded Unix timestamps with int32 tick values; nil when poolPath is absent or malformed.
func (s *stakerV1) GetPoolHistoricalTicks(poolPath string) *rotree.ReadOnlyTree {
	pool := s.findPoolByPoolPath(poolPath)
	if pool == nil {
		return nil
	}

	return pool.HistoricalTick().ReadOnly(historicalTickEntry)
}

getter_utils.gno

package staker

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

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

// cloneExternalIncentiveEntry is the transformation for a pool's incentive
// tree. ExternalIncentive is mutable and its setters are declared in
// /r/gnoswap/staker, so an external holder of the stored pointer could write
// realm state through it.
func cloneExternalIncentiveEntry(value any) any {
	incentive, ok := value.(*sr.ExternalIncentive)
	if !ok {
		return nil
	}

	return incentive.Clone()
}

// rewardCacheEntry, accumulationEntry, and historicalTickEntry are the
// transformations for the UintTree-backed views. Their values are immutable
// scalars, so nothing needs copying; they type-check instead, which keeps the
// filtering the replaced slice getters did when an entry failed its cast.
func rewardCacheEntry(value any) any {
	reward, ok := value.(int64)
	if !ok {
		return nil
	}

	return reward
}

func accumulationEntry(value any) any {
	accumulation, ok := value.(string)
	if !ok {
		return nil
	}

	return accumulation
}

func historicalTickEntry(value any) any {
	tick, ok := value.(int32)
	if !ok {
		return nil
	}

	return tick
}

gnomod.toml

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

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

init.gno

package staker

import (
	"time"

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

	"gno.land/r/gnoswap/emission"

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

const (
	defaultDepositGnsAmount    = int64(100_000_000_000)
	defaultMinimumRewardAmount = int64(1_000_000_000)

	// unstakingFee is the fee charged when unstaking positions.
	// This parameter can be modified through governance.
	defaultUnstakingFee = uint64(100) // 1%
)

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

func registerStakerV1(cur realm) {
	sr.RegisterInitializer(cross(cur), func(_ int, rlm realm, stakerStore sr.IStakerStore, poolAccessor sr.PoolAccessor, emissionAccessor sr.EmissionAccessor, nftAccessor sr.NFTAccessor) sr.IStaker {
		access.AssertIsRlmCurrent(0, rlm)

		err := initStoreData(0, rlm, stakerStore, emissionAccessor)
		if err != nil {
			panic(err)
		}

		instance := NewStakerV1(stakerStore, poolAccessor, emissionAccessor, nftAccessor)
		instance.setupSwapHooks(0, rlm)
		emissionAccessor.SetOnDistributionPctChangeCallback(0, rlm, instance.emissionCacheUpdateHook)

		return instance
	})
}

func initStoreData(_ int, rlm realm, stakerStore sr.IStakerStore, emissionAccessor sr.EmissionAccessor) error {
	if !stakerStore.HasDepositGnsAmountStoreKey() {
		err := stakerStore.SetDepositGnsAmount(0, rlm, defaultDepositGnsAmount)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasMinimumRewardAmountStoreKey() {
		err := stakerStore.SetMinimumRewardAmount(0, rlm, defaultMinimumRewardAmount)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasDepositsStoreKey() {
		err := stakerStore.SetDeposits(0, rlm, sr.NewBPTreeN(16))
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasExternalIncentivesStoreKey() {
		err := stakerStore.SetExternalIncentives(0, rlm, sr.NewBPTreeN(16))
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasTotalEmissionSentStoreKey() {
		err := stakerStore.SetTotalEmissionSent(0, rlm, 0)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasAllowedTokensStoreKey() {
		// Copy the package-level default slice so each store owns its own
		// allowed-tokens slice. Storing sr.DefaultAllowedTokens directly would
		// alias the shared (sr-owned) slice across every store, leaking
		// mutations and tripping the readonly-taint gate on later writes.
		err := stakerStore.SetAllowedTokens(0, rlm, sr.DefaultAllowedTokens())
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasIncentiveCounterStoreKey() {
		err := stakerStore.SetIncentiveCounter(0, rlm, sr.NewCounter())
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasTokenSpecificMinimumRewardsStoreKey() {
		err := stakerStore.SetTokenSpecificMinimumRewards(0, rlm, make(map[string]int64))
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasUnstakingFeeStoreKey() {
		err := stakerStore.SetUnstakingFee(0, rlm, defaultUnstakingFee)
		if err != nil {
			return err
		}
	}

	pendingProtocolFees := make(map[string]int64)
	if stakerStore.HasPendingProtocolFeesStoreKey() {
		pendingProtocolFees = stakerStore.GetPendingProtocolFees()
	}
	if err := stakerStore.SetPendingProtocolFees(0, rlm, pendingProtocolFees); err != nil {
		return err
	}

	if !stakerStore.HasUnstakedPositionsStoreKey() {
		err := stakerStore.SetUnstakedPositions(0, rlm, sr.NewBPTreeN(16))
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasUncollectedIncentiveCountsStoreKey() {
		err := stakerStore.SetUncollectedIncentiveCounts(0, rlm, sr.NewBPTreeN(16))
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasWarmupTemplateStoreKey() {
		err := stakerStore.SetWarmupTemplate(0, rlm, sr.DefaultWarmupTemplate())
		if err != nil {
			return err
		}
	}

	initializedPoolTier, initializedPools, initialPoolTierTime, initialTierRewards := initializePoolTier(stakerStore)

	previousRealm := rlm.Previous()
	emitSetPoolTier(
		previousRealm.Address().String(),
		previousRealm.PkgPath(),
		emission.DefaultInitialPoolTierPath,
		uint64(Tier1),
		initializedPoolTier.currentEmission,
		initialTierRewards,
		initializedPoolTier.counts,
		initialPoolTierTime,
	)

	if !stakerStore.HasPoolsStoreKey() {
		err := stakerStore.SetPools(0, rlm, initializedPools.tree)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasPoolTierMembershipsStoreKey() {
		err := stakerStore.SetPoolTierMemberships(0, rlm, initializedPoolTier.membership)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasPoolTierRatioStoreKey() {
		err := stakerStore.SetPoolTierRatio(0, rlm, initializedPoolTier.tierRatio)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasPoolTierCountsStoreKey() {
		err := stakerStore.SetPoolTierCounts(0, rlm, initializedPoolTier.counts)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasPoolTierLastRewardCacheTimestampStoreKey() {
		err := stakerStore.SetPoolTierLastRewardCacheTimestamp(0, rlm, initializedPoolTier.lastRewardCacheTimestamp)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasPoolTierCurrentEmissionStoreKey() {
		err := stakerStore.SetPoolTierCurrentEmission(0, rlm, initializedPoolTier.currentEmission)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasPoolTierGetEmissionStoreKey() {
		getEmissionFn := func() (int64, error) {
			return emissionAccessor.GetStakerEmissionAmountPerSecond()
		}

		err := stakerStore.SetPoolTierGetEmission(0, rlm, getEmissionFn)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasPoolTierGetHalvingBlocksInRangeStoreKey() {
		getHalvingBlocksInRangeFn := func(start, end int64) ([]int64, []int64, error) {
			return emissionAccessor.GetStakerEmissionAmountPerSecondInRange(start, end)
		}

		err := stakerStore.SetPoolTierGetHalvingBlocksInRange(0, rlm, getHalvingBlocksInRangeFn)
		if err != nil {
			return err
		}
	}

	if !stakerStore.HasCurrentSwapBatchStoreKey() {
		err := stakerStore.SetCurrentSwapBatch(0, rlm, nil)
		if err != nil {
			return err
		}
	}

	return nil
}

// initializePoolTier seeds the staker's pool tiering state on first init.
//
// The default pool is the canonical WUGNOT:GNS:3000 pool, sourced from the
// emission realm's DefaultInitialPoolTierPath constant so that the staker's
// tier-1 base pool is guaranteed to match the pool emission distributes to.
//
// When SetDistributionStartTime executes, emission distributes to this default
// pool and the staker uses the same path as the base tier-1 pool for reward
// accrual. Keeping both sides on emission's single constant structurally
// enforces that invariant and removes any risk of the two realms drifting
// apart on the canonical default pool identity.
func initializePoolTier(stakerStore sr.IStakerStore) (*PoolTier, *Pools, int64, map[uint64]int64) {
	pools := NewPools()
	currentTime := time.Now().Unix()

	pl := NewPools().GetPoolOrNil(emission.DefaultInitialPoolTierPath)
	if pl == nil {
		pl = sr.NewPool(emission.DefaultInitialPoolTierPath, currentTime)
		pools.set(emission.DefaultInitialPoolTierPath, pl)
	}

	poolTier := NewPoolTier(
		pools,
		currentTime,
		emission.DefaultInitialPoolTierPath,
		emission.GetStakerEmissionAmountPerSecond,
		emission.GetStakerEmissionAmountPerSecondInRange,
	)

	return poolTier, pools, currentTime, poolTier.computeTierRewards(poolTier.currentEmission)
}

instance.gno

package staker

import sr "gno.land/r/gnoswap/staker"

type stakerV1 struct {
	store            sr.IStakerStore
	poolAccessor     sr.PoolAccessor
	emissionAccessor sr.EmissionAccessor
	nftAccessor      sr.NFTAccessor
}

func (s *stakerV1) getPools() *Pools {
	return &Pools{
		tree: s.store.GetPools(),
	}
}

func (s *stakerV1) getPoolTier() *PoolTier {
	return NewPoolTierBy(
		s.store.GetPoolTierMemberships(),
		s.store.GetPoolTierRatio(),
		s.store.GetPoolTierCounts(),
		s.store.GetPoolTierLastRewardCacheTimestamp(),
		s.store.GetPoolTierCurrentEmission(),
		s.store.GetPoolTierGetEmission(),
		s.store.GetPoolTierGetHalvingBlocksInRange(),
	)
}

func (s *stakerV1) updatePoolTier(_ int, rlm realm, poolTier *PoolTier) {
	err := s.store.SetPoolTierMemberships(0, rlm, poolTier.membership)
	if err != nil {
		panic(err)
	}

	err = s.store.SetPoolTierRatio(0, rlm, poolTier.tierRatio)
	if err != nil {
		panic(err)
	}

	err = s.store.SetPoolTierCounts(0, rlm, poolTier.counts)
	if err != nil {
		panic(err)
	}

	err = s.store.SetPoolTierLastRewardCacheTimestamp(0, rlm, poolTier.lastRewardCacheTimestamp)
	if err != nil {
		panic(err)
	}

	err = s.store.SetPoolTierCurrentEmission(0, rlm, poolTier.currentEmission)
	if err != nil {
		panic(err)
	}

	err = s.store.SetPoolTierGetEmission(0, rlm, poolTier.getEmission)
	if err != nil {
		panic(err)
	}

	err = s.store.SetPoolTierGetHalvingBlocksInRange(0, rlm, poolTier.getHalvingBlocksInRange)
	if err != nil {
		panic(err)
	}
}

func (s *stakerV1) getDeposits() *Deposits {
	return &Deposits{
		tree: s.store.GetDeposits(),
	}
}

func (s *stakerV1) getExternalIncentives() *ExternalIncentives {
	return &ExternalIncentives{
		tree: s.store.GetExternalIncentives(),
	}
}

func (s *stakerV1) getDepositResolver(lpTokenId uint64) (*DepositResolver, error) {
	deposit, err := s.getDeposit(lpTokenId)
	if err != nil {
		return nil, err
	}
	return NewDepositResolver(deposit), nil
}

// NewStakerV1 constructs a version 1 staker implementation backed by the supplied accessors.
//
// Parameters:
//   - stakerStore: Persistent storage accessor for pools, deposits, incentives, tier state, and reward bookkeeping.
//   - poolAccessor: Accessor for pool state used while updating and resolving staked positions.
//   - emissionAccessor: Accessor for GNS emission data used to calculate rewards.
//   - nftAccessor: Accessor for the position NFT ownership and token operations.
//
// Returns:
//   - staker: New stakerV1 implementation wired to the supplied store and accessors.
func NewStakerV1(stakerStore sr.IStakerStore, poolAccessor sr.PoolAccessor, emissionAccessor sr.EmissionAccessor, nftAccessor sr.NFTAccessor) *stakerV1 {
	return &stakerV1{
		store:            stakerStore,
		poolAccessor:     poolAccessor,
		emissionAccessor: emissionAccessor,
		nftAccessor:      nftAccessor,
	}
}

manage_pool_tier_and_warmup.gno

package staker

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

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

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/halt/v1"
	sr "gno.land/r/gnoswap/staker"
)

const (
	NOT_EMISSION_TARGET_TIER uint64 = 0
)

// SetPoolTier assigns a tier level to a pool for internal GNS emission rewards.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - poolPath: Existing pool path whose internal GNS emission tier is being assigned.
//   - tier: Emission tier to assign; valid values are below AllTierCount, including 0 for no emission target.
func (s *stakerV1) SetPoolTier(_ int, rlm realm, poolPath string, tier uint64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	assertIsPoolExists(s, poolPath)
	assertIsValidPoolTier(tier)

	// If the tier is already set, do nothing
	poolTier := s.getPoolTier()
	previousTier := poolTier.CurrentTier(poolPath)
	if previousTier == tier {
		return
	}

	currentTime := time.Now().Unix()
	rewardPerSecond, tierRewards := s.setPoolTier(0, rlm, poolPath, tier, currentTime)

	previousRealm := rlm.Previous()
	emitSetPoolTier(
		previousRealm.Address().String(),
		previousRealm.PkgPath(),
		poolPath,
		tier,
		rewardPerSecond,
		tierRewards,
		poolTier.counts,
		currentTime,
	)
}

// ChangePoolTier modifies the tier level of an existing pool.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - poolPath: Existing pool path whose emission tier is being changed.
//   - tier: Replacement emission tier; values at or above AllTierCount are rejected.
func (s *stakerV1) ChangePoolTier(_ int, rlm realm, poolPath string, tier uint64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	assertIsPoolExists(s, poolPath)
	assertIsValidPoolTier(tier)

	poolTier := s.getPoolTier()

	// If the tier is already set, do nothing
	previousTier := poolTier.CurrentTier(poolPath)
	if previousTier == tier {
		return
	}

	currentTime := time.Now().Unix()
	previousTier, newTier, rewardPerSecond, tierRewards := s.changePoolTier(0, rlm, poolPath, tier, currentTime)

	chain.Emit(
		"ChangePoolTier",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"poolPath", poolPath,
		"prevTier", utils.FormatUint(previousTier),
		"newTier", utils.FormatUint(newTier),
		"rewardPerSecond", utils.FormatInt(rewardPerSecond),
		"tier1RewardPerSecond", utils.FormatInt(tierRewards[Tier1]),
		"tier2RewardPerSecond", utils.FormatInt(tierRewards[Tier2]),
		"tier3RewardPerSecond", utils.FormatInt(tierRewards[Tier3]),
		"tier1Count", utils.FormatUint(poolTier.counts[Tier1]),
		"tier2Count", utils.FormatUint(poolTier.counts[Tier2]),
		"tier3Count", utils.FormatUint(poolTier.counts[Tier3]),
		"currentTime", utils.FormatInt(currentTime),
		"currentHeight", utils.FormatInt(runtime.ChainHeight()),
	)
}

// RemovePoolTier removes a pool from internal GNS emission rewards.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - poolPath: Existing pool path to remove from the emission-tier accounting.
func (s *stakerV1) RemovePoolTier(_ int, rlm realm, poolPath string) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	assertIsPoolExists(s, poolPath)

	poolTier := s.getPoolTier()

	// If the tier is already set, do nothing
	previousTier := poolTier.CurrentTier(poolPath)
	if previousTier == NOT_EMISSION_TARGET_TIER {
		return
	}

	currentTime := time.Now().Unix()
	rewardPerSecond, tierRewards := s.removePoolTier(0, rlm, poolPath, currentTime)

	chain.Emit(
		"RemovePoolTier",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"poolPath", poolPath,
		"rewardPerSecond", utils.FormatInt(rewardPerSecond),
		"tier1RewardPerSecond", utils.FormatInt(tierRewards[Tier1]),
		"tier2RewardPerSecond", utils.FormatInt(tierRewards[Tier2]),
		"tier3RewardPerSecond", utils.FormatInt(tierRewards[Tier3]),
		"tier1Count", utils.FormatUint(poolTier.counts[Tier1]),
		"tier2Count", utils.FormatUint(poolTier.counts[Tier2]),
		"tier3Count", utils.FormatUint(poolTier.counts[Tier3]),
		"currentTime", utils.FormatInt(currentTime),
		"currentHeight", utils.FormatInt(runtime.ChainHeight()),
	)
}

// SetWarmUp configures the duration for the warm-up tier selected by its fixed ratio.
// Finite tiers are capped at 365 days; the final 100% tier must remain math.MaxInt64.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - pct: Warm-up tier percentage selecting one of the configured 30%, 50%, 70%, or 100% templates.
//   - timeDuration: Warm-up duration in seconds; finite tiers are capped at 365 days while the 100% tier uses the maximum int64 duration.
func (s *stakerV1) SetWarmUp(_ int, rlm realm, pct, timeDuration int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	s.setWarmUp(0, rlm, pct, timeDuration)

	chain.Emit(
		"SetWarmUp",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"pct", utils.FormatInt(pct),
		"timeDuration", utils.FormatInt(timeDuration),
	)
}

// setPoolTier internally sets the pool tier.
func (s *stakerV1) setPoolTier(_ int, rlm realm, poolPath string, tier uint64, currentTime int64) (int64, map[uint64]int64) {
	s.emissionAccessor.MintAndDistributeGns(0, rlm)

	pool := s.getPools().GetPoolOrNil(poolPath)
	if pool == nil {
		pool = sr.NewPool(poolPath, currentTime)
		s.getPools().set(poolPath, pool)
	}
	poolTier := s.getPoolTier()
	tierRewards := poolTier.changeTier(currentTime, s.getPools(), poolPath, tier)

	s.updatePoolTier(0, rlm, poolTier)

	return poolTier.currentEmission, tierRewards
}

// changePoolTier internally changes the pool tier and returns old and new tiers.
func (s *stakerV1) changePoolTier(_ int, rlm realm, poolPath string, tier uint64, currentTime int64) (uint64, uint64, int64, map[uint64]int64) {
	s.emissionAccessor.MintAndDistributeGns(0, rlm)
	poolTier := s.getPoolTier()
	previousTier := poolTier.CurrentTier(poolPath)

	tierRewards := poolTier.changeTier(currentTime, s.getPools(), poolPath, tier)

	s.updatePoolTier(0, rlm, poolTier)

	return previousTier, tier, poolTier.currentEmission, tierRewards
}

// removePoolTier internally removes the pool from tier system.
func (s *stakerV1) removePoolTier(_ int, rlm realm, poolPath string, currentTime int64) (int64, map[uint64]int64) {
	s.emissionAccessor.MintAndDistributeGns(0, rlm)

	poolTier := s.getPoolTier()
	tierRewards := poolTier.changeTier(currentTime, s.getPools(), poolPath, NOT_EMISSION_TARGET_TIER)
	s.updatePoolTier(0, rlm, poolTier)

	return poolTier.currentEmission, tierRewards
}

// setWarmUp internally sets the warm-up parameters.
func (s *stakerV1) setWarmUp(_ int, rlm realm, pct, timeDuration int64) {
	s.emissionAccessor.MintAndDistributeGns(0, rlm)

	warmupTemplate := s.store.GetWarmupTemplate()
	warmupTemplate = modifyWarmup(warmupTemplate, pctToIndex(pct), timeDuration)

	err := s.store.SetWarmupTemplate(0, rlm, warmupTemplate)
	if err != nil {
		panic(err)
	}
}

// pctToIndex converts percentage to warmup index.
func pctToIndex(pct int64) int {
	switch pct {
	case 30:
		return 0
	case 50:
		return 1
	case 70:
		return 2
	case 100:
		return 3
	default:
		panic("staker.gno__pctToIndex() || pct is not valid")
	}
}

protocol_fee_unstaking.gno

package staker

import (
	"chain"
	"errors"

	"gno.land/p/gnoswap/gnsmath/v1"
	prbac "gno.land/p/gnoswap/rbac/v1"
	"gno.land/p/gnoswap/utils/v1"
	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/halt/v1"

	pf "gno.land/r/gnoswap/protocol_fee"
)

// GetUnstakingFee returns the current unstaking fee rate in basis points.
//
// Returns:
//   - uint64: Current fee rate in basis points; 100 basis points equals 1%.
func (s *stakerV1) GetUnstakingFee() uint64 { return s.store.GetUnstakingFee() }

// handleStakingRewardFee calculates and applies the unstaking fee.
func (s *stakerV1) handleStakingRewardFee(
	_ int,
	rlm realm,
	tokenPath string,
	amount int64,
	internal bool,
	unstakingFee uint64,
) (int64, int64, error) {
	if internal {
		tokenPath = GNS_TOKEN_KEY
	}

	if unstakingFee == 0 {
		s.settleProtocolFee(0, rlm, tokenPath, 0)
		return amount, 0, nil
	}

	// Do not change the order of the operation.
	feeAmount := gnsmath.SafeMulDivInt64(amount, gnsmath.SafeUint64ToInt64(unstakingFee), 10000)
	if feeAmount < 0 {
		return 0, 0, errors.New("fee amount cannot be negative")
	}

	if feeAmount == 0 {
		s.settleProtocolFee(0, rlm, tokenPath, 0)
		return amount, 0, nil
	}

	s.settleProtocolFee(0, rlm, tokenPath, feeAmount)

	return gnsmath.SafeSubInt64(amount, feeAmount), feeAmount, nil
}

// GetPendingProtocolFees returns pending protocol fee amounts keyed by reward-token path.
//
// Returns:
//   - map[string]int64: Pending fee amount per token path awaiting a later settlement.
func (s *stakerV1) GetPendingProtocolFees() map[string]int64 {
	return s.store.GetPendingProtocolFees()
}

func (s *stakerV1) addPendingProtocolFee(_ int, rlm realm, tokenPath string, amount int64) {
	if amount <= 0 {
		return
	}

	pendingAmount := gnsmath.SafeAddInt64(s.store.GetPendingProtocolFee(tokenPath), amount)
	if err := s.store.SetPendingProtocolFee(0, rlm, tokenPath, pendingAmount); err != nil {
		panic(err)
	}
}

// settleProtocolFee forwards amount, plus anything already pending for tokenPath, to
// the protocol fee realm. When collection is halted or the transfer fails, the amount
// is recorded as pending instead and settled by a later call for the same token, which
// every fee path makes even when the fee is zero.
//
// Only tokenPath is touched, so an unrelated token can never block settlement. The
// pending entry is written only when the fee cannot be forwarded, so the common path
// performs no store write at all.
func (s *stakerV1) settleProtocolFee(_ int, rlm realm, tokenPath string, amount int64) {
	if halt.IsHaltedProtocolFee() {
		s.addPendingProtocolFee(0, rlm, tokenPath, amount)
		return
	}

	pendingAmount := s.store.GetPendingProtocolFee(tokenPath)
	totalAmount := gnsmath.SafeAddInt64(pendingAmount, amount)

	if totalAmount > 0 {
		protocolFeeAddr := access.MustGetAddress(prbac.ROLE_PROTOCOL_FEE.String())
		common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddr, totalAmount)

		// AddToProtocolFee only reports an error for a halted realm, which is handled
		// above. The branch keeps the amount pending should that ever change, and
		// withdraws the approval so no unspent allowance outlives the call.
		if err := pf.AddToProtocolFee(cross(rlm), tokenPath, totalAmount); err != nil {
			common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddr, 0)
			s.addPendingProtocolFee(0, rlm, tokenPath, amount)
			return
		}
	}

	if err := s.store.RemovePendingProtocolFee(0, rlm, tokenPath); err != nil {
		panic(err)
	}
}

// SetUnStakingFee sets the unstaking fee rate in basis points.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Internal call discriminator; callers pass 0.
//   - rlm: Propagated realm context; it must be current before changing the stored fee.
//   - fee: New unstaking fee rate in basis points, validated against the configured maximum.
func (s *stakerV1) SetUnStakingFee(_ int, rlm realm, fee uint64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

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

	assertIsValidFeeRate(fee)

	prevUnStakingFee := s.GetUnstakingFee()

	err := s.setUnStakingFee(0, rlm, fee)
	if err != nil {
		panic(err)
	}

	chain.Emit(
		"SetUnStakingFee",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"prevFee", utils.FormatUint(prevUnStakingFee),
		"newFee", utils.FormatUint(fee),
	)
}

// setUnStakingFee internally updates the unstaking fee.
func (s *stakerV1) setUnStakingFee(_ int, rlm realm, fee uint64) error {
	return s.store.SetUnstakingFee(0, rlm, fee)
}

render.gno

package staker

import (
	"chain"
	"math"
	"strings"

	"gno.land/p/moul/md/v0"
	"gno.land/p/moul/mdtable/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

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

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

	tierCounts := s.store.GetPoolTierCounts()
	tierRatio := s.store.GetPoolTierRatio()
	implementation := stakerRoot.GetImplementationPackagePath()

	out := md.H1("Gnoswap Staker")
	out += md.Paragraph(
		"All GNS amounts use the token's six-decimal base units. External reward amounts use\n" +
			"the reward token's own base units.",
	)

	out += md.H2("Implementation")
	implementationTable := mdtable.Table{
		Headers: []string{"Field", "Value"},
		Rows: [][]string{
			{"Realm address", md.InlineCode(chain.PackageAddress("gno.land/r/gnoswap/staker").String())},
			{"Active implementation", md.Link(implementation, strings.TrimPrefix(implementation, "gno.land"))},
			{"Staker operations halted", ufmt.Sprintf("%t", halt.IsHaltedStaker())},
		},
	}
	out += implementationTable.String()

	out += md.H2("Accounting and configuration")
	accountingTable := mdtable.Table{
		Headers: []string{"Field", "Value"},
		Rows: [][]string{
			{"Stored pool records", ufmt.Sprintf("%d", s.store.GetPools().Size())},
			{"Active staked-position records", ufmt.Sprintf("%d", s.store.GetDeposits().Size())},
			{"Stored external incentive records", ufmt.Sprintf("%d", s.store.GetExternalIncentives().Size())},
			{"Unstaked checkpoint records", ufmt.Sprintf("%d", s.store.GetUnstakedPositions().Size())},
			{"Cumulative GNS emission sent (base units; 6 decimals)", ufmt.Sprintf("%d", s.store.GetTotalEmissionSent())},
			{"Cached GNS emission rate (base units/second; 6 decimals)", ufmt.Sprintf("%d", s.store.GetPoolTierCurrentEmission())},
			{"Required GNS deposit (GNS base units; 6 decimals)", ufmt.Sprintf("%d", s.store.GetDepositGnsAmount())},
			{"Default minimum external incentive reward (reward-token base units)", ufmt.Sprintf("%d", s.store.GetMinimumRewardAmount())},
			{"Tier pool counts (tier 1 / tier 2 / tier 3)", ufmt.Sprintf("%d / %d / %d", tierCounts[1], tierCounts[2], tierCounts[3])},
			{"Tier reward split (tier 1 / tier 2 / tier 3; percent)", ufmt.Sprintf("%d%% / %d%% / %d%%", tierRatio.Tier1, tierRatio.Tier2, tierRatio.Tier3)},
			{"Unstaking fee", ufmt.Sprintf("%d bps (maximum %d bps)", s.store.GetUnstakingFee(), maxUnstakingFee)},
			{"Allowed external incentive durations", "90 / 180 / 365 days"},
		},
	}
	out += accountingTable.String()

	out += md.H2("Warmup stages")
	warmupTable := mdtable.Table{
		Headers: []string{"Reward share", "Duration per stage"},
	}
	for _, warmup := range s.store.GetWarmupTemplate() {
		duration := ufmt.Sprintf("%d seconds", warmup.TimeDuration)
		if warmup.TimeDuration == math.MaxInt64 {
			duration = "unbounded"
		}
		warmupTable.Append([]string{
			ufmt.Sprintf("%d%%", warmup.WarmupRatio),
			duration,
		})
	}
	out += warmupTable.String()

	return out
}

reward_calculation_incentives.gno

package staker

import (
	"gno.land/p/gnoswap/gnsmath/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	bptree "gno.land/p/nt/bptree/v0"

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

type IncentivesResolver struct {
	*sr.Incentives
}

// NewIncentivesResolver wraps the persisted external-incentive state for lookup and mutation.
//
// Parameters:
//   - incentives: External incentive state containing the incentive tree and unclaimable periods.
//
// Returns:
//   - resolver: Resolver backed by incentives.
func NewIncentivesResolver(incentives *sr.Incentives) *IncentivesResolver {
	return &IncentivesResolver{
		Incentives: incentives,
	}
}

// Get resolves an external incentive by its identifier.
//
// Parameters:
//   - incentiveId: External incentive identifier used as the tree key.
//
// Returns:
//   - incentive: Stored external incentive pointer when the ID exists; nil when it is absent.
//   - found: True when incentiveId is present in the tree; false otherwise.
func (self *IncentivesResolver) Get(incentiveId string) (*sr.ExternalIncentive, bool) {
	return retrieveIncentive(self.IncentiveTrees(), incentiveId)
}

// GetIncentiveResolver resolves an incentive ID to its field accessor.
//
// Parameters:
//   - incentiveId: External incentive identifier to resolve.
//
// Returns:
//   - resolver: Resolver for the stored incentive when found; nil when incentiveId is absent.
//   - found: True when incentiveId resolves to a stored incentive; false otherwise.
func (self *IncentivesResolver) GetIncentiveResolver(incentiveId string) (*ExternalIncentiveResolver, bool) {
	if incentive, ok := self.Get(incentiveId); ok {
		return NewExternalIncentiveResolver(incentive), true
	}
	return nil, false
}

func retrieveIncentive(tree *bptree.BPTree, id string) (*sr.ExternalIncentive, bool) {
	value := tree.Get(id)
	if value == nil {
		return nil, false
	}
	v, ok := value.(*sr.ExternalIncentive)
	if !ok {
		panic("failed to cast value to *sr.ExternalIncentive")
	}
	return v, true
}

// Create a new external incentive
// Panics if the incentive already exists.
func (self *IncentivesResolver) create(incentive *sr.ExternalIncentive) {
	self.Incentives.SetIncentive(incentive.IncentiveId(), incentive)
	self.Incentives.AddIncentiveByStartTime(incentive.StartTimestamp(), incentive.IncentiveId())
}

// update updates an existing incentive with new information
func (self *IncentivesResolver) update(incentive *sr.ExternalIncentive) {
	self.Incentives.SetIncentive(incentive.IncentiveId(), incentive)
}

// remove drops an incentive from both the incentive tree and the start-time
// discovery index. It is only valid for an incentive that has not started: no
// deposit can reference it yet, so nothing is left pointing at a missing record.
func (self *IncentivesResolver) remove(incentive *sr.ExternalIncentive) {
	self.Incentives.RemoveIncentive(incentive.IncentiveId())
	self.Incentives.RemoveIncentiveByStartTime(incentive.StartTimestamp(), incentive.IncentiveId())
}

// starts incentive unclaimable period for this pool
func (self *IncentivesResolver) startUnclaimablePeriod(startTimestamp int64) {
	self.Incentives.SetUnclaimablePeriod(startTimestamp, int64(0))
}

// ends incentive unclaimable period for this pool
// ignores if currently not in unclaimable period
func (self *IncentivesResolver) endUnclaimablePeriod(endTimestamp int64) {
	startTimestamp := int64(0)
	self.UnclaimablePeriods().ReverseIterate(0, endTimestamp, func(key int64, value any) bool {
		v, ok := value.(int64)
		if !ok {
			panic("failed to cast value to int64")
		}
		if v != 0 {
			// Already ended, no need to update
			// keeping startTimestamp as 0 to indicate this
			return true
		}
		startTimestamp = key
		return true
	})

	if startTimestamp == 0 {
		// No ongoing unclaimable period found
		return
	}

	if startTimestamp == endTimestamp {
		self.Incentives.RemoveUnclaimablePeriod(startTimestamp)
	} else {
		self.Incentives.SetUnclaimablePeriod(startTimestamp, endTimestamp)
	}

	// Accumulate the just-closed period into every active incentive
	self.accumulateUnclaimableSeconds(startTimestamp, endTimestamp)
}

// accumulateUnclaimableSeconds adds the unclaimable duration between
// startTimestamp and endTimestamp to every non-refunded incentive whose window
// overlaps the period. The accumulator is updated in place on the stored
// incentive pointers, so no tree write is required here.
func (self *IncentivesResolver) accumulateUnclaimableSeconds(startTimestamp, endTimestamp int64) {
	self.Incentives.IterateIncentives(func(_ string, incentive *sr.ExternalIncentive) bool {
		if incentive.Refunded() {
			return false
		}

		duration := calculateUnClaimableDuration(
			startTimestamp,
			endTimestamp,
			incentive.StartTimestamp(),
			incentive.EndTimestamp(),
		)
		if duration > 0 {
			incentive.SetUnclaimableSeconds(gnsmath.SafeAddInt64(incentive.UnclaimableSeconds(), duration))
		}
		return false
	})
}

// calculate unclaimable reward from the per-incentive unclaimable seconds
// accumulator instead of scanning the unbounded unclaimable periods tree.
func (self *IncentivesResolver) calculateUnclaimableReward(incentiveId string) int64 {
	incentive, ok := self.Get(incentiveId)
	if !ok {
		return 0
	}

	// The accumulator holds the duration of every closed unclaimable period
	// that overlaps the incentive window.
	timeDiff := incentive.UnclaimableSeconds()

	// Ongoing unclaimable periods (end == 0) are not yet accumulated because
	// their end is unknown. They are resolved here by treating them as
	// extending to the incentive end. Unclaimable periods never overlap and
	// are recorded in ascending order, so an ongoing period is always the
	// most recently started one and therefore the highest key in the tree.
	// ReverseIterate visits the highest key first, so each scan below finds
	// the only ongoing period that can affect the reward (if any) on its
	// first visit and stops - the scan is bounded regardless of how many
	// periods exist in the tree.
	//
	// Tail 1: the ongoing period that started before the incentive window
	// (e.g. the initial pool-creation period). If the highest period starting
	// before the window is already closed, no ongoing period can overlap the
	// incentive start and there is nothing to add.
	self.UnclaimablePeriods().ReverseIterate(0, incentive.StartTimestamp()-1, func(startTimestamp int64, value any) bool {
		endTimestamp, ok := value.(int64)
		if !ok {
			panic("failed to cast value to int64")
		}
		if endTimestamp != 0 {
			// Already closed - the duration is already accumulated in
			// UnclaimableSeconds(), and being the highest key it is also the
			// latest period, so no ongoing period can exist below it.
			return true
		}

		timeDiff = gnsmath.SafeAddInt64(timeDiff, calculateUnClaimableDuration(
			startTimestamp,
			incentive.EndTimestamp(),
			incentive.StartTimestamp(),
			incentive.EndTimestamp(),
		))
		return true
	})

	// Tail 2: the ongoing period that started within the incentive window.
	// The upper bound is endTime-1 to mirror the Iterate(start, end)
	// half-open range, which excludes a period starting exactly at endTime
	// (e.g. the initial pool-creation period that coincides with endTime).
	self.UnclaimablePeriods().ReverseIterate(incentive.StartTimestamp(), incentive.EndTimestamp()-1, func(startTimestamp int64, value any) bool {
		endTimestamp, ok := value.(int64)
		if !ok {
			panic("failed to cast value to int64")
		}
		if endTimestamp != 0 {
			// Already closed - the duration is already accumulated in
			// UnclaimableSeconds(), and being the highest key it is also the
			// latest period, so no ongoing period can exist below it.
			return true
		}

		timeDiff = gnsmath.SafeAddInt64(timeDiff, calculateUnClaimableDuration(
			startTimestamp,
			incentive.EndTimestamp(),
			incentive.StartTimestamp(),
			incentive.EndTimestamp(),
		))
		return true
	})

	// rewardPerSecondX128 = rps << 128, so dividing by q128 here recovers the
	// floor of (timeDiff * rps) without the truncation that an int64 rps would
	// have introduced at incentive-creation time.
	unclaimable := u256.MulDiv(
		u256.NewUintFromInt64(timeDiff),
		incentive.RewardPerSecondX128(),
		q128,
	)
	return gnsmath.SafeConvertToInt64(unclaimable)
}

// calculateUnClaimableDuration calculates the duration of overlap between an unclaimable period and incentive period
func calculateUnClaimableDuration(unclaimableStart, unclaimableEnd, incentiveStartTimestamp, incentiveEndTimestamp int64) int64 {
	// Use later timestamp between unclaimable start and incentive start
	startTime := unclaimableStart
	if startTime < incentiveStartTimestamp {
		startTime = incentiveStartTimestamp
	}

	// Use earlier timestamp between unclaimable end and incentive end
	endTime := unclaimableEnd
	if endTime > incentiveEndTimestamp {
		endTime = incentiveEndTimestamp
	}

	// Return 0 if no overlap
	if endTime < startTime {
		return 0
	}

	// Calculate overlap duration
	return gnsmath.SafeSubInt64(endTime, startTime)
}

reward_calculation_pool.gno

package staker

import (
	"errors"
	"math"
	"time"

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

	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	sr "gno.land/r/gnoswap/staker"
)

var q128 = u256.MustFromDecimal("340282366920938463463374607431768211456")

// Pools represents the global pool storage
type Pools struct {
	tree *bptree.BPTree // string poolPath -> pool
}

// NewPools creates an empty resolver for global pool storage.
//
// Returns:
//   - pools: Pools resolver backed by a new B+ tree keyed by pool path.
func NewPools() *Pools {
	return &Pools{
		tree: sr.NewBPTreeN(16),
	}
}

// Get returns the pool stored under the given pool path.
//
// Parameters:
//   - poolPath: Pool path used as the storage key.
//
// Returns:
//   - pool: Stored pool pointer when poolPath exists; nil when absent.
//   - found: True when poolPath resolves to a pool; false when no entry exists.
func (self *Pools) Get(poolPath string) (*sr.Pool, bool) {
	v := self.tree.Get(poolPath)
	if v == nil {
		return nil, false
	}
	p, ok := v.(*sr.Pool)
	if !ok {
		panic(ufmt.Sprintf("failed to cast v to *Pool: %T", v))
	}
	return p, true
}

// GetPoolOrNil returns the pool for the given pool path, or nil when it does not exist.
//
// Parameters:
//   - poolPath: Pool path used as the storage key.
//
// Returns:
//   - pool: Stored pool pointer, or nil when poolPath is absent.
func (self *Pools) GetPoolOrNil(poolPath string) *sr.Pool {
	pool, ok := self.Get(poolPath)
	if !ok {
		return nil
	}
	return pool
}

// set sets the pool for the given poolPath.
func (self *Pools) set(poolPath string, pool *sr.Pool) {
	self.tree.Set(poolPath, pool)
}

// Has reports whether a pool exists for the given pool path.
//
// Parameters:
//   - poolPath: Pool path used as the storage key.
//
// Returns:
//   - exists: True when poolPath is present in the pool tree; false otherwise.
func (self *Pools) Has(poolPath string) bool {
	return self.tree.Has(poolPath)
}

// IterateAll visits every stored pool until the callback requests that traversal stop.
//
// Parameters:
//   - fn: Callback receiving each pool path and pool pointer; return true to stop iteration, false to continue.
func (self *Pools) IterateAll(fn func(key string, pool *sr.Pool) bool) {
	self.tree.Iterate("", "", func(key string, value any) bool {
		p, ok := value.(*sr.Pool)
		if !ok {
			panic(ufmt.Sprintf("failed to cast value to *Pool: %T", value))
		}
		return fn(key, p)
	})
}

type PoolResolver struct {
	*sr.Pool

	// exit is set only when collecting an exit checkpoint, and overrides the pool reads that
	// would otherwise come from state the position no longer takes part in.
	exit *sr.UnstakedPosition
}

// IncentivesResolver returns a resolver over the pool's external-incentive state.
//
// Returns:
//   - resolver: Incentives resolver backed by this pool's incentive tree and unclaimable periods.
func (self *PoolResolver) IncentivesResolver() *IncentivesResolver {
	return NewIncentivesResolver(self.Incentives())
}

// CurrentGlobalRewardRatioAccumulation returns the latest stored global reward-ratio checkpoint in the [0, currentTime] range.
//
// Parameters:
//   - currentTime: Unix timestamp bounding the checkpoint lookup.
//
// Returns:
//   - time: Timestamp of the latest stored checkpoint at or before currentTime; zero when no checkpoint exists.
//   - acc: Decimal-encoded Q128-scaled global reward-ratio accumulation at time.
func (self *PoolResolver) CurrentGlobalRewardRatioAccumulation(currentTime int64) (time int64, acc string) {
	acc = "0"

	self.GlobalRewardRatioAccumulation().ReverseIterate(0, currentTime, func(key int64, value any) bool {
		time = key

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

		acc = valueStr

		return true
	})

	return time, acc
}

// CurrentTick returns the latest historical tick in the [0, currentTime] range.
//
// Parameters:
//   - currentTime: Unix timestamp bounding the historical-tick lookup.
//
// Returns:
//   - tick: Latest historical tick at or before currentTime; an exit resolver uses its pinned exit tick at or after exit time.
func (self *PoolResolver) CurrentTick(currentTime int64) (tick int32) {
	if self.exit != nil && currentTime >= self.exit.ExitTime() {
		return self.exit.ExitTick()
	}

	self.HistoricalTick().ReverseIterate(0, currentTime, func(key int64, value any) bool {
		res, ok := value.(int32)
		if !ok {
			panic(ufmt.Sprintf("failed to cast value to int32: %T", value))
		}
		tick = res
		return true
	})
	return tick
}

// CurrentStakedLiquidity returns the latest staked-liquidity checkpoint in the [0, currentTime] range.
//
// Parameters:
//   - currentTime: Unix timestamp bounding the staked-liquidity lookup.
//
// Returns:
//   - liquidity: Uint256 staked liquidity effective at or before currentTime; zero when no checkpoint exists.
func (self *PoolResolver) CurrentStakedLiquidity(currentTime int64) (liquidity *u256.Uint) {
	liquidity = u256.Zero()

	self.StakedLiquidity().ReverseIterate(0, currentTime, func(key int64, value any) bool {
		res, ok := value.(*u256.Uint)
		if !ok {
			panic(ufmt.Sprintf("failed to cast value to *u256.Uint: %T", value))
		}
		liquidity = res
		return true
	})
	return liquidity
}

// GetOrNewTick returns the existing tick or a new zero-valued tick.
//
// Parameters:
//   - tickId: Boundary tick identifier to retrieve or initialize.
//
// Returns:
//   - tick: Existing stored tick, or a zero-valued tick with tickId when no entry exists.
//
// Substituting a zero-valued tick on a read is safe because ticks are pruned
// only when their staked gross liquidity reaches zero, in the same call that
// removes the last deposit referencing them.
func (self *PoolResolver) GetOrNewTick(tickId int32) *sr.Tick {
	if self.exit != nil {
		if lowerTick := self.exit.LowerTick(); lowerTick != nil && lowerTick.Id() == tickId {
			return lowerTick
		}
		if upperTick := self.exit.UpperTick(); upperTick != nil && upperTick.Id() == tickId {
			return upperTick
		}
	}

	tick := self.Ticks().Get(tickId)
	if tick == nil {
		return sr.NewTick(tickId)
	}
	return tick
}

// initializeNewTickOutsideAccumulation seeds a just-created boundary tick so
// that below(tick) == globalAccumulation holds, keeping the three branches of
// outsideAccumulationAt returns a boundary tick's outside accumulation at currentTime.
//
// An exit checkpoint answers for its own exit timestamp from the value pinned when it was
// written: a tick cross later in the same block overwrites the entry at that timestamp, while
// earlier entries can no longer change.
func (self *PoolResolver) outsideAccumulationAt(tickId int32, currentTime int64) *u256.Uint {
	if self.exit != nil && currentTime == self.exit.ExitTime() {
		switch tickId {
		case self.exit.Deposit().TickLower():
			return u256.MustFromDecimal(self.exit.LowerOutsideAcc())
		case self.exit.Deposit().TickUpper():
			return u256.MustFromDecimal(self.exit.UpperOutsideAcc())
		}
	}

	return NewTickResolver(self.GetOrNewTick(tickId)).CurrentOutsideAccumulation(currentTime)
}

// CalculateRawRewardForPosition consistent.
func (self *PoolResolver) initializeNewTickOutsideAccumulation(currentTime int64, currentTick, tickId int32, tick *sr.Tick) {
	if tickId > currentTick {
		return
	}

	globalAcc, _ := self.globalRewardRatioAccumulationAt(currentTime)
	tick.SetOutsideAccumulationAt(currentTime, globalAcc)
}

// IsExternallyIncentivizedPool reports whether the pool has any external incentive that has not ended,
// including incentives whose start time is still in the future.
//
// Returns:
//   - incentivized: True when at least one non-ended external incentive is indexed for the pool; false when all are ended or none exist.
func (self *PoolResolver) IsExternallyIncentivizedPool() bool {
	currentTime := time.Now().Unix()
	hasIncentive := false
	// With a maximum duration of 365 days, older starts have already ended.
	// Keep future starts eligible and retain historical records for reward claims.
	self.Incentives().IterateIncentiveIdsByTime(stakeScanLowerBound(currentTime), math.MaxInt64, func(incentiveId string) bool {
		incentive, ok := self.Incentives().Incentive(incentiveId)
		if !ok {
			panic("incentive missing from pool start-time index")
		}

		resolver := NewExternalIncentiveResolver(incentive)
		if !resolver.IsEnded(currentTime) {
			hasIncentive = true
			return true
		}

		return false
	})

	return hasIncentive
}

// CurrentReward returns the latest cached per-pool reward rate in the [0, currentTime] range.
//
// Parameters:
//   - currentTime: Unix timestamp bounding the reward-cache lookup.
//
// Returns:
//   - reward: Latest cached GNS reward rate at or before currentTime, in units per second; zero when no checkpoint exists.
func (self *PoolResolver) CurrentReward(currentTime int64) (reward int64) {
	self.RewardCache().ReverseIterate(0, currentTime, func(key int64, value any) bool {
		res, ok := value.(int64)
		if !ok {
			panic(ufmt.Sprintf("failed to cast value to int64: %T", value))
		}
		reward = res
		return true
	})
	return reward
}

func (self *PoolResolver) isChangedTick(currentTime int64, currentTick int32) bool {
	if self.HistoricalTick().Size() == 0 {
		return true
	}

	previousTick := self.CurrentTick(currentTime)

	return previousTick != currentTick
}

// cacheReward sets the current reward for the pool
// If the pool is in unclaimable period, it will end the unclaimable period, updates the reward, and start the unclaimable period again.
//
// Important behavior for initial tier assignment:
// - When a pool first receives a tier, oldTierReward=0 and currentTierReward>0
// - If the pool has zero liquidity at this point, startUnclaimablePeriod() is called
// - This ensures unclaimable period tracking begins from the moment rewards start emitting
func (self *PoolResolver) cacheReward(currentTime int64, currentTierReward int64) {
	oldTierReward := self.CurrentReward(currentTime)
	if oldTierReward == currentTierReward {
		return
	}

	isInUnclaimable := self.CurrentStakedLiquidity(currentTime).IsZero()
	if isInUnclaimable {
		// End any existing unclaimable period
		// Note: If lastUnclaimableTime is 0 (not yet tracking), this is a no-op
		self.endUnclaimablePeriod(currentTime)
	}

	self.Pool.SetRewardCacheAt(currentTime, currentTierReward)

	if isInUnclaimable {
		// Start/restart unclaimable period tracking
		// This handles initial tier assignment when lastUnclaimableTime is 0
		self.startUnclaimablePeriod(currentTime)
	}
}

func (self *PoolResolver) calculateGlobalRewardRatioAccumulation(currentTime int64, currentStakedLiquidity *u256.Uint) *u256.Uint {
	oldAccTime, oldAccStr := self.CurrentGlobalRewardRatioAccumulation(currentTime)
	timeDiff := gnsmath.SafeSubInt64(currentTime, oldAccTime)
	if timeDiff == 0 {
		return u256.MustFromDecimal(oldAccStr)
	}
	if timeDiff < 0 {
		panic("time cannot go backwards")
	}

	if currentStakedLiquidity.IsZero() {
		return u256.MustFromDecimal(oldAccStr)
	}

	oldAcc := u256.MustFromDecimal(oldAccStr)
	acc := u256.MulDiv(
		u256.NewUintFromInt64(timeDiff),
		q128,
		currentStakedLiquidity,
	)
	return u256.Zero().Add(oldAcc, acc)
}

// globalRewardRatioAccumulationAt returns the global reward ratio accumulation *at* currentTime.
//
// CurrentGlobalRewardRatioAccumulation returns the latest stored checkpoint (<= currentTime), which is
// only equal to the accumulation at currentTime when a checkpoint was written at that very timestamp.
// Checkpoints are written exclusively by modifyDeposit (staked liquidity changes), so on any other path
// the stored value lags by (currentTime - lastCheckpointTime) * q128 / stakedLiquidity.
//
// Reward calculation never has this problem because it derives the accumulation on demand
// (CalculateRawRewardForPosition). Event emission must do the same, otherwise off-chain indexers that
// treat the emitted accumulator as authoritative at the event timestamp silently drop that interval.
func (self *PoolResolver) globalRewardRatioAccumulationAt(currentTime int64) (*u256.Uint, *u256.Uint) {
	stakedLiquidity := self.CurrentStakedLiquidity(currentTime)
	accumulation := self.calculateGlobalRewardRatioAccumulation(currentTime, stakedLiquidity)

	return accumulation, stakedLiquidity
}

// updateGlobalRewardRatioAccumulation updates the global reward ratio accumulation and returns the new accumulation.
func (self *PoolResolver) updateGlobalRewardRatioAccumulation(currentTime int64, currentStakedLiquidity *u256.Uint) *u256.Uint {
	newAcc := self.calculateGlobalRewardRatioAccumulation(currentTime, currentStakedLiquidity)

	// Persist as string to reduce stored object complexity.
	self.Pool.SetGlobalRewardRatioAccumulationAt(currentTime, newAcc.ToString())
	return newAcc
}

// RewardStateOf initializes a new RewardState for the given deposit, allocating reward and penalty slots for each warmup.
//
// Parameters:
//   - deposit: Staked deposit whose pool, liquidity, and warmup schedule will be resolved.
//
// Returns:
//   - state: RewardState initialized with zeroed per-warmup reward and penalty accumulators.
func (self *PoolResolver) RewardStateOf(deposit *sr.Deposit) *RewardState {
	warmups := len(deposit.Warmups())
	result := &RewardState{
		pool:      self,
		deposit:   NewDepositResolver(deposit),
		rewards:   make([]int64, warmups),
		penalties: make([]int64, warmups),
	}

	return result
}

// reset clears cached rewards/penalties so a RewardState can be reused without re-allocating.
func (self *RewardState) reset() {
	for i := range self.rewards {
		self.rewards[i] = 0
		self.penalties[i] = 0
	}
}

// NewPoolResolver wraps a pool's persisted reward, liquidity, tick, and incentive state for calculations.
//
// Parameters:
//   - pool: Pool state to resolve.
//
// Returns:
//   - resolver: Pool resolver backed by pool.
func NewPoolResolver(pool *sr.Pool) *PoolResolver {
	return &PoolResolver{
		Pool: pool,
	}
}

// newPoolResolverWithExit builds a resolver that reads the pool through an exit checkpoint.
func newPoolResolverWithExit(pool *sr.Pool, exit *sr.UnstakedPosition) *PoolResolver {
	return &PoolResolver{
		Pool: pool,
		exit: exit,
	}
}

// RewardState is a struct for storing the intermediate state for reward calculation.
type RewardState struct {
	pool    *PoolResolver
	deposit *DepositResolver

	// accumulated rewards for each warmup
	rewards   []int64
	penalties []int64
}

// calculateInternalReward computes the position's per-warmup rewards and penalties from a pre-resolved
// per-second reward-rate schedule (see PoolResolver.resolveInternalRewardSegments).
//
// It is pure: it neither queries pool tier/emission state nor writes any state, so the read-only view
// path and the collect path use it identically. Each segment [start, end) is applied at its constant
// per-second rate; rewardPerWarmup is a no-op for empty segments (start == end).
func (self *RewardState) calculateInternalReward(segments []internalRewardSegment) ([]int64, []int64) {
	for _, seg := range segments {
		if err := self.rewardPerWarmup(seg.start, seg.end, seg.rewardPerSecond); err != nil {
			panic(err)
		}
	}

	self.applyWarmup()

	return self.rewards, self.penalties
}

// updateExternalReward updates the external reward for the deposit.
// It updates the last collect time for the external reward for the given incentive ID.
// It returns an error if the current time is less than the last collect time for the external reward for the given incentive ID.
func (self *RewardState) updateExternalReward(startTime, endTime int64, incentive *sr.ExternalIncentive) error {
	lastCollectTime := self.deposit.ExternalRewardLastCollectTime(incentive.IncentiveId())
	if startTime < lastCollectTime {
		// This must not happen, but adding some guards just in case.
		startTime = lastCollectTime
	}

	ictvStart := incentive.StartTimestamp()
	if endTime < ictvStart {
		return nil // Not started yet
	}

	if startTime < ictvStart {
		startTime = ictvStart
	}

	ictvEnd := incentive.EndTimestamp()
	if endTime > ictvEnd {
		endTime = ictvEnd
	}

	if startTime > ictvEnd {
		return nil // Already ended
	}

	return self.rewardPerWarmupX128(startTime, endTime, incentive.RewardPerSecondX128())
}

// calculateCollectableExternalReward calculates the calculated external reward for the deposit.
// It calls updateExternalReward for the incentive period, applies warmup and returns the rewards and penalties.
// used for reward calculation for a calculatable incentive
func (self *RewardState) calculateCollectableExternalReward(startTime, endTime int64, incentive *sr.ExternalIncentive) int64 {
	err := self.updateExternalReward(startTime, endTime, incentive)
	if err != nil {
		panic(err)
	}

	currentReward := u256.Zero()

	for i := range self.rewards {
		currentReward = currentReward.Add(currentReward, u256.NewUintFromInt64(self.rewards[i]))
	}

	return gnsmath.SafeConvertToInt64(currentReward)
}

// calculateExternalReward calculates the external reward for the deposit.
// It calls rewardPerWarmup for startTime to endTime(clamped to the incentive period), applies warmup and returns the rewards and penalties.
func (self *RewardState) calculateExternalReward(startTime, endTime int64, incentive *sr.ExternalIncentive) ([]int64, []int64) {
	err := self.updateExternalReward(startTime, endTime, incentive)
	if err != nil {
		panic(err)
	}

	// apply warmup to collect rewards
	self.applyWarmup()

	return self.rewards, self.penalties
}

// applyWarmup applies the warmup to the rewards and calculate penalties.
func (self *RewardState) applyWarmup() {
	for i, warmup := range self.deposit.Warmups() {
		warmupReward := self.rewards[i]

		// calculate warmup reward applying warmup ratio
		self.rewards[i] = gnsmath.SafeMulDivInt64(warmupReward, int64(warmup.WarmupRatio), 100)

		// warmup penalty is the difference between the warmup reward and the warmup reward applying warmup ratio
		self.penalties[i] = gnsmath.SafeSubInt64(warmupReward, self.rewards[i])
	}
}

// rewardPerWarmup calculates the reward for each warmup, adds to the RewardState's rewards array.
// Used by the internal reward path where rewardPerSecond is an int64 emission rate.
func (self *RewardState) rewardPerWarmup(startTime, endTime int64, rewardPerSecond int64) error {
	// Return early if startTime equals endTime to avoid unnecessary computation
	if startTime == endTime {
		return nil
	}

	startTick := self.pool.CurrentTick(startTime)
	startRaw := self.pool.CalculateRawRewardForPosition(startTime, startTick, self.deposit.Deposit)

	for i, warmup := range self.deposit.Warmups() {
		if startTime >= warmup.NextWarmupTime {
			// passed the warmup
			continue
		}

		if endTime < warmup.NextWarmupTime {
			endTick := self.pool.CurrentTick(endTime)
			endRaw := self.pool.CalculateRawRewardForPosition(endTime, endTick, self.deposit.Deposit)
			// Modular by design: boundary ticks created at different times give a
			// wrapped base, so the borrow is expected and the wrapped difference
			// is the true accumulation (Uniswap V3 subtracts unchecked too).
			rewardAcc := u256.Zero().Sub(endRaw, startRaw)

			rewardAcc, overflow := u256.Zero().MulOverflow(rewardAcc, self.deposit.Liquidity())
			if overflow {
				panic(errors.New(errOverflow))
			}

			rewardAcc = u256.MulDiv(rewardAcc, u256.NewUintFromInt64(rewardPerSecond), q128)
			self.rewards[i] = gnsmath.SafeAddInt64(self.rewards[i], gnsmath.SafeConvertToInt64(rewardAcc))

			break
		}

		endTick := self.pool.CurrentTick(warmup.NextWarmupTime)
		endRaw := self.pool.CalculateRawRewardForPosition(warmup.NextWarmupTime, endTick, self.deposit.Deposit)
		// See the note above: the subtraction is intentionally modular.
		rewardAcc := u256.Zero().Sub(endRaw, startRaw)

		rewardAcc, overflow := u256.Zero().MulOverflow(rewardAcc, self.deposit.Liquidity())
		if overflow {
			panic(errors.New(errOverflow))
		}

		rewardAcc = u256.MulDiv(rewardAcc, u256.NewUintFromInt64(rewardPerSecond), q128)
		self.rewards[i] = gnsmath.SafeAddInt64(self.rewards[i], gnsmath.SafeConvertToInt64(rewardAcc))

		startTime = warmup.NextWarmupTime
		startTick = endTick
		startRaw = endRaw
	}

	return nil
}

// rewardPerWarmupX128 calculates the reward for each warmup using a Q128-scaled
// per-second rate. Used by the external incentive path; the per-second rate is
// stored as `(rewardAmount << 128) / duration` in ExternalIncentive, so an
// extra `>> 128` is needed after the standard `MulDiv(rewardAcc, rps, q128)`
// to materialize the integer result.
func (self *RewardState) rewardPerWarmupX128(startTime, endTime int64, rewardPerSecondX128 *u256.Uint) error {
	if startTime == endTime {
		return nil
	}

	startTick := self.pool.CurrentTick(startTime)
	startRaw := self.pool.CalculateRawRewardForPosition(startTime, startTick, self.deposit.Deposit)

	for i, warmup := range self.deposit.Warmups() {
		if startTime >= warmup.NextWarmupTime {
			continue
		}

		if endTime < warmup.NextWarmupTime {
			endTick := self.pool.CurrentTick(endTime)
			endRaw := self.pool.CalculateRawRewardForPosition(endTime, endTick, self.deposit.Deposit)
			// Modular by design: boundary ticks created at different times give a
			// wrapped base, so the borrow is expected and the wrapped difference
			// is the true accumulation (Uniswap V3 subtracts unchecked too).
			rewardAcc := u256.Zero().Sub(endRaw, startRaw)

			rewardAcc, overflow := u256.Zero().MulOverflow(rewardAcc, self.deposit.Liquidity())
			if overflow {
				panic(errors.New(errOverflow))
			}

			rewardAcc = u256.MulDiv(rewardAcc, rewardPerSecondX128, q128)
			rewardAcc = u256.Zero().Rsh(rewardAcc, 128)
			self.rewards[i] = gnsmath.SafeAddInt64(self.rewards[i], gnsmath.SafeConvertToInt64(rewardAcc))

			break
		}

		endTick := self.pool.CurrentTick(warmup.NextWarmupTime)
		endRaw := self.pool.CalculateRawRewardForPosition(warmup.NextWarmupTime, endTick, self.deposit.Deposit)
		// See the note above: the subtraction is intentionally modular.
		rewardAcc := u256.Zero().Sub(endRaw, startRaw)

		rewardAcc, overflow := u256.Zero().MulOverflow(rewardAcc, self.deposit.Liquidity())
		if overflow {
			panic(errors.New(errOverflow))
		}

		rewardAcc = u256.MulDiv(rewardAcc, rewardPerSecondX128, q128)
		rewardAcc = u256.Zero().Rsh(rewardAcc, 128)
		self.rewards[i] = gnsmath.SafeAddInt64(self.rewards[i], gnsmath.SafeConvertToInt64(rewardAcc))

		startTime = warmup.NextWarmupTime
		startTick = endTick
		startRaw = endRaw
	}

	return nil
}

// modifyDeposit updates the pool's staked liquidity and returns the new staked liquidity.
// updates when there is a change in the staked liquidity(tick cross, stake, unstake)
func (self *PoolResolver) modifyDeposit(delta *i256.Int, currentTime int64, nextTick int32) *u256.Uint {
	// update staker side pool info
	lastStakedLiquidity := self.CurrentStakedLiquidity(currentTime)
	deltaApplied := gnsmath.LiquidityMathAddDelta(lastStakedLiquidity, delta)
	result := self.updateGlobalRewardRatioAccumulation(currentTime, lastStakedLiquidity)

	// historical tick does NOT actually reflect the tick at the timestamp, but it provides correct ordering for the staked positions
	// because TickCrossHook is assured to be called for the staked-initialized ticks
	if self.isChangedTick(currentTime, nextTick) {
		self.Pool.SetHistoricalTickAt(currentTime, nextTick)
	}

	switch deltaApplied.Sign() {
	case -1:
		panic("stakedLiquidity is less than 0, should not happen")
	case 0:
		if lastStakedLiquidity.Sign() == 1 {
			// StakedLiquidity moved from positive to zero, start unclaimable period
			self.startUnclaimablePeriod(currentTime)
			self.IncentivesResolver().startUnclaimablePeriod(currentTime)
		}
	case 1:
		if lastStakedLiquidity.Sign() == 0 {
			// StakedLiquidity moved from zero to positive, end unclaimable period
			self.endUnclaimablePeriod(currentTime)
			self.IncentivesResolver().endUnclaimablePeriod(currentTime)
		}
	}

	// Only append a staked-liquidity entry when the value actually changes (e.g. a tick cross whose
	// net delta is zero leaves it unchanged). Unlike the global reward ratio accumulation, this tree
	// carries no time-checkpoint semantics: it is read purely as a point-in-time value via
	// CurrentStakedLiquidity (latest entry <= t), so omitting a duplicate-valued entry preserves
	// behavior while keeping this append-only tree from growing on no-op updates.
	if !lastStakedLiquidity.Eq(deltaApplied) {
		self.Pool.SetStakedLiquidityAt(currentTime, deltaApplied)
	}

	return result
}

// startUnclaimablePeriod starts the unclaimable period.
func (self *PoolResolver) startUnclaimablePeriod(currentTime int64) {
	if self.LastUnclaimableTime() == 0 {
		// We set only if it's the first time entering(0 indicates not set yet)
		self.SetLastUnclaimableTime(currentTime)
	}
}

// endUnclaimablePeriod ends the unclaimable period.
// Accumulates to unclaimableAcc and resets lastUnclaimableTime to 0.
func (self *PoolResolver) endUnclaimablePeriod(currentTime int64) {
	if self.LastUnclaimableTime() == 0 {
		// lastUnclaimableTime = 0 means tracking hasn't started yet
		// This is normal during initial pool creation or when called from cacheReward
		// during tier assignment with zero liquidity
		return
	}

	self.updateUnclaimableAccumulateRewards(currentTime)
	self.SetLastUnclaimableTime(0)
}

// updateUnclaimableAccumulateRewards ends the unclaimable period.
// Accumulates to unclaimableAcc and resets lastUnclaimableTime to 0.
func (self *PoolResolver) updateUnclaimableAccumulateRewards(currentTime int64) {
	if self.LastUnclaimableTime() >= currentTime {
		return
	}

	unclaimableDuration := gnsmath.SafeSubInt64(currentTime, self.LastUnclaimableTime())
	currentUnclaimableReward := gnsmath.SafeMulInt64(unclaimableDuration, self.CurrentReward(self.LastUnclaimableTime()))
	self.SetUnclaimableAcc(gnsmath.SafeAddInt64(self.UnclaimableAcc(), currentUnclaimableReward))
}

// processUnclaimableReward processes the unclaimable reward and returns the accumulated reward.
// It resets unclaimableAcc to 0 and properly manages lastUnclaimableTime based on pool state.
func (self *PoolResolver) processUnclaimableReward(endTime int64) int64 {
	// Check current pool liquidity state
	isZeroStakedLiquidity := self.CurrentStakedLiquidity(endTime).IsZero()

	if self.LastUnclaimableTime() > 0 {
		// We have an ongoing unclaimable period tracking
		self.updateUnclaimableAccumulateRewards(endTime)

		if isZeroStakedLiquidity {
			// Still unclaimable - accumulate rewards up to endTime
			// Update tracking time for continuing unclaimable period
			self.SetLastUnclaimableTime(endTime)
		} else {
			// Was unclaimable but now has liquidity - properly end the period
			self.SetLastUnclaimableTime(0)
		}
	} else {
		if isZeroStakedLiquidity {
			// No previous tracking but currently unclaimable - this shouldn't normally happen
			// as startUnclaimablePeriod should have been called when liquidity reached 0
			// Start tracking from now
			self.SetLastUnclaimableTime(endTime)
		}
	}

	// Return and reset accumulated unclaimable rewards
	internalUnClaimable := self.UnclaimableAcc()
	self.SetUnclaimableAcc(0)
	return internalUnClaimable
}

// CalculateRawRewardForPosition calculates the theoretical reward accumulator for a position without debt or warmup adjustments.
//
// Parameters:
//   - currentTime: Unix timestamp at which pool reward state is evaluated.
//   - currentTick: Pool tick used to determine whether the position is below, inside, or above its range.
//   - deposit: Position deposit whose liquidity and boundary ticks determine the raw reward.
//
// Returns:
//   - reward: Q128-scaled raw reward accumulator for the position; debt, warmup ratios, and fees are not applied.
func (self *PoolResolver) CalculateRawRewardForPosition(currentTime int64, currentTick int32, deposit *sr.Deposit) *u256.Uint {
	var rewardAcc *u256.Uint

	globalAcc := self.calculateGlobalRewardRatioAccumulation(currentTime, self.CurrentStakedLiquidity(currentTime))

	lowerAcc := self.outsideAccumulationAt(deposit.TickLower(), currentTime)
	upperAcc := self.outsideAccumulationAt(deposit.TickUpper(), currentTime)
	if currentTick < deposit.TickLower() {
		rewardAcc = u256.Zero().Sub(lowerAcc, upperAcc)
	} else if currentTick >= deposit.TickUpper() {
		rewardAcc = u256.Zero().Sub(upperAcc, lowerAcc)
	} else {
		rewardAcc = u256.Zero().Sub(globalAcc, lowerAcc)
		rewardAcc = rewardAcc.Sub(rewardAcc, upperAcc)
	}

	return rewardAcc
}

reward_calculation_pool_tier.gno

package staker

import (
	"errors"

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

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

const (
	AllTierCount = 4 // 0, 1, 2, 3
	Tier1        = 1
	Tier2        = 2
	Tier3        = 3
)

// TierRatioFromCounts calculates the ratio distribution for each tier based on pool counts.
//
// Parameters:
// - tier1Count (uint64): Number of pools in tier 1.
// - tier2Count (uint64): Number of pools in tier 2.
// - tier3Count (uint64): Number of pools in tier 3.
//
// Returns:
// - TierRatio: The ratio distribution across tier 1, 2, and 3, scaled up by 100.
func TierRatioFromCounts(tier1Count, tier2Count, tier3Count uint64) sr.TierRatio {
	// tier1 always exists.
	//
	// TierRatio is declared in /r/gnoswap/staker; constructing it via a
	// composite literal here (/r/gnoswap/staker/v1) trips the construction-time
	// check ("cannot allocate ... in realm ..."). Route through the domain
	// constructor sr.NewTierRatio so allocation happens in the declaring realm.
	if tier2Count == 0 && tier3Count == 0 {
		return sr.NewTierRatio(100, 0, 0)
	}
	if tier2Count == 0 {
		return sr.NewTierRatio(80, 0, 20)
	}
	if tier3Count == 0 {
		return sr.NewTierRatio(70, 30, 0)
	}
	return sr.NewTierRatio(50, 30, 20)
}

// PoolTier manages pool counts, ratios, and rewards for different tiers.
//
// Fields:
// - membership: Tracks which tier a pool belongs to (poolPath -> blockNumber -> tier).
//
// Methods:
// - CurrentCount: Returns the current count of pools in a tier at a specific timestamp.
// - CurrentRatio: Returns the current ratio for a tier at a specific timestamp.
// - CurrentTier: Returns the tier of a specific pool at a given timestamp.
// - CurrentReward: Retrieves the reward for a tier at a specific timestamp.
// - changeTier: Updates the tier of a pool and recalculates ratios.
type PoolTier struct {
	membership *bptree.BPTree // poolPath -> tier(1, 2, 3)

	tierRatio sr.TierRatio

	counts [AllTierCount]uint64

	lastRewardCacheTimestamp int64

	currentEmission int64

	// returns current emission.
	getEmission func() (int64, error)
	// Returns a list of halving timestamps and their emission amounts within the interval [start, end) in ascending order.
	// The first return value is a list of timestamps where halving occurs.
	// The second return value is a list of emission amounts corresponding to each halving timestamp.
	getHalvingBlocksInRange func(start, end int64) ([]int64, []int64, error)
}

// NewPoolTier creates a new PoolTier instance with single initial 1 tier pool.
//
// Parameters:
// - pools: The pool collection.
// - currentTime: The current block time.
// - initialPoolPath: The path of the initial pool.
// - getEmission: A function that returns the current emission to the staker contract.
// - getHalvingBlocksInRange: A function that returns a list of halving blocks within the interval [start, end) in ascending order.
//
// Returns:
// - *PoolTier: The new PoolTier instance.
func NewPoolTier(pools *Pools, currentTime int64, initialPoolPath string, getEmission func() (int64, error), getHalvingBlocksInRange func(start, end int64) ([]int64, []int64, error)) *PoolTier {
	currentEmission, err := getEmission()
	if err != nil {
		panic(err)
	}

	result := &PoolTier{
		membership:               sr.NewBPTreeN(16),
		tierRatio:                TierRatioFromCounts(1, 0, 0),
		lastRewardCacheTimestamp: gnsmath.SafeAddInt64(currentTime, 1),
		getEmission:              getEmission,
		getHalvingBlocksInRange:  getHalvingBlocksInRange,
		currentEmission:          currentEmission,
	}

	pools.set(initialPoolPath, sr.NewPool(initialPoolPath, currentTime+1))
	result.changeTier(currentTime+1, pools, initialPoolPath, 1)
	return result
}

// NewPoolTierBy reconstructs a PoolTier from persisted membership, ratios, counts, and callbacks.
//
// Parameters:
//   - membership: Persisted pool-path-to-tier mapping.
//   - tierRatio: Persisted reward-share ratio for each tier.
//   - counts: Persisted number of pools in each tier index.
//   - lastRewardCacheTimestamp: Timestamp through which reward caches have been materialized.
//   - currentEmission: Emission rate currently used for reward accrual.
//   - getEmission: Callback returning the current staker emission rate or an error.
//   - getHalvingBlocksInRange: Callback returning halving timestamps and corresponding emissions in [start, end).
//
// Returns:
//   - *PoolTier: Reconstructed tier manager using the supplied persisted state and callbacks.
func NewPoolTierBy(
	membership *bptree.BPTree,
	tierRatio sr.TierRatio,
	counts [AllTierCount]uint64,
	lastRewardCacheTimestamp int64,
	currentEmission int64,
	getEmission func() (int64, error),
	getHalvingBlocksInRange func(start, end int64) ([]int64, []int64, error),
) *PoolTier {
	return &PoolTier{
		membership:               membership,
		tierRatio:                tierRatio,
		counts:                   counts,
		lastRewardCacheTimestamp: lastRewardCacheTimestamp,
		getEmission:              getEmission,
		getHalvingBlocksInRange:  getHalvingBlocksInRange,
		currentEmission:          currentEmission,
	}
}

// CurrentReward returns the current per-pool reward for the given tier.
// Parameters:
//   - tier: Tier number whose current emission reward is requested.
//
// Returns:
//   - int64: Current per-pool reward for the tier, or zero when the calculation cannot produce a reward.
//   - error: Error from emission lookup, invalid-tier lookup, or reward calculation; nil when the reward calculation succeeds.
func (self *PoolTier) CurrentReward(tier uint64) (int64, error) {
	currentEmission, err := self.getEmission()
	if err != nil {
		return 0, err
	}
	tierRatio, err := self.tierRatio.Get(tier)
	if err != nil {
		return 0, makeErrorWithDetails(errInvalidPoolTier, err.Error())
	}

	tierRatioInt64 := int64(tierRatio)
	count := int64(self.CurrentCount(tier))

	return calculatePoolReward(currentEmission, tierRatioInt64, count)
}

// CurrentCount returns the current count of pools in the given tier.
// Parameters:
//   - tier: Tier index whose pool count is requested; out-of-range indexes return zero.
//
// Returns:
//   - int: Number of pools currently assigned to tier.
func (self *PoolTier) CurrentCount(tier uint64) int {
	if tier >= AllTierCount {
		return 0
	}
	return int(self.counts[tier])
}

// CurrentAllTierCounts returns the current count of pools in each tier.
// Returns:
//   - []uint64: Snapshot of pool counts for tier indexes 0 through AllTierCount-1.
func (self *PoolTier) CurrentAllTierCounts() []uint64 {
	out := make([]uint64, AllTierCount)
	copy(out, self.counts[:])
	return out // returning snapshot
}

// CurrentTier returns the tier of the given pool.
// Parameters:
//   - poolPath: Pool path whose current tier membership is requested.
//
// Returns:
//   - tier: Current tier number, or zero when the pool is not in the membership tree.
func (self *PoolTier) CurrentTier(poolPath string) (tier uint64) {
	if tierI := self.membership.Get(poolPath); tierI == nil {
		return 0
	} else {
		var ok bool
		tier, ok = tierI.(uint64)
		if !ok {
			panic("failed to cast tier to uint64")
		}
		return tier
	}
}

// changeTier updates the tier of a pool, recalculates ratios, and applies
// updated per-pool reward to each of the pools.
func (self *PoolTier) changeTier(currentTime int64, pools *Pools, poolPath string, nextTier uint64) map[uint64]int64 {
	currentTier := self.CurrentTier(poolPath)
	if currentTier == nextTier {
		// no change, return
		return make(map[uint64]int64)
	}
	assertTier1HasSparePool(currentTier, self.counts[Tier1])

	self.cacheReward(currentTime, pools)

	// decrement count from current tier if it exists
	if currentTier > 0 {
		if self.counts[currentTier] == 0 {
			panic("counts underflow: removing from empty tier")
		}
		self.counts[currentTier]--
	}

	if nextTier == 0 {
		// removed from the tier
		self.membership.Remove(poolPath)
		pool, ok := pools.Get(poolPath)
		if !ok {
			panic("changeTier: pool not found")
		}
		poolResolver := NewPoolResolver(pool)
		// prevent new rewards from accumulating after tier removal
		poolResolver.cacheReward(currentTime, 0)
	} else {
		// handle all move/add operations
		self.membership.Set(poolPath, nextTier)
		self.counts[nextTier]++
	}

	self.tierRatio = TierRatioFromCounts(self.counts[Tier1], self.counts[Tier2], self.counts[Tier3])
	currentEmission, err := self.getEmission()
	if err != nil {
		panic(err)
	}
	tierRewards := self.computeTierRewards(currentEmission)

	// Cache updated reward for each tiered pool
	self.membership.Iterate("", "", func(key string, value any) bool {
		pool, ok := pools.Get(key)
		if !ok {
			panic("changeTier: pool not found")
		}
		tier, ok := value.(uint64)
		if !ok {
			panic("failed to cast value to uint64")
		}

		poolReward, ok := tierRewards[tier]
		if !ok {
			return false // Skip if no pools in tier
		}

		poolResolver := NewPoolResolver(pool)
		poolResolver.cacheReward(currentTime, poolReward)
		return false
	})

	self.currentEmission = currentEmission

	return tierRewards
}

// cacheReward MUST be called before calculating any position reward.
// cacheReward updates the reward cache for each pool, accounting for any halving events
// that occurred between the last cached timestamp and the current timestamp.
// Note: Block height is used only for event tracking purposes.
// tierContextOf returns the pool's tier and the ratio/count setting its current emission rate.
func (self *PoolTier) tierContextOf(poolPath string) (uint64, uint64, uint64, error) {
	tier := self.CurrentTier(poolPath)
	if tier == 0 || tier >= AllTierCount {
		return tier, 0, 0, nil
	}

	ratio, err := self.tierRatio.Get(tier)
	if err != nil {
		return 0, 0, 0, makeErrorWithDetails(errInvalidPoolTier, err.Error())
	}

	return tier, ratio, self.counts[tier], nil
}

func (self *PoolTier) cacheReward(currentTimestamp int64, pools *Pools) {
	lastTimestamp := self.lastRewardCacheTimestamp

	if currentTimestamp <= lastTimestamp {
		// no need to check
		return
	}

	// find halving blocks in range
	halvingTimestamps, halvingEmissions, err := self.getHalvingBlocksInRange(lastTimestamp, currentTimestamp)
	if err != nil {
		panic(err)
	}

	if len(halvingTimestamps) == 0 {
		self.applyCacheToAllPools(pools, currentTimestamp, self.currentEmission)
		self.lastRewardCacheTimestamp = currentTimestamp
		return
	}

	for i, hvTimestamp := range halvingTimestamps {
		emission := halvingEmissions[i]
		// caching: [lastTimestamp, hvTimestamp)
		self.applyCacheToAllPools(pools, hvTimestamp, emission)

		// halve emissions when halvingBlock is reached
		self.currentEmission = emission
	}

	// remaining range [lastTimestamp, currentTimestamp)
	self.applyCacheToAllPools(pools, currentTimestamp, self.currentEmission)

	self.lastRewardCacheTimestamp = currentTimestamp
}

// cacheRewardForPool caches internal reward/accumulators for a single pool only.
// This avoids iterating all tiered pools on every position reward calculation.
func (self *PoolTier) cacheRewardForPool(currentTimestamp int64, pools *Pools, poolPath string) {
	pool, ok := pools.Get(poolPath)
	if !ok {
		return
	}

	tierNum := self.CurrentTier(poolPath)
	// Pool not in the internal-incentive system.
	if tierNum == 0 {
		return
	}

	// Find the latest reward cache timestamp for this pool.
	lastTimestamp := int64(0)
	hasLast := false
	pool.RewardCache().ReverseIterate(0, currentTimestamp, func(key int64, _ any) bool {
		lastTimestamp = key
		hasLast = true
		return true
	})

	if !hasLast {
		// Fallback to global tier cache cursor.
		lastTimestamp = self.lastRewardCacheTimestamp
	}

	if currentTimestamp <= lastTimestamp {
		return
	}

	// Determine halving boundaries since the pool's last cached reward timestamp.
	halvingTimestamps, halvingEmissions, err := self.getHalvingBlocksInRange(lastTimestamp, currentTimestamp)
	if err != nil {
		panic(err)
	}
	poolResolver := NewPoolResolver(pool)

	if len(halvingTimestamps) == 0 {
		// No emission change within the range => use the live emission.
		currentEmission, err := self.getEmission()
		if err != nil {
			panic(err)
		}
		self.applyCacheToPool(poolResolver, tierNum, currentTimestamp, currentEmission)
		return
	}

	// Apply caching at every halving boundary.
	currentEmission := int64(0)
	for i, hvTimestamp := range halvingTimestamps {
		currentEmission = halvingEmissions[i]
		self.applyCacheToPool(poolResolver, tierNum, hvTimestamp, currentEmission)
	}

	// Remaining range [lastTimestamp, currentTimestamp).
	self.applyCacheToPool(poolResolver, tierNum, currentTimestamp, currentEmission)
}

// applyCacheToPool applies the cached reward to all tiered pool.
func (self *PoolTier) applyCacheToPool(poolResolver *PoolResolver, tierNum uint64, currentTimestamp, emissionInThisInterval int64) {
	tierRewards := self.computeTierRewards(emissionInThisInterval)
	poolReward, ok := tierRewards[tierNum]
	if !ok {
		return
	}

	poolResolver.cacheReward(currentTimestamp, poolReward)
}

// applyCacheToAllPools applies the cached reward to all tiered pools.
func (self *PoolTier) applyCacheToAllPools(pools *Pools, currentTimestamp, emissionInThisInterval int64) {
	// calculate denominator and number of pools in each tier
	counts := self.CurrentAllTierCounts()
	tierRewards := self.computeTierRewards(emissionInThisInterval)

	// apply cache to all pools
	self.membership.Iterate("", "", func(key string, value any) bool {
		pool, ok := pools.Get(key)
		if !ok {
			return false
		}

		tierNum, ok := value.(uint64)
		if !ok {
			panic("failed to cast value to uint64")
		}
		// Skip pools with tier 0 (removed from tier system)
		if tierNum == 0 {
			return false
		}

		if counts[tierNum] == 0 {
			return false // Skip if no pools in tier
		}

		poolReward, ok := tierRewards[tierNum]
		if !ok {
			return false
		}

		// accumulate the reward for the interval (startBlock to endBlock) in the Pool
		poolResolver := NewPoolResolver(pool)
		poolResolver.cacheReward(currentTimestamp, poolReward)
		return false
	})
}

// IsInternallyIncentivizedPool returns true if the pool is in a tier.
// Parameters:
//   - poolPath: Pool path whose membership is checked.
//
// Returns:
//   - bool: True when poolPath belongs to a nonzero internal-incentive tier; false otherwise.
func (self *PoolTier) IsInternallyIncentivizedPool(poolPath string) bool {
	return self.CurrentTier(poolPath) > 0
}

// calculatePoolReward calculates the reward for a pool based on the emission, tier ratio, and tier count.
//
// Parameters:
// - emission: The emission for the pool.
// - tierRatio: The tier ratio for the pool.
// - tierCount: The tier count for the pool.
//
// Returns:
// - int64: The reward for the pool.
// - error: An invalid calculation input.
func calculatePoolReward(emission int64, tierRatio int64, tierCount int64) (int64, error) {
	if emission < 0 || tierRatio < 0 || tierCount < 0 {
		return 0, errors.New(errCalculationError)
	}

	if emission == 0 || tierRatio == 0 || tierCount == 0 {
		return 0, nil
	}

	tierReward := gnsmath.SafeMulDivInt64(emission, tierRatio, 100)

	return tierReward / tierCount, nil
}

// computeTierRewards caches per-tier pool rewards to avoid recalculating for each pool iteration.
func (self *PoolTier) computeTierRewards(emission int64) map[uint64]int64 {
	tierRewards := make(map[uint64]int64, AllTierCount-1)

	for tierNum := uint64(1); tierNum < AllTierCount; tierNum++ {
		tierCount := int64(self.counts[tierNum])
		if tierCount == 0 {
			continue
		}

		tierRatio, err := self.tierRatio.Get(tierNum)
		if err != nil {
			panic(makeErrorWithDetails(errInvalidPoolTier, err.Error()))
		}

		reward, err := calculatePoolReward(emission, int64(tierRatio), tierCount)
		if err != nil {
			panic(err)
		}
		tierRewards[tierNum] = reward
	}

	return tierRewards
}

reward_calculation_tick.gno

package staker

import (
	"chain"
	"errors"

	"gno.land/p/gnoswap/gnsmath/v1"
	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	"gno.land/p/gnoswap/utils/v1"
	sr "gno.land/r/gnoswap/staker"
)

type TickResolver struct {
	*sr.Tick
}

// CurrentOutsideAccumulation returns the latest outside accumulation for the tick
// Parameters:
//   - timestamp: Timestamp through which the tick's outside-accumulation history is queried.
//
// Returns:
//   - *u256.Uint: Most recent decoded outside accumulation at or before timestamp, or zero when none exists.
func (self *TickResolver) CurrentOutsideAccumulation(timestamp int64) *u256.Uint {
	var acc *u256.Uint
	self.OutsideAccumulation().ReverseIterate(0, timestamp, func(key int64, value any) bool {
		v, ok := value.(string)
		if !ok {
			panic("failed to cast value to string")
		}
		acc = utils.DecodeUint256(v)
		return true
	})
	if acc == nil {
		return u256.Zero()
	}
	return acc
}

// modifyDepositLower updates the tick's liquidity info by treating the deposit as a lower tick
func (self *TickResolver) modifyDepositLower(currentTime int64, liquidity *i256.Int) {
	// update staker side tick info
	self.SetStakedLiquidityGross(gnsmath.LiquidityMathAddDelta(self.StakedLiquidityGross(), liquidity))
	if self.StakedLiquidityGross().Lt(u256.Zero()) {
		panic("stakedLiquidityGross is negative")
	}
	self.SetStakedLiquidityDelta(i256.Zero().Add(self.StakedLiquidityDelta(), liquidity))
}

// modifyDepositUpper updates the tick's liquidity info by treating the deposit as an upper tick
func (self *TickResolver) modifyDepositUpper(currentTime int64, liquidity *i256.Int) {
	self.SetStakedLiquidityGross(gnsmath.LiquidityMathAddDelta(self.StakedLiquidityGross(), liquidity))
	if self.StakedLiquidityGross().Lt(u256.Zero()) {
		panic("stakedLiquidityGross is negative")
	}
	self.SetStakedLiquidityDelta(i256.Zero().Sub(self.StakedLiquidityDelta(), liquidity))
}

// updateCurrentOutsideAccumulation updates the tick's outside accumulation
// It "flips" the accumulation's inside/outside by subtracting the current outside accumulation from the global accumulation.
// An unchanged result does not require a checkpoint because predecessor queries
// return the same value for this and all subsequent timestamps.
func (self *TickResolver) updateCurrentOutsideAccumulation(timestamp int64, acc *u256.Uint) *u256.Uint {
	currentOutsideAccumulation := self.CurrentOutsideAccumulation(timestamp)
	newOutsideAccumulation := u256.Zero().Sub(acc, currentOutsideAccumulation)
	if newOutsideAccumulation.Eq(currentOutsideAccumulation) {
		return currentOutsideAccumulation
	}

	self.SetOutsideAccumulationAt(timestamp, newOutsideAccumulation)
	return newOutsideAccumulation
}

// NewTickResolver wraps a staker tick to expose reward-accumulation updates.
//
// Parameters:
//   - tick: Staker tick whose state is resolved.
//
// Returns:
//   - *TickResolver: Resolver backed by tick.
func NewTickResolver(tick *sr.Tick) *TickResolver {
	return &TickResolver{
		Tick: tick,
	}
}

// swapStartHook is called when a swap starts
// This hook initializes the batch processor for accumulating tick crosses
func (s *stakerV1) swapStartHook(_ int, rlm realm, poolPath string, timestamp int64) {
	pool, ok := s.getPools().Get(poolPath)
	if !ok {
		return
	}
	if pool.Ticks().Tree().Size() == 0 {
		return
	}

	// Initialize batch processor for this swap
	// This will accumulate all tick crosses until swap completion
	currentSwapBatch := sr.NewSwapBatchProcessor(poolPath, pool, timestamp)
	err := s.store.SetCurrentSwapBatch(0, rlm, currentSwapBatch)
	if err != nil {
		panic(err)
	}
}

// swapEndHook is called when a swap ends
// This hook processes all accumulated tick crosses in a single batch operation
// and cleans up the batch processor. The batch processing approach provides:
// 1. O(1) pool state updates instead of O(n) where n = number of tick crosses
// 2. Reduced computational overhead for reward calculations
// 3. Atomic processing ensuring consistency across all tick updates
func (s *stakerV1) swapEndHook(_ int, rlm realm, poolPath string) error {
	// Validate batch processor state
	currentSwapBatch := s.store.GetCurrentSwapBatch()

	if currentSwapBatch == nil || !currentSwapBatch.IsActive() || currentSwapBatch.PoolPath() != poolPath {
		return nil
	}

	// Disable further accumulation
	currentSwapBatch.SetIsActive(false)

	// Process all accumulated tick crosses in a single batch
	// This is where the optimization happens - instead of processing
	// each tick cross individually, we calculate cumulative effects
	err := s.processBatchedTickCrosses(0, rlm)
	if err != nil {
		return err
	}

	// Clean up batch processor
	err = s.store.SetCurrentSwapBatch(0, rlm, nil)
	if err != nil {
		return err
	}

	return nil
}

// tickCrossHook is called when a tick is crossed.
// Active swaps accumulate crosses and process their net liquidity change once at
// swap end. Calls without an active batch use the immediate fallback, which
// materializes the reward cache for each individual tick cross.
func (s *stakerV1) tickCrossHook(_ int, rlm realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64) {
	pool, ok := s.getPools().Get(poolPath)
	if !ok {
		return
	}

	// Skip ticks without staking state.
	tick := pool.Ticks().Get(tickId)
	if tick == nil {
		return
	}

	// Skip ticks without staked boundary liquidity (no reward impact)
	if tick.StakedLiquidityGross().IsZero() {
		return
	}

	currentSwapBatch := s.store.GetCurrentSwapBatch()
	// Batch processing path: accumulate tick crosses during active swap
	if currentSwapBatch != nil && currentSwapBatch.IsActive() && currentSwapBatch.PoolPath() == poolPath {
		// Pre-calculate liquidity delta with direction consideration
		// zeroForOne swap: liquidity delta is negated (liquidity being removed from current tick)
		liquidityDelta := tick.StakedLiquidityDelta()
		if zeroForOne {
			liquidityDelta = i256.Zero().Neg(liquidityDelta)
		}

		// Accumulate this tick cross for batch processing
		currentSwapBatch.AddCross(sr.NewSwapTickCross(tickId, zeroForOne, liquidityDelta))
		return
	}

	// Immediate fallback for tick-cross callers without an active swap batch.
	// Current production tick crosses originate from Swap and use batching; this
	// path preserves correct accounting for future non-swap callers.
	s.processTickCrossImmediate(pool, tick, tickId, zeroForOne, timestamp)
}

// processTickCrossImmediate processes one unbatched tick cross.
// It materializes elapsed halving boundaries while the pre-cross liquidity is
// still effective, before modifying the deposit for that individual cross.
func (s *stakerV1) processTickCrossImmediate(pool *sr.Pool, tick *sr.Tick, tickId int32, zeroForOne bool, timestamp int64) {
	// Calculate the effective tick position after crossing
	// For zeroForOne swaps, liquidity becomes effective one tick lower
	nextTick := tickId
	if zeroForOne {
		nextTick-- // Move to the lower tick where liquidity becomes active
	}

	// Calculate liquidity delta with direction consideration
	liquidityDelta := tick.StakedLiquidityDelta()
	if zeroForOne {
		// Negate delta for zeroForOne direction (liquidity being removed from current range)
		liquidityDelta = i256.Zero().Neg(liquidityDelta)
	}

	// Update pool's cumulative deposit with the liquidity change
	poolResolver := NewPoolResolver(pool)
	s.getPoolTier().cacheRewardForPool(timestamp, s.getPools(), pool.PoolPath())
	newAcc := poolResolver.modifyDeposit(liquidityDelta, timestamp, nextTick)

	// Update the tick's outside accumulation for reward calculations
	// This ensures proper reward distribution tracking across tick boundaries
	tickResolver := NewTickResolver(tick)
	tickResolver.updateCurrentOutsideAccumulation(timestamp, newAcc)
}

// processBatchedTickCrosses processes all accumulated tick crosses at once
// This is the core optimization function that processes multiple tick crosses in a single operation.
// Instead of updating pool state for each tick cross individually (O(n) operations),
// it calculates the cumulative effect and applies it once (O(1) pool updates + O(n) tick updates).
func (s *stakerV1) processBatchedTickCrosses(_ int, rlm realm) error {
	// Early exit for empty batches
	currentSwapBatch := s.store.GetCurrentSwapBatch()
	if currentSwapBatch == nil || len(currentSwapBatch.Crosses()) == 0 {
		return nil
	}

	// Validate pool reference
	if currentSwapBatch.Pool() == nil {
		return errors.New(errPoolNotFound)
	}

	batch := currentSwapBatch
	timestamp := batch.Timestamp()

	// Phase 1: Calculate cumulative liquidity delta across all tick crosses
	// This replaces multiple individual pool updates with a single cumulative update
	cumulativeDelta := i256.Zero()
	for _, tickCross := range batch.Crosses() {
		newDelta := cumulativeDelta.Add(cumulativeDelta, tickCross.Delta())
		cumulativeDelta = newDelta
	}

	// Phase 2: Determine the effective tick position for pool state update
	// Use the last crossed tick as the reference point for cumulative changes
	lastCross := batch.LastCross()
	if lastCross == nil {
		return nil
	}

	lastTick := lastCross.TickID()
	if lastCross.ZeroForOne() {
		lastTick-- // Adjust for zeroForOne direction
	}

	// Phase 3: Apply the batch's cumulative change to pool state once.
	// cacheRewardForPool runs once for each non-empty normal swap batch, before
	// the net liquidity change. It sees the pre-cross liquidity and splits
	// unclaimable intervals at every elapsed halving boundary.
	poolResolver := NewPoolResolver(batch.Pool())
	s.getPoolTier().cacheRewardForPool(timestamp, s.getPools(), batch.PoolPath())
	newAcc := poolResolver.modifyDeposit(cumulativeDelta, timestamp, lastTick)

	// Phase 4: Update individual tick outside accumulations for reward tracking
	// While we optimize pool updates, each tick still needs its accumulation updated
	// for proper reward distribution calculations

	for _, tickCross := range batch.Crosses() {
		tick := batch.Pool().Ticks().Get(tickCross.TickID())
		if tick == nil {
			// Pruned after the cross was accumulated, so its staked gross
			// liquidity is zero and it carries no reward weight.
			continue
		}

		tickResolver := NewTickResolver(tick)
		outsideAccumulation := tickResolver.updateCurrentOutsideAccumulation(timestamp, newAcc)

		tickCrossEventInfo := NewTickCrossEventInfo(
			tickCross.TickID(),
			tick.StakedLiquidityGross(),
			tick.StakedLiquidityDelta(),
			outsideAccumulation,
		)

		chain.Emit(
			"StakerTickCross",
			"poolPath", batch.PoolPath(),
			"tick", tickCrossEventInfo.ToString(),
		)
	}

	previousRealm := rlm.Previous()
	stakedLiquidity := poolResolver.CurrentStakedLiquidity(timestamp)

	// Emit event with staker-side tick cross information.
	// lastTick — the effective tick written to HistoricalTick by modifyDeposit above.
	// Reward calculation (CalculateRawRewardForPosition) reads HistoricalTick for the feeGrowthInside branch,
	// so off-chain indexers must use this same value (NOT the pool's Slot0 tick) to reproduce in-range status.
	chain.Emit(
		"BatchStakerTickCross",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"poolPath", batch.PoolPath(),
		"blockTimestamp", utils.FormatInt(timestamp),
		"stakedLiquidity", stakedLiquidity.ToString(),
		"globalRewardRatioAccX128", newAcc.ToString(),
		"lastTick", utils.FormatInt(lastTick),
	)

	return nil
}

func (s *stakerV1) setupSwapHooks(_ int, rlm realm) {
	// Set tick cross hook for pool contract
	s.poolAccessor.SetTickCrossHook(0, rlm, s.tickCrossHook)

	// Set swap start/end hooks for batch processing
	s.poolAccessor.SetSwapStartHook(0, rlm, s.swapStartHook)

	// Set swap end hook for batch processing
	s.poolAccessor.SetSwapEndHook(0, rlm, s.swapEndHook)
}

reward_calculation_warmup.gno

package staker

import (
	"errors"
	"math"

	"gno.land/p/gnoswap/gnsmath/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	ufmt "gno.land/p/nt/ufmt/v0"
	sr "gno.land/r/gnoswap/staker"
)

const maxDurationOneYear = int64(365 * 86400) // 31,536,000 seconds

// expected to be called by governance
func modifyWarmup(warmupTemplate []sr.Warmup, index int, timeDuration int64) []sr.Warmup {
	if index >= len(warmupTemplate) {
		panic(ufmt.Sprintf("index(%d) is out of range", index))
	}

	// Handle negative duration - panic with error
	if timeDuration < 0 {
		panic(ufmt.Sprintf("warmup duration cannot be negative, got %d seconds", timeDuration))
	}

	// Early return for last tier - must always be math.MaxInt64
	if index == len(warmupTemplate)-1 {
		if timeDuration != math.MaxInt64 {
			panic(ufmt.Sprintf("last warmup tier must have duration of math.MaxInt64, got %d", timeDuration))
		}
		// No modification needed as it's already math.MaxInt64
		return warmupTemplate
	}

	// Limit non-final tier durations to 1 year (365 days)
	if timeDuration > maxDurationOneYear {
		panic(ufmt.Sprintf("warmup duration cannot exceed 1 year (365 days), got %d seconds", timeDuration))
	}

	warmupTemplate[index].SetTimeDuration(timeDuration)

	return warmupTemplate
}

func instantiateWarmup(warmupTemplate []sr.Warmup, currentTime int64) []sr.Warmup {
	warmups := make([]sr.Warmup, 0, len(warmupTemplate))
	for i, warmup := range warmupTemplate {
		nextWarmupTime := safeAddTime(currentTime, warmup.TimeDuration)

		warmups = append(warmups, sr.NewWarmup(warmup.TimeDuration, nextWarmupTime, warmup.WarmupRatio))

		// Only update currentTime if not the last tier
		if i < len(warmupTemplate)-1 {
			currentTime = safeAddTime(currentTime, warmup.TimeDuration)
		}
	}
	return warmups
}

func applyWarmup(warmup sr.Warmup, poolReward int64, positionLiquidity, stakedLiquidity *u256.Uint) (int64, int64) {
	if stakedLiquidity.IsZero() {
		return 0, 0
	}

	divisor := u256.NewUint(100)
	poolRewardUint := u256.NewUintFromInt64(poolReward)
	perPositionReward, overflow := u256.Zero().MulOverflow(poolRewardUint, positionLiquidity)
	if overflow {
		panic(errors.New(errOverflow))
	}
	perPositionReward = u256.Zero().Div(perPositionReward, stakedLiquidity)

	penaltyRatio := u256.NewUint(100 - warmup.WarmupRatio)
	rewardRatio := u256.NewUint(warmup.WarmupRatio)
	totalReward, overflow := u256.Zero().MulOverflow(perPositionReward, rewardRatio)
	if overflow {
		panic(errors.New(errOverflow))
	}
	totalReward = u256.Zero().Div(totalReward, divisor)

	totalPenalty, overflow := u256.Zero().MulOverflow(perPositionReward, penaltyRatio)
	if overflow {
		panic(errors.New(errOverflow))
	}
	totalPenalty = u256.Zero().Div(totalPenalty, divisor)
	return gnsmath.SafeConvertToInt64(totalReward), gnsmath.SafeConvertToInt64(totalPenalty)
}

// safeAddTime performs safe addition with overflow protection
func safeAddTime(currentTime, duration int64) int64 {
	if duration == math.MaxInt64 {
		return math.MaxInt64
	}

	// Check for overflow before addition
	if currentTime > 0 && duration > math.MaxInt64-currentTime {
		return math.MaxInt64
	}

	return gnsmath.SafeAddInt64(currentTime, duration)
}

staker.gno

package staker

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

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

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

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

	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/halt/v1"
	sr "gno.land/r/gnoswap/staker"

	"gno.land/r/gnoswap/gns"

	en "gno.land/r/gnoswap/emission"
	pn "gno.land/r/gnoswap/position"

	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"

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

const ZERO_ADDRESS = address("")

// Deposits manages all staked positions.
type Deposits struct {
	tree *bptree.BPTree
}

// NewDeposits creates a new Deposits instance.
//
// Returns:
//   - deposits: Empty deposit collection backed by a position-ID tree.
func NewDeposits() *Deposits {
	return &Deposits{
		tree: sr.NewBPTreeN(16), // positionId -> *Deposit
	}
}

// Has checks if a position ID exists in deposits.
//
// Parameters:
//   - positionId: LP position NFT ID whose deposit presence should be checked.
//
// Returns:
//   - exists: True when positionId is stored in the deposit tree; false otherwise.
func (self *Deposits) Has(positionId uint64) bool {
	return self.tree.Has(utils.EncodeUint64(positionId))
}

// Iterate traverses deposits within the specified range.
//
// Parameters:
//   - start: Lower position-ID bound passed to the tree iterator.
//   - end: Upper position-ID bound passed to the tree iterator.
//   - fn: Callback receiving each decoded position ID and deposit; return true to stop iteration or false to continue.
func (self *Deposits) Iterate(start uint64, end uint64, fn func(positionId uint64, deposit *sr.Deposit) bool) {
	self.tree.Iterate(utils.EncodeUint64(start), utils.EncodeUint64(end), func(positionId string, depositI any) bool {
		dpst := retrieveDeposit(depositI)
		return fn(utils.DecodeUint64(positionId), dpst)
	})
}

// IterateByPoolPath traverses deposits in the ID range and invokes fn only for the requested pool.
//
// Parameters:
//   - start: Lower position-ID bound passed to the tree iterator.
//   - end: Upper position-ID bound passed to the tree iterator.
//   - poolPath: Pool identifier deposits must match before the callback is invoked.
//   - fn: Callback receiving each matching position ID and deposit; return true to stop iteration or false to continue.
func (self *Deposits) IterateByPoolPath(start, end uint64, poolPath string, fn func(positionId uint64, deposit *sr.Deposit) bool) {
	self.tree.Iterate(utils.EncodeUint64(start), utils.EncodeUint64(end), func(positionId string, depositI any) bool {
		deposit := retrieveDeposit(depositI)
		if deposit.TargetPoolPath() != poolPath {
			return false
		}

		return fn(utils.DecodeUint64(positionId), deposit)
	})
}

// Size returns the number of deposits.
//
// Returns:
//   - size: Number of deposits currently stored.
func (self *Deposits) Size() int {
	return self.tree.Size()
}

// get retrieves a deposit by position ID.
func (self *Deposits) get(positionId uint64) *sr.Deposit {
	depositI := self.tree.Get(utils.EncodeUint64(positionId))
	if depositI == nil {
		panic(makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("positionId(%d) not found", positionId),
		))
	}
	return retrieveDeposit(depositI)
}

// retrieveDeposit safely casts data to Deposit type.
func retrieveDeposit(data any) *sr.Deposit {
	deposit, ok := data.(*sr.Deposit)
	if !ok {
		panic("failed to cast value to *Deposit")
	}
	return deposit
}

// set stores a deposit for a position ID.
func (self *Deposits) set(positionId uint64, deposit *sr.Deposit) {
	self.tree.Set(utils.EncodeUint64(positionId), deposit)
}

// remove deletes a deposit by position ID.
func (self *Deposits) remove(positionId uint64) {
	self.tree.Remove(utils.EncodeUint64(positionId))
}

// ExternalIncentives manages external incentive programs.
type ExternalIncentives struct {
	tree *bptree.BPTree
}

// NewExternalIncentives creates a new ExternalIncentives instance.
//
// Returns:
//   - incentives: Empty external-incentive collection backed by an incentive-ID tree.
func NewExternalIncentives() *ExternalIncentives {
	return &ExternalIncentives{
		tree: sr.NewBPTreeN(16),
	}
}

// Has checks if an incentive ID exists.
//
// Parameters:
//   - incentiveId: External incentive ID whose presence should be checked.
//
// Returns:
//   - exists: True when incentiveId is stored in the incentive tree; false otherwise.
func (self *ExternalIncentives) Has(incentiveId string) bool { return self.tree.Has(incentiveId) }

// Size returns the number of external incentives.
//
// Returns:
//   - size: Number of external incentives currently stored.
func (self *ExternalIncentives) Size() int { return self.tree.Size() }

// get retrieves an external incentive by ID.
func (self *ExternalIncentives) get(incentiveId string) *sr.ExternalIncentive {
	incentiveI := self.tree.Get(incentiveId)
	if incentiveI == nil {
		panic(makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("incentiveId(%s) not found", incentiveId),
		))
	}

	incentive, ok := incentiveI.(*sr.ExternalIncentive)
	if !ok {
		panic("failed to cast value to *ExternalIncentive")
	}
	return incentive
}

// set stores an external incentive.
func (self *ExternalIncentives) set(incentiveId string, incentive *sr.ExternalIncentive) {
	self.tree.Set(incentiveId, incentive)
}

// remove deletes an external incentive by ID.
func (self *ExternalIncentives) remove(incentiveId string) {
	self.tree.Remove(incentiveId)
}

// EmissionCacheUpdateHook updates the emission cache when called.
// This follows the same pattern as other hooks in the staker contract.
func (s *stakerV1) emissionCacheUpdateHook(_ int, rlm realm, emissionAmountPerSecond int64) {
	poolTier := s.getPoolTier()
	if poolTier != nil {
		currentTime := time.Now().Unix()
		pools := s.getPools()

		// First cache the current rewards before updating emission
		poolTier.cacheReward(currentTime, pools)

		// Update the current emission cache with the latest value
		poolTier.currentEmission = emissionAmountPerSecond

		// Now apply the new emission rate to each pool individually
		poolTier.applyCacheToAllPools(pools, currentTime, emissionAmountPerSecond)

		s.updatePoolTier(0, rlm, poolTier)
	}
}

// stakeScanLowerBound returns the lower bound of the stake-time incentive scan
// window, clamped to 0. The start-time index encodes keys as unsigned, so a
// negative bound aborts when the chain time is under TIMESTAMP_365DAYS.
func stakeScanLowerBound(currentTime int64) int64 {
	if currentTime < TIMESTAMP_365DAYS {
		return 0
	}

	return currentTime - TIMESTAMP_365DAYS
}

// StakeToken stakes an LP position NFT to earn rewards.
//
// Transfers position NFT to staker and begins reward accumulation.
// Eligible for internal incentives (GNS emission) and external rewards.
// A pool is stakeable when it has an internal tier or an active/future external incentive.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - positionId: LP position NFT token ID to stake.
//   - referrer: Optional referral address for tracking.
//
// Returns:
//   - poolPath: Pool identifier (token0:token1:fee).
//
// Requirements:
//   - Caller must own the position NFT.
//   - Position must have non-zero liquidity.
//   - Pool must have an internal tier or an active/future external incentive.
//   - Position not already staked.
//
// Note: Out-of-range positions earn no rewards but can be staked.
func (s *stakerV1) StakeToken(_ int, rlm realm, positionId uint64, referrer string) string {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedStaker()

	assertIsNotStaked(s, positionId)
	assertHasNoExitCheckpoint(s, positionId)

	en.MintAndDistributeGns(cross(rlm))

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

	owner, err := s.nftAccessor.OwnerOf(positionIdFrom(positionId))
	if err != nil {
		panic(err.Error())
	}
	assertIsPositionOwner(owner, caller)

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

	if err := tokenHasLiquidity(positionId); err != nil {
		panic(err.Error())
	}

	// check pool path from positionId
	poolPath, err := pn.GetPositionPoolKey(positionId)
	if err != nil {
		panic(err)
	}
	pools := s.getPools()

	pool, ok := pools.Get(poolPath)
	if !ok {
		panic(makeErrorWithDetails(
			errNonIncentivizedPool,
			ufmt.Sprintf("cannot stake position to non existing pool(%s)", poolPath),
		))
	}

	err = s.poolHasIncentives(pool)
	if err != nil {
		panic(err.Error())
	}

	liquidity := getLiquidity(positionId)
	tickLower, tickUpper := getTickOf(positionId)

	warmups := s.store.GetWarmupTemplate()
	currentWarmups := instantiateWarmup(warmups, currentTime)

	// staked status
	deposit := sr.NewDeposit(
		caller,
		poolPath,
		liquidity,
		currentTime,
		tickLower,
		tickUpper,
		currentWarmups,
	)

	// when staking, add new incentives to deposit.
	//
	// Incentive duration is capped at TIMESTAMP_365DAYS, so anything still
	// active at currentTime starts within [currentTime-365d, currentTime].
	// Incentives starting before that window have ended and are filtered by
	// the EndTimestamp check below.
	//
	currentIncentiveIds := s.getExternalIncentiveIdsBy(poolPath, stakeScanLowerBound(currentTime), currentTime)

	for _, incentiveId := range currentIncentiveIds {
		incentive := s.getExternalIncentives().get(incentiveId)
		// If incentive is ended, not available to collect reward
		if currentTime > incentive.EndTimestamp() {
			continue
		}

		deposit.AddExternalIncentiveId(incentiveId)
	}

	// set last external incentive ids updated at
	deposit.SetLastExternalIncentiveUpdatedAt(currentTime)

	deposits := s.getDeposits()
	deposits.set(positionId, deposit)

	// transfer NFT ownership to staker contract
	stakerAddr := access.MustGetAddress(prbac.ROLE_STAKER.String())
	if err := s.transferDeposit(0, rlm, positionId, owner, caller, stakerAddr); err != nil {
		panic(err.Error())
	}

	// after transfer, set caller(user) as position operator (to collect fee and reward)
	pn.SetPositionOperator(cross(rlm), positionId, caller)

	poolTier := s.getPoolTier()
	poolTier.cacheRewardForPool(currentTime, pools, poolPath)

	signedLiquidity := i256.FromUint256(liquidity)
	currentTick := s.poolAccessor.GetSlot0Tick(poolPath)

	poolResolver := NewPoolResolver(pool)

	isInRange := false
	inRange, err := pn.IsInRange(positionId)
	if err != nil {
		panic(err)
	}
	if inRange {
		isInRange = true
		poolResolver.modifyDeposit(signedLiquidity, currentTime, currentTick)
	}
	// historical tick must be set regardless of the deposit's range
	if poolResolver.isChangedTick(currentTime, currentTick) {
		poolResolver.Pool.SetHistoricalTickAt(currentTime, currentTick)
	}

	// This could happen because of how position stores the ticks.
	// Ticks are negated if the token1 < token0.
	// A tick this stake creates must be seeded before it is persisted.
	upperTick := pool.Ticks().Get(tickUpper)
	if upperTick == nil {
		upperTick = sr.NewTick(tickUpper)
		poolResolver.initializeNewTickOutsideAccumulation(currentTime, currentTick, tickUpper, upperTick)
	}

	lowerTick := pool.Ticks().Get(tickLower)
	if lowerTick == nil {
		lowerTick = sr.NewTick(tickLower)
		poolResolver.initializeNewTickOutsideAccumulation(currentTime, currentTick, tickLower, lowerTick)
	}

	upperTickResolver := NewTickResolver(upperTick)
	lowerTickResolver := NewTickResolver(lowerTick)

	upperTickResolver.modifyDepositUpper(currentTime, signedLiquidity)
	lowerTickResolver.modifyDepositLower(currentTime, signedLiquidity)

	amount0, amount1 := s.calculateAmounts(poolPath, tickLower, tickUpper, liquidity)

	// Get accumulator values for reward calculation tracking
	globalAccX128, stakedLiquidity := poolResolver.globalRewardRatioAccumulationAt(currentTime)
	lowerOutsideAccX128 := lowerTickResolver.CurrentOutsideAccumulation(currentTime)
	upperOutsideAccX128 := upperTickResolver.CurrentOutsideAccumulation(currentTime)

	pool.Ticks().SetTick(tickUpper, upperTick)
	pool.Ticks().SetTick(tickLower, lowerTick)
	s.getPools().set(poolPath, pool)

	chain.Emit(
		"StakeToken",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"positionId", utils.FormatUint(positionId),
		"poolPath", poolPath,
		"owner", owner.String(),
		"liquidity", liquidity.ToString(),
		"positionUpperTick", utils.FormatInt(tickUpper),
		"positionLowerTick", utils.FormatInt(tickLower),
		"currentTick", utils.FormatInt(currentTick),
		"isInRange", utils.FormatBool(isInRange),
		"referrer", actualReferrer,
		"amount0", amount0.ToString(),
		"amount1", amount1.ToString(),
		"stakedLiquidity", stakedLiquidity.ToString(),
		"globalRewardRatioAccX128", globalAccX128.ToString(),
		"lowerTickOutsideAccX128", lowerOutsideAccX128.ToString(),
		"upperTickOutsideAccX128", upperOutsideAccX128.ToString(),
	)

	return poolPath
}

// transferDeposit transfers deposit ownership to a new address.
//
// Manages NFT custody during staking operations.
// Transfers ownership to staker contract for reward eligibility.
// Handles cases where the staker already holds custody.
//
// Parameters:
//   - positionId: The ID of the position NFT to transfer
//   - owner: The current owner of the position
//   - caller: The entity initiating the transfer
//   - to: The recipient address (usually staker contract)
//
// Security Features:
//   - Prevents self-transfer exploits
//   - Validates ownership before transfer
//   - Atomic operation with staking
//   - No transfer if owner == to (already in custody)
//
// Returns:
//   - nil: If owner and recipient are same
//   - error: If caller unauthorized or transfer fails
//
// NFT remains locked in staker until unstaking.
// Otherwise delegates the transfer to `gnft.TransferFrom`.
func (s *stakerV1) transferDeposit(_ int, rlm realm, positionId uint64, owner, caller, to address) error {
	// If the recipient already owns the NFT, no transfer is needed.
	if owner == to {
		return nil
	}

	if caller == to {
		return ufmt.Errorf(
			"%v: only owner(%s) can transfer positionId(%d), called from %s",
			errNoPermission, owner, positionId, caller,
		)
	}

	// transfer NFT ownership
	return s.nftAccessor.TransferFrom(0, rlm, owner, to, positionIdFrom(positionId))
}

// collectContext carries the values every reward delivery of one collect call shares: the deposit being
// collected, the collect timestamp and height, the caller identity used in events, and the accumulator
// snapshot emitted with every collect event.
//
// Resolving it once is what keeps a collect-everything call at a single snapshot: the emission delivery
// and each incentive delivery all read the same context.
type collectContext struct {
	positionId      uint64
	deposit         *sr.Deposit
	depositResolver *DepositResolver

	// checkpoint is set when the position was unstaked before collecting.
	checkpoint *sr.UnstakedPosition

	currentTime int64
	blockHeight int64

	prevAddr  string
	prevRealm string

	stakedLiquidity     *u256.Uint
	globalAccX128       *u256.Uint
	lowerOutsideAccX128 *u256.Uint
	upperOutsideAccX128 *u256.Uint
}

// newCollectContext resolves the deposit and snapshots the accumulator values used for reward
// calculation tracking. Call it AFTER the calculation's state update has been applied, so a lazily
// created pool is already persisted.
func (s *stakerV1) newCollectContext(_ int, rlm realm, target *collectTarget, currentTime, blockHeight int64) *collectContext {
	positionId := target.positionId
	deposit := target.deposit

	pool, _ := s.getPools().Get(deposit.TargetPoolPath())
	poolResolver := newPoolResolverWithExit(pool, target.checkpoint)
	globalAccX128, stakedLiquidity := poolResolver.globalRewardRatioAccumulationAt(currentTime)

	previousRealm := rlm.Previous()

	return &collectContext{
		positionId:      positionId,
		deposit:         deposit,
		depositResolver: NewDepositResolver(deposit),
		checkpoint:      target.checkpoint,

		currentTime: currentTime,
		blockHeight: blockHeight,

		prevAddr:  previousRealm.Address().String(),
		prevRealm: previousRealm.PkgPath(),

		stakedLiquidity:     stakedLiquidity,
		globalAccX128:       globalAccX128,
		lowerOutsideAccX128: poolResolver.outsideAccumulationAt(deposit.TickLower(), currentTime),
		upperOutsideAccX128: poolResolver.outsideAccumulationAt(deposit.TickUpper(), currentTime),
	}
}

// unstakingFee returns the fee rate this collect settles under: the live rate while staked,
// and the rate pinned at exit for a checkpoint, whose window closed under it.
func (self *collectContext) unstakingFee(s *stakerV1) uint64 {
	if self.checkpoint != nil {
		return self.checkpoint.UnstakingFee()
	}

	return s.GetUnstakingFee()
}

// persistDeposit writes the deposit back, unless it belongs to a checkpoint and is not there.
func (self *collectContext) persistDeposit(s *stakerV1) {
	if self.checkpoint != nil {
		return
	}

	s.getDeposits().set(self.positionId, self.deposit)
}

// externalDeliveryOutcome is what deliverExternalIncentiveReward did with one incentive. The
// checkpoint bookkeeping keys off it instead of re-deriving the decision from incentive state,
// which a permissionless re-entering collect may already have changed.
type externalDeliveryOutcome int

const (
	// externalDeliveryPaid: the incentive was debited, the cursor advanced and the reward moved.
	externalDeliveryPaid externalDeliveryOutcome = iota
	// externalDeliveryNothingOwed: the window yielded no reward and no penalty.
	externalDeliveryNothingOwed
	// externalDeliveryAlreadyDelivered: a checkpoint cursor already at the window's close, so the
	// source is settled - by a collect earlier in the exit second, or by an outer call whose
	// transfer this call re-entered from.
	externalDeliveryAlreadyDelivered
	// externalDeliveryDeferred: skipped without bookkeeping and still payable later - the incentive
	// has not started, or the staker realm's balance of the reward token is short while staked.
	externalDeliveryDeferred
	// externalDeliveryUnpayable: skipped without bookkeeping and never payable from this record,
	// because the incentive's reward amount only ever decreases.
	externalDeliveryUnpayable
)

// markEmissionCollected records the emission collect on the checkpoint. Idempotent: a
// re-entering collect may have marked it already.
func (s *stakerV1) markEmissionCollected(_ int, rlm realm, target *collectTarget) {
	if !target.isCheckpoint() || target.checkpoint.EmissionCollected() {
		return
	}

	target.checkpoint.MarkEmissionCollected()
	s.emitCheckpointSourceCollected(0, rlm, target, "emission", "")
	s.dropUnstakedPositionIfCollected(0, rlm, target)
}

// settleHaltedEmission handles the emission source of a collect that ran while emission is halted.
func (s *stakerV1) settleHaltedEmission(_ int, rlm realm, target *collectTarget, rewardParam *calculatePositionRewardParam) {
	if !target.isCheckpoint() || target.checkpoint.EmissionCollected() {
		return
	}

	internalRewards, _, err := s.calculateInternalPositionReward(rewardParam)
	if err != nil {
		panic(err)
	}

	internalReward := aggregateRewards(internalRewards)
	if internalReward.Internal != 0 || internalReward.InternalPenalty != 0 {
		return
	}

	// Mark the checkpoint's emission source as collected.
	s.markEmissionCollected(0, rlm, target)
}

// markIncentiveCollected records the incentive collect on the checkpoint from the delivery's
// reported outcome. A paid, empty or already-delivered source is done. A deferred one stays
// pending. An unpayable one is forfeited: keeping it pending forever would lock both this
// position's re-staking and the incentive's own refund, with no escape path.
func (s *stakerV1) markIncentiveCollected(_ int, rlm realm, target *collectTarget, incentiveId string, rewardAmount, rewardPenalty int64, outcome externalDeliveryOutcome) {
	if !target.isCheckpoint() || !target.checkpoint.HasPendingIncentiveId(incentiveId) {
		return
	}

	switch outcome {
	case externalDeliveryDeferred:
		return
	case externalDeliveryUnpayable:
		incentiveResolver := NewExternalIncentiveResolver(s.getExternalIncentives().get(incentiveId))
		previousRealm := rlm.Previous()
		chain.Emit(
			"ForfeitUncollectedIncentiveReward",
			"prevAddr", previousRealm.Address().String(),
			"prevRealm", previousRealm.PkgPath(),
			"positionId", utils.FormatUint(target.positionId),
			"incentiveId", incentiveId,
			"rewardToken", incentiveResolver.RewardToken(),
			"forfeitedAmount", utils.FormatInt(rewardAmount),
			"forfeitedPenalty", utils.FormatInt(rewardPenalty),
			"availableAmount", utils.FormatInt(incentiveResolver.RewardAmount()),
			"currentTime", utils.FormatInt(time.Now().Unix()),
			"currentHeight", utils.FormatInt(runtime.ChainHeight()),
		)
	}

	target.checkpoint.MarkIncentiveCollected(incentiveId)
	s.addUncollectedIncentiveCount(incentiveId, -1)
	s.emitCheckpointSourceCollected(0, rlm, target, "external", incentiveId)
	s.dropUnstakedPositionIfCollected(0, rlm, target)
}

// emitCheckpointSourceCollected reports one reward source of a checkpoint as settled, so an
// indexer can follow what the checkpoint still owes without reading realm state.
func (s *stakerV1) emitCheckpointSourceCollected(_ int, rlm realm, target *collectTarget, source, incentiveId string) {
	previousRealm := rlm.Previous()
	chain.Emit(
		"CollectUnstakedPositionSource",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"positionId", utils.FormatUint(target.positionId),
		"poolPath", target.deposit.TargetPoolPath(),
		"source", source,
		"incentiveId", incentiveId,
		"exitTime", utils.FormatInt(target.checkpoint.ExitTime()),
		"emissionCollected", utils.FormatBool(target.checkpoint.EmissionCollected()),
		"pendingIncentiveCount", utils.FormatInt(int64(target.checkpoint.PendingIncentiveCount())),
		"currentTime", utils.FormatInt(time.Now().Unix()),
		"currentHeight", utils.FormatInt(runtime.ChainHeight()),
	)
}

// collectTarget is the record a collect runs against: the live deposit while staked, or the
// exit checkpoint an unstake left behind.
type collectTarget struct {
	positionId uint64
	deposit    *sr.Deposit
	// currentTime is now while staked, and the exit time for a checkpoint.
	currentTime int64
	checkpoint  *sr.UnstakedPosition
}

// checkpointDeposit returns the deposit to calculate against when it is not in the tree.
func (self *collectTarget) checkpointDeposit() *sr.Deposit {
	if self.checkpoint == nil {
		return nil
	}

	return self.deposit
}

// isCheckpoint reports whether the collect runs against an exit checkpoint.
func (self *collectTarget) isCheckpoint() bool {
	return self.checkpoint != nil
}

// resolveCollectTarget resolves what a collect runs against and asserts the caller may.
func (s *stakerV1) resolveCollectTarget(positionId uint64, caller address) *collectTarget {
	position := s.getUnstakedPositions().get(positionId)
	if position == nil {
		assertIsDepositor(s, caller, positionId)

		return &collectTarget{
			positionId:  positionId,
			deposit:     s.getDeposits().get(positionId),
			currentTime: time.Now().Unix(),
		}
	}

	// A checkpoint collect is permissionless: it can only ever deliver to the position's owner,
	// and an open entry point is what lets anyone clear the checkpoints that hold up
	// EndExternalIncentive on the pool.
	return &collectTarget{
		positionId:  positionId,
		deposit:     position.Deposit(),
		currentTime: position.ExitTime(),
		checkpoint:  position,
	}
}

// newRewardCollectParam builds the calculation input for a collect of the given position.
func (s *stakerV1) newRewardCollectParam(target *collectTarget, currentTime, blockHeight int64) *calculatePositionRewardParam {
	return &calculatePositionRewardParam{
		CurrentHeight: blockHeight,
		CurrentTime:   currentTime,
		Deposits:      s.getDeposits(),
		Pools:         s.getPools(),
		PoolTier:      s.getPoolTier(),
		PositionId:    target.positionId,
		Deposit:       target.checkpointDeposit(),
		Exit:          target.checkpoint,
	}
}

// CollectEmissionReward harvests only the GNS emission (internal) reward for a live staked deposit
// or an exit checkpoint left by UnStakeToken.
//
// The emission and the external incentive rewards track their collection cursors independently
// (a single lastCollectTime on the deposit for emission, one per incentive id for external), so
// collecting one side leaves the other side fully accruable.
//
// State Transition:
//  1. Emission is minted and distributed so the staker holds the GNS to pay out; when emission is
//     halted, collection returns without consuming the accrued reward
//  2. Warm-up ratios are applied and the emission reward is split into user / penalty amounts
//  3. GNS is transferred to the owner, penalties and unclaimable amounts to the community pool
//  4. The deposit's internal lastCollectTime is advanced
//
// Requirements:
//   - Withdrawals must not be halted
//   - An emission halt returns zero without advancing internal reward state
//   - Caller must be the position owner for a live deposit; checkpoint collection is permissionless
//   - Position must be staked or have an exit checkpoint
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - positionId: LP position NFT token ID or position with an exit checkpoint.
//
// Returns:
//   - rewardToUser: GNS emission amount sent to the position owner, in token smallest units.
//   - rewardPenalty: GNS warmup penalty sent to the community pool, in token smallest units.
func (s *stakerV1) CollectEmissionReward(_ int, rlm realm, positionId uint64) (int64, int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	target := s.resolveCollectTarget(positionId, rlm.Previous().Address())

	_, emissionActive := en.MintAndDistributeGns(cross(rlm))

	currentTime := target.currentTime
	blockHeight := runtime.ChainHeight()
	rewardParam := s.newRewardCollectParam(target, currentTime, blockHeight)

	if !emissionActive {
		// Deferred: the accrued reward stays on the cursor until emission resumes. A checkpoint that
		// owes no emission is still settled so the halt does not block re-staking.
		s.settleHaltedEmission(0, rlm, target, rewardParam)

		return 0, 0
	}

	// Calculation is read-only; the resulting state updates (reward-cache update, lazy pool persistence)
	// are applied via updateInternalPositionReward, which is the collect-only counterpart to the
	// calculation shared with the Collectable* view getters.
	rewards, rewardUpdate, err := s.calculateInternalPositionReward(rewardParam)
	if err != nil {
		panic(err)
	}
	reward := aggregateRewards(rewards)
	s.updateInternalPositionReward(rewardParam, rewardUpdate)

	ctx := s.newCollectContext(0, rlm, target, currentTime, blockHeight)

	rewardToUser, rewardPenalty := s.deliverEmissionReward(0, rlm, ctx, reward)

	s.markEmissionCollected(0, rlm, target)

	return rewardToUser, rewardPenalty
}

// CollectExternalIncentiveReward harvests one external incentive reward for a live staked deposit
// or an exit checkpoint left by UnStakeToken.
//
// Each incentive keeps its own lastCollectTime, so the emission reward and every incentive other than
// the requested one stay collectible afterwards. For a live deposit, a not-started, zero-reward, or
// reward-token-balance-short incentive remains collectible because its cursor is not advanced. For
// an exit checkpoint, an incentive-balance shortfall is forfeited to release the checkpoint rather
// than left as an unpayable claim.
//
// State Transition:
//  1. Incentives created since the deposit's last update are added to its incentive index
//  2. Warm-up ratios are applied and the reward is split into user / penalty amounts
//  3. The reward token is transferred to the owner, the penalty accumulates on the incentive
//  4. The collected incentive's lastCollectTime is advanced
//
// Requirements:
//   - Contract must not be halted
//   - Caller must be the position owner for a live deposit; checkpoint collection is permissionless
//   - Position must be staked or have an exit checkpoint
//   - Incentive must exist and target the pool the position is staked in
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - positionId: LP position NFT token ID or position with an exit checkpoint.
//   - incentiveId: External incentive to collect.
//
// Returns:
//   - rewardAmount: Gross external reward amount delivered before the staking reward fee, in token smallest units.
//   - rewardPenalty: External warmup penalty retained by the incentive, in token smallest units.
func (s *stakerV1) CollectExternalIncentiveReward(_ int, rlm realm, positionId uint64, incentiveId string) (int64, int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	target := s.resolveCollectTarget(positionId, rlm.Previous().Address())
	assertIsIncentiveOfPool(s, target.deposit.TargetPoolPath(), positionId, incentiveId)

	currentTime := target.currentTime
	blockHeight := runtime.ChainHeight()

	// Calculation is read-only; the resulting state updates (lazy pool persistence, deposit
	// incentive-index updates) are applied via updateExternalPositionReward, which is the collect-only
	// counterpart to the calculation shared with the Collectable* view getters.
	rewardParam := s.newRewardCollectParam(target, currentTime, blockHeight)
	rewards, rewardUpdate := s.calculateExternalPositionReward(rewardParam, incentiveId)
	reward := aggregateRewards(rewards)
	s.updateExternalPositionReward(rewardParam, rewardUpdate)

	ctx := s.newCollectContext(0, rlm, target, currentTime, blockHeight)

	_, rewardAmount, rewardPenalty, outcome := s.deliverExternalIncentiveReward(
		0, rlm, ctx, incentiveId, reward.External[incentiveId], reward.ExternalPenalty[incentiveId],
	)

	// Persist the deposit even when nothing was delivered: the incentive-index update above still ran.
	ctx.persistDeposit(s)

	s.markIncentiveCollected(0, rlm, target, incentiveId, reward.External[incentiveId], reward.ExternalPenalty[incentiveId], outcome)

	return rewardAmount, rewardPenalty
}

// CollectReward harvests accumulated rewards for a live staked deposit or an exit checkpoint left
// by UnStakeToken. This includes both internal GNS emission and external incentive rewards.
//
// It is the "collect everything" entry point kept for callers that do not want to choose a side. It
// delivers each incentive, then the emission reward, through the same delivery functions the
// single-source entry points use. During an emission halt, it skips internal calculation, state updates,
// and delivery while continuing to settle external incentives.
//
// Requirements:
//   - Withdrawals must not be halted
//   - Caller must be the position owner for a live deposit; checkpoint collection is permissionless
//   - Position must be staked or have an exit checkpoint
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - positionId: LP position NFT token ID or position with an exit checkpoint.
//
// Returns:
//   - internalRewardToUser: GNS emission amount sent to the owner, formatted as a decimal string.
//   - internalRewardPenalty: GNS warmup penalty sent to the community pool, formatted as a decimal string.
//   - externalRewards: Map from reward-token path to gross external reward amounts before staking fees.
//   - externalPenalties: Map from reward-token path to external warmup penalty amounts.
func (s *stakerV1) CollectReward(_ int, rlm realm, positionId uint64) (string, string, map[string]int64, map[string]int64) {
	access.AssertIsRlmCurrent(0, rlm)

	halt.AssertIsNotHaltedWithdraw()

	target := s.resolveCollectTarget(positionId, rlm.Previous().Address())

	_, emissionActive := en.MintAndDistributeGns(cross(rlm))

	currentTime := target.currentTime
	blockHeight := runtime.ChainHeight()
	rewardParam := s.newRewardCollectParam(target, currentTime, blockHeight)

	var (
		rewards      []Reward
		rewardUpdate positionRewardUpdate
	)

	if emissionActive {
		var err error

		rewards, rewardUpdate, err = s.calculatePositionReward(rewardParam)
		if err != nil {
			panic(err)
		}
		s.updatePositionReward(rewardParam, rewardUpdate)
	} else {
		rewards, rewardUpdate = s.calculateExternalPositionRewards(rewardParam)
		s.updateExternalPositionReward(rewardParam, rewardUpdate)
	}

	reward := aggregateRewards(rewards)

	ctx := s.newCollectContext(0, rlm, target, currentTime, blockHeight)

	// External rewards are delivered first, the order the two reward paths ran in before they were split.
	toUserExternalReward := make(map[string]int64)
	toUserExternalPenalty := make(map[string]int64)

	for _, incentiveId := range rewardUpdate.externalIncentiveIds {
		rewardToken, rewardAmount, rewardPenalty, outcome := s.deliverExternalIncentiveReward(
			0, rlm, ctx, incentiveId, reward.External[incentiveId], reward.ExternalPenalty[incentiveId],
		)

		s.markIncentiveCollected(0, rlm, target, incentiveId, reward.External[incentiveId], reward.ExternalPenalty[incentiveId], outcome)

		// An empty reward token means the incentive delivered nothing and stays collectible.
		if rewardToken == "" {
			continue
		}

		toUserExternalReward[rewardToken] = gnsmath.SafeAddInt64(toUserExternalReward[rewardToken], rewardAmount)
		toUserExternalPenalty[rewardToken] = gnsmath.SafeAddInt64(toUserExternalPenalty[rewardToken], rewardPenalty)
	}

	internalRewardToUser := int64(0)
	internalRewardPenalty := int64(0)

	if emissionActive {
		internalRewardToUser, internalRewardPenalty = s.deliverEmissionReward(0, rlm, ctx, reward)
		s.markEmissionCollected(0, rlm, target)
	} else {
		s.settleHaltedEmission(0, rlm, target, rewardParam)

		// The halted path does not reach deliverEmissionReward, which is where the live deposit's
		// incentive-index and cursor updates were written back. A checkpoint is not in the tree, so
		// this is a no-op for it.
		ctx.persistDeposit(s)
	}

	return utils.FormatInt(internalRewardToUser), utils.FormatInt(internalRewardPenalty), toUserExternalReward, toUserExternalPenalty
}

// deliverExternalIncentiveReward pays out one incentive's already-calculated reward: it debits the
// incentive, advances its lastCollectTime, takes the staking reward fee and transfers the rest.
//
// The incentive is skipped WITHOUT advancing its lastCollectTime when it yields no user reward or does
// not hold enough reward token, so the amount stays collectible later. A skipped incentive is reported
// by an empty reward token, and the outcome says why, so a checkpoint can tell a deferral from a debt
// it will never be able to pay.
//
// A warmup ratio below 100% floors the user reward, so a small accrual can yield rewardAmount == 0 while
// externalPenalty > 0. Such a call is skipped as a whole: the penalty is NOT booked and the cursor is NOT
// advanced, which leaves the untouched accrual to be recalculated over the wider window of the next
// collect. Nothing is lost either way, because an unbooked penalty stays in the incentive's reward
// amount, and endExternalIncentive refunds the reward amount and the accumulated penalty to the same
// address.
//
// Returns the reward token, the collected reward amount before the staking reward fee, the penalty,
// and the delivery outcome.
func (s *stakerV1) deliverExternalIncentiveReward(
	_ int,
	rlm realm,
	ctx *collectContext,
	incentiveId string,
	rewardAmount int64,
	externalPenalty int64,
) (string, int64, int64, externalDeliveryOutcome) {
	// A checkpoint's window closes at ctx.currentTime, so a cursor already there means this
	// incentive was delivered. The checkpoint entry points are permissionless, and rewardAmount
	// was computed before the deliveries ran: without this, a reentrant collect between them
	// would let the stale amount be paid a second time.
	if ctx.checkpoint != nil && ctx.depositResolver.ExternalRewardLastCollectTime(incentiveId) >= ctx.currentTime {
		return "", 0, 0, externalDeliveryAlreadyDelivered
	}

	// Skip when user reward is zero.
	// Do not update last collect time so the reward accrues until
	// the next collection where a non-zero amount can be delivered.
	//
	// An exit checkpoint has no next collection: it stopped accruing, so a penalty left here
	// would never be booked and would be dropped with the checkpoint.
	if rewardAmount == 0 && (ctx.checkpoint == nil || externalPenalty == 0) {
		if externalPenalty == 0 {
			return "", 0, 0, externalDeliveryNothingOwed
		}

		return "", 0, 0, externalDeliveryDeferred
	}

	// get panics on a missing id; incentives are never removed from the tree.
	incentive := s.getExternalIncentives().get(incentiveId)

	incentiveResolver := NewExternalIncentiveResolver(incentive)

	// Defensive backstop, unreachable through the current callers: computeExternalReward already drops a
	// not-yet-started incentive at the same currentTime, so its reward is zero and the check above
	// returns first. Kept so a future caller that supplies a non-zero amount cannot pay out of an
	// incentive whose distribution window has not opened.
	if !incentiveResolver.IsStarted(ctx.currentTime) {
		return "", 0, 0, externalDeliveryDeferred
	}

	totalRewardAmount := gnsmath.SafeAddInt64(rewardAmount, externalPenalty)

	if incentiveResolver.RewardAmount() < totalRewardAmount {
		// Do not update last collect time here; insufficient funds should
		// leave the incentive collectible when refilled or corrected.
		chain.Emit(
			"InsufficientExternalReward",
			"prevAddr", ctx.prevAddr,
			"prevRealm", ctx.prevRealm,
			"positionId", utils.FormatUint(ctx.positionId),
			"incentiveId", incentiveId,
			"requiredAmount", utils.FormatInt(totalRewardAmount),
			"availableAmount", utils.FormatInt(incentiveResolver.RewardAmount()),
			"currentTime", utils.FormatInt(ctx.currentTime),
			"currentHeight", utils.FormatInt(ctx.blockHeight),
		)

		// The reward amount only ever decreases, so this shortfall cannot be corrected later.
		return "", 0, 0, externalDeliveryUnpayable
	}

	// process reward states
	rewardToken := incentive.RewardToken()

	// Ledger-level delivery guard (audit finding #4).
	//
	// The bookkeeping check above proves the incentive owes this reward; it says
	// nothing about whether the ledger transfers below can succeed. A panic there
	// would abort the collect: while staked that only delays the payout, but on an
	// exit checkpoint it would leave the checkpoint in place forever, holding the
	// position's re-staking and the incentive's refund hostage to a third-party token.
	//
	// GnoSwap transfers resolve through grc20reg's concrete *grc20.Token straight
	// into PrivateLedger, so no token-realm code runs in the path and the
	// reachable failure set is closed. Because grc20 Mint enforces
	// totalSupply <= MaxInt64 and every ledger operation conserves
	// sum(balances) == totalSupply, a recipient-balance overflow is unreachable;
	// the only reachable failure is the sender balance falling short of what
	// BOTH legs move (issuer burn of the staker's balance, or accounting drift).
	// The fee leg settles carried-over pending protocol fees of the same token
	// too, hence the +pending term. The full derivation, the trust model, and
	// the re-audit trigger live in docs/staker.md.
	//
	// Skipping BEFORE any bookkeeping means: while staked the reward simply
	// stays pending and becomes collectible once the balance is restored. A
	// checkpoint aborts instead: its claim is fixed and must not be waived by
	// a permissionless caller, so it stays owed until the balance is restored.
	stakerAddr := access.MustGetAddress(prbac.ROLE_STAKER.String())
	pendingProtocolFee := s.store.GetPendingProtocolFees()[rewardToken]
	requiredBalance := gnsmath.SafeAddInt64(totalRewardAmount, pendingProtocolFee)

	if common.BalanceOf(rewardToken, stakerAddr) < requiredBalance {
		chain.Emit(
			"UndeliverableExternalReward",
			"prevAddr", ctx.prevAddr,
			"prevRealm", ctx.prevRealm,
			"positionId", utils.FormatUint(ctx.positionId),
			"incentiveId", incentiveId,
			"rewardToken", rewardToken,
			"requiredBalance", utils.FormatInt(requiredBalance),
			"stakerBalance", utils.FormatInt(common.BalanceOf(rewardToken, stakerAddr)),
			"currentTime", utils.FormatInt(ctx.currentTime),
			"currentHeight", utils.FormatInt(ctx.blockHeight),
		)

		if ctx.checkpoint != nil {
			panic(makeErrorWithDetails(
				errInsufficientRewardTokenBalance,
				ufmt.Sprintf(
					"incentive(%s) owes %d of %s to positionId(%d) but the staker holds %d",
					incentiveId, requiredBalance, rewardToken, ctx.positionId, common.BalanceOf(rewardToken, stakerAddr),
				),
			))
		}

		return "", 0, 0, externalDeliveryDeferred
	}

	incentive.SetRewardAmount(gnsmath.SafeSubInt64(incentive.RewardAmount(), totalRewardAmount))
	incentiveResolver.addDistributedRewardAmount(rewardAmount)
	incentiveResolver.addAccumulatedPenaltyAmount(externalPenalty)
	ctx.depositResolver.addCollectedExternalReward(incentiveId, totalRewardAmount)

	// Update the last collect time ONLY for this specific incentive
	// This happens only if the reward was successfully transferred.
	err := ctx.depositResolver.updateExternalRewardLastCollectTime(incentiveId, ctx.currentTime)
	if err != nil {
		panic(err)
	}

	// If incentive ended and user already collected after end, remove from index
	// This ensures deposit's incentive list shrinks over time as incentives complete
	if ctx.depositResolver.ExternalRewardLastCollectTime(incentiveId) > incentiveResolver.EndTimestamp() {
		ctx.deposit.RemoveExternalIncentiveId(incentiveId)
	}

	// update
	s.getExternalIncentives().set(incentiveId, incentive)

	toUser, feeAmount, err := s.handleStakingRewardFee(0, rlm, rewardToken, rewardAmount, false, ctx.unstakingFee(s))
	if err != nil {
		panic(err.Error())
	}

	if toUser > 0 {
		common.SafeGRC20Transfer(0, rlm, rewardToken, ctx.deposit.Owner(), toUser)
	}

	chain.Emit(
		"ProtocolFeeExternalReward",
		"prevAddr", ctx.prevAddr,
		"prevRealm", ctx.prevRealm,
		"fromPositionId", utils.FormatUint(ctx.positionId),
		"fromPoolPath", incentive.TargetPoolPath(),
		"feeTokenPath", rewardToken,
		"feeAmount", utils.FormatInt(feeAmount),
		"currentTime", utils.FormatInt(ctx.currentTime),
		"currentHeight", utils.FormatInt(ctx.blockHeight),
	)

	chain.Emit(
		"CollectReward",
		"prevAddr", ctx.prevAddr,
		"prevRealm", ctx.prevRealm,
		"positionId", utils.FormatUint(ctx.positionId),
		"poolPath", ctx.deposit.TargetPoolPath(),
		"recipient", ctx.deposit.Owner().String(),
		"incentiveId", incentiveId,
		"rewardToken", rewardToken,
		"rewardAmount", utils.FormatInt(rewardAmount),
		"rewardToUser", utils.FormatInt(toUser),
		"rewardToFee", utils.FormatInt(rewardAmount-toUser),
		"rewardPenalty", utils.FormatInt(externalPenalty),
		"currentTime", utils.FormatInt(ctx.currentTime),
		"currentHeight", utils.FormatInt(ctx.blockHeight),
		"stakedLiquidity", ctx.stakedLiquidity.ToString(),
		"globalRewardRatioAccX128", ctx.globalAccX128.ToString(),
		"lowerTickOutsideAccX128", ctx.lowerOutsideAccX128.ToString(),
		"upperTickOutsideAccX128", ctx.upperOutsideAccX128.ToString(),
	)

	return rewardToken, rewardAmount, externalPenalty, externalDeliveryPaid
}

// deliverEmissionReward pays out the already-calculated GNS emission reward: it takes the staking reward
// fee, settles the pool's unclaimable accumulation to the community pool, advances totalEmissionSent and
// the deposit's internal lastCollectTime, and transfers the GNS.
//
// When the position has no emission reward to deliver, the internal lastCollectTime is left untouched so
// the amount keeps accruing; the pool's unclaimable accumulation is still settled.
//
// Returns the GNS amount sent to the user and the penalty amount sent to the community pool.
func (s *stakerV1) deliverEmissionReward(_ int, rlm realm, ctx *collectContext, reward Reward) (int64, int64) {
	// Same reentrancy backstop as deliverExternalIncentiveReward: a checkpoint whose internal
	// cursor already reached its window's close has had this delivery, and reward was computed
	// before the external deliveries ran. The source counts as settled either way.
	if ctx.checkpoint != nil && ctx.depositResolver.InternalRewardLastCollectTime() >= ctx.currentTime {
		return 0, 0
	}

	communityPoolAddr := access.MustGetAddress(prbac.ROLE_COMMUNITY_POOL.String())

	internalReward := int64(0)
	internalRewardToUser := int64(0)
	internalRewardToFee := int64(0)
	internalRewardPenalty := int64(0)

	// Skip internal reward state update when user reward is zero (only penalty).
	// Do not update last collect time so the reward accrues until the next
	// collection where a non-zero amount can be delivered.
	//
	// An exit checkpoint has no next collection: it stopped accruing, so a penalty left here
	// would never be delivered and would be dropped with the checkpoint.
	skipInternalUpdate := reward.Internal == 0 &&
		(ctx.checkpoint == nil || reward.InternalPenalty == 0)

	// internal reward to user
	if !skipInternalUpdate {
		toUser, feeAmount, err := s.handleStakingRewardFee(0, rlm, GNS_TOKEN_KEY, reward.Internal, true, ctx.unstakingFee(s))
		if err != nil {
			panic(err.Error())
		}

		internalReward = reward.Internal
		internalRewardToUser = toUser
		internalRewardToFee = feeAmount
		internalRewardPenalty = reward.InternalPenalty

		chain.Emit(
			"ProtocolFeeInternalReward",
			"prevAddr", ctx.prevAddr,
			"prevRealm", ctx.prevRealm,
			"fromPositionId", utils.FormatUint(ctx.positionId),
			"fromPoolPath", ctx.deposit.TargetPoolPath(),
			"feeTokenPath", GNS_TOKEN_KEY,
			"feeAmount", utils.FormatInt(internalRewardToFee),
			"currentTime", utils.FormatInt(ctx.currentTime),
			"currentHeight", utils.FormatInt(ctx.blockHeight),
		)
	}

	totalEmissionSent := s.store.GetTotalEmissionSent()

	if internalRewardToUser > 0 {
		// internal reward to user
		totalEmissionSent = gnsmath.SafeAddInt64(totalEmissionSent, internalRewardToUser)
		ctx.depositResolver.addCollectedInternalReward(reward.Internal)
	}

	if internalRewardPenalty > 0 {
		// internal penalty to community pool
		totalEmissionSent = gnsmath.SafeAddInt64(totalEmissionSent, internalRewardPenalty)
		ctx.depositResolver.addCollectedInternalReward(internalRewardPenalty)
	}

	// Unclaimable must be processed after regular rewards so that accumulated
	// unclaimable amounts are reset in the same collect window.
	// Always at the current time, never at ctx.currentTime: this accumulator is pool-global, and
	// a checkpoint collect would rewind it to its exit timestamp, re-counting everything since as
	// unclaimable and paying it out of the shared reserve.
	unClaimableInternal := s.processUnClaimableReward(ctx.depositResolver.TargetPoolPath(), time.Now().Unix())
	if unClaimableInternal > 0 {
		totalEmissionSent = gnsmath.SafeAddInt64(totalEmissionSent, unClaimableInternal)
	}

	if err := s.store.SetTotalEmissionSent(0, rlm, totalEmissionSent); err != nil {
		panic(err)
	}

	if !skipInternalUpdate {
		// Update lastCollectTime for internal rewards (GNS emissions)
		if err := ctx.depositResolver.updateInternalRewardLastCollectTime(ctx.currentTime); err != nil {
			panic(err)
		}
	}

	ctx.persistDeposit(s)

	if internalRewardToUser > 0 {
		gns.Transfer(cross(rlm), ctx.deposit.Owner(), internalRewardToUser)
	}

	if internalRewardPenalty > 0 {
		gns.Transfer(cross(rlm), communityPoolAddr, internalRewardPenalty)
	}

	if unClaimableInternal > 0 {
		gns.Transfer(cross(rlm), communityPoolAddr, unClaimableInternal)
	}

	if !skipInternalUpdate {
		chain.Emit(
			"CollectReward",
			"prevAddr", ctx.prevAddr,
			"prevRealm", ctx.prevRealm,
			"positionId", utils.FormatUint(ctx.positionId),
			"poolPath", ctx.depositResolver.TargetPoolPath(),
			"recipient", ctx.depositResolver.Owner().String(),
			"rewardToken", GNS_TOKEN_KEY,
			"rewardAmount", utils.FormatInt(internalReward),
			"rewardToUser", utils.FormatInt(internalRewardToUser),
			"rewardToFee", utils.FormatInt(internalRewardToFee),
			"rewardPenalty", utils.FormatInt(internalRewardPenalty),
			"rewardUnClaimableAmount", utils.FormatInt(unClaimableInternal),
			"currentTime", utils.FormatInt(ctx.currentTime),
			"currentHeight", utils.FormatInt(ctx.blockHeight),
			"stakedLiquidity", ctx.stakedLiquidity.ToString(),
			"globalRewardRatioAccX128", ctx.globalAccX128.ToString(),
			"lowerTickOutsideAccX128", ctx.lowerOutsideAccX128.ToString(),
			"upperTickOutsideAccX128", ctx.upperOutsideAccX128.ToString(),
		)
	}

	return internalRewardToUser, internalRewardPenalty
}

// UnStakeToken withdraws an LP token from staking and returns the NFT to its original owner.
// Rewards are not collected here: an exit checkpoint records what the position is still owed,
// and the Collect* entry points settle it per source.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the staker proxy.
//   - positionId: LP position NFT token ID to unstake.
//
// Process:
//  1. Records an exit checkpoint owing every reward source (GNS + external)
//  2. Transfers NFT ownership back to original owner
//  3. Clears position operator rights
//  4. Removes from reward tracking systems
//  5. Cleans up all staking metadata
//
// Returns:
//   - poolPath: Pool identifier where position was staked.
//
// Requirements:
//   - Caller must be the depositor
//   - Position must be currently staked
func (s *stakerV1) UnStakeToken(_ int, rlm realm, positionId uint64) string { // poolPath
	access.AssertIsRlmCurrent(0, rlm)

	caller := rlm.Previous().Address()
	halt.AssertIsNotHaltedWithdraw()
	assertIsDepositor(s, caller, positionId)

	deposit := s.getDeposits().get(positionId)

	// unStaked status
	poolPath := deposit.TargetPoolPath()

	// record the exit checkpoint; collecting is left to the Collect* entry points
	checkpoint := s.recordUnstakedPosition(0, rlm, positionId, deposit, time.Now().Unix())

	if err := s.applyUnStake(positionId); err != nil {
		panic(err)
	}

	// transfer NFT ownership to origin owner
	stakerAddr := access.MustGetAddress(prbac.ROLE_STAKER.String())
	s.nftAccessor.TransferFrom(0, rlm, stakerAddr, deposit.Owner(), positionIdFrom(positionId))
	pn.SetPositionOperator(cross(rlm), positionId, ZERO_ADDRESS)

	// get position information for event
	liquidity := getLiquidity(positionId)
	tickLower, tickUpper := getTickOf(positionId)

	amount0, amount1 := s.calculateAmounts(poolPath, tickLower, tickUpper, liquidity)

	// Get pool and accumulator values for reward calculation tracking
	currentTime := time.Now().Unix()
	pool, _ := s.getPools().Get(poolPath)
	poolResolver := NewPoolResolver(pool)
	currentTick := s.poolAccessor.GetSlot0Tick(poolPath)

	globalAccX128, stakedLiquidity := poolResolver.globalRewardRatioAccumulationAt(currentTime)

	previousRealm := rlm.Previous()
	chain.Emit(
		"UnStakeToken",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"positionId", utils.FormatUint(positionId),
		"poolPath", poolPath,
		"owner", deposit.Owner().String(),
		"liquidity", liquidity.ToString(),
		"positionUpperTick", utils.FormatInt(tickUpper),
		"positionLowerTick", utils.FormatInt(tickLower),
		"amount0", amount0.ToString(),
		"amount1", amount1.ToString(),
		"from", stakerAddr.String(),
		"to", deposit.Owner().String(),
		"currentTick", utils.FormatInt(currentTick),
		"stakedLiquidity", stakedLiquidity.ToString(),
		"globalRewardRatioAccX128", globalAccX128.ToString(),
		"exitTime", utils.FormatInt(checkpoint.ExitTime()),
		"pendingIncentiveIds", strings.Join(checkpoint.PendingIncentiveIdList(), ","),
		"pendingIncentiveCount", utils.FormatInt(int64(checkpoint.PendingIncentiveCount())),
	)

	return poolPath
}

func (s *stakerV1) applyUnStake(positionId uint64) error {
	deposit := s.getDeposits().get(positionId)
	depositResolver := NewDepositResolver(deposit)
	pool, ok := s.getPools().Get(depositResolver.TargetPoolPath())
	poolResolver := NewPoolResolver(pool)
	if !ok {
		return ufmt.Errorf(
			"%v: pool(%s) does not exist",
			errDataNotFound, depositResolver.TargetPoolPath(),
		)
	}

	currentTime := time.Now().Unix()
	currentTick := s.poolAccessor.GetSlot0Tick(depositResolver.TargetPoolPath())
	signedLiquidity := i256.Zero().Neg(i256.FromUint256(depositResolver.Liquidity()))
	inRange, err := pn.IsInRange(positionId)
	if err != nil {
		return err
	}
	if inRange {
		poolResolver.modifyDeposit(signedLiquidity, currentTime, currentTick)
	}

	upperTick := poolResolver.GetOrNewTick(depositResolver.TickUpper())
	NewTickResolver(upperTick).modifyDepositUpper(currentTime, signedLiquidity)
	pool.Ticks().SetTick(depositResolver.TickUpper(), upperTick)

	lowerTick := poolResolver.GetOrNewTick(depositResolver.TickLower())
	NewTickResolver(lowerTick).modifyDepositLower(currentTime, signedLiquidity)
	pool.Ticks().SetTick(depositResolver.TickLower(), lowerTick)

	s.getDeposits().remove(positionId)

	return nil
}

// poolHasIncentives checks if the pool has any stakeable incentives (internal or external).
// External eligibility includes active and future incentives.
func (s *stakerV1) poolHasIncentives(pool *sr.Pool) error {
	poolPath := pool.PoolPath()
	if s.getPoolTier().IsInternallyIncentivizedPool(poolPath) {
		return nil
	}

	if !NewPoolResolver(pool).IsExternallyIncentivizedPool() {
		return ufmt.Errorf(
			"%v: cannot stake position to non incentivized pool(%s)",
			errNonIncentivizedPool, poolPath,
		)
	}

	return nil
}

// tokenHasLiquidity checks if the target positionId has non-zero liquidity
func tokenHasLiquidity(positionId uint64) error {
	if getLiquidity(positionId).Lte(u256.Zero()) {
		return ufmt.Errorf(
			"%v: positionId(%d) has no liquidity",
			errZeroLiquidity, positionId,
		)
	}
	return nil
}

func getLiquidity(positionId uint64) *u256.Uint {
	liquidity, err := pn.GetPositionLiquidity(positionId)
	if err != nil {
		panic(err)
	}

	return u256.MustFromDecimal(liquidity)
}

func getTickOf(positionId uint64) (int32, int32) {
	tickLower, err := pn.GetPositionTickLower(positionId)
	if err != nil {
		panic(err)
	}
	tickUpper, err := pn.GetPositionTickUpper(positionId)
	if err != nil {
		panic(err)
	}
	if tickUpper < tickLower {
		panic(ufmt.Sprintf("tickUpper(%d) is less than tickLower(%d)", tickUpper, tickLower))
	}
	return tickLower, tickUpper
}

// calculateAmounts calculates the amounts of token0 and token1 for a given liquidity and range.
func (s *stakerV1) calculateAmounts(poolPath string, tickLower, tickUpper int32, liquidity *u256.Uint) (*u256.Uint, *u256.Uint) {
	sqrtPriceX96 := u256.MustFromDecimal(s.poolAccessor.GetSlot0SqrtPriceX96(poolPath))
	sqrtPriceLowerX96 := gnsmath.TickMathGetSqrtRatioAtTick(tickLower)
	sqrtPriceUpperX96 := gnsmath.TickMathGetSqrtRatioAtTick(tickUpper)

	return gnsmath.GetAmountsForLiquidity(sqrtPriceX96, sqrtPriceLowerX96, sqrtPriceUpperX96, liquidity)
}

type.gno

package staker

import (
	"gno.land/p/gnoswap/gnsmath/v1"
	sr "gno.land/r/gnoswap/staker"
)

type ExternalIncentiveResolver struct {
	*sr.ExternalIncentive
}

// isActive checks if the incentive is currently active at the given timestamp
func (self *ExternalIncentiveResolver) isActive(currentTimestamp int64) bool {
	return currentTimestamp >= self.StartTimestamp() && currentTimestamp <= self.EndTimestamp()
}

// IsEnded reports whether an external incentive's distribution window has ended.
//
// Parameters:
//   - currentTimestamp: Timestamp in Unix seconds to compare with the incentive end time.
//
// Returns:
//   - ended: True when currentTimestamp is after the inclusive end timestamp; false otherwise.
func (self *ExternalIncentiveResolver) IsEnded(currentTimestamp int64) bool {
	return currentTimestamp > self.EndTimestamp()
}

// IsStarted reports whether an external incentive's distribution window has opened.
//
// Parameters:
//   - currentTimestamp: Timestamp in Unix seconds to compare with the incentive start time.
//
// Returns:
//   - started: True when currentTimestamp is at or after the incentive start timestamp; false otherwise.
func (self *ExternalIncentiveResolver) IsStarted(currentTimestamp int64) bool {
	return currentTimestamp >= self.StartTimestamp()
}

// addDistributedRewardAmount adds the given amount to the distributed reward amount.
// This function is used to add the distributed reward amount when the incentive is un-staked and refunded.
func (self *ExternalIncentiveResolver) addDistributedRewardAmount(amount int64) {
	distributedRewardAmount := gnsmath.SafeAddInt64(self.DistributedRewardAmount(), amount)
	self.SetDistributedRewardAmount(distributedRewardAmount)
}

// addAccumulatedPenaltyAmount adds the given amount to the accumulated penalty amount.
// Called during CollectReward to track warmup penalties for later collection.
func (self *ExternalIncentiveResolver) addAccumulatedPenaltyAmount(amount int64) {
	accumulatedPenaltyAmount := gnsmath.SafeAddInt64(self.AccumulatedPenaltyAmount(), amount)
	self.SetAccumulatedPenaltyAmount(accumulatedPenaltyAmount)
}

// NewExternalIncentiveResolver wraps an external incentive with resolver operations.
//
// Parameters:
//   - externalIncentive: External incentive whose timestamps and accounting state the resolver exposes.
//
// Returns:
//   - resolver: Resolver backed by externalIncentive.
func NewExternalIncentiveResolver(
	externalIncentive *sr.ExternalIncentive,
) *ExternalIncentiveResolver {
	return &ExternalIncentiveResolver{
		ExternalIncentive: externalIncentive,
	}
}

type DepositResolver struct {
	*sr.Deposit
}

// InternalRewardLastCollectTime returns the last collect time for the internal reward.
// If the last collect time is 0, it returns the staked time.
//
// Returns:
//   - lastCollectTime: Last internal reward collection time in Unix seconds, falling back to StakeTime when the stored cursor is zero.
func (self *DepositResolver) InternalRewardLastCollectTime() int64 {
	if self.Deposit.InternalRewardLastCollectTime() == 0 {
		return self.Deposit.StakeTime()
	}

	return self.Deposit.InternalRewardLastCollectTime()
}

// ExternalRewardLastCollectTime returns the last collect time for the external reward for the given incentive ID.
// If the last collect time is 0, it returns the staked time.
//
// Parameters:
//   - incentiveID: External incentive ID whose collection cursor should be resolved.
//
// Returns:
//   - lastCollectTime: Last collection time in Unix seconds, falling back to StakeTime when no nonzero cursor is stored.
func (self *DepositResolver) ExternalRewardLastCollectTime(incentiveID string) int64 {
	lastCollectTime, exists := self.Deposit.GetExternalRewardLastCollectTime(incentiveID)
	if !exists || lastCollectTime == 0 {
		return self.Deposit.StakeTime()
	}

	return lastCollectTime
}

// CollectedExternalReward returns the amount already collected for one external incentive.
//
// Parameters:
//   - incentiveID: External incentive ID whose collected amount should be resolved.
//
// Returns:
//   - collectedReward: Cumulative amount collected for incentiveID, or 0 when no amount is stored.
func (self *DepositResolver) CollectedExternalReward(incentiveID string) int64 {
	collectedExternalReward, exists := self.Deposit.GetCollectedExternalReward(incentiveID)
	if !exists {
		return 0
	}

	return collectedExternalReward
}

func (self *DepositResolver) addCollectedInternalReward(reward int64) {
	self.SetCollectedInternalReward(gnsmath.SafeAddInt64(self.CollectedInternalReward(), reward))
}

func (self *DepositResolver) addCollectedExternalReward(incentiveID string, reward int64) {
	collectedExternalReward := gnsmath.SafeAddInt64(self.CollectedExternalReward(incentiveID), reward)
	self.SetCollectedExternalReward(incentiveID, collectedExternalReward)
}

// updateInternalRewardLastCollectTime updates the last collect time for the internal reward.
// It returns an error if the current time is less than the last collect time for the internal reward.
func (self *DepositResolver) updateInternalRewardLastCollectTime(currentTime int64) error {
	if self.InternalRewardLastCollectTime() > currentTime {
		return makeErrorWithDetails(errNotAvailableUpdateCollectTime, "currentTime must be greater than internal reward last collect time")
	}

	self.SetInternalRewardLastCollectTime(currentTime)

	return nil
}

// updateExternalRewardLastCollectTime lazily updates the last collect time for the external reward for the given incentive ID.
// It returns an error if the current time is less than the last collect time for the external reward for the given incentive ID.
func (self *DepositResolver) updateExternalRewardLastCollectTime(incentiveID string, currentTime int64) error {
	if self.ExternalRewardLastCollectTimes() == nil {
		self.SetExternalRewardLastCollectTimes(make(map[string]int64))
	}

	externalLastCollectTime, exists := self.Deposit.GetExternalRewardLastCollectTime(incentiveID)
	if exists && externalLastCollectTime > currentTime {
		return makeErrorWithDetails(errNotAvailableUpdateCollectTime, "currentTime must be greater than external reward last collect time")
	}

	self.Deposit.SetExternalRewardLastCollectTime(incentiveID, currentTime)

	return nil
}

// FindWarmup returns the first warmup tier whose end time is after currentTime.
//
// Parameters:
//   - currentTime: Timestamp in Unix seconds used to select the active warmup tier.
//
// Returns:
//   - index: Index of the first tier with a later NextWarmupTime, or the final tier's index when all tiers have ended.
func (self *DepositResolver) FindWarmup(currentTime int64) int {
	for i, warmup := range self.Warmups() {
		if currentTime < warmup.NextWarmupTime {
			return i
		}
	}
	return len(self.Warmups()) - 1
}

// GetWarmup returns the warmup tier at index.
//
// Parameters:
//   - index: Zero-based warmup-tier index; an out-of-range index panics through slice indexing.
//
// Returns:
//   - warmup: Warmup tier stored at index.
func (self *DepositResolver) GetWarmup(index int) sr.Warmup {
	return self.Warmups()[index]
}

// NewDepositResolver wraps a deposit with reward-cursor and warmup resolution helpers.
//
// Parameters:
//   - deposit: Deposit whose persisted reward state should be resolved.
//
// Returns:
//   - resolver: Resolver backed by deposit.
func NewDepositResolver(
	deposit *sr.Deposit,
) *DepositResolver {
	return &DepositResolver{
		Deposit: deposit,
	}
}

unstaked_position.gno

package staker

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

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

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

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

// UnstakedPositions manages exit checkpoints.
type UnstakedPositions struct {
	tree *bptree.BPTree
}

// NewUnstakedPositions creates a new UnstakedPositions instance.
//
// Returns:
//   - *UnstakedPositions: Empty exit-checkpoint manager backed by a new B+ tree.
func NewUnstakedPositions() *UnstakedPositions {
	return &UnstakedPositions{
		tree: sr.NewBPTreeN(16), // positionId -> *UnstakedPosition
	}
}

// Has checks if a position ID has an exit checkpoint.
//
// Parameters:
//   - positionId: Position ID whose exit-checkpoint membership is checked.
//
// Returns:
//   - bool: true when an exit checkpoint exists for positionId; false otherwise.
func (self *UnstakedPositions) Has(positionId uint64) bool {
	return self.tree.Has(utils.EncodeUint64(positionId))
}

// get retrieves an exit checkpoint by position ID, or nil when there is none.
func (self *UnstakedPositions) get(positionId uint64) *sr.UnstakedPosition {
	value := self.tree.Get(utils.EncodeUint64(positionId))
	if value == nil {
		return nil
	}

	position, ok := value.(*sr.UnstakedPosition)
	if !ok {
		panic(ufmt.Sprintf("failed to cast value to *UnstakedPosition: %T", value))
	}

	return position
}

// set stores an exit checkpoint for a position ID.
func (self *UnstakedPositions) set(positionId uint64, position *sr.UnstakedPosition) {
	self.tree.Set(utils.EncodeUint64(positionId), position)
}

// remove deletes an exit checkpoint by position ID.
func (self *UnstakedPositions) remove(positionId uint64) {
	self.tree.Remove(utils.EncodeUint64(positionId))
}

// getUnstakedPositions returns the exit checkpoints backed by the store.
func (s *stakerV1) getUnstakedPositions() *UnstakedPositions {
	return &UnstakedPositions{tree: s.store.GetUnstakedPositions()}
}

// uncollectedIncentiveCountOf returns how many checkpoints still owe the incentive.
//
// The count is per incentive, not per pool: one checkpoint that can never be funded would
// otherwise lock the refunds of every other incentive in the same pool.
func (s *stakerV1) uncollectedIncentiveCountOf(incentiveId string) int64 {
	value := s.store.GetUncollectedIncentiveCounts().Get(incentiveId)
	if value == nil {
		return 0
	}

	count, ok := value.(int64)
	if !ok {
		panic(ufmt.Sprintf("failed to cast uncollected incentive count to int64: %T", value))
	}

	return count
}

// addUncollectedIncentiveCount moves the incentive's count by delta, dropping the entry at zero.
func (s *stakerV1) addUncollectedIncentiveCount(incentiveId string, delta int64) {
	addUncollectedIncentiveCountTo(s.store.GetUncollectedIncentiveCounts(), incentiveId, delta)
}

func addUncollectedIncentiveCountTo(counts *bptree.BPTree, incentiveId string, delta int64) {
	count := int64(0)
	if value := counts.Get(incentiveId); value != nil {
		casted, ok := value.(int64)
		if !ok {
			panic(ufmt.Sprintf("failed to cast uncollected incentive count to int64: %T", value))
		}
		count = casted
	}

	next := gnsmath.SafeAddInt64(count, delta)
	if next < 0 {
		panic(makeErrorWithDetails(
			errCalculationError,
			ufmt.Sprintf("uncollected count of incentive(%s) went negative", incentiveId),
		))
	}

	if next == 0 {
		counts.Remove(incentiveId)
		return
	}

	counts.Set(incentiveId, next)
}

// recordUnstakedPosition writes the exit checkpoint before the teardown touches the pool.
// The deposit's incentive index is brought up to date first, so the checkpoint owes exactly
// the incentives the position accrued from.
func (s *stakerV1) recordUnstakedPosition(_ int, rlm realm, positionId uint64, deposit *sr.Deposit, exitTime int64) *sr.UnstakedPosition {
	poolPath := deposit.TargetPoolPath()

	pool, ok := s.getPools().Get(poolPath)
	if !ok {
		panic(makeErrorWithDetails(
			errDataNotFound,
			ufmt.Sprintf("pool(%s) does not exist", poolPath),
		))
	}

	poolResolver := NewPoolResolver(pool)
	depositResolver := NewDepositResolver(deposit)

	lastUpdatedAt := depositResolver.LastExternalIncentiveUpdatedAt()
	if lastUpdatedAt < exitTime {
		poolResolver.IncentivesResolver().IterateIncentiveIdsByTime(lastUpdatedAt, exitTime, func(incentiveId string) bool {
			deposit.AddExternalIncentiveId(incentiveId)
			return false
		})
		deposit.SetLastExternalIncentiveUpdatedAt(exitTime)
	}

	tier, tierRatio, tierCount, err := s.getPoolTier().tierContextOf(poolPath)
	if err != nil {
		panic(err)
	}

	lowerTick := poolResolver.GetOrNewTick(deposit.TickLower())
	upperTick := poolResolver.GetOrNewTick(deposit.TickUpper())
	incentiveIds := deposit.GetExternalIncentiveIdList()

	position := sr.NewUnstakedPosition(
		deposit,
		exitTime,
		poolResolver.CurrentTick(exitTime),
		lowerTick,
		upperTick,
		NewTickResolver(lowerTick).CurrentOutsideAccumulation(exitTime).ToString(),
		NewTickResolver(upperTick).CurrentOutsideAccumulation(exitTime).ToString(),
		tier,
		tierRatio,
		tierCount,
		s.GetUnstakingFee(),
		incentiveIds,
	)

	s.getUnstakedPositions().set(positionId, position)

	counts := s.store.GetUncollectedIncentiveCounts()
	for _, incentiveId := range incentiveIds {
		addUncollectedIncentiveCountTo(counts, incentiveId, 1)
	}

	return position
}

// dropUnstakedPositionIfCollected removes the checkpoint once every reward source is collected.
func (s *stakerV1) dropUnstakedPositionIfCollected(_ int, rlm realm, target *collectTarget) {
	if !target.checkpoint.FullyCollected() {
		return
	}

	s.getUnstakedPositions().remove(target.positionId)

	previousRealm := rlm.Previous()
	chain.Emit(
		"ClearUnstakedPosition",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"positionId", utils.FormatUint(target.positionId),
		"poolPath", target.deposit.TargetPoolPath(),
		"exitTime", utils.FormatInt(target.checkpoint.ExitTime()),
		"currentTime", utils.FormatInt(time.Now().Unix()),
		"currentHeight", utils.FormatInt(runtime.ChainHeight()),
	)
}

// HasUnstakedPosition reports whether a position is staked no longer but still has uncollected rewards.
//
// Parameters:
//   - positionId: Position ID whose exit-checkpoint membership is checked.
//
// Returns:
//   - bool: true when positionId has an exit checkpoint; false otherwise.
func (s *stakerV1) HasUnstakedPosition(positionId uint64) bool {
	return s.getUnstakedPositions().Has(positionId)
}

// GetUnstakedPositionExitTime returns when an unstaked position stopped accruing rewards.
//
// Parameters:
//   - positionId: Position ID whose exit checkpoint is queried.
//
// Returns:
//   - int64: Exit timestamp in Unix seconds.
//   - error: Non-nil when positionId has no uncollected exit checkpoint; nil on success.
func (s *stakerV1) GetUnstakedPositionExitTime(positionId uint64) (int64, error) {
	position := s.getUnstakedPositions().get(positionId)
	if position == nil {
		return 0, ufmt.Errorf("%v: positionId(%d) has no uncollected reward", errDataNotFound, positionId)
	}

	return position.ExitTime(), nil
}

// GetUnstakedPositionPendingIncentives returns the incentives an unstaked position has yet to
// collect.
//
// Parameters:
//   - positionId: Position ID whose pending incentive IDs are queried.
//
// Returns:
//   - []string: External incentive IDs with rewards still pending for the checkpoint.
//   - error: Non-nil when positionId has no uncollected exit checkpoint; nil on success.
func (s *stakerV1) GetUnstakedPositionPendingIncentives(positionId uint64) ([]string, error) {
	position := s.getUnstakedPositions().get(positionId)
	if position == nil {
		return nil, ufmt.Errorf("%v: positionId(%d) has no uncollected reward", errDataNotFound, positionId)
	}

	return position.PendingIncentiveIdList(), nil
}

// GetUncollectedIncentiveCount returns how many unstaked positions still owe a reward from the
// incentive; EndExternalIncentive is refused while it is non-zero.
//
// Parameters:
//   - incentiveId: External incentive identifier whose outstanding checkpoint count is queried.
//
// Returns:
//   - int64: Number of exit checkpoints still owing incentiveId; zero permits incentive finalization.
func (s *stakerV1) GetUncollectedIncentiveCount(incentiveId string) int64 {
	return s.uncollectedIncentiveCountOf(incentiveId)
}

utils.gno

package staker

import (
	"errors"
	"strconv"
	"strings"

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

// poolPathDivide splits a pool path into token addresses and fee tier.
func poolPathDivide(poolPath string) (string, string, string) {
	res := strings.Split(poolPath, ":")
	if len(res) != 3 {
		panic(errors.New(errInvalidPoolPath))
	}

	pToken0, pToken1, fee := res[0], res[1], res[2]
	return pToken0, pToken1, fee
}

// positionIdFrom converts a uint64 position ID to grc721.TokenID.
func positionIdFrom(positionId uint64) grc721.TokenID {
	return grc721.TokenID(strconv.FormatUint(positionId, 10))
}

// contains checks if a string exists in a slice.
func contains(slice []string, item string) bool {
	// We can use strings.EqualFold here, but this function should be case-sensitive.
	// So, it is better to compare strings directly.
	for _, element := range slice {
		if element == item {
			return true
		}
	}
	return false
}