reward

package
v1.12.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 1, 2024 License: GPL-3.0 Imports: 25 Imported by: 17

Documentation

Overview

Package reward implements the Klaytn Reward System. The Klaytn reward system manages stakingInfo and distributes block rewards.

Managing stakingInfo

Klaytn uses WeightedRandom policy to choose a block proposer. It means, the percentage of becoming a block proposer depends on how much KLAY a node has staked. Therefore, a node with stakes more than others will have more opportunities than other nodes.

StakingInfo is a data including stakingAmount and addresses (node, staking, reward, KFF and KCF). StakingAmount is a balance how much KLAY each node has staked. Only CCO can stake KLAY. Each CCO stakes KLAY by a smart contract called staking contract. StakingAmount is derived by checking balance of staking contract. StakingInfo has 5 types of addresses. All addresses are obtained by the addressBookContract which is pre-deployed in the genesis block. stakingAddress are addresses of staking contracts of CCO. reward, KFF and KCF addresses are the addresses which get a block reward when a block has been created. StakingInfo is made every 86400 blocks (stakingInterval) and used in a next interval.

type StakingInfo struct {
	BlockNum              uint64
	CouncilNodeAddrs      []common.Address // Address of Council
	CouncilStakingAddrs   []common.Address // Address of Staking contract which holds staking balance
	CouncilRewardAddrs    []common.Address // Address of Council account which will get a block reward
	KCFAddr               common.Address   // Address of KCF contract
	KFFAddr               common.Address   // Address of KFF contract
	UseGini               bool             // configure whether Gini is used or not
	Gini                  float64          // Gini coefficient
	CouncilStakingAmounts []uint64         // StakingAmounts of Council. They are derived from Staking addresses of council
}

StakingInfo is managed by a StakingManager which has a cache for saving StakingInfos. The StakingManager calculates block number with interval to find a stakingInfo for current block and returns correct stakingInfo to use.

related struct
- RewardDistributor
- StakingManager
- addressBookConnector
- stakingInfoCache
- stakingInfo

Distributing Reward

Klaytn distributes the reward of a block to proposer, KFF and KCF. The detail information of KFF and KCF is available on Klaytn docs.

Token Economy - https://docs.klaytn.foundation/content/klaytn/design/token-economy

Configurations related to the reward system such as mintingAmount, ratio and unitPrice are determined by the Klaytn governance. All configurations are saved as rewardConfig on every epoch block (default 604,800 blocks) and managed by a rewardConfigCache.

A proposer which has made a current block will get the reward of the block. A block reward is calculated by following steps. First, calculate totalReward by adding mintingAmount and totalTxFee (unitPrice * gasUsed). Second, divide totalReward by ratio (default 34/54/12 - proposer/KFF/KCF). Last, distribute reward to each address (proposer, KFF, KCF).

related struct
- RewardDistributor
- rewardConfigCache

Index

Constants

View Source
const (
	AddrNotFoundInCouncilNodes = -1

	DefaultGiniCoefficient = -1.0
)

Variables

View Source
var (

	// errors for staking manager
	ErrStakingManagerNotSet = errors.New("staking manager is not set")
	ErrChainHeadChanNotSet  = errors.New("chain head channel is not set")
)
View Source
var CalcDeferredRewardTimer time.Duration
View Source
var (
	ErrAddrNotInStakingInfo = errors.New("Address is not in stakingInfo")
)
View Source
var ErrStakingDBNotSet = errors.New("stakingInfoDB is not set")

Functions

func AddStakingInfoToDB added in v1.9.0

func AddStakingInfoToDB(stakingInfo *StakingInfo) error

func CalcGiniCoefficient

func CalcGiniCoefficient(stakingAmount float64Slice) float64

func CalcRewardParamBlock added in v1.10.0

func CalcRewardParamBlock(num, epoch uint64, rules params.Rules) uint64

CalcRewardParamBlock returns the block number with which governance parameters must be fetched This mimics the legacy reward config cache before Kore

func CheckStakingInfoStored added in v1.5.0

func CheckStakingInfoStored(blockNum uint64) error

CheckStakingInfoStored makes sure the given staking info is stored in cache and DB

func DistributeBlockReward added in v1.10.0

func DistributeBlockReward(b BalanceAdder, rewards map[common.Address]*big.Int)

DistributeBlockReward distributes a given block's reward at the end of block processing

func GetTotalTxFee added in v1.10.0

func GetTotalTxFee(header *types.Header, rules params.Rules, pset *params.GovParamSet) *big.Int

func HasStakingInfoFromDB added in v1.10.2

func HasStakingInfoFromDB(blockNumber uint64) (bool, error)

HasStakingInfoFromDB returns existence of staking information from miscdb.

func IsRewardSimple added in v1.10.0

func IsRewardSimple(pset *params.GovParamSet) bool

config.Istanbul must have been set

func NewRewardConfig added in v1.10.0

func NewRewardConfig(header *types.Header, rules params.Rules, pset *params.GovParamSet) (*rewardConfig, error)

func PurgeStakingInfoCache added in v1.12.0

func PurgeStakingInfoCache()

func SetTestAddressBookAddress added in v1.9.0

func SetTestAddressBookAddress(addr common.Address)

SetTestAddressBookAddress is only for testing purpose.

func SetTestStakingManager added in v1.7.0

func SetTestStakingManager(sm *StakingManager)

SetTestStakingManager sets the staking manager for testing purpose. Note that this method is used only for testing purpose.

func SetTestStakingManagerWithChain added in v1.9.0

func SetTestStakingManagerWithChain(bc blockChain, gh governanceHelper, db stakingInfoDB)

SetTestStakingManagerWithChain sets a full-featured staking manager with blockchain, database and cache. Note that this method is used only for testing purpose.

func SetTestStakingManagerWithDB added in v1.9.0

func SetTestStakingManagerWithDB(testDB stakingInfoDB)

SetTestStakingManagerWithDB sets the staking manager with the given database. Note that this method is used only for testing purpose.

func SetTestStakingManagerWithStakingInfoCache added in v1.7.0

func SetTestStakingManagerWithStakingInfoCache(testInfo *StakingInfo)

SetTestStakingManagerWithStakingInfoCache sets the staking manager with the given test staking information. Note that this method is used only for testing purpose.

func StakingManagerSubscribe added in v1.5.0

func StakingManagerSubscribe()

StakingManagerSubscribe setups a channel to listen chain head event and starts a goroutine to update staking cache.

func StakingManagerUnsubscribe added in v1.5.0

func StakingManagerUnsubscribe()

StakingManagerUnsubscribe can unsubscribe a subscription on chain head event.

func TestGetStakingCacheSize added in v1.12.0

func TestGetStakingCacheSize() int

Types

type BalanceAdder

type BalanceAdder interface {
	AddBalance(addr common.Address, v *big.Int)
}

type ConsolidatedStakingInfo added in v1.9.0

type ConsolidatedStakingInfo struct {
	// contains filtered or unexported fields
}

func (*ConsolidatedStakingInfo) CalcGiniCoefficientMinStake added in v1.9.0

func (c *ConsolidatedStakingInfo) CalcGiniCoefficientMinStake(minStake uint64) float64

Calculate Gini coefficient of the StakingAmounts. Only amounts greater or equal to `minStake` are included in the calculation. Set `minStake` to 0 to calculate Gini coefficient of all amounts.

func (*ConsolidatedStakingInfo) GetAllNodes added in v1.9.0

func (c *ConsolidatedStakingInfo) GetAllNodes() []consolidatedNode

func (*ConsolidatedStakingInfo) GetConsolidatedNode added in v1.9.0

func (c *ConsolidatedStakingInfo) GetConsolidatedNode(nodeAddr common.Address) *consolidatedNode

func (*ConsolidatedStakingInfo) String added in v1.9.0

func (c *ConsolidatedStakingInfo) String() string

type RewardDistributor

type RewardDistributor struct{}

TODO: this is for legacy, will be removed

func NewRewardDistributor

func NewRewardDistributor(gh governanceHelper) *RewardDistributor

type RewardSpec added in v1.10.0

type RewardSpec struct {
	Minted   *big.Int                    `json:"minted"`   // the amount newly minted
	TotalFee *big.Int                    `json:"totalFee"` // total tx fee spent
	BurntFee *big.Int                    `json:"burntFee"` // the amount burnt
	Proposer *big.Int                    `json:"proposer"` // the amount allocated to the block proposer
	Stakers  *big.Int                    `json:"stakers"`  // total amount allocated to stakers
	KFF      *big.Int                    `json:"kff"`      // the amount allocated to KFF
	KCF      *big.Int                    `json:"kcf"`      // the amount allocated to KCF
	Rewards  map[common.Address]*big.Int `json:"rewards"`  // mapping from reward recipient to amounts
}

func CalcDeferredReward added in v1.10.0

func CalcDeferredReward(header *types.Header, rules params.Rules, pset *params.GovParamSet) (*RewardSpec, error)

CalcDeferredReward calculates the deferred rewards, which are determined at the end of block processing.

func CalcDeferredRewardSimple added in v1.10.0

func CalcDeferredRewardSimple(header *types.Header, rules params.Rules, pset *params.GovParamSet) (*RewardSpec, error)

CalcDeferredRewardSimple distributes rewards to proposer after optional fee burning this behaves similar to the previous MintKLAY MintKLAY has been superseded because we need to split reward distribution logic into (1) calculation, and (2) actual distribution. CalcDeferredRewardSimple does the former and DistributeBlockReward does the latter

func GetBlockReward added in v1.10.0

func GetBlockReward(header *types.Header, rules params.Rules, pset *params.GovParamSet) (*RewardSpec, error)

GetBlockReward returns the actual reward amounts paid in this block Used in klay_getReward RPC API

func NewRewardSpec added in v1.10.0

func NewRewardSpec() *RewardSpec

func (*RewardSpec) Add added in v1.11.0

func (spec *RewardSpec) Add(delta *RewardSpec)

type StakingInfo

type StakingInfo struct {
	BlockNum uint64 `json:"blockNum"` // Block number where staking information of Council is fetched

	// Information retrieved from AddressBook smart contract
	CouncilNodeAddrs    []common.Address `json:"councilNodeAddrs"`    // NodeIds of Council
	CouncilStakingAddrs []common.Address `json:"councilStakingAddrs"` // Address of Staking account which holds staking balance
	CouncilRewardAddrs  []common.Address `json:"councilRewardAddrs"`  // Address of Council account which will get block reward

	KCFAddr common.Address `json:"kcfAddr"` // Address of KCF contract
	KFFAddr common.Address `json:"kffAddr"` // Address of KFF contract

	UseGini bool    `json:"useGini"`
	Gini    float64 `json:"gini"` // gini coefficient

	// Derived from CouncilStakingAddrs
	CouncilStakingAmounts []uint64 `json:"councilStakingAmounts"` // Staking amounts of Council
}

StakingInfo contains staking information.

func GetStakingInfo added in v1.5.0

func GetStakingInfo(blockNum uint64) *StakingInfo

GetStakingInfo returns a stakingInfo on the staking block of the given block number. Note that staking block is the block on which the associated staking information is stored and used during an interval.

func GetStakingInfoOnStakingBlock added in v1.9.0

func GetStakingInfoOnStakingBlock(stakingBlockNumber uint64) *StakingInfo

GetStakingInfoOnStakingBlock returns a corresponding StakingInfo for a staking block number. If the given number is not on the staking block, it returns nil.

Fixup for Gini coefficients: Klaytn core stores Gini: -1 in its database. We ensure GetStakingInfoOnStakingBlock() to always return meaningful Gini. - If cache hit -> fillMissingGini -> modifies cached in-memory object - If db hit -> fillMissingGini -> write to cache - If read contract -> write to db (gini: -1) -> fillMissingGini -> write to cache

func (*StakingInfo) DecodeRLP added in v1.9.0

func (s *StakingInfo) DecodeRLP(st *rlp.Stream) error

func (*StakingInfo) EncodeRLP added in v1.9.0

func (s *StakingInfo) EncodeRLP(w io.Writer) error

func (*StakingInfo) GetConsolidatedStakingInfo added in v1.9.0

func (s *StakingInfo) GetConsolidatedStakingInfo() *ConsolidatedStakingInfo

func (*StakingInfo) GetIndexByNodeAddress

func (s *StakingInfo) GetIndexByNodeAddress(nodeAddress common.Address) (int, error)

func (*StakingInfo) GetStakingAmountByNodeId

func (s *StakingInfo) GetStakingAmountByNodeId(nodeAddress common.Address) (uint64, error)

func (StakingInfo) MarshalJSON added in v1.10.2

func (st StakingInfo) MarshalJSON() ([]byte, error)

MarshalJSON supports json marshalling for both oldStakingInfo and StakingInfo TODO-klaytn-Mantle: remove this marshal function when backward-compatibility for KIR/PoC is not needed

func (*StakingInfo) String added in v1.2.0

func (s *StakingInfo) String() string

func (*StakingInfo) UnmarshalJSON added in v1.10.2

func (st *StakingInfo) UnmarshalJSON(input []byte) error

UnmarshalJSON supports json unmarshalling for both oldStakingInfo and StakingInfo

type StakingManager

type StakingManager struct {
	// contains filtered or unexported fields
}

func GetStakingManager added in v1.5.0

func GetStakingManager() *StakingManager

func NewStakingManager

func NewStakingManager(bc blockChain, gh governanceHelper, db stakingInfoDB) *StakingManager

NewStakingManager creates and returns StakingManager.

On the first call, a StakingManager is created with given parameters. From next calls, the existing StakingManager is returned. (Parameters from the next calls will not affect.)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL