-
Notifications
You must be signed in to change notification settings - Fork 0
/
ibc_packet_handlers.go
1165 lines (1050 loc) · 41.7 KB
/
ibc_packet_handlers.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 (
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
icatypes "github.com/cosmos/ibc-go/v5/modules/apps/27-interchain-accounts/types"
ibctransfertypes "github.com/cosmos/ibc-go/v5/modules/apps/transfer/types"
clienttypes "github.com/cosmos/ibc-go/v5/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/v5/modules/core/04-channel/types"
"github.com/golang/protobuf/proto" //nolint:staticcheck
lsmstakingtypes "github.com/iqlusioninc/liquidity-staking-module/x/staking/types"
"github.com/nephirim/blackfury/utils"
"github.com/nephirim/blackfury/utils/addressutils"
queryTypes "github.com/nephirim/blackfury/x/interchainquery/types"
"github.com/nephirim/blackfury/x/interchainstaking/types"
)
type TypedMsg struct {
Msg sdk.Msg
Type string
}
func DeserializeCosmosTxTyped(cdc codec.BinaryCodec, data []byte) ([]TypedMsg, error) {
var cosmosTx icatypes.CosmosTx
if err := cdc.Unmarshal(data, &cosmosTx); err != nil {
return nil, err
}
msgs := make([]TypedMsg, len(cosmosTx.Messages))
for i, any := range cosmosTx.Messages {
var msg sdk.Msg
err := cdc.UnpackAny(any, &msg)
if err != nil {
return nil, err
}
msgs[i] = TypedMsg{Msg: msg, Type: any.TypeUrl}
}
return msgs, nil
}
func (k *Keeper) HandleAcknowledgement(ctx sdk.Context, packet channeltypes.Packet, acknowledgement []byte) error {
ack := channeltypes.Acknowledgement_Result{}
err := json.Unmarshal(acknowledgement, &ack)
txMsgData := &sdk.TxMsgData{}
var success bool
if err != nil {
k.Logger(ctx).Error("unable to unmarshal acknowledgement", "error", err, "data", acknowledgement)
return err
}
if reflect.DeepEqual(ack, channeltypes.Acknowledgement_Result{}) {
ackErr := channeltypes.Acknowledgement_Error{}
err := json.Unmarshal(acknowledgement, &ackErr)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal acknowledgement error", "error", err, "data", acknowledgement)
return err
}
k.Logger(ctx).Error("received an acknowledgement error", "error", err, "remote_err", ackErr, "data", acknowledgement)
defer telemetry.IncrCounter(1, types.ModuleName, "ica_acknowledgement_errors")
success = false
} else {
defer telemetry.IncrCounter(1, types.ModuleName, "ica_acknowledgement_success")
err = proto.Unmarshal(ack.Result, txMsgData)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal acknowledgement", "error", err, "ack", ack.Result)
return err
}
success = true
}
var packetData icatypes.InterchainAccountPacketData
err = icatypes.ModuleCdc.UnmarshalJSON(packet.GetData(), &packetData)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal acknowledgement packet data", "error", err, "data", packetData)
return err
}
if reflect.DeepEqual(packetData, icatypes.InterchainAccountPacketData{}) {
return errors.New("unable to unmarshal packet data; got empty JSON object")
}
msgs, err := DeserializeCosmosTxTyped(k.cdc, packetData.Data)
if err != nil {
k.Logger(ctx).Error("unable to decode messages", "err", err)
return err
}
for msgIndex, msg := range msgs {
// use msgData for v0.45 and below and msgResponse for v0.46+
//nolint:staticcheck // SA1019 ignore this!
var msgData *sdk.MsgData
var msgResponse []byte
var msgResponseType string
if len(txMsgData.MsgResponses) > 0 {
msgResponseType = txMsgData.MsgResponses[msgIndex].GetTypeUrl()
msgResponse = txMsgData.MsgResponses[msgIndex].GetValue()
} else if len(txMsgData.Data) > 0 {
msgData = txMsgData.Data[msgIndex]
}
src := msg.Msg
switch msg.Type {
case "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward":
// TODO: if this fails, it's okay. log but continue.
if !success {
return nil
}
k.Logger(ctx).Info("Rewards withdrawn")
if err := k.HandleWithdrawRewards(ctx, src); err != nil {
return err
}
continue
case "/cosmos.staking.v1beta1.MsgRedeemTokensforShares":
// TODO: handle this before LSM
if !success {
return nil
}
response := lsmstakingtypes.MsgRedeemTokensforSharesResponse{}
if msgResponseType != "" {
err = proto.Unmarshal(msgResponse, &response)
if err != nil {
k.Logger(ctx).Error("unable to unpack MsgRedeemTokensforShares response", "error", err)
return err
}
} else {
err := proto.Unmarshal(msgData.Data, &response)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal MsgRedeemTokensforShares response", "error", err)
return err
}
}
k.Logger(ctx).Info("Tokens redeemed for shares", "response", response)
// we should update delegation records here.
if err := k.HandleRedeemTokens(ctx, src, response.Amount); err != nil {
return err
}
continue
case "/cosmos.staking.v1beta1.MsgTokenizeShares":
// TODO: handle this before LSM
if !success {
return nil
}
response := lsmstakingtypes.MsgTokenizeSharesResponse{}
if msgResponseType != "" {
err = proto.Unmarshal(msgResponse, &response)
if err != nil {
k.Logger(ctx).Error("unable to unpack MsgTokenizeShares response", "error", err)
return err
}
} else {
err := proto.Unmarshal(msgData.Data, &response)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal MsgTokenizeShares response", "error", err)
return err
}
}
k.Logger(ctx).Info("Shares tokenized", "response", response)
if err := k.HandleTokenizedShares(ctx, src, response.Amount, packetData.Memo); err != nil {
return err
}
continue
case "/cosmos.staking.v1beta1.MsgDelegate":
// TODO: can we safely ignore this?
if !success {
return nil
}
response := stakingtypes.MsgDelegateResponse{}
if msgResponseType != "" {
err = proto.Unmarshal(msgResponse, &response)
if err != nil {
k.Logger(ctx).Error("unable to unpack MsgDelegate response", "error", err)
return err
}
} else {
err := proto.Unmarshal(msgData.Data, &response)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal MsgDelegate response", "error", err)
return err
}
}
k.Logger(ctx).Info("Delegated", "response", response)
// we should update delegation records here.
if err := k.HandleDelegate(ctx, src, packetData.Memo); err != nil {
return err
}
continue
case "/cosmos.staking.v1beta1.MsgBeginRedelegate":
if success {
response := stakingtypes.MsgBeginRedelegateResponse{}
if msgResponseType != "" {
err = proto.Unmarshal(msgResponse, &response)
if err != nil {
k.Logger(ctx).Error("unable to unpack MsgBeginRedelegate response", "error", err)
return err
}
} else {
err := proto.Unmarshal(msgData.Data, &response)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal MsgBeginRedelegate response", "error", err)
return err
}
}
k.Logger(ctx).Info("Redelegation initiated", "response", response)
if err := k.HandleBeginRedelegate(ctx, src, response.CompletionTime, packetData.Memo); err != nil {
return err
}
} else {
if err := k.HandleFailedBeginRedelegate(ctx, src, packetData.Memo); err != nil {
return err
}
}
continue
case "/cosmos.staking.v1beta1.MsgUndelegate":
if success {
response := stakingtypes.MsgUndelegateResponse{}
if msgResponseType != "" {
err = proto.Unmarshal(msgResponse, &response)
if err != nil {
k.Logger(ctx).Error("unable to unpack MsgUndelegate response", "error", err)
return err
}
} else {
err := proto.Unmarshal(msgData.Data, &response)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal MsgUndelegate response", "error", err)
return err
}
}
k.Logger(ctx).Info("Undelegation started", "response", response)
if err := k.HandleUndelegate(ctx, src, response.CompletionTime, packetData.Memo); err != nil {
return err
}
} else {
if err := k.HandleFailedUndelegate(ctx, src, packetData.Memo); err != nil {
return err
}
}
continue
case "/cosmos.bank.v1beta1.MsgSend":
if !success {
// TODO: handle this.
return nil
}
response := banktypes.MsgSendResponse{}
if msgResponseType != "" {
err = proto.Unmarshal(msgResponse, &response)
if err != nil {
k.Logger(ctx).Error("unable to unpack MsgSend response", "error", err)
return err
}
} else {
err := proto.Unmarshal(msgData.Data, &response)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal MsgSend response", "error", err)
return err
}
}
k.Logger(ctx).Info("Funds Transferred", "response", response)
// check tokenTransfers - if end user unescrow and burn txs
if err := k.HandleCompleteSend(ctx, src, packetData.Memo); err != nil {
return err
}
case "/cosmos.distribution.v1beta1.MsgSetWithdrawAddress":
if !success {
// safely ignore this, as we'll try again anyway.
return nil
}
response := distrtypes.MsgSetWithdrawAddressResponse{}
if msgResponseType != "" {
err = proto.Unmarshal(msgResponse, &response)
if err != nil {
k.Logger(ctx).Error("unable to unpack MsgSetWithdrawAddress response", "error", err)
return err
}
} else {
err := proto.Unmarshal(msgData.Data, &response)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal MsgSetWithdrawAddress response", "error", err)
return err
}
}
k.Logger(ctx).Info("Withdraw Address Updated", "response", response)
if err := k.HandleUpdatedWithdrawAddress(ctx, src); err != nil {
return err
}
case "/ibc.applications.transfer.v1.MsgTransfer":
// this should be okay to fail; we'll pick it up next time around.
if !success {
return nil
}
response := ibctransfertypes.MsgTransferResponse{}
if msgResponseType != "" {
err = proto.Unmarshal(msgResponse, &response)
if err != nil {
k.Logger(ctx).Error("unable to unpack MsgTransfer response", "error", err)
return err
}
} else {
err := proto.Unmarshal(msgData.Data, &response)
if err != nil {
k.Logger(ctx).Error("unable to unmarshal MsgTransfer response", "error", err)
return err
}
}
k.Logger(ctx).Info("MsgTranfer acknowledgement received")
if err := k.HandleMsgTransfer(ctx, src); err != nil {
return err
}
default:
k.Logger(ctx).Error("unhandled acknowledgement packet", "type", reflect.TypeOf(src).Name())
}
}
return nil
}
func (k *Keeper) HandleTimeout(_ sdk.Context, _ channeltypes.Packet) error {
return nil
}
//----------------------------------------------------------------
func (k *Keeper) HandleMsgTransfer(ctx sdk.Context, msg sdk.Msg) error {
k.Logger(ctx).Info("Received MsgTransfer acknowledgement")
// first, type assertion. we should have ibctransfertypes.MsgTransfer
sMsg, ok := msg.(*ibctransfertypes.MsgTransfer)
if !ok {
k.Logger(ctx).Error("unable to cast source message to MsgTransfer")
return errors.New("unable to cast source message to MsgTransfer")
}
// check if destination is interchainstaking module account (spoiler: it was)
if sMsg.Receiver != k.AccountKeeper.GetModuleAddress(types.ModuleName).String() {
k.Logger(ctx).Error("msgTransfer to unknown account!")
return errors.New("unexpected recipient")
}
return k.HandleDistributeFeesFromModuleAccount(ctx)
}
func (k *Keeper) HandleDistributeFeesFromModuleAccount(ctx sdk.Context) error {
// what do we have in the account?
balance := k.BankKeeper.GetAllBalances(ctx, k.AccountKeeper.GetModuleAddress(types.ModuleName))
k.Logger(ctx).Info("distributing collected fees to stakers", "amount", balance)
return k.BankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, authtypes.FeeCollectorName, balance) // Fee collector name needs to be passed in to keeper constructor.
}
func (k *Keeper) HandleCompleteSend(ctx sdk.Context, msg sdk.Msg, memo string) error {
k.Logger(ctx).Info("Received MsgSend acknowledgement")
// first, type assertion. we should have banktypes.MsgSend
sMsg, ok := msg.(*banktypes.MsgSend)
if !ok {
err := errors.New("unable to cast source message to MsgSend")
k.Logger(ctx).Error(err.Error())
return err
}
// get zone
zone, err := k.GetZoneFromContext(ctx)
if err != nil {
err = fmt.Errorf("2: %w", err)
k.Logger(ctx).Error(err.Error())
return err
}
// checks here are specific to ensure future extensibility;
switch {
case sMsg.FromAddress == zone.WithdrawalAddress.GetAddress():
// WithdrawalAddress (for rewards) only send to DelegationAddresses.
// Target here is the DelegationAddresses.
return k.handleRewardsDelegation(ctx, *zone, sMsg)
case zone.IsDelegateAddress(sMsg.FromAddress):
return k.HandleWithdrawForUser(ctx, zone, sMsg, memo)
case zone.IsDelegateAddress(sMsg.ToAddress) && zone.DepositAddress.Address == sMsg.FromAddress:
return k.handleSendToDelegate(ctx, zone, sMsg, memo)
default:
err = errors.New("unexpected completed send")
k.Logger(ctx).Error(err.Error())
return err
}
}
func (k *Keeper) handleRewardsDelegation(ctx sdk.Context, zone types.Zone, msg *banktypes.MsgSend) error {
return k.handleSendToDelegate(ctx, &zone, msg, "rewards")
}
func (k *Keeper) handleSendToDelegate(ctx sdk.Context, zone *types.Zone, msg *banktypes.MsgSend, memo string) error {
var msgs []sdk.Msg
for _, coin := range msg.Amount {
if coin.Denom == zone.BaseDenom {
allocations, err := k.DeterminePlanForDelegation(ctx, zone, msg.Amount)
if err != nil {
return err
}
msgs = append(msgs, k.PrepareDelegationMessagesForCoins(zone, allocations)...)
} else {
msgs = append(msgs, k.PrepareDelegationMessagesForShares(zone, msg.Amount)...)
}
}
k.Logger(ctx).Info("messages to send", "messages", msgs)
return k.SubmitTx(ctx, msgs, zone.DelegationAddress, memo, zone.MessagesPerTx)
}
// HandleWithdrawForUser handles withdraw for user will check that the msgSend we have successfully executed matches an existing withdrawal record.
// on a match (recipient = msg.ToAddress + amount + status == SEND), we mark the record as complete.
// if no other withdrawal records exist for this triple (i.e. no further withdrawal from this delegator account for this user (i.e. different validator))
// then burn the withdrawal_record's burn_amount.
func (k *Keeper) HandleWithdrawForUser(ctx sdk.Context, zone *types.Zone, msg *banktypes.MsgSend, memo string) error {
withdrawalRecord, found := k.GetWithdrawalRecord(ctx, zone.ChainId, memo, WithdrawStatusSend)
if !found {
return errors.New("no matching withdrawal record found")
}
// case 1: total amount - native unbonding
// this statement is ridiculous, but currently calling coins.Equals against coins with different denoms panics; which is pretty useless.
if len(withdrawalRecord.Amount) == 1 && len(msg.Amount) == 1 && msg.Amount[0].Denom == withdrawalRecord.Amount[0].Denom && withdrawalRecord.Amount.IsEqual(msg.Amount) {
k.Logger(ctx).Info("found matching withdrawal; marking as completed")
k.UpdateWithdrawalRecordStatus(ctx, &withdrawalRecord, WithdrawStatusCompleted)
if err := k.BankKeeper.BurnCoins(ctx, types.EscrowModuleAccount, sdk.NewCoins(withdrawalRecord.BurnAmount)); err != nil {
// if we can't burn the coins, fail.
return err
}
k.SetWithdrawalRecord(ctx, withdrawalRecord)
k.Logger(ctx).Info("burned coins post-withdrawal", "coins", withdrawalRecord.BurnAmount)
} else {
// case 2: per validator amounts - LSM unbonding
dlist := make(map[int]struct{})
for i, dist := range withdrawalRecord.Distribution {
if msg.Amount[0].Amount.Equal(sdk.NewIntFromUint64(dist.Amount)) { // check valoper here too?
dlist[i] = struct{}{}
// matched amount
if len(withdrawalRecord.Distribution) == len(dlist) {
// we just removed the last element
k.Logger(ctx).Info("found matching withdrawal; marking as completed")
k.UpdateWithdrawalRecordStatus(ctx, &withdrawalRecord, WithdrawStatusCompleted)
if err := k.BankKeeper.BurnCoins(ctx, types.EscrowModuleAccount, sdk.NewCoins(withdrawalRecord.BurnAmount)); err != nil {
// if we can't burn the coins, fail.
return err
}
k.SetWithdrawalRecord(ctx, withdrawalRecord)
k.Logger(ctx).Info("burned coins post-withdrawal", "coins", withdrawalRecord.BurnAmount)
}
break
}
}
if len(dlist) > 0 {
newDist := make([]*types.Distribution, 0)
i := 0
for idx := range withdrawalRecord.Distribution {
if _, remove := dlist[idx]; !remove {
newDist = append(newDist, withdrawalRecord.Distribution[idx])
}
i++
}
k.Logger(ctx).Info("found matching withdrawal; awaiting additional messages")
withdrawalRecord.Distribution = newDist
k.SetWithdrawalRecord(ctx, withdrawalRecord)
}
}
period := int64(k.GetParam(ctx, types.KeyValidatorSetInterval))
query := stakingtypes.QueryValidatorsRequest{}
return k.EmitValSetQuery(ctx, zone.ConnectionId, zone.ChainId, query, sdkmath.NewInt(period))
}
func (k *Keeper) GCCompletedRedelegations(ctx sdk.Context) error {
var err error
k.IterateRedelegationRecords(ctx, func(idx int64, key []byte, redelegation types.RedelegationRecord) bool {
// if the redelegation completion time was in the past AND is not 0000-00-00T00:00:00Z, then delete it.
if ctx.BlockTime().After(redelegation.CompletionTime) && !redelegation.CompletionTime.Equal(time.Time{}) {
k.Logger(ctx).Info("garbage collecting completed redelegations", "key", key, "completion", redelegation.CompletionTime)
k.DeleteRedelegationRecordByKey(ctx, append(types.KeyPrefixRedelegationRecord, key...))
}
return false
})
return err
}
func (k *Keeper) HandleMaturedUnbondings(ctx sdk.Context, zone *types.Zone) error {
var err error
k.IterateZoneStatusWithdrawalRecords(ctx, zone.ChainId, WithdrawStatusUnbond, func(idx int64, withdrawal types.WithdrawalRecord) bool {
if ctx.BlockTime().After(withdrawal.CompletionTime) && !withdrawal.CompletionTime.Equal(time.Time{}) { // completion date has passed.
k.Logger(ctx).Info("found completed unbonding")
sendMsg := &banktypes.MsgSend{FromAddress: zone.DelegationAddress.GetAddress(), ToAddress: withdrawal.Recipient, Amount: sdk.Coins{withdrawal.Amount[0]}}
err = k.SubmitTx(ctx, []sdk.Msg{sendMsg}, zone.DelegationAddress, withdrawal.Txhash, zone.MessagesPerTx)
if err != nil {
k.Logger(ctx).Error("error", err)
return true
}
k.Logger(ctx).Info("sending funds", "for", withdrawal.Delegator, "delegate_account", zone.DelegationAddress.GetAddress(), "to", withdrawal.Recipient, "amount", withdrawal.Amount)
k.UpdateWithdrawalRecordStatus(ctx, &withdrawal, WithdrawStatusSend)
}
return false
})
return err
}
func (k *Keeper) HandleTokenizedShares(ctx sdk.Context, msg sdk.Msg, sharesAmount sdk.Coin, memo string) error {
var err error
k.Logger(ctx).Info("received MsgTokenizeShares acknowledgement")
// first, type assertion. we should have stakingtypes.MsgTokenizeShares
tsMsg, ok := msg.(*lsmstakingtypes.MsgTokenizeShares)
if !ok {
k.Logger(ctx).Error("unable to cast source message to MsgTokenizeShares")
return errors.New("unable to cast source message to MsgTokenizeShares")
}
zone := k.GetZoneForDelegateAccount(ctx, tsMsg.DelegatorAddress)
withdrawalRecord, found := k.GetWithdrawalRecord(ctx, zone.ChainId, memo, WithdrawStatusTokenize)
if !found {
return errors.New("no matching withdrawal record found")
}
for _, dist := range withdrawalRecord.Distribution {
if sharesAmount.Equal(dist.Amount) {
withdrawalRecord.Amount.Add(sharesAmount)
// matched amount
if len(withdrawalRecord.Distribution) == len(withdrawalRecord.Amount) {
// we just added the last tokens
k.Logger(ctx).Info("Found matching withdrawal; marking for send")
k.DeleteWithdrawalRecord(ctx, zone.ChainId, memo, WithdrawStatusTokenize)
withdrawalRecord.Status = WithdrawStatusSend
sendMsg := &banktypes.MsgSend{FromAddress: zone.DelegationAddress.Address, ToAddress: withdrawalRecord.Recipient, Amount: withdrawalRecord.Amount}
err = k.SubmitTx(ctx, []sdk.Msg{sendMsg}, zone.DelegationAddress, memo, zone.MessagesPerTx)
if err != nil {
return err
}
} else {
k.Logger(ctx).Info("Found matching withdrawal; awaiting additional messages")
}
k.SetWithdrawalRecord(ctx, withdrawalRecord)
break
}
}
return nil
}
func (k *Keeper) HandleBeginRedelegate(ctx sdk.Context, msg sdk.Msg, completion time.Time, memo string) error {
if completion.IsZero() {
return errors.New("invalid zero nil completion time")
}
epochNumber, err := types.ParseMsgMemo(memo, types.MsgTypeRebalance)
if err != nil {
return err
}
k.Logger(ctx).Info("Received MsgBeginRedelegate acknowledgement")
// first, type assertion. we should have stakingtypes.MsgBeginRedelegate
redelegateMsg, ok := msg.(*stakingtypes.MsgBeginRedelegate)
if !ok {
return errors.New("unable to unmarshal MsgBeginRedelegate")
}
zone := k.GetZoneForDelegateAccount(ctx, redelegateMsg.DelegatorAddress)
record, found := k.GetRedelegationRecord(ctx, zone.ChainId, redelegateMsg.ValidatorSrcAddress, redelegateMsg.ValidatorDstAddress, epochNumber)
if !found {
k.Logger(ctx).Error("unable to find redelegation record", "chain", zone.ChainId, "source", redelegateMsg.ValidatorSrcAddress, "dst", redelegateMsg.ValidatorDstAddress, "epoch_number", epochNumber)
return fmt.Errorf("unable to find redelegation record for chain %s, src: %s, dst: %s, at epoch %d", zone.ChainId, redelegateMsg.ValidatorSrcAddress, redelegateMsg.ValidatorDstAddress, epochNumber)
}
k.Logger(ctx).Info("updating redelegation record with completion time", "completion", completion)
record.CompletionTime = completion
k.SetRedelegationRecord(ctx, record)
tgtDelegation, found := k.GetDelegation(ctx, zone, redelegateMsg.DelegatorAddress, redelegateMsg.ValidatorDstAddress)
if !found {
k.Logger(ctx).Error("unable to find delegation record", "chain", zone.ChainId, "source", redelegateMsg.ValidatorSrcAddress, "dst", redelegateMsg.ValidatorDstAddress, "epoch_number", epochNumber)
return fmt.Errorf("unable to find delegation record for chain %s, src: %s, dst: %s, at epoch %d", zone.ChainId, redelegateMsg.ValidatorSrcAddress, redelegateMsg.ValidatorDstAddress, epochNumber)
}
// TODO: is the field below actually used?
tgtDelegation.Amount = tgtDelegation.Amount.Add(redelegateMsg.Amount)
tgtDelegation.RedelegationEnd = completion.Unix() // this field should be a timestamp, but let's avoid unnecessary state changes.
k.SetDelegation(ctx, zone, tgtDelegation)
delAddr, err := addressutils.AccAddressFromBech32(redelegateMsg.DelegatorAddress, zone.AccountPrefix)
if err != nil {
return err
}
valAddr, err := addressutils.ValAddressFromBech32(redelegateMsg.ValidatorDstAddress, zone.AccountPrefix+"valoper")
if err != nil {
return err
}
data := stakingtypes.GetDelegationKey(delAddr, valAddr)
// send request to update delegation record for target del/val tuple.
k.ICQKeeper.MakeRequest(
ctx,
zone.ConnectionId,
zone.ChainId,
"store/staking/key",
data,
sdk.NewInt(-1),
types.ModuleName,
"delegation",
0,
)
srcDelegation, found := k.GetDelegation(ctx, zone, redelegateMsg.DelegatorAddress, redelegateMsg.ValidatorDstAddress)
if !found {
k.Logger(ctx).Error("unable to find delegation record", "chain", zone.ChainId, "source", redelegateMsg.ValidatorSrcAddress, "dst", redelegateMsg.ValidatorDstAddress, "epoch_number", epochNumber)
return fmt.Errorf("unable to find delegation record for chain %s, src: %s, dst: %s, at epoch %d", zone.ChainId, redelegateMsg.ValidatorSrcAddress, redelegateMsg.ValidatorDstAddress, epochNumber)
}
srcDelegation.Amount = tgtDelegation.Amount.Sub(redelegateMsg.Amount)
k.SetDelegation(ctx, zone, srcDelegation)
valAddr, err = addressutils.ValAddressFromBech32(redelegateMsg.ValidatorDstAddress, zone.AccountPrefix+"valoper")
if err != nil {
return err
}
data = stakingtypes.GetDelegationKey(delAddr, valAddr)
// send request to update delegation record for src del/val tuple.
k.ICQKeeper.MakeRequest(
ctx,
zone.ConnectionId,
zone.ChainId,
"store/staking/key",
data,
sdk.NewInt(-1),
types.ModuleName,
"delegation",
0,
)
return nil
}
func (k *Keeper) HandleFailedBeginRedelegate(ctx sdk.Context, msg sdk.Msg, memo string) error {
epochNumber, err := types.ParseMsgMemo(memo, types.MsgTypeRebalance)
if err != nil {
return err
}
k.Logger(ctx).Error("Received MsgBeginRedelegate acknowledgement error")
// first, type assertion. we should have stakingtypes.MsgBeginRedelegate
redelegateMsg, ok := msg.(*stakingtypes.MsgBeginRedelegate)
if !ok {
return errors.New("unable to unmarshal MsgBeginRedelegate")
}
zone := k.GetZoneForDelegateAccount(ctx, redelegateMsg.DelegatorAddress)
k.DeleteRedelegationRecord(ctx, zone.ChainId, redelegateMsg.ValidatorSrcAddress, redelegateMsg.ValidatorDstAddress, epochNumber)
k.Logger(ctx).Error("Cleaning up redelegation record")
return nil
}
func (k *Keeper) HandleUndelegate(ctx sdk.Context, msg sdk.Msg, completion time.Time, memo string) error {
if completion.IsZero() {
return errors.New("invalid zero nil completion time")
}
k.Logger(ctx).Info("Received MsgUndelegate acknowledgement")
// first, type assertion. we should have stakingtypes.MsgUndelegate
undelegateMsg, ok := msg.(*stakingtypes.MsgUndelegate)
if !ok {
k.Logger(ctx).Error("unable to cast source message to MsgUndelegate")
return errors.New("unable to cast source message to MsgUndelegate")
}
epochNumber, err := types.ParseMsgMemo(memo, types.MsgTypeWithdrawal)
if err != nil {
return err
}
zone := k.GetZoneForDelegateAccount(ctx, undelegateMsg.DelegatorAddress)
ubr, found := k.GetUnbondingRecord(ctx, zone.ChainId, undelegateMsg.ValidatorAddress, epochNumber)
if !found {
return fmt.Errorf("unbonding record for %s not found for epoch %d", undelegateMsg.ValidatorAddress, epochNumber)
}
for _, hash := range ubr.RelatedTxhash {
k.Logger(ctx).Info("MsgUndelegate", "del", undelegateMsg.DelegatorAddress, "val", undelegateMsg.ValidatorAddress, "hash", hash, "chain", zone.ChainId)
record, found := k.GetWithdrawalRecord(ctx, zone.ChainId, hash, WithdrawStatusUnbond)
if !found {
return fmt.Errorf("unable to lookup withdrawal record; chain: %s, hash: %s", zone.ChainId, hash)
}
if completion.After(record.CompletionTime) {
record.CompletionTime = completion
}
k.Logger(ctx).Info("withdrawal record to save", "rcd", record)
k.UpdateWithdrawalRecordStatus(ctx, &record, WithdrawStatusUnbond)
}
delAddr, err := addressutils.AccAddressFromBech32(undelegateMsg.DelegatorAddress, "")
if err != nil {
return err
}
valAddr, err := addressutils.ValAddressFromBech32(undelegateMsg.ValidatorAddress, "")
if err != nil {
return err
}
data := stakingtypes.GetDelegationKey(delAddr, valAddr)
// send request to update delegation record for undelegated del/val tuple.
k.ICQKeeper.MakeRequest(
ctx,
zone.ConnectionId,
zone.ChainId,
"store/staking/key",
data,
sdk.NewInt(-1),
types.ModuleName,
"delegation",
0,
)
return nil
}
func (k *Keeper) HandleFailedUndelegate(ctx sdk.Context, msg sdk.Msg, memo string) error {
epochNumber, err := types.ParseMsgMemo(memo, types.MsgTypeWithdrawal)
if err != nil {
return err
}
k.Logger(ctx).Error("Received MsgUndelegate acknowledgement error")
// first, type assertion. we should have stakingtypes.MsgBeginRedelegate
undelegateMsg, ok := msg.(*stakingtypes.MsgUndelegate)
if !ok {
return errors.New("unable to unmarshal MsgUndelegate")
}
zone := k.GetZoneForDelegateAccount(ctx, undelegateMsg.DelegatorAddress)
ubr, found := k.GetUnbondingRecord(ctx, zone.ChainId, undelegateMsg.ValidatorAddress, epochNumber)
if !found {
return fmt.Errorf("cannot find unbonding record for %s/%s/%d", zone.ChainId, undelegateMsg.ValidatorAddress, epochNumber)
}
for _, hash := range ubr.RelatedTxhash {
wdr, found := k.GetWithdrawalRecord(ctx, zone.ChainId, hash, WithdrawStatusUnbond)
if !found {
return fmt.Errorf("cannot find withdrawal record for %s/%s", zone.ChainId, hash)
}
if len(wdr.Distribution) == 1 {
// sanity check
if wdr.Distribution[0].Valoper != ubr.Validator {
return fmt.Errorf("unable to requeue withdrawal record for failed unbonding; expected %s, got %s", ubr.Validator, wdr.Distribution[0].Valoper)
}
wdr.Distribution = nil
wdr.Requeued = true
k.UpdateWithdrawalRecordStatus(ctx, &wdr, WithdrawStatusQueued)
} else {
// remove this validator from distribution; amend amounts; requeue.
newDistribution := make([]*types.Distribution, 0)
relatedAmount := uint64(0)
for _, dist := range wdr.Distribution {
if dist.Valoper != ubr.Validator {
newDistribution = append(newDistribution, dist)
} else {
relatedAmount = dist.Amount
}
}
wdr.Distribution = newDistribution
amount := wdr.Amount.AmountOf(zone.BaseDenom)
wdr.Amount = wdr.Amount.Sub(sdk.NewCoin(zone.BaseDenom, sdk.NewIntFromUint64(relatedAmount)))
rr := sdk.NewDecFromInt(wdr.BurnAmount.Amount).Quo(sdk.NewDecFromInt(amount))
relatedQAsset := sdk.NewDec(int64(relatedAmount)).Mul(rr).TruncateInt()
wdr.BurnAmount = wdr.BurnAmount.SubAmount(relatedQAsset)
k.SetWithdrawalRecord(ctx, wdr)
// create a new record with the failed amount
newWdr := types.WithdrawalRecord{
ChainId: zone.ChainId,
Delegator: wdr.Delegator,
Recipient: wdr.Recipient,
Distribution: nil,
Amount: sdk.NewCoins(sdk.NewCoin(zone.BaseDenom, sdk.NewIntFromUint64(relatedAmount))),
BurnAmount: sdk.NewCoin(zone.LocalDenom, relatedQAsset),
Txhash: fmt.Sprintf("%064d", k.GetNextWithdrawalRecordSequence(ctx)),
Status: WithdrawStatusQueued,
Requeued: true,
}
k.SetWithdrawalRecord(ctx, newWdr)
}
}
k.DeleteUnbondingRecord(ctx, zone.ChainId, undelegateMsg.ValidatorAddress, epochNumber)
k.Logger(ctx).Error("Cleaning up redelegation record")
return nil
}
func (k *Keeper) HandleRedeemTokens(ctx sdk.Context, msg sdk.Msg, amount sdk.Coin) error {
k.Logger(ctx).Info("Received MsgRedeemTokensforShares acknowledgement")
// first, type assertion. we should have stakingtypes.MsgRedeemTokensforShares
redeemMsg, ok := msg.(*lsmstakingtypes.MsgRedeemTokensforShares)
if !ok {
k.Logger(ctx).Error("unable to cast source message to MsgRedeemTokensforShares")
return errors.New("unable to cast source message to MsgRedeemTokensforShares")
}
validatorAddress, err := k.GetValidatorForToken(ctx, redeemMsg.Amount)
if err != nil {
return err
}
zone := k.GetZoneForDelegateAccount(ctx, redeemMsg.DelegatorAddress)
return k.UpdateDelegationRecordForAddress(ctx, redeemMsg.DelegatorAddress, validatorAddress, amount, zone, false)
}
func (k *Keeper) HandleDelegate(ctx sdk.Context, msg sdk.Msg, memo string) error {
k.Logger(ctx).Info("Received MsgDelegate acknowledgement")
// first, type assertion. we should have stakingtypes.MsgDelegate
delegateMsg, ok := msg.(*stakingtypes.MsgDelegate)
if !ok {
k.Logger(ctx).Error("unable to cast source message to MsgDelegate")
return errors.New("unable to cast source message to MsgDelegate")
}
zone := k.GetZoneForDelegateAccount(ctx, delegateMsg.DelegatorAddress)
if zone == nil {
// most likely a performance account...
if zone := k.GetZoneForPerformanceAccount(ctx, delegateMsg.DelegatorAddress); zone != nil {
return nil
}
return fmt.Errorf("unable to find zone for address %s", delegateMsg.DelegatorAddress)
}
switch {
case memo == "rewards":
case strings.HasPrefix(memo, "batch"):
k.Logger(ctx).Debug("batch delegation", "memo", memo, "tx", delegateMsg)
exclusionTimestampUnix, err := strconv.ParseInt(strings.Split(memo, "/")[1], 10, 64)
if err != nil {
return err
}
k.Logger(ctx).Debug("outstanding delegations ack-received")
k.SetReceiptsCompleted(ctx, zone, time.Unix(exclusionTimestampUnix, 0), ctx.BlockTime())
zone.DelegationAddress.Balance = zone.DelegationAddress.Balance.Sub(delegateMsg.Amount)
k.SetZone(ctx, zone)
if zone.DelegationAddress.Balance.IsZero() && zone.WithdrawalWaitgroup == 0 {
k.Logger(ctx).Info("Triggering redemption rate calc after delegation flush")
if err := k.TriggerRedemptionRate(ctx, zone); err != nil {
return err
}
}
default:
receipt, found := k.GetReceipt(ctx, types.GetReceiptKey(zone.ChainId, memo))
if !found {
return fmt.Errorf("unable to find receipt for hash %s", memo)
}
t := ctx.BlockTime()
receipt.Completed = &t
k.SetReceipt(ctx, receipt)
}
return k.UpdateDelegationRecordForAddress(ctx, delegateMsg.DelegatorAddress, delegateMsg.ValidatorAddress, delegateMsg.Amount, zone, false)
}
func (k *Keeper) HandleUpdatedWithdrawAddress(ctx sdk.Context, msg sdk.Msg) error {
k.Logger(ctx).Info("Received MsgSetWithdrawAddress acknowledgement")
// first, type assertion. we should have distrtypes.MsgSetWithdrawAddress
original, ok := msg.(*distrtypes.MsgSetWithdrawAddress)
if !ok {
k.Logger(ctx).Error("unable to cast source message to MsgSetWithdrawAddress")
return errors.New("unable to cast source message to MsgSetWithdrawAddress")
}
zone := k.GetZoneForDelegateAccount(ctx, original.DelegatorAddress)
if zone == nil {
zone = k.GetZoneForPerformanceAccount(ctx, original.DelegatorAddress)
if zone == nil {
zone = k.GetZoneForDepositAccount(ctx, original.DelegatorAddress)
if zone == nil {
return errors.New("unable to find zone")
}
if err := zone.DepositAddress.SetWithdrawalAddress(original.WithdrawAddress); err != nil {
return err
}
}
if err := zone.PerformanceAddress.SetWithdrawalAddress(original.WithdrawAddress); err != nil {
return err
}
} else {
if err := zone.DelegationAddress.SetWithdrawalAddress(original.WithdrawAddress); err != nil {
return err
}
}
k.SetZone(ctx, zone)
return nil
}
func (k *Keeper) GetValidatorForToken(ctx sdk.Context, amount sdk.Coin) (string, error) {
zone, err := k.GetZoneFromContext(ctx)
if err != nil {
err = fmt.Errorf("3: %w", err)
k.Logger(ctx).Error(err.Error())
return "", err
}
for _, val := range k.GetValidatorAddresses(ctx, zone.ChainId) {
if strings.HasPrefix(amount.Denom, val) {
// match!
return val, nil
}
}
return "", fmt.Errorf("unable to find validator for token %s", amount.Denom)
}
func (k *Keeper) UpdateDelegationRecordsForAddress(ctx sdk.Context, zone types.Zone, delegatorAddress string, args []byte) error {
var response stakingtypes.QueryDelegatorDelegationsResponse
err := k.cdc.Unmarshal(args, &response)
if err != nil {
return err
}
k.Logger(ctx).Info("Delegation query response", "response", response)
_, delAddr, err := bech32.DecodeAndConvert(delegatorAddress)
if err != nil {
return err
}
delegatorDelegations := k.GetDelegatorDelegations(ctx, &zone, delAddr)
delMap := make(map[string]types.Delegation, len(delegatorDelegations))
for _, del := range delegatorDelegations {
delMap[del.ValidatorAddress] = del
}
for _, delegationRecord := range response.DelegationResponses {
_, valAddr, err := bech32.DecodeAndConvert(delegationRecord.Delegation.ValidatorAddress)
if err != nil {
return err
}
data := stakingtypes.GetDelegationKey(delAddr, valAddr)
delegation, ok := delMap[delegationRecord.Delegation.ValidatorAddress]
if !ok || !delegation.Amount.Equal(delegationRecord.GetBalance()) { // new or updated delegation
k.Logger(ctx).Info("Outdated delegation record - fetching proof...", "valoper", delegationRecord.Delegation.ValidatorAddress)
k.ICQKeeper.MakeRequest(
ctx,
zone.ConnectionId,
zone.ChainId,
"store/staking/key",
data,
sdk.NewInt(-1),
types.ModuleName,
"delegation",
0,
)
// zone.DelegationAddress.IncrementBalanceWaitgroup() // does this get decremented?
}
if ok {
delete(delMap, delegationRecord.Delegation.ValidatorAddress)
}
}
for _, existingValAddr := range utils.Keys(delMap) {
existingDelegation := delMap[existingValAddr]
_, valAddr, err := bech32.DecodeAndConvert(existingDelegation.ValidatorAddress)
if err != nil {
return err
}
data := stakingtypes.GetDelegationKey(delAddr, valAddr)
// send request to prove delegation no longer exists. If the response is nil (i.e. no delegation), then
// the delegation record is removed by the callback.
k.ICQKeeper.MakeRequest(
ctx,
zone.ConnectionId,
zone.ChainId,
"store/staking/key",
data,
sdk.NewInt(-1),
types.ModuleName,
"delegation",
0,
)
}