/
delegation_strategy.go
318 lines (259 loc) · 12.1 KB
/
delegation_strategy.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package keeper
import (
"sort"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/persistenceOne/pstake-native/v2/x/lscosmos/types"
)
// DelegateMsgs gives the list of Delegate Txs to be executed based on the current state and params.
// CONTRACT: allowlistedValList.len > 0, amount > 0
func (k Keeper) DelegateMsgs(ctx sdk.Context, amount sdk.Int, denom string, delegationState types.DelegationState) ([]sdk.Msg, error) {
// fetch a combined updated val set list and delegation state
updateValList, hostAccountDelegations := k.GetAllValidatorsState(ctx, denom)
// assign the updated validator delegation state to the current delegation state
delegationState.HostAccountDelegations = hostAccountDelegations
updatedAllowListedValidators := types.AllowListedValidators{AllowListedValidators: updateValList}
valAddressAmount, err := FetchValidatorsToDelegate(updatedAllowListedValidators, delegationState, sdk.NewCoin(denom, amount))
if err != nil {
return nil, err
}
var msgs []sdk.Msg
for _, val := range valAddressAmount {
if val.Amount.IsPositive() {
msg := &stakingtypes.MsgDelegate{
DelegatorAddress: delegationState.HostChainDelegationAddress,
ValidatorAddress: val.ValidatorAddr,
Amount: val.Amount,
}
msgs = append(msgs, msg)
}
}
if len(msgs) == 0 {
return nil, sdkerrors.Wrap(types.ErrInvalidMsgs, "No msgs to delegate")
}
return msgs, nil
}
// UndelegateMsgs gives the list of Undelegate Txs to be executed based on the current state and params.
// CONTRACT: allowlistedValList.len > 0, amount > 0
func (k Keeper) UndelegateMsgs(ctx sdk.Context, amount sdk.Int, denom string, delegationState types.DelegationState) ([]sdk.Msg, []types.UndelegationEntry, error) {
// fetch a combined updated val set list and delegation state
updateValList, hostAccountDelegations := k.GetAllValidatorsState(ctx, denom)
// assign the updated validator delegation state to the current delegation state
delegationState.HostAccountDelegations = hostAccountDelegations
updatedAllowListedValidators := types.AllowListedValidators{AllowListedValidators: updateValList}
valAddressAmount, err := FetchValidatorsToUndelegate(updatedAllowListedValidators, delegationState, sdk.NewCoin(denom, amount))
if err != nil {
return nil, nil, err
}
//nolint:prealloc,len_not_fixed
var msgs []sdk.Msg
//nolint:prealloc,len_not_fixed
var undelegationEntries []types.UndelegationEntry
for _, val := range valAddressAmount {
msg := &stakingtypes.MsgUndelegate{
DelegatorAddress: delegationState.HostChainDelegationAddress,
ValidatorAddress: val.ValidatorAddr,
Amount: val.Amount,
}
msgs = append(msgs, msg)
undelegationEntry := types.UndelegationEntry{
ValidatorAddress: val.ValidatorAddr,
Amount: val.Amount,
}
undelegationEntries = append(undelegationEntries, undelegationEntry)
}
// should never come ideally
if len(msgs) == 0 || len(undelegationEntries) == 0 {
return nil, nil, sdkerrors.Wrap(types.ErrInvalidMsgs, "No msgs to undelegate")
}
return msgs, undelegationEntries, nil
}
// FetchValidatorsToDelegate gives a list of all validators having weighted amount for few and 1uatom for rest in order to auto claim all rewards accumulated in current epoch
func FetchValidatorsToDelegate(valList types.AllowListedValidators, delegationState types.DelegationState, amount sdk.Coin) (types.ValAddressAmounts, error) {
curDiffDistribution, err := GetIdealCurrentDelegations(valList, delegationState, amount, false)
if err != nil {
return nil, err
}
sort.Sort(sort.Reverse(curDiffDistribution))
return DivideAmountIntoValidatorSet(curDiffDistribution, amount)
}
// FetchValidatorsToUndelegate gives a list of all validators having weighted amount for few and 1uatom for rest in order to auto claim all rewards accumulated in current epoch
func FetchValidatorsToUndelegate(valList types.AllowListedValidators, delegationState types.DelegationState, amount sdk.Coin) (types.ValAddressAmounts, error) {
currDiffDistribution, err := GetIdealCurrentDelegations(valList, delegationState, amount, true)
if err != nil {
return nil, err
}
sort.Sort(sort.Reverse(currDiffDistribution))
return DivideUndelegateAmountIntoValidatorSet(currDiffDistribution, amount)
}
// GetIdealCurrentDelegations returns ideal amount of delegations to validators on host chain
func GetIdealCurrentDelegations(valList types.AllowListedValidators, delegationState types.DelegationState, amt sdk.Coin, reverse bool) (types.WeightedAddressAmounts, error) {
totalDelegations := delegationState.TotalDelegations(amt.Denom)
if reverse && totalDelegations.IsLT(amt) {
return nil, sdkerrors.Wrapf(types.ErrInsufficientFundsToUndelegate, "staked: %s, undelegate : %s", totalDelegations, amt)
}
curDiffDistribution := types.WeightedAddressAmounts{}
delegationMap := types.GetHostAccountDelegationMap(delegationState.HostAccountDelegations)
var idealTokens, curTokens sdk.Int
for _, valT := range valList.AllowListedValidators {
totalAmt := totalDelegations.Amount.Add(amt.Amount)
if reverse {
totalAmt = totalDelegations.Amount.Sub(amt.Amount)
}
idealTokens = valT.TargetWeight.Mul(sdk.NewDecFromInt(totalAmt)).TruncateInt()
curCoins, ok := delegationMap[valT.ValidatorAddress]
if !ok {
curCoins = sdk.NewCoin(amt.Denom, sdk.ZeroInt())
}
curTokens = curCoins.Amount
diffAmt := idealTokens.Sub(curTokens)
if reverse {
diffAmt = curTokens.Sub(idealTokens)
}
curDiffDistribution = append(curDiffDistribution, types.WeightedAddressAmount{
Address: valT.ValidatorAddress,
Weight: valT.TargetWeight,
Denom: amt.Denom,
Amount: diffAmt,
})
}
return curDiffDistribution, nil
}
// divideAmountWeightedSet : divides amount to be delegated or undelegated w.r.t weights.
func divideAmountWeightedSet(valAmounts types.ValAddressAmounts, coin sdk.Coin, valAddressWeightMap map[string]sdk.Dec) types.ValAddressAmounts {
var newValAmounts types.ValAddressAmounts
totalWeight := sdk.ZeroDec()
for _, weight := range valAddressWeightMap {
totalWeight = totalWeight.Add(weight)
}
for _, valAmt := range valAmounts {
weight := valAddressWeightMap[valAmt.ValidatorAddr].Quo(totalWeight)
amt := weight.MulInt(coin.Amount).RoundInt()
newValAmounts = append(newValAmounts, types.ValAddressAmount{
ValidatorAddr: valAmt.ValidatorAddr,
Amount: sdk.NewCoin(valAmt.Amount.Denom, valAmt.Amount.Amount.Add(amt)),
})
}
return newValAmounts
}
// distributeCoinsAmongstValSet takes the validator distribution and coins to distribute and returns the
// validator address amount to distribute and the remaining amount to make
func distributeCoinsAmongstValSet(ws types.WeightedAddressAmounts, coin sdk.Coin) (types.ValAddressAmounts, sdk.Coin) {
var valAddrAmts types.ValAddressAmounts
for _, w := range ws {
if coin.Amount.LTE(w.Amount) {
valAddrAmts = append(valAddrAmts, types.ValAddressAmount{ValidatorAddr: w.Address, Amount: coin})
return valAddrAmts, sdk.NewInt64Coin(coin.Denom, 0)
}
tempAmount := w.Amount
if w.Amount.IsNegative() {
tempAmount = sdk.ZeroInt()
}
valAddrAmts = append(valAddrAmts, types.ValAddressAmount{ValidatorAddr: w.Address, Amount: sdk.NewCoin(w.Denom, tempAmount)})
coin = coin.SubAmount(tempAmount)
}
return valAddrAmts, coin
}
// DivideAmountIntoValidatorSet : divides amount into validator set
func DivideAmountIntoValidatorSet(sortedValDiff types.WeightedAddressAmounts, coin sdk.Coin) (types.ValAddressAmounts, error) {
if coin.IsZero() {
return nil, nil
}
// Delegate to non-zero weighted validator set only
_, nonZeroWeighted := types.GetZeroNonZeroWightedAddrAmts(sortedValDiff)
sort.Sort(sort.Reverse(nonZeroWeighted))
valAmounts, remainderCoin := distributeCoinsAmongstValSet(nonZeroWeighted, coin)
// If the remaining amount is not possitive, return early
if !remainderCoin.IsPositive() {
return valAmounts, nil
}
// Remaining token is the slippage from the multiplication with dec,
// Ideally this amount is not going to be alot, hence assigning to
// validator with index zero.
valAmounts[0].Amount = valAmounts[0].Amount.Add(remainderCoin)
sort.Sort(valAmounts)
return valAmounts, nil
}
// DivideUndelegateAmountIntoValidatorSet : divides undelegation amount into validator set
//
//nolint:gocritic,len_not_fixed
func DivideUndelegateAmountIntoValidatorSet(sortedValDiff types.WeightedAddressAmounts, coin sdk.Coin) (types.ValAddressAmounts, error) {
if coin.IsZero() {
return nil, nil
}
// Undelegate first from zero weighted validators then nonzero weighted
zeroWeighted, nonZeroWeighted := types.GetZeroNonZeroWightedAddrAmts(sortedValDiff)
sort.Sort(sort.Reverse(zeroWeighted))
sort.Sort(sort.Reverse(nonZeroWeighted))
valWeighted := append(zeroWeighted, nonZeroWeighted...)
valAmounts, remainderCoin := distributeCoinsAmongstValSet(valWeighted, coin)
// If the remaining amount is not positive, return early
if !remainderCoin.IsPositive() {
return valAmounts, nil
}
// Divide the remaining amount amongst the validators a/c to weight
zeroValued := sortedValDiff.GetZeroValued()
valAddressMap := types.GetWeightedAddressMap(zeroValued)
valAmounts = divideAmountWeightedSet(valAmounts, remainderCoin, valAddressMap)
// sort the val address amount based on address to avoid generating different lists
// by all validators
sort.Sort(valAmounts)
return valAmounts, nil
}
// GetAllValidatorsState returns the combined allowed listed validators set and combined
// delegation state. It is done to keep the old validators in the loop while calculating weighted amounts
// for delegation and undelegation
func (k Keeper) GetAllValidatorsState(ctx sdk.Context, denom string) (types.AllowListedVals, types.HostAccountDelegations) {
// Get current active val set and make a map of it
currentAllowListedValSet := k.GetAllowListedValidators(ctx)
currentAllowListedValSetMap := make(map[string]sdk.Dec)
for _, val := range currentAllowListedValSet.AllowListedValidators {
currentAllowListedValSetMap[val.ValidatorAddress] = val.TargetWeight
}
// get delegation state and make a map with address as
currentDelegationState := k.GetDelegationState(ctx)
currentDelegationStateMap := make(map[string]sdk.Coin)
for _, delegation := range currentDelegationState.HostAccountDelegations {
currentDelegationStateMap[delegation.ValidatorAddress] = delegation.Amount
}
// get validator list from allow listed validators
delList := make([]string, len(currentAllowListedValSet.AllowListedValidators))
for i, delegation := range currentAllowListedValSet.AllowListedValidators {
delList[i] = delegation.ValidatorAddress
}
// get validator list from current delegation state
valList := make([]string, len(currentDelegationState.HostAccountDelegations))
for i, val := range currentDelegationState.HostAccountDelegations {
valList[i] = val.ValidatorAddress
}
// Assign zero weights to all the validators not present in the current allow listed validator set map
for _, val := range valList {
_, ok := currentAllowListedValSetMap[val]
if !ok {
currentAllowListedValSetMap[val] = sdk.ZeroDec()
}
}
// Convert the updated val set map to a slice of types.AllowListedValidator
var updatedValSet types.AllowListedVals
for key, value := range currentAllowListedValSetMap {
updatedValSet = append(updatedValSet, types.AllowListedValidator{ValidatorAddress: key, TargetWeight: value})
}
// Assign zero coin to all the validators not present in the current delegation state map
for _, val := range delList {
_, ok := currentDelegationStateMap[val]
if !ok {
currentDelegationStateMap[val] = sdk.NewCoin(denom, sdk.ZeroInt())
}
}
// Convert the updated delegation state map to slice of types.HostChainDelegation
var updatedDelegationState types.HostAccountDelegations
for key, value := range currentDelegationStateMap {
updatedDelegationState = append(updatedDelegationState, types.HostAccountDelegation{ValidatorAddress: key, Amount: value})
}
// sort both updatedValList and hostAccountDelegations
sort.Sort(updatedValSet)
sort.Sort(updatedDelegationState)
// returns the two updated lists
return updatedValSet, updatedDelegationState
}