-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathdelegation.go
1387 lines (1168 loc) · 42.5 KB
/
delegation.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package keeper
import (
"bytes"
"context"
"errors"
"fmt"
"time"
corestore "cosmossdk.io/core/store"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/math"
storetypes "cosmossdk.io/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
// GetDelegation returns a specific delegation.
func (k Keeper) GetDelegation(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (types.Delegation, error) {
store := k.storeService.OpenKVStore(ctx)
key := types.GetDelegationKey(delAddr, valAddr)
value, err := store.Get(key)
if err != nil {
return types.Delegation{}, err
}
if value == nil {
return types.Delegation{}, types.ErrNoDelegation
}
return types.UnmarshalDelegation(k.cdc, value)
}
// IterateAllDelegations iterates through all of the delegations.
func (k Keeper) IterateAllDelegations(ctx context.Context, cb func(delegation types.Delegation) (stop bool)) error {
store := k.storeService.OpenKVStore(ctx)
iterator, err := store.Iterator(types.DelegationKey, storetypes.PrefixEndBytes(types.DelegationKey))
if err != nil {
return err
}
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())
if cb(delegation) {
break
}
}
return nil
}
// GetAllDelegations returns all delegations used during genesis dump.
func (k Keeper) GetAllDelegations(ctx context.Context) (delegations []types.Delegation, err error) {
err = k.IterateAllDelegations(ctx, func(delegation types.Delegation) bool {
delegations = append(delegations, delegation)
return false
})
return delegations, err
}
// GetValidatorDelegations returns all delegations to a specific validator.
// Useful for querier.
func (k Keeper) GetValidatorDelegations(ctx context.Context, valAddr sdk.ValAddress) (delegations []types.Delegation, err error) {
store := k.storeService.OpenKVStore(ctx)
prefix := types.GetDelegationsByValPrefixKey(valAddr)
iterator, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix))
if err != nil {
return delegations, err
}
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var delegation types.Delegation
valAddr, delAddr, err := types.ParseDelegationsByValKey(iterator.Key())
if err != nil {
return delegations, err
}
bz, err := store.Get(types.GetDelegationKey(delAddr, valAddr))
if err != nil {
return delegations, err
}
if err := k.cdc.Unmarshal(bz, &delegation); err != nil {
return delegations, err
}
delegations = append(delegations, delegation)
}
return delegations, nil
}
// GetDelegatorDelegations returns a given amount of all the delegations from a
// delegator.
func (k Keeper) GetDelegatorDelegations(ctx context.Context, delegator sdk.AccAddress, maxRetrieve uint16) (delegations []types.Delegation, err error) {
delegations = make([]types.Delegation, maxRetrieve)
store := k.storeService.OpenKVStore(ctx)
delegatorPrefixKey := types.GetDelegationsKey(delegator)
iterator, err := store.Iterator(delegatorPrefixKey, storetypes.PrefixEndBytes(delegatorPrefixKey))
if err != nil {
return delegations, err
}
defer iterator.Close()
i := 0
for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() {
delegation, err := types.UnmarshalDelegation(k.cdc, iterator.Value())
if err != nil {
return delegations, err
}
delegations[i] = delegation
i++
}
return delegations[:i], nil // trim if the array length < maxRetrieve
}
// SetDelegation sets a delegation.
func (k Keeper) SetDelegation(ctx context.Context, delegation types.Delegation) error {
delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(delegation.DelegatorAddress)
if err != nil {
return err
}
valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
return err
}
store := k.storeService.OpenKVStore(ctx)
b := types.MustMarshalDelegation(k.cdc, delegation)
err = store.Set(types.GetDelegationKey(delegatorAddress, valAddr), b)
if err != nil {
return err
}
// set the delegation in validator delegator index
return store.Set(types.GetDelegationsByValKey(valAddr, delegatorAddress), []byte{})
}
// RemoveDelegation removes a delegation
func (k Keeper) RemoveDelegation(ctx context.Context, delegation types.Delegation) error {
delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(delegation.DelegatorAddress)
if err != nil {
return err
}
valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
return err
}
// TODO: Consider calling hooks outside of the store wrapper functions, it's unobvious.
if err := k.Hooks().BeforeDelegationRemoved(ctx, delegatorAddress, valAddr); err != nil {
return err
}
store := k.storeService.OpenKVStore(ctx)
err = store.Delete(types.GetDelegationKey(delegatorAddress, valAddr))
if err != nil {
return err
}
return store.Delete(types.GetDelegationsByValKey(valAddr, delegatorAddress))
}
// GetUnbondingDelegations returns a given amount of all the delegator unbonding-delegations.
func (k Keeper) GetUnbondingDelegations(ctx context.Context, delegator sdk.AccAddress, maxRetrieve uint16) (unbondingDelegations []types.UnbondingDelegation, err error) {
unbondingDelegations = make([]types.UnbondingDelegation, maxRetrieve)
store := k.storeService.OpenKVStore(ctx)
delegatorPrefixKey := types.GetUBDsKey(delegator)
iterator, err := store.Iterator(delegatorPrefixKey, storetypes.PrefixEndBytes(delegatorPrefixKey))
if err != nil {
return unbondingDelegations, err
}
defer iterator.Close()
i := 0
for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() {
unbondingDelegation, err := types.UnmarshalUBD(k.cdc, iterator.Value())
if err != nil {
return unbondingDelegations, err
}
unbondingDelegations[i] = unbondingDelegation
i++
}
return unbondingDelegations[:i], nil // trim if the array length < maxRetrieve
}
// GetUnbondingDelegation returns a unbonding delegation.
func (k Keeper) GetUnbondingDelegation(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (ubd types.UnbondingDelegation, err error) {
store := k.storeService.OpenKVStore(ctx)
key := types.GetUBDKey(delAddr, valAddr)
value, err := store.Get(key)
if err != nil {
return ubd, err
}
if value == nil {
return ubd, types.ErrNoUnbondingDelegation
}
return types.UnmarshalUBD(k.cdc, value)
}
// GetUnbondingDelegationsFromValidator returns all unbonding delegations from a
// particular validator.
func (k Keeper) GetUnbondingDelegationsFromValidator(ctx context.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation, err error) {
store := k.storeService.OpenKVStore(ctx)
prefix := types.GetUBDsByValIndexKey(valAddr)
iterator, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix))
if err != nil {
return ubds, err
}
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
key := types.GetUBDKeyFromValIndexKey(iterator.Key())
value, err := store.Get(key)
if err != nil {
return ubds, err
}
ubd, err := types.UnmarshalUBD(k.cdc, value)
if err != nil {
return ubds, err
}
ubds = append(ubds, ubd)
}
return ubds, nil
}
// IterateUnbondingDelegations iterates through all of the unbonding delegations.
func (k Keeper) IterateUnbondingDelegations(ctx context.Context, fn func(index int64, ubd types.UnbondingDelegation) (stop bool)) error {
store := k.storeService.OpenKVStore(ctx)
prefix := types.UnbondingDelegationKey
iterator, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix))
if err != nil {
return err
}
defer iterator.Close()
for i := int64(0); iterator.Valid(); iterator.Next() {
ubd, err := types.UnmarshalUBD(k.cdc, iterator.Value())
if err != nil {
return err
}
if stop := fn(i, ubd); stop {
break
}
i++
}
return nil
}
// GetDelegatorUnbonding returns the total amount a delegator has unbonding.
func (k Keeper) GetDelegatorUnbonding(ctx context.Context, delegator sdk.AccAddress) (math.Int, error) {
unbonding := math.ZeroInt()
err := k.IterateDelegatorUnbondingDelegations(ctx, delegator, func(ubd types.UnbondingDelegation) bool {
for _, entry := range ubd.Entries {
unbonding = unbonding.Add(entry.Balance)
}
return false
})
return unbonding, err
}
// IterateDelegatorUnbondingDelegations iterates through a delegator's unbonding delegations.
func (k Keeper) IterateDelegatorUnbondingDelegations(ctx context.Context, delegator sdk.AccAddress, cb func(ubd types.UnbondingDelegation) (stop bool)) error {
store := k.storeService.OpenKVStore(ctx)
prefix := types.GetUBDsKey(delegator)
iterator, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix))
if err != nil {
return err
}
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
ubd, err := types.UnmarshalUBD(k.cdc, iterator.Value())
if err != nil {
return err
}
if cb(ubd) {
break
}
}
return nil
}
// GetDelegatorBonded returs the total amount a delegator has bonded.
func (k Keeper) GetDelegatorBonded(ctx context.Context, delegator sdk.AccAddress) (math.Int, error) {
bonded := math.LegacyZeroDec()
err := k.IterateDelegatorDelegations(ctx, delegator, func(delegation types.Delegation) bool {
validatorAddr, err := k.validatorAddressCodec.StringToBytes(delegation.ValidatorAddress)
if err != nil {
panic(err) // shouldn't happen
}
validator, err := k.GetValidator(ctx, validatorAddr)
if err == nil {
shares := delegation.Shares
tokens := validator.TokensFromSharesTruncated(shares)
bonded = bonded.Add(tokens)
}
return false
})
return bonded.RoundInt(), err
}
// IterateDelegatorDelegations iterates through one delegator's delegations.
func (k Keeper) IterateDelegatorDelegations(ctx context.Context, delegator sdk.AccAddress, cb func(delegation types.Delegation) (stop bool)) error {
store := k.storeService.OpenKVStore(ctx)
prefix := types.GetDelegationsKey(delegator)
iterator, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix))
if err != nil {
return err
}
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
delegation, err := types.UnmarshalDelegation(k.cdc, iterator.Value())
if err != nil {
return err
}
if cb(delegation) {
break
}
}
return nil
}
// IterateDelegatorRedelegations iterates through one delegator's redelegations.
func (k Keeper) IterateDelegatorRedelegations(ctx context.Context, delegator sdk.AccAddress, cb func(red types.Redelegation) (stop bool)) error {
store := k.storeService.OpenKVStore(ctx)
delegatorPrefixKey := types.GetREDsKey(delegator)
iterator, err := store.Iterator(delegatorPrefixKey, storetypes.PrefixEndBytes(delegatorPrefixKey))
if err != nil {
return err
}
for ; iterator.Valid(); iterator.Next() {
red, err := types.UnmarshalRED(k.cdc, iterator.Value())
if err != nil {
return err
}
if cb(red) {
break
}
}
return nil
}
// HasMaxUnbondingDelegationEntries checks if unbonding delegation has maximum number of entries.
func (k Keeper) HasMaxUnbondingDelegationEntries(ctx context.Context, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (bool, error) {
ubd, err := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr)
if err != nil && !errors.Is(err, types.ErrNoUnbondingDelegation) {
return false, err
}
maxEntries, err := k.MaxEntries(ctx)
if err != nil {
return false, err
}
return len(ubd.Entries) >= int(maxEntries), nil
}
// SetUnbondingDelegation sets the unbonding delegation and associated index.
func (k Keeper) SetUnbondingDelegation(ctx context.Context, ubd types.UnbondingDelegation) error {
delAddr, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress)
if err != nil {
return err
}
store := k.storeService.OpenKVStore(ctx)
bz := types.MustMarshalUBD(k.cdc, ubd)
valAddr, err := k.validatorAddressCodec.StringToBytes(ubd.ValidatorAddress)
if err != nil {
return err
}
key := types.GetUBDKey(delAddr, valAddr)
err = store.Set(key, bz)
if err != nil {
return err
}
return store.Set(types.GetUBDByValIndexKey(delAddr, valAddr), []byte{}) // index, store empty bytes
}
// RemoveUnbondingDelegation removes the unbonding delegation object and associated index.
func (k Keeper) RemoveUnbondingDelegation(ctx context.Context, ubd types.UnbondingDelegation) error {
delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress)
if err != nil {
return err
}
store := k.storeService.OpenKVStore(ctx)
addr, err := k.validatorAddressCodec.StringToBytes(ubd.ValidatorAddress)
if err != nil {
return err
}
key := types.GetUBDKey(delegatorAddress, addr)
err = store.Delete(key)
if err != nil {
return err
}
return store.Delete(types.GetUBDByValIndexKey(delegatorAddress, addr))
}
// SetUnbondingDelegationEntry adds an entry to the unbonding delegation at
// the given addresses. It creates the unbonding delegation if it does not exist.
func (k Keeper) SetUnbondingDelegationEntry(
ctx context.Context, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress,
creationHeight int64, minTime time.Time, balance math.Int,
) (types.UnbondingDelegation, error) {
id, err := k.IncrementUnbondingID(ctx)
if err != nil {
return types.UnbondingDelegation{}, err
}
isNewUbdEntry := true
ubd, err := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr)
if err == nil {
isNewUbdEntry = ubd.AddEntry(creationHeight, minTime, balance, id)
} else if errors.Is(err, types.ErrNoUnbondingDelegation) {
ubd = types.NewUnbondingDelegation(delegatorAddr, validatorAddr, creationHeight, minTime, balance, id, k.validatorAddressCodec, k.authKeeper.AddressCodec())
} else {
return ubd, err
}
if err = k.SetUnbondingDelegation(ctx, ubd); err != nil {
return ubd, err
}
// only call the hook for new entries since
// calls to AfterUnbondingInitiated are not idempotent
if isNewUbdEntry {
// Add to the UBDByUnbondingOp index to look up the UBD by the UBDE ID
if err = k.SetUnbondingDelegationByUnbondingID(ctx, ubd, id); err != nil {
return ubd, err
}
if err := k.Hooks().AfterUnbondingInitiated(ctx, id); err != nil {
k.Logger(ctx).Error("failed to call after unbonding initiated hook", "error", err)
}
}
return ubd, nil
}
// unbonding delegation queue timeslice operations
// GetUBDQueueTimeSlice gets a specific unbonding queue timeslice. A timeslice
// is a slice of DVPairs corresponding to unbonding delegations that expire at a
// certain time.
func (k Keeper) GetUBDQueueTimeSlice(ctx context.Context, timestamp time.Time) (dvPairs []types.DVPair, err error) {
store := k.storeService.OpenKVStore(ctx)
bz, err := store.Get(types.GetUnbondingDelegationTimeKey(timestamp))
if bz == nil || err != nil {
return []types.DVPair{}, err
}
pairs := types.DVPairs{}
err = k.cdc.Unmarshal(bz, &pairs)
return pairs.Pairs, err
}
// SetUBDQueueTimeSlice sets a specific unbonding queue timeslice.
func (k Keeper) SetUBDQueueTimeSlice(ctx context.Context, timestamp time.Time, keys []types.DVPair) error {
store := k.storeService.OpenKVStore(ctx)
bz, err := k.cdc.Marshal(&types.DVPairs{Pairs: keys})
if err != nil {
return err
}
return store.Set(types.GetUnbondingDelegationTimeKey(timestamp), bz)
}
// InsertUBDQueue inserts an unbonding delegation to the appropriate timeslice
// in the unbonding queue.
func (k Keeper) InsertUBDQueue(ctx context.Context, ubd types.UnbondingDelegation, completionTime time.Time) error {
dvPair := types.DVPair{DelegatorAddress: ubd.DelegatorAddress, ValidatorAddress: ubd.ValidatorAddress}
timeSlice, err := k.GetUBDQueueTimeSlice(ctx, completionTime)
if err != nil {
return err
}
if len(timeSlice) == 0 {
if err = k.SetUBDQueueTimeSlice(ctx, completionTime, []types.DVPair{dvPair}); err != nil {
return err
}
return nil
}
timeSlice = append(timeSlice, dvPair)
return k.SetUBDQueueTimeSlice(ctx, completionTime, timeSlice)
}
// UBDQueueIterator returns all the unbonding queue timeslices from time 0 until endTime.
func (k Keeper) UBDQueueIterator(ctx context.Context, endTime time.Time) (corestore.Iterator, error) {
store := k.storeService.OpenKVStore(ctx)
return store.Iterator(types.UnbondingQueueKey,
storetypes.InclusiveEndBytes(types.GetUnbondingDelegationTimeKey(endTime)))
}
// DequeueAllMatureUBDQueue returns a concatenated list of all the timeslices inclusively previous to
// currTime, and deletes the timeslices from the queue.
func (k Keeper) DequeueAllMatureUBDQueue(ctx context.Context, currTime time.Time) (matureUnbonds []types.DVPair, err error) {
store := k.storeService.OpenKVStore(ctx)
// gets an iterator for all timeslices from time 0 until the current Blockheader time
unbondingTimesliceIterator, err := k.UBDQueueIterator(ctx, currTime)
if err != nil {
return matureUnbonds, err
}
defer unbondingTimesliceIterator.Close()
for ; unbondingTimesliceIterator.Valid(); unbondingTimesliceIterator.Next() {
timeslice := types.DVPairs{}
value := unbondingTimesliceIterator.Value()
if err = k.cdc.Unmarshal(value, ×lice); err != nil {
return matureUnbonds, err
}
matureUnbonds = append(matureUnbonds, timeslice.Pairs...)
if err = store.Delete(unbondingTimesliceIterator.Key()); err != nil {
return matureUnbonds, err
}
}
return matureUnbonds, nil
}
// GetRedelegations returns a given amount of all the delegator redelegations.
func (k Keeper) GetRedelegations(ctx context.Context, delegator sdk.AccAddress, maxRetrieve uint16) (redelegations []types.Redelegation, err error) {
redelegations = make([]types.Redelegation, maxRetrieve)
store := k.storeService.OpenKVStore(ctx)
delegatorPrefixKey := types.GetREDsKey(delegator)
iterator, err := store.Iterator(delegatorPrefixKey, storetypes.PrefixEndBytes(delegatorPrefixKey))
if err != nil {
return nil, err
}
i := 0
for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() {
redelegation, err := types.UnmarshalRED(k.cdc, iterator.Value())
if err != nil {
return nil, err
}
redelegations[i] = redelegation
i++
}
return redelegations[:i], nil // trim if the array length < maxRetrieve
}
// GetRedelegation returns a redelegation.
func (k Keeper) GetRedelegation(ctx context.Context, delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (red types.Redelegation, err error) {
store := k.storeService.OpenKVStore(ctx)
key := types.GetREDKey(delAddr, valSrcAddr, valDstAddr)
value, err := store.Get(key)
if err != nil {
return red, err
}
if value == nil {
return red, types.ErrNoRedelegation
}
return types.UnmarshalRED(k.cdc, value)
}
// GetRedelegationsFromSrcValidator returns all redelegations from a particular
// validator.
func (k Keeper) GetRedelegationsFromSrcValidator(ctx context.Context, valAddr sdk.ValAddress) (reds []types.Redelegation, err error) {
store := k.storeService.OpenKVStore(ctx)
prefix := types.GetREDsFromValSrcIndexKey(valAddr)
iterator, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix))
if err != nil {
return nil, err
}
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
key := types.GetREDKeyFromValSrcIndexKey(iterator.Key())
value, err := store.Get(key)
if err != nil {
return nil, err
}
red, err := types.UnmarshalRED(k.cdc, value)
if err != nil {
return nil, err
}
reds = append(reds, red)
}
return reds, nil
}
// HasReceivingRedelegation checks if validator is receiving a redelegation.
func (k Keeper) HasReceivingRedelegation(ctx context.Context, delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) (bool, error) {
store := k.storeService.OpenKVStore(ctx)
prefix := types.GetREDsByDelToValDstIndexKey(delAddr, valDstAddr)
iterator, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix))
if err != nil {
return false, err
}
defer iterator.Close()
return iterator.Valid(), nil
}
// HasMaxRedelegationEntries checks if the redelegation entries reached maximum limit.
func (k Keeper) HasMaxRedelegationEntries(ctx context.Context, delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress) (bool, error) {
red, err := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr)
if err != nil {
if err == types.ErrNoRedelegation {
return false, nil
}
return false, err
}
maxEntries, err := k.MaxEntries(ctx)
if err != nil {
return false, err
}
return len(red.Entries) >= int(maxEntries), nil
}
// SetRedelegation sets a redelegation and associated index.
func (k Keeper) SetRedelegation(ctx context.Context, red types.Redelegation) error {
delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(red.DelegatorAddress)
if err != nil {
return err
}
store := k.storeService.OpenKVStore(ctx)
bz := types.MustMarshalRED(k.cdc, red)
valSrcAddr, err := k.validatorAddressCodec.StringToBytes(red.ValidatorSrcAddress)
if err != nil {
return err
}
valDestAddr, err := k.validatorAddressCodec.StringToBytes(red.ValidatorDstAddress)
if err != nil {
return err
}
key := types.GetREDKey(delegatorAddress, valSrcAddr, valDestAddr)
if err = store.Set(key, bz); err != nil {
return err
}
if err = store.Set(types.GetREDByValSrcIndexKey(delegatorAddress, valSrcAddr, valDestAddr), []byte{}); err != nil {
return err
}
return store.Set(types.GetREDByValDstIndexKey(delegatorAddress, valSrcAddr, valDestAddr), []byte{})
}
// SetRedelegationEntry adds an entry to the unbonding delegation at the given
// addresses. It creates the unbonding delegation if it does not exist.
func (k Keeper) SetRedelegationEntry(ctx context.Context,
delegatorAddr sdk.AccAddress, validatorSrcAddr,
validatorDstAddr sdk.ValAddress, creationHeight int64,
minTime time.Time, balance math.Int,
sharesSrc, sharesDst math.LegacyDec,
) (types.Redelegation, error) {
id, err := k.IncrementUnbondingID(ctx)
if err != nil {
return types.Redelegation{}, err
}
red, err := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr)
if err == nil {
red.AddEntry(creationHeight, minTime, balance, sharesDst, id)
} else if errors.Is(err, types.ErrNoRedelegation) {
red = types.NewRedelegation(delegatorAddr, validatorSrcAddr,
validatorDstAddr, creationHeight, minTime, balance, sharesDst, id, k.validatorAddressCodec, k.authKeeper.AddressCodec())
} else {
return types.Redelegation{}, err
}
if err = k.SetRedelegation(ctx, red); err != nil {
return types.Redelegation{}, err
}
// Add to the UBDByEntry index to look up the UBD by the UBDE ID
if err = k.SetRedelegationByUnbondingID(ctx, red, id); err != nil {
return types.Redelegation{}, err
}
if err := k.Hooks().AfterUnbondingInitiated(ctx, id); err != nil {
k.Logger(ctx).Error("failed to call after unbonding initiated hook", "error", err)
// TODO (Facu): Should we return here? We are ignoring this error
}
return red, nil
}
// IterateRedelegations iterates through all redelegations.
func (k Keeper) IterateRedelegations(ctx context.Context, fn func(index int64, red types.Redelegation) (stop bool)) error {
store := k.storeService.OpenKVStore(ctx)
iterator, err := store.Iterator(types.RedelegationKey, storetypes.PrefixEndBytes(types.RedelegationKey))
if err != nil {
return err
}
defer iterator.Close()
for i := int64(0); iterator.Valid(); iterator.Next() {
red, err := types.UnmarshalRED(k.cdc, iterator.Value())
if err != nil {
return err
}
if stop := fn(i, red); stop {
break
}
i++
}
return nil
}
// RemoveRedelegation removes a redelegation object and associated index.
func (k Keeper) RemoveRedelegation(ctx context.Context, red types.Redelegation) error {
delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(red.DelegatorAddress)
if err != nil {
return err
}
store := k.storeService.OpenKVStore(ctx)
valSrcAddr, err := k.validatorAddressCodec.StringToBytes(red.ValidatorSrcAddress)
if err != nil {
return err
}
valDestAddr, err := k.validatorAddressCodec.StringToBytes(red.ValidatorDstAddress)
if err != nil {
return err
}
redKey := types.GetREDKey(delegatorAddress, valSrcAddr, valDestAddr)
if err = store.Delete(redKey); err != nil {
return err
}
if err = store.Delete(types.GetREDByValSrcIndexKey(delegatorAddress, valSrcAddr, valDestAddr)); err != nil {
return err
}
return store.Delete(types.GetREDByValDstIndexKey(delegatorAddress, valSrcAddr, valDestAddr))
}
// redelegation queue timeslice operations
// GetRedelegationQueueTimeSlice gets a specific redelegation queue timeslice. A
// timeslice is a slice of DVVTriplets corresponding to redelegations that
// expire at a certain time.
func (k Keeper) GetRedelegationQueueTimeSlice(ctx context.Context, timestamp time.Time) (dvvTriplets []types.DVVTriplet, err error) {
store := k.storeService.OpenKVStore(ctx)
bz, err := store.Get(types.GetRedelegationTimeKey(timestamp))
if err != nil {
return nil, err
}
if bz == nil {
return []types.DVVTriplet{}, nil
}
triplets := types.DVVTriplets{}
err = k.cdc.Unmarshal(bz, &triplets)
if err != nil {
return nil, err
}
return triplets.Triplets, nil
}
// SetRedelegationQueueTimeSlice sets a specific redelegation queue timeslice.
func (k Keeper) SetRedelegationQueueTimeSlice(ctx context.Context, timestamp time.Time, keys []types.DVVTriplet) error {
store := k.storeService.OpenKVStore(ctx)
bz, err := k.cdc.Marshal(&types.DVVTriplets{Triplets: keys})
if err != nil {
return err
}
return store.Set(types.GetRedelegationTimeKey(timestamp), bz)
}
// InsertRedelegationQueue insert an redelegation delegation to the appropriate
// timeslice in the redelegation queue.
func (k Keeper) InsertRedelegationQueue(ctx context.Context, red types.Redelegation, completionTime time.Time) error {
timeSlice, err := k.GetRedelegationQueueTimeSlice(ctx, completionTime)
if err != nil {
return err
}
dvvTriplet := types.DVVTriplet{
DelegatorAddress: red.DelegatorAddress,
ValidatorSrcAddress: red.ValidatorSrcAddress,
ValidatorDstAddress: red.ValidatorDstAddress,
}
if len(timeSlice) == 0 {
return k.SetRedelegationQueueTimeSlice(ctx, completionTime, []types.DVVTriplet{dvvTriplet})
}
timeSlice = append(timeSlice, dvvTriplet)
return k.SetRedelegationQueueTimeSlice(ctx, completionTime, timeSlice)
}
// RedelegationQueueIterator returns all the redelegation queue timeslices from
// time 0 until endTime.
func (k Keeper) RedelegationQueueIterator(ctx context.Context, endTime time.Time) (storetypes.Iterator, error) {
store := k.storeService.OpenKVStore(ctx)
return store.Iterator(types.RedelegationQueueKey, storetypes.InclusiveEndBytes(types.GetRedelegationTimeKey(endTime)))
}
// DequeueAllMatureRedelegationQueue returns a concatenated list of all the
// timeslices inclusively previous to currTime, and deletes the timeslices from
// the queue.
func (k Keeper) DequeueAllMatureRedelegationQueue(ctx context.Context, currTime time.Time) (matureRedelegations []types.DVVTriplet, err error) {
store := k.storeService.OpenKVStore(ctx)
// gets an iterator for all timeslices from time 0 until the current Blockheader time
sdkCtx := sdk.UnwrapSDKContext(ctx)
redelegationTimesliceIterator, err := k.RedelegationQueueIterator(ctx, sdkCtx.HeaderInfo().Time)
if err != nil {
return nil, err
}
defer redelegationTimesliceIterator.Close()
for ; redelegationTimesliceIterator.Valid(); redelegationTimesliceIterator.Next() {
timeslice := types.DVVTriplets{}
value := redelegationTimesliceIterator.Value()
if err = k.cdc.Unmarshal(value, ×lice); err != nil {
return nil, err
}
matureRedelegations = append(matureRedelegations, timeslice.Triplets...)
if err = store.Delete(redelegationTimesliceIterator.Key()); err != nil {
return nil, err
}
}
return matureRedelegations, nil
}
// Delegate performs a delegation, set/update everything necessary within the store.
// tokenSrc indicates the bond status of the incoming funds.
func (k Keeper) Delegate(
ctx context.Context, delAddr sdk.AccAddress, bondAmt math.Int, tokenSrc types.BondStatus,
validator types.Validator, subtractAccount bool,
) (newShares math.LegacyDec, err error) {
// In some situations, the exchange rate becomes invalid, e.g. if
// Validator loses all tokens due to slashing. In this case,
// make all future delegations invalid.
if validator.InvalidExRate() {
return math.LegacyZeroDec(), types.ErrDelegatorShareExRateInvalid
}
valbz, err := k.ValidatorAddressCodec().StringToBytes(validator.GetOperator())
if err != nil {
return math.LegacyZeroDec(), err
}
// Get or create the delegation object and call the appropriate hook if present
delegation, err := k.GetDelegation(ctx, delAddr, valbz)
if err == nil {
// found
err = k.Hooks().BeforeDelegationSharesModified(ctx, delAddr, valbz)
} else if errors.Is(err, types.ErrNoDelegation) {
// not found
delAddrStr, err1 := k.authKeeper.AddressCodec().BytesToString(delAddr)
if err1 != nil {
return math.LegacyDec{}, err1
}
delegation = types.NewDelegation(delAddrStr, validator.GetOperator(), math.LegacyZeroDec())
err = k.Hooks().BeforeDelegationCreated(ctx, delAddr, valbz)
} else {
return math.LegacyZeroDec(), err
}
if err != nil {
return math.LegacyZeroDec(), err
}
// if subtractAccount is true then we are
// performing a delegation and not a redelegation, thus the source tokens are
// all non bonded
if subtractAccount {
if tokenSrc == types.Bonded {
panic("delegation token source cannot be bonded")
}
var sendName string
switch {
case validator.IsBonded():
sendName = types.BondedPoolName
case validator.IsUnbonding(), validator.IsUnbonded():
sendName = types.NotBondedPoolName
default:
panic("invalid validator status")
}
bondDenom, err := k.BondDenom(ctx)
if err != nil {
return math.LegacyDec{}, err
}
coins := sdk.NewCoins(sdk.NewCoin(bondDenom, bondAmt))
if err := k.bankKeeper.DelegateCoinsFromAccountToModule(ctx, delAddr, sendName, coins); err != nil {
return math.LegacyDec{}, err
}
} else {
// potentially transfer tokens between pools, if
switch {
case tokenSrc == types.Bonded && validator.IsBonded():
// do nothing
case (tokenSrc == types.Unbonded || tokenSrc == types.Unbonding) && !validator.IsBonded():
// do nothing
case (tokenSrc == types.Unbonded || tokenSrc == types.Unbonding) && validator.IsBonded():
// transfer pools
err = k.notBondedTokensToBonded(ctx, bondAmt)
if err != nil {
return math.LegacyDec{}, err
}
case tokenSrc == types.Bonded && !validator.IsBonded():
// transfer pools
err = k.bondedTokensToNotBonded(ctx, bondAmt)
if err != nil {
return math.LegacyDec{}, err
}
default:
panic("unknown token source bond status")
}
}
_, newShares, err = k.AddValidatorTokensAndShares(ctx, validator, bondAmt)
if err != nil {
return newShares, err
}
// Update delegation
delegation.Shares = delegation.Shares.Add(newShares)
if err = k.SetDelegation(ctx, delegation); err != nil {
return newShares, err
}
// Call the after-modification hook
if err := k.Hooks().AfterDelegationModified(ctx, delAddr, valbz); err != nil {
return newShares, err
}
return newShares, nil
}
// Unbond unbonds a particular delegation and perform associated store operations.
func (k Keeper) Unbond(
ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, shares math.LegacyDec,
) (amount math.Int, err error) {
// check if a delegation object exists in the store
delegation, err := k.GetDelegation(ctx, delAddr, valAddr)
if errors.Is(err, types.ErrNoDelegation) {
return amount, types.ErrNoDelegatorForAddress
} else if err != nil {
return amount, err
}
// call the before-delegation-modified hook
if err := k.Hooks().BeforeDelegationSharesModified(ctx, delAddr, valAddr); err != nil {
return amount, err
}
// ensure that we have enough shares to remove
if delegation.Shares.LT(shares) {
return amount, errorsmod.Wrap(types.ErrNotEnoughDelegationShares, delegation.Shares.String())
}
// get validator
validator, err := k.GetValidator(ctx, valAddr)
if err != nil {
return amount, err
}
// subtract shares from delegation