Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

v1 source realm

package staker manages liquidity mining rewards for GnoSwap positions.

Readme View source

Staker

Liquidity mining and reward distribution for LP positions.

Overview

Staker manages distribution of internal (GNS emission) and external (caller-funded) rewards to staked LP positions, with time-weighted rewards and warmup periods.

Configuration

  • Deposit GNS Amount: 100,000 GNS per external incentive (default; governance-adjustable)
  • Minimum Reward Amount: 1,000 token units (default for external incentive creation)
  • Unstaking Fee: 1% default (100 basis points; configurable from 0 to 10%)
  • Internal Pool Tiers: 1, 2, or 3 (assigned per pool); external-only pools can also be stakeable
  • Warmup Schedule: 30/50/70/100% over default cumulative windows of 0-5, 5-15, 15-45, and 45+ days
  • External Token Policy: Approved reward tokens; pool-pair tokens are also accepted for their own pool unless explicitly denied
  • External Incentive Start: UTC midnight, from the first eligible start (at least 24 hours after creation) through 7 days later

Core Features

Internal Rewards (GNS Emission)

  • Allocated to tiered pools (tiers 1, 2, 3)
  • Split across tiers by TierRatio
  • Distributed proportionally to in-range liquidity
  • Unclaimed rewards go to community pool

External Rewards (Caller-Funded Incentives)

  • Created for specific pools by any caller that satisfies the token, duration, start-time, reward-minimum, and GNS-deposit checks
  • Constant reward per second over the configured incentive window; the stored rate is Q128-scaled as (rewardAmount << 128) / duration
  • Proportional to staked liquidity
  • EndExternalIncentive is creator/admin-only and sends only the unclaimable/remainder portion plus the GNS deposit to its explicit refundAddress; rewards still owed by live positions remain claimable
  • Accumulated warmup penalties are collected separately through CollectExternalIncentivePenalty after EndExternalIncentive

Warmup Periods

Every staked position progresses through warmup periods. The default finite durations are 5, 10, and 30 days, followed by a final math.MaxInt64 tier:

  • 0-5 days: 30% of the calculated reward
  • 5-15 days: 50% of the calculated reward
  • 15-45 days: 70% of the calculated reward
  • 45+ days: 100% of the calculated reward

Governance may change the finite durations. Warmup ratios are applied before the staking-reward fee: internal GNS penalties go to the community pool, while external penalties accumulate on the incentive and are collected separately to an explicit address after EndExternalIncentive.

Key Functions

StakeToken

Stakes LP position NFT to earn rewards.

UnStakeToken

Unstakes the position and creates an exit checkpoint. It returns the NFT and the staked pool path without collecting rewards; use a Collect* entry point afterward.

CollectReward

Collects accumulated rewards for a live staked position or an exit checkpoint. Live collection requires the depositor/owner; checkpoint collection is permissionless and pays its pinned owner.

CreateExternalIncentive

Creates an external reward program for a specific pool. Creation is permissionless after all reward-token allowlist/denial, duration, start-time, reward-minimum, and GNS-deposit checks pass.

EndExternalIncentive

Ends an incentive after its end timestamp and finalizes its refundable unclaimable/remainder amount. The reward tokens and GNS deposit are sent to the caller-supplied refundAddress; only the creator or admin may call it, and an outstanding exit checkpoint for that incentive blocks ending.

CollectExternalIncentivePenalty

Collects accumulated warmup penalties for an incentive after EndExternalIncentive has finalized it, sending the penalty to the caller-supplied refundAddress. Only the creator or admin may call.

CancelExternalIncentive

Removes a not-yet-started incentive and refunds its reward tokens and GNS deposit to the creator. Callable by admin, governance, or the creator; the reward-token refund is capped by the staker balance.

Reward Calculation Logic

Tier Ratio Distribution

Emission split across tiers based on active pools:

If only tier 1 has pools:    [100%, 0%, 0%]
If tiers 1 & 3 have pools:   [80%, 0%, 20%]
If tiers 1 & 2 have pools:   [70%, 30%, 0%]
If all tiers have pools:     [50%, 30%, 20%]

Mathematical representation:

TierRatio(t) =
  [100, 0, 0]  if Count(2) = 0 ∧ Count(3) = 0
  [80, 0, 20]  if Count(2) = 0
  [70, 30, 0]  if Count(3) = 0
  [50, 30, 20] otherwise

Pool Reward Formula

poolReward(pool) = (emission × TierRatio[tier(pool)] / 100) / Count(tier(pool))

Where emission is calculated as:

emission = GetStakerEmissionAmountPerSecond()

Position Reward Calculation

The reward for each position is calculated through:

  1. Resolve the persisted/halving per-second reward schedule (read-only)
  2. Retrieve position state from deposit records or an exit checkpoint
  3. Calculate internal rewards if the pool has an internal tier
  4. Calculate external rewards for the incentive IDs
  5. Apply warmup ratios and penalties based on stake duration

Collection may separately advance reward caches and persist newly discovered incentive IDs; the read-only calculation itself does not write those caches.

Mathematical formula for total reward ratio:

TotalRewardRatio(s,e) = Σ[i=0 to m-1] ΔRaw(αᵢ, βᵢ) × rᵢ

where:
  αᵢ = max(s, Hᵢ₋₁)
  βᵢ = min(e, Hᵢ)
  
ΔRaw(a, b) = CalcRaw(b) - CalcRaw(a)

CalcRaw(h) = 
  L(h) - U(h)           if tick(h) < ℓ
  U(h) - L(h)           if tick(h) ≥ u
  G(h) - (L(h) + U(h))  otherwise

where:
  L(h) = tickLower.OutsideAccumulation(h)
  U(h) = tickUpper.OutsideAccumulation(h)
  G(h) = globalRewardRatioAccumulation(h)
  ℓ = tickLower.id
  u = tickUpper.id

Final position reward:

finalReward = TotalRewardRatio × poolReward × positionLiquidity
            = ∫[s to e] (poolReward × positionLiquidity) / TotalStakedLiquidity(h) dh

Tick Cross Hook

When price crosses an initialized tick with staked positions:

  1. Updates staked liquidity - Adjusts total staked liquidity
  2. Updates reward accumulation - Recalculates globalRewardRatioAccumulation
  3. Manages unclaimable periods - Starts/ends periods with no in-range liquidity
  4. Updates tick accumulation - Adjusts CurrentOutsideAccumulation

The globalRewardRatioAccumulation tracks the integral:

globalRewardRatioAccumulation = ∫ 1/TotalStakedLiquidity(h) dh

This integral is only computed when TotalStakedLiquidity(h) ≠ 0, enabling precise reward calculation even as liquidity changes.

Reward State Tracking

The system maintains:

  • Global accumulation: Tracks reward ratio across all positions
  • Tick accumulation: Tracks rewards "outside" each tick
  • Position state: Individual reward calculation parameters

Approval Requirements

  • StakeToken moves the position NFT to the staker realm through gnft.TransferFrom, so the caller must approve the staker on that NFT first with gnft.Approve(cross(cur), stakerAddress, positionId), or grant gnft.SetApprovalForAll(cross(cur), stakerAddress, true).
  • CreateExternalIncentive pulls two amounts into the staker realm: the reward token amount and the GNS deposit. Approve the staker realm for both token contracts before calling.
  • UnStakeToken, the reward-collection functions, EndExternalIncentive, and CancelExternalIncentive pay out to the caller or to a supplied address and require no approval.
1// Approve the staker on the position NFT, then stake
2stakerAddress := access.MustGetAddress(prabc.ROLE_STAKER.String())
3gnft.Approve(cross(cur), stakerAddress, grc721.TokenID("123"))
4StakeToken(cross(cur), 123, "")
5
6// GNS pays both the external reward and the required deposit
7gns.Approve(cross(cur), stakerAddress, 1_000_000_000+GetDepositGnsAmount())

Usage

The proxy functions receive a realm argument. From a caller realm with cur realm, pass cross(cur) as that first argument:

 1// Stake an existing position
 2StakeToken(cross(cur), 123, "g1referrer...")
 3
 4// Create an external incentive (rewardAmount is an int64 token-unit amount)
 5CreateExternalIncentive(
 6    cross(cur),
 7    "gno.land/r/gnoland/wugnot.wugnot:gno.land/r/gnoswap/gns.GNS:3000",
 8    "gno.land/r/gnoswap/gns.GNS",
 9    1_000_000_000,
10    startTime,
11    endTime,
12)
13
14// Collect while the position is staked
15CollectReward(cross(cur), 123)
16
17// Unstake: this returns the NFT and creates an exit checkpoint; it does not collect
18UnStakeToken(cross(cur), 123)
19
20// Collect the checkpoint, either per source or all at once
21CollectEmissionReward(cross(cur), 123)
22CollectExternalIncentiveReward(cross(cur), 123, incentiveId)
23
24// End an incentive after its end timestamp, then collect accumulated penalties
25EndExternalIncentive(cross(cur), poolPath, incentiveId, refundAddress)
26CollectExternalIncentivePenalty(cross(cur), poolPath, incentiveId, refundAddress)

Security

  • Positions locked during staking
  • External incentive creation is permissionless after validation
  • External incentives require GNS deposit
  • Warmup periods prevent gaming
  • Unclaimed rewards properly redirected
  • Hook integration ensures accurate tracking

Overview

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.

Constants 5

Functions 14

func TierRatioFromCounts

Action
1func TierRatioFromCounts(tier1Count, tier2Count, tier3Count uint64) sr.TierRatio
source

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 NewDepositResolver

Action
1func NewDepositResolver(
2	deposit *sr.Deposit,
3) *DepositResolver
source

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 NewDeposits

Action
1func NewDeposits() *Deposits
source

NewDeposits creates a new Deposits instance.

Returns:

  • deposits: Empty deposit collection backed by a position-ID tree.

func NewExternalIncentiveResolver

Action
1func NewExternalIncentiveResolver(
2	externalIncentive *sr.ExternalIncentive,
3) *ExternalIncentiveResolver
source

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 NewExternalIncentives

Action
1func NewExternalIncentives() *ExternalIncentives
source

NewExternalIncentives creates a new ExternalIncentives instance.

Returns:

  • incentives: Empty external-incentive collection backed by an incentive-ID tree.

func NewIncentivesResolver

Action
1func NewIncentivesResolver(incentives *sr.Incentives) *IncentivesResolver
source

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 NewPoolResolver

Action
1func NewPoolResolver(pool *sr.Pool) *PoolResolver
source

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 NewPoolTier

Action
1func NewPoolTier(pools *Pools, currentTime int64, initialPoolPath string, getEmission func() (int64, error), getHalvingBlocksInRange func(start, end int64) ([]int64, []int64, error)) *PoolTier
source

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 NewPoolTierBy

Action
1func NewPoolTierBy(
2	membership *bptree.BPTree,
3	tierRatio sr.TierRatio,
4	counts [AllTierCount]uint64,
5	lastRewardCacheTimestamp int64,
6	currentEmission int64,
7	getEmission func() (int64, error),
8	getHalvingBlocksInRange func(start, end int64) ([]int64, []int64, error),
9) *PoolTier
source

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 NewPools

Action
1func NewPools() *Pools
source

NewPools creates an empty resolver for global pool storage.

Returns:

  • pools: Pools resolver backed by a new B+ tree keyed by pool path.

func NewTickResolver

Action
1func NewTickResolver(tick *sr.Tick) *TickResolver
source

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 NewUnstakedPositions

Action
1func NewUnstakedPositions() *UnstakedPositions
source

NewUnstakedPositions creates a new UnstakedPositions instance.

Returns:

  • *UnstakedPositions: Empty exit-checkpoint manager backed by a new B+ tree.

func NewStakerV1

Action
1func NewStakerV1(stakerStore sr.IStakerStore, poolAccessor sr.PoolAccessor, emissionAccessor sr.EmissionAccessor, nftAccessor sr.NFTAccessor) *stakerV1
source

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 NewTickCrossEventInfo

Action
1func NewTickCrossEventInfo(tickID int32, stakedLiquidityGross *u256.Uint, stakedLiquidityDelta *i256.Int, outsideAccumulation *u256.Uint) *tickCrossEventInfo
source

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.

Types 12

type DepositResolver

struct
1type DepositResolver struct {
2	*sr.Deposit
3}
source

Methods on DepositResolver

func CollectedExternalReward

method on DepositResolver
1func (self *DepositResolver) CollectedExternalReward(incentiveID string) int64
source

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 ExternalRewardLastCollectTime

method on DepositResolver
1func (self *DepositResolver) ExternalRewardLastCollectTime(incentiveID string) int64
source

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 FindWarmup

method on DepositResolver
1func (self *DepositResolver) FindWarmup(currentTime int64) int
source

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 GetWarmup

method on DepositResolver
1func (self *DepositResolver) GetWarmup(index int) sr.Warmup
source

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 InternalRewardLastCollectTime

method on DepositResolver
1func (self *DepositResolver) InternalRewardLastCollectTime() int64
source

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.

type Deposits

struct
1type Deposits struct {
2	tree *bptree.BPTree
3}
source

Deposits manages all staked positions.

Methods on Deposits

func Has

method on Deposits
1func (self *Deposits) Has(positionId uint64) bool
source

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 Iterate

method on Deposits
1func (self *Deposits) Iterate(start uint64, end uint64, fn func(positionId uint64, deposit *sr.Deposit) bool)
source

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 IterateByPoolPath

method on Deposits
1func (self *Deposits) IterateByPoolPath(start, end uint64, poolPath string, fn func(positionId uint64, deposit *sr.Deposit) bool)
source

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 Size

method on Deposits
1func (self *Deposits) Size() int
source

Size returns the number of deposits.

Returns:

  • size: Number of deposits currently stored.

type ExternalIncentiveResolver

struct
1type ExternalIncentiveResolver struct {
2	*sr.ExternalIncentive
3}
source

Methods on ExternalIncentiveResolver

func IsEnded

method on ExternalIncentiveResolver
1func (self *ExternalIncentiveResolver) IsEnded(currentTimestamp int64) bool
source

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 IsStarted

method on ExternalIncentiveResolver
1func (self *ExternalIncentiveResolver) IsStarted(currentTimestamp int64) bool
source

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.

type ExternalIncentives

struct
1type ExternalIncentives struct {
2	tree *bptree.BPTree
3}
source

ExternalIncentives manages external incentive programs.

Methods on ExternalIncentives

func Has

method on ExternalIncentives
1func (self *ExternalIncentives) Has(incentiveId string) bool
source

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 Size

method on ExternalIncentives
1func (self *ExternalIncentives) Size() int
source

Size returns the number of external incentives.

Returns:

  • size: Number of external incentives currently stored.

type IncentivesResolver

struct
1type IncentivesResolver struct {
2	*sr.Incentives
3}
source

Methods on IncentivesResolver

func Get

method on IncentivesResolver
1func (self *IncentivesResolver) Get(incentiveId string) (*sr.ExternalIncentive, bool)
source

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 GetIncentiveResolver

method on IncentivesResolver
1func (self *IncentivesResolver) GetIncentiveResolver(incentiveId string) (*ExternalIncentiveResolver, bool)
source

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.

type PoolResolver

struct
1type PoolResolver struct {
2	*sr.Pool
3
4	// exit is set only when collecting an exit checkpoint, and overrides the pool reads that
5	// would otherwise come from state the position no longer takes part in.
6	exit *sr.UnstakedPosition
7}
source

Methods on PoolResolver

func CalculateRawRewardForPosition

method on PoolResolver
1func (self *PoolResolver) CalculateRawRewardForPosition(currentTime int64, currentTick int32, deposit *sr.Deposit) *u256.Uint
source

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 CurrentGlobalRewardRatioAccumulation

method on PoolResolver
1func (self *PoolResolver) CurrentGlobalRewardRatioAccumulation(currentTime int64) (time int64, acc string)
source

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 CurrentReward

method on PoolResolver
1func (self *PoolResolver) CurrentReward(currentTime int64) (reward int64)
source

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 CurrentStakedLiquidity

method on PoolResolver
1func (self *PoolResolver) CurrentStakedLiquidity(currentTime int64) (liquidity *u256.Uint)
source

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 CurrentTick

method on PoolResolver
1func (self *PoolResolver) CurrentTick(currentTime int64) (tick int32)
source

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 GetOrNewTick

method on PoolResolver
1func (self *PoolResolver) GetOrNewTick(tickId int32) *sr.Tick
source

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 IncentivesResolver

method on PoolResolver
1func (self *PoolResolver) IncentivesResolver() *IncentivesResolver
source

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 IsExternallyIncentivizedPool

method on PoolResolver
1func (self *PoolResolver) IsExternallyIncentivizedPool() bool
source

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 RewardStateOf

method on PoolResolver
1func (self *PoolResolver) RewardStateOf(deposit *sr.Deposit) *RewardState
source

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.

type PoolTier

struct
 1type PoolTier struct {
 2	membership *bptree.BPTree // poolPath -> tier(1, 2, 3)
 3
 4	tierRatio sr.TierRatio
 5
 6	counts [AllTierCount]uint64
 7
 8	lastRewardCacheTimestamp int64
 9
10	currentEmission int64
11
12	// returns current emission.
13	getEmission func() (int64, error)
14	// Returns a list of halving timestamps and their emission amounts within the interval [start, end) in ascending order.
15	// The first return value is a list of timestamps where halving occurs.
16	// The second return value is a list of emission amounts corresponding to each halving timestamp.
17	getHalvingBlocksInRange func(start, end int64) ([]int64, []int64, error)
18}
source

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.

Methods on PoolTier

func CurrentAllTierCounts

method on PoolTier
1func (self *PoolTier) CurrentAllTierCounts() []uint64
source

CurrentAllTierCounts returns the current count of pools in each tier. Returns:

  • []uint64: Snapshot of pool counts for tier indexes 0 through AllTierCount-1.

func CurrentCount

method on PoolTier
1func (self *PoolTier) CurrentCount(tier uint64) int
source

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 CurrentReward

method on PoolTier
1func (self *PoolTier) CurrentReward(tier uint64) (int64, error)
source

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 CurrentTier

method on PoolTier
1func (self *PoolTier) CurrentTier(poolPath string) (tier uint64)
source

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 IsInternallyIncentivizedPool

method on PoolTier
1func (self *PoolTier) IsInternallyIncentivizedPool(poolPath string) bool
source

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.

type Pools

struct
1type Pools struct {
2	tree *bptree.BPTree // string poolPath -> pool
3}
source

Pools represents the global pool storage

Methods on Pools

func Get

method on Pools
1func (self *Pools) Get(poolPath string) (*sr.Pool, bool)
source

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 GetPoolOrNil

method on Pools
1func (self *Pools) GetPoolOrNil(poolPath string) *sr.Pool
source

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 Has

method on Pools
1func (self *Pools) Has(poolPath string) bool
source

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 IterateAll

method on Pools
1func (self *Pools) IterateAll(fn func(key string, pool *sr.Pool) bool)
source

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.

type Reward

struct
1type Reward struct {
2	Internal        int64
3	InternalPenalty int64
4	External        map[string]int64 // Incentive ID -> TokenAmount
5	ExternalPenalty map[string]int64 // Incentive ID -> TokenAmount
6}
source

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 RewardState

struct
1type RewardState struct {
2	pool    *PoolResolver
3	deposit *DepositResolver
4
5	// accumulated rewards for each warmup
6	rewards   []int64
7	penalties []int64
8}
source

RewardState is a struct for storing the intermediate state for reward calculation.

type TickResolver

struct
1type TickResolver struct {
2	*sr.Tick
3}
source

Methods on TickResolver

func CurrentOutsideAccumulation

method on TickResolver
1func (self *TickResolver) CurrentOutsideAccumulation(timestamp int64) *u256.Uint
source

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.

type UnstakedPositions

struct
1type UnstakedPositions struct {
2	tree *bptree.BPTree
3}
source

UnstakedPositions manages exit checkpoints.

Methods on UnstakedPositions

func Has

method on UnstakedPositions
1func (self *UnstakedPositions) Has(positionId uint64) bool
source

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.

Imports 28

Source Files 28