-
Notifications
You must be signed in to change notification settings - Fork 22
/
staking_reward_calculator.go
207 lines (179 loc) · 8.58 KB
/
staking_reward_calculator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package rewards
import (
"sort"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/logging"
)
var minThresholdDelegatorReward, _ = num.DecimalFromString("0.001")
// distribute rewards for a given asset account with the given settings of delegation and reward constraints.
func calculateRewardsByStake(epochSeq, asset, accountID string, rewardBalance *num.Uint, valScore map[string]num.Decimal, validatorDelegation []*types.ValidatorData, delegatorShare num.Decimal, maxPayout *num.Uint, log *logging.Logger) *payout {
minLeftOverForDistribution := num.UintZero()
if !maxPayout.IsZero() {
minLeftOverForDistribution, _ = num.UintFromDecimal(minThresholdDelegatorReward.Mul(maxPayout.ToDecimal()))
}
// if there is no reward to give, return no payout
rewards := map[string]*num.Uint{}
totalRewardPayout := num.UintZero()
reward := rewardBalance.Clone()
if reward.IsZero() {
return &payout{
partyToAmount: rewards,
totalReward: totalRewardPayout,
asset: asset,
epochSeq: epochSeq,
}
}
for _, vd := range validatorDelegation {
valScore := valScore[vd.NodeID] // normalised score
if valScore.IsZero() {
// if the validator isn't eligible for reward this round, nothing to do here
continue
}
// how much reward is assigned to the validator and its delegators
epochPayoutForValidatorAndDelegators := valScore.Mul(reward.ToDecimal())
// calculate the fraction delegators to the validator get
totalStakeForValidator := vd.StakeByDelegators.ToDecimal().Add(vd.SelfStake.ToDecimal())
delegatorFraction := delegatorShare.Mul(vd.StakeByDelegators.ToDecimal()).Div(totalStakeForValidator) // totalStakeForValidator must be non zero as valScore is non zero
validatorFraction := num.DecimalFromInt64(1).Sub(delegatorFraction)
// how much delegators take
amountToGiveToDelegators, _ := num.UintFromDecimal(delegatorFraction.Mul(epochPayoutForValidatorAndDelegators))
// calculate the potential reward for delegators and the validator
amountToKeepByValidator, _ := num.UintFromDecimal(validatorFraction.Mul(epochPayoutForValidatorAndDelegators))
log.Info("Rewards: reward calculation for validator",
logging.String("epochSeq", epochSeq),
logging.String("epochPayoutForValidatorAndDelegators", epochPayoutForValidatorAndDelegators.String()),
logging.String("totalStakeForValidator", totalStakeForValidator.String()),
logging.String("delegatorFraction", delegatorFraction.String()),
logging.String("validatorFraction", validatorFraction.String()),
logging.String("amountToGiveToDelegators", amountToGiveToDelegators.String()),
logging.String("amountToKeepByValidator", amountToKeepByValidator.String()))
// check how much reward the validator can accept with the cap per participant
rewardForNode, ok := rewards[vd.PubKey]
if !ok {
rewardForNode = num.UintZero()
}
// if there is no cap just add the total payout for the validator
if maxPayout.IsZero() {
rewards[vd.PubKey] = num.Sum(rewardForNode, amountToKeepByValidator)
totalRewardPayout.AddSum(amountToKeepByValidator)
} else {
balanceWithPayout := num.UintZero().Add(rewardForNode, amountToKeepByValidator)
if balanceWithPayout.LTE(maxPayout) {
rewards[vd.PubKey] = balanceWithPayout
totalRewardPayout.AddSum(amountToKeepByValidator)
} else {
rewards[vd.PubKey] = maxPayout
totalRewardPayout.AddSum(num.UintZero().Sub(maxPayout, rewardForNode))
}
}
log.Info("Rewards: reward kept by validator for epoch (post max payout cap)", logging.String("epoch", epochSeq), logging.String("validator", vd.NodeID), logging.String("amountToKeepByValidator", rewards[vd.PubKey].String()))
remainingRewardForDelegators := amountToGiveToDelegators
// if there's nothing to give to delegators move on
if remainingRewardForDelegators.IsZero() {
continue
}
// calculate the weight of each delegator out of the delegated stake to the validator
delegatorWeights := make(map[string]num.Decimal, len(vd.Delegators))
weightSums := num.DecimalZero()
decimalOne := num.DecimalFromInt64(1)
sortedParties := make([]string, 0, len(vd.Delegators))
for party, delegatorAmt := range vd.Delegators {
delegatorWeight := delegatorAmt.ToDecimal().Div(vd.StakeByDelegators.ToDecimal()) // this is not entered if there are no delegators
weightSums = weightSums.Add(delegatorWeight)
// if the party has 0 delegation, ignore it
if !delegatorAmt.IsZero() {
delegatorWeights[party] = delegatorWeight
sortedParties = append(sortedParties, party)
}
}
sort.Strings(sortedParties)
adjustWeights(delegatorWeights, weightSums, sortedParties, decimalOne)
// calculate delegator amounts
// this may take a few rounds due to the cap on the reward a party can get
// if we still have parties that haven't maxed their reward, they are split the remaining balance
roundsRemaining := 10
for {
log.Info("Reward remaining to distribute to delegators", logging.String("epoch", epochSeq), logging.String("remainingRewardForDelegators", remainingRewardForDelegators.String()))
totalAwardedThisRound := num.UintZero()
for _, party := range sortedParties {
// check if the party has already rewards from other validators or previous rounds (this epoch)
rewardForParty, ok := rewards[party]
if !ok {
rewardForParty = num.UintZero()
}
delegatorWeight := delegatorWeights[party]
rewardAsUint, _ := num.UintFromDecimal(delegatorWeight.Mul(remainingRewardForDelegators.ToDecimal()))
if maxPayout.IsZero() {
totalAwardedThisRound.AddSum(rewardAsUint)
totalRewardPayout.AddSum(rewardAsUint)
rewards[party] = num.UintZero().Add(rewardForParty, rewardAsUint)
} else {
balanceWithPayout := num.UintZero().Add(rewardForParty, rewardAsUint)
if balanceWithPayout.LTE(maxPayout) {
rewards[party] = balanceWithPayout
totalAwardedThisRound.AddSum(rewardAsUint)
totalRewardPayout.AddSum(rewardAsUint)
} else {
rewards[party] = maxPayout
totalAwardedThisRound.AddSum(num.UintZero().Sub(maxPayout, rewardForParty))
totalRewardPayout.AddSum(num.UintZero().Sub(maxPayout, rewardForParty))
}
}
}
roundsRemaining--
// if we finished a round without distributing anything, we should stop
// if this is the final round, stop
// if the left over is too small for retrying to distribute, stop
remainingRewardForDelegators = num.UintZero().Sub(remainingRewardForDelegators, totalAwardedThisRound)
if roundsRemaining == 0 || remainingRewardForDelegators.LT(minLeftOverForDistribution) || totalAwardedThisRound.IsZero() {
break
}
}
}
if totalRewardPayout.GT(rewardBalance) {
log.Error("The reward payout is greater than the reward balance, this should never happen", logging.String("reward-payout", totalRewardPayout.String()), logging.String("reward-balance", rewardBalance.String()))
}
return &payout{
fromAccount: accountID,
partyToAmount: rewards,
totalReward: totalRewardPayout,
asset: asset,
epochSeq: epochSeq,
}
}
func adjustWeights(delegatorWeights map[string]num.Decimal, weightSums num.Decimal, sortedParties []string, decimalOne num.Decimal) {
// NB: due to rounding errors this sum can be greater than 1
// to avoid overflow, we choose the one with the highest weight, if that's not sufficient, we'll again choose the one with the highest weight and adjust
// it marginally until convergence.
for weightSums.GreaterThan(decimalOne) {
precisionError := weightSums.Sub(decimalOne)
maxWeight := num.DecimalZero()
maxWeightParty := ""
for _, p := range sortedParties {
if delegatorWeights[p].GreaterThan(maxWeight) {
maxWeight = delegatorWeights[p]
maxWeightParty = p
}
}
delegatorWeights[maxWeightParty] = num.MaxD(num.DecimalZero(), delegatorWeights[maxWeightParty].Sub(precisionError))
weightSums = num.DecimalZero()
for _, d := range delegatorWeights {
weightSums = weightSums.Add(d)
}
}
}