-
Notifications
You must be signed in to change notification settings - Fork 608
/
e2e_test.go
1586 lines (1300 loc) · 70 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"
"time"
transfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types"
"github.com/iancoleman/orderedmap"
"github.com/osmosis-labs/osmosis/v15/tests/e2e/configurer/chain"
"github.com/osmosis-labs/osmosis/v15/tests/e2e/util"
packetforwardingtypes "github.com/strangelove-ventures/packet-forward-middleware/v4/router/types"
ibchookskeeper "github.com/osmosis-labs/osmosis/x/ibc-hooks/keeper"
ibcratelimittypes "github.com/osmosis-labs/osmosis/v15/x/ibc-rate-limit/types"
poolmanagertypes "github.com/osmosis-labs/osmosis/v15/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/v15/app/params"
v16 "github.com/osmosis-labs/osmosis/v15/app/upgrades/v16"
"github.com/osmosis-labs/osmosis/v15/tests/e2e/configurer/config"
"github.com/osmosis-labs/osmosis/v15/tests/e2e/initialization"
cl "github.com/osmosis-labs/osmosis/v15/x/concentrated-liquidity"
cltypes "github.com/osmosis-labs/osmosis/v15/x/concentrated-liquidity/types"
)
// Reusable Checks
// 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) TestProtoRev() {
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 = "week"
)
chainA := s.configurer.GetChainConfig(0)
chainANode, err := chainA.GetDefaultNode()
s.NoError(err)
// --------------- 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.
poolWeights, err := chainANode.QueryProtoRevPoolWeights()
s.T().Logf("checking that the protorev module has pool weights on init: %v", poolWeights)
s.Require().NoError(err)
s.Require().NotNil(poolWeights)
// 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")
// The module should have no developer account by default.
_, err = chainANode.QueryProtoRevDeveloperAccount()
s.T().Logf("checking that the protorev module has no developer account on init: %s", err)
s.Require().Error(err)
// --------------- Set up for a calculated backrun ---------------- //
// Create all of the pools that will be used in the test.
chainANode.CreateBalancerPool(poolFile1, initialization.ValidatorWalletName)
swapPoolId := chainANode.CreateBalancerPool(poolFile2, initialization.ValidatorWalletName)
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.EpochWeekDuration.Seconds())
chainA.WaitForNumEpochs(1, epochIdentifier)
// Create a wallet to use for the swap txs.
swapWalletAddr := chainANode.CreateWallet(walletName)
coinIn := fmt.Sprintf("%s%s", amount, denomIn)
chainANode.BankSend(coinIn, chainA.NodeConfigs[0].PublicAddress, 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", swapPoolId), 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{swapPoolId - 1, swapPoolId, swapPoolId + 1}, routeStats[0].Route)
s.Require().Equal(profits, routeStats[0].Profits)
}
// CheckBalance Checks the balance of an address
func (s *IntegrationTestSuite) CheckBalance(node *chain.NodeConfig, addr, denom string, amount int64) {
// check the balance of the contract
s.Require().Eventually(func() bool {
balance, err := node.QueryBalances(addr)
s.Require().NoError(err)
if len(balance) == 0 {
return false
}
// check that the amount is in one of the balances inside the balance list
for _, b := range balance {
if b.Denom == denom && b.Amount.Int64() == amount {
return true
}
}
return false
},
1*time.Minute,
10*time.Millisecond,
)
}
func (s *IntegrationTestSuite) TestConcentratedLiquidity() {
chainA := s.configurer.GetChainConfig(0)
chainANode, err := chainA.GetDefaultNode()
s.Require().NoError(err)
var (
denom0 string = "uion"
denom1 string = "uosmo"
tickSpacing uint64 = 100
swapFee = "0.001" // 0.1%
swapFeeDec sdk.Dec = sdk.MustNewDecFromStr("0.001")
)
// Get the permisionless pool creation parameter.
isPermisionlessCreationEnabledStr := chainANode.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.
chainA.SubmitParamChangeProposal("concentratedliquidity", string(cltypes.KeyIsPermisionlessPoolCreationEnabled), []byte("true"))
// Confirm that the parameter has been changed.
isPermisionlessCreationEnabledStr = chainANode.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, err := chainANode.CreateConcentratedPool(initialization.ValidatorWalletName, denom0, denom1, tickSpacing, swapFee)
s.Require().NoError(err)
concentratedPool := s.updatedPool(chainANode, poolID)
// Sanity check that pool initialized with valid parameters (the ones that we haven't explicitly specified)
s.Require().Equal(concentratedPool.GetCurrentTick(), sdk.ZeroInt())
s.Require().Equal(concentratedPool.GetCurrentSqrtPrice(), sdk.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.GetSwapFee(sdk.Context{}), sdk.MustNewDecFromStr(swapFee))
fundTokens := []string{"100000000uosmo", "100000000uion", "100000000stake"}
// Get 3 addresses to create positions
address1 := chainANode.CreateWalletAndFund("addr1", fundTokens)
address2 := chainANode.CreateWalletAndFund("addr2", fundTokens)
address3 := chainANode.CreateWalletAndFund("addr3", fundTokens)
// Create 2 positions for address1: overlap together, overlap with 2 address3 positions
chainANode.CreateConcentratedPosition(address1, "[-120000]", "40000", fmt.Sprintf("10000000%s", denom0), fmt.Sprintf("10000000%s", denom1), 0, 0, poolID)
chainANode.CreateConcentratedPosition(address1, "[-40000]", "120000", fmt.Sprintf("10000000%s", denom0), fmt.Sprintf("10000000%s", denom1), 0, 0, poolID)
// Create 1 position for address2: does not overlap with anything, ends at maximum
chainANode.CreateConcentratedPosition(address2, "220000", fmt.Sprintf("%d", cltypes.MaxTick), fmt.Sprintf("10000000%s", denom0), fmt.Sprintf("10000000%s", denom1), 0, 0, poolID)
// Create 2 positions for address3: overlap together, overlap with 2 address1 positions, one position starts from minimum
chainANode.CreateConcentratedPosition(address3, "[-160000]", "[-20000]", fmt.Sprintf("10000000%s", denom0), fmt.Sprintf("10000000%s", denom1), 0, 0, poolID)
chainANode.CreateConcentratedPosition(address3, fmt.Sprintf("[%d]", cltypes.MinTick), "140000", fmt.Sprintf("10000000%s", denom0), fmt.Sprintf("10000000%s", denom1), 0, 0, poolID)
// Get newly created positions
positionsAddress1 := chainANode.QueryConcentratedPositions(address1)
positionsAddress2 := chainANode.QueryConcentratedPositions(address2)
positionsAddress3 := chainANode.QueryConcentratedPositions(address3)
concentratedPool = s.updatedPool(chainANode, 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.MinTick, 140000)
// Collect Fees
var (
// feeGrowthGlobal is a variable for tracking global fee growth
feeGrowthGlobal = 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 fees are correctly collected for non cross-tick swaps
var (
// Swap parameters
uosmoInDec_Swap1 = sdk.NewDec(3465198)
uosmoIn_Swap1 = fmt.Sprintf("%suosmo", uosmoInDec_Swap1.String())
)
// Perform swap (not crossing initialized ticks)
chainANode.SwapExactAmountIn(uosmoIn_Swap1, outMinAmt, fmt.Sprintf("%d", poolID), denom0, initialization.ValidatorWalletName)
// Calculate and track global fee growth for swap 1
feeGrowthGlobal.AddMut(calculateFeeGrowthGlobal(uosmoInDec_Swap1, swapFeeDec, concentratedPool.GetLiquidity()))
// Update pool and track liquidity and sqrt price
liquidityBeforeSwap := concentratedPool.GetLiquidity()
sqrtPriceBeforeSwap := concentratedPool.GetCurrentSqrtPrice()
concentratedPool = s.updatedPool(chainANode, 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
inAmountSubFee := uosmoInDec_Swap1.Mul(sdk.OneDec().Sub(swapFeeDec))
expectedSqrtPriceDelta := inAmountSubFee.QuoTruncate(concentratedPool.GetLiquidity()) // Δ(sqrtPrice) = Δy / L
expectedSqrtPrice := sqrtPriceBeforeSwap.Add(expectedSqrtPriceDelta)
s.Require().Equal(expectedSqrtPrice.String(), sqrtPriceAfterSwap.String())
// Collect Fees: Swap 1
// Track balances for address1 position1
addr1BalancesBefore := s.addrBalance(chainANode, address1)
chainANode.CollectFees(address1, fmt.Sprint(positionsAddress1[0].Position.PositionId))
addr1BalancesAfter := s.addrBalance(chainANode, address1)
// Assert that the balance changed only for tokenIn (uosmo)
s.assertBalancesInvariants(addr1BalancesBefore, addr1BalancesAfter, false, true)
// Assert Balances: Swap 1
// Calculate uncollected fees for address1 position1
feesUncollectedAddress1Position1_Swap1 := calculateUncollectedFees(
positionsAddress1[0].Position.Liquidity,
sdk.ZeroDec(), // no growth below
sdk.ZeroDec(), // no growth above
sdk.ZeroDec(), // no feeGrowthInsideLast - it is the first swap
feeGrowthGlobal,
)
// Assert
s.Require().Equal(
addr1BalancesBefore.AmountOf("uosmo").Add(feesUncollectedAddress1Position1_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 fees 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 := sdk.NewInt(300)
sqrtPriceBeforeSwap = concentratedPool.GetCurrentSqrtPrice()
liquidityBeforeSwap = concentratedPool.GetLiquidity()
nextInitTick := sdk.NewInt(40000) // address1 position1's upper tick
// Calculate sqrtPrice after and at the next initialized tick (upperTick of address1 position1 - 40000)
sqrtPriceAfterNextInitializedTick, err := cl.TickToSqrtPrice(nextInitTick.Add(tickOffset))
s.Require().NoError(err)
sqrtPriceAtNextInitializedTick, err := cl.TickToSqrtPrice(nextInitTick)
s.Require().NoError(err)
// Calculate Δ(sqrtPrice):
// deltaSqrtPriceAfterNextInitializedTick = ΔsqrtP(40300) - ΔsqrtP(40000)
// deltaSqrtPriceAtNextInitializedTick = ΔsqrtP(40000) - ΔsqrtP(currentTick)
deltaSqrtPriceAfterNextInitializedTick := sqrtPriceAfterNextInitializedTick.Sub(sqrtPriceAtNextInitializedTick)
deltaSqrtPriceAtNextInitializedTick := sqrtPriceAtNextInitializedTick.Sub(sqrtPriceBeforeSwap)
// 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_NoFee is calculated such that swapping this amount (not considering fee) moves the price over the next initialized tick
uosmoInDec_Swap2_NoFee = amountInToGetToNextInitTick.Add(amountInToGetToTickAfterInitialized)
uosmoInDec_Swap2 = uosmoInDec_Swap2_NoFee.Quo(sdk.OneDec().Sub(swapFeeDec)).TruncateDec() // account for swap fee of 1%
uosmoIn_Swap2 = fmt.Sprintf("%suosmo", uosmoInDec_Swap2.String())
feeGrowthGlobal_Swap1 = feeGrowthGlobal.Clone()
)
// Perform a swap
chainANode.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.updatedPool(chainANode, 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 fees: Swap 2
// Calculate fee charges per each step
// Step1: amountIn is uosmo tokens that are swapped + uosmo tokens that are paid for fee
// hasReachedTarget in SwapStep is true, hence, to find fees, calculate:
// feeCharge = amountIn * swapFee / (1 - swapFee)
feeCharge_Swap2_Step1 := amountInToGetToNextInitTick.Mul(swapFeeDec).Quo(sdk.OneDec().Sub(swapFeeDec))
// Step2: hasReachedTarget in SwapStep is false (nextTick is 120000), hence, to find fees, calculate:
// feeCharge = amountRemaining - amountOne
amountRemainingAfterStep1 := uosmoInDec_Swap2.Sub(amountInToGetToNextInitTick).Sub(feeCharge_Swap2_Step1)
feeCharge_Swap2_Step2 := amountRemainingAfterStep1.Sub(amountInToGetToTickAfterInitialized)
// per unit of virtual liquidity
feeCharge_Swap2_Step1.QuoMut(liquidityBeforeSwap)
feeCharge_Swap2_Step2.QuoMut(liquidityAfterSwap)
// Update feeGrowthGlobal
feeGrowthGlobal.AddMut(feeCharge_Swap2_Step1.Add(feeCharge_Swap2_Step2))
// Assert Balances: Swap 2
// Assert that address1 position1 earned fees only from first swap step
// Track balances for address1 position1
addr1BalancesBefore = s.addrBalance(chainANode, address1)
chainANode.CollectFees(address1, fmt.Sprint(positionsAddress1[0].Position.PositionId))
addr1BalancesAfter = s.addrBalance(chainANode, address1)
// Assert that the balance changed only for tokenIn (uosmo)
s.assertBalancesInvariants(addr1BalancesBefore, addr1BalancesAfter, false, true)
// Calculate uncollected fees for position, which liquidity will only be live part of the swap
feesUncollectedAddress1Position1_Swap2 := calculateUncollectedFees(
positionsAddress1[0].Position.Liquidity,
sdk.ZeroDec(),
sdk.ZeroDec(),
calculateFeeGrowthInside(feeGrowthGlobal_Swap1, sdk.ZeroDec(), sdk.ZeroDec()),
feeGrowthGlobal_Swap1.Add(feeCharge_Swap2_Step1), // cannot use feeGrowthGlobal, it was already increased by second swap's step
)
// Assert
s.Require().Equal(
addr1BalancesBefore.AmountOf("uosmo").Add(feesUncollectedAddress1Position1_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(chainANode, address3)
chainANode.CollectFees(address3, fmt.Sprint(positionsAddress3[1].Position.PositionId))
addr3BalancesAfter := s.addrBalance(chainANode, address3)
// Calculate uncollected fees for address3 position2 earned from Swap 1
feesUncollectedAddress3Position2_Swap1 := calculateUncollectedFees(
positionsAddress3[1].Position.Liquidity,
sdk.ZeroDec(),
sdk.ZeroDec(),
sdk.ZeroDec(),
feeGrowthGlobal_Swap1,
)
// Calculate uncollected fees for address3 position2 (was active throughout both swap steps): Swap2
feesUncollectedAddress3Position2_Swap2 := calculateUncollectedFees(
positionsAddress3[1].Position.Liquidity,
sdk.ZeroDec(),
sdk.ZeroDec(),
calculateFeeGrowthInside(feeGrowthGlobal_Swap1, sdk.ZeroDec(), sdk.ZeroDec()),
feeGrowthGlobal,
)
// Total fees earned by address3 position2 from 2 swaps
totalUncollectedFeesAddress3Position2 := feesUncollectedAddress3Position2_Swap1.Add(feesUncollectedAddress3Position2_Swap2)
// Assert
s.Require().Equal(
addr3BalancesBefore.AmountOf("uosmo").Add(totalUncollectedFeesAddress3Position2.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 = sdk.NewInt(300)
sqrtPriceBeforeSwap = concentratedPool.GetCurrentSqrtPrice()
liquidityBeforeSwap = concentratedPool.GetLiquidity()
nextInitTick = sdk.NewInt(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 := cl.TickToSqrtPrice(nextInitTick.Sub(tickOffset))
s.Require().NoError(err)
sqrtPriceAtNextInitializedTick, err = cl.TickToSqrtPrice(nextInitTick)
s.Require().NoError(err)
// Calculate numerators
numeratorBelowNextInitializedTick := sqrtPriceAtNextInitializedTick.Sub(sqrtPricebBelowNextInitializedTick)
numeratorNextInitializedTick := sqrtPriceBeforeSwap.Sub(sqrtPriceAtNextInitializedTick)
// Calculate denominators
denominatorBelowNextInitializedTick := sqrtPriceAtNextInitializedTick.Mul(sqrtPricebBelowNextInitializedTick)
denominatorNextInitializedTick := sqrtPriceBeforeSwap.Mul(sqrtPriceAtNextInitializedTick)
// 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)
var (
// Swap parameters
uionInDec_Swap3_NoFee = amountInToGetToNextInitTick.Add(amountInToGetToTickBelowInitialized) // amount of uion to move price from current to desired (not considering swapFee)
uionInDec_Swap3 = uionInDec_Swap3_NoFee.Quo(sdk.OneDec().Sub(swapFeeDec)).TruncateDec() // consider swapFee
uionIn_Swap3 = fmt.Sprintf("%suion", uionInDec_Swap3.String())
// Save variables from previous swaps
feeGrowthGlobal_Swap2 = feeGrowthGlobal.Clone()
feeGrowthInsideAddress1Position1Last = feeGrowthGlobal_Swap1.Add(feeCharge_Swap2_Step1)
)
// Collect fees for address1 position1 to avoid overhead computations (swap2 already asserted fees are aggregated correctly from multiple swaps)
chainANode.CollectFees(address1, fmt.Sprint(positionsAddress1[0].Position.PositionId))
// Perform a swap
chainANode.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.updatedPool(chainANode, poolID)
liquidityAfterSwap = concentratedPool.GetLiquidity()
s.Require().Equal(liquidityBeforeSwap.Add(positionsAddress1[0].Position.Liquidity), liquidityAfterSwap)
// Track balance of address1
addr1BalancesBefore = s.addrBalance(chainANode, address1)
chainANode.CollectFees(address1, fmt.Sprint(positionsAddress1[0].Position.PositionId))
addr1BalancesAfter = s.addrBalance(chainANode, address1)
// Assert that the balance changed only for tokenIn (uion)
s.assertBalancesInvariants(addr1BalancesBefore, addr1BalancesAfter, true, false)
// Assert the amount of collected fees:
// Step1: amountIn is uion tokens that are swapped + uion tokens that are paid for fee
// hasReachedTarget in SwapStep is true, hence, to find fees, calculate:
// feeCharge = amountIn * swapFee / (1 - swapFee)
feeCharge_Swap3_Step1 := amountInToGetToNextInitTick.Mul(swapFeeDec).Quo(sdk.OneDec().Sub(swapFeeDec))
// Step2: hasReachedTarget in SwapStep is false (next initialized tick is -20000), hence, to find fees, calculate:
// feeCharge = amountRemaining - amountZero
amountRemainingAfterStep1 = uionInDec_Swap3.Sub(amountInToGetToNextInitTick).Sub(feeCharge_Swap3_Step1)
feeCharge_Swap3_Step2 := amountRemainingAfterStep1.Sub(amountInToGetToTickBelowInitialized)
// Per unit of virtual liquidity
feeCharge_Swap3_Step1.QuoMut(liquidityBeforeSwap)
feeCharge_Swap3_Step2.QuoMut(liquidityAfterSwap)
// Update feeGrowthGlobal
feeGrowthGlobal.AddMut(feeCharge_Swap3_Step1.Add(feeCharge_Swap3_Step2))
// Assert position that was active throughout second swap step (address1 position1) only earned fees for this step:
// Only collects fees for second swap step
feesUncollectedAddress1Position1_Swap3 := calculateUncollectedFees(
positionsAddress1[0].Position.Liquidity,
sdk.ZeroDec(),
feeCharge_Swap2_Step2.Add(feeCharge_Swap3_Step1), // fees acquired by swap2 step2 and swap3 step1 (steps happened above upper tick of this position)
feeGrowthInsideAddress1Position1Last, // feeGrowthInside from first and second swaps
feeGrowthGlobal,
)
// Assert
s.Require().Equal(
addr1BalancesBefore.AmountOf("uion").Add(feesUncollectedAddress1Position1_Swap3.TruncateInt()),
addr1BalancesAfter.AmountOf("uion"),
)
// Assert position that was active thoughout the whole swap:
// Track balance of address3
addr3BalancesBefore = s.addrBalance(chainANode, address3)
chainANode.CollectFees(address3, fmt.Sprint(positionsAddress3[1].Position.PositionId))
addr3BalancesAfter = s.addrBalance(chainANode, address3)
// Assert that the balance changed only for tokenIn (uion)
s.assertBalancesInvariants(addr3BalancesBefore, addr3BalancesAfter, true, false)
// Was active throughout the whole swap, collects fees from 2 steps
// Step 1
feesUncollectedAddress3Position2_Swap3_Step1 := calculateUncollectedFees(
positionsAddress3[1].Position.Liquidity,
sdk.ZeroDec(), // no growth below
sdk.ZeroDec(), // no growth above
calculateFeeGrowthInside(feeGrowthGlobal_Swap2, sdk.ZeroDec(), sdk.ZeroDec()), // snapshot of fee growth at swap 2
feeGrowthGlobal.Sub(feeCharge_Swap3_Step2), // step 1 hasn't earned fees from step 2
)
// Step 2
feesUncollectedAddress3Position2_Swap3_Step2 := calculateUncollectedFees(
positionsAddress3[1].Position.Liquidity,
sdk.ZeroDec(), // no growth below
sdk.ZeroDec(), // no growth above
calculateFeeGrowthInside(feeGrowthGlobal_Swap2, sdk.ZeroDec(), sdk.ZeroDec()), // snapshot of fee growth at swap 2
feeGrowthGlobal.Sub(feeCharge_Swap3_Step1), // step 2 hasn't earned fees from step 1
)
// Calculate total fees acquired by address3 position2 from all swap steps
totalUncollectedFeesAddress3Position2 = feesUncollectedAddress3Position2_Swap3_Step1.Add(feesUncollectedAddress3Position2_Swap3_Step2)
// Assert
s.Require().Equal(
addr3BalancesBefore.AmountOf("uion").Add(totalUncollectedFeesAddress3Position2.TruncateInt()),
addr3BalancesAfter.AmountOf("uion"),
)
// Collect Fees: Sanity Checks
// Assert that positions, which were not included in swaps, were not affected
// Address3 Position1: [-160000; -20000]
addr3BalancesBefore = s.addrBalance(chainANode, address3)
chainANode.CollectFees(address3, fmt.Sprint(positionsAddress3[0].Position.PositionId))
addr3BalancesAfter = s.addrBalance(chainANode, 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(chainANode, address2)
chainANode.CollectFees(address2, fmt.Sprint(positionsAddress2[0].Position.PositionId))
addr2BalancesAfter := s.addrBalance(chainANode, address2)
// Assert the balances did not change for every token
s.assertBalancesInvariants(addr2BalancesBefore, addr2BalancesAfter, true, true)
// Withdraw Position
var (
// Withdraw Position parameters
defaultLiquidityRemoval string = "1000"
)
chainA.WaitForNumHeights(2)
// Assert removing some liquidity
// address1: check removing some amount of liquidity
address1position1liquidityBefore := positionsAddress1[0].Position.Liquidity
chainANode.WithdrawPosition(address1, defaultLiquidityRemoval, positionsAddress1[0].Position.PositionId)
// assert
positionsAddress1 = chainANode.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
chainANode.WithdrawPosition(address2, defaultLiquidityRemoval, positionsAddress2[0].Position.PositionId)
// assert
positionsAddress2 = chainANode.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
chainANode.WithdrawPosition(address3, defaultLiquidityRemoval, positionsAddress3[0].Position.PositionId)
// assert
positionsAddress3 = chainANode.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
chainANode.WithdrawPosition(address2, allLiquidityAddress2Position1.String(), positionsAddress2[0].Position.PositionId)
positionsAddress2 = chainANode.QueryConcentratedPositions(address2)
s.Require().Empty(positionsAddress2)
// address1: one position left
allLiquidityAddress1Position1 := positionsAddress1[0].Position.Liquidity
chainANode.WithdrawPosition(address1, allLiquidityAddress1Position1.String(), positionsAddress1[0].Position.PositionId)
positionsAddress1 = chainANode.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
chainANode.SubmitTickSpacingReductionProposal(fmt.Sprintf("%d,%d", poolID, newTickSpacing), sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.InitialMinExpeditedDeposit)), true)
chainA.LatestProposalNumber += 1
chainANode.DepositProposal(chainA.LatestProposalNumber, true)
totalTimeChan := make(chan time.Duration, 1)
go chainANode.QueryPropStatusTimed(chainA.LatestProposalNumber, "PROPOSAL_STATUS_PASSED", totalTimeChan)
for _, node := range chainA.NodeConfigs {
node.VoteYesProposal(initialization.ValidatorWalletName, chainA.LatestProposalNumber)
}
// 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.updatedPool(chainANode, poolID)
s.Require().Equal(newTickSpacing, concentratedPool.GetTickSpacing())
}
func (s *IntegrationTestSuite) TestStableSwapPostUpgrade() {
if s.skipUpgrade {
s.T().Skip("Skipping StableSwapPostUpgrade test")
}
chainA := s.configurer.GetChainConfig(0)
chainANode, err := chainA.GetDefaultNode()
s.Require().NoError(err)
const (
denomA = "stake"
denomB = "uosmo"
minAmountOut = "1"
)
coinAIn, coinBIn := fmt.Sprintf("20000%s", denomA), fmt.Sprintf("1%s", denomB)
chainANode.BankSend(initialization.WalletFeeTokens.String(), chainA.NodeConfigs[0].PublicAddress, config.StableswapWallet)
chainANode.BankSend(coinAIn, chainA.NodeConfigs[0].PublicAddress, config.StableswapWallet)
chainANode.BankSend(coinBIn, chainA.NodeConfigs[0].PublicAddress, config.StableswapWallet)
s.T().Log("performing swaps")
chainANode.SwapExactAmountIn(coinAIn, minAmountOut, fmt.Sprintf("%d", config.PreUpgradeStableSwapPoolId), denomB, config.StableswapWallet)
chainANode.SwapExactAmountIn(coinBIn, minAmountOut, fmt.Sprintf("%d", config.PreUpgradeStableSwapPoolId), denomA, config.StableswapWallet)
}
// TestGeometricTwapMigration tests that the geometric twap record
// migration runs succesfully. 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) TestGeometricTwapMigration() {
if s.skipUpgrade {
s.T().Skip("Skipping upgrade tests")
}
const (
// Configurations for tests/e2e/scripts/pool1A.json
// This pool gets initialized pre-upgrade.
minAmountOut = "1"
otherDenom = "ibc/ED07A3391A112B175915CD8FAF43A2DA8E4790EDE12566649D0C2F97716B8518"
migrationWallet = "migration"
)
chainA := s.configurer.GetChainConfig(0)
node, err := chainA.GetDefaultNode()
s.Require().NoError(err)
uosmoIn := fmt.Sprintf("1000000%s", "uosmo")
swapWalletAddr := node.CreateWallet(migrationWallet)
node.BankSend(uosmoIn, chainA.NodeConfigs[0].PublicAddress, swapWalletAddr)
// Swap to create new twap records on the pool that was created pre-upgrade.
node.SwapExactAmountIn(uosmoIn, minAmountOut, fmt.Sprintf("%d", config.PreUpgradePoolId), otherDenom, swapWalletAddr)
}
// TestIBCTokenTransfer tests that IBC token transfers work as expected.
// Additionally, it attempst to create a pool with IBC denoms.
func (s *IntegrationTestSuite) TestIBCTokenTransferAndCreatePool() {
if s.skipIBC {
s.T().Skip("Skipping IBC tests")
}
chainA := s.configurer.GetChainConfig(0)
chainB := s.configurer.GetChainConfig(1)
chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, initialization.OsmoToken)
chainB.SendIBC(chainA, chainA.NodeConfigs[0].PublicAddress, initialization.OsmoToken)
chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, initialization.StakeToken)
chainB.SendIBC(chainA, chainA.NodeConfigs[0].PublicAddress, initialization.StakeToken)
chainANode, err := chainA.GetDefaultNode()
s.NoError(err)
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) TestSuperfluidVoting() {
chainA := s.configurer.GetChainConfig(0)
chainANode, err := chainA.GetDefaultNode()
s.NoError(err)
poolId := chainANode.CreateBalancerPool("nativeDenomPool.json", chainA.NodeConfigs[0].PublicAddress)
// enable superfluid assets
chainA.EnableSuperfluidAsset(fmt.Sprintf("gamm/pool/%d", poolId))
// setup wallets and send gamm tokens to these wallets (both chains)
superfluidVotingWallet := chainANode.CreateWallet("TestSuperfluidVoting")
chainANode.BankSend(fmt.Sprintf("10000000000000000000gamm/pool/%d", poolId), chainA.NodeConfigs[0].PublicAddress, superfluidVotingWallet)
chainANode.LockTokens(fmt.Sprintf("%v%s", sdk.NewInt(1000000000000000000), fmt.Sprintf("gamm/pool/%d", poolId)), "240s", superfluidVotingWallet)
chainA.LatestLockNumber += 1
chainANode.SuperfluidDelegate(chainA.LatestLockNumber, chainA.NodeConfigs[1].OperatorAddress, superfluidVotingWallet)
// create a text prop, deposit and vote yes
chainANode.SubmitTextProposal("superfluid vote overwrite test", sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.InitialMinDeposit)), false)
chainA.LatestProposalNumber += 1
chainANode.DepositProposal(chainA.LatestProposalNumber, false)
for _, node := range chainA.NodeConfigs {
node.VoteYesProposal(initialization.ValidatorWalletName, chainA.LatestProposalNumber)
}
// set delegator vote to no
chainANode.VoteNoProposal(superfluidVotingWallet, chainA.LatestProposalNumber)
s.Eventually(
func() bool {
noTotal, yesTotal, noWithVetoTotal, abstainTotal, err := chainANode.QueryPropTally(chainA.LatestProposalNumber)
if err != nil {
return false
}
if abstainTotal.Int64()+noTotal.Int64()+noWithVetoTotal.Int64()+yesTotal.Int64() <= 0 {
return false
}
return true
},
1*time.Minute,
10*time.Millisecond,
"Osmosis node failed to retrieve prop tally",
)
noTotal, _, _, _, _ := chainANode.QueryPropTally(chainA.LatestProposalNumber)
noTotalFinal, err := strconv.Atoi(noTotal.String())
s.NoError(err)
s.Eventually(
func() bool {
intAccountBalance, err := chainANode.QueryIntermediaryAccount(fmt.Sprintf("gamm/pool/%d", poolId), chainA.NodeConfigs[1].OperatorAddress)
s.Require().NoError(err)
if err != nil {
return false
}
if noTotalFinal != intAccountBalance {
fmt.Printf("noTotalFinal %v does not match intAccountBalance %v", noTotalFinal, intAccountBalance)
return false
}
return true
},
1*time.Minute,
10*time.Millisecond,
"superfluid delegation vote overwrite not working as expected",
)
}
func (s *IntegrationTestSuite) TestCreateConcentratedLiquidityPoolVoting() {
chainA := s.configurer.GetChainConfig(0)
chainANode, err := chainA.GetDefaultNode()
s.NoError(err)
err = chainA.SubmitCreateConcentratedPoolProposal()
s.NoError(err)
var (
expectedDenom0 = "stake"
expectedDenom1 = "uosmo"
expectedTickspacing = uint64(100)
expectedSwapFee = "0.001000000000000000"
)
poolId := chainANode.QueryNumPools()
s.Eventually(
func() bool {
concentratedPool := s.updatedPool(chainANode, poolId)
s.Require().Equal(poolmanagertypes.Concentrated, concentratedPool.GetType())
s.Require().Equal(expectedDenom0, concentratedPool.GetToken0())
s.Require().Equal(expectedDenom1, concentratedPool.GetToken1())
s.Require().Equal(expectedTickspacing, concentratedPool.GetTickSpacing())
s.Require().Equal(expectedSwapFee, concentratedPool.GetSwapFee(sdk.Context{}).String())
return true
},
1*time.Minute,
10*time.Millisecond,
"create concentrated liquidity pool was not successful.",
)
}
func (s *IntegrationTestSuite) TestIBCTokenTransferRateLimiting() {
if s.skipIBC {
s.T().Skip("Skipping IBC tests")
}
chainA := s.configurer.GetChainConfig(0)
chainB := s.configurer.GetChainConfig(1)
node, err := chainA.GetDefaultNode()
s.Require().NoError(err)
// If the RL param is already set. Remember it to set it back at the end
param := node.QueryParams(ibcratelimittypes.ModuleName, string(ibcratelimittypes.KeyContractAddress))
fmt.Println("param", param)
osmoSupply, err := node.QuerySupplyOf("uosmo")
s.Require().NoError(err)
f, err := osmoSupply.ToDec().Float64()
s.Require().NoError(err)
over := f * 0.02
paths := fmt.Sprintf(`{"channel_id": "channel-0", "denom": "%s", "quotas": [{"name":"testQuota", "duration": 86400, "send_recv": [1, 1]}] }`, initialization.OsmoToken.Denom)
// Sending >1%
chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, sdk.NewInt64Coin(initialization.OsmoDenom, int64(over)))
contract, err := chainA.SetupRateLimiting(paths, chainA.NodeConfigs[0].PublicAddress)
s.Require().NoError(err)
s.Eventually(
func() bool {
val := node.QueryParams(ibcratelimittypes.ModuleName, string(ibcratelimittypes.KeyContractAddress))
return strings.Contains(val, contract)
},
1*time.Minute,
10*time.Millisecond,
"Osmosis node failed to retrieve params",
)
// Sending <1%. Should work
chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, sdk.NewInt64Coin(initialization.OsmoDenom, 1))
// Sending >1%. Should fail
node.FailIBCTransfer(initialization.ValidatorWalletName, chainB.NodeConfigs[0].PublicAddress, fmt.Sprintf("%duosmo", int(over)))
// Removing the rate limit so it doesn't affect other tests
node.WasmExecute(contract, `{"remove_path": {"channel_id": "channel-0", "denom": "uosmo"}}`, initialization.ValidatorWalletName)
//reset the param to the original contract if it existed
if param != "" {
err = chainA.SubmitParamChangeProposal(
ibcratelimittypes.ModuleName,
string(ibcratelimittypes.KeyContractAddress),
[]byte(param),
)
s.Require().NoError(err)
s.Eventually(func() bool {
val := node.QueryParams(ibcratelimittypes.ModuleName, string(ibcratelimittypes.KeyContractAddress))
return strings.Contains(val, param)
}, time.Second*30, time.Millisecond*500)
}
}
func (s *IntegrationTestSuite) TestLargeWasmUpload() {
chainA := s.configurer.GetChainConfig(0)
node, err := chainA.GetDefaultNode()
s.NoError(err)