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

staker source realm

Package staker manages liquidity mining rewards for GnoSwap positions.

Readme View source

Staker

Liquidity mining and reward distribution for LP positions.

Overview

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

Configuration

  • Deposit GNS Amount: 1,000 GNS for external incentives (default)
  • Minimum Reward Amount: 1,000 tokens (default)
  • Unstaking Fee: 1% (default)
  • Pool Tiers: 1, 2, or 3 (assigned per pool)
  • Warmup Schedule: 30/50/70/100% over 30/60/90 days
  • External Token Whitelist: Approved reward tokens

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 block
  • Proportional to staked liquidity
  • Unclaimed rewards returned to creator

Warmup Periods

Every staked position progresses through warmup periods:

  • 0-30 days: 30% rewards (70% to community/creator)
  • 30-60 days: 50% rewards (50% to community/creator)
  • 60-90 days: 70% rewards (30% to community/creator)
  • 90+ days: 100% rewards

Key Functions

StakeToken

Stakes LP position NFT to earn rewards.

UnStakeToken

Unstakes position and collects all rewards.

CollectReward

Collects accumulated rewards without unstaking.

CreateExternalIncentive

Creates external reward program for specific pool.

EndExternalIncentive

Ends incentive program and returns unused rewards.

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) =
  [1, 0, 0]        if Count(2) = 0 ∧ Count(3) = 0
  [0.8, 0, 0.2]    if Count(2) = 0
  [0.7, 0.3, 0]    if Count(3) = 0
  [0.5, 0.3, 0.2]  otherwise

Pool Reward Formula

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

Where emission is calculated as:

emission = GNSEmissionPerSecond × (avgMsPerBlock/1000) × StakerEmissionRatio

Position Reward Calculation

The reward for each position is calculated through:

  1. Cache pool rewards up to current block
  2. Retrieve position state from deposit records
  3. Calculate internal rewards if pool is tiered
  4. Calculate external rewards for active incentives
  5. Apply warmup penalties based on stake duration

Mathematical formula for total reward ratio:

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

where:
  αᵢ = max(s, Hᵢ₋₁)
  βᵢ = min(e, Hᵢ)

ΔRaw(a, b) = CalcRaw(b) - CalcRaw(a)

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

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

Final position reward:

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

Tick Cross Hook

When price crosses an initialized tick with staked positions:

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

The globalRewardRatioAccumulation tracks the integral:

globalRewardRatioAccumulation = ∫ 1/TotalStakedLiquidity(h) dh

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

Reward State Tracking

The system maintains:

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

Usage

 1// Stake existing position
 2StakeToken(123, "g1referrer...")
 3
 4// Create external incentive
 5CreateExternalIncentive(
 6    "gno.land/r/demo/bar:gno.land/r/demo/baz:3000",
 7    "gno.land/r/demo/reward",
 8    "1000000000",  // 1000 tokens
 9    startTime,
10    endTime,
11)
12
13// Collect rewards without unstaking
14CollectReward(123)
15
16// Unstake and collect all rewards
17UnStakeToken(123)

Security

  • Positions locked during staking
  • External incentives require GNS deposit
  • Warmup periods prevent gaming
  • Unclaimed rewards properly redirected
  • Hook integration ensures accurate tracking

Overview

Package staker manages liquidity mining rewards for GnoSwap positions.

The staker distributes GNS emissions and external incentives to liquidity providers based on their position size, price range, and staking duration. It supports both internal GNS rewards and external token incentives.

Rewards are calculated per-tick and accumulate over time, with automatic compounding and fee collection integration.

Constants 4

const GNS_PATH, WUGNOT_PATH

1const (
2	GNS_PATH    string = "gno.land/r/gnoswap/gns.GNS"
3	WUGNOT_PATH string = "gno.land/r/gnoland/wugnot.wugnot"
4)
source

const StoreKeyDepositGnsAmount, StoreKeyMinimumRewardAmount, StoreKeyDeposits, StoreKeyExternalIncentives, StoreKeyTotalEmissionSent, StoreKeyAllowedTokens, StoreKeyIncentiveCounter, StoreKeyTokenSpecificMinimumRewards, StoreKeyUnstakingFee, StoreKeyPendingProtocolFees, StoreKeyPools, StoreKeyPoolTierMemberships, StoreKeyPoolTierRatio, StoreKeyPoolTierCounts, StoreKeyPoolTierLastRewardCacheTimestamp, StoreKeyPoolTierCurrentEmission, StoreKeyPoolTierGetEmission, StoreKeyPoolTierGetHalvingBlocksInRange, StoreKeyWarmupTemplate, StoreKeyCurrentSwapBatch, StoreKeyExternalIncentivesByCreationTime

 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	StoreKeyIncentiveCounter                 StoreKey = "incentiveCounter"
 9	StoreKeyTokenSpecificMinimumRewards      StoreKey = "tokenSpecificMinimumRewards"
10	StoreKeyUnstakingFee                     StoreKey = "unstakingFee"
11	StoreKeyPendingProtocolFees              StoreKey = "pendingProtocolFees"
12	StoreKeyPools                            StoreKey = "pools"
13	StoreKeyPoolTierMemberships              StoreKey = "poolTierMemberships"
14	StoreKeyPoolTierRatio                    StoreKey = "poolTierRatio"
15	StoreKeyPoolTierCounts                   StoreKey = "poolTierCounts"
16	StoreKeyPoolTierLastRewardCacheTimestamp StoreKey = "poolTierLastRewardCacheTimestamp"
17	StoreKeyPoolTierCurrentEmission          StoreKey = "poolTierCurrentEmission"
18	StoreKeyPoolTierGetEmission              StoreKey = "poolTierGetEmission"
19	StoreKeyPoolTierGetHalvingBlocksInRange  StoreKey = "poolTierGetHalvingBlocksInRange"
20	StoreKeyWarmupTemplate                   StoreKey = "warmupTemplate"
21	StoreKeyCurrentSwapBatch                 StoreKey = "currentSwapBatch"
22	StoreKeyExternalIncentivesByCreationTime StoreKey = "externalIncentivesByCreationTime"
23)
source

Functions 102

func AddToken

crossing Action
1func AddToken(cur realm, tokenPath string)
source

AddToken adds a token to the reward token whitelist.

func ChangePoolTier

crossing Action
1func ChangePoolTier(cur realm, poolPath string, tier uint64)
source

ChangePoolTier changes the reward tier of a pool.

func CollectExternalIncentivePenalty

crossing Action
1func CollectExternalIncentivePenalty(cur realm, targetPoolPath, incentiveId string, refundAddress address) int64
source

CollectExternalIncentivePenalty collects accumulated warmup penalties for an ended incentive.

func CollectReward

crossing Action
1func CollectReward(cur realm, positionId uint64) (string, string, map[string]int64, map[string]int64)
source

CollectReward collects accumulated rewards from a staked position.

Parameters:

  • positionId: ID of the staked position

Returns:

  • string: pool path
  • string: staking details
  • map[string]int64: internal rewards
  • map[string]int64: external rewards

func CreateExternalIncentive

crossing Action
1func CreateExternalIncentive(
2	cur realm,
3	targetPoolPath string,
4	rewardToken string,
5	rewardAmount int64,
6	startTimestamp int64,
7	endTimestamp int64,
8)
source

CreateExternalIncentive creates an external reward incentive for a pool.

Parameters:

  • targetPoolPath: pool to incentivize
  • rewardToken: token to use as reward
  • rewardAmount: total reward amount
  • startTimestamp: incentive start time
  • endTimestamp: incentive end time

func DecodeUint

Action
1func DecodeUint(s string) uint64
source

DecodeUint converts a zero-padded string back into a uint64 number.

Parameters: - s (string): The zero-padded string.

Returns: - uint64: The decoded number.

Panics: - If the string cannot be parsed into a uint64.

Example: Input: "00000000000000012345" Output: 12345

func EncodeInt

Action
1func EncodeInt(num int32) string
source

EncodeInt takes an int32 and returns a zero-padded decimal string with up to 10 digits for the absolute value. If the number is negative, the '-' sign comes first, followed by zeros, then digits.

func EncodeUint

Action
1func EncodeUint(num uint64) string
source

EncodeUint converts a uint64 number into a zero-padded 20-character string.

Parameters: - num (uint64): The number to encode.

Returns: - string: A zero-padded string representation of the number.

Example: Input: 12345 Output: "00000000000000012345"

func EndExternalIncentive

crossing Action
1func EndExternalIncentive(cur realm, targetPoolPath, incentiveId string, refundAddress address)
source

EndExternalIncentive terminates an external incentive early.

func GetCreatedHeightOfIncentive

Action
1func GetCreatedHeightOfIncentive(poolPath string, incentiveId string) int64
source

GetCreatedHeightOfIncentive returns the block height when an incentive was created.

func GetDepositLiquidity

Action
1func GetDepositLiquidity(lpTokenId uint64) *u256.Uint
source

GetDepositLiquidity returns the liquidity amount of a staked position.

func GetIncentiveRefunded

Action
1func GetIncentiveRefunded(poolPath string, incentiveId string) bool
source

GetIncentiveRefunded returns whether an incentive has been refunded.

func GetIncentiveRewardAmount

Action
1func GetIncentiveRewardAmount(poolPath string, incentiveId string) *u256.Uint
source

GetIncentiveRewardAmount returns the total reward amount of an incentive.

func GetIncentiveRewardPerSecondX128

Action
1func GetIncentiveRewardPerSecondX128(poolPath string, incentiveId string) *u256.Uint
source

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.

func GetPoolGlobalRewardRatioAccumulation

Action
1func GetPoolGlobalRewardRatioAccumulation(poolPath string, timestamp uint64) string
source

GetPoolGlobalRewardRatioAccumulation returns the global reward ratio accumulation at a specific timestamp for a pool.

func GetPoolGlobalRewardRatioAccumulationIDs

Action
1func GetPoolGlobalRewardRatioAccumulationIDs(poolPath string, offset, count int) []uint64
source

GetPoolGlobalRewardRatioAccumulationIDs returns a paginated list of timestamps for global reward ratio accumulation entries.

func GetPoolHistoricalTick

Action
1func GetPoolHistoricalTick(poolPath string, tick uint64) int32
source

GetPoolHistoricalTick returns the historical tick at a specific timestamp for a pool.

func GetPoolHistoricalTickIDs

Action
1func GetPoolHistoricalTickIDs(poolPath string, offset, count int) []int32
source

GetPoolHistoricalTickIDs returns a paginated list of historical tick values for a pool.

func GetPoolIncentiveIDs

Action
1func GetPoolIncentiveIDs(poolPath string, offset, count int) []string
source

GetPoolIncentiveIDs returns a paginated list of incentive IDs for a pool.

func GetPoolRewardCache

Action
1func GetPoolRewardCache(poolPath string, timestamp uint64) int64
source

GetPoolRewardCache returns the reward cache value at a specific timestamp for a pool.

func GetPoolRewardCacheIDs

Action
1func GetPoolRewardCacheIDs(poolPath string, offset, count int) []int64
source

GetPoolRewardCacheIDs returns a paginated list of reward cache timestamps for a pool.

func IsIncentiveActive

Action
1func IsIncentiveActive(poolPath string, incentiveId string) bool
source

IsIncentiveActive returns whether an incentive is active.

func IsStaked

Action
1func IsStaked(positionId uint64) bool
source

IsStaked returns whether a position is staked.

func NewBPTreeN

Action
1func NewBPTreeN(fanout int) *bptree.BPTree
source

NewBPTreeN 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.

func RegisterInitializer

crossing Action
1func RegisterInitializer(cur realm, initializer func(_ int, rlm realm, stakerStore IStakerStore, poolAccessor PoolAccessor, emissionAccessor EmissionAccessor, nftAccessor NFTAccessor) IStaker)
source

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.

Security: Only contracts within the domain path can register initializers. Each package path can only register once to prevent duplicate registrations.

func RemovePoolTier

crossing Action
1func RemovePoolTier(cur realm, poolPath string)
source

RemovePoolTier removes a pool from the tier system.

func RemoveToken

crossing Action
1func RemoveToken(cur realm, tokenPath string)
source

RemoveToken removes a token from the reward token whitelist.

func SetDepositGnsAmount

crossing Action
1func SetDepositGnsAmount(cur realm, amount int64)
source

SetDepositGnsAmount sets the required GNS deposit amount for staking.

func SetPoolTier

crossing Action
1func SetPoolTier(cur realm, poolPath string, tier uint64)
source

SetPoolTier sets the reward tier for a pool.

func SetWarmUp

crossing Action
1func SetWarmUp(cur realm, pct, timeDuration int64)
source

SetWarmUp sets the warm-up period parameters for staking.

func StakeToken

crossing Action
1func StakeToken(cur realm, positionId uint64, referrer string) string
source

StakeToken stakes a position NFT to earn rewards.

Parameters:

  • positionId: ID of the position to stake
  • referrer: referrer address for reward tracking

Returns:

  • string: deposit ID

func UnStakeToken

crossing Action
1func UnStakeToken(cur realm, positionId uint64) string
source

UnStakeToken unstakes a position NFT and collects rewards.

Parameters:

  • positionId: ID of the position to unstake

Returns:

  • string: collected reward details

func UpgradeImpl

crossing Action
1func UpgradeImpl(cur realm, packagePath string)
source

UpgradeImpl switches the active staker implementation to a different version. This function allows seamless upgrades from one version to another without data migration or downtime.

Security: Only admin or governance can perform upgrades. The new implementation must have been previously registered via RegisterInitializer.

func GetDeposit

Action
1func GetDeposit(lpTokenId uint64) *Deposit
source

GetDeposit returns a copy of the deposit for the given position ID.

func NewDeposit

Action
1func NewDeposit(
2	owner address,
3	targetPoolPath string,
4	liquidity *u256.Uint,
5	currentTime int64,
6	tickLower, tickUpper int32,
7	warmups []Warmup,
8) *Deposit
source

func GetIncentive

Action
1func GetIncentive(poolPath string, incentiveId string) *ExternalIncentive
source

GetIncentive returns a copy of the incentive for the given pool and ID.

func NewExternalIncentive

Action
 1func NewExternalIncentive(
 2	incentiveId string,
 3	targetPoolPath string,
 4	rewardToken string,
 5	rewardAmount int64,
 6	startTimestamp int64,
 7	endTimestamp int64,
 8	creator address,
 9	depositGnsAmount int64,
10	createdHeight int64,
11	currentTime int64,
12) *ExternalIncentive
source

NewExternalIncentive creates a new external incentive

func NewStakerStore

Action
1func NewStakerStore(kvStore store.KVStore) IStakerStore
source

NewStakerStore 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.

func GetPool

Action
1func GetPool(poolPath string) *Pool
source

GetPool returns a copy of the pool for the given path.

func NewPool

Action
1func NewPool(poolPath string, currentTime int64) *Pool
source

NewPool creates a new pool with the given poolPath and currentHeight.

func NewUintTree

Action
1func NewUintTree() *UintTree
source

NewUintTree creates a new UintTree instance with default fanout 64.

func NewUintTreeN

Action
1func NewUintTreeN(fanout int) *UintTree
source

NewUintTreeN creates a new UintTree instance with the specified fanout.

func GetDepositWarmUp

Action
1func GetDepositWarmUp(lpTokenId uint64) []Warmup
source

GetDepositWarmUp returns the warmup records of a staked position.

Types 20

type Counter

struct
1type Counter struct {
2	id int64
3}
source

Methods on Counter

func Get

method on Counter
1func (c *Counter) Get() int64
source

func Next

method on Counter
1func (c *Counter) Next() int64
source

type 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}
source

Methods on Deposit

func AddExternalIncentiveId

method on Deposit
1func (d *Deposit) AddExternalIncentiveId(incentiveId string)
source

AddExternalIncentiveId adds an external incentive id to the deposit.

func Clone

method on Deposit
1func (d *Deposit) Clone() *Deposit
source

Clone returns a deep copy of the deposit.

func GetCollectedExternalReward

method on Deposit
1func (d *Deposit) GetCollectedExternalReward(incentiveID string) (int64, bool)
source

GetCollectedExternalReward returns the collected external reward for the given incentive ID. Returns 0 if the incentive ID does not exist.

func GetExternalIncentiveIdList

method on Deposit
1func (d *Deposit) GetExternalIncentiveIdList() []string
source

GetExternalIncentiveIdList returns a list of external incentive ids for the deposit.

func GetExternalRewardLastCollectTime

method on Deposit
1func (d *Deposit) GetExternalRewardLastCollectTime(incentiveID string) (int64, bool)
source

GetExternalRewardLastCollectTime returns the last collect time for the given incentive ID. Returns 0 if the incentive ID does not exist.

func HasExternalIncentiveId

method on Deposit
1func (d *Deposit) HasExternalIncentiveId(incentiveId string) bool
source

HasExternalIncentiveId checks if the deposit has the given external incentive id.

func IterateExternalIncentiveIds

method on Deposit
1func (d *Deposit) IterateExternalIncentiveIds(fn func(incentiveId string) bool)
source

IterateExternalIncentiveIds 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.

func Liquidity

method on Deposit
1func (d *Deposit) Liquidity() *u256.Uint
source

func Owner

method on Deposit
1func (d *Deposit) Owner() address
source

func RemoveExternalIncentiveId

method on Deposit
1func (d *Deposit) RemoveExternalIncentiveId(incentiveId string)
source

RemoveExternalIncentiveId removes an external incentive id from the deposit.

func SetLiquidity

method on Deposit
1func (d *Deposit) SetLiquidity(liquidity *u256.Uint)
source

func SetOwner

method on Deposit
1func (d *Deposit) SetOwner(owner address)
source

func SetStakeTime

method on Deposit
1func (d *Deposit) SetStakeTime(stakeTime int64)
source

func SetTickLower

method on Deposit
1func (d *Deposit) SetTickLower(tickLower int32)
source

func SetTickUpper

method on Deposit
1func (d *Deposit) SetTickUpper(tickUpper int32)
source

func SetWarmups

method on Deposit
1func (d *Deposit) SetWarmups(warmups []Warmup)
source

func StakeTime

method on Deposit
1func (d *Deposit) StakeTime() int64
source

func TickLower

method on Deposit
1func (d *Deposit) TickLower() int32
source

func TickUpper

method on Deposit
1func (d *Deposit) TickUpper() int32
source

func Warmups

method on Deposit
1func (d *Deposit) Warmups() []Warmup
source

type EmissionAccessor

interface
1type EmissionAccessor interface {
2	MintAndDistributeGns(_ int, rlm realm) (int64, bool)
3	GetStakerEmissionAmountPerSecond() int64
4	GetStakerEmissionAmountPerSecondInRange(start, end int64) ([]int64, []int64)
5	SetOnDistributionPctChangeCallback(_ int, rlm realm, callback func(_ int, rlm realm, emissionAmountPerSecond int64))
6}
source

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      // to be distributed reward amount
12	rewardPerSecondX128      *u256.Uint // reward per second, scaled by 2^128 to preserve sub-second precision
13	distributedRewardAmount  int64      // distributed reward amount, when un-staked and refunded
14	accumulatedPenaltyAmount int64      // accumulated warmup penalty from CollectReward
15	creator                  address    // creator address
16
17	refunded bool // whether incentive has been refunded (includes GNS deposit and unclaimed rewards)
18}
source

Methods on ExternalIncentive

func AccumulatedPenaltyAmount

method on ExternalIncentive
1func (e *ExternalIncentive) AccumulatedPenaltyAmount() int64
source

AccumulatedPenaltyAmount returns the accumulated warmup penalty amount

func Clone

method on ExternalIncentive
1func (e *ExternalIncentive) Clone() *ExternalIncentive
source

func CreatedHeight

method on ExternalIncentive
1func (e *ExternalIncentive) CreatedHeight() int64
source

CreatedHeight returns the created height

func CreatedTimestamp

method on ExternalIncentive
1func (e *ExternalIncentive) CreatedTimestamp() int64
source

CreatedTimestamp returns the created timestamp

func Creator

method on ExternalIncentive
1func (e *ExternalIncentive) Creator() address
source

Creator returns the creator address

func DepositGnsAmount

method on ExternalIncentive
1func (e *ExternalIncentive) DepositGnsAmount() int64
source

DepositGnsAmount returns the deposit GNS amount

func DistributedRewardAmount

method on ExternalIncentive
1func (e *ExternalIncentive) DistributedRewardAmount() int64
source

DistributedRewardAmount returns the distributed reward amount

func EndTimestamp

method on ExternalIncentive
1func (e *ExternalIncentive) EndTimestamp() int64
source

EndTimestamp returns the end timestamp

func IncentiveId

method on ExternalIncentive
1func (e *ExternalIncentive) IncentiveId() string
source

IncentiveId returns the incentive ID

func Refunded

method on ExternalIncentive
1func (e *ExternalIncentive) Refunded() bool
source

Refunded returns the refunded status

func RewardAmount

method on ExternalIncentive
1func (e *ExternalIncentive) RewardAmount() int64
source

RewardAmount returns the reward amount

func RewardPerSecondX128

method on ExternalIncentive
1func (e *ExternalIncentive) RewardPerSecondX128() *u256.Uint
source

RewardPerSecondX128 returns the Q128-scaled reward per second. The underlying value is (rewardAmount << 128) / duration.

func RewardToken

method on ExternalIncentive
1func (e *ExternalIncentive) RewardToken() string
source

RewardToken returns the reward token

func SetAccumulatedPenaltyAmount

method on ExternalIncentive
1func (e *ExternalIncentive) SetAccumulatedPenaltyAmount(accumulatedPenaltyAmount int64)
source

SetAccumulatedPenaltyAmount sets the accumulated warmup penalty amount

func SetCreatedHeight

method on ExternalIncentive
1func (e *ExternalIncentive) SetCreatedHeight(createdHeight int64)
source

SetCreatedHeight sets the created height

func SetCreatedTimestamp

method on ExternalIncentive
1func (e *ExternalIncentive) SetCreatedTimestamp(createdTimestamp int64)
source

SetCreatedTimestamp sets the created timestamp

func SetCreator

method on ExternalIncentive
1func (e *ExternalIncentive) SetCreator(creator address)
source

SetCreator sets the creator address

func SetDepositGnsAmount

method on ExternalIncentive
1func (e *ExternalIncentive) SetDepositGnsAmount(depositGnsAmount int64)
source

SetDepositGnsAmount sets the deposit GNS amount

func SetDistributedRewardAmount

method on ExternalIncentive
1func (e *ExternalIncentive) SetDistributedRewardAmount(distributedRewardAmount int64)
source

SetDistributedRewardAmount sets the distributed reward amount

func SetEndTimestamp

method on ExternalIncentive
1func (e *ExternalIncentive) SetEndTimestamp(endTimestamp int64)
source

SetEndTimestamp sets the end timestamp

func SetIncentiveId

method on ExternalIncentive
1func (e *ExternalIncentive) SetIncentiveId(incentiveId string)
source

SetIncentiveId sets the incentive ID

func SetRefunded

method on ExternalIncentive
1func (e *ExternalIncentive) SetRefunded(refunded bool)
source

SetRefunded sets the refunded status

func SetRewardAmount

method on ExternalIncentive
1func (e *ExternalIncentive) SetRewardAmount(rewardAmount int64)
source

SetRewardAmount sets the reward amount

func SetRewardPerSecondX128

method on ExternalIncentive
1func (e *ExternalIncentive) SetRewardPerSecondX128(rewardPerSecondX128 *u256.Uint)
source

SetRewardPerSecondX128 sets the Q128-scaled reward per second.

func SetRewardToken

method on ExternalIncentive
1func (e *ExternalIncentive) SetRewardToken(rewardToken string)
source

SetRewardToken sets the reward token

func SetStartTimestamp

method on ExternalIncentive
1func (e *ExternalIncentive) SetStartTimestamp(startTimestamp int64)
source

SetStartTimestamp sets the start timestamp

func SetTargetPoolPath

method on ExternalIncentive
1func (e *ExternalIncentive) SetTargetPoolPath(targetPoolPath string)
source

SetTargetPoolPath sets the target pool path

func SetTotalRewardAmount

method on ExternalIncentive
1func (e *ExternalIncentive) SetTotalRewardAmount(totalRewardAmount int64)
source

SetTotalRewardAmount sets the total reward amount

func StartTimestamp

method on ExternalIncentive
1func (e *ExternalIncentive) StartTimestamp() int64
source

StartTimestamp returns the start timestamp

func TargetPoolPath

method on ExternalIncentive
1func (e *ExternalIncentive) TargetPoolPath() string
source

TargetPoolPath returns the target pool path

func TotalRewardAmount

method on ExternalIncentive
1func (e *ExternalIncentive) TotalRewardAmount() int64
source

TotalRewardAmount returns the total reward amount

type IStaker

interface
1type IStaker interface {
2	IStakerManager
3	IStakerGetter
4}
source

type IStakerGetter

interface
 1type IStakerGetter interface {
 2	GetPool(poolPath string) *Pool
 3	GetPoolRewardCacheCount(poolPath string) uint64
 4	GetPoolRewardCacheIDs(poolPath string, offset, count int) []int64
 5	GetPoolRewardCache(poolPath string, timestamp uint64) int64
 6	GetPoolIncentiveCount(poolPath string) uint64
 7	GetPoolIncentiveIDs(poolPath string, offset, count int) []string
 8	GetPoolGlobalRewardRatioAccumulationCount(poolPath string) uint64
 9	GetPoolGlobalRewardRatioAccumulationIDs(poolPath string, offset, count int) []uint64
10	GetPoolGlobalRewardRatioAccumulation(poolPath string, timestamp uint64) string
11	GetPoolHistoricalTickCount(poolPath string) uint64
12	GetPoolHistoricalTickIDs(poolPath string, offset, count int) []int32
13	GetPoolHistoricalTick(poolPath string, tick uint64) int32
14	GetIncentive(poolPath string, incentiveId string) *ExternalIncentive
15	GetDeposit(lpTokenId uint64) *Deposit
16	CollectableEmissionReward(positionId uint64) int64
17	CollectableExternalIncentiveReward(positionId uint64, incentiveId string) int64
18	GetCreatedHeightOfIncentive(poolPath string, incentiveId string) int64
19	GetIncentiveCreatedTimestamp(poolPath string, incentiveId string) int64
20	GetIncentiveTotalRewardAmount(poolPath string, incentiveId string) int64
21	GetIncentiveDistributedRewardAmount(poolPath string, incentiveId string) int64
22	GetIncentiveRemainingRewardAmount(poolPath string, incentiveId string) int64
23	GetIncentiveAccumulatedPenaltyAmount(poolPath string, incentiveId string) int64
24	GetIncentiveDepositGnsAmount(poolPath string, incentiveId string) int64
25	GetIncentiveRefunded(poolPath string, incentiveId string) bool
26	IsIncentiveActive(poolPath string, incentiveId string) bool
27	GetDepositExternalRewardLastCollectTimestamp(lpTokenId uint64, incentiveId string) int64
28	GetDepositGnsAmount() int64
29	GetDepositInternalRewardLastCollectTimestamp(lpTokenId uint64) int64
30	GetDepositCollectedInternalReward(lpTokenId uint64) int64
31	GetDepositCollectedExternalReward(lpTokenId uint64, incentiveId string) int64
32	GetDepositLiquidity(lpTokenId uint64) *u256.Uint
33	GetDepositLiquidityAsString(lpTokenId uint64) string
34	GetDepositOwner(lpTokenId uint64) address
35	GetDepositStakeTime(lpTokenId uint64) int64
36	GetDepositTargetPoolPath(lpTokenId uint64) string
37	GetDepositTickLower(lpTokenId uint64) int32
38	GetDepositTickUpper(lpTokenId uint64) int32
39	GetDepositWarmUp(lpTokenId uint64) []Warmup
40	GetDepositExternalIncentiveIdList(lpTokenId uint64) []string
41	GetExternalIncentiveByPoolPath(poolPath string) []ExternalIncentive
42	GetIncentiveEndTimestamp(poolPath string, incentiveId string) int64
43	GetIncentiveCreator(poolPath string, incentiveId string) address
44	GetIncentiveRewardAmount(poolPath string, incentiveId string) *u256.Uint
45	GetIncentiveRewardAmountAsString(poolPath string, incentiveId string) string
46	GetIncentiveRewardPerSecondX128(poolPath string, incentiveId string) *u256.Uint
47	GetIncentiveRewardToken(poolPath string, incentiveId string) string
48	GetIncentiveStartTimestamp(poolPath string, incentiveId string) int64
49	GetMinimumRewardAmount() int64
50	GetMinimumRewardAmountForToken(tokenPath string) int64
51	GetPoolIncentiveIdList(poolPath string) []string
52	GetPoolStakedLiquidity(poolPath string) string
53	GetPoolsByTier(tier uint64) []string
54	GetPoolReward(tier uint64) int64
55	GetPoolTier(poolPath string) uint64
56	GetPoolTierCount(tier uint64) uint64
57	GetPoolTierRatio(poolPath string) uint64
58	GetSpecificTokenMinimumRewardAmount(tokenPath string) (int64, bool)
59	GetTargetPoolPathByIncentiveId(poolPath string, incentiveId string) string
60	GetUnstakingFee() uint64
61	IsStaked(positionId uint64) bool
62	GetTotalEmissionSent() int64
63	GetAllowedTokens() []string
64	GetWarmupTemplate() []Warmup
65}
source

type IStakerManager

interface
 1type IStakerManager interface {
 2	StakeToken(_ int, rlm realm, positionId uint64, referrer string) string
 3	UnStakeToken(_ int, rlm realm, positionId uint64) string
 4	CollectReward(_ int, rlm realm, positionId uint64) (string, string, map[string]int64, map[string]int64)
 5
 6	SetPoolTier(_ int, rlm realm, poolPath string, tier uint64)
 7	ChangePoolTier(_ int, rlm realm, poolPath string, tier uint64)
 8	RemovePoolTier(_ int, rlm realm, poolPath string)
 9
10	CreateExternalIncentive(
11		_ int,
12		rlm realm,
13		targetPoolPath string,
14		rewardToken string,
15		rewardAmount int64,
16		startTimestamp int64,
17		endTimestamp int64,
18	)
19	EndExternalIncentive(_ int, rlm realm, targetPoolPath, incentiveId string, refundAddress address)
20	CollectExternalIncentivePenalty(_ int, rlm realm, targetPoolPath, incentiveId string, refundAddress address) int64
21	AddToken(_ int, rlm realm, tokenPath string)
22	RemoveToken(_ int, rlm realm, tokenPath string)
23
24	SetWarmUp(_ int, rlm realm, pct, timeDuration int64)
25	SetDepositGnsAmount(_ int, rlm realm, amount int64)
26	SetMinimumRewardAmount(_ int, rlm realm, amount int64)
27	SetTokenMinimumRewardAmount(_ int, rlm realm, paramsStr string)
28	SetUnStakingFee(_ int, rlm realm, fee uint64)
29}
source

type IStakerStore

interface
  1type IStakerStore interface {
  2	// DepositGnsAmount
  3	HasDepositGnsAmountStoreKey() bool
  4	GetDepositGnsAmount() int64
  5	SetDepositGnsAmount(_ int, rlm realm, amount int64) error
  6
  7	// MinimumRewardAmount
  8	HasMinimumRewardAmountStoreKey() bool
  9	GetMinimumRewardAmount() int64
 10	SetMinimumRewardAmount(_ int, rlm realm, amount int64) error
 11
 12	// Deposits
 13	HasDepositsStoreKey() bool
 14	GetDeposits() *bptree.BPTree
 15	SetDeposits(_ int, rlm realm, deposits *bptree.BPTree) error
 16
 17	// ExternalIncentives
 18	HasExternalIncentivesStoreKey() bool
 19	GetExternalIncentives() *bptree.BPTree
 20	SetExternalIncentives(_ int, rlm realm, incentives *bptree.BPTree) error
 21
 22	// TotalEmissionSent
 23	HasTotalEmissionSentStoreKey() bool
 24	GetTotalEmissionSent() int64
 25	SetTotalEmissionSent(_ int, rlm realm, amount int64) error
 26
 27	// AllowedTokens
 28	HasAllowedTokensStoreKey() bool
 29	GetAllowedTokens() []string
 30	SetAllowedTokens(_ int, rlm realm, tokens []string) error
 31	AddAllowedToken(_ int, rlm realm, tokenPath string) error
 32	RemoveAllowedToken(_ int, rlm realm, tokenPath string) error
 33
 34	// IncentiveCounter
 35	HasIncentiveCounterStoreKey() bool
 36	GetIncentiveCounter() *Counter
 37	SetIncentiveCounter(_ int, rlm realm, counter *Counter) error
 38	NextIncentiveID(creator address, timestamp int64) string
 39
 40	// TokenSpecificMinimumRewards
 41	HasTokenSpecificMinimumRewardsStoreKey() bool
 42	GetTokenSpecificMinimumRewards() map[string]int64
 43	SetTokenSpecificMinimumRewards(_ int, rlm realm, rewards map[string]int64) error
 44	SetTokenSpecificMinimumRewardItem(_ int, rlm realm, tokenPath string, amount int64) error
 45	RemoveTokenSpecificMinimumRewardItem(_ int, rlm realm, tokenPath string) error
 46
 47	// UnstakingFee
 48	HasUnstakingFeeStoreKey() bool
 49	GetUnstakingFee() uint64
 50	SetUnstakingFee(_ int, rlm realm, fee uint64) error
 51
 52	HasPendingProtocolFeesStoreKey() bool
 53	GetPendingProtocolFees() map[string]int64
 54	SetPendingProtocolFees(_ int, rlm realm, fees map[string]int64) error
 55
 56	// Pools
 57	HasPoolsStoreKey() bool
 58	GetPools() *bptree.BPTree
 59	SetPools(_ int, rlm realm, pools *bptree.BPTree) error
 60
 61	// PoolTierMemberships
 62	HasPoolTierMembershipsStoreKey() bool
 63	GetPoolTierMemberships() *bptree.BPTree
 64	SetPoolTierMemberships(_ int, rlm realm, memberships *bptree.BPTree) error
 65
 66	// PoolTierRatio
 67	HasPoolTierRatioStoreKey() bool
 68	GetPoolTierRatio() TierRatio
 69	SetPoolTierRatio(_ int, rlm realm, ratio TierRatio) error
 70
 71	// PoolTierCounts
 72	HasPoolTierCountsStoreKey() bool
 73	GetPoolTierCounts() [AllTierCount]uint64
 74	SetPoolTierCounts(_ int, rlm realm, counts [AllTierCount]uint64) error
 75
 76	// PoolTierLastRewardCacheTimestamp
 77	HasPoolTierLastRewardCacheTimestampStoreKey() bool
 78	GetPoolTierLastRewardCacheTimestamp() int64
 79	SetPoolTierLastRewardCacheTimestamp(_ int, rlm realm, timestamp int64) error
 80
 81	// PoolTierCurrentEmission
 82	HasPoolTierCurrentEmissionStoreKey() bool
 83	GetPoolTierCurrentEmission() int64
 84	SetPoolTierCurrentEmission(_ int, rlm realm, emission int64) error
 85
 86	// PoolTierGetEmission
 87	HasPoolTierGetEmissionStoreKey() bool
 88	GetPoolTierGetEmission() func() int64
 89	SetPoolTierGetEmission(_ int, rlm realm, fn func() int64) error
 90
 91	// PoolTierGetHalvingBlocksInRange
 92	HasPoolTierGetHalvingBlocksInRangeStoreKey() bool
 93	GetPoolTierGetHalvingBlocksInRange() func(start, end int64) ([]int64, []int64)
 94	SetPoolTierGetHalvingBlocksInRange(_ int, rlm realm, fn func(start, end int64) ([]int64, []int64)) error
 95
 96	HasWarmupTemplateStoreKey() bool
 97	GetWarmupTemplate() []Warmup
 98	SetWarmupTemplate(_ int, rlm realm, warmups []Warmup) error
 99
100	// CurrentSwapBatch
101	HasCurrentSwapBatchStoreKey() bool
102	GetCurrentSwapBatch() *SwapBatchProcessor
103	SetCurrentSwapBatch(_ int, rlm realm, batch *SwapBatchProcessor) error
104
105	// ExternalIncentivesByCreationTime
106	HasExternalIncentivesByCreationTimeStoreKey() bool
107	GetExternalIncentivesByCreationTime() *UintTree
108	SetExternalIncentivesByCreationTime(_ int, rlm realm, tree *UintTree) error
109}
source

type Incentives

struct
1type Incentives struct {
2	incentives *bptree.BPTree // (incentiveId) => ExternalIncentive
3
4	targetPoolPath string // The target pool path for this incentive collection
5
6	unclaimablePeriods *UintTree // blockTimestamp -> any
7}
source

Incentives 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

Methods on Incentives

func Incentive

method on Incentives
1func (i *Incentives) Incentive(incentiveId string) (*ExternalIncentive, bool)
source

Incentive returns an incentive by ID

func IncentiveTrees

method on Incentives
1func (i *Incentives) IncentiveTrees() *bptree.BPTree
source

Incentives returns the incentives tree

func IterateIncentives

method on Incentives
1func (i *Incentives) IterateIncentives(fn func(incentiveId string, incentive *ExternalIncentive) bool)
source

IterateIncentives iterates over all incentives

func SetIncentive

method on Incentives
1func (i *Incentives) SetIncentive(incentiveId string, incentive *ExternalIncentive)
source

SetIncentive sets an incentive by ID

func SetIncentives

method on Incentives
1func (i *Incentives) SetIncentives(incentives *bptree.BPTree)
source

SetIncentives sets the incentives tree

func SetTargetPoolPath

method on Incentives
1func (i *Incentives) SetTargetPoolPath(targetPoolPath string)
source

SetTargetPoolPath sets the target pool path

func SetUnclaimablePeriod

method on Incentives
1func (i *Incentives) SetUnclaimablePeriod(startTimestamp int64, endTimestamp int64)
source

func SetUnclaimablePeriods

method on Incentives
1func (i *Incentives) SetUnclaimablePeriods(unclaimablePeriods *UintTree)
source

SetUnclaimablePeriods sets the unclaimable periods tree

func TargetPoolPath

method on Incentives
1func (i *Incentives) TargetPoolPath() string
source

TargetPoolPath returns the target pool path

func UnclaimablePeriods

method on Incentives
1func (i *Incentives) UnclaimablePeriods() *UintTree
source

UnclaimablePeriods returns the unclaimable periods tree

type NFTAccessor

interface
 1type NFTAccessor interface {
 2	Approve(_ int, rlm realm, approved address, tid grc721.TokenID) error
 3	Mint(_ int, rlm realm, to address, tid grc721.TokenID) grc721.TokenID
 4	Burn(_ int, rlm realm, tid grc721.TokenID)
 5	TransferFrom(_ int, rlm realm, from, to address, tid grc721.TokenID) error
 6	TotalSupply() int64
 7	Exists(tid grc721.TokenID) bool
 8	MustOwnerOf(tid grc721.TokenID) address
 9	OwnerOf(tid grc721.TokenID) (address, error)
10}
source

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}
source

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.

  • currentStakedLiquidity: 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 undisributed 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 Pool
1func (p *Pool) Clone() *Pool
source

Clone returns a deep copy of the pool.

func GlobalRewardRatioAccumulation

method on Pool
1func (p *Pool) GlobalRewardRatioAccumulation() *UintTree
source

GlobalRewardRatioAccumulation returns the global reward ratio accumulation tree

func HistoricalTick

method on Pool
1func (p *Pool) HistoricalTick() *UintTree
source

HistoricalTick returns the historical tick tree

func Incentives

method on Pool
1func (p *Pool) Incentives() *Incentives
source

Incentives returns the incentives

func LastUnclaimableTime

method on Pool
1func (p *Pool) LastUnclaimableTime() int64
source

LastUnclaimableTime returns the last unclaimable time

func PoolPath

method on Pool
1func (p *Pool) PoolPath() string
source

PoolPath returns the pool path

func RewardCache

method on Pool
1func (p *Pool) RewardCache() *UintTree
source

RewardCache returns the reward cache tree

func SetGlobalRewardRatioAccumulation

method on Pool
1func (p *Pool) SetGlobalRewardRatioAccumulation(globalRewardRatioAccumulation *UintTree)
source

SetGlobalRewardRatioAccumulation sets the global reward ratio accumulation tree

func SetHistoricalTick

method on Pool
1func (p *Pool) SetHistoricalTick(historicalTick *UintTree)
source

SetHistoricalTick sets the historical tick tree

func SetIncentives

method on Pool
1func (p *Pool) SetIncentives(incentives *Incentives)
source

SetIncentives sets the incentives

func SetLastUnclaimableTime

method on Pool
1func (p *Pool) SetLastUnclaimableTime(lastUnclaimableTime int64)
source

SetLastUnclaimableTime sets the last unclaimable time

func SetPoolPath

method on Pool
1func (p *Pool) SetPoolPath(poolPath string)
source

SetPoolPath sets the pool path

func SetRewardCache

method on Pool
1func (p *Pool) SetRewardCache(rewardCache *UintTree)
source

SetRewardCache sets the reward cache tree

func SetRewardCacheAt

method on Pool
1func (p *Pool) SetRewardCacheAt(currentTime int64, reward int64)
source

func SetStakedLiquidity

method on Pool
1func (p *Pool) SetStakedLiquidity(stakedLiquidity *UintTree)
source

SetStakedLiquidity sets the staked liquidity tree

func SetTicks

method on Pool
1func (p *Pool) SetTicks(ticks Ticks)
source

SetTicks sets the ticks

func SetUnclaimableAcc

method on Pool
1func (p *Pool) SetUnclaimableAcc(unclaimableAcc int64)
source

SetUnclaimableAcc sets the unclaimable accumulation

func StakedLiquidity

method on Pool
1func (p *Pool) StakedLiquidity() *UintTree
source

StakedLiquidity returns the staked liquidity tree

func Ticks

method on Pool
1func (p *Pool) Ticks() *Ticks
source

Ticks returns the ticks

func UnclaimableAcc

method on Pool
1func (p *Pool) UnclaimableAcc() int64
source

UnclaimableAcc returns the unclaimable accumulation

type PoolAccessor

interface
1type PoolAccessor interface {
2	ExistsPoolPath(poolPath string) bool
3	GetSlot0Tick(poolPath string) int32
4	GetSlot0SqrtPriceX96(poolPath string) string
5
6	SetTickCrossHook(_ int, rlm realm, hook func(_ int, rlm realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64))
7	SetSwapStartHook(_ int, rlm realm, hook func(_ int, rlm realm, poolPath string, timestamp int64))
8	SetSwapEndHook(_ int, rlm realm, hook func(_ int, rlm realm, poolPath string) error)
9}
source

type StoreKey

ident
1type StoreKey string
source

Methods on StoreKey

func String

method on StoreKey
1func (s StoreKey) String() string
source

type SwapBatchProcessor

struct
1type 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}
source

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 SwapBatchProcessor
1func (s *SwapBatchProcessor) AddCross(tickCross *SwapTickCross)
source

func Crosses

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) Crosses() []*SwapTickCross
source

func IsActive

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) IsActive() bool
source

func LastCross

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) LastCross() *SwapTickCross
source

func Pool

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) Pool() *Pool
source

func PoolPath

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) PoolPath() string
source

func SetCrosses

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) SetCrosses(crosses []*SwapTickCross)
source

func SetIsActive

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) SetIsActive(isActive bool)
source

func SetPool

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) SetPool(pool *Pool)
source

func SetPoolPath

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) SetPoolPath(poolPath string)
source

func SetTimestamp

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) SetTimestamp(timestamp int64)
source

func Timestamp

method on SwapBatchProcessor
1func (s *SwapBatchProcessor) Timestamp() int64
source

type SwapTickCross

struct
1type SwapTickCross struct {
2	tickID     int32     // The tick index that was crossed
3	zeroForOne bool      // Direction of the swap (true: token0->token1, false: token1->token0)
4	delta      *i256.Int // Pre-calculated liquidity delta for this tick cross
5}
source

SwapTickCross 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 SwapTickCross
1func (s *SwapTickCross) Delta() *i256.Int
source

func TickID

method on SwapTickCross
1func (s *SwapTickCross) TickID() int32
source

func ZeroForOne

method on SwapTickCross
1func (s *SwapTickCross) ZeroForOne() bool
source

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 -> *u256.Uint
13}
source

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 Tick
1func (t *Tick) Clone() *Tick
source

Clone returns a deep copy of the tick.

func Id

method on Tick
1func (t *Tick) Id() int32
source

Id returns the tick ID

func OutsideAccumulation

method on Tick
1func (t *Tick) OutsideAccumulation() *UintTree
source

OutsideAccumulation returns the outside accumulation tree

func SetId

method on Tick
1func (t *Tick) SetId(id int32)
source

SetId sets the tick ID

func SetOutsideAccumulation

method on Tick
1func (t *Tick) SetOutsideAccumulation(outsideAccumulation *UintTree)
source

SetOutsideAccumulation sets the outside accumulation tree

func SetOutsideAccumulationAt

method on Tick
1func (t *Tick) SetOutsideAccumulationAt(timestamp int64, acc *u256.Uint)
source

SetOutsideAccumulationAt sets the outside accumulation at the timestamp.

func SetStakedLiquidityDelta

method on Tick
1func (t *Tick) SetStakedLiquidityDelta(stakedLiquidityDelta *i256.Int)
source

SetStakedLiquidityDelta sets the staked liquidity delta

func SetStakedLiquidityGross

method on Tick
1func (t *Tick) SetStakedLiquidityGross(stakedLiquidityGross *u256.Uint)
source

SetStakedLiquidityGross sets the staked liquidity gross

func StakedLiquidityDelta

method on Tick
1func (t *Tick) StakedLiquidityDelta() *i256.Int
source

StakedLiquidityDelta returns the staked liquidity delta

func StakedLiquidityGross

method on Tick
1func (t *Tick) StakedLiquidityGross() *u256.Uint
source

StakedLiquidityGross returns the staked liquidity gross

type Ticks

struct
1type Ticks struct {
2	tree *bptree.BPTree // int32 tickId -> tick
3}
source

Tick mapping for each pool

Methods on Ticks

func Clone

method on Ticks
1func (t Ticks) Clone() Ticks
source

Clone returns a deep copy of ticks.

func Get

method on Ticks
1func (t *Ticks) Get(tickId int32) *Tick
source

func Has

method on Ticks
1func (self *Ticks) Has(tickId int32) bool
source

func IterateTicks

method on Ticks
1func (t *Ticks) IterateTicks(fn func(tickId int32, tick *Tick) bool)
source

IterateTicks iterates over all ticks

func SetTick

method on Ticks
1func (t *Ticks) SetTick(tickId int32, tick *Tick)
source

SetTick sets a tick by ID

func SetTree

method on Ticks
1func (t *Ticks) SetTree(tree *bptree.BPTree)
source

SetTree sets the ticks tree

func Tree

method on Ticks
1func (t *Ticks) Tree() *bptree.BPTree
source

Tree returns the ticks tree

type TierRatio

struct
1type TierRatio struct {
2	Tier1 uint64
3	Tier2 uint64
4	Tier3 uint64
5}
source

100%, 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 TierRatio
1func (ratio *TierRatio) Get(tier uint64) (uint64, error)
source

Get returns the ratio(scaled up by 100) for the given tier.

type UintTree

struct
1type UintTree struct {
2	tree   *bptree.BPTree // blockTimestamp -> any
3	fanout int
4}
source

UintTree is a wrapper around a B+ tree for storing block timestamps as strings. Since block timestamps are defined as int64, we take int64 and convert it to uint64 for the tree.

Methods: - Get: Retrieves a value associated with a uint64 key. - Set: Stores a value with a uint64 key. - Has: Checks if a uint64 key exists in the tree. - Remove: Removes a uint64 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 UintTree
1func (self *UintTree) Clone() *UintTree
source

func Get

method on UintTree
1func (self *UintTree) Get(key int64) (any, bool)
source

func Has

method on UintTree
1func (self *UintTree) Has(key int64) bool
source

func Iterate

method on UintTree
1func (self *UintTree) Iterate(start, end int64, fn func(key int64, value any) bool)
source

func IterateByOffset

method on UintTree
1func (self *UintTree) IterateByOffset(offset, count int, fn func(key int64, value any) bool)
source

func Remove

method on UintTree
1func (self *UintTree) Remove(key int64)
source

func ReverseIterate

method on UintTree
1func (self *UintTree) ReverseIterate(start, end int64, fn func(key int64, value any) bool)
source

func Set

method on UintTree
1func (self *UintTree) Set(key int64, value any)
source

func Size

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

type Warmup

struct
1type Warmup struct {
2	TimeDuration   int64
3	NextWarmupTime int64 // time when this warmup period ends
4	WarmupRatio    uint64
5}
source

Methods on Warmup

Imports 19

Source Files 15