-
Notifications
You must be signed in to change notification settings - Fork 4
/
common.go
1330 lines (1178 loc) · 40.7 KB
/
common.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 chain
import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"math/big"
"sort"
"strings"
"time"
"github.com/cosmos/cosmos-sdk/types"
errType "github.com/cosmos/cosmos-sdk/types/errors"
xAuthTypes "github.com/cosmos/cosmos-sdk/x/auth/types"
xBankTypes "github.com/cosmos/cosmos-sdk/x/bank/types"
xDistriTypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
xStakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types"
icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types"
hubClient "github.com/stafihub/cosmos-relay-sdk/client"
"github.com/stafihub/rtoken-relay-core/common/core"
"github.com/stafihub/rtoken-relay-core/common/log"
"github.com/stafihub/rtoken-relay-core/common/utils"
stafiHubXLedgerTypes "github.com/stafihub/stafihub/x/ledger/types"
stafiHubXRValidatorTypes "github.com/stafihub/stafihub/x/rvalidator/types"
)
const (
UnSignedTxTypeUnSpecified = 0
UnSignedTxTypeBondEqualUnbondWithdraw = 1
UnSignedTxTypeDelegate = 2
UnSignedTxTypeUnDelegateAndWithdraw = 3
UnSignedTxTypeSkipAndWithdraw = 4
)
var (
ErrNoOutPuts = errors.New("outputs length is zero")
ErrNoRewardNeedDelegate = fmt.Errorf("no tx reward need delegate")
ErrNotFound = errors.New("NotFound")
ErrUnknownQueryPath = errors.New("UnknownQueryPath")
)
var (
TxTypeHandleEraPoolUpdatedEvent = "handleEraPoolUpdatedEvent"
TxTypeHandleBondReportedEvent = "handleBondReportedEvent"
TxTypeHandleActiveReportedEvent = "handleActiveReportedEvent"
TxTypeHandleRValidatorUpdatedEvent = "handleRValidatorUpdatedEvent"
)
var ValidatorBondCapDisabled = types.NewDecFromInt(types.NewInt(-1))
func GetMemo(era uint32, txType string) string {
return fmt.Sprintf("%d:%s", era, txType)
}
func GetValidatorUpdatedMemo(era uint32, cycleVersion, cycleNumber uint64) string {
return fmt.Sprintf("%d:%d:%d:%s", era, cycleVersion, cycleNumber, TxTypeHandleRValidatorUpdatedEvent)
}
func ShotIdToArray(shotId string) ([32]byte, error) {
shotIdBts, err := hex.DecodeString(shotId)
if err != nil {
return [32]byte{}, err
}
var shotIdArray [32]byte
copy(shotIdArray[:], shotIdBts)
return shotIdArray, nil
}
func GetBondUnBondProposalId(shotId [32]byte, bond, unbond *big.Int, index uint8) []byte {
proposalId := make([]byte, 65)
copy(proposalId, shotId[:])
bondBts := make([]byte, 16)
bond.FillBytes(bondBts)
copy(proposalId[32:], bondBts)
unbondBts := make([]byte, 16)
unbond.FillBytes(unbondBts)
copy(proposalId[48:], unbondBts)
proposalId[64] = index
return proposalId
}
func ParseBondUnBondProposalId(content []byte) (shotId [32]byte, bond, unbond *big.Int, index uint8, err error) {
if len(content) != 65 {
err = errors.New("cont length is not right")
return
}
copy(shotId[:], content[:32])
bond = new(big.Int).SetBytes(content[32:48])
unbond = new(big.Int).SetBytes(content[48:64])
index = content[64]
return
}
func GetClaimRewardProposalId(shotId [32]byte, height uint64, index uint8) []byte {
proposalId := make([]byte, 41)
copy(proposalId, shotId[:])
binary.BigEndian.PutUint64(proposalId[32:], height)
proposalId[40] = index
return proposalId
}
func ParseClaimRewardProposalId(content []byte) (shotId [32]byte, height uint64, index uint8, err error) {
if len(content) != 41 {
err = errors.New("cont length is not right")
return
}
copy(shotId[:], content[:32])
height = binary.BigEndian.Uint64(content[32:])
index = content[40]
return
}
func GetTransferProposalId(unSignTxHash [32]byte, index uint8) []byte {
proposalId := make([]byte, 33)
copy(proposalId, unSignTxHash[:])
proposalId[32] = index
return proposalId
}
func GetValidatorUpdateProposalId(content []byte, index uint8) []byte {
hash := utils.BlakeTwo256(content)
return append(hash[:], index)
}
// ensue every validator claim reward
// if bond == unbond: if no delegation before, return errNoMsgs, else gen withdraw tx
// if bond > unbond: gen delegate tx
// if bond < unbond: gen undelegate+withdraw tx or withdraw tx when no available vals for unbonding
func GetBondUnbondWithdrawUnsignedTxWithTargets(client *hubClient.Client, bond, unbond, minUnDelegateAmount *big.Int,
poolAddr types.AccAddress, height int64, targets []types.ValAddress, memo string) (unSignedTx []byte, unSignedTxType int, err error) {
done := core.UseSdkConfigContext(client.GetAccountPrefix())
poolAddrStr := poolAddr.String()
done()
switch bond.Cmp(unbond) {
case 0:
// return errnoMsgs if total delegate amount <= 10000
var delegationRes *xStakingTypes.QueryDelegatorDelegationsResponse
delegationRes, err = client.QueryDelegations(poolAddr, height)
if err != nil {
if strings.Contains(err.Error(), "unable to find delegations for address") {
err = hubClient.ErrNoMsgs
return
} else {
return
}
}
totalDelegateAmount := big.NewInt(0)
for _, res := range delegationRes.DelegationResponses {
totalDelegateAmount = new(big.Int).Add(totalDelegateAmount, res.Balance.Amount.BigInt())
}
if totalDelegateAmount.Cmp(big.NewInt(1e4)) <= 0 {
err = hubClient.ErrNoMsgs
return
}
unSignedTx, err = client.GenMultiSigRawWithdrawAllRewardTxWithMemo(
poolAddr,
height,
memo)
unSignedTxType = UnSignedTxTypeBondEqualUnbondWithdraw
return
case 1:
valAddrs := targets
valAddrsLen := len(valAddrs)
//check valAddrs length
if valAddrsLen == 0 {
return nil, 0, fmt.Errorf("no target valAddrs, pool: %s", poolAddrStr)
}
val := bond.Sub(bond, unbond)
val = val.Div(val, big.NewInt(int64(valAddrsLen)))
unSignedTx, err = client.GenMultiSigRawDelegateTxWithMemo(
poolAddr,
valAddrs,
types.NewCoin(client.GetDenom(), types.NewIntFromBigInt(val)),
memo)
unSignedTxType = UnSignedTxTypeDelegate
return
case -1:
// skip and withdraw if less than min undelegate amount
if minUnDelegateAmount.Sign() > 0 && new(big.Int).Sub(unbond, bond).Cmp(minUnDelegateAmount) < 0 {
unSignedTx, err = client.GenMultiSigRawWithdrawAllRewardTxWithMemo(
poolAddr,
height,
memo)
unSignedTxType = UnSignedTxTypeSkipAndWithdraw
return
}
var deleRes *xStakingTypes.QueryDelegatorDelegationsResponse
deleRes, err = client.QueryDelegations(poolAddr, height)
if err != nil {
return nil, 0, fmt.Errorf("QueryDelegations failed: %s", err)
}
totalDelegateAmount := types.NewInt(0)
valAddrs := make([]types.ValAddress, 0)
deleAmount := make(map[string]types.Int)
//get validators amount>=3
for _, dele := range deleRes.GetDelegationResponses() {
//filter old validator,we say validator is old if amount < 3 uatom
if dele.GetBalance().Amount.LT(types.NewInt(3)) {
continue
}
done := core.UseSdkConfigContext(client.GetAccountPrefix())
valAddr, err := types.ValAddressFromBech32(dele.GetDelegation().ValidatorAddress)
if err != nil {
done()
return nil, 0, err
}
valAddrs = append(valAddrs, valAddr)
totalDelegateAmount = totalDelegateAmount.Add(dele.GetBalance().Amount)
deleAmount[valAddr.String()] = dele.GetBalance().Amount
done()
}
//check valAddrs length
valAddrsLen := len(valAddrs)
if valAddrsLen == 0 {
return nil, 0, fmt.Errorf("no valAddrs, pool: %s", poolAddr)
}
//check totalDelegateAmount
if totalDelegateAmount.LT(types.NewInt(3 * int64(valAddrsLen))) {
return nil, 0, fmt.Errorf("validators have no reserve value to unbond")
}
//make val <= totalDelegateAmount-3*len and we reserve 3 uatom
val := new(big.Int).Sub(unbond, bond)
willUsetotalDelegateAmount := totalDelegateAmount.Sub(types.NewInt(3 * int64(valAddrsLen)))
if val.Cmp(willUsetotalDelegateAmount.BigInt()) > 0 {
return nil, 0, fmt.Errorf("no enough value can be used to unbond, pool: %s", poolAddr)
}
willUseTotalVal := types.NewIntFromBigInt(val)
//remove validator who's unbonding >= 7
canUseValAddrs := make([]types.ValAddress, 0)
for _, val := range valAddrs {
res, err := client.QueryUnbondingDelegation(poolAddr, val, height)
if err != nil {
// unbonding empty case
if strings.Contains(err.Error(), "NotFound") {
canUseValAddrs = append(canUseValAddrs, val)
continue
}
return nil, 0, err
}
if len(res.GetUnbond().Entries) < 7 {
canUseValAddrs = append(canUseValAddrs, val)
}
}
valAddrs = canUseValAddrs
if len(valAddrs) == 0 {
unSignedTx, err = client.GenMultiSigRawWithdrawAllRewardTxWithMemo(
poolAddr,
height,
memo)
unSignedTxType = UnSignedTxTypeSkipAndWithdraw
return
}
//sort validators by delegate amount
done := core.UseSdkConfigContext(client.GetAccountPrefix())
sort.Slice(valAddrs, func(i int, j int) bool {
return deleAmount[valAddrs[i].String()].
GT(deleAmount[valAddrs[j].String()])
})
//choose validators to be undelegated
choosedVals := make([]types.ValAddress, 0)
choosedAmount := make(map[string]types.Int)
selectedAmount := types.NewInt(0)
enough := false
for _, validator := range valAddrs {
nowValMaxUnDeleAmount := deleAmount[validator.String()].Sub(types.NewInt(3))
//if we find all validators needed
if selectedAmount.Add(nowValMaxUnDeleAmount).GTE(willUseTotalVal) {
willUseChoosedAmount := willUseTotalVal.Sub(selectedAmount)
choosedVals = append(choosedVals, validator)
choosedAmount[validator.String()] = willUseChoosedAmount
enough = true
break
}
choosedVals = append(choosedVals, validator)
choosedAmount[validator.String()] = nowValMaxUnDeleAmount
selectedAmount = selectedAmount.Add(nowValMaxUnDeleAmount)
}
if !enough {
done()
unSignedTx, err = client.GenMultiSigRawWithdrawAllRewardTxWithMemo(
poolAddr,
height,
memo)
unSignedTxType = UnSignedTxTypeSkipAndWithdraw
return
}
// filter withdraw validators
withdrawVals := make([]types.ValAddress, 0)
for valAddressStr := range deleAmount {
if _, exist := choosedAmount[valAddressStr]; !exist {
valAddr, err := types.ValAddressFromBech32(valAddressStr)
if err != nil {
done()
return nil, 0, err
}
withdrawVals = append(withdrawVals, valAddr)
}
}
sort.Slice(withdrawVals, func(i int, j int) bool {
return bytes.Compare(withdrawVals[i].Bytes(), withdrawVals[j].Bytes()) > 0
})
done()
unSignedTx, err = client.GenMultiSigRawUnDelegateWithdrawTxWithMemo(
poolAddr,
choosedVals,
choosedAmount,
withdrawVals,
memo)
unSignedTxType = UnSignedTxTypeUnDelegateAndWithdraw
return
default:
return nil, 0, fmt.Errorf("unreached case err")
}
}
// ensue every validator claim reward
// if bond == unbond: if no delegation before, return errNoMsgs, else gen withdraw tx
// if bond > unbond: gen delegate tx
// if bond < unbond: gen undelegate+withdraw tx
func GetBondUnbondWithdrawMsgsWithTargets(client *hubClient.Client, bond, unbond *big.Int,
poolAddr types.AccAddress, height int64, targets []types.ValAddress, logger log.Logger) (msgs []types.Msg, unSignedType int, err error) {
logger.Debug("GetBondUnbondWithdrawMsgsWithTargets", "targets", targets, "height", height, "bond", bond.String(), "unbond", unbond.String())
done := core.UseSdkConfigContext(client.GetAccountPrefix())
poolAddrStr := poolAddr.String()
done()
switch bond.Cmp(unbond) {
case 0:
// return errnoMsgs if no delegation before
var delegationRes *xStakingTypes.QueryDelegatorDelegationsResponse
delegationRes, err = client.QueryDelegations(poolAddr, height)
if err != nil {
if strings.Contains(err.Error(), "unable to find delegations for address") {
err = hubClient.ErrNoMsgs
return
} else {
return
}
}
if len(delegationRes.DelegationResponses) == 0 {
err = hubClient.ErrNoMsgs
return
}
msgs, err = client.GenWithdrawAllRewardMsgs(
poolAddr,
height)
unSignedType = 0
return
case 1:
var valAddrs []types.ValAddress
totalShouldBondAmount := types.NewIntFromBigInt(new(big.Int).Sub(bond, unbond))
// lsm case
if client.GetDenom() == "uatom" {
logger.Debug("lsm case")
var stakingParams *xStakingTypes.QueryParamsResponse
stakingParams, err = client.QueryStakingParams()
if err != nil {
return
}
poolRes, poolErr := client.QueryPool(height)
if poolErr != nil {
err = poolErr
return
}
totalLiquidStakedAmountRes, lsErr := client.TotalLiquidStaked(height)
if lsErr != nil {
err = lsErr
return
}
totalLiquidStakedAmount, ok := types.NewIntFromString(totalLiquidStakedAmountRes.Tokens)
if !ok {
err = fmt.Errorf("parse totalLiquidStakedAmount %s failed", totalLiquidStakedAmountRes.Tokens)
return
}
totalStakedAmount := poolRes.Pool.BondedTokens.Add(totalShouldBondAmount)
totalLiquidStakedAmount = totalLiquidStakedAmount.Add(totalShouldBondAmount)
// 0 check global liquid staking cap
liquidStakePercent := types.NewDecFromInt(totalLiquidStakedAmount).Quo(types.NewDecFromInt(totalStakedAmount))
if liquidStakePercent.GT(stakingParams.Params.GlobalLiquidStakingCap) {
return nil, 0, fmt.Errorf("ExceedsGlobalLiquidStakingCap %s", liquidStakePercent.String())
}
for _, val := range targets {
done := core.UseSdkConfigContext(client.GetAccountPrefix())
valStr := val.String()
done()
valRes, sErr := client.QueryValidator(valStr, height)
if sErr != nil {
err = sErr
return
}
shares, sErr := valRes.Validator.SharesFromTokens(totalShouldBondAmount)
if sErr != nil {
err = sErr
return
}
maxValLiquidSharesLog := valRes.Validator.ValidatorBondShares.Mul(stakingParams.Params.ValidatorBondFactor)
logger.Debug("validatorInfo", "address", valStr, "ValidatorBondShares", valRes.Validator.ValidatorBondShares, "LiquidShares", valRes.Validator.LiquidShares, "shares", shares, "maxValLiquidShares", maxValLiquidSharesLog)
// 1 check val bond cap
if !stakingParams.Params.ValidatorBondFactor.Equal(ValidatorBondCapDisabled) {
maxValLiquidShares := valRes.Validator.ValidatorBondShares.Mul(stakingParams.Params.ValidatorBondFactor)
logger.Debug("check info", "maxValLiquidShares", maxValLiquidShares)
if valRes.Validator.LiquidShares.Add(shares).GT(maxValLiquidShares) {
continue
}
}
// 2 check val liquid staking cap
updatedLiquidShares := valRes.Validator.LiquidShares.Add(shares)
updatedTotalShares := valRes.Validator.DelegatorShares.Add(shares)
liquidStakePercent := updatedLiquidShares.Quo(updatedTotalShares)
logger.Debug("check info", "ValidatorLiquidStakingCap", stakingParams.Params.ValidatorLiquidStakingCap, "liquidStakePercent", liquidStakePercent, "updatedTotalShares", updatedTotalShares)
if liquidStakePercent.GT(stakingParams.Params.ValidatorLiquidStakingCap) {
continue
}
valAddrs = append(valAddrs, val)
}
} else {
valAddrs = targets
}
valAddrsLen := len(valAddrs)
//check valAddrs length
if valAddrsLen == 0 {
return nil, 0, fmt.Errorf("no enough target valAddrs, pool: %s", poolAddrStr)
}
msgs, err = client.GenDelegateMsgs(
poolAddr,
valAddrs,
types.NewCoin(client.GetDenom(), totalShouldBondAmount))
unSignedType = 1
return
case -1:
var deleRes *xStakingTypes.QueryDelegatorDelegationsResponse
deleRes, err = client.QueryDelegations(poolAddr, height)
if err != nil {
return nil, 0, fmt.Errorf("QueryDelegations failed: %s", err)
}
totalDelegateAmount := types.NewInt(0)
valAddrs := make([]types.ValAddress, 0)
deleAmount := make(map[string]types.Int)
//get validators amount>=3
for _, dele := range deleRes.GetDelegationResponses() {
//filter old validator,we say validator is old if amount < 3 uatom
if dele.GetBalance().Amount.LT(types.NewInt(3)) {
continue
}
done := core.UseSdkConfigContext(client.GetAccountPrefix())
valAddr, err := types.ValAddressFromBech32(dele.GetDelegation().ValidatorAddress)
if err != nil {
done()
return nil, 0, err
}
valAddrs = append(valAddrs, valAddr)
totalDelegateAmount = totalDelegateAmount.Add(dele.GetBalance().Amount)
deleAmount[valAddr.String()] = dele.GetBalance().Amount
done()
}
//check valAddrs length
valAddrsLen := len(valAddrs)
if valAddrsLen == 0 {
return nil, 0, fmt.Errorf("no valAddrs, pool: %s", poolAddr)
}
//check totalDelegateAmount
if totalDelegateAmount.LT(types.NewInt(3 * int64(valAddrsLen))) {
return nil, 0, fmt.Errorf("validators have no reserve value to unbond")
}
//make val <= totalDelegateAmount-3*len and we reserve 3 uatom
val := new(big.Int).Sub(unbond, bond)
willUsetotalDelegateAmount := totalDelegateAmount.Sub(types.NewInt(3 * int64(valAddrsLen)))
if val.Cmp(willUsetotalDelegateAmount.BigInt()) > 0 {
return nil, 0, fmt.Errorf("no enough value can be used to unbond, pool: %s", poolAddr)
}
willUseTotalVal := types.NewIntFromBigInt(val)
//remove validator who's unbonding >= 7
canUseValAddrs := make([]types.ValAddress, 0)
for _, val := range valAddrs {
res, err := client.QueryUnbondingDelegation(poolAddr, val, height)
if err != nil {
// unbonding empty case
if strings.Contains(err.Error(), "NotFound") {
canUseValAddrs = append(canUseValAddrs, val)
continue
}
return nil, 0, err
}
if len(res.GetUnbond().Entries) < 7 {
canUseValAddrs = append(canUseValAddrs, val)
}
}
valAddrs = canUseValAddrs
if len(valAddrs) == 0 {
return nil, 0, fmt.Errorf("no valAddrs can be used to unbond, pool: %s", poolAddr)
}
//sort validators by delegate amount
done := core.UseSdkConfigContext(client.GetAccountPrefix())
sort.Slice(valAddrs, func(i int, j int) bool {
return deleAmount[valAddrs[i].String()].
GT(deleAmount[valAddrs[j].String()])
})
//choose validators to be undelegated
choosedVals := make([]types.ValAddress, 0)
choosedAmount := make(map[string]types.Int)
selectedAmount := types.NewInt(0)
enough := false
for _, validator := range valAddrs {
nowValMaxUnDeleAmount := deleAmount[validator.String()].Sub(types.NewInt(3))
//if we find all validators needed
if selectedAmount.Add(nowValMaxUnDeleAmount).GTE(willUseTotalVal) {
willUseChoosedAmount := willUseTotalVal.Sub(selectedAmount)
choosedVals = append(choosedVals, validator)
choosedAmount[validator.String()] = willUseChoosedAmount
enough = true
break
}
choosedVals = append(choosedVals, validator)
choosedAmount[validator.String()] = nowValMaxUnDeleAmount
selectedAmount = selectedAmount.Add(nowValMaxUnDeleAmount)
}
if !enough {
done()
return nil, 0, fmt.Errorf("can't find enough valAddrs to unbond, pool: %s", poolAddrStr)
}
// filter withdraw validators
withdrawVals := make([]types.ValAddress, 0)
for valAddressStr := range deleAmount {
if _, exist := choosedAmount[valAddressStr]; !exist {
valAddr, err := types.ValAddressFromBech32(valAddressStr)
if err != nil {
done()
return nil, 0, err
}
withdrawVals = append(withdrawVals, valAddr)
}
}
sort.Slice(withdrawVals, func(i int, j int) bool {
return bytes.Compare(withdrawVals[i].Bytes(), withdrawVals[j].Bytes()) > 0
})
done()
msgs, err = client.GenUnDelegateWithdrawMsgs(
poolAddr,
choosedVals,
choosedAmount,
withdrawVals)
unSignedType = -1
return
default:
return nil, 0, fmt.Errorf("unreached case err")
}
}
// Notice: delegate/undelegate/withdraw operates will withdraw all reward
// all delegations had withdraw all reward in eraUpdatedEvent handler
// (0)if rewardAmount of height == 0, hubClient.ErrNoMsgs
// (1)else gen delegate tx
func GetDelegateRewardUnsignedTxWithReward(client *hubClient.Client, poolAddr types.AccAddress, height int64,
rewards map[string]types.Coin, memo string) ([]byte, *types.Int, error) {
unSignedTx, err := client.GenMultiSigRawDeleRewardTxWithRewardsWithMemo(
poolAddr,
height,
rewards,
memo)
if err != nil {
return nil, nil, err
}
decodedTx, err := client.GetTxConfig().TxJSONDecoder()(unSignedTx)
if err != nil {
return nil, nil, fmt.Errorf("GetTxConfig().TxDecoder() failed: %s, unSignedTx: %s", err, string(unSignedTx))
}
totalAmountRet := types.NewInt(0)
for _, msg := range decodedTx.GetMsgs() {
if m, ok := msg.(*xStakingTypes.MsgDelegate); ok {
totalAmountRet = totalAmountRet.Add(m.Amount.Amount)
}
}
return unSignedTx, &totalAmountRet, nil
}
func GetTransferUnsignedTxWithMemo(client *hubClient.Client, poolAddr types.AccAddress, receives []*stafiHubXLedgerTypes.Unbonding, memo string,
logger log.Logger) ([]byte, []xBankTypes.Output, error) {
outPuts := make([]xBankTypes.Output, 0)
done := core.UseSdkConfigContext(client.GetAccountPrefix())
for _, receive := range receives {
addr, err := types.AccAddressFromBech32(receive.Recipient)
if err != nil {
logger.Error("GetTransferUnsignedTx AccAddressFromHex failed", "Account", receive.Recipient, "err", err)
continue
}
out := xBankTypes.Output{
Address: addr.String(),
Coins: types.NewCoins(types.NewCoin(client.GetDenom(), receive.Amount)),
}
outPuts = append(outPuts, out)
}
done()
outPuts = combineSameAddress(outPuts)
//len should not be 0
if len(outPuts) == 0 {
return nil, nil, ErrNoOutPuts
}
txBts, err := client.GenMultiSigRawBatchTransferTxWithMemo(poolAddr, outPuts, memo)
if err != nil {
return nil, nil, ErrNoOutPuts
}
return txBts, outPuts, nil
}
func GetTransferMsgs(client *hubClient.Client, poolAddr types.AccAddress, receives []*stafiHubXLedgerTypes.Unbonding,
logger log.Logger) ([]types.Msg, []xBankTypes.Output, error) {
outPuts := make([]xBankTypes.Output, 0)
done := core.UseSdkConfigContext(client.GetAccountPrefix())
for _, receive := range receives {
addr, err := types.AccAddressFromBech32(receive.Recipient)
if err != nil {
logger.Error("GetTransferUnsignedTx AccAddressFromHex failed", "Account", receive.Recipient, "err", err)
continue
}
out := xBankTypes.Output{
Address: addr.String(),
Coins: types.NewCoins(types.NewCoin(client.GetDenom(), receive.Amount)),
}
outPuts = append(outPuts, out)
}
done()
outPuts = combineSameAddress(outPuts)
//len should not be 0
if len(outPuts) == 0 {
return nil, nil, ErrNoOutPuts
}
msg, err := client.GenBatchTransferMsg(poolAddr, outPuts)
if err != nil {
return nil, nil, ErrNoOutPuts
}
return []types.Msg{msg}, outPuts, nil
}
func combineSameAddress(outPuts []xBankTypes.Output) []xBankTypes.Output {
amountMap := make(map[string]types.Coins)
for _, outPut := range outPuts {
if existCoin, exist := amountMap[outPut.Address]; exist {
amountMap[outPut.Address] = existCoin.Add(outPut.Coins...)
} else {
amountMap[outPut.Address] = outPut.Coins
}
}
retOutputs := make([]xBankTypes.Output, 0)
for address, sendCoins := range amountMap {
retOutputs = append(retOutputs, xBankTypes.Output{
Address: address,
Coins: sendCoins,
})
}
//sort outPuts for the same rawTx from different relayer
sort.SliceStable(retOutputs, func(i, j int) bool {
return bytes.Compare([]byte(retOutputs[i].Address), []byte(retOutputs[j].Address)) < 0
})
return retOutputs
}
// get reward info of pre txs(tx in eraUpdatedEvent of this era and tx in bondReportedEvent/rValidatorUpdatedEvent of era-1)
// tx in bondReportedEvent of era-1 should use the old validator
// tx in rValidatorUpdatedEvent of era -1 should replace old to new validator
// tx in eraUpdatedEvent of this era should already use the new validator
func GetRewardToBeDelegated(c *hubClient.Client, delegatorAddr string, era uint32) (map[string]types.Coin, int64, bool, error) {
done := core.UseSdkConfigContext(c.GetAccountPrefix())
moduleAddressStr := xAuthTypes.NewModuleAddress(xDistriTypes.ModuleName).String()
delAddress, err := types.AccAddressFromBech32(delegatorAddr)
if err != nil {
done()
return nil, 0, false, err
}
done()
txs, err := c.GetTxs(
[]string{
fmt.Sprintf("transfer.recipient='%s'", delegatorAddr),
fmt.Sprintf("transfer.sender='%s'", moduleAddressStr),
}, 1, 10, "desc")
if err != nil {
return nil, 0, false, err
}
if len(txs.Txs) == 0 {
return nil, 0, false, ErrNoRewardNeedDelegate
}
valRewards := make(map[string]types.Coin)
retHeight := int64(0)
alreadyDealBondReportedEvent := false
for i := len(txs.Txs) - 1; i >= 0; i-- {
tx := txs.Txs[i]
txValue := tx.Tx.Value
decodeTx, err := c.GetTxConfig().TxDecoder()(txValue)
if err != nil {
return nil, 0, false, err
}
memoTx, ok := decodeTx.(types.TxWithMemo)
if !ok {
return nil, 0, false, fmt.Errorf("tx is not type TxWithMemo, txhash: %s", txs.Txs[0].TxHash)
}
memoInTx := memoTx.GetMemo()
switch {
case memoInTx == GetMemo(era, TxTypeHandleBondReportedEvent):
alreadyDealBondReportedEvent = true
case memoInTx == GetMemo(era, TxTypeHandleEraPoolUpdatedEvent):
//return tx handleEraPoolUpdatedEvent height
retHeight = tx.Height - 1
fallthrough // should go next case logic
case memoInTx == GetMemo(era-1, TxTypeHandleBondReportedEvent):
height := tx.Height - 1
totalReward, err := c.QueryDelegationTotalRewards(delAddress, height)
if err != nil {
return nil, 0, false, err
}
for _, r := range totalReward.Rewards {
rewardCoin := types.NewCoin(c.GetDenom(), r.Reward.AmountOf(c.GetDenom()).TruncateInt())
if rewardCoin.IsZero() {
continue
}
if _, exist := valRewards[r.ValidatorAddress]; !exist {
valRewards[r.ValidatorAddress] = rewardCoin
} else {
valRewards[r.ValidatorAddress] = valRewards[r.ValidatorAddress].Add(rewardCoin)
}
}
case strings.Contains(memoInTx, TxTypeHandleRValidatorUpdatedEvent):
fragments := strings.Split(memoInTx, ":")
if len(fragments) != 4 {
continue
}
// only collect the old validator's reward info which is redelegated in era-1
if fragments[0] == fmt.Sprintf("%d", era-1) {
msg, ok := decodeTx.GetMsgs()[0].(*xStakingTypes.MsgBeginRedelegate)
if !ok {
continue
}
height := tx.Height - 1
totalReward, err := c.QueryDelegationTotalRewards(delAddress, height)
if err != nil {
return nil, 0, false, err
}
willRemoveVal := msg.ValidatorSrcAddress
willUseVal := msg.ValidatorDstAddress
for _, r := range totalReward.Rewards {
if willRemoveVal == r.ValidatorAddress {
rewardCoin := types.NewCoin(c.GetDenom(), r.Reward.AmountOf(c.GetDenom()).TruncateInt())
if rewardCoin.IsZero() {
continue
}
if reward, exist := valRewards[willRemoveVal]; exist {
valRewards[willUseVal] = reward
// put reward on new validator and delete old validator
delete(valRewards, willRemoveVal)
valRewards[willUseVal] = valRewards[willUseVal].Add(rewardCoin)
} else {
valRewards[willUseVal] = rewardCoin
}
break
}
}
}
default:
}
}
if len(valRewards) == 0 {
return nil, 0, false, ErrNoRewardNeedDelegate
}
return valRewards, retHeight, alreadyDealBondReportedEvent, nil
}
func GetLatestReDelegateTx(c *hubClient.Client, delegatorAddr string) (*types.TxResponse, int64, error) {
txs, err := c.GetTxs(
[]string{
fmt.Sprintf("message.sender='%s'", delegatorAddr),
fmt.Sprintf("message.action='%s'", "/cosmos.staking.v1beta1.MsgBeginRedelegate"),
}, 1, 1, "desc")
if err != nil {
return nil, 0, err
}
if len(txs.Txs) == 0 {
return nil, 0, nil
}
return txs.Txs[0], txs.Txs[0].Height, nil
}
// used for ica pool
// should filter with dst channel, because the dst channel is unique on dst chain.
func GetLatestDealEraUpdatedTx(c *hubClient.Client, dstChannelId string) (*types.TxResponse, int64, error) {
txs, err := c.GetTxs(
[]string{
fmt.Sprintf("recv_packet.packet_dst_channel='%s'", dstChannelId),
}, 1, 5, "desc")
if err != nil {
return nil, 0, err
}
if len(txs.Txs) == 0 {
return nil, 0, nil
}
for _, tx := range txs.Txs {
for _, event := range tx.Events {
if event.Type == "recv_packet" {
for _, a := range event.Attributes {
if string(a.Key) == "packet_data_hex" {
bts, err := hex.DecodeString(string(a.Value))
if err == nil {
var packetData icatypes.InterchainAccountPacketData
err := icatypes.ModuleCdc.UnmarshalJSON(bts, &packetData)
if err == nil {
if packetData.Memo == stafiHubXLedgerTypes.TxTypeDealEraUpdated.String() {
return tx, tx.Height, nil
}
}
}
}
}
}
}
}
return nil, 0, nil
}
func (h *Handler) checkAndSend(poolClient *hubClient.Client, wrappedUnSignedTx *WrapUnsignedTx,
m *core.Message, txHash, txBts []byte, poolAddress types.AccAddress, unSignedTxType int) error {
if len(txBts) == 0 {
return fmt.Errorf("tx empty, pool: %s", poolAddress.String())
}
h.log.Debug("checkAndSend", "txBts", hex.EncodeToString(txBts))
txHashHexStr := hex.EncodeToString(txHash)
done := core.UseSdkConfigContext(poolClient.GetAccountPrefix())
poolAddressStr := poolAddress.String()
done()
retry := BlockRetryLimit
var err error
for {
if retry <= 0 {
h.log.Error("checkAndSend broadcast tx reach retry limit",
"pool address", poolAddressStr,
"txHash", txHashHexStr,
"err", err)
return fmt.Errorf("checkAndSend broadcast tx reach retry limit pool address: %s,err: %s", poolAddressStr, err)
}
//check on chain
var res *types.TxResponse
res, err = poolClient.QueryTxByHash(txHashHexStr)
if err != nil || res.Empty() || res.Code != 0 {
h.log.Warn(fmt.Sprintf(
"checkAndSend QueryTxByHash failed. will rebroadcast after %f second",
BlockRetryInterval.Seconds()),
"tx hash", txHashHexStr,
"err or res.empty", err)
//broadcast if not on chain
_, err = poolClient.BroadcastTx(txBts)
if err != nil && err != errType.ErrTxInMempoolCache {
h.log.Warn("checkAndSend BroadcastTx failed will retry", "err", err)
}
poolBalanceStr := ""
poolBalance, err := poolClient.QueryBalance(poolAddress, poolClient.GetDenom(), 0)
if err != nil {
h.log.Warn("queryBalance err", "err", err)
} else {
poolBalanceStr = poolBalance.Balance.String()
}
currentBlock, currentTimestamp, err := poolClient.GetCurrentBLockAndTimestamp()
if err != nil {
h.log.Warn("GetCurrentBLockAndTimestamp err", "err", err)
}
h.log.Info("rpc info", "poolBalance", poolBalanceStr, "currentBlock", currentBlock,
"currentTimestamp", currentTimestamp)
time.Sleep(BlockRetryInterval)
retry--
continue
}
h.log.Info("checkAndSend success",
"pool address", poolAddressStr,
"tx type", wrappedUnSignedTx.Type,
"era", wrappedUnSignedTx.Era,
"txHash", txHashHexStr)
//report to stafihub
switch wrappedUnSignedTx.Type {
case stafiHubXLedgerTypes.TxTypeDealEraUpdated: //bond/unbond/claim
switch unSignedTxType {
case UnSignedTxTypeSkipAndWithdraw:
return h.sendBondReportMsg(wrappedUnSignedTx.SnapshotId, stafiHubXLedgerTypes.EitherBondUnbond)
default:
return h.sendBondReportMsg(wrappedUnSignedTx.SnapshotId, stafiHubXLedgerTypes.BothBondUnbond)
}
case stafiHubXLedgerTypes.TxTypeDealBondReported: //delegate reward
total := types.NewInt(0)
delegationsRes, err := poolClient.QueryDelegations(poolAddress, 0)
if err != nil {
if !strings.Contains(err.Error(), "unable to find delegations for address") {
h.log.Error("QueryDelegations failed",
"pool", poolAddressStr,
"err", err)
return err
}
} else {
for _, dele := range delegationsRes.GetDelegationResponses() {
total = total.Add(dele.Balance.Amount)
}
}
// height = max(latest redelegate height, era height)?
// the redelegate tx height maybe bigger than era height if rValidatorUpdatedEvent is dealed after a long time
height, err := poolClient.GetHeightByEra(wrappedUnSignedTx.Era, h.conn.eraSeconds, h.conn.offset)
if err != nil {
h.log.Error("handleEraPoolUpdatedEvent GetHeightByEra failed",