-
Notifications
You must be signed in to change notification settings - Fork 606
/
e2e_test.go
1852 lines (1506 loc) · 80 KB
/
e2e_test.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 e2e
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/cosmos/cosmos-sdk/types/address"
transfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types"
"github.com/iancoleman/orderedmap"
packetforwardingtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v4/router/types"
"github.com/osmosis-labs/osmosis/osmomath"
ibchookskeeper "github.com/osmosis-labs/osmosis/x/ibc-hooks/keeper"
ibcratelimittypes "github.com/osmosis-labs/osmosis/v17/x/ibc-rate-limit/types"
poolmanagertypes "github.com/osmosis-labs/osmosis/v17/x/poolmanager/types"
sdk "github.com/cosmos/cosmos-sdk/types"
coretypes "github.com/tendermint/tendermint/rpc/core/types"
"github.com/osmosis-labs/osmosis/osmoutils/osmoassert"
appparams "github.com/osmosis-labs/osmosis/v17/app/params"
v17 "github.com/osmosis-labs/osmosis/v17/app/upgrades/v17"
"github.com/osmosis-labs/osmosis/v17/tests/e2e/configurer/chain"
"github.com/osmosis-labs/osmosis/v17/tests/e2e/configurer/config"
"github.com/osmosis-labs/osmosis/v17/tests/e2e/initialization"
clmath "github.com/osmosis-labs/osmosis/v17/x/concentrated-liquidity/math"
cltypes "github.com/osmosis-labs/osmosis/v17/x/concentrated-liquidity/types"
protorevtypes "github.com/osmosis-labs/osmosis/v17/x/protorev/types"
)
var (
// minDecTolerance minimum tolerance for sdk.Dec, given its precision of 18.
minDecTolerance = sdk.MustNewDecFromStr("0.000000000000000001")
)
// TODO: Find more scalable way to do this
func (s *IntegrationTestSuite) TestAllE2E() {
// Zero Dependent Tests
s.T().Run("CreateConcentratedLiquidityPoolVoting_And_TWAP", func(t *testing.T) {
t.Parallel()
s.CreateConcentratedLiquidityPoolVoting_And_TWAP()
})
s.T().Run("ProtoRev", func(t *testing.T) {
t.Parallel()
s.ProtoRev()
})
s.T().Run("ConcentratedLiquidity", func(t *testing.T) {
t.Parallel()
s.ConcentratedLiquidity()
})
s.T().Run("SuperfluidVoting", func(t *testing.T) {
t.Parallel()
s.SuperfluidVoting()
})
s.T().Run("AddToExistingLock", func(t *testing.T) {
t.Parallel()
s.AddToExistingLock()
})
s.T().Run("ExpeditedProposals", func(t *testing.T) {
t.Parallel()
s.ExpeditedProposals()
})
s.T().Run("GeometricTWAP", func(t *testing.T) {
t.Parallel()
s.GeometricTWAP()
})
s.T().Run("LargeWasmUpload", func(t *testing.T) {
t.Parallel()
s.LargeWasmUpload()
})
// Test currently disabled
// s.T().Run("ArithmeticTWAP", func(t *testing.T) {
// t.Parallel()
// s.ArithmeticTWAP()
// })
// State Sync Dependent Tests
if s.skipStateSync {
s.T().Skip()
} else {
s.T().Run("StateSync", func(t *testing.T) {
t.Parallel()
s.StateSync()
})
}
// Upgrade Dependent Tests
if s.skipUpgrade {
s.T().Skip("Skipping StableSwapPostUpgrade test")
} else {
s.T().Run("StableSwapPostUpgrade", func(t *testing.T) {
t.Parallel()
s.StableSwapPostUpgrade()
})
}
if s.skipUpgrade {
s.T().Skip("Skipping GeometricTwapMigration test")
} else {
s.T().Run("GeometricTwapMigration", func(t *testing.T) {
t.Parallel()
s.GeometricTwapMigration()
})
}
if s.skipUpgrade {
s.T().Skip("Skipping AddToExistingLockPostUpgrade test")
} else {
s.T().Run("AddToExistingLockPostUpgrade", func(t *testing.T) {
t.Parallel()
s.AddToExistingLockPostUpgrade()
})
}
if s.skipUpgrade {
s.T().Skip("Skipping ConcentratedLiquidity_CanonicalPools test")
} else {
s.T().Run("ConcentratedLiquidity_CanonicalPools", func(t *testing.T) {
t.Parallel()
s.ConcentratedLiquidity_CanonicalPools()
})
}
// IBC Dependent Tests
if s.skipIBC {
s.T().Skip("Skipping IBC tests")
} else {
s.T().Run("IBCTokenTransferRateLimiting", func(t *testing.T) {
t.Parallel()
s.IBCTokenTransferRateLimiting()
})
}
if s.skipIBC {
s.T().Skip("Skipping IBC tests")
} else {
s.T().Run("IBCTokenTransferAndCreatePool", func(t *testing.T) {
t.Parallel()
s.IBCTokenTransferAndCreatePool()
})
}
if s.skipIBC {
s.T().Skip("Skipping IBC tests")
} else {
s.T().Run("IBCWasmHooks", func(t *testing.T) {
t.Parallel()
s.IBCWasmHooks()
})
}
if s.skipIBC {
s.T().Skip("Skipping IBC tests")
} else {
s.T().Run("PacketForwarding", func(t *testing.T) {
t.Parallel()
s.PacketForwarding()
})
}
}
// TestProtoRev is a test that ensures that the protorev module is working as expected. In particular, this tests and ensures that:
// 1. The protorev module is correctly configured on init
// 2. The protorev module can correctly back run a swap
// 3. the protorev module correctly tracks statistics
func (s *IntegrationTestSuite) ProtoRev() {
const (
poolFile1 = "protorevPool1.json"
poolFile2 = "protorevPool2.json"
poolFile3 = "protorevPool3.json"
walletName = "swap-that-creates-an-arb"
denomIn = initialization.LuncIBCDenom
denomOut = initialization.UstIBCDenom
amount = "10000"
minAmountOut = "1"
epochIdentifier = "day"
)
// NOTE: Uses chainA since IBC denoms are hard coded.
chainA, chainANode, err := s.getChainACfgs()
s.Require().NoError(err)
sender := chainANode.GetWallet(initialization.ValidatorWalletName)
// --------------- Module init checks ---------------- //
// The module should be enabled by default.
enabled, err := chainANode.QueryProtoRevEnabled()
s.T().Logf("checking that the protorev module is enabled: %t", enabled)
s.Require().NoError(err)
s.Require().True(enabled)
// The module should have no new hot routes by default.
hotRoutes, err := chainANode.QueryProtoRevTokenPairArbRoutes()
s.T().Logf("checking that the protorev module has no new hot routes: %v", hotRoutes)
s.Require().NoError(err)
s.Require().Len(hotRoutes, 0)
// The module should have no trades by default.
_, err = chainANode.QueryProtoRevNumberOfTrades()
s.T().Logf("checking that the protorev module has no trades on init: %s", err)
s.Require().Error(err)
// The module should have pool weights by default.
info, err := chainANode.QueryProtoRevInfoByPoolType()
s.T().Logf("checking that the protorev module has pool info on init: %v", info)
s.Require().NoError(err)
s.Require().NotNil(info)
// The module should have max pool points per tx by default.
maxPoolPointsPerTx, err := chainANode.QueryProtoRevMaxPoolPointsPerTx()
s.T().Logf("checking that the protorev module has max pool points per tx on init: %d", maxPoolPointsPerTx)
s.Require().NoError(err)
// The module should have max pool points per block by default.
maxPoolPointsPerBlock, err := chainANode.QueryProtoRevMaxPoolPointsPerBlock()
s.T().Logf("checking that the protorev module has max pool points per block on init: %d", maxPoolPointsPerBlock)
s.Require().NoError(err)
// The module should have only osmosis as a supported base denom by default.
supportedBaseDenoms, err := chainANode.QueryProtoRevBaseDenoms()
s.T().Logf("checking that the protorev module has only osmosis as a supported base denom on init: %v", supportedBaseDenoms)
s.Require().NoError(err)
s.Require().Len(supportedBaseDenoms, 1)
s.Require().Equal(supportedBaseDenoms[0].Denom, "uosmo")
// --------------- Set up for a calculated backrun ---------------- //
// Create all of the pools that will be used in the test.
swapPoolId1 := chainANode.CreateBalancerPool(poolFile1, initialization.ValidatorWalletName)
swapPoolId2 := chainANode.CreateBalancerPool(poolFile2, initialization.ValidatorWalletName)
swapPoolId3 := chainANode.CreateBalancerPool(poolFile3, initialization.ValidatorWalletName)
// Wait for the creation to be propogated to the other nodes + for the protorev module to
// correctly update the highest liquidity pools.
s.T().Logf("waiting for the protorev module to update the highest liquidity pools (wait %.f sec) after the week epoch duration", initialization.EpochDayDuration.Seconds())
chainA.WaitForNumEpochs(1, epochIdentifier)
// Create a wallet to use for the swap txs.
swapWalletAddr := chainANode.CreateWallet(walletName, chainA)
coinIn := fmt.Sprintf("%s%s", amount, denomIn)
chainANode.BankSend(coinIn, sender, swapWalletAddr)
// Check supplies before swap.
supplyBefore, err := chainANode.QuerySupply()
s.Require().NoError(err)
s.Require().NotNil(supplyBefore)
// Performing the swap that creates a cyclic arbitrage opportunity.
s.T().Logf("performing a swap that creates a cyclic arbitrage opportunity")
chainANode.SwapExactAmountIn(coinIn, minAmountOut, fmt.Sprintf("%d", swapPoolId2), denomOut, swapWalletAddr)
// --------------- Module checks after a calculated backrun ---------------- //
// Check that the supplies have not changed.
s.T().Logf("checking that the supplies have not changed")
supplyAfter, err := chainANode.QuerySupply()
s.Require().NoError(err)
s.Require().NotNil(supplyAfter)
s.Require().Equal(supplyBefore, supplyAfter)
// Check that the number of trades executed by the protorev module is 1.
numTrades, err := chainANode.QueryProtoRevNumberOfTrades()
s.T().Logf("checking that the protorev module has executed 1 trade")
s.Require().NoError(err)
s.Require().NotNil(numTrades)
s.Require().Equal(uint64(1), numTrades.Uint64())
// Check that the profits of the protorev module are not nil.
profits, err := chainANode.QueryProtoRevProfits()
s.T().Logf("checking that the protorev module has non-nil profits: %s", profits)
s.Require().NoError(err)
s.Require().NotNil(profits)
s.Require().Len(profits, 1)
// Check that the route statistics of the protorev module are not nil.
routeStats, err := chainANode.QueryProtoRevAllRouteStatistics()
s.T().Logf("checking that the protorev module has non-nil route statistics: %x", routeStats)
s.Require().NoError(err)
s.Require().NotNil(routeStats)
s.Require().Len(routeStats, 1)
s.Require().Equal(sdk.OneInt(), routeStats[0].NumberOfTrades)
s.Require().Equal([]uint64{swapPoolId1, swapPoolId2, swapPoolId3}, routeStats[0].Route)
s.Require().Equal(profits, routeStats[0].Profits)
}
func (s *IntegrationTestSuite) ConcentratedLiquidity() {
var (
denom0 = "uion"
denom1 = "uosmo"
tickSpacing uint64 = 100
spreadFactor = "0.001" // 0.1%
spreadFactorDec = sdk.MustNewDecFromStr("0.001")
)
chainAB, chainABNode, err := s.getChainCfgs()
s.Require().NoError(err)
// Get the permisionless pool creation parameter.
isPermisionlessCreationEnabledStr := chainABNode.QueryParams(cltypes.ModuleName, string(cltypes.KeyIsPermisionlessPoolCreationEnabled))
if !strings.EqualFold(isPermisionlessCreationEnabledStr, "false") {
s.T().Fatal("concentrated liquidity pool creation is enabled when should not have been")
}
// Change the parameter to enable permisionless pool creation.
err = chainABNode.ParamChangeProposal("concentratedliquidity", string(cltypes.KeyIsPermisionlessPoolCreationEnabled), []byte("true"), chainAB)
s.Require().NoError(err)
// Change the parameter to disable protorev
err = chainABNode.ParamChangeProposal("protorev", string(protorevtypes.ParamStoreKeyEnableModule), []byte("false"), chainAB)
s.Require().NoError(err)
// Confirm that the parameter has been changed.
isPermisionlessCreationEnabledStr = chainABNode.QueryParams(cltypes.ModuleName, string(cltypes.KeyIsPermisionlessPoolCreationEnabled))
if !strings.EqualFold(isPermisionlessCreationEnabledStr, "true") {
s.T().Fatal("concentrated liquidity pool creation is not enabled")
}
// Create concentrated liquidity pool when permisionless pool creation is enabled.
poolID := chainABNode.CreateConcentratedPool(initialization.ValidatorWalletName, denom0, denom1, tickSpacing, spreadFactor)
concentratedPool := s.updatedConcentratedPool(chainABNode, poolID)
// Sanity check that pool initialized with valid parameters (the ones that we haven't explicitly specified)
s.Require().Equal(concentratedPool.GetCurrentTick(), int64(0))
s.Require().Equal(concentratedPool.GetCurrentSqrtPrice(), osmomath.ZeroDec())
s.Require().Equal(concentratedPool.GetLiquidity(), sdk.ZeroDec())
// Assert contents of the pool are valid (that we explicitly specified)
s.Require().Equal(concentratedPool.GetId(), poolID)
s.Require().Equal(concentratedPool.GetToken0(), denom0)
s.Require().Equal(concentratedPool.GetToken1(), denom1)
s.Require().Equal(concentratedPool.GetTickSpacing(), tickSpacing)
s.Require().Equal(concentratedPool.GetExponentAtPriceOne(), cltypes.ExponentAtPriceOne)
s.Require().Equal(concentratedPool.GetSpreadFactor(sdk.Context{}), sdk.MustNewDecFromStr(spreadFactor))
fundTokens := []string{"100000000uosmo", "100000000uion", "100000000stake"}
// Get 3 addresses to create positions
address1 := chainABNode.CreateWalletAndFund("addr1", fundTokens, chainAB)
address2 := chainABNode.CreateWalletAndFund("addr2", fundTokens, chainAB)
address3 := chainABNode.CreateWalletAndFund("addr3", fundTokens, chainAB)
// Create 2 positions for address1: overlap together, overlap with 2 address3 positions
chainABNode.CreateConcentratedPosition(address1, "[-120000]", "40000", fmt.Sprintf("10000000%s,10000000%s", denom0, denom1), 0, 0, poolID)
chainABNode.CreateConcentratedPosition(address1, "[-40000]", "120000", fmt.Sprintf("10000000%s,10000000%s", denom0, denom1), 0, 0, poolID)
// Create 1 position for address2: does not overlap with anything, ends at maximum
chainABNode.CreateConcentratedPosition(address2, "220000", fmt.Sprintf("%d", cltypes.MaxTick), fmt.Sprintf("10000000%s,10000000%s", denom0, denom1), 0, 0, poolID)
// Create 2 positions for address3: overlap together, overlap with 2 address1 positions, one position starts from minimum
chainABNode.CreateConcentratedPosition(address3, "[-160000]", "[-20000]", fmt.Sprintf("10000000%s,10000000%s", denom0, denom1), 0, 0, poolID)
chainABNode.CreateConcentratedPosition(address3, fmt.Sprintf("[%d]", cltypes.MinInitializedTick), "140000", fmt.Sprintf("10000000%s,10000000%s", denom0, denom1), 0, 0, poolID)
// Get newly created positions
positionsAddress1 := chainABNode.QueryConcentratedPositions(address1)
positionsAddress2 := chainABNode.QueryConcentratedPositions(address2)
positionsAddress3 := chainABNode.QueryConcentratedPositions(address3)
concentratedPool = s.updatedConcentratedPool(chainABNode, poolID)
// Assert number of positions per address
s.Require().Equal(len(positionsAddress1), 2)
s.Require().Equal(len(positionsAddress2), 1)
s.Require().Equal(len(positionsAddress3), 2)
// Assert positions for address1
addr1position1 := positionsAddress1[0].Position
addr1position2 := positionsAddress1[1].Position
// First position first address
s.validateCLPosition(addr1position1, poolID, -120000, 40000)
// Second position second address
s.validateCLPosition(addr1position2, poolID, -40000, 120000)
// Assert positions for address2
addr2position1 := positionsAddress2[0].Position
// First position second address
s.validateCLPosition(addr2position1, poolID, 220000, cltypes.MaxTick)
// Assert positions for address3
addr3position1 := positionsAddress3[0].Position
addr3position2 := positionsAddress3[1].Position
// First position third address
s.validateCLPosition(addr3position1, poolID, -160000, -20000)
// Second position third address
s.validateCLPosition(addr3position2, poolID, cltypes.MinInitializedTick, 140000)
// Collect SpreadRewards
var (
// spreadRewardGrowthGlobal is a variable for tracking global spread reward growth
spreadRewardGrowthGlobal = sdk.ZeroDec()
outMinAmt = "1"
)
// Swap 1
// Not crossing initialized ticks => performed in one swap step
// Swap affects 3 positions: both that address1 has and one of address3's positions
// Asserts that spread rewards are correctly collected for non cross-tick swaps
var (
// Swap parameters
uosmoInDec_Swap1 = osmomath.NewBigDec(3465198)
uosmoIn_Swap1 = fmt.Sprintf("%suosmo", uosmoInDec_Swap1.SDKDec().String())
)
// Perform swap (not crossing initialized ticks)
chainABNode.SwapExactAmountIn(uosmoIn_Swap1, outMinAmt, fmt.Sprintf("%d", poolID), denom0, initialization.ValidatorWalletName)
// Calculate and track global spread reward growth for swap 1
spreadRewardGrowthGlobal.AddMut(calculateSpreadRewardGrowthGlobal(uosmoInDec_Swap1.SDKDec(), spreadFactorDec, concentratedPool.GetLiquidity()))
// Update pool and track liquidity and sqrt price
liquidityBeforeSwap := concentratedPool.GetLiquidity()
sqrtPriceBeforeSwap := concentratedPool.GetCurrentSqrtPrice()
concentratedPool = s.updatedConcentratedPool(chainABNode, poolID)
liquidityAfterSwap := concentratedPool.GetLiquidity()
sqrtPriceAfterSwap := concentratedPool.GetCurrentSqrtPrice()
// Assert swaps don't change pool's liquidity amount
s.Require().Equal(liquidityAfterSwap.String(), liquidityBeforeSwap.String())
// Assert current sqrt price
inAmountSubSpreadReward := uosmoInDec_Swap1.Mul(osmomath.OneDec().Sub(osmomath.BigDecFromSDKDec(spreadFactorDec)))
expectedSqrtPriceDelta := inAmountSubSpreadReward.QuoTruncate(osmomath.BigDecFromSDKDec(concentratedPool.GetLiquidity())) // Δ(sqrtPrice) = Δy / L
expectedSqrtPrice := sqrtPriceBeforeSwap.Add(expectedSqrtPriceDelta)
s.Require().Equal(expectedSqrtPrice.String(), sqrtPriceAfterSwap.String())
// Collect SpreadRewards: Swap 1
// Track balances for address1 position1
addr1BalancesBefore := s.addrBalance(chainABNode, address1)
chainABNode.CollectSpreadRewards(address1, fmt.Sprint(positionsAddress1[0].Position.PositionId))
addr1BalancesAfter := s.addrBalance(chainABNode, address1)
// Assert that the balance changed only for tokenIn (uosmo)
s.assertBalancesInvariants(addr1BalancesBefore, addr1BalancesAfter, false, true)
// Assert Balances: Swap 1
// Calculate uncollected spread rewards for address1 position1
spreadRewardsUncollectedAddress1Position1_Swap1 := calculateUncollectedSpreadRewards(
positionsAddress1[0].Position.Liquidity,
sdk.ZeroDec(), // no growth below
sdk.ZeroDec(), // no growth above
sdk.ZeroDec(), // no spreadRewardGrowthInsideLast - it is the first swap
spreadRewardGrowthGlobal,
)
// Assert
s.Require().Equal(
addr1BalancesBefore.AmountOf("uosmo").Add(spreadRewardsUncollectedAddress1Position1_Swap1.TruncateInt()).String(),
addr1BalancesAfter.AmountOf("uosmo").String(),
)
// Swap 2
//
// Cross-tick swap:
// * Part of swap happens in range of liquidity of 3 positions: both of address1 and one for address3 (until tick 40000 - upper tick of address1 position1)
// * Another part happens in range of liquidity of 2 positions: one from address1 and address3
//
// Asserts:
// * Net liquidity is kicked out when crossing initialized tick
// * Liquidity of position that was kicked out after first swap step does not earn rewards from second swap step
// * Uncollected spread rewards from multiple swaps are correctly summed up and collected
// tickOffset is a tick index after the next initialized tick to which this swap needs to move the current price
tickOffset := int64(300)
sqrtPriceBeforeSwap = concentratedPool.GetCurrentSqrtPrice()
liquidityBeforeSwap = concentratedPool.GetLiquidity()
nextInitTick := int64(40000) // address1 position1's upper tick
// Calculate sqrtPrice after and at the next initialized tick (upperTick of address1 position1 - 40000)
_, sqrtPriceAfterNextInitializedTick, err := clmath.TickToSqrtPrice(nextInitTick + tickOffset)
s.Require().NoError(err)
_, sqrtPriceAtNextInitializedTick, err := clmath.TickToSqrtPrice(nextInitTick)
s.Require().NoError(err)
sqrtPriceAfterNextInitializedTickBigDec := osmomath.BigDecFromSDKDec(sqrtPriceAfterNextInitializedTick)
sqrtPriceAtNextInitializedTickBigDec := osmomath.BigDecFromSDKDec(sqrtPriceAtNextInitializedTick)
// Calculate Δ(sqrtPrice):
// deltaSqrtPriceAfterNextInitializedTick = ΔsqrtP(40300) - ΔsqrtP(40000)
// deltaSqrtPriceAtNextInitializedTick = ΔsqrtP(40000) - ΔsqrtP(currentTick)
deltaSqrtPriceAfterNextInitializedTick := sqrtPriceAfterNextInitializedTickBigDec.Sub(sqrtPriceAtNextInitializedTickBigDec).SDKDec()
deltaSqrtPriceAtNextInitializedTick := sqrtPriceAtNextInitializedTickBigDec.Sub(sqrtPriceBeforeSwap).SDKDec()
// Calculate the amount of osmo required to:
// * amountInToGetToTickAfterInitialized - move price from next initialized tick (40000) to destination tick (40000 + tickOffset)
// * amountInToGetToNextInitTick - move price from current tick to next initialized tick
// Formula is as follows:
// Δy = L * Δ(sqrtPrice)
amountInToGetToTickAfterInitialized := deltaSqrtPriceAfterNextInitializedTick.Mul(liquidityBeforeSwap.Sub(positionsAddress1[0].Position.Liquidity))
amountInToGetToNextInitTick := deltaSqrtPriceAtNextInitializedTick.Mul(liquidityBeforeSwap)
var (
// Swap parameters
// uosmoInDec_Swap2_NoSpreadReward is calculated such that swapping this amount (not considering spread reward) moves the price over the next initialized tick
uosmoInDec_Swap2_NoSpreadReward = amountInToGetToNextInitTick.Add(amountInToGetToTickAfterInitialized)
uosmoInDec_Swap2 = uosmoInDec_Swap2_NoSpreadReward.Quo(sdk.OneDec().Sub(spreadFactorDec)).TruncateDec() // account for spread factor of 1%
uosmoIn_Swap2 = fmt.Sprintf("%suosmo", uosmoInDec_Swap2.String())
spreadRewardGrowthGlobal_Swap1 = spreadRewardGrowthGlobal.Clone()
)
// Perform a swap
chainABNode.SwapExactAmountIn(uosmoIn_Swap2, outMinAmt, fmt.Sprintf("%d", poolID), denom0, initialization.ValidatorWalletName)
// Calculate the amount of liquidity of the position that was kicked out during swap (address1 position1)
liquidityOfKickedOutPosition := positionsAddress1[0].Position.Liquidity
// Update pool and track pool's liquidity
concentratedPool = s.updatedConcentratedPool(chainABNode, poolID)
liquidityAfterSwap = concentratedPool.GetLiquidity()
// Assert that net liquidity of kicked out position was successfully removed from current pool's liquidity
s.Require().Equal(liquidityBeforeSwap.Sub(liquidityOfKickedOutPosition), liquidityAfterSwap)
// Collect spread rewards: Swap 2
// Calculate spread reward charges per each step
// Step1: amountIn is uosmo tokens that are swapped + uosmo tokens that are paid for spread reward
// hasReachedTarget in SwapStep is true, hence, to find spread rewards, calculate:
// spreadRewardCharge = amountIn * spreadFactor / (1 - spreadFactor)
spreadRewardCharge_Swap2_Step1 := amountInToGetToNextInitTick.Mul(spreadFactorDec).Quo(sdk.OneDec().Sub(spreadFactorDec))
// Step2: hasReachedTarget in SwapStep is false (nextTick is 120000), hence, to find spread rewards, calculate:
// spreadRewardCharge = amountRemaining - amountOne
amountRemainingAfterStep1 := uosmoInDec_Swap2.Sub(amountInToGetToNextInitTick).Sub(spreadRewardCharge_Swap2_Step1)
spreadRewardCharge_Swap2_Step2 := amountRemainingAfterStep1.Sub(amountInToGetToTickAfterInitialized)
// per unit of virtual liquidity
spreadRewardCharge_Swap2_Step1.QuoMut(liquidityBeforeSwap)
spreadRewardCharge_Swap2_Step2.QuoMut(liquidityAfterSwap)
// Update spreadRewardGrowthGlobal
spreadRewardGrowthGlobal.AddMut(spreadRewardCharge_Swap2_Step1.Add(spreadRewardCharge_Swap2_Step2))
// Assert Balances: Swap 2
// Assert that address1 position1 earned spread rewards only from first swap step
// Track balances for address1 position1
addr1BalancesBefore = s.addrBalance(chainABNode, address1)
chainABNode.CollectSpreadRewards(address1, fmt.Sprint(positionsAddress1[0].Position.PositionId))
addr1BalancesAfter = s.addrBalance(chainABNode, address1)
// Assert that the balance changed only for tokenIn (uosmo)
s.assertBalancesInvariants(addr1BalancesBefore, addr1BalancesAfter, false, true)
// Calculate uncollected spread rewards for position, which liquidity will only be live part of the swap
spreadRewardsUncollectedAddress1Position1_Swap2 := calculateUncollectedSpreadRewards(
positionsAddress1[0].Position.Liquidity,
sdk.ZeroDec(),
sdk.ZeroDec(),
calculateSpreadRewardGrowthInside(spreadRewardGrowthGlobal_Swap1, sdk.ZeroDec(), sdk.ZeroDec()),
spreadRewardGrowthGlobal_Swap1.Add(spreadRewardCharge_Swap2_Step1), // cannot use spreadRewardGrowthGlobal, it was already increased by second swap's step
)
// Assert
s.Require().Equal(
addr1BalancesBefore.AmountOf("uosmo").Add(spreadRewardsUncollectedAddress1Position1_Swap2.TruncateInt()),
addr1BalancesAfter.AmountOf("uosmo"),
)
// Assert that address3 position2 earned rewards from first and second swaps
// Track balance off address3 position2: check that position that has not been kicked out earned full rewards
addr3BalancesBefore := s.addrBalance(chainABNode, address3)
chainABNode.CollectSpreadRewards(address3, fmt.Sprint(positionsAddress3[1].Position.PositionId))
addr3BalancesAfter := s.addrBalance(chainABNode, address3)
// Calculate uncollected spread rewards for address3 position2 earned from Swap 1
spreadRewardsUncollectedAddress3Position2_Swap1 := calculateUncollectedSpreadRewards(
positionsAddress3[1].Position.Liquidity,
sdk.ZeroDec(),
sdk.ZeroDec(),
sdk.ZeroDec(),
spreadRewardGrowthGlobal_Swap1,
)
// Calculate uncollected spread rewards for address3 position2 (was active throughout both swap steps): Swap2
spreadRewardsUncollectedAddress3Position2_Swap2 := calculateUncollectedSpreadRewards(
positionsAddress3[1].Position.Liquidity,
sdk.ZeroDec(),
sdk.ZeroDec(),
calculateSpreadRewardGrowthInside(spreadRewardGrowthGlobal_Swap1, sdk.ZeroDec(), sdk.ZeroDec()),
spreadRewardGrowthGlobal,
)
// Total spread rewards earned by address3 position2 from 2 swaps
totalUncollectedSpreadRewardsAddress3Position2 := spreadRewardsUncollectedAddress3Position2_Swap1.Add(spreadRewardsUncollectedAddress3Position2_Swap2)
// Assert
s.Require().Equal(
addr3BalancesBefore.AmountOf("uosmo").Add(totalUncollectedSpreadRewardsAddress3Position2.TruncateInt()),
addr3BalancesAfter.AmountOf("uosmo"),
)
// Swap 3
// Asserts:
// * swapping amountZero for amountOne works correctly
// * liquidity of positions that come in range are correctly kicked in
// tickOffset is a tick index after the next initialized tick to which this swap needs to move the current price
tickOffset = 300
sqrtPriceBeforeSwap = concentratedPool.GetCurrentSqrtPrice()
liquidityBeforeSwap = concentratedPool.GetLiquidity()
nextInitTick = 40000
// Calculate amount required to get to
// 1) next initialized tick
// 2) tick below next initialized (-300)
// Using: CalcAmount0Delta = liquidity * ((sqrtPriceB - sqrtPriceA) / (sqrtPriceB * sqrtPriceA))
// Calculate sqrtPrice after and at the next initialized tick (which is upperTick of address1 position1 - 40000)
_, sqrtPricebBelowNextInitializedTick, err := clmath.TickToSqrtPrice(nextInitTick - tickOffset)
s.Require().NoError(err)
_, sqrtPriceAtNextInitializedTick, err = clmath.TickToSqrtPrice(nextInitTick)
s.Require().NoError(err)
sqrtPriceAtNextInitializedTickBigDec = osmomath.BigDecFromSDKDec(sqrtPriceAtNextInitializedTick)
// Calculate numerators
numeratorBelowNextInitializedTick := sqrtPriceAtNextInitializedTick.Sub(sqrtPricebBelowNextInitializedTick)
numeratorNextInitializedTick := sqrtPriceBeforeSwap.Sub(sqrtPriceAtNextInitializedTickBigDec)
// Calculate denominators
denominatorBelowNextInitializedTick := sqrtPriceAtNextInitializedTick.Mul(sqrtPricebBelowNextInitializedTick)
denominatorNextInitializedTick := sqrtPriceBeforeSwap.Mul(sqrtPriceAtNextInitializedTickBigDec)
// Calculate fractions
fractionBelowNextInitializedTick := numeratorBelowNextInitializedTick.Quo(denominatorBelowNextInitializedTick)
fractionAtNextInitializedTick := numeratorNextInitializedTick.Quo(denominatorNextInitializedTick)
// Calculate amounts of uionIn needed
amountInToGetToTickBelowInitialized := liquidityBeforeSwap.Add(positionsAddress1[0].Position.Liquidity).Mul(fractionBelowNextInitializedTick)
amountInToGetToNextInitTick = liquidityBeforeSwap.Mul(fractionAtNextInitializedTick.SDKDec())
var (
// Swap parameters
uionInDec_Swap3_NoSpreadReward = amountInToGetToNextInitTick.Add(amountInToGetToTickBelowInitialized) // amount of uion to move price from current to desired (not considering spreadFactor)
uionInDec_Swap3 = uionInDec_Swap3_NoSpreadReward.Quo(sdk.OneDec().Sub(spreadFactorDec)).TruncateDec() // consider spreadFactor
uionIn_Swap3 = fmt.Sprintf("%suion", uionInDec_Swap3.String())
// Save variables from previous swaps
spreadRewardGrowthGlobal_Swap2 = spreadRewardGrowthGlobal.Clone()
spreadRewardGrowthInsideAddress1Position1Last = spreadRewardGrowthGlobal_Swap1.Add(spreadRewardCharge_Swap2_Step1)
)
// Collect spread rewards for address1 position1 to avoid overhead computations (swap2 already asserted spread rewards are aggregated correctly from multiple swaps)
chainABNode.CollectSpreadRewards(address1, fmt.Sprint(positionsAddress1[0].Position.PositionId))
// Perform a swap
chainABNode.SwapExactAmountIn(uionIn_Swap3, outMinAmt, fmt.Sprintf("%d", poolID), denom1, initialization.ValidatorWalletName)
// Assert liquidity of kicked in position was successfully added to the pool
concentratedPool = s.updatedConcentratedPool(chainABNode, poolID)
liquidityAfterSwap = concentratedPool.GetLiquidity()
s.Require().Equal(liquidityBeforeSwap.Add(positionsAddress1[0].Position.Liquidity), liquidityAfterSwap)
// Track balance of address1
addr1BalancesBefore = s.addrBalance(chainABNode, address1)
chainABNode.CollectSpreadRewards(address1, fmt.Sprint(positionsAddress1[0].Position.PositionId))
addr1BalancesAfter = s.addrBalance(chainABNode, address1)
// Assert that the balance changed only for tokenIn (uion)
s.assertBalancesInvariants(addr1BalancesBefore, addr1BalancesAfter, true, false)
// Assert the amount of collected spread rewards:
// Step1: amountIn is uion tokens that are swapped + uion tokens that are paid for spread reward
// hasReachedTarget in SwapStep is true, hence, to find spread rewards, calculate:
// spreadRewardCharge = amountIn * spreadFactor / (1 - spreadFactor)
spreadRewardCharge_Swap3_Step1 := amountInToGetToNextInitTick.Mul(spreadFactorDec).Quo(sdk.OneDec().Sub(spreadFactorDec))
// Step2: hasReachedTarget in SwapStep is false (next initialized tick is -20000), hence, to find spread rewards, calculate:
// spreadRewardCharge = amountRemaining - amountZero
amountRemainingAfterStep1 = uionInDec_Swap3.Sub(amountInToGetToNextInitTick).Sub(spreadRewardCharge_Swap3_Step1)
spreadRewardCharge_Swap3_Step2 := amountRemainingAfterStep1.Sub(amountInToGetToTickBelowInitialized)
// Per unit of virtual liquidity
spreadRewardCharge_Swap3_Step1.QuoMut(liquidityBeforeSwap)
spreadRewardCharge_Swap3_Step2.QuoMut(liquidityAfterSwap)
// Update spreadRewardGrowthGlobal
spreadRewardGrowthGlobal.AddMut(spreadRewardCharge_Swap3_Step1.Add(spreadRewardCharge_Swap3_Step2))
// Assert position that was active throughout second swap step (address1 position1) only earned spread rewards for this step:
// Only collects spread rewards for second swap step
spreadRewardsUncollectedAddress1Position1_Swap3 := calculateUncollectedSpreadRewards(
positionsAddress1[0].Position.Liquidity,
sdk.ZeroDec(),
spreadRewardCharge_Swap2_Step2.Add(spreadRewardCharge_Swap3_Step1), // spread rewards acquired by swap2 step2 and swap3 step1 (steps happened above upper tick of this position)
spreadRewardGrowthInsideAddress1Position1Last, // spreadRewardGrowthInside from first and second swaps
spreadRewardGrowthGlobal,
)
// Assert
s.Require().Equal(
addr1BalancesBefore.AmountOf("uion").Add(spreadRewardsUncollectedAddress1Position1_Swap3.TruncateInt()),
addr1BalancesAfter.AmountOf("uion"),
)
// Assert position that was active throughout the whole swap:
// Track balance of address3
addr3BalancesBefore = s.addrBalance(chainABNode, address3)
chainABNode.CollectSpreadRewards(address3, fmt.Sprint(positionsAddress3[1].Position.PositionId))
addr3BalancesAfter = s.addrBalance(chainABNode, address3)
// Assert that the balance changed only for tokenIn (uion)
s.assertBalancesInvariants(addr3BalancesBefore, addr3BalancesAfter, true, false)
// Was active throughout the whole swap, collects spread rewards from 2 steps
// Step 1
spreadRewardsUncollectedAddress3Position2_Swap3_Step1 := calculateUncollectedSpreadRewards(
positionsAddress3[1].Position.Liquidity,
sdk.ZeroDec(), // no growth below
sdk.ZeroDec(), // no growth above
calculateSpreadRewardGrowthInside(spreadRewardGrowthGlobal_Swap2, sdk.ZeroDec(), sdk.ZeroDec()), // snapshot of spread reward growth at swap 2
spreadRewardGrowthGlobal.Sub(spreadRewardCharge_Swap3_Step2), // step 1 hasn't earned spread rewards from step 2
)
// Step 2
spreadRewardsUncollectedAddress3Position2_Swap3_Step2 := calculateUncollectedSpreadRewards(
positionsAddress3[1].Position.Liquidity,
sdk.ZeroDec(), // no growth below
sdk.ZeroDec(), // no growth above
calculateSpreadRewardGrowthInside(spreadRewardGrowthGlobal_Swap2, sdk.ZeroDec(), sdk.ZeroDec()), // snapshot of spread reward growth at swap 2
spreadRewardGrowthGlobal.Sub(spreadRewardCharge_Swap3_Step1), // step 2 hasn't earned spread rewards from step 1
)
// Calculate total spread rewards acquired by address3 position2 from all swap steps
totalUncollectedSpreadRewardsAddress3Position2 = spreadRewardsUncollectedAddress3Position2_Swap3_Step1.Add(spreadRewardsUncollectedAddress3Position2_Swap3_Step2)
// Assert
s.Require().Equal(
addr3BalancesBefore.AmountOf("uion").Add(totalUncollectedSpreadRewardsAddress3Position2.TruncateInt()),
addr3BalancesAfter.AmountOf("uion"),
)
// Collect SpreadRewards: Sanity Checks
// Assert that positions, which were not included in swaps, were not affected
// Address3 Position1: [-160000; -20000]
addr3BalancesBefore = s.addrBalance(chainABNode, address3)
chainABNode.CollectSpreadRewards(address3, fmt.Sprint(positionsAddress3[0].Position.PositionId))
addr3BalancesAfter = s.addrBalance(chainABNode, address3)
// Assert that balances did not change for any token
s.assertBalancesInvariants(addr3BalancesBefore, addr3BalancesAfter, true, true)
// Address2's only position: [220000; 342000]
addr2BalancesBefore := s.addrBalance(chainABNode, address2)
chainABNode.CollectSpreadRewards(address2, fmt.Sprint(positionsAddress2[0].Position.PositionId))
addr2BalancesAfter := s.addrBalance(chainABNode, address2)
// Assert the balances did not change for every token
s.assertBalancesInvariants(addr2BalancesBefore, addr2BalancesAfter, true, true)
// Withdraw Position
// Withdraw Position parameters
defaultLiquidityRemoval := "1000"
chainAB.WaitForNumHeights(2)
// Assert removing some liquidity
// address1: check removing some amount of liquidity
address1position1liquidityBefore := positionsAddress1[0].Position.Liquidity
chainABNode.WithdrawPosition(address1, defaultLiquidityRemoval, positionsAddress1[0].Position.PositionId)
// assert
positionsAddress1 = chainABNode.QueryConcentratedPositions(address1)
s.Require().Equal(address1position1liquidityBefore, positionsAddress1[0].Position.Liquidity.Add(sdk.MustNewDecFromStr(defaultLiquidityRemoval)))
// address2: check removing some amount of liquidity
address2position1liquidityBefore := positionsAddress2[0].Position.Liquidity
chainABNode.WithdrawPosition(address2, defaultLiquidityRemoval, positionsAddress2[0].Position.PositionId)
// assert
positionsAddress2 = chainABNode.QueryConcentratedPositions(address2)
s.Require().Equal(address2position1liquidityBefore, positionsAddress2[0].Position.Liquidity.Add(sdk.MustNewDecFromStr(defaultLiquidityRemoval)))
// address3: check removing some amount of liquidity
address3position1liquidityBefore := positionsAddress3[0].Position.Liquidity
chainABNode.WithdrawPosition(address3, defaultLiquidityRemoval, positionsAddress3[0].Position.PositionId)
// assert
positionsAddress3 = chainABNode.QueryConcentratedPositions(address3)
s.Require().Equal(address3position1liquidityBefore, positionsAddress3[0].Position.Liquidity.Add(sdk.MustNewDecFromStr(defaultLiquidityRemoval)))
// Assert removing all liquidity
// address2: no more positions left
allLiquidityAddress2Position1 := positionsAddress2[0].Position.Liquidity
chainABNode.WithdrawPosition(address2, allLiquidityAddress2Position1.String(), positionsAddress2[0].Position.PositionId)
positionsAddress2 = chainABNode.QueryConcentratedPositions(address2)
s.Require().Empty(positionsAddress2)
// address1: one position left
allLiquidityAddress1Position1 := positionsAddress1[0].Position.Liquidity
chainABNode.WithdrawPosition(address1, allLiquidityAddress1Position1.String(), positionsAddress1[0].Position.PositionId)
positionsAddress1 = chainABNode.QueryConcentratedPositions(address1)
s.Require().Equal(len(positionsAddress1), 1)
// Test tick spacing reduction proposal
// Get the current tick spacing
currentTickSpacing := concentratedPool.GetTickSpacing()
// Get the index of the current tick spacing in relation to authorized tick spacings
indexOfCurrentTickSpacing := uint64(0)
for i, tickSpacing := range cltypes.AuthorizedTickSpacing {
if tickSpacing == currentTickSpacing {
indexOfCurrentTickSpacing = uint64(i)
break
}
}
// The new tick spacing will be the next lowest authorized tick spacing
newTickSpacing := cltypes.AuthorizedTickSpacing[indexOfCurrentTickSpacing-1]
// Run the tick spacing reduction proposal
propNumber := chainABNode.SubmitTickSpacingReductionProposal(fmt.Sprintf("%d,%d", poolID, newTickSpacing), sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.InitialMinExpeditedDeposit)), true)
chainABNode.DepositProposal(propNumber, true)
totalTimeChan := make(chan time.Duration, 1)
go chainABNode.QueryPropStatusTimed(propNumber, "PROPOSAL_STATUS_PASSED", totalTimeChan)
var wg sync.WaitGroup
// TODO: create a helper function for all these go routine yes vote calls.
for _, n := range chainAB.NodeConfigs {
wg.Add(1)
go func(nodeConfig *chain.NodeConfig) {
defer wg.Done()
nodeConfig.VoteYesProposal(initialization.ValidatorWalletName, propNumber)
}(n)
}
wg.Wait()
// if querying proposal takes longer than timeoutPeriod, stop the goroutine and error
timeoutPeriod := 2 * time.Minute
select {
case <-time.After(timeoutPeriod):
err := fmt.Errorf("go routine took longer than %s", timeoutPeriod)
s.Require().NoError(err)
case <-totalTimeChan:
// The goroutine finished before the timeout period, continue execution.
}
// Check that the tick spacing was reduced to the expected new tick spacing
concentratedPool = s.updatedConcentratedPool(chainABNode, poolID)
s.Require().Equal(newTickSpacing, concentratedPool.GetTickSpacing())
}
func (s *IntegrationTestSuite) StableSwapPostUpgrade() {
if s.skipUpgrade {
s.T().Skip("Skipping StableSwapPostUpgrade test")
}
chainAB, chainABNode, err := s.getChainCfgs()
s.Require().NoError(err)
index := s.getChainIndex(chainAB)
sender := chainABNode.GetWallet(initialization.ValidatorWalletName)
const (
denomA = "stake"
denomB = "uosmo"
minAmountOut = "1"
)
coinAIn, coinBIn := fmt.Sprintf("20000%s", denomA), fmt.Sprintf("1%s", denomB)
chainABNode.BankSend(initialization.WalletFeeTokens.String(), sender, config.StableswapWallet[index])
chainABNode.BankSend(coinAIn, sender, config.StableswapWallet[index])
chainABNode.BankSend(coinBIn, sender, config.StableswapWallet[index])
s.T().Log("performing swaps")
chainABNode.SwapExactAmountIn(coinAIn, minAmountOut, fmt.Sprintf("%d", config.PreUpgradeStableSwapPoolId[index]), denomB, config.StableswapWallet[index])
chainABNode.SwapExactAmountIn(coinBIn, minAmountOut, fmt.Sprintf("%d", config.PreUpgradeStableSwapPoolId[index]), denomA, config.StableswapWallet[index])
}
// TestGeometricTwapMigration tests that the geometric twap record
// migration runs successfully. It does so by attempting to execute
// the swap on the pool created pre-upgrade. When a pool is created
// pre-upgrade, twap records are initialized for a pool. By runnning
// a swap post-upgrade, we confirm that the geometric twap was initialized
// correctly and does not cause a chain halt. This test was created
// in-response to a testnet incident when performing the geometric twap
// upgrade. Upon adding the migrations logic, the tests began to pass.
func (s *IntegrationTestSuite) GeometricTwapMigration() {
if s.skipUpgrade {
s.T().Skip("Skipping upgrade tests")
}
var (
// Configurations for tests/e2e/scripts/pool1A.json
// This pool gets initialized pre-upgrade.
minAmountOut = "1"
otherDenom = []string{"ibc/ED07A3391A112B175915CD8FAF43A2DA8E4790EDE12566649D0C2F97716B8518", "ibc/C053D637CCA2A2BA030E2C5EE1B28A16F71CCB0E45E8BE52766DC1B241B77878"}
migrationWallet = "migration"
)
chainAB, chainABNode, err := s.getChainCfgs()
s.Require().NoError(err)
index := s.getChainIndex(chainAB)
sender := chainABNode.GetWallet(initialization.ValidatorWalletName)
uosmoIn := fmt.Sprintf("1000000%s", "uosmo")
swapWalletAddr := chainABNode.CreateWallet(migrationWallet, chainAB)
chainABNode.BankSend(uosmoIn, sender, swapWalletAddr)
// Swap to create new twap records on the pool that was created pre-upgrade.
chainABNode.SwapExactAmountIn(uosmoIn, minAmountOut, fmt.Sprintf("%d", config.PreUpgradePoolId[index]), otherDenom[index], swapWalletAddr)
}
// TestIBCTokenTransfer tests that IBC token transfers work as expected.
// Additionally, it attempst to create a pool with IBC denoms.
func (s *IntegrationTestSuite) IBCTokenTransferAndCreatePool() {
if s.skipIBC {
s.T().Skip("Skipping IBC tests")
}
chainA, chainANode, err := s.getChainACfgs()
s.Require().NoError(err)
chainB, chainBNode, err := s.getChainBCfgs()
s.Require().NoError(err)
chainANode.SendIBC(chainA, chainB, chainBNode.PublicAddress, initialization.OsmoToken)
chainBNode.SendIBC(chainB, chainA, chainANode.PublicAddress, initialization.OsmoToken)
chainANode.SendIBC(chainA, chainB, chainBNode.PublicAddress, initialization.StakeToken)
chainBNode.SendIBC(chainB, chainA, chainANode.PublicAddress, initialization.StakeToken)
chainANode.CreateBalancerPool("ibcDenomPool.json", initialization.ValidatorWalletName)
}
// TestSuperfluidVoting tests that superfluid voting is functioning as expected.
// It does so by doing the following:
// - creating a pool
// - attempting to submit a proposal to enable superfluid voting in that pool
// - voting yes on the proposal from the validator wallet
// - voting no on the proposal from the delegator wallet
// - ensuring that delegator's wallet overwrites the validator's vote
func (s *IntegrationTestSuite) SuperfluidVoting() {
chainAB, chainABNode, err := s.getChainCfgs()
s.Require().NoError(err)
poolId := chainABNode.CreateBalancerPool("nativeDenomPool.json", initialization.ValidatorWalletName)
// enable superfluid assets
chainABNode.EnableSuperfluidAsset(chainAB, fmt.Sprintf("gamm/pool/%d", poolId))
// setup wallets and send gamm tokens to these wallets (both chains)
superfluidVotingWallet := chainABNode.CreateWallet("TestSuperfluidVoting", chainAB)
chainABNode.BankSend(fmt.Sprintf("10000000000000000000gamm/pool/%d", poolId), initialization.ValidatorWalletName, superfluidVotingWallet)
lockId := chainABNode.LockTokens(fmt.Sprintf("%v%s", sdk.NewInt(1000000000000000000), fmt.Sprintf("gamm/pool/%d", poolId)), "240s", superfluidVotingWallet)
chainABNode.SuperfluidDelegate(lockId, chainABNode.OperatorAddress, superfluidVotingWallet)
// create a text prop, deposit and vote yes
propNumber := chainABNode.SubmitTextProposal("superfluid vote overwrite test", sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.InitialMinDeposit)), false)
chainABNode.DepositProposal(propNumber, false)
var wg sync.WaitGroup
for _, n := range chainAB.NodeConfigs {
wg.Add(1)
go func(nodeConfig *chain.NodeConfig) {
defer wg.Done()
nodeConfig.VoteYesProposal(initialization.ValidatorWalletName, propNumber)
}(n)
}