Playground
counter.gno
package staker
type Counter struct {
id int64
}
// NewCounter creates a counter initialized before the first allocated identifier.
//
// Returns:
// - *Counter: counter whose current identifier is zero.
func NewCounter() *Counter {
return &Counter{id: 0}
}
// Get returns the counter's current identifier without incrementing it.
//
// Returns:
// - int64: most recently allocated identifier, or zero for a new counter.
func (c *Counter) Get() int64 { return c.id }
// Next increments the counter and returns the newly allocated identifier.
//
// Returns:
// - int64: next identifier after incrementing the counter by one.
func (c *Counter) Next() int64 {
c.id++
return c.id
}
delegation.gno
package staker
import bptree "gno.land/p/nt/bptree/v0"
// DelegationType represents the type of delegation operation
type DelegationType string
const (
DelegateType DelegationType = "DELEGATE"
UnDelegateType DelegationType = "UNDELEGATE"
)
// String returns the textual operation name represented by the delegation type.
//
// Returns:
// - string: "DELEGATE", "UNDELEGATE", or the underlying value for another type.
func (d DelegationType) String() string { return string(d) }
// IsDelegate reports whether the operation type is DelegateType.
//
// Returns:
// - bool: true only when d represents a delegation operation.
func (d DelegationType) IsDelegate() bool { return d == DelegateType }
// IsUnDelegate reports whether the operation type is UnDelegateType.
//
// Returns:
// - bool: true only when d represents an undelegation operation.
func (d DelegationType) IsUnDelegate() bool { return d == UnDelegateType }
// Delegation represents a delegation between two addresses
type Delegation struct {
id int64
delegateAmount int64
unDelegateAmount int64
collectedAmount int64
delegateFrom address
delegateTo address
createdHeight int64
createdAt int64
withdraws []DelegationWithdraw
}
// NewDelegation creates a delegation record with no undelegated or collected amount.
//
// Parameters:
// - id: unique identifier assigned to this delegation record.
// - delegateFrom: address whose tokens are delegated.
// - delegateTo: address receiving the delegated voting power.
// - delegateAmount: initial delegated token amount in the smallest token unit.
// - createdHeight: block height at which the delegation was created.
// - createdAt: Unix timestamp at which the delegation was created.
//
// Returns:
// - *Delegation: initialized delegation with empty withdrawal history.
func NewDelegation(
id int64,
delegateFrom, delegateTo address,
delegateAmount, createdHeight, createdAt int64,
) *Delegation {
return &Delegation{
id: id,
delegateFrom: delegateFrom,
delegateTo: delegateTo,
delegateAmount: delegateAmount,
createdHeight: createdHeight,
createdAt: createdAt,
unDelegateAmount: 0,
collectedAmount: 0,
withdraws: make([]DelegationWithdraw, 0),
}
}
// Basic getters
// ID returns the unique identifier of the delegation record.
//
// Returns:
// - int64: delegation identifier assigned at creation.
func (d *Delegation) ID() int64 { return d.id }
// DelegateFrom returns the address that supplied the delegated tokens.
//
// Returns:
// - address: delegator address recorded on the delegation.
func (d *Delegation) DelegateFrom() address { return d.delegateFrom }
// DelegateTo returns the address receiving the delegated voting power.
//
// Returns:
// - address: delegatee address recorded on the delegation.
func (d *Delegation) DelegateTo() address { return d.delegateTo }
// CreatedAt returns the Unix timestamp recorded when the delegation was created.
//
// Returns:
// - int64: creation timestamp in Unix seconds.
func (d *Delegation) CreatedAt() int64 { return d.createdAt }
// Amount getters
// TotalDelegatedAmount returns the current amount still actively delegated.
//
// Returns:
// - int64: active delegated token amount in the smallest token unit.
func (d *Delegation) TotalDelegatedAmount() int64 { return d.delegateAmount }
// UnDelegatedAmount returns the amount moved into undelegation lockup.
//
// Returns:
// - int64: token amount awaiting collection after its lockup period.
func (d *Delegation) UnDelegatedAmount() int64 { return d.unDelegateAmount }
// CollectedAmount returns the amount already collected from undelegation.
//
// Returns:
// - int64: token amount released from this delegation.
func (d *Delegation) CollectedAmount() int64 { return d.collectedAmount }
// Withdraws getters
// Withdraws returns the delegation's withdrawal records.
//
// Returns:
// - []DelegationWithdraw: withdrawal entries tracked for this delegation.
func (d *Delegation) Withdraws() []DelegationWithdraw { return d.withdraws }
// Setters
// SetUnDelegateAmount replaces the amount currently in undelegation lockup.
//
// Parameters:
// - amount: token amount awaiting collection in the smallest token unit.
func (d *Delegation) SetUnDelegateAmount(amount int64) {
d.unDelegateAmount = amount
}
// SetCollectedAmount replaces the amount already collected from this delegation.
//
// Parameters:
// - amount: released token amount in the smallest token unit.
func (d *Delegation) SetCollectedAmount(amount int64) {
d.collectedAmount = amount
}
// AddWithdraw appends a withdrawal record to the delegation history.
//
// Parameters:
// - withdraw: withdrawal record to append, including its amount and unlock timing.
func (d *Delegation) AddWithdraw(withdraw DelegationWithdraw) {
d.withdraws = append(d.withdraws, withdraw)
}
// SetWithdraw replaces one withdrawal record at the supplied slice index.
//
// Parameters:
// - index: zero-based index of the withdrawal entry to replace.
// - withdraw: replacement withdrawal record.
func (d *Delegation) SetWithdraw(index int, withdraw DelegationWithdraw) {
d.withdraws[index] = withdraw
}
// SetWithdraws replaces the complete withdrawal history.
//
// Parameters:
// - withdraws: withdrawal records to store for this delegation.
func (d *Delegation) SetWithdraws(withdraws []DelegationWithdraw) {
d.withdraws = withdraws
}
// Clone returns a deep copy of the delegation and its withdrawal slice.
//
// Returns:
// - *Delegation: copied delegation, or nil when the receiver is nil.
func (d *Delegation) Clone() *Delegation {
if d == nil {
return nil
}
clonedWithdraws := make([]DelegationWithdraw, len(d.withdraws))
copy(clonedWithdraws, d.withdraws)
return &Delegation{
id: d.id,
delegateAmount: d.delegateAmount,
unDelegateAmount: d.unDelegateAmount,
collectedAmount: d.collectedAmount,
delegateFrom: d.delegateFrom,
delegateTo: d.delegateTo,
createdHeight: d.createdHeight,
createdAt: d.createdAt,
withdraws: clonedWithdraws,
}
}
// NewDelegationTree creates an empty tree for delegatee-to-delegation-ID mappings.
//
// Returns:
// - *bptree.BPTree: empty tree configured for delegation lookup entries.
func NewDelegationTree() *bptree.BPTree {
return bptree.NewBPTreeN(16)
}
// NewUserDelegationTree creates an empty tree for user delegation mappings.
// Returns:
// - *bptree.BPTree: empty tree configured for user delegation entries.
func NewUserDelegationTree() *bptree.BPTree {
return bptree.NewBPTreeN(16)
}
delegation_manager.gno
package staker
import (
bptree "gno.land/p/nt/bptree/v0"
)
// DelegationManager manages the mapping between users and their delegation IDs.
// It provides efficient lookup and management of user delegations organized by delegator and delegatee addresses.
type DelegationManager struct {
// userDelegations maps delegator address -> *bptree.BPTree (delegatee address -> list of delegation IDs)
// Using BPTree instead of map to handle unbounded growth of delegators efficiently
userDelegations *bptree.BPTree
}
// NewDelegationManager creates a new instance of DelegationManager.
// This factory function initializes the BPTree structure for tracking user delegations.
//
// Returns:
// - *DelegationManager: manager ready to track delegator/delegatee ID lists.
func NewDelegationManager() *DelegationManager {
return &DelegationManager{
userDelegations: bptree.NewBPTreeN(16),
}
}
// GetUserDelegations returns the entire user delegations tree.
//
// Returns:
// - *bptree.BPTree: tree keyed by delegator address string.
func (dm *DelegationManager) GetUserDelegations() *bptree.BPTree {
return dm.userDelegations
}
// SetUserDelegations replaces the root delegator-to-delegations tree.
//
// Parameters:
// - userDelegations: tree keyed by delegator address string and containing delegatee trees.
func (dm *DelegationManager) SetUserDelegations(userDelegations *bptree.BPTree) {
dm.userDelegations = userDelegations
}
// GetDelegatorDelegations returns the delegatee tree for one delegator.
//
// Parameters:
// - delegator: delegator address string used as the root-tree key.
//
// Returns:
// - *bptree.BPTree: delegatee-to-delegation-ID tree when present and correctly typed.
// - bool: true when the delegator entry exists with the expected tree type.
func (dm *DelegationManager) GetDelegatorDelegations(delegator string) (*bptree.BPTree, bool) {
delegations := dm.userDelegations.Get(delegator)
if delegations == nil {
return nil, false
}
delegationsTree, ok := delegations.(*bptree.BPTree)
if !ok {
return nil, false
}
return delegationsTree, true
}
// GetDelegationIDs returns IDs recorded for one delegator/delegatee pair.
//
// Parameters:
// - delegator: delegator address string used to select the nested tree.
// - delegatee: delegatee address string used as the nested-tree key.
//
// Returns:
// - []int64: delegation IDs stored for the pair.
// - bool: true when the pair exists with a valid ID slice.
func (dm *DelegationManager) GetDelegationIDs(delegator, delegatee string) ([]int64, bool) {
delegations, exists := dm.GetDelegatorDelegations(delegator)
if !exists {
return nil, false
}
ids := delegations.Get(delegatee)
if ids == nil {
return nil, false
}
idsSlice, ok := ids.([]int64)
if !ok {
return nil, false
}
return idsSlice, true
}
// SetDelegationIDs stores the complete ID slice for a delegator/delegatee pair.
// A missing delegator entry is initialized with a new nested tree.
//
// Parameters:
// - delegator: delegator address string used to select or create the nested tree.
// - delegatee: delegatee address string used as the nested-tree key.
// - ids: delegation IDs to store for the pair.
func (dm *DelegationManager) SetDelegationIDs(delegator, delegatee string, ids []int64) {
delegations, exists := dm.GetDelegatorDelegations(delegator)
if !exists {
delegations = NewDelegationTree()
dm.userDelegations.Set(delegator, delegations)
}
delegations.Set(delegatee, ids)
}
// AddDelegationID appends a delegation ID to the delegator-delegatee pair,
// skipping duplicates. The whole get-modify-set runs inside this domain method
// so the nested BPTree mutation never escapes the owning realm. Performing the
// lookup in one realm and the write in another (e.g. re-fetching the inner tree
// across a realm boundary and mutating it) would hit the cross-realm write
// guard for the persisted leaf slot.
//
// Parameters:
// - delegator: delegator address string used to select the nested tree.
// - delegatee: delegatee address string used as the nested-tree key.
// - delegationID: delegation ID to append when it is not already present.
func (dm *DelegationManager) AddDelegationID(delegator, delegatee string, delegationID int64) {
ids, _ := dm.GetDelegationIDs(delegator, delegatee)
for _, id := range ids {
if id == delegationID {
return
}
}
ids = append(ids, delegationID)
dm.SetDelegationIDs(delegator, delegatee, ids)
}
// RemoveDelegationID removes a delegation ID from the delegator-delegatee pair.
// Like AddDelegationID, the read-modify-write is kept inside this domain method.
// RemoveDelegationID removes one ID from a delegator/delegatee pair.
// Missing pairs and IDs are left unchanged.
//
// Parameters:
// - delegator: delegator address string used to select the nested tree.
// - delegatee: delegatee address string used as the nested-tree key.
// - delegationID: delegation ID to remove when it is present.
func (dm *DelegationManager) RemoveDelegationID(delegator, delegatee string, delegationID int64) {
ids, exists := dm.GetDelegationIDs(delegator, delegatee)
if !exists {
return
}
index := -1
for i, id := range ids {
if id == delegationID {
index = i
break
}
}
if index == -1 {
return
}
ids = append(ids[:index], ids[index+1:]...)
dm.SetDelegationIDs(delegator, delegatee, ids)
}
delegation_withdraw.gno
package staker
import (
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
)
// DelegationWithdraw represents a pending withdrawal from a delegation.
// This struct tracks undelegated amounts that are subject to lockup periods
// and manages the collection process once the lockup period expires.
type DelegationWithdraw struct {
// delegationID is the unique identifier of the associated delegation
delegationID int64
// unDelegateAmount is the total amount that was undelegated
unDelegateAmount int64
// unDelegatedHeight is the height when the undelegation occurred
unDelegatedHeight int64
// unDelegatedAt is the timestamp when the undelegation occurred
unDelegatedAt int64
// collectedAmount is the amount that has already been collected
collectedAmount int64
// collectableTime is the timestamp when collection becomes available
collectableTime int64
// collectedAt is the timestamp when collection occurred
collectedAt int64
// collected indicates whether the withdrawal has been fully collected
collected bool
}
// DelegationID returns the unique identifier of the associated delegation.
//
// Returns:
// - int64: delegation ID
func (d *DelegationWithdraw) DelegationID() int64 {
return d.delegationID
}
// UnDelegateAmount returns the total amount that was undelegated.
//
// Returns:
// - int64: undelegated amount
func (d *DelegationWithdraw) UnDelegateAmount() int64 {
return d.unDelegateAmount
}
// UnDelegatedAt returns the timestamp when the undelegation occurred.
//
// Returns:
// - int64: undelegation timestamp
func (d *DelegationWithdraw) UnDelegatedAt() int64 {
return d.unDelegatedAt
}
// UnDelegatedHeight returns the height when the undelegation occurred.
//
// Returns:
// - int64: undelegation height
func (d *DelegationWithdraw) UnDelegatedHeight() int64 {
return d.unDelegatedHeight
}
// CollectedAmount returns the amount that has already been collected.
//
// Returns:
// - int64: collected amount
func (d *DelegationWithdraw) CollectedAmount() int64 {
return d.collectedAmount
}
// CollectableTime returns the timestamp when collection becomes available.
//
// Returns:
// - int64: collectable time
func (d *DelegationWithdraw) CollectableTime() int64 {
return d.collectableTime
}
// CollectedAt returns the timestamp when collection occurred.
//
// Returns:
// - int64: collection timestamp
func (d *DelegationWithdraw) CollectedAt() int64 {
return d.collectedAt
}
// IsCollected returns whether the withdrawal has been fully collected.
//
// Returns:
// - bool: true if fully collected, false otherwise
func (d *DelegationWithdraw) IsCollected() bool {
return d.collected
}
// SetCollected sets the collected status.
//
// Parameters:
// - collected: new collected status
func (d *DelegationWithdraw) SetCollected(collected bool) {
d.collected = collected
}
// SetCollectedAt sets the collection timestamp.
//
// Parameters:
// - collectedAt: collection timestamp
func (d *DelegationWithdraw) SetCollectedAt(collectedAt int64) {
d.collectedAt = collectedAt
}
// SetCollectedAmount sets the collected amount.
//
// Parameters:
// - amount: collected amount
func (d *DelegationWithdraw) SetCollectedAmount(amount int64) {
d.collectedAmount = amount
}
// NewDelegationWithdraw creates a new delegation withdrawal with lockup period.
// The withdrawal becomes collectable after the lockup period expires.
//
// Parameters:
// - delegationID: Unique identifier of the associated delegation.
// - unDelegateAmount: Amount being withdrawn.
// - createdHeight: Block height at which the undelegation was created.
// - createdAt: Unix timestamp at which the withdrawal was created.
// - unDelegationLockupPeriod: Lockup duration in seconds.
//
// Returns:
// - DelegationWithdraw: new withdrawal instance with its collectable time set after the lockup.
func NewDelegationWithdraw(
delegationID,
unDelegateAmount,
createdHeight,
createdAt,
unDelegationLockupPeriod int64,
) DelegationWithdraw {
return DelegationWithdraw{
delegationID: delegationID,
unDelegateAmount: unDelegateAmount,
unDelegatedHeight: createdHeight,
unDelegatedAt: createdAt,
collectableTime: gnsmath.SafeAddInt64(createdAt, unDelegationLockupPeriod),
collectedAmount: 0,
collectedAt: 0,
collected: false,
}
}
// NewDelegationWithdrawWithoutLockup creates a withdrawal that is immediately collectable.
// This is used for special cases such as redelegation where no lockup is required.
//
// Parameters:
// - delegationID: Unique identifier of the associated delegation.
// - unDelegateAmount: Amount being withdrawn.
// - createdHeight: Block height at which the undelegation was created.
// - createdAt: Unix timestamp at which the withdrawal was created.
//
// Returns:
// - DelegationWithdraw: new withdrawal instance marked collected with collectable time equal to createdAt.
func NewDelegationWithdrawWithoutLockup(
delegationID,
unDelegateAmount,
createdHeight,
createdAt int64,
) DelegationWithdraw {
return DelegationWithdraw{
delegationID: delegationID,
unDelegateAmount: unDelegateAmount,
unDelegatedHeight: createdHeight,
unDelegatedAt: createdAt,
collectableTime: createdAt,
collectedAmount: unDelegateAmount, // Immediately collected
collectedAt: createdAt,
collected: true,
}
}
// Clone creates a deep copy of the delegation withdraw.
//
// Returns:
// - DelegationWithdraw: independent copy of the withdrawal state.
func (d *DelegationWithdraw) Clone() DelegationWithdraw {
return DelegationWithdraw{
delegationID: d.delegationID,
unDelegateAmount: d.unDelegateAmount,
unDelegatedHeight: d.unDelegatedHeight,
unDelegatedAt: d.unDelegatedAt,
collectedAmount: d.collectedAmount,
collectableTime: d.collectableTime,
collectedAt: d.collectedAt,
collected: d.collected,
}
}
doc.gno
package staker
emission_reward_manager.gno
package staker
import (
bptree "gno.land/p/nt/bptree/v0"
ufmt "gno.land/p/nt/ufmt/v0"
u256 "gno.land/p/gnoswap/uint256/v1"
)
const errFailedToCastRewardState = "failed to cast rewardStates's element to *EmissionRewardState: %T"
// EmissionRewardManager manages the distribution of emission rewards to stakers.
type EmissionRewardManager struct {
// rewardStates maps address to EmissionRewardState for tracking individual staker rewards
rewardStates *bptree.BPTree // address -> EmissionRewardState
// accumulatedRewardX128PerStake tracks the cumulative reward per unit of stake with 128-bit precision
accumulatedRewardX128PerStake *u256.Uint
// distributedAmount tracks the total amount of rewards distributed
distributedAmount int64
// accumulatedTimestamp tracks the last timestamp when rewards were accumulated
accumulatedTimestamp int64
// totalStakedAmount tracks the total amount of tokens staked in the system
totalStakedAmount int64
}
// NewEmissionRewardManager creates and initializes an EmissionRewardManager with empty reward states and zero accounting totals.
// Returns:
// - *EmissionRewardManager: initialized manager with empty reward states, zero totals, and a zero Q128 accumulator.
func NewEmissionRewardManager() *EmissionRewardManager {
return &EmissionRewardManager{
accumulatedRewardX128PerStake: u256.NewUint(0),
accumulatedTimestamp: 0,
totalStakedAmount: 0,
distributedAmount: 0,
rewardStates: bptree.NewBPTreeN(16),
}
}
// GetAccumulatedRewardX128PerStake returns the accumulated reward per stake with 128-bit precision.
// Returns:
// - *u256.Uint: accumulated emission reward per unit of stake in Q128 fixed-point form.
func (e *EmissionRewardManager) GetAccumulatedRewardX128PerStake() *u256.Uint {
return e.accumulatedRewardX128PerStake
}
// GetAccumulatedTimestamp returns the last timestamp when rewards were accumulated.
// Returns:
// - int64: Unix timestamp of the latest emission-reward accumulation.
func (e *EmissionRewardManager) GetAccumulatedTimestamp() int64 {
return e.accumulatedTimestamp
}
// GetTotalStakedAmount returns the total amount of tokens staked in the system.
// Returns:
// - int64: total staked token amount tracked by the manager.
func (e *EmissionRewardManager) GetTotalStakedAmount() int64 {
return e.totalStakedAmount
}
// GetDistributedAmount returns the total amount of rewards distributed.
// Returns:
// - int64: total emission reward amount marked as distributed.
func (e *EmissionRewardManager) GetDistributedAmount() int64 {
return e.distributedAmount
}
// GetRewardState retrieves the reward state for addr.
//
// Parameters:
// - addr: Address key identifying the staker's emission reward state.
//
// Returns:
// - *EmissionRewardState: stored state, or nil when addr has no state.
// - bool: true when a reward state exists for addr; false when absent.
// - error: nil on success or absence; non-nil when the stored value has the wrong type.
func (e *EmissionRewardManager) GetRewardState(addr string) (*EmissionRewardState, bool, error) {
ri := e.rewardStates.Get(addr)
if ri == nil {
return nil, false, nil
}
rs, castOk := ri.(*EmissionRewardState)
if !castOk {
return nil, false, ufmt.Errorf(errFailedToCastRewardState, ri)
}
return rs, true, nil
}
/* Setters */
// SetRewardStates replaces the tree containing per-address emission reward states.
//
// Parameters:
// - rewardStates: BPTree mapping staker addresses to emission reward states.
func (e *EmissionRewardManager) SetRewardStates(rewardStates *bptree.BPTree) {
e.rewardStates = rewardStates
}
// SetAccumulatedRewardX128PerStake stores the accumulated emission reward per stake.
//
// Parameters:
// - accumulatedRewardX128PerStake: Q128 fixed-point reward-per-stake accumulator to copy into the manager.
func (e *EmissionRewardManager) SetAccumulatedRewardX128PerStake(accumulatedRewardX128PerStake *u256.Uint) {
e.accumulatedRewardX128PerStake = u256.Zero().Set(accumulatedRewardX128PerStake)
}
// SetDistributedAmount stores the total emission amount marked as distributed.
//
// Parameters:
// - distributedAmount: Total emission reward amount distributed so far.
func (e *EmissionRewardManager) SetDistributedAmount(distributedAmount int64) {
e.distributedAmount = distributedAmount
}
// SetAccumulatedTimestamp stores the latest emission-reward accumulation timestamp.
//
// Parameters:
// - accumulatedTimestamp: Unix timestamp associated with the current accumulator.
func (e *EmissionRewardManager) SetAccumulatedTimestamp(accumulatedTimestamp int64) {
e.accumulatedTimestamp = accumulatedTimestamp
}
// SetTotalStakedAmount stores the total amount currently staked.
//
// Parameters:
// - totalStakedAmount: Aggregate token amount participating in emission rewards.
func (e *EmissionRewardManager) SetTotalStakedAmount(totalStakedAmount int64) {
e.totalStakedAmount = totalStakedAmount
}
// SetRewardState sets the reward state for a specific address
// SetRewardState stores one staker's emission reward state under address.
//
// Parameters:
// - address: Address key for the staker's reward state.
// - rewardState: Emission reward state to store for address.
func (e *EmissionRewardManager) SetRewardState(address string, rewardState *EmissionRewardState) {
e.rewardStates.Set(address, rewardState)
}
emission_reward_state.gno
package staker
import (
u256 "gno.land/p/gnoswap/uint256/v1"
)
// EmissionRewardState tracks emission reward information for an individual staker.
// This struct maintains reward debt, accumulated rewards, and claiming history
// to ensure accurate reward calculations and prevent double-claiming.
type EmissionRewardState struct {
// rewardDebtX128 represents the reward debt with 128-bit precision scaling
// Used to calculate rewards earned since the last update
rewardDebtX128 *u256.Uint
// accumulatedRewardAmount is the total rewards accumulated but not yet claimed
accumulatedRewardAmount int64
// accumulatedTimestamp is the last timestamp when rewards were accumulated
accumulatedTimestamp int64
// claimedRewardAmount is the total amount of rewards that have been claimed
claimedRewardAmount int64
// claimedTimestamp is the last timestamp when rewards were claimed
claimedTimestamp int64
// stakedAmount is the current amount of tokens staked by this address
stakedAmount int64
}
// NewEmissionRewardState creates a new emission reward state for a staker.
// This factory function initializes the state with the current system reward debt.
//
// Parameters:
// - accumulatedRewardX128PerStake: current system-wide accumulated reward per stake
//
// Returns:
// - *EmissionRewardState: new emission reward state instance
func NewEmissionRewardState(accumulatedRewardX128PerStake *u256.Uint) *EmissionRewardState {
return &EmissionRewardState{
// Deep copy the input to snapshot the current accumulator value.
rewardDebtX128: accumulatedRewardX128PerStake.Clone(),
accumulatedRewardAmount: 0,
accumulatedTimestamp: 0,
claimedRewardAmount: 0,
claimedTimestamp: 0,
stakedAmount: 0,
}
}
/* Getters */
// GetRewardDebtX128 returns the scaled reward debt used for accrual calculations.
//
// Returns:
// - *u256.Uint: current reward debt in the protocol's 128-bit fixed-point scale.
func (e *EmissionRewardState) GetRewardDebtX128() *u256.Uint { return e.rewardDebtX128 }
// GetAccumulatedRewardAmount returns rewards accrued but not yet claimed.
//
// Returns:
// - int64: accumulated reward amount in the smallest token unit.
func (e *EmissionRewardState) GetAccumulatedRewardAmount() int64 { return e.accumulatedRewardAmount }
// GetAccumulatedTimestamp returns when accumulated rewards were last updated.
//
// Returns:
// - int64: Unix timestamp in seconds of the last accumulation update.
func (e *EmissionRewardState) GetAccumulatedTimestamp() int64 { return e.accumulatedTimestamp }
// GetClaimedRewardAmount returns the total rewards already claimed.
//
// Returns:
// - int64: claimed reward amount in the smallest token unit.
func (e *EmissionRewardState) GetClaimedRewardAmount() int64 { return e.claimedRewardAmount }
// GetClaimedTimestamp returns when rewards were last claimed.
//
// Returns:
// - int64: Unix timestamp in seconds of the last claim.
func (e *EmissionRewardState) GetClaimedTimestamp() int64 { return e.claimedTimestamp }
// GetStakedAmount returns the amount currently staked for this state.
//
// Returns:
// - int64: staked token amount in the smallest token unit.
func (e *EmissionRewardState) GetStakedAmount() int64 { return e.stakedAmount }
/* Setters */
// SetRewardDebtX128 replaces the reward debt with a copied fixed-point value.
//
// Parameters:
// - rewardDebtX128: reward debt in the protocol's 128-bit fixed-point scale.
func (e *EmissionRewardState) SetRewardDebtX128(rewardDebtX128 *u256.Uint) {
e.rewardDebtX128 = u256.Zero().Set(rewardDebtX128)
}
// SetAccumulatedRewardAmount replaces the unclaimed accumulated reward amount.
//
// Parameters:
// - accumulatedRewardAmount: accumulated reward in the smallest token unit.
func (e *EmissionRewardState) SetAccumulatedRewardAmount(accumulatedRewardAmount int64) {
e.accumulatedRewardAmount = accumulatedRewardAmount
}
// SetAccumulatedTimestamp records the latest reward accumulation timestamp.
//
// Parameters:
// - accumulatedTimestamp: Unix timestamp in seconds for the accumulation update.
func (e *EmissionRewardState) SetAccumulatedTimestamp(accumulatedTimestamp int64) {
e.accumulatedTimestamp = accumulatedTimestamp
}
// SetClaimedRewardAmount replaces the total claimed reward amount.
//
// Parameters:
// - claimedRewardAmount: claimed reward in the smallest token unit.
func (e *EmissionRewardState) SetClaimedRewardAmount(claimedRewardAmount int64) {
e.claimedRewardAmount = claimedRewardAmount
}
// SetClaimedTimestamp records the latest reward claim timestamp.
//
// Parameters:
// - claimedTimestamp: Unix timestamp in seconds for the claim.
func (e *EmissionRewardState) SetClaimedTimestamp(claimedTimestamp int64) {
e.claimedTimestamp = claimedTimestamp
}
// SetStakedAmount replaces the current staked amount.
// Parameters:
// - stakedAmount: staked token amount in the smallest token unit.
func (e *EmissionRewardState) SetStakedAmount(stakedAmount int64) {
e.stakedAmount = stakedAmount
}
errors.gno
package staker // ErrSpoofedRealm is returned by store Set* methods when the supplied realm // token does not match the current crossing frame (rlm.IsCurrent() is false), // rejecting spoofed or stale realm tokens before any write is performed. const ErrSpoofedRealm = "rlm does not match the current crossing frame"
getter_utils.gno
package staker
func cloneInt64Slice(src []int64) []int64 {
if src == nil {
return nil
}
cloned := make([]int64, len(src))
copy(cloned, src)
return cloned
}
func cloneStringInt64Map(src map[string]int64) map[string]int64 {
if src == nil {
return nil
}
cloned := make(map[string]int64, len(src))
for key, value := range src {
cloned[key] = value
}
return cloned
}
func cloneDelegationWithdraws(src []DelegationWithdraw) []DelegationWithdraw {
if src == nil {
return nil
}
cloned := make([]DelegationWithdraw, len(src))
copy(cloned, src)
return cloned
}
getters.gno
package staker
import (
u256 "gno.land/p/gnoswap/uint256/v1"
rotree "gno.land/p/nt/bptree/rotree/v0"
)
// GetTotalxGnsSupply returns total xGNS supply, including launchpad-held xGNS.
// Returns:
// - int64: total xGNS supply, including xGNS held by launchpad projects.
func GetTotalxGnsSupply() int64 {
return getImplementation().GetTotalxGnsSupply()
}
// GetTotalDelegated returns the total amount of GNS delegated.
// Returns:
// - int64: total GNS amount delegated across all delegators.
func GetTotalDelegated() int64 {
return getImplementation().GetTotalDelegated()
}
// GetTotalLockedAmount returns the total amount of GNS locked in undelegation.
// Returns:
// - int64: total GNS amount currently locked in undelegation withdrawals.
func GetTotalLockedAmount() int64 {
return getImplementation().GetTotalLockedAmount()
}
// GetUnDelegationLockupPeriod returns the undelegation lockup period in seconds.
// Returns:
// - int64: configured undelegation lockup duration in seconds.
func GetUnDelegationLockupPeriod() int64 {
return getImplementation().GetUnDelegationLockupPeriod()
}
// GetDelegations returns a read-only view of every delegation, keyed by the
// decimal string form of the delegation ID. Callers paginate it themselves
// through IterateByOffset. Reading an entry yields a clone, so the view cannot
// mutate realm state.
// Returns:
// - *rotree.ReadOnlyTree: read-only delegation view keyed by decimal delegation ID; entry reads return clones.
func GetDelegations() *rotree.ReadOnlyTree {
return getImplementation().GetDelegations()
}
// ExistsDelegation checks if a delegation exists.
// Parameters:
// - delegationID: Numeric identifier of the delegation to look up.
//
// Returns:
// - bool: true when a delegation with delegationID exists, false otherwise.
func ExistsDelegation(delegationID int64) bool {
return getImplementation().ExistsDelegation(delegationID)
}
// GetDelegatorDelegations returns a read-only view of a delegator's delegations,
// keyed by delegatee address with that pair's delegation IDs as the value.
// Reading an entry yields a copy of the ID slice, so the view cannot mutate
// realm state. nil is returned when the delegator has no delegations.
// Parameters:
// - delegator: Address whose delegations should be listed.
//
// Returns:
// - *rotree.ReadOnlyTree: read-only view keyed by delegatee address, or nil when delegator has no delegations.
func GetDelegatorDelegations(delegator address) *rotree.ReadOnlyTree {
return getImplementation().GetDelegatorDelegations(delegator)
}
// GetUserDelegationIDs returns a list of delegation IDs for a specific delegator-delegatee pair.
// Parameters:
// - delegator: Address that supplied the delegation.
// - delegatee: Address receiving that delegation.
//
// Returns:
// - []int64: delegation IDs for the delegator-delegatee pair; the returned slice is independent of realm state.
func GetUserDelegationIDs(delegator address, delegatee address) []int64 {
return cloneInt64Slice(getImplementation().GetUserDelegationIDs(delegator, delegatee))
}
// HasDelegationSnapshotsKey returns true if delegation history exists.
// Returns:
// - bool: true when delegation history has been initialized in storage.
func HasDelegationSnapshotsKey() bool {
return getImplementation().HasDelegationSnapshotsKey()
}
// GetTotalDelegationAmountAtSnapshot returns total delegation at a Unix
// timestamp, using the latest history entry at or before that timestamp.
// The lookup is timestamp-based rather than a block-height snapshot.
// Parameters:
// - snapshotTime: Unix timestamp at or before which to select the latest aggregate delegation history entry.
//
// Returns:
// - int64: aggregate delegated amount recorded at or before snapshotTime.
// - bool: true when a qualifying history entry exists; false when no entry is available.
func GetTotalDelegationAmountAtSnapshot(snapshotTime int64) (int64, bool) {
return getImplementation().GetTotalDelegationAmountAtSnapshot(snapshotTime)
}
// GetUserDelegationAmountAtSnapshot returns one user's delegation at a Unix
// timestamp, using that user's latest history entry at or before the timestamp.
// The bool is false when no qualifying history entry exists.
// Parameters:
// - userAddr: Delegator address whose historical delegation is queried.
// - snapshotTime: Unix timestamp at or before which to select the user's latest history entry.
//
// Returns:
// - int64: user's delegated amount recorded at or before snapshotTime.
// - bool: true when a qualifying user-history entry exists; false otherwise.
func GetUserDelegationAmountAtSnapshot(userAddr address, snapshotTime int64) (int64, bool) {
return getImplementation().GetUserDelegationAmountAtSnapshot(userAddr, snapshotTime)
}
// GetClaimableRewardByAddress returns claimable rewards for an address.
//
// Parameters:
// - addr: Address whose emission and protocol-fee rewards are queried.
//
// Returns:
// - int64: emission reward amount available to addr.
// - map[string]int64: protocol-fee reward amounts keyed by token path.
// - error: nil on success; non-nil when reward state cannot be resolved for addr.
func GetClaimableRewardByAddress(addr address) (int64, map[string]int64, error) {
emissionReward, protocolFees, err := getImplementation().GetClaimableRewardByAddress(addr)
if err != nil {
return 0, nil, err
}
return emissionReward, cloneStringInt64Map(protocolFees), nil
}
// GetClaimableRewardByLaunchpad returns claimable launchpad rewards for an address.
//
// Parameters:
// - addr: Address whose launchpad and protocol-fee rewards are queried.
//
// Returns:
// - int64: emission reward amount available to addr.
// - map[string]int64: protocol-fee reward amounts keyed by token path.
// - error: nil on success; non-nil when reward state cannot be resolved for addr.
func GetClaimableRewardByLaunchpad(addr address) (int64, map[string]int64, error) {
emissionReward, protocolFees, err := getImplementation().GetClaimableRewardByLaunchpad(addr)
if err != nil {
return 0, nil, err
}
return emissionReward, cloneStringInt64Map(protocolFees), nil
}
// GetClaimableRewardByRewardID returns claimable reward details by reward ID.
//
// Parameters:
// - rewardID: Reward-state identifier whose claimable rewards are queried.
//
// Returns:
// - int64: emission reward amount associated with rewardID.
// - map[string]int64: protocol-fee reward amounts keyed by token path.
// - error: nil on success; non-nil when rewardID cannot be resolved.
func GetClaimableRewardByRewardID(rewardID string) (int64, map[string]int64, error) {
emissionReward, protocolFees, err := getImplementation().GetClaimableRewardByRewardID(rewardID)
if err != nil {
return 0, nil, err
}
return emissionReward, cloneStringInt64Map(protocolFees), nil
}
// GetLaunchpadProjectDeposit returns the deposit amount for a launchpad project.
// Parameters:
// - projectAddr: Launchpad project address whose deposited amount is queried.
//
// Returns:
// - int64: recorded launchpad project deposit amount.
// - bool: true when a deposit record exists for projectAddr; false otherwise.
func GetLaunchpadProjectDeposit(projectAddr string) (int64, bool) {
return getImplementation().GetLaunchpadProjectDeposit(projectAddr)
}
// GetDelegationWithdrawCount returns the total number of delegation withdraws for a specific delegation.
// Parameters:
// - delegationID: Identifier of the delegation whose withdrawals are counted.
//
// Returns:
// - int: number of withdrawal records associated with delegationID.
func GetDelegationWithdrawCount(delegationID int64) int {
return getImplementation().GetDelegationWithdrawCount(delegationID)
}
// GetDelegationWithdraws returns a paginated list of delegation withdraws for a specific delegation.
// Parameters:
// - delegationID: Identifier of the delegation whose withdrawals are requested.
// - offset: Number of matching withdrawal records to skip before collecting results.
// - count: Maximum number of withdrawal records to return.
//
// Returns:
// - []DelegationWithdraw: requested page of withdrawal records, copied before returning.
// - error: nil on success; non-nil when the requested delegation or page cannot be read.
func GetDelegationWithdraws(delegationID int64, offset, count int) ([]DelegationWithdraw, error) {
withdraws, err := getImplementation().GetDelegationWithdraws(delegationID, offset, count)
if err != nil {
return nil, err
}
return cloneDelegationWithdraws(withdraws), nil
}
// GetCollectableWithdrawAmount returns the collectable withdraw amount for a specific delegation.
// Parameters:
// - delegationID: Identifier of the delegation whose collectable amount is queried.
//
// Returns:
// - int64: amount currently available to collect from delegationID.
func GetCollectableWithdrawAmount(delegationID int64) int64 {
return getImplementation().GetCollectableWithdrawAmount(delegationID)
}
// GetProtocolFeeAccumulatedX128PerStake returns the accumulated protocol fee per stake (Q128) for a token path.
// Parameters:
// - tokenPath: Registered token path whose protocol-fee accumulator is queried.
//
// Returns:
// - *u256.Uint: accumulated protocol-fee amount per unit stake in Q128 fixed-point form.
func GetProtocolFeeAccumulatedX128PerStake(tokenPath string) *u256.Uint {
return getImplementation().GetProtocolFeeAccumulatedX128PerStake(tokenPath).Clone()
}
// GetProtocolFeeAmount returns the protocol fee amounts for a token path.
// Parameters:
// - tokenPath: Registered token path whose protocol fees are queried.
//
// Returns:
// - int64: accumulated protocol-fee amount for tokenPath in token base units.
func GetProtocolFeeAmount(tokenPath string) int64 {
return getImplementation().GetProtocolFeeAmount(tokenPath)
}
// GetProtocolFeeAccumulatedTimestamp returns the accumulated timestamp for protocol fee rewards.
// Returns:
// - int64: Unix timestamp at which protocol-fee accumulation was last updated.
func GetProtocolFeeAccumulatedTimestamp() int64 {
return getImplementation().GetProtocolFeeAccumulatedTimestamp()
}
// GetEmissionAccumulatedX128PerStake returns the accumulated emission per stake (Q128).
// Returns:
// - *u256.Uint: accumulated emission reward per unit stake in Q128 fixed-point form.
func GetEmissionAccumulatedX128PerStake() *u256.Uint {
return getImplementation().GetEmissionAccumulatedX128PerStake().Clone()
}
// GetEmissionDistributedAmount returns the total distributed emission amount.
// Returns:
// - int64: total emission amount distributed to stakers.
func GetEmissionDistributedAmount() int64 {
return getImplementation().GetEmissionDistributedAmount()
}
// GetEmissionAccumulatedTimestamp returns the accumulated timestamp for emission rewards.
// Returns:
// - int64: Unix timestamp at which emission accumulation was last updated.
func GetEmissionAccumulatedTimestamp() int64 {
return getImplementation().GetEmissionAccumulatedTimestamp()
}
gnomod.toml
module = "gno.land/r/gnoswap/gov/staker" gno = "0.9" [addpkg] creator = "g1q5tjjv3kkslzwf2na9y9wk7e5a8ugph8xfsk04" height = 77260 max_deposit = "100000000ugnot"
launchpad_project_deposits.gno
package staker
import (
bptree "gno.land/p/nt/bptree/v0"
)
// LaunchpadProjectDeposits manages deposit amounts for launchpad projects.
// It tracks the total staked amount for each project identified by owner address.
type LaunchpadProjectDeposits struct {
// deposits maps owner address to deposit amount
deposits *bptree.BPTree // string -> int64
}
// NewLaunchpadProjectDeposits creates an empty owner-to-deposit tree.
//
// Returns:
// - *LaunchpadProjectDeposits: deposit manager initialized with an empty tree.
func NewLaunchpadProjectDeposits() *LaunchpadProjectDeposits {
return &LaunchpadProjectDeposits{
deposits: bptree.NewBPTreeN(16),
}
}
// GetDeposits returns the owner-to-deposit tree managed by this instance.
//
// Returns:
// - *bptree.BPTree: tree keyed by owner address string and storing int64 amounts.
func (lpd *LaunchpadProjectDeposits) GetDeposits() *bptree.BPTree {
return lpd.deposits
}
// SetDeposits replaces the owner-to-deposit tree.
//
// Parameters:
// - deposits: tree keyed by owner address string and storing int64 amounts.
func (lpd *LaunchpadProjectDeposits) SetDeposits(deposits *bptree.BPTree) {
lpd.deposits = deposits
}
// GetDeposit looks up a project's deposit by owner address.
//
// Parameters:
// - ownerAddress: owner address string used as the deposit key.
//
// Returns:
// - int64: stored deposit amount in the smallest token unit, or zero when absent.
// - bool: true when an int64 deposit is stored for the owner.
func (lpd *LaunchpadProjectDeposits) GetDeposit(ownerAddress string) (int64, bool) {
deposit := lpd.deposits.Get(ownerAddress)
if deposit == nil {
return 0, false
}
amount, ok := deposit.(int64)
return amount, ok
}
// SetDeposit stores or replaces an owner's deposit amount.
//
// Parameters:
// - ownerAddress: owner address string used as the deposit key.
// - amount: deposit amount in the smallest token unit.
func (lpd *LaunchpadProjectDeposits) SetDeposit(ownerAddress string, amount int64) {
lpd.deposits.Set(ownerAddress, amount)
}
// RemoveDeposit removes an owner's deposit entry.
//
// Parameters:
// - ownerAddress: owner address string whose deposit entry should be removed.
//
// Returns:
// - bool: true when an entry was removed; false when no entry existed.
func (lpd *LaunchpadProjectDeposits) RemoveDeposit(ownerAddress string) bool {
_, ok := lpd.deposits.Remove(ownerAddress)
return ok
}
protocol_fee_reward_manager.gno
package staker
import (
bptree "gno.land/p/nt/bptree/v0"
ufmt "gno.land/p/nt/ufmt/v0"
u256 "gno.land/p/gnoswap/uint256/v1"
)
// ProtocolFeeRewardManager distributes protocol fees to stakers.
//
// Protocol fees arrive in many tokens, so the manager keeps one accumulator per token
// instead of a single one. A stake change never touches those accumulators: it advances
// the accrual epoch, records the total stake in force from that epoch, and appends one
// event for an ordinary add/remove. Redelegate performs a remove plus an add and
// therefore appends two events. The per-token work happens when a token is collected,
// so stake-change cost does not depend on how many tokens ever collected a fee.
type ProtocolFeeRewardManager struct {
// rewardStates maps a reward ID to the ProtocolFeeRewardState tracking that staker
rewardStates *bptree.BPTree // rewardID -> *ProtocolFeeRewardState
// tokenAccumulators maps a token path to its ProtocolFeeTokenAccumulator
tokenAccumulators *bptree.BPTree // tokenPath -> *ProtocolFeeTokenAccumulator
// currentEpoch is the accrual epoch in force, mirrored from protocol_fee
currentEpoch int64
// totalStakedAmount is the total amount currently staked
totalStakedAmount int64
// totalStakedHistory records the total staked amount in force from each epoch
totalStakedHistory *UintTree // epoch -> int64
// accumulatedTimestamp is the last timestamp at which the accrual state moved: a fold or a stake change
accumulatedTimestamp int64
}
// NewProtocolFeeRewardManager creates a new instance of ProtocolFeeRewardManager.
//
// Returns:
// - *ProtocolFeeRewardManager: new protocol fee reward manager instance
func NewProtocolFeeRewardManager() *ProtocolFeeRewardManager {
totalStakedHistory := NewUintTree()
totalStakedHistory.Set(0, int64(0))
return &ProtocolFeeRewardManager{
rewardStates: bptree.NewBPTreeN(16),
tokenAccumulators: bptree.NewBPTreeN(16),
currentEpoch: 0,
totalStakedAmount: 0,
totalStakedHistory: totalStakedHistory,
accumulatedTimestamp: 0,
}
}
/* Getters */
// GetRewardState retrieves the reward state identified by rewardID.
// Missing IDs return nil and false; a stored value of the wrong type returns
// an error.
//
// Parameters:
// - rewardID: identifier of the staker reward state to retrieve
//
// Returns:
// - *ProtocolFeeRewardState: stored reward state, or nil when rewardID is absent or invalid
// - bool: true when a correctly typed reward state was found
// - error: nil when absent or found; a cast error when the stored value has the wrong type
func (p *ProtocolFeeRewardManager) GetRewardState(rewardID string) (*ProtocolFeeRewardState, bool, error) {
ri := p.rewardStates.Get(rewardID)
if ri == nil {
return nil, false, nil
}
rs, castOk := ri.(*ProtocolFeeRewardState)
if !castOk {
return nil, false, ufmt.Errorf(errFailedToCastRewardState, ri)
}
return rs, true, nil
}
// GetTokenAccumulator returns the accumulator of tokenPath, or false when the token
// never had a fee folded in.
//
// Parameters:
// - tokenPath: token package path whose protocol-fee accumulator is requested
//
// Returns:
// - *ProtocolFeeTokenAccumulator: accumulator for tokenPath, or nil when none exists
// - bool: true when tokenPath has a folded-fee accumulator
func (p *ProtocolFeeRewardManager) GetTokenAccumulator(tokenPath string) (*ProtocolFeeTokenAccumulator, bool) {
ai := p.tokenAccumulators.Get(tokenPath)
if ai == nil {
return nil, false
}
accumulator, castOk := ai.(*ProtocolFeeTokenAccumulator)
if !castOk {
panic(ufmt.Sprintf("failed to cast token accumulator: %T", ai))
}
return accumulator, true
}
// GetTokenPaths returns every token path that had a fee folded in, in key order.
//
// Returns:
// - []string: token paths present in the accumulator tree, ordered by tree key
func (p *ProtocolFeeRewardManager) GetTokenPaths() []string {
tokenPaths := make([]string, 0, p.tokenAccumulators.Size())
p.tokenAccumulators.Iterate("", "", func(key string, _ any) bool {
tokenPaths = append(tokenPaths, key)
return false
})
return tokenPaths
}
// GetAccumulatedProtocolFeeX128PerStake returns the accumulated fee per stake of tokenPath
// (scaled by 2^128), or nil when the token never had a fee folded in.
//
// Parameters:
// - tokenPath: token package path whose accumulated per-stake fee is requested
//
// Returns:
// - *u256.Uint: accumulated fee per stake scaled by 2^128, or nil when tokenPath has no accumulator
func (p *ProtocolFeeRewardManager) GetAccumulatedProtocolFeeX128PerStake(tokenPath string) *u256.Uint {
accumulator, ok := p.GetTokenAccumulator(tokenPath)
if !ok {
return nil
}
return accumulator.GetAccumulatedX128PerStake()
}
// GetProtocolFeeAmount returns the total fee amount folded in for tokenPath.
//
// Parameters:
// - tokenPath: token package path whose folded protocol-fee amount is requested
//
// Returns:
// - int64: total fee amount folded for tokenPath, or zero when no accumulator exists
func (p *ProtocolFeeRewardManager) GetProtocolFeeAmount(tokenPath string) int64 {
accumulator, ok := p.GetTokenAccumulator(tokenPath)
if !ok {
return 0
}
return accumulator.GetProtocolFeeAmount()
}
// GetCurrentEpoch returns the accrual epoch currently in force.
//
// Returns:
// - int64: current protocol-fee accrual epoch
func (p *ProtocolFeeRewardManager) GetCurrentEpoch() int64 {
return p.currentEpoch
}
// GetTotalStakedAmount returns the total amount currently staked.
//
// Returns:
// - int64: current total staked amount
func (p *ProtocolFeeRewardManager) GetTotalStakedAmount() int64 {
return p.totalStakedAmount
}
// GetTotalStakedAmountAt returns the total staked amount in force during epoch,
// using the latest recorded stake amount at or before that epoch.
//
// Parameters:
// - epoch: accrual epoch whose effective total stake is requested
//
// Returns:
// - int64: total stake recorded at or before epoch, or zero for a negative epoch
func (p *ProtocolFeeRewardManager) GetTotalStakedAmountAt(epoch int64) int64 {
if epoch < 0 {
return 0
}
totalStakedAmount := int64(0)
p.totalStakedHistory.ReverseIterate(0, epoch, func(_ int64, value any) bool {
amount, castOk := value.(int64)
if !castOk {
panic(ufmt.Sprintf("failed to cast total staked amount: %T", value))
}
totalStakedAmount = amount
return true
})
return totalStakedAmount
}
// GetAccumulatedTimestamp returns the last timestamp at which fee accrual
// state moved through a fold or stake change.
//
// Returns:
// - int64: last accumulated-state update timestamp
func (p *ProtocolFeeRewardManager) GetAccumulatedTimestamp() int64 {
return p.accumulatedTimestamp
}
/* Setters */
// SetRewardState stores rewardState under rewardID.
//
// Parameters:
// - rewardID: identifier under which the staker reward state is stored
// - rewardState: reward state to associate with rewardID
func (p *ProtocolFeeRewardManager) SetRewardState(rewardID string, rewardState *ProtocolFeeRewardState) {
p.rewardStates.Set(rewardID, rewardState)
}
// SetTokenAccumulator stores accumulator under tokenPath.
//
// Parameters:
// - tokenPath: token package path used as the accumulator key
// - accumulator: protocol-fee accumulator to store for tokenPath
func (p *ProtocolFeeRewardManager) SetTokenAccumulator(tokenPath string, accumulator *ProtocolFeeTokenAccumulator) {
p.tokenAccumulators.Set(tokenPath, accumulator)
}
// SetCurrentEpoch records the accrual epoch currently in force.
//
// Parameters:
// - epoch: new current protocol-fee accrual epoch
func (p *ProtocolFeeRewardManager) SetCurrentEpoch(epoch int64) {
p.currentEpoch = epoch
}
// SetTotalStakedAmount records the total amount currently staked.
//
// Parameters:
// - totalStakedAmount: new total staked amount
func (p *ProtocolFeeRewardManager) SetTotalStakedAmount(totalStakedAmount int64) {
p.totalStakedAmount = totalStakedAmount
}
// SetTotalStakedAmountAt records the total staked amount in force from epoch on.
//
// Parameters:
// - epoch: first accrual epoch at which totalStakedAmount is in force
// - totalStakedAmount: total stake amount to record from epoch onward
func (p *ProtocolFeeRewardManager) SetTotalStakedAmountAt(epoch int64, totalStakedAmount int64) {
p.totalStakedHistory.Set(epoch, totalStakedAmount)
}
// SetAccumulatedTimestamp records the timestamp at which accrual state last moved.
//
// Parameters:
// - accumulatedTimestamp: timestamp to record for the latest fold or stake change
func (p *ProtocolFeeRewardManager) SetAccumulatedTimestamp(accumulatedTimestamp int64) {
p.accumulatedTimestamp = accumulatedTimestamp
}
protocol_fee_reward_state.gno
package staker
import (
bptree "gno.land/p/nt/bptree/v0"
ufmt "gno.land/p/nt/ufmt/v0"
u256 "gno.land/p/gnoswap/uint256/v1"
)
// ProtocolFeeRewardState tracks the protocol fee rewards of one staker.
//
// Ordinary stake changes append one ProtocolFeeStakeEvent; Redelegate performs
// a remove plus an add and appends two events. Each token is settled on its own
// from those events, so the state keeps a per-token cursor into the event
// history rather than a reward debt for every token at once.
type ProtocolFeeRewardState struct {
// stakedAmount is the current amount staked
stakedAmount int64
// stakeEvents records the staked amount in force from each stake change, by index
stakeEvents *UintTree // index -> *ProtocolFeeStakeEvent
// stakeEventCount is the number of recorded stake events
stakeEventCount int64
// tokenStates maps a token path to the settlement state of that token
tokenStates *bptree.BPTree // tokenPath -> *ProtocolFeeTokenRewardState
// claimedTimestamp is the last timestamp at which every token was collected
claimedTimestamp int64
}
// ProtocolFeeStakeEvent is one stake change: from epoch on, stakedAmount was staked.
type ProtocolFeeStakeEvent struct {
epoch int64
stakedAmount int64
}
// GetEpoch returns the accrual epoch from which this stake event applies.
//
// Returns:
// - int64: epoch at which the stake amount became effective
func (e *ProtocolFeeStakeEvent) GetEpoch() int64 { return e.epoch }
// GetStakedAmount returns the stake amount in force for this event.
//
// Returns:
// - int64: staked amount associated with the event
func (e *ProtocolFeeStakeEvent) GetStakedAmount() int64 { return e.stakedAmount }
// ProtocolFeeTokenRewardState is the settlement state of one token for one staker.
//
// Stake events up to eventCursor are folded into earnedX128. The open segment starts
// where the last folded event left the accumulator (segmentStartX128) with
// segmentStakedAmount staked.
type ProtocolFeeTokenRewardState struct {
// eventCursor is the number of stake events already folded in
eventCursor int64
// segmentStakedAmount is the amount staked during the open segment
segmentStakedAmount int64
// segmentStartX128 is the accumulated fee per stake at the start of the open segment
segmentStartX128 *u256.Uint
// earnedX128 is the reward earned by closed segments and not yet collected, scaled by 2^128
earnedX128 *u256.Uint
// claimedReward is the total reward collected so far
claimedReward int64
}
// NewProtocolFeeRewardState creates an empty state for a staker with no stake.
//
// Returns:
// - *ProtocolFeeRewardState: initialized reward state with empty event and token trees
func NewProtocolFeeRewardState() *ProtocolFeeRewardState {
return &ProtocolFeeRewardState{
stakedAmount: 0,
stakeEvents: NewUintTree(),
stakeEventCount: 0,
tokenStates: bptree.NewBPTreeN(16),
claimedTimestamp: 0,
}
}
// NewProtocolFeeTokenRewardState creates the settlement state of a token whose open
// segment starts at the given cursor, stake and accumulator value.
//
// Parameters:
// - eventCursor: number of stake events already folded into this token state
// - segmentStakedAmount: stake amount in force during the open segment
// - segmentStartX128: accumulated fee-per-stake value at the open segment start, scaled by 2^128
//
// Returns:
// - *ProtocolFeeTokenRewardState: token settlement state with zero closed-segment earnings and claimed reward
func NewProtocolFeeTokenRewardState(eventCursor int64, segmentStakedAmount int64, segmentStartX128 *u256.Uint) *ProtocolFeeTokenRewardState {
return &ProtocolFeeTokenRewardState{
eventCursor: eventCursor,
segmentStakedAmount: segmentStakedAmount,
segmentStartX128: u256.Zero().Set(segmentStartX128),
earnedX128: u256.Zero(),
claimedReward: 0,
}
}
/* ProtocolFeeRewardState getters */
// GetStakedAmount returns the current stake amount tracked for the staker.
//
// Returns:
// - int64: current staked amount
func (p *ProtocolFeeRewardState) GetStakedAmount() int64 {
return p.stakedAmount
}
// GetStakeEventCount returns the number of stake-change events recorded.
//
// Returns:
// - int64: count of indexed stake events
func (p *ProtocolFeeRewardState) GetStakeEventCount() int64 {
return p.stakeEventCount
}
// GetStakeEvent returns the indexed stake event.
//
// Parameters:
// - index: zero-based stake-event index
//
// Returns:
// - *ProtocolFeeStakeEvent: event at index, or nil when no event is stored there
// - bool: true when an event exists at index; false when the index is absent
func (p *ProtocolFeeRewardState) GetStakeEvent(index int64) (*ProtocolFeeStakeEvent, bool) {
ei, ok := p.stakeEvents.Get(index)
if !ok {
return nil, false
}
event, castOk := ei.(*ProtocolFeeStakeEvent)
if !castOk {
panic(ufmt.Sprintf("failed to cast stake event: %T", ei))
}
return event, true
}
// GetTokenState returns the settlement state of tokenPath, or false when the token was
// never settled for this staker.
//
// Parameters:
// - tokenPath: registered token path whose per-staker settlement state is requested
//
// Returns:
// - *ProtocolFeeTokenRewardState: token settlement state, or nil when it has not been initialized
// - bool: true when tokenPath has a stored settlement state, otherwise false
func (p *ProtocolFeeRewardState) GetTokenState(tokenPath string) (*ProtocolFeeTokenRewardState, bool) {
ti := p.tokenStates.Get(tokenPath)
if ti == nil {
return nil, false
}
tokenState, castOk := ti.(*ProtocolFeeTokenRewardState)
if !castOk {
panic(ufmt.Sprintf("failed to cast token reward state: %T", ti))
}
return tokenState, true
}
// GetTokenPaths returns every token path settled for this staker, in key order.
//
// Returns:
// - []string: token paths with stored settlement state, ordered by the underlying tree keys
func (p *ProtocolFeeRewardState) GetTokenPaths() []string {
tokenPaths := make([]string, 0, p.tokenStates.Size())
p.tokenStates.Iterate("", "", func(key string, _ any) bool {
tokenPaths = append(tokenPaths, key)
return false
})
return tokenPaths
}
// GetClaimedReward returns the total reward of tokenPath collected so far.
//
// Parameters:
// - tokenPath: token path whose accumulated claimed reward is requested
//
// Returns:
// - int64: total reward collected for tokenPath, or zero when no token state exists
func (p *ProtocolFeeRewardState) GetClaimedReward(tokenPath string) int64 {
tokenState, ok := p.GetTokenState(tokenPath)
if !ok {
return 0
}
return tokenState.GetClaimedReward()
}
// GetClaimedTimestamp returns the last timestamp at which all token rewards were collected.
//
// Returns:
// - int64: Unix timestamp recorded for the most recent all-token collection
func (p *ProtocolFeeRewardState) GetClaimedTimestamp() int64 {
return p.claimedTimestamp
}
/* ProtocolFeeRewardState setters */
// SetStakedAmount updates the current stake amount tracked for the staker.
//
// Parameters:
// - stakedAmount: new current staked amount
func (p *ProtocolFeeRewardState) SetStakedAmount(stakedAmount int64) {
p.stakedAmount = stakedAmount
}
// AppendStakeEvent records that stakedAmount is staked from epoch on.
//
// Parameters:
// - epoch: accrual epoch at which this stake amount becomes effective
// - stakedAmount: stake amount in force from epoch onward
func (p *ProtocolFeeRewardState) AppendStakeEvent(epoch int64, stakedAmount int64) {
p.stakeEvents.Set(p.stakeEventCount, &ProtocolFeeStakeEvent{
epoch: epoch,
stakedAmount: stakedAmount,
})
p.stakeEventCount++
}
// SetTokenState stores the settlement state for a token path.
//
// Parameters:
// - tokenPath: token path used as the settlement-state key
// - tokenState: per-token settlement state to store
func (p *ProtocolFeeRewardState) SetTokenState(tokenPath string, tokenState *ProtocolFeeTokenRewardState) {
p.tokenStates.Set(tokenPath, tokenState)
}
// SetClaimedTimestamp records the timestamp at which all token rewards were collected.
//
// Parameters:
// - claimedTimestamp: Unix timestamp of the all-token collection
func (p *ProtocolFeeRewardState) SetClaimedTimestamp(claimedTimestamp int64) {
p.claimedTimestamp = claimedTimestamp
}
/* ProtocolFeeTokenRewardState getters and setters */
// GetEventCursor returns the number of stake events already folded for this token.
//
// Returns:
// - int64: count of folded stake events
func (t *ProtocolFeeTokenRewardState) GetEventCursor() int64 {
return t.eventCursor
}
// GetSegmentStakedAmount returns the stake amount in the open segment.
//
// Returns:
// - int64: stake amount used while settling the open segment
func (t *ProtocolFeeTokenRewardState) GetSegmentStakedAmount() int64 {
return t.segmentStakedAmount
}
// GetSegmentStartX128 returns the accumulator value at the open segment start.
//
// Returns:
// - *u256.Uint: fee-per-stake accumulator at segment start, scaled by 2^128
func (t *ProtocolFeeTokenRewardState) GetSegmentStartX128() *u256.Uint {
return t.segmentStartX128
}
// GetEarnedX128 returns closed-segment earnings awaiting collection.
//
// Returns:
// - *u256.Uint: unclaimed reward accumulator scaled by 2^128
func (t *ProtocolFeeTokenRewardState) GetEarnedX128() *u256.Uint {
return t.earnedX128
}
// GetClaimedReward returns the total reward collected for this token state.
//
// Returns:
// - int64: cumulative collected reward amount
func (t *ProtocolFeeTokenRewardState) GetClaimedReward() int64 {
return t.claimedReward
}
// SetSegment moves the open segment: events up to eventCursor are folded, and the
// segment starts at segmentStartX128 with segmentStakedAmount staked.
//
// Parameters:
// - eventCursor: number of stake events folded into the new segment
// - segmentStakedAmount: stake amount in force for the new open segment
// - segmentStartX128: fee-per-stake accumulator at the new segment start, scaled by 2^128
func (t *ProtocolFeeTokenRewardState) SetSegment(eventCursor int64, segmentStakedAmount int64, segmentStartX128 *u256.Uint) {
t.eventCursor = eventCursor
t.segmentStakedAmount = segmentStakedAmount
t.segmentStartX128 = u256.Zero().Set(segmentStartX128)
}
// SetEarnedX128 replaces the closed-segment earnings accumulator.
//
// Parameters:
// - earnedX128: unclaimed earnings accumulator scaled by 2^128
func (t *ProtocolFeeTokenRewardState) SetEarnedX128(earnedX128 *u256.Uint) {
t.earnedX128 = u256.Zero().Set(earnedX128)
}
// SetClaimedReward replaces the cumulative collected reward amount.
//
// Parameters:
// - claimedReward: total reward collected for this token state
func (t *ProtocolFeeTokenRewardState) SetClaimedReward(claimedReward int64) {
t.claimedReward = claimedReward
}
protocol_fee_token_accumulator.gno
package staker
import (
ufmt "gno.land/p/nt/ufmt/v0"
u256 "gno.land/p/gnoswap/uint256/v1"
)
// ProtocolFeeTokenAccumulator tracks the accumulated protocol fee per stake of one token.
//
// Fees are folded in per accrual epoch, each against the total stake in force during
// that epoch. The value after folding each epoch is kept in history so that a staker's
// reward can be settled later against the accumulator as it stood at any epoch.
type ProtocolFeeTokenAccumulator struct {
// accumulatedX128PerStake is the latest accumulated fee per stake, scaled by 2^128
accumulatedX128PerStake *u256.Uint
// history maps an epoch to the accumulated value after that epoch's fees were folded
history *UintTree // epoch -> *u256.Uint
// firstEpoch is the first epoch a fee was folded for, or -1 when none was
firstEpoch int64
// foldedEpoch is the last epoch whose fees are known to be fully folded, or -1
foldedEpoch int64
// protocolFeeAmount is the total fee amount folded in
protocolFeeAmount int64
}
// NewProtocolFeeTokenAccumulator creates an empty accumulator with no folded
// epochs or protocol fees recorded.
//
// Returns:
// - *ProtocolFeeTokenAccumulator: accumulator initialized with zero values and
// empty epoch history.
func NewProtocolFeeTokenAccumulator() *ProtocolFeeTokenAccumulator {
return &ProtocolFeeTokenAccumulator{
accumulatedX128PerStake: u256.Zero(),
history: NewUintTree(),
firstEpoch: -1,
foldedEpoch: -1,
protocolFeeAmount: 0,
}
}
/* Getters */
// GetAccumulatedX128PerStake returns the latest accumulated protocol fee per stake,
// scaled by 2^128.
//
// Returns:
// - *u256.Uint: latest accumulated fee-per-stake value in Q128 fixed-point form.
func (a *ProtocolFeeTokenAccumulator) GetAccumulatedX128PerStake() *u256.Uint {
return a.accumulatedX128PerStake
}
// GetAccumulatedX128PerStakeAt returns the accumulated value after the fees of the
// latest folded epoch at or before epoch, or zero when no fee was folded by then.
//
// Parameters:
// - epoch: accrual epoch whose latest post-fold value is requested.
//
// Returns:
// - *u256.Uint: accumulated fee per stake in Q128 fixed-point form, or zero
// when no fee was folded by epoch.
func (a *ProtocolFeeTokenAccumulator) GetAccumulatedX128PerStakeAt(epoch int64) *u256.Uint {
if epoch < 0 {
return u256.Zero()
}
accumulated := u256.Zero()
a.history.ReverseIterate(0, epoch, func(_ int64, value any) bool {
stored, castOk := value.(*u256.Uint)
if !castOk {
panic(ufmt.Sprintf("failed to cast accumulated value: %T", value))
}
accumulated = stored
return true
})
return accumulated
}
// GetFirstEpoch returns the first epoch for which a fee was folded.
//
// Returns:
// - int64: first folded epoch, or -1 when no fee has been folded.
func (a *ProtocolFeeTokenAccumulator) GetFirstEpoch() int64 {
return a.firstEpoch
}
// GetFoldedEpoch returns the last epoch known to be fully folded.
//
// Returns:
// - int64: last fully folded epoch, or -1 when no epoch is fully folded.
func (a *ProtocolFeeTokenAccumulator) GetFoldedEpoch() int64 {
return a.foldedEpoch
}
// GetProtocolFeeAmount returns the total protocol fee amount folded into the
// accumulator.
//
// Returns:
// - int64: total fee amount folded for this token.
func (a *ProtocolFeeTokenAccumulator) GetProtocolFeeAmount() int64 {
return a.protocolFeeAmount
}
/* Setters */
// SetAccumulatedX128PerStakeAt stores value as the accumulated amount after epoch's
// fees and makes it the latest value.
//
// Parameters:
// - epoch: epoch whose post-fold accumulator value is being stored.
// - value: accumulated fee-per-stake value in Q128 fixed-point form.
func (a *ProtocolFeeTokenAccumulator) SetAccumulatedX128PerStakeAt(epoch int64, value *u256.Uint) {
stored := u256.Zero().Set(value)
a.accumulatedX128PerStake = stored
a.history.Set(epoch, stored)
if a.firstEpoch < 0 || epoch < a.firstEpoch {
a.firstEpoch = epoch
}
}
// SetFoldedEpoch records the last epoch whose protocol fees are fully folded.
//
// Parameters:
// - epoch: latest fully folded accrual epoch.
func (a *ProtocolFeeTokenAccumulator) SetFoldedEpoch(epoch int64) {
a.foldedEpoch = epoch
}
// SetProtocolFeeAmount records the total protocol fee amount folded so far.
//
// Parameters:
// - amount: total folded protocol fee amount for this token.
func (a *ProtocolFeeTokenAccumulator) SetProtocolFeeAmount(amount int64) {
a.protocolFeeAmount = amount
}
proxy.gno
package staker
// Delegation operations
// Delegate delegates GNS to a delegate.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - to: delegatee address that receives voting power
// - amount: positive GNS amount to delegate and convert to xGNS voting power
// - referrer: optional referral identifier to register for reward tracking
//
// Returns:
// - delegatedAmount: The amount of GNS delegated and mirrored as xGNS.
//
// Halt check: reverts while the GovStaker halt scope is active.
func Delegate(cur realm, to address, amount int64, referrer string) int64 {
return getImplementation().Delegate(0, cur, to, amount, referrer)
}
// Undelegate undelegates xGNS from the existing delegate.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - from: delegatee address from which the caller removes delegation
// - amount: positive xGNS amount to move into undelegation lockup
//
// Returns:
// - amount: The amount of GNS moved into undelegation lockup.
//
// Halt check: reverts while the Withdraw halt scope is active.
func Undelegate(cur realm, from address, amount int64) int64 {
return getImplementation().Undelegate(0, cur, from, amount)
}
// Redelegate redelegates xGNS from the existing delegate to another.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - delegatee: current delegatee address whose voting power is reduced
// - newDelegatee: destination address that receives the redelegated voting power
// - amount: positive xGNS amount to move without a user-facing lockup
//
// Returns:
// - redelegatedAmount: The amount moved from the current delegatee to the new delegatee.
//
// Halt check: reverts while the GovStaker halt scope is active.
func Redelegate(cur realm, delegatee, newDelegatee address, amount int64) int64 {
return getImplementation().Redelegate(0, cur, delegatee, newDelegatee, amount)
}
// CollectUndelegatedGns collects the amount of the undelegated GNS.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//
// Returns:
// - amount: GNS amount released to the caller after eligible undelegation withdrawals are collected
//
// Halt check: reverts while the Withdraw halt scope is active.
func CollectUndelegatedGns(cur realm) int64 {
return getImplementation().CollectUndelegatedGns(0, cur)
}
// Reward operations
// CollectReward claims the caller's GNS emission reward and all known
// protocol-fee token rewards.
//
// The all-token path folds and settles every known token. It is not a
// single-current-xGNS-balance formula.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//
// Halt check: reverts while the Withdraw halt scope is active.
func CollectReward(cur realm) {
getImplementation().CollectReward(0, cur)
}
// CollectEmissionReward claims the caller's accumulated GNS emission reward.
//
// The call is subject to the withdrawal halt and transfers GNS when a reward
// is available.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
//
// Halt check: reverts while the Withdraw halt scope is active.
func CollectEmissionReward(cur realm) {
getImplementation().CollectEmissionReward(0, cur)
}
// CollectProtocolFeeReward claims accumulated protocol-fee rewards for one
// registered token path. Folding and settlement are bounded per call; any
// remaining buckets or stake events are collected by a later call.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - tokenPath: registered token path whose accumulated protocol-fee reward is claimed
//
// Halt check: reverts while the Withdraw halt scope is active.
func CollectProtocolFeeReward(cur realm, tokenPath string) {
getImplementation().CollectProtocolFeeReward(0, cur, tokenPath)
}
// CollectRewardFromLaunchPad claims both GNS emission and protocol-fee rewards
// for a registered launchpad project wallet. Only the launchpad contract may
// call this entry point.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - to: registered launchpad project wallet that receives both reward streams
//
// Halt check: reverts while the Withdraw halt scope is active.
func CollectRewardFromLaunchPad(cur realm, to address) {
getImplementation().CollectRewardFromLaunchPad(0, cur, to)
}
// CollectEmissionRewardFromLaunchPad claims only accumulated GNS emission
// rewards for a registered launchpad project wallet.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - to: registered launchpad project wallet whose emission reward is claimed
//
// Halt check: reverts while the Withdraw halt scope is active.
func CollectEmissionRewardFromLaunchPad(cur realm, to address) {
getImplementation().CollectEmissionRewardFromLaunchPad(0, cur, to)
}
// CollectProtocolFeeRewardFromLaunchPad claims one token path of accumulated
// protocol-fee rewards for a registered launchpad project wallet.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - to: registered launchpad project wallet whose protocol-fee reward is claimed
// - tokenPath: registered token path whose accumulated protocol-fee reward is claimed
//
// Halt check: reverts while the Withdraw halt scope is active.
func CollectProtocolFeeRewardFromLaunchPad(cur realm, to address, tokenPath string) {
getImplementation().CollectProtocolFeeRewardFromLaunchPad(0, cur, to, tokenPath)
}
// SetAmountByProjectWallet adjusts launchpad-backed stake and xGNS accounting for a project wallet.
// Only callable by launchpad contract.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - addr: registered project wallet whose launchpad-backed stake is adjusted
// - amount: stake amount delta passed to the launchpad reward accounting
// - add: true to add stake and mint xGNS; false to remove stake and burn xGNS
//
// Halt check: reverts while the GovStaker halt scope is active when add is true, or while the Withdraw halt scope is active when add is false.
func SetAmountByProjectWallet(cur realm, addr address, amount int64, add bool) {
getImplementation().SetAmountByProjectWallet(0, cur, addr, amount, add)
}
// Admin functions
// CleanStakerDelegationSnapshotByAdmin removes old delegation snapshots for the
// total history and the user history of a single target address.
// Only callable by admin.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - threshold: Unix timestamp cutoff for removing eligible old delegation history
// - target: user address whose delegation history to clean
//
// Halt check: reverts while the GovStaker halt scope is active.
func CleanStakerDelegationSnapshotByAdmin(cur realm, threshold int64, target address) {
getImplementation().CleanStakerDelegationSnapshotByAdmin(0, cur, threshold, target)
}
// SetUnDelegationLockupPeriodByAdmin sets the undelegation lockup period.
// Only callable by admin.
//
// Parameters:
// - cur: Current realm context; callers use cross(cur) when crossing into this realm.
// - period: non-negative undelegation lockup duration in seconds
//
// Halt check: reverts while the GovStaker halt scope is active.
func SetUnDelegationLockupPeriodByAdmin(cur realm, period int64) {
getImplementation().SetUnDelegationLockupPeriodByAdmin(0, cur, period)
}
render.gno
package staker
// Render delegates web rendering to the active implementation.
func Render(path string) string {
return getImplementation().Render(path)
}
state.gno
package staker
import (
"errors"
_ "gno.land/r/gnoswap/rbac/v1" // initialize readable contract role(s)
"gno.land/p/gnoswap/store/v1"
"gno.land/p/gnoswap/version_manager/v1"
)
var (
// Package-init reads use chain/runtime/unsafe.CurrentRealm because there
// is no `cur realm` in scope at package-initialization time. The values
// captured here describe the gov/staker realm itself, not any caller.
currentAddress address
domainPath = "gno.land/r/gnoswap/gov/staker"
kvStore store.KVStore
versionManager version_manager.VersionManager
implementation IGovStaker
)
func init(cur realm) {
currentAddress = cur.Address()
// Initialize KVStore
kvStore = store.NewKVStore(currentAddress)
// Create VersionManager
versionManager = version_manager.NewVersionManager(domainPath, kvStore, initializeDomainStore)
implementation = nil
}
func initializeDomainStore(_ int, rlm realm, kvStore store.KVStore) any {
return NewGovStakerStore(kvStore)
}
// getImplementation returns the current active implementation
func getImplementation() IGovStaker {
if implementation == nil {
panic("implementation is not initialized")
}
return implementation
}
func updateImplementation() error {
result := versionManager.GetCurrentImplementation()
if result == nil {
return errors.New("implementation is not initialized")
}
impl, ok := result.(IGovStaker)
if !ok {
return errors.New("impl is not an IGovStaker")
}
implementation = impl
return nil
}
store.gno
package staker
import (
"errors"
"gno.land/p/gnoswap/store/v1"
"gno.land/p/gnoswap/utils/v1"
bptree "gno.land/p/nt/bptree/v0"
ufmt "gno.land/p/nt/ufmt/v0"
)
// Storage key constants
const (
// Basic configuration
StoreKeyUnDelegationLockupPeriod = "unDelegationLockupPeriod"
StoreKeyTotalDelegatedAmount = "totalDelegatedAmount"
StoreKeyTotalLockedAmount = "totalLockedAmount"
// Counters
StoreKeyDelegationNextID = "delegationNextID"
// Complex data structures
StoreKeyDelegations = "delegations" // BPTree of delegations
StoreKeyTotalDelegationHistory = "totalDelegationHistory" // UintTree: timestamp -> int64 (cumulative total)
StoreKeyUserDelegationHistory = "userDelegationHistory" // BPTree: address -> *UintTree[timestamp -> int64]
// Manager states
StoreKeyEmissionRewardManager = "emissionRewardManager"
StoreKeyProtocolFeeRewardManager = "protocolFeeRewardManager"
StoreKeyDelegationManager = "delegationManager"
StoreKeyLaunchpadProjectDeposits = "launchpadProjectDeposits"
)
// govStakerStore is the concrete implementation of IGovStakerStore
type govStakerStore struct {
kvStore store.KVStore
}
var _ IGovStakerStore = (*govStakerStore)(nil)
// NewGovStakerStore creates a new governance staker store instance backed by kvStore.
//
// Parameters:
// - kvStore: Key-value store used to persist governance staker state.
//
// Returns:
// - IGovStakerStore: store implementation that reads and writes the supplied KV store.
func NewGovStakerStore(kvStore store.KVStore) IGovStakerStore {
return &govStakerStore{
kvStore: kvStore,
}
}
// Basic configuration methods
// Returns:
// - bool: true when the undelegation lockup-period key is present in storage.
func (s *govStakerStore) HasUnDelegationLockupPeriodStoreKey() bool {
return s.kvStore.Has(StoreKeyUnDelegationLockupPeriod)
}
// GetUnDelegationLockupPeriod returns the configured undelegation lockup period in seconds.
//
// Returns:
// - int64: lockup duration in seconds; panics if the stored value is unavailable or not int64.
func (s *govStakerStore) GetUnDelegationLockupPeriod() int64 {
result, err := s.kvStore.Get(StoreKeyUnDelegationLockupPeriod)
if err != nil {
panic(err)
}
period, ok := result.(int64)
if !ok {
panic(ufmt.Sprintf("failed to cast result to int64: %T", result))
}
return period
}
// SetUnDelegationLockupPeriod stores the undelegation lockup period.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - period: Undelegation lockup duration in seconds.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetUnDelegationLockupPeriod(_ int, rlm realm, period int64) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyUnDelegationLockupPeriod, period)
}
// Returns:
// - bool: true when the total delegated-amount key is present in storage.
func (s *govStakerStore) HasTotalDelegatedAmountStoreKey() bool {
return s.kvStore.Has(StoreKeyTotalDelegatedAmount)
}
// GetTotalDelegatedAmount returns the total amount currently delegated.
//
// Returns:
// - int64: aggregate delegated amount; panics if the stored value is unavailable or not int64.
func (s *govStakerStore) GetTotalDelegatedAmount() int64 {
result, err := s.kvStore.Get(StoreKeyTotalDelegatedAmount)
if err != nil {
panic(err)
}
amount, ok := result.(int64)
if !ok {
panic(ufmt.Sprintf("failed to cast result to int64: %T", result))
}
return amount
}
// SetTotalDelegatedAmount stores the aggregate delegated amount.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - amount: Aggregate amount of GNS delegated across all delegators.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetTotalDelegatedAmount(_ int, rlm realm, amount int64) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyTotalDelegatedAmount, amount)
}
// Returns:
// - bool: true when the total locked-amount key is present in storage.
func (s *govStakerStore) HasTotalLockedAmountStoreKey() bool {
return s.kvStore.Has(StoreKeyTotalLockedAmount)
}
// GetTotalLockedAmount returns the total amount locked in undelegation withdrawals.
//
// Returns:
// - int64: aggregate locked amount; panics if the stored value is unavailable or not int64.
func (s *govStakerStore) GetTotalLockedAmount() int64 {
result, err := s.kvStore.Get(StoreKeyTotalLockedAmount)
if err != nil {
panic(err)
}
amount, ok := result.(int64)
if !ok {
panic(ufmt.Sprintf("failed to cast result to int64: %T", result))
}
return amount
}
// SetTotalLockedAmount stores the aggregate amount locked in undelegation.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - amount: Aggregate GNS amount currently locked in undelegation withdrawals.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetTotalLockedAmount(_ int, rlm realm, amount int64) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyTotalLockedAmount, amount)
}
// Delegation management methods
// Returns:
// - bool: true when the delegations tree key is present in storage.
func (s *govStakerStore) HasDelegationsStoreKey() bool {
return s.kvStore.Has(StoreKeyDelegations)
}
// SetDelegations replaces the persisted delegation tree.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - delegations: BPTree containing delegation records keyed by decimal delegation ID.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetDelegations(_ int, rlm realm, delegations *bptree.BPTree) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyDelegations, delegations)
}
// HasDelegation reports whether a delegation with id exists.
//
// Parameters:
// - id: Numeric delegation identifier converted to the tree's decimal-string key.
//
// Returns:
// - bool: true when a delegation record exists for id, false when the key is absent.
func (s *govStakerStore) HasDelegation(id int64) bool {
delegations := s.GetAllDelegations()
return delegations.Get(utils.Int64ToString(id)) != nil
}
// GetDelegation retrieves a delegation by id.
//
// Parameters:
// - id: Numeric delegation identifier converted to the tree's decimal-string key.
//
// Returns:
// - *Delegation: stored delegation, or nil when no record exists for id.
// - bool: true when a delegation was found; false when id is absent.
func (s *govStakerStore) GetDelegation(id int64) (*Delegation, bool) {
delegations := s.GetAllDelegations()
result := delegations.Get(utils.Int64ToString(id))
if result == nil {
return nil, false
}
delegation, ok := result.(*Delegation)
if !ok {
panic(ufmt.Sprintf("failed to cast result to *Delegation: %T", result))
}
return delegation, true
}
// SetDelegation stores one delegation under id.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - id: Numeric identifier used as the delegation's decimal-string tree key.
// - delegation: Delegation record to store for id.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetDelegation(_ int, rlm realm, id int64, delegation *Delegation) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
delegations := s.GetAllDelegations()
delegations.Set(utils.Int64ToString(id), delegation)
return s.kvStore.Set(0, rlm, StoreKeyDelegations, delegations)
}
// RemoveDelegation deletes the delegation stored under id.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - id: Numeric delegation identifier whose decimal-string tree entry is removed.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) RemoveDelegation(_ int, rlm realm, id int64) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
delegations := s.GetAllDelegations()
delegations.Remove(utils.Int64ToString(id))
return s.kvStore.Set(0, rlm, StoreKeyDelegations, delegations)
}
// GetAllDelegations returns the persisted tree of delegation records keyed by decimal ID.
//
// Returns:
// - *bptree.BPTree: delegation tree; panics if storage is unavailable or contains a different type.
func (s *govStakerStore) GetAllDelegations() *bptree.BPTree {
result, err := s.kvStore.Get(StoreKeyDelegations)
if err != nil {
panic(err)
}
delegations, ok := result.(*bptree.BPTree)
if !ok {
panic(ufmt.Sprintf("failed to cast result to *bptree.BPTree: %T", result))
}
return delegations
}
// Returns:
// - bool: true when the next-delegation-ID counter key is present in storage.
func (s *govStakerStore) HasDelegationCounterStoreKey() bool {
return s.kvStore.Has(StoreKeyDelegationNextID)
}
// GetDelegationCounter returns the counter used to allocate delegation IDs.
//
// Returns:
// - *Counter: persisted next-ID counter; panics if storage is unavailable or contains a different type.
func (s *govStakerStore) GetDelegationCounter() *Counter {
result, err := s.kvStore.Get(StoreKeyDelegationNextID)
if err != nil {
panic(err)
}
counter, ok := result.(*Counter)
if !ok {
panic(ufmt.Sprintf("failed to cast result to Counter: %T", result))
}
return counter
}
// SetDelegationCounter stores the counter used to allocate delegation IDs.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - counter: Counter holding the next delegation ID.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetDelegationCounter(_ int, rlm realm, counter *Counter) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyDelegationNextID, counter)
}
// Total delegation history methods (timestamp -> int64)
// Returns:
// - bool: true when the total delegation-history key is present in storage.
func (s *govStakerStore) HasTotalDelegationHistoryStoreKey() bool {
return s.kvStore.Has(StoreKeyTotalDelegationHistory)
}
// GetTotalDelegationHistory returns timestamp-indexed aggregate delegation history.
//
// Returns:
// - *UintTree: history mapping Unix timestamps to cumulative delegated amounts; panics on missing or invalid storage.
func (s *govStakerStore) GetTotalDelegationHistory() *UintTree {
result, err := s.kvStore.Get(StoreKeyTotalDelegationHistory)
if err != nil {
panic(err)
}
history, ok := result.(*UintTree)
if !ok {
panic(ufmt.Sprintf("failed to cast result to *UintTree: %T", result))
}
return history
}
// SetTotalDelegationHistory stores timestamp-indexed aggregate delegation history.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - history: UintTree mapping timestamps to cumulative total delegated amounts.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetTotalDelegationHistory(_ int, rlm realm, history *UintTree) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyTotalDelegationHistory, history)
}
// User delegation history methods (address -> *UintTree[timestamp -> int64])
// Returns:
// - bool: true when the per-user delegation-history key is present in storage.
func (s *govStakerStore) HasUserDelegationHistoryStoreKey() bool {
return s.kvStore.Has(StoreKeyUserDelegationHistory)
}
// GetUserDelegationHistory returns the address-indexed delegation-history tree.
//
// Returns:
// - *bptree.BPTree: tree mapping delegator addresses to timestamp histories; panics on missing or invalid storage.
func (s *govStakerStore) GetUserDelegationHistory() *bptree.BPTree {
result, err := s.kvStore.Get(StoreKeyUserDelegationHistory)
if err != nil {
panic(err)
}
history, ok := result.(*bptree.BPTree)
if !ok {
panic(ufmt.Sprintf("failed to cast result to *bptree.BPTree: %T", result))
}
return history
}
// SetUserDelegationHistory stores the address-indexed delegation-history tree.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - history: BPTree mapping delegator addresses to their timestamp-indexed histories.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetUserDelegationHistory(_ int, rlm realm, history *bptree.BPTree) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyUserDelegationHistory, history)
}
// Returns:
// - bool: true when the emission-reward-manager key is present in storage.
func (s *govStakerStore) HasEmissionRewardManagerStoreKey() bool {
return s.kvStore.Has(StoreKeyEmissionRewardManager)
}
// GetEmissionRewardManager returns the persisted emission reward manager.
//
// Returns:
// - *EmissionRewardManager: emission reward accounting state; panics on missing or invalid storage.
func (s *govStakerStore) GetEmissionRewardManager() *EmissionRewardManager {
result, err := s.kvStore.Get(StoreKeyEmissionRewardManager)
if err != nil {
panic(err)
}
manager, ok := result.(*EmissionRewardManager)
if !ok {
panic(ufmt.Sprintf("failed to cast result to *EmissionRewardManager: %T", result))
}
return manager
}
// SetEmissionRewardManager stores the emission reward manager.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - manager: Emission reward accounting state to persist.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetEmissionRewardManager(_ int, rlm realm, manager *EmissionRewardManager) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyEmissionRewardManager, manager)
}
// Returns:
// - bool: true when the protocol-fee reward-manager key is present in storage.
func (s *govStakerStore) HasProtocolFeeRewardManagerStoreKey() bool {
return s.kvStore.Has(StoreKeyProtocolFeeRewardManager)
}
// GetProtocolFeeRewardManager returns the persisted protocol-fee reward manager.
//
// Returns:
// - *ProtocolFeeRewardManager: protocol-fee reward accounting state; panics on missing or invalid storage.
func (s *govStakerStore) GetProtocolFeeRewardManager() *ProtocolFeeRewardManager {
result, err := s.kvStore.Get(StoreKeyProtocolFeeRewardManager)
if err != nil {
panic(err)
}
manager, ok := result.(*ProtocolFeeRewardManager)
if !ok {
panic(ufmt.Sprintf("failed to cast result to *ProtocolFeeRewardManager: %T", result))
}
return manager
}
// SetProtocolFeeRewardManager stores the protocol-fee reward manager.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - manager: Protocol-fee reward accounting state to persist.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetProtocolFeeRewardManager(_ int, rlm realm, manager *ProtocolFeeRewardManager) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyProtocolFeeRewardManager, manager)
}
// Returns:
// - bool: true when the delegation-manager key is present in storage.
func (s *govStakerStore) HasDelegationManagerStoreKey() bool {
return s.kvStore.Has(StoreKeyDelegationManager)
}
// GetDelegationManager returns the persisted delegation manager.
//
// Returns:
// - *DelegationManager: delegation-management state; panics on missing or invalid storage.
func (s *govStakerStore) GetDelegationManager() *DelegationManager {
result, err := s.kvStore.Get(StoreKeyDelegationManager)
if err != nil {
panic(err)
}
manager, ok := result.(*DelegationManager)
if !ok {
panic(ufmt.Sprintf("failed to cast result to *DelegationManager: %T", result))
}
return manager
}
// SetDelegationManager stores the delegation manager.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - manager: Delegation-management state to persist.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetDelegationManager(_ int, rlm realm, manager *DelegationManager) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyDelegationManager, manager)
}
// Returns:
// - bool: true when the launchpad-project-deposits key is present in storage.
func (s *govStakerStore) HasLaunchpadProjectDepositsStoreKey() bool {
return s.kvStore.Has(StoreKeyLaunchpadProjectDeposits)
}
// GetLaunchpadProjectDeposits returns persisted launchpad project deposit state.
//
// Returns:
// - *LaunchpadProjectDeposits: launchpad deposit accounting state; panics on missing or invalid storage.
func (s *govStakerStore) GetLaunchpadProjectDeposits() *LaunchpadProjectDeposits {
result, err := s.kvStore.Get(StoreKeyLaunchpadProjectDeposits)
if err != nil {
panic(err)
}
deposits, ok := result.(*LaunchpadProjectDeposits)
if !ok {
panic(ufmt.Sprintf("failed to cast result to *LaunchpadProjectDeposits: %T", result))
}
return deposits
}
// SetLaunchpadProjectDeposits stores launchpad project deposit state.
//
// Parameters:
// - _: Internal call discriminator; pass 0.
// - rlm: Propagated realm context; the write is accepted only when this realm is current.
// - deposits: Launchpad project deposit accounting state to persist.
//
// Returns:
// - error: nil on success; ErrSpoofedRealm when rlm is not current, or the underlying KV-store error.
func (s *govStakerStore) SetLaunchpadProjectDeposits(_ int, rlm realm, deposits *LaunchpadProjectDeposits) error {
if !rlm.IsCurrent() {
return errors.New(ErrSpoofedRealm)
}
return s.kvStore.Set(0, rlm, StoreKeyLaunchpadProjectDeposits, deposits)
}
tree.gno
package staker
import (
"gno.land/p/gnoswap/gnsmath/v1"
"gno.land/p/gnoswap/utils/v1"
bptree "gno.land/p/nt/bptree/v0"
ufmt "gno.land/p/nt/ufmt/v0"
)
// UintTree is a wrapper around a BPTree for storing non-negative int64 keys as
// ordered strings. Depending on the caller, keys represent Unix timestamps,
// accrual epochs, or stake-event indexes.
//
// Since keys are int64 values, they are converted to uint64-compatible strings.
//
// Methods:
// - Get: Retrieves a value associated with a non-negative int64 key.
// - set: Stores a value with a non-negative int64 key.
// - Has: Checks if a non-negative int64 key exists in the tree.
// - remove: Removes a non-negative 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.
type UintTree struct {
tree *bptree.BPTree // non-negative int64 key -> any
}
// NewUintTree creates a new UintTree instance.
//
// Returns:
// - *UintTree: new tree backed by an empty ordered BPTree
func NewUintTree() *UintTree {
return &UintTree{
tree: bptree.NewBPTreeN(64),
}
}
// Get looks up a value by its non-negative int64 key.
//
// Parameters:
// - key: non-negative int64 key encoded for the ordered tree lookup; a negative key panics
//
// Returns:
// - any: value stored at key, or nil when no entry exists
// - bool: true when key has an entry; false when absent
func (self *UintTree) Get(key int64) (any, bool) {
v := self.tree.Get(encodeInt64(key))
if v == nil {
return nil, false
}
return v, true
}
// Set associates a value with a non-negative int64 key, replacing any existing
// value at that key.
//
// Parameters:
// - key: non-negative int64 key to encode and store; a negative key panics
// - value: value to associate with key
func (self *UintTree) Set(key int64, value any) {
self.tree.Set(encodeInt64(key), value)
}
// Has checks whether a non-negative int64 key is present in the tree.
//
// Parameters:
// - key: non-negative int64 key to encode and test; a negative key panics
//
// Returns:
// - bool: true when key is present; false when no entry is stored at key
func (self *UintTree) Has(key int64) bool {
return self.tree.Has(encodeInt64(key))
}
// Remove deletes the entry associated with a non-negative int64 key, if one
// exists.
//
// Parameters:
// - key: non-negative int64 key to encode and remove; a negative key panics
func (self *UintTree) Remove(key int64) {
self.tree.Remove(encodeInt64(key))
}
// Iterate visits entries in the half-open [start, end) key range in ascending
// order.
//
// Parameters:
// - start: non-negative lower-bound key for the iteration range; a negative bound panics
// - end: non-negative upper-bound key for the iteration range; a negative bound panics
// - fn: callback receiving each decoded key and value; return true to stop iteration, or false to continue
func (self *UintTree) Iterate(start, end int64, fn func(key int64, value any) bool) {
self.tree.Iterate(encodeInt64(start), encodeInt64(end), func(key string, value any) bool {
return fn(decodeInt64(key), value)
})
}
// ReverseIterate visits entries in descending order over the half-open
// [start, end) key range.
//
// Parameters:
// - start: non-negative lower-bound key for the iteration range; a negative bound panics
// - end: non-negative upper-bound key for the iteration range; a negative bound panics
// - fn: callback receiving each decoded key and value; return true to stop iteration, or false to continue
func (self *UintTree) ReverseIterate(start, end int64, fn func(key int64, value any) bool) {
self.tree.ReverseIterate(encodeInt64(start), encodeInt64(end), func(key string, value any) bool {
return fn(decodeInt64(key), value)
})
}
// Size returns the number of entries in the tree.
//
// Returns:
// - int: number of key-value entries currently stored in the tree
func (self *UintTree) Size() int {
return self.tree.Size()
}
func encodeInt64(num int64) string {
if num < 0 {
panic(ufmt.Sprintf("negative value not supported: %d", num))
}
return utils.EncodeUint64(uint64(num))
}
func decodeInt64(s string) int64 {
return gnsmath.SafeUint64ToInt64(utils.DecodeUint64(s))
}
types.gno
package staker
import (
"gno.land/p/gnoswap/uint256/v1"
rotree "gno.land/p/nt/bptree/rotree/v0"
bptree "gno.land/p/nt/bptree/v0"
)
// Main interface that combines all sub-interfaces
type IGovStaker interface {
IGovStakerDelegation
IGovStakerReward
IGovStakerGetter
IGovStakerAdmin
Render(path string) string
}
// Delegation operations interface
//
// Mutating methods take `_ int, rlm realm` so the realm token is threaded
// from the proxy entry points down to the cross-realm token transfers and
// store writes performed inside each implementation. The `_ int` sentinel
// surfaces at every call site as a literal `0`, making the realm threading
// visible to readers.
type IGovStakerDelegation interface {
// Main delegation operations
// Delegate moves GNS into delegation and assigns the corresponding xGNS voting power.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before token transfers and state updates
// - to: address that receives the delegated voting power
// - amount: positive GNS amount to delegate
// - referrer: optional referral identifier associated with the delegation
//
// Returns:
// - int64: amount delegated and represented as xGNS
Delegate(_ int, rlm realm, to address, amount int64, referrer string) int64
// Undelegate removes voting power from an existing delegatee and starts the
// undelegation lockup for the returned GNS.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before token and state updates
// - from: delegatee address from which the caller removes delegation
// - amount: positive xGNS amount to undelegate
//
// Returns:
// - int64: amount moved from active delegation into undelegation lockup
Undelegate(_ int, rlm realm, from address, amount int64) int64
// Redelegate moves voting power from one delegatee to another without a
// user-facing undelegation lockup.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before token and state updates
// - delegatee: current delegatee address whose delegation is reduced
// - newDelegatee: destination address that receives the redelegated amount
// - amount: positive xGNS amount to move between delegatees
//
// Returns:
// - int64: amount moved from the current delegatee to the new delegatee
Redelegate(_ int, rlm realm, delegatee, newDelegatee address, amount int64) int64
// CollectUndelegatedGns releases GNS whose undelegation lockup has expired.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before token and state updates
//
// Returns:
// - int64: amount of unlocked GNS collected by the caller
CollectUndelegatedGns(_ int, rlm realm) int64
}
// Reward management interface
type IGovStakerReward interface {
// Reward collection
// CollectReward settles the caller's GNS emission and all known protocol-fee
// token rewards.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before reward transfers and state updates
CollectReward(_ int, rlm realm)
// CollectEmissionReward settles only the caller's accumulated GNS emission reward.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before reward transfer and state updates
CollectEmissionReward(_ int, rlm realm)
// CollectProtocolFeeReward settles one registered protocol-fee token reward
// for the caller.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before reward transfer and state updates
// - tokenPath: registered token path whose accumulated reward is settled
CollectProtocolFeeReward(_ int, rlm realm, tokenPath string)
// CollectRewardFromLaunchPad settles both reward streams for a registered
// launchpad project wallet.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before launchpad authorization and reward transfers
// - to: registered launchpad project wallet that receives the rewards
CollectRewardFromLaunchPad(_ int, rlm realm, to address)
// CollectEmissionRewardFromLaunchPad settles only the emission reward for a
// registered launchpad project wallet.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before launchpad authorization and reward transfer
// - to: registered launchpad project wallet that receives the emission reward
CollectEmissionRewardFromLaunchPad(_ int, rlm realm, to address)
// CollectProtocolFeeRewardFromLaunchPad settles one protocol-fee token reward
// for a registered launchpad project wallet.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before launchpad authorization and reward transfer
// - to: registered launchpad project wallet that receives the token reward
// - tokenPath: registered token path whose accumulated reward is settled
CollectProtocolFeeRewardFromLaunchPad(_ int, rlm realm, to address, tokenPath string)
// SetAmountByProjectWallet adjusts the launchpad-backed stake amount and
// corresponding xGNS balance for a project wallet.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before launchpad authorization and state updates
// - addr: project wallet address whose launchpad-backed stake is adjusted
// - amount: stake amount delta passed to the launchpad reward accounting
// - add: true to add stake and mint xGNS; false to remove stake and burn xGNS
SetAmountByProjectWallet(_ int, rlm realm, addr address, amount int64, add bool)
}
// Getter interface for read operations
type IGovStakerGetter interface {
// Store data getters
// GetUnDelegationLockupPeriod returns the configured undelegation cooldown.
//
// Returns:
// - int64: undelegation lockup duration in seconds
GetUnDelegationLockupPeriod() int64
// Delegation getters
// GetTotalxGnsSupply returns total xGNS supply, including xGNS held by the
// launchpad.
//
// Returns:
// - int64: total xGNS supply used as the governance quorum base
GetTotalxGnsSupply() int64
// GetTotalDelegated returns the amount currently delegated for governance
// voting power.
//
// Returns:
// - int64: total active delegated xGNS amount
GetTotalDelegated() int64
// GetTotalLockedAmount returns GNS held by the staker contract for active
// delegations and not-yet-collected undelegations.
//
// Returns:
// - int64: total locked GNS amount
GetTotalLockedAmount() int64
// GetDelegations returns a read-only tree of all delegations keyed by their
// decimal-string IDs.
//
// Returns:
// - *rotree.ReadOnlyTree: read-only delegation index whose entries are cloned for callers
GetDelegations() *rotree.ReadOnlyTree
// ExistsDelegation checks whether a delegation record exists.
//
// Parameters:
// - delegationID: unique delegation identifier to look up
//
// Returns:
// - bool: true when delegationID has a stored record; false otherwise
ExistsDelegation(delegationID int64) bool
// GetDelegatorDelegations returns a read-only tree for one delegator, keyed
// by delegatee address.
//
// Parameters:
// - delegator: address whose delegatee mappings are requested
//
// Returns:
// - *rotree.ReadOnlyTree: delegatee-to-delegation-ID tree, or nil when the delegator has no delegations
GetDelegatorDelegations(delegator address) *rotree.ReadOnlyTree
// GetUserDelegationIDs returns delegation IDs for one delegator-delegatee
// pair.
//
// Parameters:
// - delegator: address that owns the delegation
// - delegatee: address receiving the delegation
//
// Returns:
// - []int64: stored delegation IDs for the pair, or an empty list when none exist
GetUserDelegationIDs(delegator address, delegatee address) []int64
// HasDelegationSnapshotsKey reports whether total delegation history has
// been initialized in storage.
//
// Returns:
// - bool: true when the total delegation history store key exists; false otherwise
HasDelegationSnapshotsKey() bool
// GetTotalDelegationAmountAtSnapshot finds the latest total delegation
// history value at or before a Unix timestamp.
//
// Parameters:
// - snapshotTime: Unix timestamp at which to resolve historical total delegation
//
// Returns:
// - int64: total delegated amount from the latest qualifying history entry
// - bool: true when a qualifying history entry exists; false when history has no such entry
GetTotalDelegationAmountAtSnapshot(snapshotTime int64) (int64, bool)
// GetUserDelegationAmountAtSnapshot finds one user's latest delegation
// history value at or before a Unix timestamp.
//
// Parameters:
// - userAddr: user's address whose delegation history is searched
// - snapshotTime: Unix timestamp at which to resolve the user's historical delegation
//
// Returns:
// - int64: user's delegated amount from the latest qualifying history entry
// - bool: true when a qualifying history entry exists; false otherwise
GetUserDelegationAmountAtSnapshot(userAddr address, snapshotTime int64) (int64, bool)
// Reward getters
// GetClaimableRewardByAddress computes current claimable emission and
// protocol-fee rewards for an address reward ID.
//
// Parameters:
// - addr: staker address whose reward ID is queried
//
// Returns:
// - int64: claimable GNS emission reward amount
// - map[string]int64: claimable protocol-fee amounts keyed by token path
// - error: nil when both reward streams are computed; otherwise the reward-accounting error
GetClaimableRewardByAddress(addr address) (int64, map[string]int64, error)
// GetClaimableRewardByLaunchpad computes rewards for a launchpad project
// wallet's launchpad-specific reward ID.
//
// Parameters:
// - addr: registered launchpad project wallet address
//
// Returns:
// - int64: claimable GNS emission reward amount
// - map[string]int64: claimable protocol-fee amounts keyed by token path
// - error: nil when both reward streams are computed; otherwise the reward-accounting error
GetClaimableRewardByLaunchpad(addr address) (int64, map[string]int64, error)
// GetClaimableRewardByRewardID computes current rewards for an explicit
// reward identifier.
//
// Parameters:
// - rewardID: staker or launchpad reward-state identifier
//
// Returns:
// - int64: claimable GNS emission reward amount
// - map[string]int64: claimable protocol-fee amounts keyed by token path
// - error: nil when both reward streams are computed; otherwise the reward-accounting error
GetClaimableRewardByRewardID(rewardID string) (int64, map[string]int64, error)
// Launchpad getters
// GetLaunchpadProjectDeposit returns a project's recorded launchpad deposit.
//
// Parameters:
// - projectAddr: project address identifier used to derive the launchpad reward key
//
// Returns:
// - int64: stored project deposit amount
// - bool: true when a deposit record exists for projectAddr; false otherwise
GetLaunchpadProjectDeposit(projectAddr string) (int64, bool)
// Withdraw getters
// GetDelegationWithdrawCount returns the number of pending withdrawal
// records attached to a delegation.
//
// Parameters:
// - delegationID: delegation whose withdrawal list is counted
//
// Returns:
// - int: number of withdrawal records, or 0 when the delegation is absent
GetDelegationWithdrawCount(delegationID int64) int
// GetDelegationWithdraws returns a slice of a delegation's withdrawal list.
//
// Parameters:
// - delegationID: delegation whose withdrawals are requested
// - offset: non-negative zero-based starting index in the withdrawal list
// - count: non-negative maximum number of withdrawals to include
//
// Returns:
// - []DelegationWithdraw: withdrawals in the requested range, or an empty slice when the delegation or range is absent
// - error: nil when the lookup completes; an unknown delegation yields an empty slice
GetDelegationWithdraws(delegationID int64, offset, count int) ([]DelegationWithdraw, error)
// GetCollectableWithdrawAmount sums all withdrawal amounts currently
// collectable for a delegation.
//
// Parameters:
// - delegationID: delegation whose expired withdrawals are summed
//
// Returns:
// - int64: total GNS amount collectable now, or 0 when none is collectable
GetCollectableWithdrawAmount(delegationID int64) int64
// Protocol fee reward getters
// GetProtocolFeeAccumulatedX128PerStake returns the per-stake protocol-fee
// accumulator for a token path, scaled by 2^128.
//
// Parameters:
// - tokenPath: registered token path whose accumulator is queried
//
// Returns:
// - *uint256.Uint: Q128-scaled accumulated fee per stake, zero when the token has no folded fee
GetProtocolFeeAccumulatedX128PerStake(tokenPath string) *uint256.Uint
// GetProtocolFeeAmount returns the total protocol fee folded for a token
// path.
//
// Parameters:
// - tokenPath: registered token path whose folded fee amount is queried
//
// Returns:
// - int64: total folded protocol-fee amount, or 0 when the token has no accumulator
GetProtocolFeeAmount(tokenPath string) int64
// GetProtocolFeeAccumulatedTimestamp returns the last timestamp at which
// protocol-fee accrual state advanced.
//
// Returns:
// - int64: Unix timestamp of the latest protocol-fee accumulation update
GetProtocolFeeAccumulatedTimestamp() int64
// Emission reward getters
// GetEmissionAccumulatedX128PerStake returns the accumulated GNS emission
// reward per stake, scaled by 2^128.
//
// Returns:
// - *uint256.Uint: Q128-scaled accumulated emission per stake
GetEmissionAccumulatedX128PerStake() *uint256.Uint
// GetEmissionDistributedAmount returns the total GNS emission distributed
// through the staker reward manager.
//
// Returns:
// - int64: cumulative distributed GNS emission amount
GetEmissionDistributedAmount() int64
// GetEmissionAccumulatedTimestamp returns the last timestamp at which
// emission reward accrual state advanced.
//
// Returns:
// - int64: Unix timestamp of the latest emission accumulation update
GetEmissionAccumulatedTimestamp() int64
}
// Admin interface for administrative functions
type IGovStakerAdmin interface {
// CleanStakerDelegationSnapshotByAdmin removes delegation-history entries
// older than a validated timestamp cutoff.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before administrative state updates
// - snapshotTime: Unix timestamp cutoff before which eligible history entries are removed
// - target: address whose user delegation history is cleaned
CleanStakerDelegationSnapshotByAdmin(_ int, rlm realm, snapshotTime int64, target address)
// SetUnDelegationLockupPeriodByAdmin updates the duration used by future
// undelegation withdrawals.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded implementation call
// - rlm: propagated current realm context validated before the administrative store write
// - period: non-negative undelegation lockup duration in seconds
SetUnDelegationLockupPeriodByAdmin(_ int, rlm realm, period int64)
}
// IGovStakerStore mirrors the mutating-method realm-threading convention used
// by the public IGovStaker* interfaces above. Setters take `_ int, rlm realm`
// so KV-store writes execute under the proxy realm — the only address with
// write access to the shared store.
type IGovStakerStore interface {
// Basic configuration
// HasUnDelegationLockupPeriodStoreKey reports whether the lockup duration is initialized.
//
// Returns:
// - bool: true when the undelegation lockup period store key exists
HasUnDelegationLockupPeriodStoreKey() bool
// GetUnDelegationLockupPeriod returns the persisted undelegation lockup duration.
//
// Returns:
// - int64: configured lockup duration in seconds
GetUnDelegationLockupPeriod() int64
// SetUnDelegationLockupPeriod persists the undelegation lockup duration.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - period: lockup duration in seconds
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetUnDelegationLockupPeriod(_ int, rlm realm, period int64) error
// HasTotalDelegatedAmountStoreKey reports whether total active delegation is initialized.
//
// Returns:
// - bool: true when the total delegated amount store key exists
HasTotalDelegatedAmountStoreKey() bool
// GetTotalDelegatedAmount returns the persisted total active delegation amount.
//
// Returns:
// - int64: total delegated xGNS amount
GetTotalDelegatedAmount() int64
// SetTotalDelegatedAmount persists the total active delegation amount.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - amount: total active delegated xGNS amount to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetTotalDelegatedAmount(_ int, rlm realm, amount int64) error
// HasTotalLockedAmountStoreKey reports whether total locked GNS is initialized.
//
// Returns:
// - bool: true when the total locked amount store key exists
HasTotalLockedAmountStoreKey() bool
// GetTotalLockedAmount returns the persisted total GNS held by the staker.
//
// Returns:
// - int64: total locked GNS amount
GetTotalLockedAmount() int64
// SetTotalLockedAmount persists the total locked GNS amount.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - amount: total locked GNS amount to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetTotalLockedAmount(_ int, rlm realm, amount int64) error
// Delegation management
// HasDelegation reports whether a delegation record exists for an ID.
//
// Parameters:
// - id: delegation identifier to look up
//
// Returns:
// - bool: true when a delegation is stored under id; false otherwise
HasDelegation(id int64) bool
// GetDelegation retrieves one delegation record.
//
// Parameters:
// - id: delegation identifier to look up
//
// Returns:
// - *Delegation: stored delegation pointer, or nil when id is absent
// - bool: true when a delegation record exists and has the expected type; false otherwise
GetDelegation(id int64) (*Delegation, bool)
// SetDelegation stores a delegation under its identifier.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - id: delegation identifier used as the storage key
// - delegation: delegation record to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetDelegation(_ int, rlm realm, id int64, delegation *Delegation) error
// RemoveDelegation deletes a delegation record and its storage entry.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - id: delegation identifier to remove
//
// Returns:
// - error: nil when the store write succeeds; otherwise the KV-store error, including a spoofed realm context
RemoveDelegation(_ int, rlm realm, id int64) error
// HasDelegationsStoreKey reports whether the all-delegations tree is initialized.
//
// Returns:
// - bool: true when the delegations store key exists
HasDelegationsStoreKey() bool
// SetDelegations replaces the persisted all-delegations tree.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - delegations: BPTree containing delegation records keyed by delegation ID
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetDelegations(_ int, rlm realm, delegations *bptree.BPTree) error
// GetAllDelegations returns the persisted tree containing every delegation.
//
// Returns:
// - *bptree.BPTree: all-delegations tree keyed by decimal-string delegation ID
GetAllDelegations() *bptree.BPTree
// HasDelegationCounterStoreKey reports whether the next-delegation-ID counter is initialized.
//
// Returns:
// - bool: true when the delegation counter store key exists
HasDelegationCounterStoreKey() bool
// GetDelegationCounter returns the persisted counter used to allocate delegation IDs.
//
// Returns:
// - *Counter: mutable delegation-ID counter
GetDelegationCounter() *Counter
// SetDelegationCounter persists the delegation-ID counter.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - counter: delegation-ID counter to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetDelegationCounter(_ int, rlm realm, counter *Counter) error
// Total delegation history (timestamp -> int64)
// HasTotalDelegationHistoryStoreKey reports whether cumulative total delegation history is initialized.
//
// Returns:
// - bool: true when the total-delegation-history store key exists
HasTotalDelegationHistoryStoreKey() bool
// GetTotalDelegationHistory returns timestamp-keyed cumulative total delegation history.
//
// Returns:
// - *UintTree: total delegation history tree mapping Unix timestamps to int64 amounts
GetTotalDelegationHistory() *UintTree
// SetTotalDelegationHistory persists timestamp-keyed cumulative total delegation history.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - history: timestamp-to-total-delegation tree to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetTotalDelegationHistory(_ int, rlm realm, history *UintTree) error
// User delegation history (address -> *UintTree[timestamp -> int64])
// HasUserDelegationHistoryStoreKey reports whether per-user delegation history is initialized.
//
// Returns:
// - bool: true when the user-delegation-history store key exists
HasUserDelegationHistoryStoreKey() bool
// GetUserDelegationHistory returns the composite-keyed per-user delegation history tree.
//
// Returns:
// - *bptree.BPTree: history tree keyed by address and timestamp
GetUserDelegationHistory() *bptree.BPTree
// SetUserDelegationHistory persists the composite-keyed per-user delegation history tree.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - history: address-and-timestamp delegation history tree to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetUserDelegationHistory(_ int, rlm realm, history *bptree.BPTree) error
// Manager states
// HasEmissionRewardManagerStoreKey reports whether the emission reward manager is initialized.
//
// Returns:
// - bool: true when the emission reward manager store key exists
HasEmissionRewardManagerStoreKey() bool
// GetEmissionRewardManager returns the persisted emission reward manager.
//
// Returns:
// - *EmissionRewardManager: emission reward accounting manager
GetEmissionRewardManager() *EmissionRewardManager
// SetEmissionRewardManager persists the emission reward manager.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - manager: emission reward manager state to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetEmissionRewardManager(_ int, rlm realm, manager *EmissionRewardManager) error
// HasProtocolFeeRewardManagerStoreKey reports whether protocol-fee reward state is initialized.
//
// Returns:
// - bool: true when the protocol-fee reward manager store key exists
HasProtocolFeeRewardManagerStoreKey() bool
// GetProtocolFeeRewardManager returns the persisted protocol-fee reward manager.
//
// Returns:
// - *ProtocolFeeRewardManager: protocol-fee reward accounting manager
GetProtocolFeeRewardManager() *ProtocolFeeRewardManager
// SetProtocolFeeRewardManager persists the protocol-fee reward manager.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - manager: protocol-fee reward manager state to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetProtocolFeeRewardManager(_ int, rlm realm, manager *ProtocolFeeRewardManager) error
// HasDelegationManagerStoreKey reports whether delegation-manager state is initialized.
//
// Returns:
// - bool: true when the delegation manager store key exists
HasDelegationManagerStoreKey() bool
// GetDelegationManager returns the persisted delegation manager.
//
// Returns:
// - *DelegationManager: delegation-to-address index manager
GetDelegationManager() *DelegationManager
// SetDelegationManager persists the delegation manager.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - manager: delegation manager state to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetDelegationManager(_ int, rlm realm, manager *DelegationManager) error
// HasLaunchpadProjectDepositsStoreKey reports whether launchpad project deposits are initialized.
//
// Returns:
// - bool: true when the launchpad-project-deposits store key exists
HasLaunchpadProjectDepositsStoreKey() bool
// GetLaunchpadProjectDeposits returns the persisted launchpad project deposit state.
//
// Returns:
// - *LaunchpadProjectDeposits: project-address-to-deposit state
GetLaunchpadProjectDeposits() *LaunchpadProjectDeposits
// SetLaunchpadProjectDeposits persists launchpad project deposit state.
//
// Parameters:
// - _: leading realm-call discriminator; callers pass 0 for the forwarded store write
// - rlm: propagated current realm context required by the KV store
// - deposits: launchpad project deposit state to store
//
// Returns:
// - error: nil when stored; otherwise the KV-store error, including a spoofed realm context
SetLaunchpadProjectDeposits(_ int, rlm realm, deposits *LaunchpadProjectDeposits) error
}
upgrade.gno
package staker
import (
"gno.land/r/gnoswap/access/v1"
)
// RegisterInitializer registers an implementation initializer for this realm.
// Each implementation version calls it during initialization. The callback
// receives the current realm context and shared gov/staker store so it can
// construct the versioned implementation.
//
// Parameters:
// - cur: current realm context; callers use cross(cur) when crossing into this realm
// - initializer: callback invoked with discriminator 0, validated propagated realm context, and IGovStakerStore, returning the implementation
func RegisterInitializer(cur realm, initializer func(_ int, rlm realm, govStakerStore IGovStakerStore) IGovStaker) {
// `cur` captured here is the gov/staker crossing frame. The wrapping
// closure forwards it to the v1 initializer so any store writes the
// initializer performs run under the proxy's identity rather than the
// version package's, which would fail the kvStore ACL.
initializerFunc := func(_ int, rlm realm, domainStore any) any {
access.AssertIsRlmCurrent(0, rlm)
currentGovStakerStore, ok := domainStore.(IGovStakerStore)
if !ok {
panic("domainStore is not an IGovStakerStore")
}
return initializer(0, rlm, currentGovStakerStore)
}
err := versionManager.RegisterInitializer(0, cur, initializerFunc)
if err != nil {
panic(err)
}
err = updateImplementation()
if err != nil {
panic(err)
}
}
// UpgradeImpl upgrades the active implementation to packagePath.
// Only admin or governance can call this function.
//
// Parameters:
// - cur: current realm context; callers use cross(cur) when crossing into this realm
// - packagePath: package path of the implementation version to activate
func UpgradeImpl(cur realm, packagePath string) {
// Check admin or governance permission
prev := cur.Previous()
access.AssertIsAdminOrGovernance(prev.Address())
err := versionManager.ChangeImplementation(0, cur, packagePath)
if err != nil {
panic(err)
}
err = updateImplementation()
if err != nil {
panic(err)
}
}
// GetImplementationPackagePath returns the package path of the currently active implementation.
//
// Returns:
// - packagePath: package path of the active implementation
func GetImplementationPackagePath() string {
return versionManager.GetCurrentPackagePath()
}
util.gno
package staker