-
Notifications
You must be signed in to change notification settings - Fork 17
/
keeper_pool.go
1048 lines (925 loc) · 34.8 KB
/
keeper_pool.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 (
"fmt"
"strconv"
"time"
icqueriestypes "github.com/lum-network/chain/x/icqueries/types"
icacontrollerkeeper "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/keeper"
icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types"
"github.com/cosmos/gogoproto/proto"
gogotypes "github.com/cosmos/gogoproto/types"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
distribtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types"
ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types"
clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types"
icacallbackstypes "github.com/lum-network/chain/x/icacallbacks/types"
"github.com/lum-network/chain/x/millions/types"
)
// SetupPoolICA registers the ICA account on the native chain
// - waits for the ICA callback to move to OnSetupPoolICACompleted
// - or go to OnSetupPoolICACompleted directly if local zone
func (k Keeper) SetupPoolICA(ctx sdk.Context, poolID uint64) (*types.Pool, error) {
// Acquire and deserialize our pool entity
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return nil, err
}
if pool.IsLocalZone(ctx) {
// Skip ICA setup for local pools
return k.SetupPoolWithdrawalAddress(ctx, poolID)
}
// Get the chain ID from the connection
chainID, err := k.GetChainID(ctx, pool.GetConnectionId())
if err != nil {
return &pool, errorsmod.Wrapf(types.ErrFailedToRegisterPool, "unable to obtain chain id from connection %s, err: %v", pool.GetConnectionId(), err)
}
if chainID != pool.ChainId {
return &pool, errorsmod.Wrapf(types.ErrFailedToRegisterPool, "provided chain id %s differs from the connection chain id %s", pool.ChainId, chainID)
}
// Compute the app version structure for ICA registration
appVersion, err := k.getPoolAppVersion(ctx, pool)
if err != nil {
return &pool, errorsmod.Wrapf(types.ErrFailedToRegisterPool, err.Error())
}
// Register the accounts deposit account first
// Wait for this account to be setup to register the prize pool account
// This is done to avoid race conditions for the last setup step (SetWithdrawAddress)
pool.IcaDepositPortId = string(types.NewPoolName(pool.GetPoolId(), types.ICATypeDeposit))
if err != nil {
return &pool, errorsmod.Wrapf(types.ErrFailedToRegisterPool, fmt.Sprintf("Unable to create deposit account port id, err: %s", err.Error()))
}
if err := k.ICAControllerKeeper.RegisterInterchainAccount(ctx, pool.GetConnectionId(), pool.GetIcaDepositPortId(), appVersion); err != nil {
return &pool, errorsmod.Wrapf(types.ErrFailedToRegisterPool, fmt.Sprintf("Unable to trigger deposit account registration, err: %s", err.Error()))
}
k.updatePool(ctx, &pool)
return &pool, nil
}
// OnPoolICASetupCompleted Acknowledge the ICA account creation on the native chain
// then moves to SetupPoolWithdrawalAddress once all ICA accounts have been created
func (k Keeper) OnSetupPoolICACompleted(ctx sdk.Context, poolID uint64, icaType string, icaAddress string) (*types.Pool, error) {
logger := k.Logger(ctx).With("ctx", "pool_on_setup_ica_completed")
// Grab our local pool instance
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return nil, err
}
// Make sure our pool is in state created, otherwise just continue without error
if pool.GetState() != types.PoolState_Created {
return &pool, nil
}
// If it's a local pool, not further processing required
if pool.IsLocalZone(ctx) {
// Ignore this step for local pools
return k.SetupPoolWithdrawalAddress(ctx, poolID)
}
if pool.IcaDepositAddress == "" && icaType == types.ICATypeDeposit && len(icaAddress) > 0 {
// Assign the ICA deposit address
pool.IcaDepositAddress = icaAddress
if pool.IcaPrizepoolPortId == "" {
// First time registering ICA Deposit
// Initialize ICA PrizePool
appVersion, err := k.getPoolAppVersion(ctx, pool)
if err != nil {
return &pool, errorsmod.Wrapf(types.ErrFailedToRegisterPool, err.Error())
}
pool.IcaPrizepoolPortId = string(types.NewPoolName(pool.GetPoolId(), types.ICATypePrizePool))
if err != nil {
return &pool, errorsmod.Wrapf(types.ErrFailedToRegisterPool, fmt.Sprintf("Unable to create prizepool account port id, err: %s", err.Error()))
}
if err := k.ICAControllerKeeper.RegisterInterchainAccount(ctx, pool.GetConnectionId(), pool.GetIcaPrizepoolPortId(), appVersion); err != nil {
logger.Error("Unable to trigger prizepool account registration, err: %s", err.Error())
}
}
// Save pool state
k.updatePool(ctx, &pool)
} else if pool.IcaPrizepoolAddress == "" && icaType == types.ICATypePrizePool && len(icaAddress) > 0 {
// Assign the ICA prize pool address
pool.IcaPrizepoolAddress = icaAddress
k.updatePool(ctx, &pool)
}
if len(pool.IcaDepositAddress) > 0 && len(pool.IcaPrizepoolAddress) > 0 {
// Move to next step since both accounts have been created
return k.SetupPoolWithdrawalAddress(ctx, poolID)
}
return &pool, nil
}
// SetupPoolWithdrawalAddress sets the PrizePoolAddress as the Staking withdrawal address for the DepositAddress
// - waits for the ICA callback to move to OnSetupPoolWithdrawalAddressCompleted
// - or go to OnSetupPoolWithdrawalAddressCompleted directly upon setting up the withdrawal address if local zone
func (k Keeper) SetupPoolWithdrawalAddress(ctx sdk.Context, poolID uint64) (*types.Pool, error) {
logger := k.Logger(ctx).With("ctx", "pool_setup_withdrawal")
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return nil, err
}
if pool.GetState() != types.PoolState_Created {
return &pool, nil
}
if pool.IsLocalZone(ctx) {
if err := k.DistributionKeeper.SetWithdrawAddr(
ctx,
sdk.MustAccAddressFromBech32(pool.IcaDepositAddress),
sdk.MustAccAddressFromBech32(pool.IcaPrizepoolAddress),
); err != nil {
logger.Error(
fmt.Sprintf("failed to dispatch set withdrawal address for local pool: %v", err),
"pool_id", poolID,
"chain_id", pool.GetChainId(),
)
return &pool, errorsmod.Wrapf(types.ErrFailedToRegisterPool, err.Error())
}
return k.OnSetupPoolWithdrawalAddressCompleted(ctx, poolID)
}
callbackData := types.SetWithdrawAddressCallback{
PoolId: poolID,
}
marshalledCallbackData, err := k.MarshalSetWithdrawAddressCallbackArgs(ctx, callbackData)
if err != nil {
return &pool, err
}
msgs := []sdk.Msg{&distribtypes.MsgSetWithdrawAddress{
DelegatorAddress: pool.GetIcaDepositAddress(),
WithdrawAddress: pool.GetIcaPrizepoolAddress(),
}}
sequence, err := k.BroadcastICAMessages(ctx, pool, types.ICATypeDeposit, msgs, types.IBCTimeoutNanos, ICACallbackID_SetWithdrawAddress, marshalledCallbackData)
if err != nil {
logger.Error(
fmt.Sprintf("failed to dispatch ICA set withdraw address: %v", err),
"pool_id", poolID,
"chain_id", pool.GetChainId(),
"sequence", sequence,
)
return &pool, errorsmod.Wrapf(types.ErrFailedToRegisterPool, err.Error())
} else {
logger.Debug(
"ICA set withdraw address dispatched",
"pool_id", poolID,
"chain_id", pool.GetChainId(),
"sequence", sequence,
)
}
return &pool, nil
}
// OnSetupPoolWithdrawalAddressCompleted Acknowledge the withdrawal address configuration on the native chain
// then sets the pool to status ready in case of success
func (k Keeper) OnSetupPoolWithdrawalAddressCompleted(ctx sdk.Context, poolID uint64) (*types.Pool, error) {
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return nil, err
}
if pool.GetState() != types.PoolState_Created {
return &pool, nil
}
pool.State = types.PoolState_Ready
k.updatePool(ctx, &pool)
return &pool, nil
}
// GetNextPoolID Return the next pool id to be used
func (k Keeper) GetNextPoolID(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
nextPoolId := gogotypes.UInt64Value{}
b := store.Get(types.NextPoolIdPrefix)
if b == nil {
panic(fmt.Errorf("getting at key (%v) should not have been nil", types.NextPoolIdPrefix))
}
k.cdc.MustUnmarshal(b, &nextPoolId)
return nextPoolId.GetValue()
}
// SetNextPoolID sets next pool ID
func (k Keeper) SetNextPoolID(ctx sdk.Context, poolId uint64) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshal(&gogotypes.UInt64Value{Value: poolId})
store.Set(types.NextPoolIdPrefix, bz)
}
func (k Keeper) GetNextPoolIDAndIncrement(ctx sdk.Context) uint64 {
nextPoolId := k.GetNextPoolID(ctx)
k.SetNextPoolID(ctx, nextPoolId+1)
return nextPoolId
}
// HasPool Returns a boolean that indicates if the given poolID exists in the KVStore or not
func (k Keeper) HasPool(ctx sdk.Context, poolID uint64) bool {
store := ctx.KVStore(k.storeKey)
return store.Has(types.GetPoolKey(poolID))
}
// AddPool Set a pool structure in the KVStore for a given pool ID
func (k Keeper) AddPool(ctx sdk.Context, pool *types.Pool) {
// Automatically affect ID if missing
if pool.GetPoolId() == types.UnknownID {
pool.PoolId = k.GetNextPoolIDAndIncrement(ctx)
}
// Ensure payload is valid
if err := pool.ValidateBasic(k.GetParams(ctx)); err != nil {
panic(err)
}
// Ensure runner is valid
if _, err := k.GetPoolRunner(pool.PoolType); err != nil {
panic(err)
}
// Ensure we never override an existing entity
if k.HasPool(ctx, pool.GetPoolId()) {
panic(errorsmod.Wrapf(types.ErrEntityOverride, "ID %d", pool.GetPoolId()))
}
store := ctx.KVStore(k.storeKey)
encodedPool := k.cdc.MustMarshal(pool)
store.Set(types.GetPoolKey(pool.GetPoolId()), encodedPool)
}
// RegisterPool Register a given pool from the transaction message
func (k Keeper) RegisterPool(
ctx sdk.Context,
poolType types.PoolType,
denom, nativeDenom, chainId, connectionId, transferChannelId string,
vals []string,
bech32Acc, bech32Val string,
minDepositAmount math.Int,
UnbondingDuration time.Duration,
maxUnbondingEntries math.Int,
drawSchedule types.DrawSchedule,
prizeStrategy types.PrizeStrategy,
fees []types.FeeTaker,
) (uint64, error) {
// Acquire new pool ID
poolID := k.GetNextPoolIDAndIncrement(ctx)
// Initialize validators
var validators []types.PoolValidator
for _, addr := range vals {
validators = append(validators, types.PoolValidator{
OperatorAddress: addr,
IsEnabled: true,
BondedAmount: sdk.ZeroInt(),
})
}
// Initialize our local deposit address
localAddress := types.NewPoolAddress(poolID, types.ICATypeDeposit)
poolAccount := k.AccountKeeper.NewAccount(ctx, authtypes.NewModuleAccount(authtypes.NewBaseAccountWithAddress(localAddress), localAddress.String()))
k.AccountKeeper.SetAccount(ctx, poolAccount)
// Prepare new pool
var pool = types.Pool{
PoolId: poolID,
PoolType: poolType,
Denom: denom,
NativeDenom: nativeDenom,
ChainId: chainId,
ConnectionId: connectionId,
Validators: validators,
Bech32PrefixAccAddr: bech32Acc,
Bech32PrefixValAddr: bech32Val,
MinDepositAmount: minDepositAmount,
UnbondingDuration: UnbondingDuration,
MaxUnbondingEntries: maxUnbondingEntries,
DrawSchedule: drawSchedule.Sanitized(),
PrizeStrategy: prizeStrategy,
LocalAddress: localAddress.String(),
NextDrawId: 1,
TvlAmount: sdk.ZeroInt(),
DepositorsCount: 0,
SponsorshipAmount: sdk.ZeroInt(),
AvailablePrizePool: sdk.NewCoin(denom, sdk.ZeroInt()),
State: types.PoolState_Created,
FeeTakers: fees,
TransferChannelId: transferChannelId,
CreatedAtHeight: ctx.BlockHeight(),
UpdatedAtHeight: ctx.BlockHeight(),
CreatedAt: ctx.BlockTime(),
UpdatedAt: ctx.BlockTime(),
}
// Validate pool configuration
if err := pool.ValidateBasic(k.GetParams(ctx)); err != nil {
return 0, errorsmod.Wrapf(types.ErrFailedToRegisterPool, err.Error())
}
// Validate pool runner exists
if _, err := k.GetPoolRunner(poolType); err != nil {
return 0, errorsmod.Wrapf(types.ErrFailedToRegisterPool, err.Error())
}
// If it's a local zone, we have more setup steps for module accounts
if pool.IsLocalZone(ctx) {
// Set the deposit address to the local module account address
pool.IcaDepositAddress = localAddress.String()
// Initialize our local prizepool address
icaPrizePoolAddress := types.NewPoolAddress(poolID, types.ICATypePrizePool)
icaPrizePoolAccount := k.AccountKeeper.NewAccount(ctx, authtypes.NewModuleAccount(authtypes.NewBaseAccountWithAddress(icaPrizePoolAddress), icaPrizePoolAddress.String()))
k.AccountKeeper.SetAccount(ctx, icaPrizePoolAccount)
pool.IcaPrizepoolAddress = icaPrizePoolAddress.String()
}
// Commit the pool to the KVStore
k.AddPool(ctx, &pool)
// Emit event
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName),
),
sdk.NewEvent(
types.EventTypeRegisterPool,
sdk.NewAttribute(types.AttributeKeyPoolID, strconv.FormatUint(pool.PoolId, 10)),
),
})
// Remote zone pool
_, err := k.SetupPoolICA(ctx, poolID)
if err != nil {
return poolID, err
}
return poolID, nil
}
// UpdatePool Update the updatable properties of a pool from the transaction message
func (k Keeper) UpdatePool(
ctx sdk.Context,
poolID uint64,
vals []string,
minDepositAmount *math.Int,
UnbondingDuration *time.Duration,
maxUnbondingEntries *math.Int,
drawSchedule *types.DrawSchedule,
prizeStrategy *types.PrizeStrategy,
state types.PoolState,
feeTakers []types.FeeTaker,
) error {
// Acquire and deserialize our pool entity
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return err
}
// Only a few properties can be updated
if minDepositAmount != nil {
pool.MinDepositAmount = *minDepositAmount
}
if UnbondingDuration != nil {
pool.UnbondingDuration = *UnbondingDuration
}
if maxUnbondingEntries != nil {
pool.MaxUnbondingEntries = *maxUnbondingEntries
}
if drawSchedule != nil {
pool.DrawSchedule = *drawSchedule
if pool.DrawSchedule.InitialDrawAt.After(ctx.BlockTime()) {
// Specifying a new valid InitialDrawAt resets the Pool draw timing to this date
// Also useful for governance to change the timing of Draws in case of time drift
pool.LastDrawCreatedAt = nil
}
}
if prizeStrategy != nil {
pool.PrizeStrategy = *prizeStrategy
}
if feeTakers != nil {
pool.FeeTakers = feeTakers
}
// Update pool state only if current pool state is in paused and incoming state ready
// else if current pool state is in ready and incoming state paused
if state == types.PoolState_Paused && pool.State == types.PoolState_Ready {
pool.State = state
} else if state == types.PoolState_Ready && pool.State == types.PoolState_Paused {
pool.State = state
} else if state != types.PoolState_Unspecified {
return types.ErrPoolStateChangeNotAllowed
}
// Update enabled validators
if pool.PoolType == types.PoolType_Staking && len(vals) > 0 {
for i := range pool.Validators {
pool.Validators[i].IsEnabled = false
}
valIdx := pool.GetValidatorsMapIndex()
for _, addr := range vals {
if _, exists := valIdx[addr]; exists {
pool.Validators[valIdx[addr]].IsEnabled = true
} else {
pool.Validators = append(pool.Validators, types.PoolValidator{
OperatorAddress: addr,
IsEnabled: true,
BondedAmount: sdk.ZeroInt(),
})
valIdx[addr] = len(pool.Validators) - 1
}
}
}
// Validate pool configuration
if err := pool.ValidateBasic(k.GetParams(ctx)); err != nil {
return errorsmod.Wrapf(types.ErrFailedToUpdatePool, err.Error())
}
// Validate pool runner exists
poolRunner, err := k.GetPoolRunner(pool.PoolType)
if err != nil {
return errorsmod.Wrapf(types.ErrFailedToUpdatePool, err.Error())
}
// Commit the pool to the KVStore
k.updatePool(ctx, &pool)
// Trigger rebalance distribution
if err := poolRunner.OnUpdatePool(ctx, pool); err != nil {
return errorsmod.Wrapf(types.ErrFailedToUpdatePool, err.Error())
}
// Emit event
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName),
),
sdk.NewEvent(
types.EventTypeUpdatePool,
sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName),
sdk.NewAttribute(types.AttributeKeyPoolID, strconv.FormatUint(pool.PoolId, 10)),
),
})
return nil
}
// ClosePool iterate through many stages to close a Pool based on its local state, deposits and withdrawals
//
// Closing procedure steps:
// 1. Move pool into state Closing
// 2. Launch the final Draw
// 3. Launch the withdrawal of all the deposits
// 4. Wait for all withdrawals to complete
func (k Keeper) ClosePool(ctx sdk.Context, poolID uint64) error {
logger := k.Logger(ctx).With("ctx", "close_pool", "pool_id", poolID)
// Make sure we always have a valid pool entity
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return err
}
// Make sure the pool can be closed or is already closing
if pool.State != types.PoolState_Ready &&
pool.State != types.PoolState_Paused &&
pool.State != types.PoolState_Closing {
logger.Error(fmt.Sprintf("Impossible state change requested due to pool state %s", pool.State))
return types.ErrPoolStateChangeNotAllowed
}
// Step 1: Pool is not yet in closing state - launch closing procedure
if pool.State != types.PoolState_Closing {
logger.Info("Update pool to state closing")
pool.State = types.PoolState_Closing
pool.UpdatedAt = ctx.BlockTime()
pool.UpdatedAtHeight = ctx.BlockHeight()
k.updatePool(ctx, &pool)
// Launch step 2 final draw
logger.Info("Launch final draw")
if _, err := k.LaunchNewDraw(ctx, poolID); err != nil {
logger.Error(fmt.Sprintf("Error while launching final draw: %v", err))
return err
}
}
// Step 2: Wait for final draw completion
if pool.LastDrawState != types.DrawState_Success {
return nil
}
// Step 3: Initiate the withdrawal of all the deposits
deposits := k.ListPoolDeposits(ctx, poolID)
if len(deposits) > 0 {
logger.Info("Initiate the withdrawal of all deposits")
// As long as we have deposits we will keep trying to withdraw them before moving forward
serv := msgServer{Keeper: k}
for _, deposit := range deposits {
if deposit.State == types.DepositState_Failure {
// Force retry deposits in error states
logger.Info(fmt.Sprintf("Retrying deposit with ID %d in error state %s", deposit.GetDepositId(), deposit.GetErrorState().String()))
_, err := serv.DepositRetry(sdk.WrapSDKContext(ctx), &types.MsgDepositRetry{
PoolId: deposit.GetPoolId(),
DepositId: deposit.GetDepositId(),
DepositorAddress: deposit.GetDepositorAddress(),
})
if err != nil {
logger.Error(fmt.Sprintf("Error while forcing retry for deposit %d: %v", deposit.GetDepositId(), err))
return err
}
} else if deposit.State == types.DepositState_Success {
// Withdraw deposits in success state
logger.Info(fmt.Sprintf("Withdrawing deposit with ID %d", deposit.GetDepositId()))
_, err := serv.WithdrawDeposit(sdk.WrapSDKContext(ctx), types.NewMsgWithdrawDeposit(
deposit.GetDepositorAddress(),
deposit.GetDepositorAddress(),
deposit.GetPoolId(),
deposit.GetDepositId(),
))
if err != nil {
logger.Error(fmt.Sprintf("Error while launching withdrawal for deposit with ID %d: %v", deposit.GetDepositId(), err))
return err
}
}
}
return nil
}
// Step 4: Wait for all withdrawals to complete
withdrawals := k.ListPoolWithdrawals(ctx, poolID)
if len(withdrawals) > 0 {
serv := msgServer{Keeper: k}
for _, withdrawal := range withdrawals {
if withdrawal.State == types.WithdrawalState_Failure {
// Force retry withdrawals in error state
logger.Info(fmt.Sprintf("Retrying withdrawal with ID %d in error state %s", withdrawal.GetWithdrawalId(), withdrawal.GetErrorState().String()))
_, err := serv.WithdrawDepositRetry(sdk.WrapSDKContext(ctx), &types.MsgWithdrawDepositRetry{
PoolId: withdrawal.GetPoolId(),
WithdrawalId: withdrawal.GetWithdrawalId(),
DepositorAddress: withdrawal.GetDepositorAddress(),
})
if err != nil {
logger.Error(fmt.Sprintf("Error while forcing retry for withdrawal with ID %d: %v", withdrawal.GetWithdrawalId(), err))
return err
}
}
}
return nil
}
// Step 5: Clear module dust and close Pool
balance := k.BankKeeper.GetBalance(ctx, sdk.MustAccAddressFromBech32(pool.LocalAddress), pool.Denom)
if balance.IsPositive() {
if err := k.BankKeeper.SendCoinsFromAccountToModule(ctx, sdk.MustAccAddressFromBech32(pool.GetLocalAddress()), authtypes.FeeCollectorName, sdk.NewCoins(balance)); err != nil {
logger.Error(fmt.Sprintf("Failed to transfer dust from pool with ID %d local account to fee collector: %v", poolID, err))
}
}
logger.Info("Update pool to state closed")
pool.State = types.PoolState_Closed
pool.UpdatedAt = ctx.BlockTime()
pool.UpdatedAtHeight = ctx.BlockHeight()
k.updatePool(ctx, &pool)
return nil
}
// RebalanceValidatorsBondings allows rebalancing of validators bonded assets
// Current implementation:
// - Initiate an even redelegate distribution from inactive bonded validators to active validators
func (k Keeper) RebalanceValidatorsBondings(ctx sdk.Context, poolID uint64) error {
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return err
}
// Make sure pool is ready
if pool.State != types.PoolState_Ready && pool.State != types.PoolState_Paused {
return types.ErrPoolNotReady
}
_, valsSrc := pool.BondedValidators()
for _, valSrc := range valsSrc {
// Double check that valSrc is inactive
if !valSrc.IsEnabled {
if err := k.RedelegateToActiveValidatorsOnRemoteZone(ctx, pool.PoolId, valSrc.GetOperatorAddress()); err != nil {
return err
}
}
}
return nil
}
// RedelegateToActiveValidatorsOnRemoteZone redistribute evenly the bondedAmount from the bonded inactive to the active valitator set of the pool
func (k Keeper) RedelegateToActiveValidatorsOnRemoteZone(ctx sdk.Context, poolID uint64, valSrcAddr string) error {
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return err
}
// Make sure pool is ready
if pool.State != types.PoolState_Ready && pool.State != types.PoolState_Paused {
return types.ErrPoolNotReady
}
// Get the validator to redelegate
valIdx := pool.GetValidatorsMapIndex()
index, found := valIdx[valSrcAddr]
if !found {
return errorsmod.Wrapf(types.ErrValidatorNotFound, "%s", valSrcAddr)
}
inactiveVal := pool.Validators[index]
// Check that the validator is inactive
if inactiveVal.IsEnabled {
return errorsmod.Wrapf(
types.ErrInvalidValidatorEnablementStatus,
"status is %t instead of %t",
inactiveVal.IsEnabled, !inactiveVal.IsEnabled,
)
}
splits := pool.ComputeSplitDelegations(ctx, inactiveVal.BondedAmount)
if len(splits) == 0 {
return types.ErrPoolEmptySplitDelegations
}
// Validate pool runner
poolRunner := k.MustGetPoolRunner(pool.PoolType)
// ApplySplitRedelegate to pool validator set
pool.ApplySplitRedelegate(ctx, inactiveVal.GetOperatorAddress(), splits)
k.updatePool(ctx, &pool)
if err := poolRunner.RedelegateToActiveValidatorsOnRemoteZone(ctx, pool, inactiveVal, splits); err != nil {
return err
}
if pool.IsLocalZone(ctx) {
return k.OnRedelegateToActiveValidatorsOnRemoteZoneCompleted(ctx, pool.PoolId, inactiveVal.GetOperatorAddress(), splits, false)
}
return nil
}
// OnRedelegateToActiveValidatorsOnRemoteZoneCompleted Acknowledged a redelegation of an inactive validator's bondedAmount
func (k Keeper) OnRedelegateToActiveValidatorsOnRemoteZoneCompleted(ctx sdk.Context, poolID uint64, valSrcAddr string, splits []*types.SplitDelegation, isError bool) error {
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return err
}
// Get the validator
valIdx := pool.GetValidatorsMapIndex()
index, found := valIdx[valSrcAddr]
if !found {
return errorsmod.Wrapf(types.ErrValidatorNotFound, "%s", valSrcAddr)
}
inactiveVal := pool.Validators[index]
// RevertSplitRedelegate in case of failure
if isError {
pool.RevertSplitRedelegate(ctx, inactiveVal.GetOperatorAddress(), splits)
k.updatePool(ctx, &pool)
return nil
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName),
),
sdk.NewEvent(
types.EventTypeRedelegate,
sdk.NewAttribute(types.AttributeKeyPoolID, strconv.FormatUint(pool.PoolId, 10)),
sdk.NewAttribute(types.AttributeKeyOperatorAddress, inactiveVal.GetOperatorAddress()),
),
})
return nil
}
// UnsafeUpdatePoolPortIds This method raw update the provided pool port ids.
// It's heavily unsafe and could break the ICA implementation. It should only be used by store migrations.
func (k Keeper) UnsafeUpdatePoolPortIds(ctx sdk.Context, poolID uint64, icaDepositPortId, icaPrizePoolPortId string) (types.Pool, error) {
// Grab our pool instance
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return types.Pool{}, err
}
// Patch and update our pool entity
pool.IcaDepositPortId = icaDepositPortId
pool.IcaPrizepoolPortId = icaPrizePoolPortId
k.updatePool(ctx, &pool)
return pool, nil
}
// UnsafeUpdatePoolUnbondingFrequencyAndType raw updates the UnbondingDuration, mexUnbonding and pool type entries
// Unsafe and should only be used for store migration
func (k Keeper) UnsafeUpdatePoolUnbondingFrequencyAndType(ctx sdk.Context, poolID uint64, UnbondingDuration time.Duration, maxUnbondingEntries math.Int, poolType types.PoolType) (types.Pool, error) {
// Grab our pool instance
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return types.Pool{}, err
}
// Patch and update our pool entity
pool.UnbondingDuration = UnbondingDuration
pool.MaxUnbondingEntries = maxUnbondingEntries
pool.PoolType = poolType
k.updatePool(ctx, &pool)
return pool, nil
}
// UnsafeUpdatePoolFeeTakers raw updates the fee takers entries
// Unsafe and should only be used for store migration
func (k Keeper) UnsafeUpdatePoolFeeTakers(ctx sdk.Context, poolID uint64, feeTakers []types.FeeTaker) (types.Pool, error) {
// Grab our pool instance
pool, err := k.GetPool(ctx, poolID)
if err != nil {
return types.Pool{}, err
}
// Patch and update our pool entity
pool.FeeTakers = feeTakers
k.updatePool(ctx, &pool)
return pool, nil
}
func (k Keeper) updatePool(ctx sdk.Context, pool *types.Pool) {
pool.UpdatedAt = ctx.BlockTime()
pool.UpdatedAtHeight = ctx.BlockHeight()
// Ensure payload is valid
if err := pool.ValidateBasic(k.GetParams(ctx)); err != nil {
panic(err)
}
// Validate pool runner exists
if _, err := k.GetPoolRunner(pool.PoolType); err != nil {
panic(err)
}
store := ctx.KVStore(k.storeKey)
encodedPool := k.cdc.MustMarshal(pool)
store.Set(types.GetPoolKey(pool.GetPoolId()), encodedPool)
}
// GetPool Returns a pool instance for the given poolID
func (k Keeper) GetPool(ctx sdk.Context, poolID uint64) (types.Pool, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.GetPoolKey(poolID))
if bz == nil {
return types.Pool{}, errorsmod.Wrapf(types.ErrPoolNotFound, "%d", poolID)
}
var pool types.Pool
if err := k.cdc.Unmarshal(bz, &pool); err != nil {
return types.Pool{}, err
}
return pool, nil
}
func (k Keeper) GetPoolForChainID(ctx sdk.Context, chainID string) (types.Pool, bool) {
var pool = types.Pool{}
found := false
k.IteratePools(ctx, func(p types.Pool) bool {
if p.GetChainId() == chainID {
pool = p
found = true
return true
}
return false
})
return pool, found
}
func (k Keeper) GetPoolForConnectionID(ctx sdk.Context, connectionID string) (types.Pool, bool) {
var pool = types.Pool{}
found := false
k.IteratePools(ctx, func(p types.Pool) bool {
if p.GetConnectionId() == connectionID {
pool = p
found = true
return true
}
return false
})
return pool, found
}
func (k Keeper) GetPoolForControllerPortID(ctx sdk.Context, controllerPortID string) (types.Pool, bool) {
var pool = types.Pool{}
found := false
k.IteratePools(ctx, func(p types.Pool) bool {
if p.GetIcaDepositPortIdWithPrefix() == controllerPortID || p.GetIcaPrizepoolPortIdWithPrefix() == controllerPortID {
pool = p
found = true
return true
}
return false
})
return pool, found
}
// IteratePools Iterate over the pools, and for each entry call the callback
func (k Keeper) IteratePools(ctx sdk.Context, callback func(pool types.Pool) (stop bool)) {
iterator := k.PoolsIterator(ctx)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var pool types.Pool
k.cdc.MustUnmarshal(iterator.Value(), &pool)
if callback(pool) {
break
}
}
}
// PoolsIterator Return a ready to use iterator for the pools store
func (k Keeper) PoolsIterator(ctx sdk.Context) sdk.Iterator {
kvStore := ctx.KVStore(k.storeKey)
return sdk.KVStorePrefixIterator(kvStore, types.PoolPrefix)
}
// ListPools Return the pools
func (k Keeper) ListPools(ctx sdk.Context) (pools []types.Pool) {
k.IteratePools(ctx, func(pool types.Pool) bool {
pools = append(pools, pool)
return false
})
return pools
}
// ListPoolsToDraw Returns the pools which should be launching a Draw
func (k Keeper) ListPoolsToDraw(ctx sdk.Context) (pools []types.Pool) {
allPools := k.ListPools(ctx)
for _, p := range allPools {
if p.ShouldDraw(ctx) {
pools = append(pools, p)
}
}
return pools
}
// BroadcastIBCTransfer broadcasts and IBC transfer for the a given amount to the Pool remote zone ICA Deposit account from the Pool Local address
// Amount denom must be based on pool.Denom
// Also registers the requested callback
// This method should not and DOEST NOT update the pool state
func (k Keeper) BroadcastIBCTransfer(ctx sdk.Context, pool types.Pool, amount sdk.Coin, timeoutNanos uint64, callbackID string, callbackArgs []byte) (uint64, error) {
logger := k.Logger(ctx).With("ctx", "pool_broadcast_ibc")
// We always want our pool to have passed the created state and not be unspecified
if pool.State == types.PoolState_Created || pool.State == types.PoolState_Unspecified {
return 0, types.ErrPoolNotReady
}
// Timeout is now plus 30 minutes in nanoseconds
// We use the standard transfer port ID and not the one opened for ICA
timeoutTimestamp := uint64(ctx.BlockTime().UnixNano()) + timeoutNanos
// From Local to Remote - use transfer channel ID
msg := ibctransfertypes.NewMsgTransfer(
ibctransfertypes.PortID,
pool.GetTransferChannelId(),
amount,
pool.GetLocalAddress(),
pool.GetIcaDepositAddress(),
clienttypes.Height{},
timeoutTimestamp,
"Cosmos Millions",
)
// Broadcast the transfer
res, err := k.IBCTransferKeeper.Transfer(ctx, msg)
if err != nil {
return 0, err
}
if callbackID != "" && callbackArgs != nil {
callback := icacallbackstypes.CallbackData{
CallbackKey: icacallbackstypes.PacketID(msg.SourcePort, msg.SourceChannel, res.Sequence),
PortId: msg.SourcePort,
ChannelId: msg.SourceChannel,
Sequence: res.Sequence,
CallbackId: callbackID,
CallbackArgs: callbackArgs,
}
k.ICACallbacksKeeper.SetCallbackData(ctx, callback)
}
logger.Debug(
fmt.Sprintf("Broadcasted IBC transfer with sequence %d", res.Sequence),
"pool_id", pool.GetPoolId(),
)
return res.Sequence, nil
}
// BroadcastICAMessages broadcasts ICA transaction containing the specified Messages
// Also registers the requested callback
// This method should not and DOEST NOT update the pool state
func (k Keeper) BroadcastICAMessages(ctx sdk.Context, pool types.Pool, accountType string, msgs []sdk.Msg, timeoutNanos uint64, callbackID string, callbackArgs []byte) (uint64, error) {
logger := k.Logger(ctx).With("ctx", "pool_broadcast_ica")
// Pool must be ready or created (creating) to process those kind of operations
if pool.GetState() != types.PoolState_Ready && pool.GetState() != types.PoolState_Created {
return 0, types.ErrPoolNotReady
}
// Acquire the ICA PortID
// Compute the port ID
var portOwner string
var portID string
if accountType == types.ICATypeDeposit {
portOwner = pool.GetIcaDepositPortId()
portID = pool.GetIcaDepositPortIdWithPrefix()
} else if accountType == types.ICATypePrizePool {
portOwner = pool.GetIcaPrizepoolPortId()
portID = pool.GetIcaPrizepoolPortIdWithPrefix()
} else {
return 0, fmt.Errorf("unknown account type %q", accountType)
}
// Acquire the channel capacities
channelID, found := k.ICAControllerKeeper.GetActiveChannelID(ctx, pool.GetConnectionId(), portID)
if !found {
return 0, errorsmod.Wrapf(icatypes.ErrActiveChannelNotFound, "Millions failed to retrieve open active channel for port %s (%s / %s) on connection %s", portID, pool.GetIcaDepositPortId(), pool.GetIcaPrizepoolPortId(), pool.GetConnectionId())
}
// Serialize the data and construct the packet to send
var protoMsgs []proto.Message
for _, msg := range msgs {
protoMsgs = append(protoMsgs, msg)
}
data, err := icatypes.SerializeCosmosTx(k.cdc, protoMsgs)
if err != nil {
return 0, err
}
packetData := icatypes.InterchainAccountPacketData{
Type: icatypes.EXECUTE_TX,
Data: data,
Memo: "Cosmos Millions ICA",
}
// Broadcast the messages
msgServer := icacontrollerkeeper.NewMsgServerImpl(&k.ICAControllerKeeper)
msgSendTx := icacontrollertypes.NewMsgSendTx(portOwner, pool.GetConnectionId(), timeoutNanos, packetData)
res, err := msgServer.SendTx(ctx, msgSendTx)
if err != nil {
return 0, err
}
sequence := res.Sequence
// Store the callback data
if callbackID != "" && callbackArgs != nil {
callback := icacallbackstypes.CallbackData{
CallbackKey: icacallbackstypes.PacketID(portID, channelID, sequence),
PortId: portID,
ChannelId: channelID,
Sequence: sequence,
CallbackId: callbackID,
CallbackArgs: callbackArgs,
}