staker source realm
Package staker manages liquidity mining rewards for GnoSwap positions.
View source
Staker
Liquidity mining and reward distribution for LP positions.
Overview
Staker manages distribution of internal (GNS emission) and external (user-provided) rewards to staked LP positions, with time-weighted rewards and warmup periods.
Gnoweb
The root Render("") delegates to the active implementation and shows realm identity, the halt flag, stored record counts, cumulative GNS emissions, the cached emission rate, incentive requirements, tier allocations, unstaking fees, and warmup stages.
GNS amounts use six-decimal base units; external rewards use their token's base units. Warmup durations are per-stage seconds, with the final stage shown as unbounded. Rendering reads stored counts and fixed configuration without traversing positions or incentives. Unsupported paths return 404.
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
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 (User Incentives)
- Created for specific pools
- Constant reward per second over the incentive window; the stored rate is Q128-scaled as
(rewardAmount << 128) / duration - Proportional to staked liquidity
EndExternalIncentivereturns only the unclaimable/remainder portion and GNS deposit to its explicit refund address; rewards still owed by live positions remain claimable
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 a position and records an exit checkpoint for its rewards. It neither calculates nor pays them: withdrawing must never depend on the reward side.
CollectReward
Collects accumulated rewards. Takes a position that was unstaked without collecting as well as a
staked one, so withdrawing is UnStakeToken plus one collect. A collect on an unstaked position
is permissionless, since it can only ever pay that position's owner.
CreateExternalIncentive
Creates an external reward program for a specific pool. Any caller may create one after satisfying the reward-token allowlist/denial, duration, start-time, reward-minimum, and GNS-deposit checks.
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.
CancelExternalIncentive
Removes an incentive that has not started 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 balance held by the staker.
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))
Here emission is the already-allocated per-second GNS amount returned by the emission module
for liquidity stakers. It is split by the tier percentage and then divided among pools in that
tier:
emission = GetStakerEmissionAmountPerSecond()
Position Reward Calculation
The reward for each position is calculated through:
- Resolve the persisted/halving per-second reward schedule (read-only)
- Retrieve position state from deposit records or an exit checkpoint
- Calculate internal rewards if the pool has an internal tier
- Calculate external rewards for the incentive IDs
- 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:
- Updates staked liquidity - Adjusts total staked liquidity
- Updates reward accumulation - Recalculates
globalRewardRatioAccumulation - Manages unclaimable periods - Starts/ends periods with no in-range liquidity
- 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
StakeTokenmoves the position NFT to the staker realm throughgnft.TransferFrom, so the caller must approve the staker on that NFT first withgnft.Approve(cross(cur), stakerAddress, positionId), or grantgnft.SetApprovalForAll(cross(cur), stakerAddress, true).CreateExternalIncentivepulls 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, andCancelExternalIncentivepay 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)
Security
- Positions locked during staking
- External incentives require GNS deposit
- Warmup periods prevent gaming
- Unclaimed rewards properly redirected
- Hook integration ensures accurate tracking
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.
4
const AllTierCount
const ErrSpoofedRealm
const StoreKeyDepositGnsAmount, StoreKeyMinimumRewardAmount, StoreKeyDeposits, StoreKeyExternalIncentives, StoreKeyTotalEmissionSent, StoreKeyAllowedTokens, StoreKeyDeniedRewardTokens, StoreKeyIncentiveCounter, StoreKeyTokenSpecificMinimumRewards, StoreKeyUnstakingFee, StoreKeyPendingProtocolFees, StoreKeyUnstakedPositions, StoreKeyUncollectedIncentiveCounts, StoreKeyPools, StoreKeyPoolTierMemberships, StoreKeyPoolTierRatio, StoreKeyPoolTierCounts, StoreKeyPoolTierLastRewardCacheTimestamp, StoreKeyPoolTierCurrentEmission, StoreKeyPoolTierGetEmission, StoreKeyPoolTierGetHalvingBlocksInRange, StoreKeyWarmupTemplate, StoreKeyCurrentSwapBatch
1const (
2 StoreKeyDepositGnsAmount StoreKey = "depositGnsAmount"
3 StoreKeyMinimumRewardAmount StoreKey = "minimumRewardAmount"
4 StoreKeyDeposits StoreKey = "deposits"
5 StoreKeyExternalIncentives StoreKey = "externalIncentives"
6 StoreKeyTotalEmissionSent StoreKey = "totalEmissionSent"
7 StoreKeyAllowedTokens StoreKey = "allowedTokens"
8 StoreKeyDeniedRewardTokens StoreKey = "deniedRewardTokens"
9 StoreKeyIncentiveCounter StoreKey = "incentiveCounter"
10 StoreKeyTokenSpecificMinimumRewards StoreKey = "tokenSpecificMinimumRewards"
11 StoreKeyUnstakingFee StoreKey = "unstakingFee"
12 StoreKeyPendingProtocolFees StoreKey = "pendingProtocolFees"
13 StoreKeyUnstakedPositions StoreKey = "unstakedPositions"
14 StoreKeyUncollectedIncentiveCounts StoreKey = "uncollectedIncentiveCounts"
15 StoreKeyPools StoreKey = "pools"
16 StoreKeyPoolTierMemberships StoreKey = "poolTierMemberships"
17 StoreKeyPoolTierRatio StoreKey = "poolTierRatio"
18 StoreKeyPoolTierCounts StoreKey = "poolTierCounts"
19 StoreKeyPoolTierLastRewardCacheTimestamp StoreKey = "poolTierLastRewardCacheTimestamp"
20 StoreKeyPoolTierCurrentEmission StoreKey = "poolTierCurrentEmission"
21 StoreKeyPoolTierGetEmission StoreKey = "poolTierGetEmission"
22 StoreKeyPoolTierGetHalvingBlocksInRange StoreKey = "poolTierGetHalvingBlocksInRange"
23 StoreKeyWarmupTemplate StoreKey = "warmupTemplate"
24 StoreKeyCurrentSwapBatch StoreKey = "currentSwapBatch"
25)100
func AddToken
crossing ActionAddToken adds a token to the reward token whitelist.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- tokenPath: Registered token path to add to the allowed reward-token list.
Halt check: reverts while the Staker halt scope is active.
func CancelExternalIncentive
crossing ActionCancelExternalIncentive cancels an external incentive that has not started yet, removing it and refunding the reward tokens and the GNS deposit to the creator. Callable by admin, governance, or the incentive creator.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- targetPoolPath: Pool path containing the incentive.
- incentiveId: Unique incentive identifier to cancel.
Halt check: reverts while the Withdraw halt scope is active.
func ChangePoolTier
crossing ActionChangePoolTier changes the internal GNS emission tier assigned to a pool.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- poolPath: Pool path whose emission tier is changed.
- tier: New tier number from 0 through 3; zero means no internal-emission target.
Halt check: reverts while the Staker halt scope is active.
func CollectEmissionReward
crossing ActionCollectEmissionReward collects only the GNS emission reward for a live staked deposit or an exit checkpoint left by UnStakeToken.
A live-deposit collect requires the depositor/owner. An exit-checkpoint collect is permissionless and pays the owner pinned in the checkpoint.
External incentive rewards keep accruing; collect them with CollectExternalIncentiveReward.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- positionId: Staked position NFT token ID or position with an exit checkpoint.
Returns:
- int64: GNS emission amount sent to the user.
- int64: GNS emission penalty amount sent to the community pool.
Halt check: reverts while the Withdraw halt scope is active.
func CollectExternalIncentivePenalty
crossing Action1func CollectExternalIncentivePenalty(cur realm, targetPoolPath, incentiveId string, refundAddress address) int64CollectExternalIncentivePenalty collects accumulated warm-up penalties after EndExternalIncentive has finalized the incentive, sending them to refundAddress. Only the incentive creator or admin may call it.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- targetPoolPath: Pool path containing the incentive.
- incentiveId: Unique incentive identifier whose penalty is collected.
- refundAddress: Address receiving the collected penalty amount.
Returns:
- int64: Penalty amount transferred, capped by the staker's available reward-token balance.
Halt check: reverts while the Withdraw halt scope is active.
func CollectExternalIncentiveReward
crossing Action1func CollectExternalIncentiveReward(cur realm, positionId uint64, incentiveId string) (int64, int64)CollectExternalIncentiveReward collects one external incentive reward for a live staked deposit or an exit checkpoint left by UnStakeToken.
A live-deposit collect requires the depositor/owner. An exit-checkpoint collect is permissionless and pays the owner pinned in the checkpoint.
The GNS emission reward and every other incentive keep accruing; collect the emission reward with CollectEmissionReward and the other incentives by calling this with their own incentive id.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- positionId: Staked position NFT token ID or position with an exit checkpoint.
- incentiveId: External incentive identifier to collect.
Returns:
- int64: Gross reward amount before the staking-reward fee.
- int64: Penalty amount retained by the incentive.
Halt check: reverts while the Withdraw halt scope is active.
func CollectReward
crossing Action1func CollectReward(cur realm, positionId uint64) (string, string, map[string]int64, map[string]int64)CollectReward collects both the GNS emission and external incentive rewards for a live staked deposit or an exit checkpoint left by UnStakeToken.
A live-deposit collect requires the depositor/owner. An exit-checkpoint collect is permissionless and pays the owner pinned in the checkpoint.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- positionId: Staked position NFT token ID or position with an exit checkpoint.
Returns:
- string: GNS emission amount sent to the user.
- string: GNS emission penalty amount sent to the community pool.
- map[string]int64: Gross external reward amount per reward token, before the staking-reward fee.
- map[string]int64: External penalty amount per reward token.
Halt check: reverts while the Withdraw halt scope is active.
func CollectableEmissionReward
ActionCollectableEmissionReward returns the claimable internal GNS reward for a live staked deposit or an exit checkpoint left by UnStakeToken.
Parameters:
- positionId: staked position NFT token ID or position with an exit checkpoint
Returns:
- amount: claimable internal reward amount
- err: non-nil when positionId cannot be resolved
func CollectableExternalIncentiveReward
Action1func CollectableExternalIncentiveReward(positionId uint64, incentiveId string) (int64, error)CollectableExternalIncentiveReward returns a position's claimable external reward for a live staked deposit or an exit checkpoint left by UnStakeToken.
Parameters:
- positionId: staked position NFT token ID or position with an exit checkpoint
- incentiveId: external incentive identifier
Returns:
- amount: claimable external reward amount
- err: non-nil when the position or incentive cannot be resolved
func CreateExternalIncentive
crossing ActionCreateExternalIncentive creates an external reward incentive for a pool.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- targetPoolPath: Pool path whose liquidity providers will receive the incentive.
- rewardToken: Registered token path used to pay the incentive.
- rewardAmount: Total reward amount deposited, in reward-token units.
- startTimestamp: Incentive start time as an inclusive Unix timestamp.
- endTimestamp: Incentive end time as an inclusive Unix timestamp.
Any caller may create an incentive after satisfying the token, duration, start-time, reward-minimum, and GNS-deposit checks.
Halt check: reverts while the Staker halt scope is active.
func DefaultAllowedTokens
ActionDefaultAllowedTokens returns the token paths accepted by the staker's default configuration.
Returns:
- tokenPaths: Slice containing the GNS and wrapped-GNOT token paths.
func EndExternalIncentive
crossing Action1func EndExternalIncentive(cur realm, targetPoolPath, incentiveId string, refundAddress address)EndExternalIncentive finalizes an external incentive once its end timestamp has passed, sending the unclaimable/remainder reward portion and GNS deposit to the explicit refundAddress. Only the incentive creator or admin may call it; an outstanding exit checkpoint for this incentive must be collected or forfeited first.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- targetPoolPath: Pool path containing the incentive.
- incentiveId: Unique incentive identifier to finalize.
- refundAddress: Address receiving the refundable reward tokens and GNS deposit.
Halt check: reverts while the Withdraw halt scope is active.
func GetAllowedTokens
ActionGetAllowedTokens returns the allowed external incentive tokens.
Returns:
- tokenPaths: Copy of token paths permitted for external incentives.
func GetCreatedHeightOfIncentive
ActionGetCreatedHeightOfIncentive returns an incentive's creation block height.
Parameters:
- poolPath: pool realm path
- incentiveId: external incentive identifier
Returns:
- height: creation block height
- err: non-nil when the incentive cannot be resolved
func GetDeniedRewardTokens
ActionGetDeniedRewardTokens returns the denied external incentive reward tokens.
Returns:
- tokenPaths: Copy of token paths excluded from external incentive rewards.
func GetDepositCollectedExternalReward
ActionGetDepositCollectedExternalReward returns the collected external reward amount of a position.
Parameters:
- lpTokenId: Position NFT token ID whose collected reward should be read.
- incentiveId: External incentive identifier whose collected amount should be read.
Returns:
- amount: External reward amount already recorded as collected for the incentive, in token units.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositCollectedInternalReward
ActionGetDepositCollectedInternalReward returns the collected internal reward amount of a position.
Parameters:
- lpTokenId: Position NFT token ID whose collected internal reward should be read.
Returns:
- amount: Internal GNS reward amount already recorded as collected, in token units.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositExternalIncentiveIdList
ActionGetDepositExternalIncentiveIdList returns external incentive IDs tracked by a deposit.
Parameters:
- lpTokenId: Position NFT token ID whose deposit should be inspected.
Returns:
- incentiveIds: Independent copy of external incentive IDs associated with the deposit.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositExternalRewardLastCollectTimestamp
Action1func GetDepositExternalRewardLastCollectTimestamp(lpTokenId uint64, incentiveId string) (int64, error)GetDepositExternalRewardLastCollectTimestamp returns the last external reward collection time for a position and incentive. For a newly tracked incentive, the value is based on the stake timestamp.
Parameters:
- lpTokenId: Position NFT token ID whose external reward cursor should be read.
- incentiveId: External incentive identifier whose collection cursor should be read.
Returns:
- timestamp: Unix timestamp of the last collection cursor; newly tracked incentives use the deposit's stake time.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositGnsAmount
ActionGetDepositGnsAmount returns the GNS deposit required for each external incentive.
Returns:
- amount: Configured GNS deposit required per external incentive, in token units.
func GetDepositInternalRewardLastCollectTimestamp
ActionGetDepositInternalRewardLastCollectTimestamp returns the last internal reward collection time for a position.
Parameters:
- lpTokenId: Position NFT token ID whose internal reward cursor should be read.
Returns:
- timestamp: Unix timestamp of the deposit's last internal reward collection.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositLiquidity
ActionGetDepositLiquidity returns the liquidity amount of a staked position.
Parameters:
- lpTokenId: Position NFT token ID whose liquidity should be read.
Returns:
- liquidity: Independent uint256 copy of the deposit's liquidity amount.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositLiquidityAsString
ActionGetDepositLiquidityAsString returns the liquidity amount of a staked position as a decimal string.
Parameters:
- lpTokenId: Position NFT token ID whose liquidity should be formatted.
Returns:
- liquidity: Decimal representation of the deposit's uint256 liquidity amount.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositStakeTime
ActionGetDepositStakeTime returns the Unix timestamp at which a position was staked.
Parameters:
- lpTokenId: Position NFT token ID whose stake time should be read.
Returns:
- stakeTime: Unix timestamp recorded when the deposit entered staking.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositTargetPoolPath
ActionGetDepositTargetPoolPath returns the pool path of a staked position.
Parameters:
- lpTokenId: Position NFT token ID whose target pool should be read.
Returns:
- poolPath: Pool path stored on the deposit.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositTickLower
ActionGetDepositTickLower returns the lower tick of a staked position.
Parameters:
- lpTokenId: Position NFT token ID whose lower boundary should be read.
Returns:
- tickLower: Lower price-range tick stored on the deposit.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetDepositTickUpper
ActionGetDepositTickUpper returns the upper tick of a staked position.
Parameters:
- lpTokenId: Position NFT token ID whose upper boundary should be read.
Returns:
- tickUpper: Upper price-range tick stored on the deposit.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetImplementationPackagePath
ActionGetImplementationPackagePath returns the package path of the currently active implementation.
Returns:
- packagePath: package path of the active implementation
func GetIncentiveAccumulatedPenaltyAmount
Action1func GetIncentiveAccumulatedPenaltyAmount(poolPath string, incentiveId string) (int64, error)GetIncentiveAccumulatedPenaltyAmount returns the accumulated warmup penalty amount of an incentive.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- amount: Warmup penalty accumulated from collections for the incentive, in reward-token units.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveCreatedTimestamp
ActionGetIncentiveCreatedTimestamp returns an incentive's creation timestamp.
Parameters:
- poolPath: pool realm path
- incentiveId: external incentive identifier
Returns:
- timestamp: creation Unix timestamp
- err: non-nil when the incentive cannot be resolved
func GetIncentiveDepositGnsAmount
ActionGetIncentiveDepositGnsAmount returns the deposited GNS amount of an incentive.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- amount: GNS deposit locked by the incentive, in token units.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveDistributedRewardAmount
Action1func GetIncentiveDistributedRewardAmount(poolPath string, incentiveId string) (int64, error)GetIncentiveDistributedRewardAmount returns the distributed reward amount of an incentive.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- amount: Reward amount already delivered to positions or refunded at incentive end, in token units.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveEndTimestamp
ActionGetIncentiveEndTimestamp returns the end timestamp of an incentive.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- endTimestamp: Incentive end time as a Unix timestamp.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveRefunded
ActionGetIncentiveRefunded returns whether an incentive has been refunded.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- refunded: True when the incentive has been finalized as refunded; false while it remains open.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveRemainingRewardAmount
ActionGetIncentiveRemainingRewardAmount returns the remaining reward amount of an incentive.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- amount: Mutable reward balance remaining after distributions and refunds, in token units.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveRewardAmount
ActionGetIncentiveRewardAmount returns the remaining reward amount of an incentive, after deliveries and refunds represented by the current incentive state.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- amount: Independent uint256 copy of the incentive's mutable remaining reward amount.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveRewardAmountAsString
ActionGetIncentiveRewardAmountAsString returns the remaining reward amount of an incentive as string.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- amount: Decimal string for the incentive's remaining reward amount after deliveries and refunds.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveRewardPerSecondX128
Action1func GetIncentiveRewardPerSecondX128(poolPath string, incentiveId string) (*u256.Uint, error)GetIncentiveRewardPerSecondX128 returns the reward rate per second of an incentive, expressed as a Q128 fixed-point number (i.e. actual rate = value / 2^128). Callers needing an integer rate can right-shift the result by 128.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- rateX128: Clone of the Q128-scaled reward rate; divide by 2^128 to recover the actual token units per second.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveRewardToken
ActionGetIncentiveRewardToken returns the reward token of an incentive.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- tokenPath: Reward-token path configured for the incentive.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveStartTimestamp
ActionGetIncentiveStartTimestamp returns the start timestamp of an incentive.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- startTimestamp: Incentive start time as a Unix timestamp.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetIncentiveTotalRewardAmount
ActionGetIncentiveTotalRewardAmount returns the total reward amount of an incentive.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- amount: Total reward amount configured when the incentive was created, in token units.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetMinimumRewardAmount
ActionGetMinimumRewardAmount returns the default minimum reward amount required to create an external incentive. A token-specific override may apply.
Returns:
- amount: Default minimum external-incentive reward amount in token units.
func GetMinimumRewardAmountForToken
ActionGetMinimumRewardAmountForToken returns the minimum reward amount for a specific token.
Parameters:
- tokenPath: Token path whose configured minimum-reward override should be read.
Returns:
- amount: Token-specific minimum reward amount when configured, otherwise the default minimum, in token units.
func GetPendingProtocolFees
ActionGetPendingProtocolFees returns the pending protocol fee amount per token path.
Returns:
- fees: Copy of pending protocol-fee amounts keyed by token path, in the corresponding token units.
func GetPoolGlobalRewardRatioAccumulations
ActionGetPoolGlobalRewardRatioAccumulations returns a read-only view of a pool's global reward ratio accumulation, keyed by the encoded block timestamp.
Parameters:
- poolPath: Pool path whose global reward-ratio checkpoints should be read.
Returns:
- accumulations: Read-only tree of timestamp keys to stored accumulation values, or nil when poolPath has no pool.
func GetPoolHistoricalTicks
ActionGetPoolHistoricalTicks returns a read-only view of a pool's historical ticks, keyed by the encoded block timestamp with the int32 tick as the value.
Parameters:
- poolPath: Pool path whose historical tick checkpoints should be read.
Returns:
- ticks: Read-only tree of timestamp keys to int32 ticks, or nil when poolPath has no pool.
func GetPoolIncentives
ActionGetPoolIncentives returns a read-only view of a pool's external incentives, keyed by incentive ID. Reading an entry yields a clone, so the view cannot mutate realm state.
Parameters:
- poolPath: Pool path whose external-incentive records should be read.
Returns:
- incentives: Read-only tree keyed by incentive ID with cloned entries, or nil when poolPath has no pool.
func GetPoolReward
ActionGetPoolReward returns the reward amount for a tier.
Parameters:
- tier: Emission tier identifier for which to retrieve the per-pool reward.
Returns:
- reward: Current per-pool GNS reward rate for tier, in token units per second.
- err: Non-nil when tier is outside the valid range 1 through AllTierCount-1.
func GetPoolRewardCaches
ActionGetPoolRewardCaches returns a read-only view of a pool's reward cache, keyed by the encoded block timestamp. Callers paginate it themselves through IterateByOffset and decode keys with DecodeInt64.
Parameters:
- poolPath: Pool path whose reward-cache checkpoints should be read.
Returns:
- caches: Read-only tree of timestamp keys to cached reward values, or nil when poolPath has no pool.
func GetPoolStakedLiquidity
ActionGetPoolStakedLiquidity returns the current total staked liquidity of a pool.
Parameters:
- poolPath: Pool path whose current staked liquidity should be read.
Returns:
- liquidity: Decimal string containing the pool's total staked liquidity at the current time.
- err: Non-nil when poolPath does not resolve to a pool.
func GetPoolTier
ActionGetPoolTier returns the tier of a pool.
Parameters:
- poolPath: Pool path whose current emission tier should be read.
Returns:
- tier: Current emission tier identifier; zero when the pool has no tier assignment.
func GetPoolTierCount
ActionGetPoolTierCount returns the number of pools in a tier.
Parameters:
- tier: Emission tier identifier to count; tier zero has no pools.
Returns:
- count: Number of pools currently assigned to tier, or zero for tier zero.
func GetPoolTierRatio
ActionGetPoolTierRatio returns the reward ratio of a pool.
Parameters:
- poolPath: Pool path whose current emission tier ratio should be read.
Returns:
- ratio: Stored reward-share ratio for the pool's current tier.
- err: Non-nil when the pool's tier is invalid and has no configured ratio.
func GetPoolsByTier
ActionGetPoolsByTier returns the pool list for a tier.
Parameters:
- tier: Emission tier identifier whose current pool memberships should be listed.
Returns:
- poolPaths: Copy of pool paths currently assigned to tier; tier zero yields an empty list.
- err: Non-nil when the stored tier membership contains an invalid value.
func GetSpecificTokenMinimumRewardAmount
ActionGetSpecificTokenMinimumRewardAmount 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 units, or 0 when no override is configured.
- found: True when tokenPath has an explicit override; false when the default would be used.
func GetTargetPoolPathByIncentiveId
ActionGetTargetPoolPathByIncentiveId returns the pool path for an incentive ID.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- targetPoolPath: Pool path stored on the resolved incentive.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func GetTotalEmissionSent
ActionGetTotalEmissionSent returns the total GNS emission sent.
Returns:
- amount: Cumulative GNS emission amount sent by the staker, in token units.
func GetUncollectedIncentiveCount
ActionGetUncollectedIncentiveCount returns how many unstaked positions still owe a reward from the incentive.
Parameters:
- incentiveId: External incentive identifier whose outstanding exit positions should be counted.
Returns:
- count: Number of unstaked positions with an uncollected reward for incentiveId.
func GetUnstakedPositionExitTime
ActionGetUnstakedPositionExitTime returns the timestamp at which an unstaked position stopped accruing rewards.
Parameters:
- positionId: Position NFT token ID identifying the unstaked exit checkpoint.
Returns:
- exitTime: Unix timestamp pinned as the end of the position's reward-accrual window.
- err: Non-nil when positionId has no unstaked checkpoint with uncollected rewards.
func GetUnstakedPositionPendingIncentives
ActionGetUnstakedPositionPendingIncentives returns the incentives an unstaked position has yet to collect.
Parameters:
- positionId: Position NFT token ID identifying the unstaked exit checkpoint.
Returns:
- incentiveIds: Copy of external incentive IDs still pending for the exit checkpoint.
- err: Non-nil when positionId has no unstaked checkpoint with uncollected rewards.
func GetUnstakingFee
ActionGetUnstakingFee returns the current unstaking fee rate in basis points (0-1,000; 100 = 1%).
Returns:
- feeRate: Current staking-reward fee rate in basis points.
func HasUnstakedPosition
ActionHasUnstakedPosition returns whether a position was unstaked with rewards left to collect.
Parameters:
- positionId: Position NFT token ID to check in the unstaked-position tree.
Returns:
- unstaked: True when positionId has an exit checkpoint awaiting collection; false otherwise.
func IsIncentiveActive
ActionIsIncentiveActive reports whether an unrefunded incentive is active, including both start and end timestamps.
Parameters:
- poolPath: Pool path containing the incentive record.
- incentiveId: External incentive identifier to resolve.
Returns:
- active: True when the current Unix time is within the incentive window and it has not been refunded.
- err: Non-nil when poolPath or incentiveId cannot be resolved.
func IsStaked
ActionIsStaked returns whether a position is staked.
Parameters:
- positionId: Position NFT token ID to check in the active deposit tree.
Returns:
- staked: True when positionId has an active deposit; false for an unstaked or unknown position.
func NewBPTreeN
ActionNewBPTreeN allocates a raw BP-tree under /r/gnoswap/staker's realm context (the realm that declares Pool/Deposit/ExternalIncentive). The tree's PkgID is therefore /r/gnoswap/staker, matching the domain values it stores, so tree.Set leaf-slot writes clear the readonly-taint gate regardless of which realm (staker/v1, mock) calls Set (borrow rule #2 borrows m.Realm to the tree's owning realm). Implementations and mocks must allocate trees that hold /r/gnoswap/staker-declared values through here rather than calling bptree.NewBPTreeN directly in their own realm.
Parameters:
- fanout: Number of child pointers per B+ tree node; controls the tree's branching factor.
Returns:
- tree: Mutable raw B+ tree allocated in the staker realm context.
func RegisterInitializer
crossing Action1func RegisterInitializer(cur realm, initializer func(_ int, rlm realm, stakerStore IStakerStore, poolAccessor PoolAccessor, emissionAccessor EmissionAccessor, nftAccessor NFTAccessor) IStaker)RegisterInitializer registers a new staker implementation version. This function is called by each version (v1, v2, etc.) during initialization to register their implementation with the proxy system.
The initializer function creates a new instance of the implementation using the provided stakerStore interface.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- initializer: Factory callback that receives the internal discriminator, current staker realm, and accessor interfaces, then returns the implementation instance.
Security: Only contracts within the domain path can register initializers. Each package path can only register once to prevent duplicate registrations.
func RemovePoolTier
crossing ActionRemovePoolTier removes a pool from the internal GNS emission tier system.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- poolPath: Pool path to remove from emission-tier membership.
Halt check: reverts while the Staker halt scope is active.
func RemoveToken
crossing ActionRemoveToken removes a token from the reward token whitelist.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- tokenPath: Token path to remove from the allowed reward-token list.
Halt check: reverts while the Staker halt scope is active.
func Render
Render delegates web rendering to the active implementation.
func SetDeniedRewardToken
crossing ActionSetDeniedRewardToken sets or clears the operational deny flag for an external incentive reward token. Pool-pair tokens qualify as reward tokens without the governance allowlist (by design), so this flag is the only lever to stop NEW incentives in a pair token whose issuer turned hostile. Existing incentives and their collection are deliberately unaffected; the ledger-level delivery guard in the implementation bounds their blast radius instead.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- tokenPath: Reward-token path whose deny status is changed.
- denied: True to block new incentives for tokenPath; false to clear that block.
Halt check: reverts while the Staker halt scope is active.
func SetDepositGnsAmount
crossing ActionSetDepositGnsAmount sets the GNS deposit required for each external incentive.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- amount: GNS amount required as the per-incentive deposit.
Halt check: reverts while the Staker halt scope is active.
func SetMinimumRewardAmount
crossing ActionSetMinimumRewardAmount sets the default minimum reward amount required to create an external incentive. A token-specific override may apply.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- amount: Default minimum reward amount, measured in the reward token's units.
Halt check: reverts while the Staker halt scope is active.
func SetPoolTier
crossing ActionSetPoolTier assigns a pool to an internal GNS emission reward tier.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- poolPath: Pool path whose emission tier is assigned.
- tier: Target tier number from 0 through 3; zero removes the pool from emission targeting.
Halt check: reverts while the Staker halt scope is active.
func SetTokenMinimumRewardAmount
crossing ActionSetTokenMinimumRewardAmount sets minimum reward amounts per token.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- paramsStr: Colon-delimited token path and minimum amount (`tokenPath:amount`); amount zero removes the override.
Halt check: reverts while the Staker halt scope is active.
func SetUnStakingFee
crossing ActionSetUnStakingFee sets the unstaking fee rate in basis points (0-1,000; 100 = 1%).
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- fee: Unstaking fee rate in basis points, from 0 through 1,000 inclusive.
Halt check: reverts while the Staker halt scope is active.
func SetWarmUp
crossing ActionSetWarmUp 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 retain math.MaxInt64.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- pct: Warm-up payout percentage selecting one of the 30%, 50%, 70%, or 100% tiers.
- timeDuration: Warm-up duration in Unix seconds for the selected percentage tier; finite tiers are capped at 365 days and the 100% tier uses math.MaxInt64.
Halt check: reverts while the Staker halt scope is active.
func StakeToken
crossing ActionStakeToken stakes a position NFT to earn rewards.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- positionId: LP position NFT token ID to stake.
- referrer: Optional referral address string used for referral tracking.
Returns:
- string: Pool path where the position was staked.
Halt check: reverts while the Staker halt scope is active.
func UnStakeToken
crossing ActionUnStakeToken unstakes a position NFT and creates an exit checkpoint for its rewards.
The NFT is returned to its owner without calculating or paying rewards. Use a Collect* entry point afterward; collection of an exit checkpoint is permissionless and pays its pinned owner.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- positionId: LP position NFT token ID to unstake.
Returns:
- string: Pool path where the position was staked.
Halt check: reverts while the Withdraw halt scope is active.
func UpgradeImpl
crossing ActionUpgradeImpl switches the active staker implementation to a different version. It changes the implementation pointer without transforming persisted state; the selected implementation must understand the existing storage schema.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- packagePath: Registered package path of the implementation to activate.
Security: Only admin or governance can perform upgrades. The new implementation must have been previously registered via RegisterInitializer.
func NewCounter
ActionNewCounter creates a counter initialized at zero.
Returns:
- counter: Counter whose next generated identifier is 1.
func GetDeposit
ActionGetDeposit returns a copy of a staked position's deposit.
Parameters:
- lpTokenId: staked position NFT token ID
Returns:
- deposit: independent deposit copy, or nil when an implementation has no deposit value
- err: implementation resolution error; the current v1 implementation returns not-found for a missing deposit
func NewDeposit
ActionNewDeposit creates a deposit for a staked LP position and initializes its reward cursors and maps.
Parameters:
- owner: Address that owns the staked position.
- targetPoolPath: Pool identifier associated with the position.
- liquidity: LP liquidity amount represented by the position.
- currentTime: Staking and initial reward-cursor time in Unix seconds.
- tickLower: Lower signed tick boundary of the position's range.
- tickUpper: Upper signed tick boundary of the position's range.
- warmups: Warmup schedule to apply to this position's rewards.
Returns:
- deposit: Newly initialized deposit containing the supplied position and warmup state.
func GetExternalIncentiveByPoolPath
ActionGetExternalIncentiveByPoolPath returns all external incentives for a pool.
Parameters:
- poolPath: Pool path whose external incentives should be listed.
Returns:
- incentives: Independent copies of incentives targeting poolPath.
- err: Non-nil when stored incentive data cannot be read or cast.
func NewExternalIncentive
ActionNewExternalIncentive creates a new external incentive
Parameters:
- incentiveId: Unique identifier assigned to the external incentive.
- targetPoolPath: Pool path whose staked positions may receive this incentive.
- rewardToken: Token path of the asset deposited for distribution.
- rewardAmount: Total reward amount, also used as the initial remaining reward balance.
- startTimestamp: Unix timestamp in seconds when reward distribution starts.
- endTimestamp: Unix timestamp in seconds when reward distribution ends; duration is endTimestamp-startTimestamp and must be nonzero for the rate calculation.
- creator: Address that funds the incentive and receives refunds at finalization.
- depositGnsAmount: GNS amount deposited as the incentive's required collateral.
- createdHeight: Block height to record for incentive creation.
- currentTime: Unix timestamp in seconds recorded as the incentive creation time.
Returns:
- incentive: New incentive with a Q128-scaled per-second rate and zeroed distribution, penalty, and unclaimable counters.
func NewStakerStore
ActionNewStakerStore creates a new staker store instance with the provided KV store. This function is used by the upgrade system to create storage instances for each implementation.
Parameters:
- kvStore: Key-value store used for all staker state.
Returns:
- IStakerStore: Store interface backed by the supplied KV store.
func NewIncentives
ActionNewIncentives creates an incentive collection for a pool and starts an open unclaimable period at the current time.
Parameters:
- targetPoolPath: Pool path to associate with the new incentive collection.
Returns:
- incentives: Collection with initialized incentive, start-time, and unclaimable-period trees.
func GetPool
ActionGetPool returns a copy of the staking state for a pool.
Parameters:
- poolPath: pool realm path
Returns:
- pool: independent pool copy, or nil when an implementation has no pool value
- err: implementation resolution error; the current v1 implementation returns not-found for a missing pool
func NewPool
ActionNewPool creates pool reward state initialized at currentTime (Unix seconds).
Parameters:
- poolPath: Pool identifier to store in the new reward-state object.
- currentTime: Unix timestamp in seconds used to seed the initial accumulation, reward-cache, and liquidity snapshots.
Returns:
- pool: Initialized pool with empty backing structures and zero initial reward/liquidity snapshots at currentTime.
func NewSwapBatchProcessor
Action1func NewSwapBatchProcessor(poolPath string, pool *Pool, timestamp int64) *SwapBatchProcessorNewSwapBatchProcessor creates an active batch for collecting tick crosses in a pool swap.
Parameters:
- poolPath: Pool identifier associated with the swap.
- pool: Pool state whose tick crosses are being collected.
- timestamp: Unix timestamp in seconds when the swap began.
Returns:
- processor: Active processor with an empty cross sequence.
func NewSwapTickCross
ActionNewSwapTickCross creates a tick-cross record for a swap batch.
Parameters:
- tickID: Index of the tick crossed during the swap.
- zeroForOne: Swap direction; true means token0-to-token1 and false means token1-to-token0.
- delta: Precomputed signed staked-liquidity change for this tick cross.
Returns:
- cross: Tick-cross record containing the supplied index, direction, and delta.
func NewTick
ActionNewTick creates a tick with zero staked liquidity and an empty fanout-4 outside-accumulation tree.
Parameters:
- tickId: Tick index to assign to the new record.
Returns:
- tick: Initialized tick record.
func NewTicks
ActionNewTicks creates an empty tick mapping with a fanout-16 B+ tree.
Returns:
- ticks: Empty Ticks value ready to store pool tick records.
func NewTierRatio
ActionNewTierRatio constructs the reward-share ratio for tiers 1 through 3.
Parameters:
- tier1: Tier-1 share scaled by 100 (for example, 70 means 70%).
- tier2: Tier-2 share scaled by 100.
- tier3: Tier-3 share scaled by 100.
Returns:
- ratio: TierRatio containing the supplied scaled shares.
func NewUintTree
ActionNewUintTree creates a new UintTree instance with default fanout 64.
Returns:
- tree: Empty UintTree using the default fanout of 64.
func NewUintTreeN
ActionNewUintTreeN creates a new UintTree instance with the specified fanout.
Parameters:
- fanout: Number of child pointers per B+ tree node used by the wrapped tree.
Returns:
- tree: Empty UintTree configured with the requested fanout.
func NewUnstakedPosition
Action 1func NewUnstakedPosition(
2 deposit *Deposit,
3 exitTime int64,
4 exitTick int32,
5 lowerTick *Tick,
6 upperTick *Tick,
7 lowerOutsideAcc string,
8 upperOutsideAcc string,
9 tier uint64,
10 tierRatio uint64,
11 tierCount uint64,
12 unstakingFee uint64,
13 pendingIncentiveIds []string,
14) *UnstakedPositionNewUnstakedPosition creates an exit checkpoint owing every reward source of the deposit.
Parameters:
- deposit: Deposit state captured when the position leaves the pool.
- exitTime: Unix timestamp when staking ended and this checkpoint's reward window stopped.
- exitTick: Pool tick observed at exitTime for reconstructing in-range rewards.
- lowerTick: Snapshot of the position's lower boundary tick, retained if the live pool prunes it.
- upperTick: Snapshot of the position's upper boundary tick, retained if the live pool prunes it.
- lowerOutsideAcc: Decimal-encoded outside reward-ratio accumulation of the lower tick at exitTime.
- upperOutsideAcc: Decimal-encoded outside reward-ratio accumulation of the upper tick at exitTime.
- tier: Pool emission tier at exitTime; zero denotes that the pool was not tiered.
- tierRatio: Tier reward-share ratio, in its stored scaled form, at exitTime.
- tierCount: Number of pools sharing the tier at exitTime for dividing tier rewards.
- unstakingFee: Staking-reward fee rate in basis points at exitTime (0-1,000; 100 = 1%).
- pendingIncentiveIds: External incentive IDs whose rewards are still owed by the position.
Returns:
- position: New exit checkpoint retaining the deposit and exit-time reward context; emission is initially uncollected and every supplied incentive is pending.
func DefaultWarmupTemplate
ActionDefaultWarmupTemplate returns the built-in four-tier warmup schedule.
Returns:
- warmups: Template with 5-day, 10-day, 30-day, and final-unbounded tiers using 30%, 50%, 70%, and 100% ratios; NextWarmupTime values are zero until instantiated.
func GetDepositWarmUp
ActionGetDepositWarmUp returns the warmup records of a staked position.
Parameters:
- lpTokenId: Position NFT token ID whose warmup schedule should be inspected.
Returns:
- warmups: Independent copy of the deposit's warmup records.
- err: Non-nil when lpTokenId does not resolve to a stored deposit.
func GetWarmupTemplate
ActionGetWarmupTemplate returns the current warmup template.
Returns:
- warmups: Copy of the configured warmup schedule used for newly staked positions.
func NewWarmup
ActionNewWarmup creates one warmup tier.
Parameters:
- timeDuration: Duration of this tier in seconds.
- nextWarmupTime: Unix timestamp at which this tier ends.
- warmupRatio: Percentage of the calculated reward credited to the position, from 0 to 100.
Returns:
- warmup: Warmup tier initialized with the supplied duration, end time, and ratio.
21
type Counter
structtype Deposit
struct 1type Deposit struct {
2 warmups []Warmup // warmup information
3 liquidity *u256.Uint // liquidity
4 targetPoolPath string // staked position's pool path
5 owner address // owner address
6 stakeTime int64 // staked time
7 internalRewardLastCollectTime int64 // last collect time for internal reward
8 collectedInternalReward int64 // collected internal reward
9 collectedExternalRewards map[string]int64 // collected external reward by incentive id (incentiveID -> int64)
10 externalRewardLastCollectTimes map[string]int64 // last collect time for external rewards by incentive id (incentiveID -> int64)
11 externalIncentiveIds map[string]bool // external incentive ids for this deposit (incentiveID -> bool)
12 lastExternalIncentiveUpdatedAt int64 // last time when external incentive ids were synced
13 tickLower int32 // tick lower
14 tickUpper int32 // tick upper
15}Methods on Deposit
func AddExternalIncentiveId
method on DepositAddExternalIncentiveId adds an external incentive id to the deposit.
Parameters:
- incentiveId: External incentive ID to add to the deposit's index.
func Clone
method on DepositClone returns a deep copy of the deposit.
Returns:
- deposit: Deep copy of the deposit, or nil when the receiver is nil.
func CollectedExternalRewards
method on DepositCollectedExternalRewards returns cumulative external rewards keyed by incentive ID.
Returns:
- collectedExternalRewards: Map from incentive ID to the amount collected for that incentive.
func CollectedInternalReward
method on DepositCollectedInternalReward returns the cumulative internal reward recorded for the deposit.
Returns:
- collectedInternalReward: Accumulated internal reward amount in the reward token's smallest units.
func ExternalIncentiveIds
method on DepositExternalIncentiveIds returns the deposit's indexed external incentive IDs.
Returns:
- externalIncentiveIds: Map from each indexed incentive ID to its membership flag.
func ExternalRewardLastCollectTimes
method on DepositExternalRewardLastCollectTimes returns per-incentive external collection cursors.
Returns:
- externalRewardLastCollectTimes: Map from incentive ID to its last collection time in Unix seconds.
func GetCollectedExternalReward
method on DepositGetCollectedExternalReward returns the collected external reward for the given incentive ID. Returns 0 if the incentive ID does not exist.
Parameters:
- incentiveID: External incentive ID whose collected amount should be looked up.
Returns:
- reward: Collected amount for the incentive, or 0 when the ID is absent.
- exists: True when the map contains incentiveID; false when it is absent.
func GetExternalIncentiveIdList
method on DepositGetExternalIncentiveIdList returns a list of external incentive ids for the deposit.
Returns:
- incentiveIds: Slice containing the incentive IDs currently indexed on the deposit; order follows map iteration and is not guaranteed.
func GetExternalRewardLastCollectTime
method on DepositGetExternalRewardLastCollectTime returns the last collect time for the given incentive ID. Returns 0 if the incentive ID does not exist.
Parameters:
- incentiveID: External incentive ID whose collection cursor should be looked up.
Returns:
- time: Last collection time for the incentive in Unix seconds, or 0 when the ID is absent.
- exists: True when the map contains incentiveID; false when it is absent.
func HasExternalIncentiveId
method on DepositHasExternalIncentiveId checks if the deposit has the given external incentive id.
Parameters:
- incentiveId: External incentive ID whose membership should be checked.
Returns:
- hasIncentive: True when incentiveId is indexed on the deposit; false otherwise.
func InternalRewardLastCollectTime
method on DepositInternalRewardLastCollectTime returns the internal-reward collection cursor.
Returns:
- internalRewardLastCollectTime: Last internal reward collection time in Unix seconds.
func IterateExternalIncentiveIds
method on DepositIterateExternalIncentiveIds iterates over external incentive IDs without allocating a slice. The callback function receives each incentive ID and should return false to continue iteration, or true to stop early. This method is more memory-efficient than GetExternalIncentiveIdList for cases where you only need to process IDs sequentially.
Parameters:
- fn: Callback invoked with each indexed incentive ID; return true to stop iteration early or false to continue.
func LastExternalIncentiveUpdatedAt
method on DepositLastExternalIncentiveUpdatedAt returns the timestamp of the last external-incentive index refresh.
Returns:
- timestamp: Last refresh time in Unix seconds.
func Liquidity
method on DepositLiquidity returns the LP liquidity recorded for the deposit.
Returns:
- liquidity: Liquidity amount represented by the staked position.
func Owner
method on DepositOwner returns the address that owns the staked position.
Returns:
- owner: Address recorded as the deposit owner.
func RemoveExternalIncentiveId
method on DepositRemoveExternalIncentiveId removes an external incentive id from the deposit.
Parameters:
- incentiveId: External incentive ID to remove from the deposit's index.
func SetCollectedExternalReward
method on DepositSetCollectedExternalReward records the cumulative amount collected for one incentive.
Parameters:
- incentiveID: External incentive ID whose collected amount should be set.
- reward: Cumulative collected amount for incentiveID.
func SetCollectedExternalRewards
method on DepositSetCollectedExternalRewards replaces the cumulative external-reward map.
Parameters:
- collectedExternalRewards: Map from incentive ID to its collected reward amount.
func SetCollectedInternalReward
method on DepositSetCollectedInternalReward replaces the cumulative internal reward recorded for the deposit.
Parameters:
- collectedInternalReward: Cumulative internal reward amount in the reward token's smallest units.
func SetExternalIncentiveIds
method on DepositSetExternalIncentiveIds replaces the deposit's indexed external incentive IDs.
Parameters:
- externalIncentiveIds: Map of incentive IDs to their membership flags.
func SetExternalRewardLastCollectTime
method on DepositSetExternalRewardLastCollectTime records the collection cursor for one incentive.
Parameters:
- incentiveID: External incentive ID whose cursor should be set.
- currentTime: New collection time for incentiveID in Unix seconds.
func SetExternalRewardLastCollectTimes
method on Deposit1func (d *Deposit) SetExternalRewardLastCollectTimes(externalRewardLastCollectTimes map[string]int64)SetExternalRewardLastCollectTimes replaces the per-incentive external collection cursors.
Parameters:
- externalRewardLastCollectTimes: Map from incentive ID to its last collection time in Unix seconds.
func SetInternalRewardLastCollectTime
method on DepositSetInternalRewardLastCollectTime updates the internal-reward collection cursor.
Parameters:
- internalRewardLastCollectTime: New last internal reward collection time in Unix seconds.
func SetLastExternalIncentiveUpdatedAt
method on DepositSetLastExternalIncentiveUpdatedAt updates the external-incentive index refresh timestamp.
Parameters:
- timestamp: Refresh time to record in Unix seconds.
func SetLiquidity
method on DepositSetLiquidity replaces the LP liquidity recorded for the deposit.
Parameters:
- liquidity: New liquidity amount; the setter copies this value into the deposit.
func SetOwner
method on DepositSetOwner updates the address recorded as the deposit owner.
Parameters:
- owner: Address that should own the deposit.
func SetStakeTime
method on DepositSetStakeTime updates the Unix timestamp at which the position was staked.
Parameters:
- stakeTime: Stake start time in Unix seconds.
func SetTargetPoolPath
method on DepositSetTargetPoolPath updates the pool path associated with the staked position.
Parameters:
- targetPoolPath: Pool identifier to associate with the deposit.
func SetTickLower
method on DepositSetTickLower updates the lower signed tick boundary of the staked position.
Parameters:
- tickLower: Lower tick boundary to store for the position's price range.
func SetTickUpper
method on DepositSetTickUpper updates the upper signed tick boundary of the staked position.
Parameters:
- tickUpper: Upper tick boundary to store for the position's price range.
func SetWarmups
method on DepositSetWarmups replaces the deposit's warmup schedule with a copied slice.
Parameters:
- warmups: Warmup tiers to use for subsequent reward calculations.
func StakeTime
method on DepositStakeTime returns the Unix timestamp at which the position was staked.
Returns:
- stakeTime: Stake start time in Unix seconds.
func TargetPoolPath
method on DepositTargetPoolPath returns the pool path associated with the staked position.
Returns:
- targetPoolPath: Pool identifier used to resolve the position's pool.
func TickLower
method on DepositTickLower returns the lower signed tick boundary of the staked position.
Returns:
- tickLower: Lower tick boundary used by the position's price range.
func TickUpper
method on DepositTickUpper returns the upper signed tick boundary of the staked position.
Returns:
- tickUpper: Upper tick boundary used by the position's price range.
func Warmups
method on DepositWarmups returns a copy of the deposit's warmup schedule.
Returns:
- warmups: Warmup tiers applied to rewards for this deposit, or nil when no schedule is stored.
type EmissionAccessor
interface 1type EmissionAccessor interface {
2 // MintAndDistributeGns mints and distributes scheduled GNS emission through the emission realm.
3 //
4 // Parameters:
5 // - _: Internal call discriminator; callers pass 0.
6 // - rlm: Propagated realm context; it must be current before crossing into the emission realm.
7 //
8 // Returns:
9 // - int64: GNS amount distributed during this call, including any carried-forward amount.
10 // - bool: false only when emission is halted; true when processing completes, including a no-op call.
11 MintAndDistributeGns(_ int, rlm realm) (int64, bool)
12
13 // GetStakerEmissionAmountPerSecond returns the current GNS emission rate allocated to liquidity stakers.
14 //
15 // Returns:
16 // - int64: Current staker allocation in GNS units per second.
17 // - error: Non-nil when the emission distribution configuration cannot provide a staker rate; nil otherwise.
18 GetStakerEmissionAmountPerSecond() (int64, error)
19
20 // GetStakerEmissionAmountPerSecondInRange returns staker emission-rate change points over an inclusive time range.
21 //
22 // Parameters:
23 // - start: Inclusive lower bound as a Unix timestamp.
24 // - end: Inclusive upper bound as a Unix timestamp.
25 //
26 // Returns:
27 // - []int64: Unix timestamps at which the underlying GNS emission rate changes.
28 // - []int64: Staker emission amounts in GNS units per second at the corresponding timestamps.
29 // - error: Non-nil when the emission distribution configuration is invalid; nil when both slices are produced.
30 GetStakerEmissionAmountPerSecondInRange(start, end int64) ([]int64, []int64, error)
31
32 // SetOnDistributionPctChangeCallback registers a callback for staker distribution-percentage changes.
33 //
34 // Parameters:
35 // - _: Internal call discriminator; callers pass 0.
36 // - rlm: Propagated realm context; it must be current before the callback is registered.
37 // - callback: Callback invoked with the internal discriminator, current emission realm, and the new staker emission amount per second.
38 SetOnDistributionPctChangeCallback(_ int, rlm realm, callback func(_ int, rlm realm, emissionAmountPerSecond int64))
39}type ExternalIncentive
struct 1type ExternalIncentive struct {
2 incentiveId string // incentive id
3 startTimestamp int64 // start time for external reward
4 endTimestamp int64 // end time for external reward
5 createdHeight int64 // block height when the incentive was created
6 createdTimestamp int64 // timestamp when the incentive was created
7 depositGnsAmount int64 // deposited gns amount
8 targetPoolPath string // external reward target pool path
9 rewardToken string // external reward token path
10 totalRewardAmount int64 // total reward amount
11 rewardAmount int64 // mutable remaining reward amount
12 rewardPerSecondX128 *u256.Uint // reward per second, scaled by 2^128 to preserve sub-second precision
13 distributedRewardAmount int64 // reward amount delivered to positions or refunded at incentive end
14 accumulatedPenaltyAmount int64 // accumulated warmup penalty from CollectReward
15 creator address // creator address
16
17 refunded bool // whether EndExternalIncentive finalized the incentive and returned its refundable portion and GNS deposit
18
19 unclaimableSeconds int64 // accumulated seconds of unclaimable periods overlapping the incentive window
20}Methods on ExternalIncentive
func AccumulatedPenaltyAmount
method on ExternalIncentiveAccumulatedPenaltyAmount returns the accumulated warmup penalty amount
Returns:
- amount: Warm-up penalty accumulated from reward collections for this incentive.
func Clone
method on ExternalIncentiveClone returns an independent ExternalIncentive value with scalar fields copied and its fixed-point rate duplicated.
Returns:
- incentive: Copied external incentive record; its fixed-point rate is cloned when present and otherwise initialized to zero.
func CreatedHeight
method on ExternalIncentiveCreatedHeight returns the created height
Returns:
- height: Block height at which the incentive record was created.
func CreatedTimestamp
method on ExternalIncentiveCreatedTimestamp returns the created timestamp
Returns:
- timestamp: Unix timestamp in seconds at which the incentive record was created.
func Creator
method on ExternalIncentiveCreator returns the creator address
Returns:
- creator: Address that created and funded the incentive.
func DepositGnsAmount
method on ExternalIncentiveDepositGnsAmount returns the deposit GNS amount
Returns:
- amount: GNS amount deposited to back this external incentive.
func DistributedRewardAmount
method on ExternalIncentiveDistributedRewardAmount returns the distributed reward amount
Returns:
- amount: Reward amount already delivered to positions or refunded at incentive end.
func EndTimestamp
method on ExternalIncentiveEndTimestamp returns the end timestamp
Returns:
- timestamp: Unix timestamp in seconds at which the incentive window ends.
func IncentiveId
method on ExternalIncentiveIncentiveId returns the incentive ID
Returns:
- id: Identifier assigned to this external incentive.
func Refunded
method on ExternalIncentiveRefunded returns the refunded status
Returns:
- refunded: True when incentive finalization has marked its refundable balances as returned.
func RewardAmount
method on ExternalIncentiveRewardAmount returns the reward amount
Returns:
- amount: Mutable reward amount remaining after distributions and refunds.
func RewardPerSecondX128
method on ExternalIncentiveRewardPerSecondX128 returns the Q128-scaled reward per second. The underlying value is (rewardAmount << 128) / duration.
Returns:
- rate: Reward emitted per second, scaled by 2^128 for fixed-point accounting.
func RewardToken
method on ExternalIncentiveRewardToken returns the reward token
Returns:
- token: Reward-token path distributed by this incentive.
func SetAccumulatedPenaltyAmount
method on ExternalIncentiveSetAccumulatedPenaltyAmount sets the accumulated warmup penalty amount
Parameters:
- accumulatedPenaltyAmount: Warm-up penalty amount to store in the incentive's accumulated accounting.
func SetCreatedHeight
method on ExternalIncentiveSetCreatedHeight sets the created height
Parameters:
- createdHeight: Block height to record as the incentive's creation height.
func SetCreatedTimestamp
method on ExternalIncentiveSetCreatedTimestamp sets the created timestamp
Parameters:
- createdTimestamp: Unix timestamp in seconds to record as the incentive creation time.
func SetCreator
method on ExternalIncentiveSetCreator sets the creator address
Parameters:
- creator: Address to record as the incentive creator and refund recipient.
func SetDepositGnsAmount
method on ExternalIncentiveSetDepositGnsAmount sets the deposit GNS amount
Parameters:
- depositGnsAmount: GNS amount deposited to back this external incentive.
func SetDistributedRewardAmount
method on ExternalIncentiveSetDistributedRewardAmount sets the distributed reward amount
Parameters:
- distributedRewardAmount: Reward amount delivered to positions or refunded at incentive end.
func SetEndTimestamp
method on ExternalIncentiveSetEndTimestamp sets the end timestamp
Parameters:
- endTimestamp: Unix timestamp in seconds at which the incentive window ends.
func SetIncentiveId
method on ExternalIncentiveSetIncentiveId sets the incentive ID
Parameters:
- incentiveId: Identifier to store on the incentive record.
func SetRefunded
method on ExternalIncentiveSetRefunded sets the refunded status
Parameters:
- refunded: Finalization status to store for the incentive.
func SetRewardAmount
method on ExternalIncentiveSetRewardAmount sets the reward amount
Parameters:
- rewardAmount: Remaining reward amount to store after accounting adjustments.
func SetRewardPerSecondX128
method on ExternalIncentiveSetRewardPerSecondX128 sets the Q128-scaled reward per second.
Parameters:
- rewardPerSecondX128: Q128-scaled per-second reward rate; the value is copied before storage.
func SetRewardToken
method on ExternalIncentiveSetRewardToken sets the reward token
Parameters:
- rewardToken: Token path of the reward asset distributed by this incentive.
func SetTargetPoolPath
method on ExternalIncentiveSetTargetPoolPath sets the target pool path
Parameters:
- targetPoolPath: Pool path to target with this external incentive.
func SetTotalRewardAmount
method on ExternalIncentiveSetTotalRewardAmount sets the total reward amount
Parameters:
- totalRewardAmount: Total reward amount to record for the incentive.
func SetUnclaimableSeconds
method on ExternalIncentiveSetUnclaimableSeconds sets the accumulated unclaimable seconds.
Parameters:
- unclaimableSeconds: Overlapping unclaimable duration in seconds to store.
func StartTimestamp
method on ExternalIncentiveStartTimestamp returns the start timestamp.
It keys the byStartTime discovery index and must stay immutable after the incentive is registered, so no setter is exposed.
Returns:
- timestamp: Unix timestamp in seconds at which reward distribution starts.
func TargetPoolPath
method on ExternalIncentiveTargetPoolPath returns the target pool path
Returns:
- path: Pool path targeted by this external incentive.
func TotalRewardAmount
method on ExternalIncentiveTotalRewardAmount returns the total reward amount
Returns:
- amount: Total reward amount configured when the incentive was created.
func UnclaimableSeconds
method on ExternalIncentiveUnclaimableSeconds returns the accumulated seconds of unclaimable periods that overlap the incentive window. It is updated whenever an unclaimable period closes and is backfilled once from the historical unclaimable periods tree after an upgrade.
Returns:
- seconds: Accumulated seconds of unclaimable periods overlapping the incentive window.
type IStaker
interfacetype IStakerGetter
interface 1type IStakerGetter interface {
2 // GetPool returns the registered pool for a canonical pool path.
3 //
4 // Parameters:
5 // - poolPath: Canonical token0:token1:fee path identifying the pool.
6 //
7 // Returns:
8 // - pool: Pointer to the registered pool; nil when lookup fails.
9 // - err: Nil on success, or an error when the pool is absent or cannot be decoded.
10 //
11 GetPool(poolPath string) (*Pool, error)
12
13 // GetPoolRewardCaches exposes a read-only tree of a pool's reward-cache snapshots,
14 // keyed by encoded block timestamps.
15 //
16 // Parameters:
17 // - poolPath: Canonical pool path whose reward cache is requested.
18 //
19 // Returns:
20 // - rewardCaches: Read-only reward-cache tree, or nil when the pool does not exist.
21 //
22 GetPoolRewardCaches(poolPath string) *rotree.ReadOnlyTree
23
24 // GetPoolIncentives exposes a read-only tree of a pool's external incentives,
25 // keyed by incentive identifier.
26 //
27 // Parameters:
28 // - poolPath: Canonical pool path whose incentives are requested.
29 //
30 // Returns:
31 // - incentives: Read-only external-incentive tree, or nil when the pool does not exist.
32 //
33 GetPoolIncentives(poolPath string) *rotree.ReadOnlyTree
34
35 // GetPoolGlobalRewardRatioAccumulations exposes a read-only tree of global
36 // reward-ratio snapshots keyed by encoded block timestamps.
37 //
38 // Parameters:
39 // - poolPath: Canonical pool path whose global accumulations are requested.
40 //
41 // Returns:
42 // - accumulations: Read-only global reward-ratio tree, or nil when the pool does not exist.
43 //
44 GetPoolGlobalRewardRatioAccumulations(poolPath string) *rotree.ReadOnlyTree
45
46 // GetPoolHistoricalTicks exposes a read-only tree of historical pool ticks
47 // keyed by encoded block timestamps.
48 //
49 // Parameters:
50 // - poolPath: Canonical pool path whose historical ticks are requested.
51 //
52 // Returns:
53 // - historicalTicks: Read-only historical-tick tree, or nil when the pool does not exist.
54 //
55 GetPoolHistoricalTicks(poolPath string) *rotree.ReadOnlyTree
56
57 // GetDeposit returns the staker deposit associated with an LP position NFT.
58 //
59 // Parameters:
60 // - lpTokenId: LP position NFT identifier used as the deposit key.
61 //
62 // Returns:
63 // - deposit: Stored deposit for the position; nil when lookup fails.
64 // - err: Nil on success, or an error when no deposit exists for the identifier.
65 //
66 GetDeposit(lpTokenId uint64) (*Deposit, error)
67
68 // CollectableEmissionReward calculates the currently claimable internal GNS
69 // emission without mutating the position.
70 //
71 // Parameters:
72 // - positionId: LP position identifier for a live deposit or exit checkpoint.
73 //
74 // Returns:
75 // - reward: Claimable internal GNS amount at the current chain time and height.
76 // - err: Nil on success, or an error when the position is neither staked nor checkpointed or calculation fails.
77 //
78 CollectableEmissionReward(positionId uint64) (int64, error)
79
80 // CollectableExternalIncentiveReward calculates the currently claimable amount
81 // for one external incentive without mutating the position.
82 //
83 // Parameters:
84 // - positionId: LP position identifier for a live deposit or exit checkpoint.
85 // - incentiveId: External incentive identifier whose reward is queried.
86 //
87 // Returns:
88 // - reward: Claimable gross reward-token amount, or zero when that incentive contributes no reward.
89 // - err: Nil on success, or an error when the position or reward calculation is invalid.
90 //
91 CollectableExternalIncentiveReward(positionId uint64, incentiveId string) (int64, error)
92
93 // GetCreatedHeightOfIncentive returns the chain height recorded when an incentive was created.
94 //
95 // Parameters:
96 // - poolPath: Pool path containing the incentive.
97 // - incentiveId: External incentive identifier to inspect.
98 //
99 // Returns:
100 // - createdHeight: Chain height persisted at incentive creation.
101 // - err: Nil on success, or an error when the pool or incentive does not exist.
102 //
103 GetCreatedHeightOfIncentive(poolPath string, incentiveId string) (int64, error)
104
105 // GetIncentiveCreatedTimestamp returns the Unix-second creation time of an incentive.
106 //
107 // Parameters:
108 // - poolPath: Pool path containing the incentive.
109 // - incentiveId: External incentive identifier to inspect.
110 //
111 // Returns:
112 // - createdTimestamp: Unix-second timestamp recorded at creation.
113 // - err: Nil on success, or an error when the pool or incentive does not exist.
114 //
115 GetIncentiveCreatedTimestamp(poolPath string, incentiveId string) (int64, error)
116
117 // GetIncentiveTotalRewardAmount returns the amount originally funded for an incentive.
118 //
119 // Parameters:
120 // - poolPath: Pool path containing the incentive.
121 // - incentiveId: External incentive identifier to inspect.
122 //
123 // Returns:
124 // - totalRewardAmount: Original reward-token amount funded at creation.
125 // - err: Nil on success, or an error when the pool or incentive does not exist.
126 //
127 GetIncentiveTotalRewardAmount(poolPath string, incentiveId string) (int64, error)
128
129 // GetIncentiveDistributedRewardAmount returns the reward amount already
130 // distributed to positions or refunded when the incentive ended.
131 //
132 // Parameters:
133 // - poolPath: Pool path containing the incentive.
134 // - incentiveId: External incentive identifier to inspect.
135 //
136 // Returns:
137 // - distributedRewardAmount: Cumulative distributed or refunded reward-token amount.
138 // - err: Nil on success, or an error when the pool or incentive does not exist.
139 //
140 GetIncentiveDistributedRewardAmount(poolPath string, incentiveId string) (int64, error)
141
142 // GetIncentiveRemainingRewardAmount returns the current undistributed reward balance.
143 //
144 // Parameters:
145 // - poolPath: Pool path containing the incentive.
146 // - incentiveId: External incentive identifier to inspect.
147 //
148 // Returns:
149 // - remainingRewardAmount: Reward-token amount still held for future distribution or refund.
150 // - err: Nil on success, or an error when the pool or incentive does not exist.
151 //
152 GetIncentiveRemainingRewardAmount(poolPath string, incentiveId string) (int64, error)
153
154 // GetIncentiveAccumulatedPenaltyAmount returns warm-up penalties accumulated
155 // from collections for an incentive.
156 //
157 // Parameters:
158 // - poolPath: Pool path containing the incentive.
159 // - incentiveId: External incentive identifier to inspect.
160 //
161 // Returns:
162 // - penaltyAmount: Reward-token penalty amount accumulated for later collection.
163 // - err: Nil on success, or an error when the pool or incentive does not exist.
164 //
165 GetIncentiveAccumulatedPenaltyAmount(poolPath string, incentiveId string) (int64, error)
166
167 // GetIncentiveDepositGnsAmount returns the GNS deposit locked by an incentive.
168 //
169 // Parameters:
170 // - poolPath: Pool path containing the incentive.
171 // - incentiveId: External incentive identifier to inspect.
172 //
173 // Returns:
174 // - depositGnsAmount: GNS amount deposited as the incentive's collateral.
175 // - err: Nil on success, or an error when the pool or incentive does not exist.
176 //
177 GetIncentiveDepositGnsAmount(poolPath string, incentiveId string) (int64, error)
178
179 // GetIncentiveRefunded reports whether the incentive has been finalized and refunded.
180 //
181 // Parameters:
182 // - poolPath: Pool path containing the incentive.
183 // - incentiveId: External incentive identifier to inspect.
184 //
185 // Returns:
186 // - refunded: True after EndExternalIncentive has marked the incentive refunded; false otherwise.
187 // - err: Nil on success, or an error when the pool or incentive does not exist.
188 //
189 GetIncentiveRefunded(poolPath string, incentiveId string) (bool, error)
190
191 // IsIncentiveActive reports whether an unrefunded incentive is within its
192 // inclusive start/end Unix-second interval at the current time.
193 //
194 // Parameters:
195 // - poolPath: Pool path containing the incentive.
196 // - incentiveId: External incentive identifier to inspect.
197 //
198 // Returns:
199 // - active: True only when the current time is between the incentive bounds and it is not refunded.
200 // - err: Nil on success, or an error when the pool or incentive does not exist.
201 //
202 IsIncentiveActive(poolPath string, incentiveId string) (bool, error)
203
204 // GetDepositExternalRewardLastCollectTimestamp returns the last collection
205 // timestamp for one deposit/incentive pair.
206 //
207 // Parameters:
208 // - lpTokenId: LP position NFT identifier owning the external reward cursor.
209 // - incentiveId: External incentive identifier whose cursor is requested.
210 //
211 // Returns:
212 // - timestamp: Unix-second cursor, falling back to stake time when the incentive has never been collected.
213 // - err: Nil on success, or an error when the deposit does not exist.
214 //
215 GetDepositExternalRewardLastCollectTimestamp(lpTokenId uint64, incentiveId string) (int64, error)
216
217 // GetDepositGnsAmount returns the configured GNS deposit required per external incentive.
218 //
219 // Returns:
220 // - amount: Current required GNS deposit in token units.
221 //
222 GetDepositGnsAmount() int64
223
224 // GetDepositInternalRewardLastCollectTimestamp returns the stored internal
225 // reward collection cursor for a deposit.
226 //
227 // Parameters:
228 // - lpTokenId: LP position NFT identifier owning the internal reward cursor.
229 //
230 // Returns:
231 // - timestamp: Unix-second cursor, which is zero before the first internal collection.
232 // - err: Nil on success, or an error when the deposit does not exist.
233 //
234 GetDepositInternalRewardLastCollectTimestamp(lpTokenId uint64) (int64, error)
235
236 // GetDepositCollectedInternalReward returns cumulative internal reward recorded for a deposit.
237 //
238 // Parameters:
239 // - lpTokenId: LP position NFT identifier whose collection total is requested.
240 //
241 // Returns:
242 // - amount: Cumulative GNS amount recorded as collected for the deposit.
243 // - err: Nil on success, or an error when the deposit does not exist.
244 //
245 GetDepositCollectedInternalReward(lpTokenId uint64) (int64, error)
246
247 // GetDepositCollectedExternalReward returns the cumulative amount recorded
248 // for one deposit/incentive pair.
249 //
250 // Parameters:
251 // - lpTokenId: LP position NFT identifier whose collection total is requested.
252 // - incentiveId: External incentive identifier for the collection total.
253 //
254 // Returns:
255 // - amount: Cumulative gross reward-token amount recorded for that incentive.
256 // - err: Nil on success, or an error when the deposit does not exist.
257 //
258 GetDepositCollectedExternalReward(lpTokenId uint64, incentiveId string) (int64, error)
259
260 // GetDepositLiquidity returns the full-precision liquidity assigned to a deposit.
261 //
262 // Parameters:
263 // - lpTokenId: LP position NFT identifier whose liquidity is requested.
264 //
265 // Returns:
266 // - liquidity: 256-bit liquidity value stored in the deposit.
267 // - err: Nil on success, or an error when the deposit does not exist.
268 //
269 GetDepositLiquidity(lpTokenId uint64) (*u256.Uint, error)
270
271 // GetDepositLiquidityAsString returns the decimal string form of a deposit's liquidity.
272 //
273 // Parameters:
274 // - lpTokenId: LP position NFT identifier whose liquidity is requested.
275 //
276 // Returns:
277 // - liquidity: Decimal representation of the stored 256-bit liquidity.
278 // - err: Nil on success, or an error when the deposit does not exist.
279 //
280 GetDepositLiquidityAsString(lpTokenId uint64) (string, error)
281
282 // GetDepositOwner returns the address recorded as owner of a deposit.
283 //
284 // Parameters:
285 // - lpTokenId: LP position NFT identifier whose owner is requested.
286 //
287 // Returns:
288 // - owner: Address recorded when the position was staked.
289 // - err: Nil on success, or an error when the deposit does not exist.
290 //
291 GetDepositOwner(lpTokenId uint64) (address, error)
292
293 // GetDepositStakeTime returns the Unix-second timestamp when a position was staked.
294 //
295 // Parameters:
296 // - lpTokenId: LP position NFT identifier whose stake time is requested.
297 //
298 // Returns:
299 // - stakeTime: Unix-second timestamp stored in the deposit.
300 // - err: Nil on success, or an error when the deposit does not exist.
301 //
302 GetDepositStakeTime(lpTokenId uint64) (int64, error)
303
304 // GetDepositTargetPoolPath returns the pool path recorded for a deposit.
305 //
306 // Parameters:
307 // - lpTokenId: LP position NFT identifier whose target pool is requested.
308 //
309 // Returns:
310 // - poolPath: Canonical target pool path recorded in the deposit.
311 // - err: Nil on success, or an error when the deposit does not exist.
312 //
313 GetDepositTargetPoolPath(lpTokenId uint64) (string, error)
314
315 // GetDepositTickLower returns the lower concentrated-liquidity tick of a deposit.
316 //
317 // Parameters:
318 // - lpTokenId: LP position NFT identifier whose lower tick is requested.
319 //
320 // Returns:
321 // - tickLower: Signed lower tick stored in the deposit.
322 // - err: Nil on success, or an error when the deposit does not exist.
323 //
324 GetDepositTickLower(lpTokenId uint64) (int32, error)
325
326 // GetDepositTickUpper returns the upper concentrated-liquidity tick of a deposit.
327 //
328 // Parameters:
329 // - lpTokenId: LP position NFT identifier whose upper tick is requested.
330 //
331 // Returns:
332 // - tickUpper: Signed upper tick stored in the deposit.
333 // - err: Nil on success, or an error when the deposit does not exist.
334 //
335 GetDepositTickUpper(lpTokenId uint64) (int32, error)
336
337 // GetDepositWarmUp returns the warm-up records currently attached to a deposit.
338 //
339 // Parameters:
340 // - lpTokenId: LP position NFT identifier whose warm-up records are requested.
341 //
342 // Returns:
343 // - warmups: Warm-up schedule entries stored for the deposit.
344 // - err: Nil on success, or an error when the deposit does not exist.
345 //
346 GetDepositWarmUp(lpTokenId uint64) ([]Warmup, error)
347
348 // GetDepositExternalIncentiveIdList returns external incentive identifiers
349 // currently tracked by a deposit.
350 //
351 // Parameters:
352 // - lpTokenId: LP position NFT identifier whose incentive index is requested.
353 //
354 // Returns:
355 // - incentiveIds: External incentive IDs attached to the deposit.
356 // - err: Nil on success, or an error when the deposit does not exist.
357 //
358 GetDepositExternalIncentiveIdList(lpTokenId uint64) ([]string, error)
359
360 // GetExternalIncentiveByPoolPath returns all stored external incentives targeting a pool.
361 //
362 // Parameters:
363 // - poolPath: Canonical pool path used to filter incentive records.
364 //
365 // Returns:
366 // - incentives: Matching external incentive records, possibly an empty slice.
367 // - err: Nil on success, or an error when a stored record has an invalid type.
368 //
369 GetExternalIncentiveByPoolPath(poolPath string) ([]ExternalIncentive, error)
370
371 // GetIncentiveEndTimestamp returns the Unix-second end time of an incentive.
372 //
373 // Parameters:
374 // - poolPath: Pool path containing the incentive.
375 // - incentiveId: External incentive identifier to inspect.
376 //
377 // Returns:
378 // - endTimestamp: Inclusive Unix-second end bound recorded for the incentive.
379 // - err: Nil on success, or an error when the pool or incentive does not exist.
380 //
381 GetIncentiveEndTimestamp(poolPath string, incentiveId string) (int64, error)
382
383 // GetIncentiveCreator returns the address that created and funded an incentive.
384 //
385 // Parameters:
386 // - poolPath: Pool path containing the incentive.
387 // - incentiveId: External incentive identifier to inspect.
388 //
389 // Returns:
390 // - creator: Address recorded as the incentive creator.
391 // - err: Nil on success, or an error when the pool or incentive does not exist.
392 //
393 GetIncentiveCreator(poolPath string, incentiveId string) (address, error)
394
395 // GetIncentiveRewardAmount returns the remaining reward amount as a 256-bit unsigned value.
396 //
397 // Parameters:
398 // - poolPath: Pool path containing the incentive.
399 // - incentiveId: External incentive identifier to inspect.
400 //
401 // Returns:
402 // - rewardAmount: Remaining reward-token amount represented as a uint256 value.
403 // - err: Nil on success, or an error when the pool or incentive does not exist.
404 //
405 GetIncentiveRewardAmount(poolPath string, incentiveId string) (*u256.Uint, error)
406
407 // GetIncentiveRewardAmountAsString returns the decimal string form of the remaining reward.
408 //
409 // Parameters:
410 // - poolPath: Pool path containing the incentive.
411 // - incentiveId: External incentive identifier to inspect.
412 //
413 // Returns:
414 // - rewardAmount: Decimal representation of the remaining reward-token amount.
415 // - err: Nil on success, or an error when the pool or incentive does not exist.
416 //
417 GetIncentiveRewardAmountAsString(poolPath string, incentiveId string) (string, error)
418
419 // GetIncentiveRewardPerSecondX128 returns the Q128-scaled reward rate of an incentive.
420 //
421 // Parameters:
422 // - poolPath: Pool path containing the incentive.
423 // - incentiveId: External incentive identifier to inspect.
424 //
425 // Returns:
426 // - rewardPerSecondX128: Reward-per-second rate scaled by 2^128 to preserve precision.
427 // - err: Nil on success, or an error when the pool or incentive does not exist.
428 //
429 GetIncentiveRewardPerSecondX128(poolPath string, incentiveId string) (*u256.Uint, error)
430
431 // GetIncentiveRewardToken returns the token path used to pay an incentive.
432 //
433 // Parameters:
434 // - poolPath: Pool path containing the incentive.
435 // - incentiveId: External incentive identifier to inspect.
436 //
437 // Returns:
438 // - rewardToken: Registered reward-token contract path.
439 // - err: Nil on success, or an error when the pool or incentive does not exist.
440 //
441 GetIncentiveRewardToken(poolPath string, incentiveId string) (string, error)
442
443 // GetIncentiveStartTimestamp returns the Unix-second start time of an incentive.
444 //
445 // Parameters:
446 // - poolPath: Pool path containing the incentive.
447 // - incentiveId: External incentive identifier to inspect.
448 //
449 // Returns:
450 // - startTimestamp: Inclusive Unix-second start bound recorded for the incentive.
451 // - err: Nil on success, or an error when the pool or incentive does not exist.
452 //
453 GetIncentiveStartTimestamp(poolPath string, incentiveId string) (int64, error)
454
455 // GetMinimumRewardAmount returns the default minimum reward amount for external incentives.
456 //
457 // Returns:
458 // - amount: Default minimum reward-token amount used when no token-specific override exists.
459 //
460 GetMinimumRewardAmount() int64
461
462 // GetMinimumRewardAmountForToken returns a token-specific minimum, falling
463 // back to the default minimum when no override is configured.
464 //
465 // Parameters:
466 // - tokenPath: Reward-token contract path whose minimum is requested.
467 //
468 // Returns:
469 // - amount: Token-specific minimum when configured, otherwise the default minimum.
470 //
471 GetMinimumRewardAmountForToken(tokenPath string) int64
472
473 // GetPoolStakedLiquidity returns the current total staked liquidity as a decimal string.
474 //
475 // Parameters:
476 // - poolPath: Canonical pool path whose active staked liquidity is requested.
477 //
478 // Returns:
479 // - liquidity: Decimal string for current staked liquidity, or zero when the pool has no value.
480 // - err: Nil on success, or an error when the pool does not exist.
481 //
482 GetPoolStakedLiquidity(poolPath string) (string, error)
483
484 // GetPoolsByTier lists pool paths currently assigned to an internal emission tier.
485 //
486 // Parameters:
487 // - tier: Tier number used to filter pool membership; tier zero returns an empty list.
488 //
489 // Returns:
490 // - poolPaths: Pool paths assigned to the requested tier.
491 // - err: Nil on success, or an error when stored tier membership cannot be decoded.
492 //
493 GetPoolsByTier(tier uint64) ([]string, error)
494
495 // GetPoolReward returns the current per-second GNS reward for a tier.
496 //
497 // Parameters:
498 // - tier: Supported nonzero tier whose reward rate is requested.
499 //
500 // Returns:
501 // - reward: Current tier reward amount per second.
502 // - err: Nil on success, or an invalid-tier error for zero or unsupported tiers.
503 //
504 GetPoolReward(tier uint64) (int64, error)
505
506 // GetPoolTier returns the internal emission tier currently assigned to a pool.
507 //
508 // Parameters:
509 // - poolPath: Canonical pool path whose tier is requested.
510 //
511 // Returns:
512 // - tier: Assigned tier number; zero denotes no internal emission tier.
513 //
514 GetPoolTier(poolPath string) uint64
515
516 // GetPoolTierCount returns the number of pools assigned to a tier.
517 //
518 // Parameters:
519 // - tier: Tier number whose membership count is requested; tier zero has count zero.
520 //
521 // Returns:
522 // - count: Current number of pools in the requested tier.
523 //
524 GetPoolTierCount(tier uint64) uint64
525
526 // GetPoolTierRatio returns the reward ratio configured for a pool's current tier.
527 //
528 // Parameters:
529 // - poolPath: Canonical pool path whose current tier ratio is requested.
530 //
531 // Returns:
532 // - ratio: Current reward ratio for the pool's assigned tier.
533 // - err: Nil on success, or an invalid-tier error when the tier has no ratio.
534 //
535 GetPoolTierRatio(poolPath string) (uint64, error)
536
537 // GetSpecificTokenMinimumRewardAmount looks up only an explicitly configured
538 // token-specific minimum and does not apply the default fallback.
539 //
540 // Parameters:
541 // - tokenPath: Reward-token contract path whose override is requested.
542 //
543 // Returns:
544 // - amount: Configured token-specific minimum, or zero when absent.
545 // - found: True when an explicit override exists; false when the default should be used.
546 //
547 GetSpecificTokenMinimumRewardAmount(tokenPath string) (int64, bool)
548
549 // GetTargetPoolPathByIncentiveId returns the pool path targeted by an incentive.
550 //
551 // Parameters:
552 // - poolPath: Pool path containing the incentive record.
553 // - incentiveId: External incentive identifier to inspect.
554 //
555 // Returns:
556 // - targetPoolPath: Pool path recorded as the incentive target.
557 // - err: Nil on success, or an error when the pool or incentive does not exist.
558 //
559 GetTargetPoolPathByIncentiveId(poolPath string, incentiveId string) (string, error)
560
561 // GetUnstakingFee returns the current reward fee rate in basis points.
562 //
563 // Returns:
564 // - fee: Current unstaking fee, where 10,000 basis points represents 100%.
565 //
566 GetUnstakingFee() uint64
567
568 // GetPendingProtocolFees returns pending protocol-fee amounts keyed by token path.
569 //
570 // Returns:
571 // - fees: Map from reward-token path to amount awaiting protocol-fee settlement.
572 //
573 GetPendingProtocolFees() map[string]int64
574
575 // HasUnstakedPosition reports whether an exit checkpoint with uncollected
576 // rewards exists for a position.
577 //
578 // Parameters:
579 // - positionId: LP position identifier whose exit checkpoint is queried.
580 //
581 // Returns:
582 // - exists: True when an uncollected exit checkpoint is present.
583 //
584 HasUnstakedPosition(positionId uint64) bool
585
586 // GetUnstakedPositionExitTime returns when an exit checkpoint stopped accruing rewards.
587 //
588 // Parameters:
589 // - positionId: LP position identifier whose checkpoint is requested.
590 //
591 // Returns:
592 // - exitTime: Unix-second timestamp at which the position was unstaked.
593 // - err: Nil on success, or an error when no uncollected checkpoint exists.
594 //
595 GetUnstakedPositionExitTime(positionId uint64) (int64, error)
596
597 // GetUnstakedPositionPendingIncentives returns external incentive IDs still
598 // owed by an exit checkpoint.
599 //
600 // Parameters:
601 // - positionId: LP position identifier whose checkpoint is requested.
602 //
603 // Returns:
604 // - incentiveIds: External incentive IDs pending collection for the checkpoint.
605 // - err: Nil on success, or an error when no uncollected checkpoint exists.
606 //
607 GetUnstakedPositionPendingIncentives(positionId uint64) ([]string, error)
608
609 // GetUncollectedIncentiveCount returns the number of exit checkpoints still
610 // carrying an uncollected claim for an incentive.
611 //
612 // Parameters:
613 // - incentiveId: External incentive identifier whose checkpoint count is requested.
614 //
615 // Returns:
616 // - count: Number of uncollected exit-position claims for the incentive.
617 //
618 GetUncollectedIncentiveCount(incentiveId string) int64
619
620 // IsStaked reports whether a live deposit exists for a position.
621 //
622 // Parameters:
623 // - positionId: LP position identifier to query.
624 //
625 // Returns:
626 // - staked: True when the position is present in active deposits.
627 //
628 IsStaked(positionId uint64) bool
629
630 // GetTotalEmissionSent returns cumulative GNS emission sent or accounted for.
631 //
632 // Returns:
633 // - amount: Cumulative internal GNS emission amount recorded by the staker.
634 //
635 GetTotalEmissionSent() int64
636
637 // GetAllowedTokens returns token paths approved for new external incentives.
638 //
639 // Returns:
640 // - tokenPaths: Registered external-incentive token paths currently allowed.
641 //
642 GetAllowedTokens() []string
643
644 // GetDeniedRewardTokens returns token paths denied for new external incentives.
645 //
646 // Returns:
647 // - tokenPaths: Reward-token paths on the operational deny list.
648 //
649 GetDeniedRewardTokens() []string
650
651 // GetWarmupTemplate returns the current warm-up schedule used for new deposits.
652 //
653 // Returns:
654 // - warmups: Ordered warm-up entries defining reward-release ratios and durations.
655 //
656 GetWarmupTemplate() []Warmup
657}type IStakerManager
interface 1type IStakerManager interface {
2 // StakeToken stakes an LP position NFT, transfers custody to the staker, and
3 // starts internal GNS and eligible external reward accounting.
4 //
5 // Parameters:
6 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
7 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
8 // - positionId: LP position NFT identifier whose liquidity will be staked.
9 // - referrer: Optional referral address or identifier supplied for referral tracking.
10 //
11 // Returns:
12 // - poolPath: Canonical token0:token1:fee path of the pool containing the staked position.
13 //
14 StakeToken(_ int, rlm realm, positionId uint64, referrer string) string
15
16 // UnStakeToken records the position's exit checkpoint, removes it from active
17 // staking, and returns the NFT to its owner.
18 //
19 // Parameters:
20 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
21 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
22 // - positionId: LP position NFT identifier to remove from staking.
23 //
24 // Returns:
25 // - poolPath: Canonical pool path from the position's active deposit.
26 //
27 UnStakeToken(_ int, rlm realm, positionId uint64) string
28
29 // CollectReward settles both GNS emission and all currently payable external
30 // incentive rewards for a live deposit or an unstaked exit checkpoint.
31 //
32 // Parameters:
33 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
34 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
35 // - positionId: LP position NFT identifier, or an identifier with an exit checkpoint.
36 //
37 // Returns:
38 // - internalRewardToUser: Decimal string for the GNS amount transferred to the position owner.
39 // - internalRewardPenalty: Decimal string for the GNS warm-up penalty sent to the community pool.
40 // - externalRewards: Map keyed by reward-token path containing gross external reward amounts before the staking fee.
41 // - externalPenalties: Map keyed by reward-token path containing warm-up penalties retained by each incentive.
42 //
43 CollectReward(_ int, rlm realm, positionId uint64) (string, string, map[string]int64, map[string]int64)
44
45 // CollectEmissionReward settles only the internal GNS emission for a live
46 // deposit or an unstaked exit checkpoint.
47 //
48 // Parameters:
49 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
50 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
51 // - positionId: LP position NFT identifier, or an identifier with an exit checkpoint.
52 //
53 // Returns:
54 // - rewardToUser: GNS amount transferred to the position owner.
55 // - rewardPenalty: GNS warm-up penalty transferred to the community pool.
56 //
57 CollectEmissionReward(_ int, rlm realm, positionId uint64) (int64, int64)
58
59 // CollectExternalIncentiveReward settles one external incentive for a live
60 // deposit or an unstaked exit checkpoint.
61 //
62 // Parameters:
63 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
64 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
65 // - positionId: LP position NFT identifier, or an identifier with an exit checkpoint.
66 // - incentiveId: External incentive identifier to settle for the position.
67 //
68 // Returns:
69 // - rewardAmount: Gross reward-token amount calculated for the incentive before the staking fee.
70 // - penaltyAmount: Warm-up penalty amount retained by the incentive rather than sent to the owner.
71 //
72 CollectExternalIncentiveReward(_ int, rlm realm, positionId uint64, incentiveId string) (int64, int64)
73
74 // SetPoolTier assigns an internal GNS-emission tier to an existing pool.
75 //
76 // Parameters:
77 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
78 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
79 // - poolPath: Canonical pool path whose emission tier is being assigned.
80 // - tier: Pool tier index in [0, AllTierCount); zero removes the pool from the internal emission target.
81 //
82 SetPoolTier(_ int, rlm realm, poolPath string, tier uint64)
83
84 // ChangePoolTier changes the internal GNS-emission tier of an existing pool.
85 //
86 // Parameters:
87 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
88 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
89 // - poolPath: Canonical pool path whose emission tier is being changed.
90 // - tier: Replacement pool tier index in [0, AllTierCount); zero removes the pool from the internal emission target.
91 //
92 ChangePoolTier(_ int, rlm realm, poolPath string, tier uint64)
93
94 // RemovePoolTier removes a pool from the internal GNS-emission tier system.
95 //
96 // Parameters:
97 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
98 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
99 // - poolPath: Canonical pool path to remove from tier membership.
100 //
101 RemovePoolTier(_ int, rlm realm, poolPath string)
102
103 // CreateExternalIncentive funds and registers an external reward program for a
104 // target pool over the requested Unix-time interval.
105 //
106 // Parameters:
107 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
108 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
109 // - targetPoolPath: Canonical pool path whose positions may earn the incentive.
110 // - rewardToken: Registered token path used to pay the external reward.
111 // - rewardAmount: Total reward-token amount deposited for the incentive.
112 // - startTimestamp: Inclusive Unix-second timestamp at which rewards begin accruing.
113 // - endTimestamp: Unix-second timestamp at which the reward interval ends.
114 //
115 CreateExternalIncentive(
116 _ int,
117 rlm realm,
118 targetPoolPath string,
119 rewardToken string,
120 rewardAmount int64,
121 startTimestamp int64,
122 endTimestamp int64,
123 )
124
125 // EndExternalIncentive finalizes an ended external incentive and refunds its
126 // remaining reward tokens and deposited GNS to the requested address.
127 //
128 // Parameters:
129 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
130 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
131 // - targetPoolPath: Canonical pool path containing the incentive.
132 // - incentiveId: Unique external incentive identifier to finalize.
133 // - refundAddress: Address receiving refundable reward tokens and the GNS deposit.
134 //
135 EndExternalIncentive(_ int, rlm realm, targetPoolPath, incentiveId string, refundAddress address)
136
137 // CancelExternalIncentive removes an external incentive before it starts and
138 // refunds the available funded amounts to its creator.
139 //
140 // Parameters:
141 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
142 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
143 // - targetPoolPath: Canonical pool path containing the incentive.
144 // - incentiveId: Unique external incentive identifier to cancel.
145 //
146 CancelExternalIncentive(_ int, rlm realm, targetPoolPath, incentiveId string)
147
148 // CollectExternalIncentivePenalty transfers accumulated warm-up penalties
149 // from an ended external incentive to the requested address.
150 //
151 // Parameters:
152 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
153 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
154 // - targetPoolPath: Canonical pool path containing the incentive.
155 // - incentiveId: Ended external incentive identifier whose penalties are collected.
156 // - refundAddress: Address receiving the collected reward-token penalty.
157 //
158 // Returns:
159 // - penaltyAmount: Amount actually transferred, capped by the staker's available balance and zero when no penalty is accrued.
160 //
161 CollectExternalIncentivePenalty(_ int, rlm realm, targetPoolPath, incentiveId string, refundAddress address) int64
162
163 // AddToken adds a registered non-default token path to the external-incentive allowlist.
164 //
165 // Parameters:
166 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
167 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
168 // - tokenPath: Registered token contract path to allow for new external incentives.
169 //
170 AddToken(_ int, rlm realm, tokenPath string)
171
172 // RemoveToken removes a non-default token path from the external-incentive allowlist.
173 //
174 // Parameters:
175 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
176 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
177 // - tokenPath: Allowed token contract path to remove from future incentive creation.
178 //
179 RemoveToken(_ int, rlm realm, tokenPath string)
180
181 // SetDeniedRewardToken sets or clears the operational deny flag for a reward token.
182 // The flag prevents new incentives while leaving already-created incentives collectible.
183 //
184 // Parameters:
185 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
186 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
187 // - tokenPath: Reward-token contract path whose deny flag is being changed.
188 // - denied: true to deny new incentives for the token, or false to remove the denial.
189 //
190 SetDeniedRewardToken(_ int, rlm realm, tokenPath string, denied bool)
191
192 // SetWarmUp changes the duration associated with one of the fixed warm-up ratios.
193 //
194 // Parameters:
195 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
196 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
197 // - pct: Warm-up completion ratio selector; supported values are 30, 50, 70, and 100.
198 // - timeDuration: Warm-up duration in seconds for the selected ratio; finite tiers are bounded by 365 days.
199 //
200 SetWarmUp(_ int, rlm realm, pct, timeDuration int64)
201
202 // SetDepositGnsAmount updates the GNS deposit required when creating an external incentive.
203 //
204 // Parameters:
205 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
206 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
207 // - amount: Nonnegative GNS amount required as each external-incentive deposit.
208 //
209 SetDepositGnsAmount(_ int, rlm realm, amount int64)
210
211 // SetMinimumRewardAmount updates the default minimum reward amount for external incentives.
212 //
213 // Parameters:
214 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
215 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
216 // - amount: Nonnegative reward-token amount used when no token-specific minimum exists.
217 //
218 SetMinimumRewardAmount(_ int, rlm realm, amount int64)
219
220 // SetTokenMinimumRewardAmount sets or removes a token-specific external-incentive minimum.
221 //
222 // Parameters:
223 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
224 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
225 // - paramsStr: Colon-delimited tokenPath:amount string; amount 0 removes that token's override.
226 //
227 SetTokenMinimumRewardAmount(_ int, rlm realm, paramsStr string)
228
229 // SetUnStakingFee updates the fee charged against collected staking rewards.
230 //
231 // Parameters:
232 // - _: Leading integer discriminator for implementation forwarding; proxy methods pass 0.
233 // - rlm: Current realm context forwarded unchanged by the staker proxy (0, cur, ...).
234 // - fee: Unstaking fee rate in basis points, where 10,000 basis points represents 100%.
235 //
236 SetUnStakingFee(_ int, rlm realm, fee uint64)
237}type IStakerStore
interface 1type IStakerStore interface {
2 // HasDepositGnsAmountStoreKey reports whether the configured GNS-deposit key exists.
3 //
4 // Returns:
5 // - exists: True when the depositGnsAmount key is present in persistent storage.
6 //
7 HasDepositGnsAmountStoreKey() bool
8
9 // GetDepositGnsAmount returns the stored GNS deposit required per external incentive.
10 //
11 // Returns:
12 // - amount: Persisted GNS amount in token units; storage read or type failures panic.
13 //
14 GetDepositGnsAmount() int64
15
16 // SetDepositGnsAmount persists the GNS deposit required per external incentive.
17 //
18 // Parameters:
19 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
20 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
21 // - amount: GNS amount in token units to persist.
22 //
23 // Returns:
24 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
25 //
26 SetDepositGnsAmount(_ int, rlm realm, amount int64) error
27
28 // HasMinimumRewardAmountStoreKey reports whether the default minimum-reward key exists.
29 //
30 // Returns:
31 // - exists: True when the minimumRewardAmount key is present in persistent storage.
32 //
33 HasMinimumRewardAmountStoreKey() bool
34
35 // GetMinimumRewardAmount returns the default minimum external-incentive reward.
36 //
37 // Returns:
38 // - amount: Persisted default reward-token minimum; storage read or type failures panic.
39 //
40 GetMinimumRewardAmount() int64
41
42 // SetMinimumRewardAmount persists the default minimum external-incentive reward.
43 //
44 // Parameters:
45 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
46 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
47 // - amount: Default minimum reward-token amount in token units.
48 //
49 // Returns:
50 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
51 //
52 SetMinimumRewardAmount(_ int, rlm realm, amount int64) error
53
54 // HasDepositsStoreKey reports whether the active-deposits tree key exists.
55 //
56 // Returns:
57 // - exists: True when the deposits key is present in persistent storage.
58 //
59 HasDepositsStoreKey() bool
60
61 // GetDeposits returns the persisted active position-deposit tree.
62 //
63 // Returns:
64 // - deposits: B+tree mapping LP position IDs to deposits; storage read or type failures panic.
65 //
66 GetDeposits() *bptree.BPTree
67
68 // SetDeposits persists the active position-deposit tree.
69 //
70 // Parameters:
71 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
72 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
73 // - deposits: B+tree containing active position deposits to persist.
74 //
75 // Returns:
76 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
77 //
78 SetDeposits(_ int, rlm realm, deposits *bptree.BPTree) error
79
80 // HasExternalIncentivesStoreKey reports whether the external-incentives tree key exists.
81 //
82 // Returns:
83 // - exists: True when the externalIncentives key is present in persistent storage.
84 //
85 HasExternalIncentivesStoreKey() bool
86
87 // GetExternalIncentives returns the persisted external-incentive tree.
88 //
89 // Returns:
90 // - incentives: B+tree mapping incentive IDs to incentive records; storage read or type failures panic.
91 //
92 GetExternalIncentives() *bptree.BPTree
93
94 // SetExternalIncentives persists the external-incentive tree.
95 //
96 // Parameters:
97 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
98 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
99 // - incentives: B+tree containing external-incentive records to persist.
100 //
101 // Returns:
102 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
103 //
104 SetExternalIncentives(_ int, rlm realm, incentives *bptree.BPTree) error
105
106 // HasTotalEmissionSentStoreKey reports whether the cumulative-emission key exists.
107 //
108 // Returns:
109 // - exists: True when the totalEmissionSent key is present in persistent storage.
110 //
111 HasTotalEmissionSentStoreKey() bool
112
113 // GetTotalEmissionSent returns the persisted cumulative GNS emission amount.
114 //
115 // Returns:
116 // - amount: Cumulative internal emission in GNS token units; storage read or type failures panic.
117 //
118 GetTotalEmissionSent() int64
119
120 // SetTotalEmissionSent persists the cumulative GNS emission amount.
121 //
122 // Parameters:
123 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
124 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
125 // - amount: Cumulative GNS amount to persist.
126 //
127 // Returns:
128 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
129 //
130 SetTotalEmissionSent(_ int, rlm realm, amount int64) error
131
132 // HasAllowedTokensStoreKey reports whether the external-incentive allowlist key exists.
133 //
134 // Returns:
135 // - exists: True when the allowedTokens key is present in persistent storage.
136 //
137 HasAllowedTokensStoreKey() bool
138
139 // GetAllowedTokens returns a copy of token paths allowed for new incentives.
140 //
141 // Returns:
142 // - tokenPaths: Store-owned allowlist copied into a caller-safe slice.
143 //
144 GetAllowedTokens() []string
145
146 // SetAllowedTokens replaces the external-incentive allowlist.
147 //
148 // Parameters:
149 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
150 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
151 // - tokens: Token contract paths to persist as the new allowlist.
152 //
153 // Returns:
154 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
155 //
156 SetAllowedTokens(_ int, rlm realm, tokens []string) error
157
158 // AddAllowedToken adds a token path to the allowlist when it is not already present.
159 //
160 // Parameters:
161 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
162 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
163 // - tokenPath: Token contract path to add to the allowlist.
164 //
165 // Returns:
166 // - err: Nil when added or already present, ErrSpoofedRealm for a non-current realm, or the KV-store write error.
167 //
168 AddAllowedToken(_ int, rlm realm, tokenPath string) error
169
170 // RemoveAllowedToken removes a token path from the allowlist when present.
171 //
172 // Parameters:
173 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
174 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
175 // - tokenPath: Token contract path to remove from the allowlist.
176 //
177 // Returns:
178 // - err: Nil when removed or absent, ErrSpoofedRealm for a non-current realm, or the KV-store write error.
179 //
180 RemoveAllowedToken(_ int, rlm realm, tokenPath string) error
181
182 // HasDeniedRewardTokensStoreKey reports whether the external reward deny-list key exists.
183 //
184 // Returns:
185 // - exists: True when the deniedRewardTokens key is present in persistent storage.
186 //
187 HasDeniedRewardTokensStoreKey() bool
188
189 // GetDeniedRewardTokens returns a copy of token paths denied for new incentives.
190 //
191 // Returns:
192 // - tokenPaths: Store-owned deny list copied for callers; an uninitialized key yields an empty slice.
193 //
194 GetDeniedRewardTokens() []string
195
196 // AddDeniedRewardToken adds a token path to the deny list when absent.
197 //
198 // Parameters:
199 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
200 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
201 // - tokenPath: Reward-token contract path to deny for new incentives.
202 //
203 // Returns:
204 // - err: Nil when added or already present, ErrSpoofedRealm for a non-current realm, or the KV-store write error.
205 //
206 AddDeniedRewardToken(_ int, rlm realm, tokenPath string) error
207
208 // RemoveDeniedRewardToken removes a token path from the deny list when present.
209 //
210 // Parameters:
211 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
212 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
213 // - tokenPath: Reward-token contract path to allow again for new incentives.
214 //
215 // Returns:
216 // - err: Nil when removed or absent, ErrSpoofedRealm for a non-current realm, or the KV-store write error.
217 //
218 RemoveDeniedRewardToken(_ int, rlm realm, tokenPath string) error
219
220 // HasIncentiveCounterStoreKey reports whether the incentive-counter key exists.
221 //
222 // Returns:
223 // - exists: True when the incentiveCounter key is present in persistent storage.
224 //
225 HasIncentiveCounterStoreKey() bool
226
227 // GetIncentiveCounter returns the persisted counter used to allocate incentive IDs.
228 //
229 // Returns:
230 // - counter: Incentive-ID counter object; storage read or type failures panic.
231 //
232 GetIncentiveCounter() *Counter
233
234 // SetIncentiveCounter persists the incentive-ID counter.
235 //
236 // Parameters:
237 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
238 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
239 // - counter: Counter object whose next value will be used for incentive IDs.
240 //
241 // Returns:
242 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
243 //
244 SetIncentiveCounter(_ int, rlm realm, counter *Counter) error
245
246 // NextIncentiveID consumes the next counter value and formats a unique incentive ID.
247 //
248 // Parameters:
249 // - creator: Address that is creating and funding the incentive.
250 // - timestamp: Unix-second creation timestamp embedded in the identifier.
251 //
252 // Returns:
253 // - incentiveId: Identifier combining creator, timestamp, and the incremented counter index.
254 //
255 NextIncentiveID(creator address, timestamp int64) string
256
257 // HasTokenSpecificMinimumRewardsStoreKey reports whether token-specific minimums exist.
258 //
259 // Returns:
260 // - exists: True when the tokenSpecificMinimumRewards key is present in persistent storage.
261 //
262 HasTokenSpecificMinimumRewardsStoreKey() bool
263
264 // GetTokenSpecificMinimumRewards returns configured token-specific reward minimums.
265 //
266 // Returns:
267 // - rewards: Map from token contract path to minimum reward amount; storage read or type failures panic.
268 //
269 GetTokenSpecificMinimumRewards() map[string]int64
270
271 // SetTokenSpecificMinimumRewards replaces all token-specific minimums.
272 //
273 // Parameters:
274 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
275 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
276 // - rewards: Token-path-to-minimum-amount mapping to persist.
277 //
278 // Returns:
279 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
280 //
281 SetTokenSpecificMinimumRewards(_ int, rlm realm, rewards map[string]int64) error
282
283 // SetTokenSpecificMinimumRewardItem sets one token's minimum reward entry.
284 //
285 // Parameters:
286 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
287 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
288 // - tokenPath: Token contract path whose override is being set.
289 // - amount: Token-specific minimum reward amount in token units.
290 //
291 // Returns:
292 // - err: Nil when the item is stored, ErrSpoofedRealm for a non-current realm, or the KV-store write error.
293 //
294 SetTokenSpecificMinimumRewardItem(_ int, rlm realm, tokenPath string, amount int64) error
295
296 // RemoveTokenSpecificMinimumRewardItem removes one token's minimum reward entry.
297 //
298 // Parameters:
299 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
300 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
301 // - tokenPath: Token contract path whose override is being removed.
302 //
303 // Returns:
304 // - err: Nil after rebuilding the mapping without the item, ErrSpoofedRealm for a non-current realm, or the KV-store write error.
305 //
306 RemoveTokenSpecificMinimumRewardItem(_ int, rlm realm, tokenPath string) error
307
308 // HasUnstakingFeeStoreKey reports whether the unstaking-fee key exists.
309 //
310 // Returns:
311 // - exists: True when the unstakingFee key is present in persistent storage.
312 //
313 HasUnstakingFeeStoreKey() bool
314
315 // GetUnstakingFee returns the stored reward fee rate in basis points.
316 //
317 // Returns:
318 // - fee: Persisted fee rate, where 10,000 basis points represents 100%.
319 //
320 GetUnstakingFee() uint64
321
322 // SetUnstakingFee persists the reward fee rate.
323 //
324 // Parameters:
325 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
326 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
327 // - fee: Fee rate in basis points.
328 //
329 // Returns:
330 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
331 //
332 SetUnstakingFee(_ int, rlm realm, fee uint64) error
333
334 // HasPendingProtocolFeesStoreKey reports whether pending protocol fees exist.
335 //
336 // Returns:
337 // - exists: True when the pendingProtocolFees key is present in persistent storage.
338 //
339 HasPendingProtocolFeesStoreKey() bool
340
341 // GetPendingProtocolFees returns pending protocol-fee amounts by token path.
342 //
343 // Returns:
344 // - fees: Token-path-to-amount map awaiting settlement; storage read or type failures panic.
345 //
346 GetPendingProtocolFees() map[string]int64
347
348 // SetPendingProtocolFees replaces all pending protocol-fee amounts.
349 //
350 // Parameters:
351 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
352 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
353 // - fees: Token-path-to-amount map copied into realm-owned persistent storage.
354 //
355 // Returns:
356 // - err: Nil when stored, ErrSpoofedRealm or write-permission error when unauthorized, or the KV-store write error.
357 //
358 SetPendingProtocolFees(_ int, rlm realm, fees map[string]int64) error
359
360 // GetPendingProtocolFee returns the pending amount for one token path.
361 //
362 // Parameters:
363 // - tokenPath: Token contract path whose pending amount is requested.
364 //
365 // Returns:
366 // - amount: Pending amount for the token, or zero when no entry exists.
367 //
368 GetPendingProtocolFee(tokenPath string) int64
369
370 // SetPendingProtocolFee updates one token's pending protocol-fee amount.
371 //
372 // Parameters:
373 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
374 // - rlm: Propagated current realm context; it must also be authorized for code-realm writes.
375 // - tokenPath: Token contract path whose pending amount is updated.
376 // - amount: Pending protocol-fee amount to record for the token.
377 //
378 // Returns:
379 // - err: Nil when updated, ErrSpoofedRealm or write-permission error when unauthorized, or the KV-store write error.
380 //
381 SetPendingProtocolFee(_ int, rlm realm, tokenPath string, amount int64) error
382
383 // RemovePendingProtocolFee deletes one token's pending protocol-fee entry.
384 //
385 // Parameters:
386 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
387 // - rlm: Propagated current realm context; it must also be authorized for code-realm writes.
388 // - tokenPath: Token contract path whose pending entry is deleted.
389 //
390 // Returns:
391 // - err: Nil when removed, ErrSpoofedRealm or write-permission error when unauthorized, or the KV-store write error.
392 //
393 RemovePendingProtocolFee(_ int, rlm realm, tokenPath string) error
394
395 // HasUnstakedPositionsStoreKey reports whether the exit-checkpoint tree key exists.
396 //
397 // Returns:
398 // - exists: True when the unstakedPositions key is present in persistent storage.
399 //
400 HasUnstakedPositionsStoreKey() bool
401
402 // GetUnstakedPositions returns the persisted exit-checkpoint tree.
403 //
404 // Returns:
405 // - positions: B+tree mapping position IDs to unstaked checkpoints; storage read or type failures panic.
406 //
407 GetUnstakedPositions() *bptree.BPTree
408
409 // SetUnstakedPositions persists the exit-checkpoint tree.
410 //
411 // Parameters:
412 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
413 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
414 // - positions: B+tree containing unstaked position checkpoints to persist.
415 //
416 // Returns:
417 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
418 //
419 SetUnstakedPositions(_ int, rlm realm, positions *bptree.BPTree) error
420
421 // HasUncollectedIncentiveCountsStoreKey reports whether the incentive-count tree key exists.
422 //
423 // Returns:
424 // - exists: True when the uncollectedIncentiveCounts key is present in persistent storage.
425 //
426 HasUncollectedIncentiveCountsStoreKey() bool
427
428 // GetUncollectedIncentiveCounts returns the persisted count tree for exit claims.
429 //
430 // Returns:
431 // - counts: B+tree mapping incentive IDs to uncollected checkpoint counts; storage read or type failures panic.
432 //
433 GetUncollectedIncentiveCounts() *bptree.BPTree
434
435 // SetUncollectedIncentiveCounts persists the exit-claim count tree.
436 //
437 // Parameters:
438 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
439 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
440 // - counts: B+tree containing uncollected incentive counts to persist.
441 //
442 // Returns:
443 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
444 //
445 SetUncollectedIncentiveCounts(_ int, rlm realm, counts *bptree.BPTree) error
446 // HasPoolsStoreKey reports whether the pool registry tree key exists.
447 //
448 // Returns:
449 // - exists: True when the pools key is present in persistent storage.
450 //
451 HasPoolsStoreKey() bool
452
453 // GetPools returns the persisted pool registry tree.
454 //
455 // Returns:
456 // - pools: B+tree mapping canonical pool paths to pool records; storage read or type failures panic.
457 //
458 GetPools() *bptree.BPTree
459
460 // SetPools persists the pool registry tree.
461 //
462 // Parameters:
463 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
464 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
465 // - pools: B+tree containing pool records to persist.
466 //
467 // Returns:
468 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
469 //
470 SetPools(_ int, rlm realm, pools *bptree.BPTree) error
471
472 // HasPoolTierMembershipsStoreKey reports whether pool-to-tier membership data exists.
473 //
474 // Returns:
475 // - exists: True when the poolTierMemberships key is present in persistent storage.
476 //
477 HasPoolTierMembershipsStoreKey() bool
478
479 // GetPoolTierMemberships returns the persisted pool-to-tier membership tree.
480 //
481 // Returns:
482 // - memberships: B+tree mapping pool paths to tier numbers; storage read or type failures panic.
483 //
484 GetPoolTierMemberships() *bptree.BPTree
485
486 // SetPoolTierMemberships persists pool-to-tier membership data.
487 //
488 // Parameters:
489 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
490 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
491 // - memberships: B+tree mapping pool paths to tier numbers.
492 //
493 // Returns:
494 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
495 //
496 SetPoolTierMemberships(_ int, rlm realm, memberships *bptree.BPTree) error
497
498 // HasPoolTierRatioStoreKey reports whether tier reward-ratio data exists.
499 //
500 // Returns:
501 // - exists: True when the poolTierRatio key is present in persistent storage.
502 //
503 HasPoolTierRatioStoreKey() bool
504
505 // GetPoolTierRatio returns the persisted tier-to-ratio configuration.
506 //
507 // Returns:
508 // - ratio: TierRatio configuration used to calculate pool emission shares; storage read or type failures panic.
509 //
510 GetPoolTierRatio() TierRatio
511
512 // SetPoolTierRatio persists tier reward-ratio configuration.
513 //
514 // Parameters:
515 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
516 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
517 // - ratio: TierRatio configuration to persist.
518 //
519 // Returns:
520 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
521 //
522 SetPoolTierRatio(_ int, rlm realm, ratio TierRatio) error
523
524 // HasPoolTierCountsStoreKey reports whether tier membership counts exist.
525 //
526 // Returns:
527 // - exists: True when the poolTierCounts key is present in persistent storage.
528 //
529 HasPoolTierCountsStoreKey() bool
530
531 // GetPoolTierCounts returns the fixed-size array of pool counts by tier.
532 //
533 // Returns:
534 // - counts: Per-tier pool membership counts indexed by AllTierCount; storage read or type failures panic.
535 //
536 GetPoolTierCounts() [AllTierCount]uint64
537
538 // SetPoolTierCounts persists per-tier pool membership counts.
539 //
540 // Parameters:
541 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
542 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
543 // - counts: Fixed-size per-tier pool membership counts to persist.
544 //
545 // Returns:
546 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
547 //
548 SetPoolTierCounts(_ int, rlm realm, counts [AllTierCount]uint64) error
549
550 // HasPoolTierLastRewardCacheTimestampStoreKey reports whether the reward-cache timestamp exists.
551 //
552 // Returns:
553 // - exists: True when the poolTierLastRewardCacheTimestamp key is present in persistent storage.
554 //
555 HasPoolTierLastRewardCacheTimestampStoreKey() bool
556
557 // GetPoolTierLastRewardCacheTimestamp returns the last tier reward-cache timestamp.
558 //
559 // Returns:
560 // - timestamp: Unix-second timestamp persisted after tier reward caching; read/type failures panic.
561 //
562 GetPoolTierLastRewardCacheTimestamp() int64
563
564 // SetPoolTierLastRewardCacheTimestamp persists the tier reward-cache timestamp.
565 //
566 // Parameters:
567 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
568 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
569 // - timestamp: Unix-second timestamp to persist as the last cache boundary.
570 //
571 // Returns:
572 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
573 //
574 SetPoolTierLastRewardCacheTimestamp(_ int, rlm realm, timestamp int64) error
575
576 // HasPoolTierCurrentEmissionStoreKey reports whether the current tier-emission key exists.
577 //
578 // Returns:
579 // - exists: True when the poolTierCurrentEmission key is present in persistent storage.
580 //
581 HasPoolTierCurrentEmissionStoreKey() bool
582
583 // GetPoolTierCurrentEmission returns the current GNS emission rate cached for tiers.
584 //
585 // Returns:
586 // - emission: Current per-second emission amount; storage read or type failures panic.
587 //
588 GetPoolTierCurrentEmission() int64
589
590 // SetPoolTierCurrentEmission persists the current tier-emission rate.
591 //
592 // Parameters:
593 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
594 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
595 // - emission: Current per-second GNS emission amount to persist.
596 //
597 // Returns:
598 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
599 //
600 SetPoolTierCurrentEmission(_ int, rlm realm, emission int64) error
601
602 // HasPoolTierGetEmissionStoreKey reports whether the emission-rate callback exists.
603 //
604 // Returns:
605 // - exists: True when the poolTierGetEmission key is present in persistent storage.
606 //
607 HasPoolTierGetEmissionStoreKey() bool
608
609 // GetPoolTierGetEmission returns the callback used to query current emission.
610 //
611 // Returns:
612 // - getEmission: Callback returning the current emission amount and an error; storage read or type failures panic.
613 //
614 GetPoolTierGetEmission() func() (int64, error)
615
616 // SetPoolTierGetEmission persists the callback used to query current emission.
617 //
618 // Parameters:
619 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
620 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
621 // - fn: Callback that returns the current per-second emission amount, or an error when unavailable.
622 //
623 // Returns:
624 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
625 //
626 SetPoolTierGetEmission(_ int, rlm realm, fn func() (int64, error)) error
627
628 // HasPoolTierGetHalvingBlocksInRangeStoreKey reports whether the halving-range callback exists.
629 //
630 // Returns:
631 // - exists: True when the poolTierGetHalvingBlocksInRange key is present in persistent storage.
632 //
633 HasPoolTierGetHalvingBlocksInRangeStoreKey() bool
634
635 // GetPoolTierGetHalvingBlocksInRange returns the callback used to query
636 // halving timestamps and matching emission amounts for a time range.
637 //
638 // Returns:
639 // - getHalvingBlocksInRange: Callback taking [start,end) timestamps and returning ascending halving timestamps, corresponding emissions, and an error; storage read or type failures panic.
640 //
641 GetPoolTierGetHalvingBlocksInRange() func(start, end int64) ([]int64, []int64, error)
642
643 // SetPoolTierGetHalvingBlocksInRange persists the halving-range callback.
644 //
645 // Parameters:
646 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
647 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
648 // - fn: Callback taking a [start,end) timestamp interval and returning matching halving timestamps, emission amounts, and an error.
649 //
650 // Returns:
651 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
652 //
653 SetPoolTierGetHalvingBlocksInRange(_ int, rlm realm, fn func(start, end int64) ([]int64, []int64, error)) error
654
655 // HasWarmupTemplateStoreKey reports whether the warm-up template key exists.
656 //
657 // Returns:
658 // - exists: True when the warmupTemplate key is present in persistent storage.
659 //
660 HasWarmupTemplateStoreKey() bool
661
662 // GetWarmupTemplate returns a copy of the warm-up schedule for new deposits.
663 //
664 // Returns:
665 // - warmups: Caller-safe copy of ordered warm-up ratio and duration entries.
666 //
667 GetWarmupTemplate() []Warmup
668
669 // SetWarmupTemplate replaces the warm-up schedule for new deposits.
670 //
671 // Parameters:
672 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
673 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
674 // - warmups: Ordered warm-up ratio and duration entries to persist.
675 //
676 // Returns:
677 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
678 //
679 SetWarmupTemplate(_ int, rlm realm, warmups []Warmup) error
680
681 // HasCurrentSwapBatchStoreKey reports whether the current swap-batch key exists.
682 //
683 // Returns:
684 // - exists: True when the currentSwapBatch key is present in persistent storage.
685 //
686 HasCurrentSwapBatchStoreKey() bool
687
688 // GetCurrentSwapBatch returns the persisted swap-batch processor state.
689 //
690 // Returns:
691 // - batch: Current SwapBatchProcessor pointer; storage read or type failures panic.
692 //
693 GetCurrentSwapBatch() *SwapBatchProcessor
694
695 // SetCurrentSwapBatch persists the current swap-batch processor state.
696 //
697 // Parameters:
698 // - _: Leading integer discriminator for internal store forwarding; callers pass 0.
699 // - rlm: Propagated current realm context; a non-current realm is rejected before writing.
700 // - batch: SwapBatchProcessor state to persist for the current batch.
701 //
702 // Returns:
703 // - err: Nil when stored, ErrSpoofedRealm for a non-current realm, or the underlying KV-store write error.
704 //
705 SetCurrentSwapBatch(_ int, rlm realm, batch *SwapBatchProcessor) error
706}type Incentives
structIncentives represents a collection of external incentives for a specific pool.
Fields:
-
incentives: BPTree storing ExternalIncentive objects indexed by incentiveId The incentiveId serves as the key to efficiently lookup incentive details
-
targetPoolPath: String identifier for the pool this incentive collection belongs to Used to associate incentives with their corresponding liquidity pool
-
unclaimablePeriods: Tree storing periods when rewards cannot be claimed Maps start timestamp (key) to end timestamp (value) An end timestamp of 0 indicates an ongoing unclaimable period Used to track intervals when staking rewards are not claimable
-
byStartTime: Per-pool start-time index mapping an incentive's start timestamp (key) to the incentive IDs that start at that timestamp (value). This mirrors the lazy-discovery lookup previously served by a global creation-time index, but scoped to this pool's own incentives, so discovery cost is bounded by this pool's incentives instead of growing with the total number of incentives system-wide.
Methods on Incentives
func AddIncentiveByStartTime
method on IncentivesAddIncentiveByStartTime registers an incentive ID under its start timestamp in the per-pool start-time index. Multiple incentives starting at the same timestamp are accumulated as a list.
Parameters:
- startTimestamp: Nonnegative Unix timestamp in seconds used as the start-time index key.
- incentiveId: Incentive identifier to append to that timestamp's bucket.
func Incentive
method on IncentivesIncentive returns an incentive by ID
Parameters:
- incentiveId: Identifier used to look up the external incentive record.
Returns:
- incentive: Matching ExternalIncentive pointer, or nil when no value is stored for incentiveId.
- found: True only when the stored value has ExternalIncentive type; false for a missing or mismatched value.
func IncentiveTrees
method on IncentivesIncentives returns the incentives tree
Returns:
- tree: Mutable B+ tree mapping incentive IDs to ExternalIncentive records.
func IterateIncentiveIdsByTime
method on Incentives1func (i *Incentives) IterateIncentiveIdsByTime(startTime, endTime int64, fn func(incentiveId string) bool)IterateIncentiveIdsByTime iterates over the incentive IDs that start within the inclusive [startTime, endTime] range, visiting only the buckets that fall in the range. ReverseIterate is used because it is inclusive on both ends, matching the discovery semantics previously implemented as (startTimestamp >= startTime && startTimestamp <= endTime).
Parameters:
- startTime: Inclusive lower Unix timestamp bound for incentive starts.
- endTime: Inclusive upper Unix timestamp bound for incentive starts.
- fn: Callback receiving each matching incentive ID; returning true requests that iteration stop.
func IterateIncentives
method on Incentives1func (i *Incentives) IterateIncentives(fn func(incentiveId string, incentive *ExternalIncentive) bool)IterateIncentives iterates over all incentives
Parameters:
- fn: Callback receiving each incentive ID and record; returning true requests that iteration stop.
func RemoveIncentive
method on IncentivesRemoveIncentive deletes an incentive by ID.
Only an incentive that never started may be removed: once rewards begin accruing, deposits and the refund accounting reference the record, so an ended incentive is marked refunded instead of removed.
Parameters:
- incentiveId: Identifier of the external incentive record to remove.
func RemoveIncentiveByStartTime
method on IncentivesRemoveIncentiveByStartTime unregisters an incentive ID from the per-pool start-time index. The bucket itself is dropped once its last ID is removed, so the index never keeps an empty entry that discovery would still visit.
Parameters:
- startTimestamp: Nonnegative Unix timestamp in seconds identifying the start-time bucket.
- incentiveId: Incentive identifier to remove from that bucket; all matching entries are omitted.
func RemoveUnclaimablePeriod
method on IncentivesRemoveUnclaimablePeriod removes the interval keyed by its start timestamp.
Parameters:
- startTimestamp: Nonnegative Unix timestamp in seconds identifying the interval to remove.
func SetIncentive
method on IncentivesSetIncentive sets an incentive by ID
Parameters:
- incentiveId: Identifier under which to store the incentive.
- incentive: ExternalIncentive record to store for incentiveId.
func SetIncentives
method on IncentivesSetIncentives sets the incentives tree
Parameters:
- incentives: B+ tree to use for incentive ID lookups and storage.
func SetTargetPoolPath
method on IncentivesSetTargetPoolPath sets the target pool path
Parameters:
- targetPoolPath: Pool path to associate with this incentive collection.
func SetUnclaimablePeriod
method on IncentivesSetUnclaimablePeriod records an interval during which staking rewards cannot be claimed.
Parameters:
- startTimestamp: Nonnegative Unix timestamp in seconds at which the interval begins.
- endTimestamp: Unix timestamp in seconds at which the interval ends; 0 records an ongoing interval.
func SetUnclaimablePeriods
method on IncentivesSetUnclaimablePeriods sets the unclaimable periods tree
Parameters:
- unclaimablePeriods: Tree of reward-unclaimable intervals keyed by their start timestamps.
func TargetPoolPath
method on IncentivesTargetPoolPath returns the target pool path
Returns:
- path: Pool path to which this incentive collection belongs.
func UnclaimablePeriods
method on IncentivesUnclaimablePeriods returns the unclaimable periods tree
Returns:
- periods: Tree mapping unclaimable-period start timestamps to end timestamps; end 0 denotes an open period.
type NFTAccessor
interface 1type NFTAccessor interface {
2 // Approve grants an address permission to transfer a specific NFT.
3 //
4 // Parameters:
5 // - _: Internal call discriminator; callers pass 0.
6 // - rlm: Propagated realm context; it must be current before crossing into the NFT realm.
7 // - approved: Address receiving permission for tid.
8 // - tid: NFT token ID whose approval is changed.
9 //
10 // Returns:
11 // - error: Non-nil when the NFT realm rejects the approval or the realm context is spoofed; nil on success.
12 Approve(_ int, rlm realm, approved address, tid grc721.TokenID) error
13
14 // Mint creates an NFT with tid and transfers it to to.
15 //
16 // Parameters:
17 // - _: Internal call discriminator; callers pass 0.
18 // - rlm: Propagated realm context; it must be current before crossing into the NFT realm.
19 // - to: Address receiving the newly minted NFT.
20 // - tid: Token ID to mint.
21 //
22 // Returns:
23 // - grc721.TokenID: The minted token ID, equal to tid.
24 Mint(_ int, rlm realm, to address, tid grc721.TokenID) grc721.TokenID
25
26 // Burn destroys an NFT.
27 //
28 // Parameters:
29 // - _: Internal call discriminator; callers pass 0.
30 // - rlm: Propagated realm context; it must be current before crossing into the NFT realm.
31 // - tid: NFT token ID to burn.
32 Burn(_ int, rlm realm, tid grc721.TokenID)
33
34 // TransferFrom moves an NFT from its current owner to another address.
35 //
36 // Parameters:
37 // - _: Internal call discriminator; callers pass 0.
38 // - rlm: Propagated realm context; it must be current before crossing into the NFT realm.
39 // - from: Current owner address of tid.
40 // - to: Recipient address for tid.
41 // - tid: NFT token ID to transfer.
42 //
43 // Returns:
44 // - error: Non-nil when the NFT realm rejects the transfer or the realm context is spoofed; nil on success.
45 TransferFrom(_ int, rlm realm, from, to address, tid grc721.TokenID) error
46
47 // TotalSupply returns the number of NFTs currently minted and not burned.
48 //
49 // Returns:
50 // - int64: Current NFT collection supply.
51 TotalSupply() int64
52
53 // Exists reports whether an NFT token ID is currently minted.
54 //
55 // Parameters:
56 // - tid: NFT token ID to look up.
57 //
58 // Returns:
59 // - bool: true when tid has an owner in the NFT ledger; false when it does not exist.
60 Exists(tid grc721.TokenID) bool
61
62 // MustOwnerOf returns the owner of an NFT and panics when tid is invalid.
63 //
64 // Parameters:
65 // - tid: NFT token ID whose owner is required.
66 //
67 // Returns:
68 // - address: Current owner address of tid; the accessor panics if tid does not exist.
69 MustOwnerOf(tid grc721.TokenID) address
70
71 // OwnerOf returns the owner of an NFT without panicking on lookup failure.
72 //
73 // Parameters:
74 // - tid: NFT token ID whose owner is queried.
75 //
76 // Returns:
77 // - address: Current owner address, or the zero address when lookup fails.
78 // - error: Non-nil when tid does not exist or the NFT realm cannot resolve its owner.
79 OwnerOf(tid grc721.TokenID) (address, error)
80}type Pool
struct 1type Pool struct {
2 poolPath string
3
4 stakedLiquidity *UintTree // uint64 timestamp -> *u256.Uint(Q128)
5
6 lastUnclaimableTime int64
7 unclaimableAcc int64
8
9 rewardCache *UintTree // uint64 timestamp -> int64 gnsReward
10
11 incentives *Incentives
12
13 ticks Ticks // int32 tickId -> Tick tick
14
15 globalRewardRatioAccumulation *UintTree // uint64 timestamp -> *u256.Uint(Q128) rewardRatioAccumulation
16
17 historicalTick *UintTree // uint64 timestamp -> int32 tickId
18}Pool is a struct for storing an incentivized pool information Each pool stores Incentives and Ticks associated with it.
Fields: - poolPath: The path of the pool.
-
stakedLiquidity: The current total staked liquidity of the in-range positions for the pool. Updated when tick cross happens or stake/unstake happens. Used to calculate the global reward ratio accumulation or decide whether to enter/exit unclaimable period.
-
lastUnclaimableTime: The time at which the unclaimable period started. Set to 0 when the pool is not in an unclaimable period.
-
unclaimableAcc: The accumulated undistributed unclaimable reward. Reset to 0 when processUnclaimableReward is called and sent to community pool.
-
rewardCache: The cached per-second reward emitted for this pool. Stores new entry only when the reward is changed. PoolTier.cacheReward() updates this.
- incentives: The external incentives associated with the pool.
- ticks: The Ticks associated with the pool.
-
globalRewardRatioAccumulation: Global ratio of Time / TotalStake accumulation(since the pool creation) Stores new entry only when tick cross or stake/unstake happens. It is used to calculate the reward for a staked position at certain time.
-
historicalTick: The historical tick for the pool at a given time. It does not reflect the exact tick at the timestamp, but it provides correct ordering for the staked position's ticks. Therefore, you should not compare it for equality, only for ordering. Set when tick cross happens or a new position is created.
Methods on Pool
func Clone
method on PoolClone returns a pool copy of the scalar state with a fresh tick container.
Returns:
- pool: Pool copy carrying scalar state and a fresh tick container; backing trees and incentives are nil, and nil receiver yields nil.
func GlobalRewardRatioAccumulation
method on PoolGlobalRewardRatioAccumulation returns the global reward ratio accumulation tree
Returns:
- tree: Historical global time-per-total-stake accumulation keyed by Unix timestamp.
func HistoricalTick
method on PoolHistoricalTick returns the historical tick tree
Returns:
- tree: Historical tick-ID ordering snapshots keyed by Unix timestamp.
func Incentives
method on PoolIncentives returns the incentives
Returns:
- incentives: External-incentive collection associated with this pool.
func LastUnclaimableTime
method on PoolLastUnclaimableTime returns the last unclaimable time
Returns:
- timestamp: Unix timestamp in seconds at which the pool entered its current unclaimable period, or 0 when tracking has not started.
func PoolPath
method on PoolPoolPath returns the pool path
Returns:
- path: Pool identifier used to associate this state with a liquidity pool.
func RewardCache
method on PoolRewardCache returns the reward cache tree
Returns:
- tree: Historical per-second GNS reward cache keyed by Unix timestamp.
func SetGlobalRewardRatioAccumulation
method on PoolSetGlobalRewardRatioAccumulation sets the global reward ratio accumulation tree
Parameters:
- globalRewardRatioAccumulation: Tree of serialized Q128-scaled reward-ratio accumulation snapshots.
func SetGlobalRewardRatioAccumulationAt
method on PoolSetGlobalRewardRatioAccumulationAt records a serialized global reward-ratio accumulation snapshot.
Parameters:
- currentTime: Nonnegative Unix timestamp in seconds used as the snapshot key.
- acc: Serialized Q128-scaled global reward-ratio accumulation value.
func SetHistoricalTick
method on PoolSetHistoricalTick sets the historical tick tree
Parameters:
- historicalTick: Tree of tick IDs representing the ordering history of staked positions.
func SetHistoricalTickAt
method on PoolSetHistoricalTickAt records the tick ordering snapshot for a timestamp.
Parameters:
- currentTime: Nonnegative Unix timestamp in seconds used as the snapshot key.
- tick: Tick ID representing the pool's historical ordering at currentTime.
func SetIncentives
method on PoolSetIncentives sets the incentives
Parameters:
- incentives: External-incentive collection to associate with the pool.
func SetLastUnclaimableTime
method on PoolSetLastUnclaimableTime sets the last unclaimable time
Parameters:
- lastUnclaimableTime: Unix timestamp in seconds marking the start of the current unclaimable period; use 0 when no period is active.
func SetPoolPath
method on PoolSetPoolPath sets the pool path
Parameters:
- poolPath: Pool identifier to store.
func SetRewardCache
method on PoolSetRewardCache sets the reward cache tree
Parameters:
- rewardCache: Tree containing the pool's per-second GNS reward snapshots.
func SetRewardCacheAt
method on PoolSetRewardCacheAt records the per-second reward rate for a timestamp.
Parameters:
- currentTime: Nonnegative Unix timestamp in seconds used as the cache key.
- reward: GNS reward emitted per second from currentTime until the next cached change.
func SetStakedLiquidity
method on PoolSetStakedLiquidity sets the staked liquidity tree
Parameters:
- stakedLiquidity: Tree of historical total staked liquidity snapshots.
func SetStakedLiquidityAt
method on PoolSetStakedLiquidityAt records the current total staked liquidity at a timestamp.
Parameters:
- currentTime: Nonnegative Unix timestamp in seconds used as the snapshot key.
- delta: Total staked liquidity at currentTime, stored as a copied Q128-scaled uint value.
func SetTicks
method on PoolSetTicks sets the ticks
Parameters:
- ticks: Tick mapping value to store in the pool.
func SetUnclaimableAcc
method on PoolSetUnclaimableAcc sets the unclaimable accumulation
Parameters:
- unclaimableAcc: Accumulated undistributed unclaimable reward amount in the pool's int64 reward units.
func StakedLiquidity
method on PoolStakedLiquidity returns the staked liquidity tree
Returns:
- tree: Historical staked-liquidity tree keyed by Unix timestamp, with Q128-scaled liquidity values.
func Ticks
method on PoolTicks returns the ticks
Returns:
- ticks: Addressable tick mapping for this pool's staked positions.
func UnclaimableAcc
method on PoolUnclaimableAcc returns the unclaimable accumulation
Returns:
- amount: Accumulated undistributed unclaimable reward amount in the pool's int64 reward units.
type PoolAccessor
interface 1type PoolAccessor interface {
2 // ExistsPoolPath reports whether a pool is registered at poolPath.
3 //
4 // Parameters:
5 // - poolPath: Pool path whose registration is checked.
6 //
7 // Returns:
8 // - bool: true when a pool is registered at poolPath; false otherwise.
9 ExistsPoolPath(poolPath string) bool
10 // GetSlot0Tick returns the current slot-0 tick for a registered pool.
11 //
12 // Parameters:
13 // - poolPath: Pool path whose current tick is queried.
14 //
15 // Returns:
16 // - int32: Current signed slot-0 tick; the accessor panics if the underlying pool query fails.
17 GetSlot0Tick(poolPath string) int32
18 // GetSlot0SqrtPriceX96 returns a pool's current Q96-scaled square-root price.
19 //
20 // Parameters:
21 // - poolPath: Pool path whose current square-root price is queried.
22 //
23 // Returns:
24 // - string: Decimal representation of the Q96-scaled square-root price; the accessor panics if the underlying query fails.
25 GetSlot0SqrtPriceX96(poolPath string) string
26
27 // SetTickCrossHook registers a callback for pool tick-crossing events.
28 //
29 // Parameters:
30 // - _: Internal call discriminator; callers pass 0.
31 // - rlm: Propagated realm context; it must be current before the hook is registered.
32 // - hook: Callback invoked with the internal discriminator, current pool realm, pool path, crossed tick ID, swap direction (zeroForOne), and the event timestamp in Unix seconds.
33 SetTickCrossHook(_ int, rlm realm, hook func(_ int, rlm realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64))
34 // SetSwapStartHook registers a callback invoked when a pool swap starts.
35 //
36 // Parameters:
37 // - _: Internal call discriminator; callers pass 0.
38 // - rlm: Propagated realm context; it must be current before the hook is registered.
39 // - hook: Callback invoked with the internal discriminator, current pool realm, pool path, and swap-start timestamp in Unix seconds.
40 SetSwapStartHook(_ int, rlm realm, hook func(_ int, rlm realm, poolPath string, timestamp int64))
41 // SetSwapEndHook registers a callback invoked when a pool swap ends.
42 //
43 // Parameters:
44 // - _: Internal call discriminator; callers pass 0.
45 // - rlm: Propagated realm context; it must be current before the hook is registered.
46 // - hook: Callback invoked with the internal discriminator, current pool realm, and pool path; its error is propagated by the pool hook.
47 SetSwapEndHook(_ int, rlm realm, hook func(_ int, rlm realm, poolPath string) error)
48}type StoreKey
identtype SwapBatchProcessor
struct1type SwapBatchProcessor struct {
2 poolPath string // The pool path identifier for this swap
3 pool *Pool // Reference to the pool being swapped in
4 crosses []*SwapTickCross // Accumulated tick crosses during the swap
5 timestamp int64 // Timestamp when the swap started
6 isActive bool // Flag to prevent accumulation after swap ends
7}SwapBatchProcessor processes tick crosses in batch for a swap This processor accumulates all tick crosses that occur during a single swap and processes them together at the end, reducing redundant calculations and state updates that would occur with individual tick processing
Methods on SwapBatchProcessor
func AddCross
method on SwapBatchProcessorAddCross appends a tick-cross record to the batch sequence.
Parameters:
- tickCross: Tick-cross record to append.
func Crosses
method on SwapBatchProcessorCrosses returns the tick crosses accumulated by this batch.
Returns:
- crosses: Slice of tick-cross records in the order they were added.
func IsActive
method on SwapBatchProcessorIsActive reports the processor's stored active flag.
Returns:
- active: True when the batch is marked active for the swap lifecycle.
func LastCross
method on SwapBatchProcessorLastCross returns the most recently appended tick cross.
Returns:
- cross: Last tick-cross record, or nil when no crosses have been added.
func Pool
method on SwapBatchProcessorPool returns the pool referenced by this swap batch.
Returns:
- pool: Pool state used to process the accumulated tick crosses.
func PoolPath
method on SwapBatchProcessorPoolPath returns the pool path associated with this swap batch.
Returns:
- path: Pool identifier for the swap being processed.
func SetCrosses
method on SwapBatchProcessorSetCrosses replaces the batch's accumulated tick-cross sequence.
Parameters:
- crosses: Tick-cross records to store as the batch's accumulated sequence.
func SetIsActive
method on SwapBatchProcessorSetIsActive stores the processor's active lifecycle flag.
Parameters:
- isActive: Active flag to store for the swap lifecycle.
func SetPool
method on SwapBatchProcessorSetPool replaces the pool reference used by this swap batch.
Parameters:
- pool: Pool state to reference while processing tick crosses.
func SetPoolPath
method on SwapBatchProcessorSetPoolPath stores the pool identifier associated with this swap batch.
Parameters:
- poolPath: Pool identifier to associate with the swap batch.
func SetTimestamp
method on SwapBatchProcessorSetTimestamp stores the swap-start timestamp for this batch.
Parameters:
- timestamp: Unix timestamp in seconds to record for the swap batch.
func Timestamp
method on SwapBatchProcessorTimestamp returns the Unix timestamp in seconds recorded when the swap started.
Returns:
- timestamp: Swap-start timestamp in Unix seconds.
type SwapTickCross
structSwapTickCross stores information about a tick cross during a swap This struct is used to accumulate tick cross events during a single swap transaction for batch processing to optimize gas usage and computational efficiency
Methods on SwapTickCross
func Delta
method on SwapTickCrossDelta returns the precomputed net staked-liquidity change for the crossed tick.
Returns:
- delta: Signed liquidity delta to apply at the crossed tick.
func TickID
method on SwapTickCrossTickID returns the index of the crossed tick.
Returns:
- tickID: Tick index represented by this cross.
func ZeroForOne
method on SwapTickCrossZeroForOne reports the swap direction represented by this cross.
Returns:
- zeroForOne: True for token0-to-token1 swaps; false for token1-to-token0 swaps.
type Tick
struct 1type Tick struct {
2 id int32
3
4 // conceptually equal with Pool.liquidityGross but only for the staked positions
5 stakedLiquidityGross *u256.Uint
6
7 // conceptually equal with Pool.liquidityNet but only for the staked positions
8 stakedLiquidityDelta *i256.Int
9
10 // currentOutsideAccumulation is the accumulation of the time / TotalStake outside the tick.
11 // It is calculated by subtracting the current tick's currentOutsideAccumulation from the global reward ratio accumulation.
12 outsideAccumulation *UintTree // timestamp -> fixed 32-byte big-endian string
13}Tick represents the state of a specific tick in a pool.
Fields: - id (int32): The ID of the tick. - stakedLiquidityGross (*u256.Uint): Total gross staked liquidity at this tick. - stakedLiquidityDelta (*i256.Int): Net change in staked liquidity at this tick. - outsideAccumulation (*UintTree): RewardRatioAccumulation outside the tick.
Methods on Tick
func Clone
method on TickClone returns a deep copy of the tick.
Returns:
- tick: Deep copy of the tick and its outside-accumulation tree, or nil when the receiver is nil.
func Id
method on TickId returns the tick ID
Returns:
- id: Tick index represented by this record.
func OutsideAccumulation
method on TickOutsideAccumulation returns the outside accumulation tree
Returns:
- tree: Historical reward-ratio accumulation observed outside this tick.
func SetId
method on TickSetId sets the tick ID
Parameters:
- id: Tick index to store in the record.
func SetOutsideAccumulation
method on TickSetOutsideAccumulation sets the outside accumulation tree
Parameters:
- outsideAccumulation: UintTree of outside-accumulation snapshots keyed by Unix timestamp.
func SetOutsideAccumulationAt
method on TickSetOutsideAccumulationAt sets the outside accumulation at the timestamp. SetOutsideAccumulationAt records the Q128-scaled outside accumulation at a timestamp.
Parameters:
- timestamp: Nonnegative Unix timestamp in seconds used as the snapshot key.
- acc: Q128-scaled accumulation value encoded into the tree.
func SetStakedLiquidityDelta
method on TickSetStakedLiquidityDelta sets the staked liquidity delta
Parameters:
- stakedLiquidityDelta: New net staked liquidity delta; the value is copied before storage.
func SetStakedLiquidityGross
method on TickSetStakedLiquidityGross sets the staked liquidity gross
Parameters:
- stakedLiquidityGross: New total gross staked liquidity; the value is copied before storage.
func StakedLiquidityDelta
method on TickStakedLiquidityDelta returns the staked liquidity delta
Returns:
- delta: Net staked liquidity change associated with this tick.
func StakedLiquidityGross
method on TickStakedLiquidityGross returns the staked liquidity gross
Returns:
- liquidity: Total gross staked liquidity currently associated with this tick.
type Ticks
structTick mapping for each pool
Methods on Ticks
func Clone
method on TicksClone returns a deep copy of ticks.
Returns:
- ticks: New Ticks value with cloned Tick records in a fresh fanout-16 tree.
func Get
method on TicksGet returns the tick for the given tickId, or nil if it does not exist.
Parameters:
- tickId: Tick index to look up.
Returns:
- tick: Matching Tick record, or nil when the encoded ID is absent; panics if a stored value has the wrong type.
func Has
method on TicksHas reports whether a tick ID is present in the underlying tree.
Parameters:
- tickId: Tick index whose encoded key is tested.
Returns:
- present: True when the encoded tick ID exists in the underlying tree.
func IterateTicks
method on TicksIterateTicks iterates over all ticks
Parameters:
- fn: Callback receiving each stored Tick and decoded tick ID; returning true requests that iteration stop.
func SetTick
method on TicksSetTick sets a tick by ID
Parameters:
- tickId: Tick index under which to store the record.
- tick: Non-nil Tick record to store; a zero gross staked liquidity removes the tick instead, while nil input panics during the gross-liquidity check.
func SetTree
method on TicksSetTree sets the ticks tree
Parameters:
- tree: B+ tree to use for tick storage.
func Tree
method on TicksTree returns the ticks tree
Returns:
- tree: Mutable B+ tree mapping encoded int32 tick IDs to Tick records.
type TierRatio
struct100%, 0%, 0% if no tier2 and tier3 80%, 0%, 20% if no tier2 70%, 30%, 0% if no tier3 50%, 30%, 20% if has tier2 and tier3
Methods on TierRatio
func Get
method on TierRatioGet returns the ratio(scaled up by 100) for the given tier.
Parameters:
- tier: Tier number to query; only tiers 1, 2, and 3 are supported.
Returns:
- ratio: Requested tier share scaled by 100.
- err: Non-nil when tier is not 1, 2, or 3; nil for a supported tier.
type UintTree
structUintTree wraps a B+ tree with nonnegative int64 timestamp keys, encoded as fixed-width 8-byte big-endian strings to preserve numeric ordering.
Methods: - Get: Retrieves a value associated with an int64 key. - Set: Stores a value with an int64 key. - Has: Checks if an int64 key exists in the tree. - Remove: Removes an int64 key and its associated value. - Iterate: Iterates over keys and values in a range. - ReverseIterate: Iterates in reverse order over keys and values in a range.
Methods on UintTree
func Clone
method on UintTreeClone returns a new UintTree with the same encoded keys and stored value references.
Returns:
- tree: New UintTree preserving this tree's fanout and entries; pointed-to values are not deep-cloned.
func Get
method on UintTreeGet looks up a value by its nonnegative int64 key.
Parameters:
- key: Nonnegative timestamp-like key encoded into the tree's ordered key format.
Returns:
- value: Stored value when the key maps to a non-nil entry; nil when absent.
- found: True when a non-nil value exists for key, and false otherwise.
func Has
method on UintTreeHas reports whether an encoded key is present in the underlying tree.
Parameters:
- key: Nonnegative timestamp-like key to test; negative values panic during encoding.
Returns:
- present: True when the underlying tree contains key, including entries whose value may be nil according to the B+ tree.
func Iterate
method on UintTreeIterate visits entries in ascending key order over the underlying tree range.
Parameters:
- start: Nonnegative lower bound for the encoded key range.
- end: Nonnegative upper bound for the encoded key range.
- fn: Callback receiving each decoded key and value; returning true requests that iteration stop.
func IterateByOffset
method on UintTree1func (self *UintTree) IterateByOffset(offset, count int, fn func(key int64, value any) bool)IterateByOffset visits a page of entries beginning at an offset.
Parameters:
- offset: Zero-based number of entries to skip before invoking fn.
- count: Maximum number of entries to visit.
- fn: Callback receiving each decoded key and value; returning true requests that iteration stop.
func ReadOnly
method on UintTreeReadOnly returns a read-only view of the underlying tree, so callers can paginate it without gaining a handle on the mutable tree.
Keys use utils.EncodeUint64's fixed-width binary encoding, not the int64 keys this type takes; utils.DecodeUint64 recovers the nonnegative value.
Parameters:
- makeEntrySafeFn: Callback that converts each stored value into the representation exposed through the read-only view.
Returns:
- tree: Read-only wrapper over the underlying tree for safe pagination.
func Remove
method on UintTreeRemove deletes the value stored under a key, if any.
Parameters:
- key: Nonnegative timestamp-like key to remove; negative values panic during encoding.
func ReverseIterate
method on UintTreeReverseIterate visits entries in descending key order over the underlying tree range.
Parameters:
- start: Nonnegative lower bound for the encoded key range.
- end: Nonnegative upper bound for the encoded key range.
- fn: Callback receiving each decoded key and value; returning true requests that iteration stop.
func Set
method on UintTreeSet stores a value under a nonnegative int64 key.
Parameters:
- key: Nonnegative timestamp-like key used as the ordered tree key; negative values panic.
- value: Value to associate with key.
func Size
method on UintTreeSize returns the number of entries currently stored in the tree.
Returns:
- size: Number of key/value entries in the underlying B+ tree.
type UnstakedPosition
struct 1type UnstakedPosition struct {
2 deposit *Deposit
3 exitTime int64
4 exitTick int32
5 lowerTick *Tick
6 upperTick *Tick
7
8 // Outside accumulations of the two boundary ticks at exitTime, as decimal strings. Entries
9 // before exitTime can no longer change, but the one at exitTime can be overwritten by a tick
10 // cross later in the same block, so it is pinned rather than read back.
11 lowerOutsideAcc string
12 upperOutsideAcc string
13
14 tier uint64
15 tierRatio uint64
16 tierCount uint64
17
18 // unstakingFee is the staking-reward fee rate in force at exitTime. The window closed under
19 // it, so a later rate change must not apply retroactively at collect time.
20 unstakingFee uint64
21
22 emissionCollected bool
23 pendingIncentiveIds map[string]bool
24}UnstakedPosition is the exit checkpoint of a position that left the pool before collecting.
It pins the pool state a later collect must reproduce the exit-time reward from: the tick observed at the exit, the two boundary ticks (which the unstake may prune from the pool), and the tier context (which a later tier change would otherwise re-rate the window with). Collection is per source, so the checkpoint tracks what is left and is dropped when nothing is.
Methods on UnstakedPosition
func Deposit
method on UnstakedPositionDeposit returns the deposit snapshot captured when this position was unstaked.
Returns:
- deposit: Stored deposit state, including its owner, pool, liquidity, ticks, warmups, and collected reward fields.
func EmissionCollected
method on UnstakedPositionEmissionCollected reports whether the emission reward has been collected.
Returns:
- collected: True after MarkEmissionCollected has been called; false while the internal reward remains pending.
func ExitTick
method on UnstakedPositionExitTick returns the pool tick observed at ExitTime.
Returns:
- exitTick: Tick value used to determine the position's in-range status at the exit checkpoint.
func ExitTime
method on UnstakedPositionExitTime returns the timestamp at which the position stopped accruing rewards.
Returns:
- exitTime: Unix timestamp pinned as the end of this position's reward-accrual window.
func FullyCollected
method on UnstakedPositionFullyCollected reports whether every reward source has been collected.
Returns:
- collected: True only when the internal emission flag is set and no external incentive IDs remain pending.
func HasPendingIncentiveId
method on UnstakedPositionHasPendingIncentiveId reports whether the incentive is still to be collected.
Parameters:
- incentiveId: External incentive identifier to look up in this checkpoint's pending set.
Returns:
- pending: True when incentiveId is currently pending; false when it is absent or the pending set is nil.
func HasPendingIncentives
method on UnstakedPositionHasPendingIncentives reports whether any incentive is still to be collected.
Returns:
- pending: True when at least one external incentive ID remains pending; false otherwise.
func LowerOutsideAcc
method on UnstakedPositionLowerOutsideAcc returns the lower boundary tick's outside accumulation at ExitTime.
Returns:
- lowerOutsideAcc: Decimal-encoded reward-ratio accumulation outside the lower boundary at exit.
func LowerTick
method on UnstakedPositionLowerTick returns the position's lower boundary tick snapshot.
Returns:
- lowerTick: Stored lower boundary tick used when calculating rewards for this exit checkpoint.
func MarkEmissionCollected
method on UnstakedPositionMarkEmissionCollected records that the emission reward has been collected.
func MarkIncentiveCollected
method on UnstakedPositionMarkIncentiveCollected records that the incentive has been collected.
Parameters:
- incentiveId: External incentive identifier to remove from the pending set.
func PendingIncentiveCount
method on UnstakedPositionPendingIncentiveCount returns how many incentives are still to be collected.
Returns:
- count: Number of external incentive IDs currently pending in the checkpoint.
func PendingIncentiveIdList
method on UnstakedPositionPendingIncentiveIdList returns the incentives still to be collected.
Returns:
- incentiveIds: IDs currently present in the pending set; iteration order is unspecified.
func Tier
method on UnstakedPositionTier returns the pool's emission tier at ExitTime, or 0 when it was not tiered.
Returns:
- tier: Tier identifier pinned at exit; zero means no emission tier applied.
func TierCount
method on UnstakedPositionTierCount returns how many pools shared the tier at ExitTime.
Returns:
- tierCount: Number of pools in the pinned tier when the position exited.
func TierRatio
method on UnstakedPositionTierRatio returns the tier's emission ratio at ExitTime.
Returns:
- tierRatio: Stored scaled reward-share ratio for the pinned tier at exit.
func UnstakingFee
method on UnstakedPositionUnstakingFee returns the staking-reward fee rate in force at ExitTime.
Returns:
- unstakingFee: Fee rate pinned for this exit in basis points (0-1,000; 100 = 1%).
func UpperOutsideAcc
method on UnstakedPositionUpperOutsideAcc returns the upper boundary tick's outside accumulation at ExitTime.
Returns:
- upperOutsideAcc: Decimal-encoded reward-ratio accumulation outside the upper boundary at exit.
func UpperTick
method on UnstakedPositionUpperTick returns the position's upper boundary tick snapshot.
Returns:
- upperTick: Stored upper boundary tick used when calculating rewards for this exit checkpoint.
type Warmup
structMethods on Warmup
func SetNextWarmupTime
method on WarmupSetNextWarmupTime updates the Unix timestamp at which this warmup tier ends.
Parameters:
- nextWarmupTime: Tier end time in Unix seconds.
func SetTimeDuration
method on WarmupSetTimeDuration updates the duration of this warmup tier.
Parameters:
- timeDuration: Tier duration in seconds.
func SetWarmupRatio
method on WarmupSetWarmupRatio updates the percentage of calculated reward credited to the position.
Parameters:
- warmupRatio: Reward percentage for this tier, expressed from 0 to 100.
20
- errors stdlib
- gno.land/p/gnoswap/consts/v1 package
- gno.land/p/gnoswap/gnsmath/v1 package
- gno.land/p/gnoswap/int256/v1 package
- gno.land/p/gnoswap/rbac/v1 package
- gno.land/p/gnoswap/store/v1 package
- gno.land/p/gnoswap/uint256/v1 package
- gno.land/p/gnoswap/utils/v1 package
- gno.land/p/gnoswap/version_manager/v1 package
- gno.land/p/nt/bptree/rotree/v0 package
- gno.land/p/nt/bptree/v0 package
- gno.land/p/nt/grc721/v0 package
- gno.land/p/nt/ufmt/v0 package
- gno.land/r/gnoswap/access/v1 realm
- gno.land/r/gnoswap/emission realm
- gno.land/r/gnoswap/gnft realm
- gno.land/r/gnoswap/pool realm
- gno.land/r/gnoswap/rbac/v1 realm
- math stdlib
- time stdlib