bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 39쪽
eference the historical record is deleted, the reference
count is decremented. If the reference count hits zero, the historical record is deleted.
## State
### FeePool
All globally tracked parameters for distribution are stored within
`FeePool`. Rewards are collected and added to the reward pool and
distributed to validators/delegators from here.
Note that the reward pool holds decimal coins (`DecCoins`) to allow
for fractions of coins to be received from operations like inflation.
When coins are distributed from the pool they are truncated back to
`sdk.Coins` which are non-decimal.
* FeePool: `0x00 -> ProtocolBuffer(FeePool)`
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// coins with decimal
type DecCoins []DecCoin
type DecCoin struct {
Amount math.LegacyDec
Denom string
}
```
```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/distribution/v1beta1/distribution.proto#L117-L124
```
### Validator Distribution
Validator distribution information for the relevant validator is updated each time:
1. delegation amount to a validator is updated,
2. any delegator withdraws from a validator, or
3. the validator withdraws its commission.
* ValidatorDistInfo: `0x02 | ValOperatorAddrLen (1 byte) | ValOperatorAddr -> ProtocolBuffer(validatorDistribution)`
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type ValidatorDistInfo struct {
OperatorAddress sdk.AccAddress
SelfBondRewards sdkmath.DecCoins
ValidatorCommission types.ValidatorAccumulatedCommission
}
```
### Delegation Distribution
Each delegation distribution only needs to record the height at which it last
withdrew fees. Because a delegation must withdraw fees each time it's
properties change (aka bonded tokens etc.) its properties will remain constant
and the delegator's *accumulation* factor can be calculated passively knowing
only the height of the last withdrawal and its current properties.
* DelegationDistInfo: `0x02 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValOperatorAddrLen (1 byte) | ValOperatorAddr -> ProtocolBuffer(delegatorDist)`
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type DelegationDistInfo struct {
WithdrawalHeight int64 // last time this delegation withdrew rewards
}
```
### Params
The distribution module stores its params in state with the prefix of `0x09`,
it can be updated with governance or the address with authority.
* Params: `0x09 | ProtocolBuffer(Params)`
```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/distribution/v1beta1/distribution.proto#L12-L44
```
## Begin Block
At each `BeginBlock`, all fees received in the previous block are transferred to
the distribution `ModuleAccount` account. When a delegator or validator
withdraws their rewards, they are taken out of the `ModuleAccount`. During begin
block, the different claims on the fees collected are updated as follows:
* The reserve community tax is charged.
* The remainder is distributed proportionally by voting power to all bonded validators
### The Distribution Scheme
See [params](#params) for description of parameters.
Let `fees` be the total fees collected in the previous block, including
inflationary rewards to the stake. All fees are collected in a specific module
account during the block. During `BeginBlock`, they are sent to the
`"distribution"` `ModuleAccount`. No other sending of tokens occurs. Instead, the
rewards each account is entitled to are stored, and withdrawals can be triggered
through the messages `FundCommunityPool`, `WithdrawValidatorCommission` and
`WithdrawDelegatorReward`.
#### Reward to the Community Pool
The community pool gets `community_tax * fees`, plus any remaining dust after
validators get their rewards that are always rounded down to the nearest
integer value.
#### Reward To the Validators
The proposer receives no extra rewards. All fees are distributed among all the
bonded validators, including the proposer, in proportion to their consensus power.
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
powFrac = validator power / total bonded validator power
voteMul = 1 - community_tax
```
All validators receive `fees * voteMul * powFrac`.
#### Rewards to Delegators
Each validator's rewards are distributed to its delegators. The validator also
has a self-delegation that is treated like a regular delegation in
distribution calculations.
The validator sets a commission rate. The commission rate is flexible, but each
validator sets a maximum rate and a maximum daily increase. These maximums cannot be exceeded and protect delegators from sudden increases of validator commission rates to prevent validators from taking all of the rewards.
The outstanding rewards that the operator is entitled to are stored in
`ValidatorAccumulatedCommission`, while the rewards the delegators are entitled
to are stored in `ValidatorCurrentRewards`. The [F1 fee distribution scheme](#concepts) is used to calculate the rewards per delegator as they
withdraw or update their delegation, and is thus not handled in `BeginBlock`.
#### Example Distribution
For this example distribution, the underlying consensus engine selects block proposers in
proportion to their power relative to the entire bonded power.
All validators are equally performant at including pre-commits in their proposed
blocks. Then hold `(pre_commits included) / (total bonded validator power)`
constant so that the amortized block reward for the validator is `( validator power / total bonded power) * (1 - community tax rate)` of
the total rewards. Consequently, the reward for a single delegator is:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
(delegator proportion of the validator power / validator power) * (validator power / total bonded power)
* (1 - community tax rate) * (1 - validator commission rate)
= (delegator proportion of the validator power / total bonded power) * (1 -
community tax rate) * (1 - validator commission rate)
```
## Messages
### MsgSetWithdrawAddress
By default, the withdraw address is the delegator address. To change its withdraw address, a delegator must send a `MsgSetWithdrawAddress` message.
Changing the withdraw address is possible only if the parameter `WithdrawAddrEnabled` is set to `true`.
The withdraw address cannot be any of the module accounts. The distribution keeper does not track these itself; it asks the bank keeper through `BlockedAddr`, so the blocked set is the one bank maintains.
A blocked withdraw address is handled differently depending on how the withdrawal is triggered. A withdrawal triggered by a user message fails with `ErrUnauthorized`. An automatic withdrawal during `BeginBlock` or `EndBlock` does not fail. Instead, the funds fall back to the owner's own address. The owner is the delegator for rewards, or the validator for commission. If the owner's address is also blocked, the funds go to the community pool.
```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/distribution/v1beta1/tx.proto#L55-L66
```
### MsgWithdrawDelegatorReward
A delegator can withdraw its rewards.
Internally in the distribution module, this transaction simultaneously removes the previous delegation with associated rewards, the same as if the delegator simply started a new delegation of the same value.
The rewards are sent immediately from the distribution `ModuleAccount` to the withdraw address.
Any remainder (truncated decimals) are sent to the community pool.
The starting height of the delegation is set to the current validator period, and the reference count for the previous period is decremented.
The amount withdrawn is deducted from the `ValidatorOutstandingRewards` variable for the validator.
In the F1 distribution, the total rewards are calculated per validator period, and a delegator receives a piece of those rewards in proportion to their stake in the validator.
In basic F1, the total rewards that all the delegators are entitled to between to periods is calculated the following way.
Let `R(X)` be the total accumulated rewards up to period `X` divided by the tokens staked at that time. The delegator allocation is `R(X) * delegator_stake`.
Then the rewards for all the delegators for staking between periods `A` and `B` are `(R(B) - R(A)) * total stake`.
However, these calculated rewards don't account for slashing.
Taking the slashes into account requires iteration.
Let `F(X)` be the fraction a validator is to be slashed for a slashing event that happened at period `X`.
If the validator was slashed at periods `P1, ..., PN`, where `A < P1`, `PN < B`, the distribution module calculates the individual delegator's rewards, `T(A, B)`, as follows:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
stake := initial stake
rewards := 0
previous := A
for P in P1, ..., PN`:
rewards = (R(P) - previous) * stake
stake = stake * F(P)
previous = P
rewards = rewards + (R(B) - R(PN)) * stake
```
The historical rewards are calculated retroactively by playing back all the slashes and then attenuating the delegator's stake at each step.
The final calculated stake is equivalent to the actual staked coins in the delegation with a margin of error due to rounding errors.
```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/distribution/v1beta1/tx.proto#L72-L83
```
### WithdrawValidatorCommission
The validator can send the WithdrawValidatorCommission message to withdraw their accumulated commission.
The commission is calculated in every block during `BeginBlock`, so no iteration is required to withdraw.
The amount withdrawn is deducted from the `ValidatorOutstandingRewards` variable for the validator.
Only integer amounts can be sent. If the accumulated awards have decimals, the amount is truncated before the withdrawal is sent, and the remainder is left to be withdrawn later.
### FundCommunityPool
This message sends coins directly from the sender to the community pool.
The transaction fails if the amount cannot be transferred from the sender to the distribution module account.
```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (k Keeper)
FundCommunityPool(ctx context.Context, amount sdk.Coins, sender sdk.AccAddress)
error {
if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount); err != nil {
return err
}
feePool, err := k.FeePool.Get(ctx)
if err != nil {
return err
}
feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...)
if err := k.FeePool.Set(ctx, feePool); err != nil {
return err
}
return nil
}
```
### Common distribution operations
These operations take place during many different messages.
#### Initialize delegation
Each time a delegation is changed, the rewards are withdrawn and the delegation is reinitialized.
Initializing a delegation increments the validator period and keeps track of the starting period of the delegation.
```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// initialize starting info for a new delegation
func (k Keeper)
initializeDelegation(ctx context.Context, val sdk.ValAddress, del sdk.AccAddress) {
// period has already been incremented - we want to store the period ended by this delegation action
previousPeriod := k.GetValidatorCurrentRewards(ctx, val).Period - 1
// increment reference count for the period we're going to track
k.incrementReferenceCount(ctx, val, previousPeriod)
validator := k.stakingKeeper.Validator(ctx, val)
delegation := k.stakingKeeper.Delegation(ctx, del, val)
// calculate delegation stake in tokens
// we don't store directly, so multiply delegation shares * (tokens per share)
// note: necessary to truncate so we don't allow withdrawing more rewards than owed
stake := validator.TokensFromSharesTruncated(delegation.GetShares())
k.SetDelegatorStartingInfo(ctx, val, del, types.NewDelegatorStartingInfo(previousPeriod, stake, uint64(ctx.BlockHeight())))
}
```
### MsgUpdateParams
Distribution module params can be updated through `MsgUpdateParams`, which can be done using governance proposal and the signer will always be gov module account address.
```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/distribution/v1beta1/tx.proto#L142-L155
```
The message handling can fail if:
* signer is not the gov module account address.
## Hooks
Available hooks that can be called by and from this module.
### Create or modify delegation distribution
* triggered-by: `staking.MsgDelegate`, `staking.MsgBeginRedelegate`, `staking.MsgUndelegate`
#### Before
* The delegation rewards are withdrawn to the withdraw address of the delegator.
The rewards include the current period and exclude the starting period.
* The validator period is incremented.
The validator period is incremented because the validator's power and share distribution might have changed.
* The reference count for the delegator's starting period is decremented.
#### After
The starting height of the delegation is set to the previous period.
Because of the `Before`-hook, this period is the last period for which the delegator was rewarded.
### Validator created
* triggered-by: `staking.MsgCreateValidator`
When a validator is created, the following validator variables are initialized:
* Historical rewards
* Current accumulated rewards
* Accumulated commission
* Total outstanding rewards
* Period
By default, all values are set to a `0`, except period, which is set to `1`.
### Validator removed
* triggered-by: `staking.RemoveValidator`
Outstanding commission is sent to the validator's self-delegation withdrawal address.
Remaining delegator rewards get sent to the community fee pool.
Note: The validator gets removed only when it has no remaining delegations.
At that time, all outstanding delegator rewards will have been withdrawn.
Any remaining rewards are dust amounts.
### Validator is slashed
* triggered-by: `staking.Slash`
* The current validator period reference count is incremented.
The reference count is incremented because the slash event has created a reference to it.
* The validator period is incremented.
* The slash event is stored for later use.
The slash event will be referenced when calculating delegator rewards.
## Events
The distribution module emits the following events:
### BeginBlocker
| Type | Attribute Key | Attribute Value |
| - | - | - |
| proposer\_reward | validator | `{validatorAddress}` |
| proposer\_reward | reward | `{proposerReward}` |
| commission | amount | `{commissionAmount}` |
| commission | validator | `{validatorAddress}` |
| rewards | amount | `{rewardAmount}` |
| rewards | validator | `{validatorAddress}` |
### Handlers
#### MsgSetWithdrawAddress
| Type | Attribute Key | Attribute Value |
| - | - | - |
| set\_withdraw\_address | withdraw\_address | `{withdrawAddress}` |
| message | module | distribution |
| message | action | set\_withdraw\_address |
| message | sender | `{senderAddress}` |
#### MsgWithdrawDelegatorReward
| Type | Attribute Key | Attribute Value |
| - | - | - |
| withdraw\_rewards | amount | `{rewardAmount}` |
| withdraw\_rewards | validator | `{validatorAddress}` |
| message | module | distribution |
| message | action | withdraw\_delegator\_reward |
| message | sender | `{senderAddress}` |
#### MsgWithdrawValidatorCommission
| Type | Attribute Key | Attribute Value |
| - | - | - |
| withdraw\_commission | amount | `{commissionAmount}` |
| message | module | distribution |
| message | action | withdraw\_validator\_commission |
| message | sender | `{senderAddress}` |
## Parameters
The distribution module contains the following parameters:
| Key | Type | Example |
| - | - | - |
| communitytax | string (dec) | "0.020000000000000000" \[0] |
| withdrawaddrenabled | bool | true |
* \[0] `communitytax` must be positive and cannot exceed 1.00.
* `baseproposerreward` and `bonusproposerreward` were parameters that are deprecated in v0.47 and are not used.
<Note>
The reserve pool is the pool of collected funds for use by governance taken via the `CommunityTax`.
Currently with the Cosmos SDK, tokens collected by the CommunityTax are accounted for but unspendable.
</Note>
## Client
## CLI
A user can query and interact with the `distribution` module using the CLI.
#### Query
The `query` commands allow users to query `distribution` state.
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
simd query distribution --help
```
##### commission
The `commission` command allows users to query validator commission rewards by address.
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
simd query distribution commission [address] [flags]
```
Example:
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
simd query distribution commission cosmosvaloper1...
```
Example Output:
```yml theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
commission:
- amount: "1000000.000000000000000000"
denom: stake
```
##### community-pool
The `community-pool` command allows users to query all coin balances within the community pool.
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
simd query distribution community-pool [flags]
```
Example:
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
simd query distribution community-pool
```
Example Output:
```yml theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
pool:
- amount: "1000000.000000000000000000"
denom: stake
```
##### params
The `params` command allows users to query the parameters of the `distribution` module.
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
simd query distribution params [flags]
```
Example:
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
simd query distribution params
```
Example Output:
```yml theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
base_proposer_reward: "0.000000000000000000"
bonus_proposer_reward: "0.000000000000000000"
community_tax: "0.020000000000000000"
withdraw_addr_enabled: true
```
##### rewards
The `rewards` command allows users to query delegator rewards. Users can optionally include the validator address to query rewards earned from a specific validator.
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
simd query distribution rewards [delegator-addr] [validator-addr] [flags]
```
Example:
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
simd query distribution rewards cosmos1...
```
Example Output:
```yml theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
rewards:
- reward:
- amount: "1000000.000000000000000000"
denom: stake
val프로젝트로 돌아가기