Skip to content

Commit

Permalink
Add delegation plan test (quicksilver-zone#709)
Browse files Browse the repository at this point in the history
* add delegation plan test

* fix: dont attempt to delegate to invalid validators!

* minor fixes, additional tests

* fix: fix delegation test

* gofumpt

* dont select validators jailed for greater than 2 epochs

* verbose variables

* lint

* linting

* linting

* linting

* duplicate import

* err is not checked

---------

Co-authored-by: ducnt131 <62016666+anhductn2001@users.noreply.github.com>
Co-authored-by: anhductn2001 <ntd1312000@gmail.com>
Co-authored-by: ThanhNhann <thanhnhan98qh@gmail.com>
4 people authored Nov 1, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 2e91ee7 commit 108ebf4
Showing 29 changed files with 1,121 additions and 825 deletions.
6 changes: 2 additions & 4 deletions icq-relayer/cmd/keys.go
Original file line number Diff line number Diff line change
@@ -19,10 +19,8 @@ const (
defaultCoinType uint32 = sdk.CoinType
)

var (
// FlagAccountPrefix allows the user to override the prefix for a given account
FlagAccountPrefix = ""
)
// FlagAccountPrefix allows the user to override the prefix for a given account
var FlagAccountPrefix = ""

// keysCmd represents the keys command
func keysCmd() *cobra.Command {
16 changes: 6 additions & 10 deletions icq-relayer/pkg/runner/run.go
Original file line number Diff line number Diff line change
@@ -215,7 +215,6 @@ type Query struct {
}

func handleHistoricRequests(queries []qstypes.Query, sourceChainId string, logger log.Logger, metrics prommetrics.Metrics) {

metrics.HistoricQueries.WithLabelValues("historic-queries").Set(float64(len(queries)))

if len(queries) == 0 {
@@ -363,7 +362,6 @@ func handleEvent(event coretypes.ResultEvent, logger log.Logger, metrics prommet
}

func RunGRPCQuery(ctx context.Context, client *lensclient.ChainClient, method string, reqBz []byte, md metadata.MD, metrics prommetrics.Metrics) (abcitypes.ResponseQuery, metadata.MD, error) {

// parse height header
height, err := lensclient.GetHeightFromMetadata(md)
if err != nil {
@@ -420,6 +418,7 @@ func retryLightblock(ctx context.Context, client *lensclient.ChainClient, height
}
return lightBlock.(*tmtypes.LightBlock), err
}

func doRequestWithMetrics(query Query, logger log.Logger, metrics prommetrics.Metrics) {
startTime := time.Now()
metrics.Requests.WithLabelValues("requests", query.Type).Inc()
@@ -609,7 +608,6 @@ func getHeader(ctx context.Context, client, submitClient *lensclient.ChainClient
clientHeight, ok := trustedHeight.(clienttypes.Height)
if !ok {
return nil, fmt.Errorf("error: Could coerce trusted height")

}

if !historicOk && clientHeight.RevisionHeight >= uint64(requestHeight+1) {
@@ -649,7 +647,6 @@ func getHeader(ctx context.Context, client, submitClient *lensclient.ChainClient
}

func getBlocksForTxResults(node rpcclient.Client, resTxs []*coretypes.ResultTx) (map[int64]*coretypes.ResultBlock, error) {

resBlocks := make(map[int64]*coretypes.ResultBlock)

for _, resTx := range resTxs {
@@ -721,26 +718,26 @@ func flush(chainId string, toSend []sdk.Msg, logger log.Logger, metrics prommetr
resp, err := chainClient.SendMsgs(ctx, msgs, VERSION)
if err != nil {
if resp != nil && resp.Code == 19 && resp.Codespace == "sdk" {
//if err.Error() == "transaction failed with code: 19" {
// if err.Error() == "transaction failed with code: 19" {
_ = logger.Log("msg", "Tx already in mempool")
} else if resp != nil && resp.Code == 12 && resp.Codespace == "sdk" {
//if err.Error() == "transaction failed with code: 19" {
// if err.Error() == "transaction failed with code: 19" {
_ = logger.Log("msg", "Not enough gas")
} else if err.Error() == "context deadline exceeded" {
_ = logger.Log("msg", "Failed to submit in time, retrying")
resp, err := chainClient.SendMsgs(ctx, msgs, VERSION)
if err != nil {
if resp != nil && resp.Code == 19 && resp.Codespace == "sdk" {
//if err.Error() == "transaction failed with code: 19" {
// if err.Error() == "transaction failed with code: 19" {
_ = logger.Log("msg", "Tx already in mempool")
} else if resp != nil && resp.Code == 12 && resp.Codespace == "sdk" {
//if err.Error() == "transaction failed with code: 19" {
// if err.Error() == "transaction failed with code: 19" {
_ = logger.Log("msg", "Not enough gas")
} else if err.Error() == "context deadline exceeded" {
_ = logger.Log("msg", "Failed to submit in time, bailing")
return
} else {
//panic(fmt.Sprintf("panic(1): %v", err))
// panic(fmt.Sprintf("panic(1): %v", err))
_ = logger.Log("msg", "Failed to submit after retry; nevermind, we'll try again!", "err", err)
metrics.FailedTxs.WithLabelValues("failed_txs").Inc()
}
@@ -789,7 +786,6 @@ func unique(msgSlice []sdk.Msg, logger log.Logger) []sdk.Msg {
}

func Close() error {

query := tmquery.MustParse(fmt.Sprintf("message.module='%s'", "interchainquery"))

for _, chainClient := range globalCfg.Cl {
70 changes: 35 additions & 35 deletions x/airdrop/keeper/keeper_test.go
Original file line number Diff line number Diff line change
@@ -58,40 +58,40 @@ func (*KeeperTestSuite) GetQuicksilverApp(chain *ibctesting.TestChain) *app.Quic
}

// SetupTest creates a coordinator with 2 test chains.
func (s *KeeperTestSuite) SetupTest() {
s.coordinator = ibctesting.NewCoordinator(s.T(), 2) // initializes 2 test chains
s.chainA = s.coordinator.GetChain(ibctesting.GetChainID(1)) // convenience and readability
s.chainB = s.coordinator.GetChain(ibctesting.GetChainID(2)) // convenience and readability
func (suite *KeeperTestSuite) SetupTest() {
suite.coordinator = ibctesting.NewCoordinator(suite.T(), 2) // initializes 2 test chains
suite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(1)) // convenience and readability
suite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(2)) // convenience and readability

s.path = newQuicksilverPath(s.chainA, s.chainB)
s.coordinator.SetupConnections(s.path)
suite.path = newQuicksilverPath(suite.chainA, suite.chainB)
suite.coordinator.SetupConnections(suite.path)

s.coordinator.CurrentTime = time.Now().UTC()
s.coordinator.UpdateTime()
suite.coordinator.CurrentTime = time.Now().UTC()
suite.coordinator.UpdateTime()

s.initTestZone()
suite.initTestZone()

s.coordinator.CommitNBlocks(s.chainA, 10)
s.coordinator.CommitNBlocks(s.chainB, 10)
suite.coordinator.CommitNBlocks(suite.chainA, 10)
suite.coordinator.CommitNBlocks(suite.chainB, 10)
}

func (s *KeeperTestSuite) initTestZone() {
func (suite *KeeperTestSuite) initTestZone() {
// test zone
zone := icstypes.Zone{
ConnectionId: s.path.EndpointB.ConnectionID,
ChainId: s.chainB.ChainID,
ConnectionId: suite.path.EndpointB.ConnectionID,
ChainId: suite.chainB.ChainID,
AccountPrefix: "cosmos",
LocalDenom: "uqatom",
BaseDenom: "uatom",
Is_118: true,
}

s.GetQuicksilverApp(s.chainA).InterchainstakingKeeper.SetZone(s.chainA.GetContext(), &zone)
suite.GetQuicksilverApp(suite.chainA).InterchainstakingKeeper.SetZone(suite.chainA.GetContext(), &zone)
}

func (s *KeeperTestSuite) getZoneDrop() types.ZoneDrop {
func (suite *KeeperTestSuite) getZoneDrop() types.ZoneDrop {
zd := types.ZoneDrop{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
StartTime: time.Now().Add(-5 * time.Minute),
Duration: time.Hour,
Decay: 30 * time.Minute,
@@ -115,32 +115,32 @@ func (s *KeeperTestSuite) getZoneDrop() types.ZoneDrop {
return zd
}

func (s *KeeperTestSuite) compressClaimRecords(crs []types.ClaimRecord) []byte {
s.T().Helper()
func (suite *KeeperTestSuite) compressClaimRecords(crs []types.ClaimRecord) []byte {
suite.T().Helper()

bz, err := json.Marshal(&crs)
s.Require().NoError(err)
suite.Require().NoError(err)

var buf bytes.Buffer
zw := zlib.NewWriter(&buf)
_, err = zw.Write(bz)
s.Require().NoError(err)
suite.Require().NoError(err)

err = zw.Close()
s.Require().NoError(err)
suite.Require().NoError(err)

return buf.Bytes()
}

func (s *KeeperTestSuite) initTestZoneDrop() {
zd := s.getZoneDrop()
s.GetQuicksilverApp(s.chainA).AirdropKeeper.SetZoneDrop(s.chainA.GetContext(), zd)
s.fundZoneDrop(zd.ChainId, zd.Allocation)
func (suite *KeeperTestSuite) initTestZoneDrop() {
zd := suite.getZoneDrop()
suite.GetQuicksilverApp(suite.chainA).AirdropKeeper.SetZoneDrop(suite.chainA.GetContext(), zd)
suite.fundZoneDrop(zd.ChainId, zd.Allocation)
}

func (s *KeeperTestSuite) fundZoneDrop(chainID string, amount uint64) {
quicksilver := s.GetQuicksilverApp(s.chainA)
ctx := s.chainA.GetContext()
func (suite *KeeperTestSuite) fundZoneDrop(chainID string, amount uint64) {
quicksilver := suite.GetQuicksilverApp(suite.chainA)
ctx := suite.chainA.GetContext()
coins := sdk.NewCoins(
sdk.NewCoin(
quicksilver.StakingKeeper.BondDenom(ctx),
@@ -151,16 +151,16 @@ func (s *KeeperTestSuite) fundZoneDrop(chainID string, amount uint64) {
zdacc := quicksilver.AirdropKeeper.GetZoneDropAccountAddress(chainID)

err := quicksilver.MintKeeper.MintCoins(ctx, coins)
s.Require().NoError(err)
suite.Require().NoError(err)

err = quicksilver.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, zdacc, coins)
s.Require().NoError(err)
suite.Require().NoError(err)
}

func (s *KeeperTestSuite) setClaimRecord(cr types.ClaimRecord) {
err := s.GetQuicksilverApp(s.chainA).AirdropKeeper.SetClaimRecord(s.chainA.GetContext(), cr)
func (suite *KeeperTestSuite) setClaimRecord(cr types.ClaimRecord) {
err := suite.GetQuicksilverApp(suite.chainA).AirdropKeeper.SetClaimRecord(suite.chainA.GetContext(), cr)
if err != nil {
s.T().Logf("setClaimRecord error: %v", err)
suite.T().Logf("setClaimRecord error: %v", err)
}
s.Require().NoError(err)
suite.Require().NoError(err)
}
124 changes: 62 additions & 62 deletions x/airdrop/keeper/msg_server_test.go
Original file line number Diff line number Diff line change
@@ -15,8 +15,8 @@ import (
minttypes "github.com/quicksilver-zone/quicksilver/x/mint/types"
)

func (s *KeeperTestSuite) Test_msgServer_Claim() {
appA := s.GetQuicksilverApp(s.chainA)
func (suite *KeeperTestSuite) Test_msgServer_Claim() {
appA := suite.GetQuicksilverApp(suite.chainA)

userAddress := addressutils.GenerateAccAddressForTest().String()
denom := "uatom" // same as test zone setup in keeper_test
@@ -40,7 +40,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// no zone airdrop state

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionInitialClaim),
Address: userAddress,
Proofs: nil,
@@ -53,10 +53,10 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
"noclaimrecord",
func() {
// set valid zone airdrop state
s.initTestZoneDrop()
suite.initTestZoneDrop()

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionInitialClaim),
Address: userAddress,
Proofs: nil,
@@ -74,17 +74,17 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {

// add claim record
cr := types.ClaimRecord{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Address: userAddress,
ActionsCompleted: nil,
MaxAllocation: 100000000,
BaseValue: 10000000,
}

s.setClaimRecord(cr)
suite.setClaimRecord(cr)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionInitialClaim),
Address: userAddress,
Proofs: nil,
@@ -102,7 +102,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {

// add deposit
rcpt := icstypes.Receipt{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Sender: userAddress,
Txhash: "TestDeposit01",
Amount: sdk.NewCoins(
@@ -113,12 +113,12 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
),
}
appA.InterchainstakingKeeper.SetReceipt(
s.chainA.GetContext(),
suite.chainA.GetContext(),
rcpt,
)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionDepositT5),
Address: userAddress,
Proofs: nil,
@@ -133,7 +133,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionDepositT4),
Address: userAddress,
Proofs: nil,
@@ -148,7 +148,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionDepositT3),
Address: userAddress,
Proofs: nil,
@@ -169,7 +169,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionDepositT2),
Address: userAddress,
Proofs: nil,
@@ -184,7 +184,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionDepositT1),
Address: userAddress,
Proofs: nil,
@@ -200,7 +200,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {

// add deposit
rcpt := icstypes.Receipt{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Sender: userAddress,
Txhash: "T5_02",
Amount: sdk.NewCoins(
@@ -211,12 +211,12 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
),
}
appA.InterchainstakingKeeper.SetReceipt(
s.chainA.GetContext(),
suite.chainA.GetContext(),
rcpt,
)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionDepositT5),
Address: userAddress,
Proofs: nil,
@@ -237,7 +237,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionStakeQCK),
Address: userAddress,
Proofs: nil,
@@ -252,21 +252,21 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

// add staking delegation
valAddress, err := sdk.ValAddressFromHex(s.chainA.Vals.Validators[2].Address.String())
s.Require().NoError(err)
valAddress, err := sdk.ValAddressFromHex(suite.chainA.Vals.Validators[2].Address.String())
suite.Require().NoError(err)

del := staking.Delegation{
DelegatorAddress: userAddress,
ValidatorAddress: valAddress.String(),
Shares: sdk.MustNewDecFromStr("10.0"),
}
appA.StakingKeeper.SetDelegation(
s.chainA.GetContext(),
suite.chainA.GetContext(),
del,
)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionStakeQCK),
Address: userAddress,
Proofs: nil,
@@ -283,7 +283,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionSignalIntent),
Address: userAddress,
Proofs: nil,
@@ -298,11 +298,11 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

// add intent
valAddress, err := sdk.ValAddressFromHex(s.chainB.Vals.Validators[1].Address.String())
s.Require().NoError(err)
valAddress, err := sdk.ValAddressFromHex(suite.chainB.Vals.Validators[1].Address.String())
suite.Require().NoError(err)

zone, found := appA.InterchainstakingKeeper.GetZone(s.chainA.GetContext(), s.chainB.ChainID)
s.Require().True(found)
zone, found := appA.InterchainstakingKeeper.GetZone(suite.chainA.GetContext(), suite.chainB.ChainID)
suite.Require().True(found)

intent := icstypes.DelegatorIntent{
Delegator: userAddress,
@@ -314,14 +314,14 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
},
}
appA.InterchainstakingKeeper.SetDelegatorIntent(
s.chainA.GetContext(),
suite.chainA.GetContext(),
&zone,
intent,
false,
)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionSignalIntent),
Address: userAddress,
Proofs: nil,
@@ -338,7 +338,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionQSGov),
Address: userAddress,
Proofs: nil,
@@ -357,7 +357,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
Id: 0,
Status: govv1.StatusPassed,
}
appA.GovKeeper.SetProposal(s.chainA.GetContext(), prop)
appA.GovKeeper.SetProposal(suite.chainA.GetContext(), prop)

vote := govv1.Vote{
ProposalId: 0,
@@ -369,10 +369,10 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
},
},
}
appA.GovKeeper.SetVote(s.chainA.GetContext(), vote)
appA.GovKeeper.SetVote(suite.chainA.GetContext(), vote)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionQSGov),
Address: userAddress,
Proofs: nil,
@@ -405,7 +405,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionOsmosis),
Address: userAddress,
Proofs: nil,
@@ -420,7 +420,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// use existing state (from prev test)

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionOsmosis),
Address: userAddress,
Proofs: []*cmtypes.Proof{
@@ -440,7 +440,7 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
// consensusState := exported.ConsensusState{}

msg = types.MsgClaim{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Action: int64(types.ActionOsmosis),
Address: userAddress,
Proofs: []*cmtypes.Proof{
@@ -469,27 +469,27 @@ func (s *KeeperTestSuite) Test_msgServer_Claim() {
for _, tt := range tests {
tt := tt

s.Run(tt.name, func() {
suite.Run(tt.name, func() {
tt.malleate()

k := keeper.NewMsgServerImpl(appA.AirdropKeeper)
resp, err := k.Claim(sdk.WrapSDKContext(s.chainA.GetContext()), &msg)
resp, err := k.Claim(sdk.WrapSDKContext(suite.chainA.GetContext()), &msg)
if tt.wantErr {
s.Require().Error(err)
s.Require().Nil(resp)
s.T().Logf("Error: %v", err)
suite.Require().Error(err)
suite.Require().Nil(resp)
suite.T().Logf("Error: %v", err)
return
}

s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().Equal(tt.want, resp)
suite.Require().NoError(err)
suite.Require().NotNil(resp)
suite.Require().Equal(tt.want, resp)
})
}
}

func (s *KeeperTestSuite) Test_msgServer_IncentivePoolSpend() {
appA := s.GetQuicksilverApp(s.chainA)
func (suite *KeeperTestSuite) Test_msgServer_IncentivePoolSpend() {
appA := suite.GetQuicksilverApp(suite.chainA)

modAccAddr := "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn"
userAddress := addressutils.GenerateAccAddressForTest().String()
@@ -498,10 +498,10 @@ func (s *KeeperTestSuite) Test_msgServer_IncentivePoolSpend() {
mintCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewIntFromUint64(100000000)))

// set up mod acct with funds
err := appA.BankKeeper.MintCoins(s.chainA.GetContext(), minttypes.ModuleName, mintCoins)
s.Require().NoError(err)
err = appA.BankKeeper.SendCoinsFromModuleToModule(s.chainA.GetContext(), minttypes.ModuleName, types.ModuleName, mintCoins)
s.Require().NoError(err)
err := appA.BankKeeper.MintCoins(suite.chainA.GetContext(), minttypes.ModuleName, mintCoins)
suite.Require().NoError(err)
err = appA.BankKeeper.SendCoinsFromModuleToModule(suite.chainA.GetContext(), minttypes.ModuleName, types.ModuleName, mintCoins)
suite.Require().NoError(err)

msg := types.MsgIncentivePoolSpend{}
tests := []struct {
@@ -538,27 +538,27 @@ func (s *KeeperTestSuite) Test_msgServer_IncentivePoolSpend() {
for _, tt := range tests {
tt := tt

s.Run(tt.name, func() {
suite.Run(tt.name, func() {
tt.malleate()

k := keeper.NewMsgServerImpl(appA.AirdropKeeper)
resp, err := k.IncentivePoolSpend(sdk.WrapSDKContext(s.chainA.GetContext()), &msg)
resp, err := k.IncentivePoolSpend(sdk.WrapSDKContext(suite.chainA.GetContext()), &msg)
if tt.wantErr {
s.Require().Error(err)
s.Require().Nil(resp)
s.T().Logf("Error: %v", err)
suite.Require().Error(err)
suite.Require().Nil(resp)
suite.T().Logf("Error: %v", err)
return
}

s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().Equal(tt.want, resp)
suite.Require().NoError(err)
suite.Require().NotNil(resp)
suite.Require().Equal(tt.want, resp)

// verify that balance has been properly transferred
accAddr, err := sdk.AccAddressFromBech32(msg.ToAddress)
s.Require().NoError(err)
balance := appA.BankKeeper.GetAllBalances(s.chainA.GetContext(), accAddr)
s.Require().Equal(msg.Amount, balance)
suite.Require().NoError(err)
balance := appA.BankKeeper.GetAllBalances(suite.chainA.GetContext(), accAddr)
suite.Require().Equal(msg.Amount, balance)
})
}
}
40 changes: 20 additions & 20 deletions x/airdrop/keeper/proposal_handler_test.go
Original file line number Diff line number Diff line change
@@ -10,11 +10,11 @@ import (
"github.com/quicksilver-zone/quicksilver/x/airdrop/types"
)

func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
appA := s.GetQuicksilverApp(s.chainA)
func (suite *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
appA := suite.GetQuicksilverApp(suite.chainA)

validZoneDrop := types.ZoneDrop{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
StartTime: time.Now().Add(time.Hour),
Duration: time.Hour,
Decay: 30 * time.Minute,
@@ -77,7 +77,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
crs := make([]types.ClaimRecord, len(userAddresses))
for i := range crs {
crs[i] = types.ClaimRecord{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Address: userAddresses[i],
ActionsCompleted: nil,
MaxAllocation: 100000000,
@@ -89,7 +89,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
Title: "Test Zone Airdrop Proposal",
Description: "Adding this zone drop allows for automated testing",
ZoneDrop: &zd,
ClaimRecords: s.compressClaimRecords(crs),
ClaimRecords: suite.compressClaimRecords(crs),
}
},
true,
@@ -98,7 +98,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
"invalid-zd-started",
func() {
zd := types.ZoneDrop{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
StartTime: time.Now().Add(-5 * time.Minute),
Duration: time.Hour,
Decay: 30 * time.Minute,
@@ -122,7 +122,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
crs := make([]types.ClaimRecord, len(userAddresses))
for i := range crs {
crs[i] = types.ClaimRecord{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Address: userAddresses[i],
ActionsCompleted: nil,
MaxAllocation: 100000000,
@@ -134,7 +134,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
Title: "Test Zone Airdrop Proposal",
Description: "Adding this zone drop allows for automated testing",
ZoneDrop: &zd,
ClaimRecords: s.compressClaimRecords(crs),
ClaimRecords: suite.compressClaimRecords(crs),
}
},
true,
@@ -158,7 +158,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
Title: "Test Zone Airdrop Proposal",
Description: "Adding this zone drop allows for automated testing",
ZoneDrop: &zd,
ClaimRecords: s.compressClaimRecords(crs),
ClaimRecords: suite.compressClaimRecords(crs),
}
},
true,
@@ -171,7 +171,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
crs := make([]types.ClaimRecord, len(userAddresses))
for i := range crs {
crs[i] = types.ClaimRecord{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Address: userAddresses[i],
ActionsCompleted: map[int32]*types.CompletedAction{
1: {},
@@ -185,7 +185,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
Title: "Test Zone Airdrop Proposal",
Description: "Adding this zone drop allows for automated testing",
ZoneDrop: &zd,
ClaimRecords: s.compressClaimRecords(crs),
ClaimRecords: suite.compressClaimRecords(crs),
}
},
true,
@@ -198,7 +198,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
crs := make([]types.ClaimRecord, len(userAddresses))
for i := range crs {
crs[i] = types.ClaimRecord{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Address: userAddresses[i],
ActionsCompleted: nil,
MaxAllocation: 1000000001,
@@ -210,7 +210,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
Title: "Test Zone Airdrop Proposal",
Description: "Adding this zone drop allows for automated testing",
ZoneDrop: &zd,
ClaimRecords: s.compressClaimRecords(crs),
ClaimRecords: suite.compressClaimRecords(crs),
}
},
true,
@@ -223,7 +223,7 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
crs := make([]types.ClaimRecord, len(userAddresses))
for i := range crs {
crs[i] = types.ClaimRecord{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Address: userAddresses[i],
ActionsCompleted: nil,
MaxAllocation: 100000000,
@@ -235,25 +235,25 @@ func (s *KeeperTestSuite) TestHandleRegisterZoneDropProposal() {
Title: "Test Zone Airdrop Proposal",
Description: "Adding this zone drop allows for automated testing",
ZoneDrop: &zd,
ClaimRecords: s.compressClaimRecords(crs),
ClaimRecords: suite.compressClaimRecords(crs),
}
},
false,
},
}
for _, tt := range tests {
s.Run(tt.name, func() {
suite.Run(tt.name, func() {
tt.malleate()

k := appA.AirdropKeeper
err := keeper.HandleRegisterZoneDropProposal(s.chainA.GetContext(), k, &prop)
err := keeper.HandleRegisterZoneDropProposal(suite.chainA.GetContext(), k, &prop)
if tt.wantErr {
s.Require().Error(err)
s.T().Logf("Error: %v", err)
suite.Require().Error(err)
suite.T().Logf("Error: %v", err)
return
}

s.Require().NoError(err)
suite.Require().NoError(err)
})
}
}
114 changes: 57 additions & 57 deletions x/claimsmanager/keeper/claims_test.go
Original file line number Diff line number Diff line change
@@ -56,7 +56,7 @@ var testClaims = []types.Claim{
},
}

func (s *KeeperTestSuite) TestKeeper_NewClaim() {
func (suite *KeeperTestSuite) TestKeeper_NewClaim() {
type args struct {
address string
chainID string
@@ -78,14 +78,14 @@ func (s *KeeperTestSuite) TestKeeper_NewClaim() {
"valid",
args{
testAddress,
s.chainB.ChainID,
suite.chainB.ChainID,
types.ClaimTypeLiquidToken,
"",
5000000,
},
types.Claim{
UserAddress: testAddress,
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
Module: types.ClaimTypeLiquidToken,
SourceChainId: "",
Amount: 5000000,
@@ -94,105 +94,105 @@ func (s *KeeperTestSuite) TestKeeper_NewClaim() {
}

for _, tt := range tests {
s.Run(tt.name, func() {
suite.Run(tt.name, func() {
got := types.NewClaim(tt.args.address, tt.args.chainID, tt.args.module, tt.args.srcChainID, tt.args.amount)
s.Require().Equal(tt.want, got)
suite.Require().Equal(tt.want, got)
})
}
}

func (s *KeeperTestSuite) TestKeeper_ClaimStore() {
k := s.GetQuicksilverApp(s.chainA).ClaimsManagerKeeper
func (suite *KeeperTestSuite) TestKeeper_ClaimStore() {
k := suite.GetQuicksilverApp(suite.chainA).ClaimsManagerKeeper

testClaims[0].ChainId = s.chainB.ChainID
testClaims[1].ChainId = s.chainB.ChainID
testClaims[2].ChainId = s.chainB.ChainID
testClaims[3].ChainId = s.chainB.ChainID
testClaims[0].ChainId = suite.chainB.ChainID
testClaims[1].ChainId = suite.chainB.ChainID
testClaims[2].ChainId = suite.chainB.ChainID
testClaims[3].ChainId = suite.chainB.ChainID

// no claim set
var getClaim types.Claim
_, found := k.GetClaim(s.chainA.GetContext(), s.chainB.ChainID, testAddress, types.ClaimTypeOsmosisPool, "osmosis-1")
s.Require().False(found)
_, found := k.GetClaim(suite.chainA.GetContext(), suite.chainB.ChainID, testAddress, types.ClaimTypeOsmosisPool, "osmosis-1")
suite.Require().False(found)

// set claim
k.SetClaim(s.chainA.GetContext(), &testClaims[0])
k.SetClaim(suite.chainA.GetContext(), &testClaims[0])

getClaim, found = k.GetClaim(s.chainA.GetContext(), s.chainB.ChainID, testAddress, types.ClaimTypeOsmosisPool, "osmosis-1")
s.Require().True(found)
s.Require().Equal(testClaims[0], getClaim)
getClaim, found = k.GetClaim(suite.chainA.GetContext(), suite.chainB.ChainID, testAddress, types.ClaimTypeOsmosisPool, "osmosis-1")
suite.Require().True(found)
suite.Require().Equal(testClaims[0], getClaim)

// delete claim
k.DeleteClaim(s.chainA.GetContext(), &getClaim)
getClaim, found = k.GetClaim(s.chainA.GetContext(), s.chainB.ChainID, testAddress, types.ClaimTypeOsmosisPool, "osmosis-1")
s.Require().False(found)
k.DeleteClaim(suite.chainA.GetContext(), &getClaim)
getClaim, found = k.GetClaim(suite.chainA.GetContext(), suite.chainB.ChainID, testAddress, types.ClaimTypeOsmosisPool, "osmosis-1")
suite.Require().False(found)

// iterators
var claims []*types.Claim

k.SetClaim(s.chainA.GetContext(), &testClaims[0])
k.SetClaim(s.chainA.GetContext(), &testClaims[1])
k.SetClaim(s.chainA.GetContext(), &testClaims[2])
k.SetClaim(s.chainA.GetContext(), &testClaims[3])
k.SetClaim(s.chainA.GetContext(), &testClaims[4])
k.SetClaim(s.chainA.GetContext(), &testClaims[5])
k.SetClaim(suite.chainA.GetContext(), &testClaims[0])
k.SetClaim(suite.chainA.GetContext(), &testClaims[1])
k.SetClaim(suite.chainA.GetContext(), &testClaims[2])
k.SetClaim(suite.chainA.GetContext(), &testClaims[3])
k.SetClaim(suite.chainA.GetContext(), &testClaims[4])
k.SetClaim(suite.chainA.GetContext(), &testClaims[5])

claims = k.AllClaims(s.chainA.GetContext())
s.Require().Equal(6, len(claims))
claims = k.AllClaims(suite.chainA.GetContext())
suite.Require().Equal(6, len(claims))

claims = k.AllZoneClaims(s.chainA.GetContext(), s.chainB.ChainID)
s.Require().Equal(4, len(claims))
claims = k.AllZoneClaims(suite.chainA.GetContext(), suite.chainB.ChainID)
suite.Require().Equal(4, len(claims))

claims = k.AllZoneClaims(s.chainA.GetContext(), "cosmoshub-4")
s.Require().Equal(2, len(claims))
claims = k.AllZoneClaims(suite.chainA.GetContext(), "cosmoshub-4")
suite.Require().Equal(2, len(claims))

// archive (last epoch)
k.ArchiveAndGarbageCollectClaims(s.chainA.GetContext(), s.chainB.ChainID)
k.ArchiveAndGarbageCollectClaims(suite.chainA.GetContext(), suite.chainB.ChainID)

getClaim, found = k.GetLastEpochClaim(s.chainA.GetContext(), s.chainB.ChainID, testAddress, types.ClaimTypeOsmosisPool, "osmosis-1")
s.Require().True(found)
s.Require().Equal(testClaims[0], getClaim)
getClaim, found = k.GetLastEpochClaim(suite.chainA.GetContext(), suite.chainB.ChainID, testAddress, types.ClaimTypeOsmosisPool, "osmosis-1")
suite.Require().True(found)
suite.Require().Equal(testClaims[0], getClaim)

// "cosmoshub-4 was not archived so this should not be found"
getClaim, found = k.GetLastEpochClaim(s.chainA.GetContext(), "cosmoshub-4", testAddress, types.ClaimTypeLiquidToken, "")
s.Require().False(found)
getClaim, found = k.GetLastEpochClaim(suite.chainA.GetContext(), "cosmoshub-4", testAddress, types.ClaimTypeLiquidToken, "")
suite.Require().False(found)

// set archive claim
k.SetLastEpochClaim(s.chainA.GetContext(), &testClaims[4])
k.SetLastEpochClaim(suite.chainA.GetContext(), &testClaims[4])

getClaim, found = k.GetLastEpochClaim(s.chainA.GetContext(), "cosmoshub-4", testAddress, types.ClaimTypeLiquidToken, "")
s.Require().True(found)
s.Require().Equal(testClaims[4], getClaim)
getClaim, found = k.GetLastEpochClaim(suite.chainA.GetContext(), "cosmoshub-4", testAddress, types.ClaimTypeLiquidToken, "")
suite.Require().True(found)
suite.Require().Equal(testClaims[4], getClaim)

// delete archive claim
k.DeleteLastEpochClaim(s.chainA.GetContext(), &getClaim)
getClaim, found = k.GetLastEpochClaim(s.chainA.GetContext(), "cosmoshub-4", testAddress, types.ClaimTypeLiquidToken, "")
s.Require().False(found)
k.DeleteLastEpochClaim(suite.chainA.GetContext(), &getClaim)
getClaim, found = k.GetLastEpochClaim(suite.chainA.GetContext(), "cosmoshub-4", testAddress, types.ClaimTypeLiquidToken, "")
suite.Require().False(found)

// iterators
// we expect none as claims have been archived
claims = k.AllZoneClaims(s.chainA.GetContext(), s.chainB.ChainID)
s.Require().Equal(0, len(claims))
claims = k.AllZoneClaims(suite.chainA.GetContext(), suite.chainB.ChainID)
suite.Require().Equal(0, len(claims))

// we expect the archived claims for chainB
claims = k.AllZoneLastEpochClaims(s.chainA.GetContext(), s.chainB.ChainID)
s.Require().Equal(4, len(claims))
claims = k.AllZoneLastEpochClaims(suite.chainA.GetContext(), suite.chainB.ChainID)
suite.Require().Equal(4, len(claims))

// clear
k.ClearClaims(s.chainA.GetContext(), "cosmoshub-4")
k.ClearClaims(suite.chainA.GetContext(), "cosmoshub-4")
// we expect none as claims have been cleared
claims = k.AllZoneClaims(s.chainA.GetContext(), "cosmoshub-4")
s.Require().Equal(0, len(claims))
claims = k.AllZoneClaims(suite.chainA.GetContext(), "cosmoshub-4")
suite.Require().Equal(0, len(claims))

// we archive current claims (none) to ensure the last epoch claims are correctly set
k.ArchiveAndGarbageCollectClaims(s.chainA.GetContext(), s.chainB.ChainID)
k.ArchiveAndGarbageCollectClaims(suite.chainA.GetContext(), suite.chainB.ChainID)

// we expect none as claims have been archived
claims = k.AllZoneClaims(s.chainA.GetContext(), s.chainB.ChainID)
s.Require().Equal(0, len(claims))
claims = k.AllZoneClaims(suite.chainA.GetContext(), suite.chainB.ChainID)
suite.Require().Equal(0, len(claims))

// we expect none as no current claims existed when we archived
claims = k.AllZoneLastEpochClaims(s.chainA.GetContext(), s.chainB.ChainID)
s.Require().Equal(0, len(claims))
claims = k.AllZoneLastEpochClaims(suite.chainA.GetContext(), suite.chainB.ChainID)
suite.Require().Equal(0, len(claims))
}

// func (suite *KeeperTestSuite) TestKeeper_IterateLastEpochUserClaims() {
40 changes: 20 additions & 20 deletions x/claimsmanager/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
@@ -6,14 +6,14 @@ import (
"github.com/quicksilver-zone/quicksilver/x/claimsmanager/types"
)

func (s *KeeperTestSuite) TestKeeper_Queries() {
k := s.GetQuicksilverApp(s.chainA).ClaimsManagerKeeper
func (suite *KeeperTestSuite) TestKeeper_Queries() {
k := suite.GetQuicksilverApp(suite.chainA).ClaimsManagerKeeper

// now that we have a kepper set the chainID of chainB
testClaims[0].ChainId = s.chainB.ChainID
testClaims[1].ChainId = s.chainB.ChainID
testClaims[2].ChainId = s.chainB.ChainID
testClaims[3].ChainId = s.chainB.ChainID
testClaims[0].ChainId = suite.chainB.ChainID
testClaims[1].ChainId = suite.chainB.ChainID
testClaims[2].ChainId = suite.chainB.ChainID
testClaims[3].ChainId = suite.chainB.ChainID

tests := []struct {
name string
@@ -26,7 +26,7 @@ func (s *KeeperTestSuite) TestKeeper_Queries() {
"Claims_chainB",
func() {},
&types.QueryClaimsRequest{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
},
k.Claims,
4,
@@ -52,10 +52,10 @@ func (s *KeeperTestSuite) TestKeeper_Queries() {
{
"LastEpochClaims_chainB",
func() {
k.ArchiveAndGarbageCollectClaims(s.chainA.GetContext(), s.chainB.ChainID)
k.ArchiveAndGarbageCollectClaims(suite.chainA.GetContext(), suite.chainB.ChainID)
},
&types.QueryClaimsRequest{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
},
k.LastEpochClaims,
4,
@@ -82,20 +82,20 @@ func (s *KeeperTestSuite) TestKeeper_Queries() {
},
}

k.SetClaim(s.chainA.GetContext(), &testClaims[0])
k.SetClaim(s.chainA.GetContext(), &testClaims[1])
k.SetClaim(s.chainA.GetContext(), &testClaims[2])
k.SetClaim(s.chainA.GetContext(), &testClaims[3])
k.SetClaim(s.chainA.GetContext(), &testClaims[4])
k.SetClaim(s.chainA.GetContext(), &testClaims[5])
k.SetClaim(suite.chainA.GetContext(), &testClaims[0])
k.SetClaim(suite.chainA.GetContext(), &testClaims[1])
k.SetClaim(suite.chainA.GetContext(), &testClaims[2])
k.SetClaim(suite.chainA.GetContext(), &testClaims[3])
k.SetClaim(suite.chainA.GetContext(), &testClaims[4])
k.SetClaim(suite.chainA.GetContext(), &testClaims[5])

for _, tt := range tests {
s.Run(tt.name, func() {
suite.Run(tt.name, func() {
tt.malleate()
resp, err := tt.queryFn(s.chainA.GetContext(), tt.req)
s.Require().NoError(err)
s.Require().NotNil(resp.Claims)
s.Require().Equal(tt.expectLength, len(resp.Claims))
resp, err := tt.queryFn(suite.chainA.GetContext(), tt.req)
suite.Require().NoError(err)
suite.Require().NotNil(resp.Claims)
suite.Require().Equal(tt.expectLength, len(resp.Claims))
})
}
}
32 changes: 16 additions & 16 deletions x/claimsmanager/keeper/keeper_test.go
Original file line number Diff line number Diff line change
@@ -44,7 +44,7 @@ type KeeperTestSuite struct {
path *ibctesting.Path
}

func (s *KeeperTestSuite) GetQuicksilverApp(chain *ibctesting.TestChain) *app.Quicksilver {
func (suite *KeeperTestSuite) GetQuicksilverApp(chain *ibctesting.TestChain) *app.Quicksilver {
quicksilver, ok := chain.App.(*app.Quicksilver)
if !ok {
panic("not quicksilver app")
@@ -54,25 +54,25 @@ func (s *KeeperTestSuite) GetQuicksilverApp(chain *ibctesting.TestChain) *app.Qu
}

// SetupTest creates a coordinator with 2 test chains.
func (s *KeeperTestSuite) SetupTest() {
s.coordinator = ibctesting.NewCoordinator(s.T(), 2) // initializes 2 test chains
s.chainA = s.coordinator.GetChain(ibctesting.GetChainID(1)) // convenience and readability
s.chainB = s.coordinator.GetChain(ibctesting.GetChainID(2)) // convenience and readability
func (suite *KeeperTestSuite) SetupTest() {
suite.coordinator = ibctesting.NewCoordinator(suite.T(), 2) // initializes 2 test chains
suite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(1)) // convenience and readability
suite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(2)) // convenience and readability

s.path = newQuicksilverPath(s.chainA, s.chainB)
s.coordinator.SetupConnections(s.path)
suite.path = newQuicksilverPath(suite.chainA, suite.chainB)
suite.coordinator.SetupConnections(suite.path)

s.coordinator.CurrentTime = time.Now().UTC()
s.coordinator.UpdateTime()
suite.coordinator.CurrentTime = time.Now().UTC()
suite.coordinator.UpdateTime()

s.initTestZone()
suite.initTestZone()
}

func (s *KeeperTestSuite) initTestZone() {
func (suite *KeeperTestSuite) initTestZone() {
// test zone
zone := icstypes.Zone{
ConnectionId: s.path.EndpointA.ConnectionID,
ChainId: s.chainB.ChainID,
ConnectionId: suite.path.EndpointA.ConnectionID,
ChainId: suite.chainB.ChainID,
AccountPrefix: "bcosmos",
LocalDenom: "uqatom",
BaseDenom: "uatom",
@@ -82,7 +82,7 @@ func (s *KeeperTestSuite) initTestZone() {
Decimals: 6,
Is_118: true,
}
s.GetQuicksilverApp(s.chainA).InterchainstakingKeeper.SetZone(s.chainA.GetContext(), &zone)
suite.GetQuicksilverApp(suite.chainA).InterchainstakingKeeper.SetZone(suite.chainA.GetContext(), &zone)

// cosmos zone
zone = icstypes.Zone{
@@ -97,7 +97,7 @@ func (s *KeeperTestSuite) initTestZone() {
Decimals: 6,
Is_118: true,
}
s.GetQuicksilverApp(s.chainA).InterchainstakingKeeper.SetZone(s.chainA.GetContext(), &zone)
suite.GetQuicksilverApp(suite.chainA).InterchainstakingKeeper.SetZone(suite.chainA.GetContext(), &zone)

// osmosis zone
zone = icstypes.Zone{
@@ -112,5 +112,5 @@ func (s *KeeperTestSuite) initTestZone() {
Decimals: 6,
Is_118: true,
}
s.GetQuicksilverApp(s.chainA).InterchainstakingKeeper.SetZone(s.chainA.GetContext(), &zone)
suite.GetQuicksilverApp(suite.chainA).InterchainstakingKeeper.SetZone(suite.chainA.GetContext(), &zone)
}
14 changes: 7 additions & 7 deletions x/claimsmanager/keeper/self_consensus_state_test.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
package keeper_test

func (s *KeeperTestSuite) TestGetSetDelete() {
k := s.GetQuicksilverApp(s.chainA).ClaimsManagerKeeper
ctx := s.chainA.GetContext()
func (suite *KeeperTestSuite) TestGetSetDelete() {
k := suite.GetQuicksilverApp(suite.chainA).ClaimsManagerKeeper
ctx := suite.chainA.GetContext()

_, found := k.GetSelfConsensusState(ctx, "test")
s.Require().False(found)
suite.Require().False(found)

err := k.StoreSelfConsensusState(ctx, "test")
s.Require().NoError(err)
suite.Require().NoError(err)

_, found = k.GetSelfConsensusState(ctx, "test")
s.Require().True(found)
suite.Require().True(found)

k.DeleteSelfConsensusState(ctx, "test")

_, found = k.GetSelfConsensusState(ctx, "test")
s.Require().False(found)
suite.Require().False(found)
}
140 changes: 70 additions & 70 deletions x/epochs/keeper/abci_test.go
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ import (
"github.com/quicksilver-zone/quicksilver/x/epochs/types"
)

func (s *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
func (suite *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
var epochInfo types.EpochInfo

now := time.Now()
@@ -27,9 +27,9 @@ func (s *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 1,
expInitialEpochStartTime: now,
fn: func() {
s.ctx = s.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
epochInfo = s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
suite.ctx = suite.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
epochInfo = suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
},
},
{
@@ -38,9 +38,9 @@ func (s *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 1,
expInitialEpochStartTime: now,
fn: func() {
s.ctx = s.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
epochInfo = s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
suite.ctx = suite.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
epochInfo = suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
},
},
{
@@ -49,11 +49,11 @@ func (s *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 1,
expInitialEpochStartTime: now,
fn: func() {
s.ctx = s.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
s.ctx = s.ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 31))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
epochInfo = s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
suite.ctx = suite.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
suite.ctx = suite.ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 31))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
epochInfo = suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
},
},
// Test that incrementing _exactly_ 1 month increments the epoch count.
@@ -63,11 +63,11 @@ func (s *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 2,
expInitialEpochStartTime: now,
fn: func() {
s.ctx = s.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
s.ctx = s.ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 32))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
epochInfo = s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
suite.ctx = suite.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
suite.ctx = suite.ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 32))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
epochInfo = suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
},
},
{
@@ -76,13 +76,13 @@ func (s *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 2,
expInitialEpochStartTime: now,
fn: func() {
s.ctx = s.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
s.ctx = s.ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 32))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
s.ctx.WithBlockHeight(4).WithBlockTime(now.Add(time.Hour * 24 * 33))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
epochInfo = s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
suite.ctx = suite.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
suite.ctx = suite.ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 32))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
suite.ctx.WithBlockHeight(4).WithBlockTime(now.Add(time.Hour * 24 * 33))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
epochInfo = suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
},
},
{
@@ -91,39 +91,39 @@ func (s *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 2,
expInitialEpochStartTime: now,
fn: func() {
s.ctx = s.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
s.ctx = s.ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 32))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
s.ctx.WithBlockHeight(4).WithBlockTime(now.Add(time.Hour * 24 * 33))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
epochInfo = s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
suite.ctx = suite.ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
suite.ctx = suite.ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 32))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
suite.ctx.WithBlockHeight(4).WithBlockTime(now.Add(time.Hour * 24 * 33))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)
epochInfo = suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
},
},
}

for i, tc := range testCases {
s.Run(fmt.Sprintf("Case %d", i), func() {
s.SetupTest() // reset
suite.Run(fmt.Sprintf("Case %d", i), func() {
suite.SetupTest() // reset

// On init genesis, default epochs information is set
// To check init genesis again, should make it fresh status
epochInfos := s.app.EpochsKeeper.AllEpochInfos(s.ctx)
epochInfos := suite.app.EpochsKeeper.AllEpochInfos(suite.ctx)
for _, epochInfo := range epochInfos {
s.app.EpochsKeeper.DeleteEpochInfo(s.ctx, epochInfo.Identifier)
suite.app.EpochsKeeper.DeleteEpochInfo(suite.ctx, epochInfo.Identifier)
}

s.ctx = s.ctx.WithBlockHeight(1).WithBlockTime(now)
suite.ctx = suite.ctx.WithBlockHeight(1).WithBlockTime(now)

// check init genesis
epochs.InitGenesis(s.ctx, s.app.EpochsKeeper, types.GenesisState{
epochs.InitGenesis(suite.ctx, suite.app.EpochsKeeper, types.GenesisState{
Epochs: []types.EpochInfo{
{
Identifier: "monthly",
StartTime: time.Time{},
Duration: time.Hour * 24 * 31,
CurrentEpoch: 0,
CurrentEpochStartHeight: s.ctx.BlockHeight(),
CurrentEpochStartHeight: suite.ctx.BlockHeight(),
CurrentEpochStartTime: time.Time{},
EpochCountingStarted: false,
},
@@ -132,71 +132,71 @@ func (s *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {

tc.fn()

s.Require().Equal(epochInfo.Identifier, "monthly")
s.Require().Equal(epochInfo.StartTime.UTC().String(), tc.expInitialEpochStartTime.UTC().String())
s.Require().Equal(epochInfo.Duration, time.Hour*24*31)
s.Require().Equal(epochInfo.CurrentEpoch, tc.expCurrentEpoch)
s.Require().Equal(epochInfo.CurrentEpochStartHeight, tc.expCurrentEpochStartHeight)
s.Require().Equal(epochInfo.CurrentEpochStartTime.UTC().String(), tc.expCurrentEpochStartTime.UTC().String())
s.Require().Equal(epochInfo.EpochCountingStarted, true)
suite.Require().Equal(epochInfo.Identifier, "monthly")
suite.Require().Equal(epochInfo.StartTime.UTC().String(), tc.expInitialEpochStartTime.UTC().String())
suite.Require().Equal(epochInfo.Duration, time.Hour*24*31)
suite.Require().Equal(epochInfo.CurrentEpoch, tc.expCurrentEpoch)
suite.Require().Equal(epochInfo.CurrentEpochStartHeight, tc.expCurrentEpochStartHeight)
suite.Require().Equal(epochInfo.CurrentEpochStartTime.UTC().String(), tc.expCurrentEpochStartTime.UTC().String())
suite.Require().Equal(epochInfo.EpochCountingStarted, true)
})
}
}

func (s *KeeperTestSuite) TestEpochStartingOneMonthAfterInitGenesis() {
func (suite *KeeperTestSuite) TestEpochStartingOneMonthAfterInitGenesis() {
// On init genesis, default epochs information is set
// To check init genesis again, should make it fresh status
epochInfos := s.app.EpochsKeeper.AllEpochInfos(s.ctx)
epochInfos := suite.app.EpochsKeeper.AllEpochInfos(suite.ctx)
for _, epochInfo := range epochInfos {
s.app.EpochsKeeper.DeleteEpochInfo(s.ctx, epochInfo.Identifier)
suite.app.EpochsKeeper.DeleteEpochInfo(suite.ctx, epochInfo.Identifier)
}

now := time.Now()
week := time.Hour * 24 * 7
month := time.Hour * 24 * 30
initialBlockHeight := int64(1)
s.ctx = s.ctx.WithBlockHeight(initialBlockHeight).WithBlockTime(now)
suite.ctx = suite.ctx.WithBlockHeight(initialBlockHeight).WithBlockTime(now)

epochs.InitGenesis(s.ctx, s.app.EpochsKeeper, types.GenesisState{
epochs.InitGenesis(suite.ctx, suite.app.EpochsKeeper, types.GenesisState{
Epochs: []types.EpochInfo{
{
Identifier: "monthly",
StartTime: now.Add(month),
Duration: time.Hour * 24 * 30,
CurrentEpoch: 0,
CurrentEpochStartHeight: s.ctx.BlockHeight(),
CurrentEpochStartHeight: suite.ctx.BlockHeight(),
CurrentEpochStartTime: time.Time{},
EpochCountingStarted: false,
},
},
})

// epoch not started yet
epochInfo := s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
s.Require().Equal(epochInfo.CurrentEpoch, int64(0))
s.Require().Equal(epochInfo.CurrentEpochStartHeight, initialBlockHeight)
s.Require().Equal(epochInfo.CurrentEpochStartTime, time.Time{})
s.Require().Equal(epochInfo.EpochCountingStarted, false)
epochInfo := suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
suite.Require().Equal(epochInfo.CurrentEpoch, int64(0))
suite.Require().Equal(epochInfo.CurrentEpochStartHeight, initialBlockHeight)
suite.Require().Equal(epochInfo.CurrentEpochStartTime, time.Time{})
suite.Require().Equal(epochInfo.EpochCountingStarted, false)

// after 1 week
s.ctx = s.ctx.WithBlockHeight(2).WithBlockTime(now.Add(week))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
suite.ctx = suite.ctx.WithBlockHeight(2).WithBlockTime(now.Add(week))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)

// epoch not started yet
epochInfo = s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
s.Require().Equal(epochInfo.CurrentEpoch, int64(0))
s.Require().Equal(epochInfo.CurrentEpochStartHeight, initialBlockHeight)
s.Require().Equal(epochInfo.CurrentEpochStartTime, time.Time{})
s.Require().Equal(epochInfo.EpochCountingStarted, false)
epochInfo = suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
suite.Require().Equal(epochInfo.CurrentEpoch, int64(0))
suite.Require().Equal(epochInfo.CurrentEpochStartHeight, initialBlockHeight)
suite.Require().Equal(epochInfo.CurrentEpochStartTime, time.Time{})
suite.Require().Equal(epochInfo.EpochCountingStarted, false)

// after 1 month
s.ctx = s.ctx.WithBlockHeight(3).WithBlockTime(now.Add(month))
s.app.EpochsKeeper.BeginBlocker(s.ctx)
suite.ctx = suite.ctx.WithBlockHeight(3).WithBlockTime(now.Add(month))
suite.app.EpochsKeeper.BeginBlocker(suite.ctx)

// epoch started
epochInfo = s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
s.Require().Equal(epochInfo.CurrentEpoch, int64(1))
s.Require().Equal(epochInfo.CurrentEpochStartHeight, s.ctx.BlockHeight())
s.Require().Equal(epochInfo.CurrentEpochStartTime.UTC().String(), now.Add(month).UTC().String())
s.Require().Equal(epochInfo.EpochCountingStarted, true)
epochInfo = suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
suite.Require().Equal(epochInfo.CurrentEpoch, int64(1))
suite.Require().Equal(epochInfo.CurrentEpochStartHeight, suite.ctx.BlockHeight())
suite.Require().Equal(epochInfo.CurrentEpochStartTime.UTC().String(), now.Add(month).UTC().String())
suite.Require().Equal(epochInfo.EpochCountingStarted, true)
}
22 changes: 11 additions & 11 deletions x/epochs/keeper/epoch_test.go
Original file line number Diff line number Diff line change
@@ -6,8 +6,8 @@ import (
"github.com/quicksilver-zone/quicksilver/x/epochs/types"
)

func (s *KeeperTestSuite) TestEpochLifeCycle() {
s.SetupTest()
func (suite *KeeperTestSuite) TestEpochLifeCycle() {
suite.SetupTest()

epochInfo := types.EpochInfo{
Identifier: "monthly",
@@ -17,14 +17,14 @@ func (s *KeeperTestSuite) TestEpochLifeCycle() {
CurrentEpochStartTime: time.Time{},
EpochCountingStarted: false,
}
s.app.EpochsKeeper.SetEpochInfo(s.ctx, epochInfo)
epochInfoSaved := s.app.EpochsKeeper.GetEpochInfo(s.ctx, "monthly")
s.Require().Equal(epochInfo, epochInfoSaved)
suite.app.EpochsKeeper.SetEpochInfo(suite.ctx, epochInfo)
epochInfoSaved := suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, "monthly")
suite.Require().Equal(epochInfo, epochInfoSaved)

allEpochs := s.app.EpochsKeeper.AllEpochInfos(s.ctx)
s.Require().Len(allEpochs, 4)
s.Require().Equal(allEpochs[0].Identifier, "day") // alphabetical order
s.Require().Equal(allEpochs[1].Identifier, "epoch")
s.Require().Equal(allEpochs[2].Identifier, "monthly")
s.Require().Equal(allEpochs[3].Identifier, "week")
allEpochs := suite.app.EpochsKeeper.AllEpochInfos(suite.ctx)
suite.Require().Len(allEpochs, 4)
suite.Require().Equal(allEpochs[0].Identifier, "day") // alphabetical order
suite.Require().Equal(allEpochs[1].Identifier, "epoch")
suite.Require().Equal(allEpochs[2].Identifier, "monthly")
suite.Require().Equal(allEpochs[3].Identifier, "week")
}
48 changes: 24 additions & 24 deletions x/epochs/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
@@ -7,34 +7,34 @@ import (
"github.com/quicksilver-zone/quicksilver/x/epochs/types"
)

func (s *KeeperTestSuite) TestQueryEpochInfos() {
s.SetupTest()
queryClient := s.queryClient
func (suite *KeeperTestSuite) TestQueryEpochInfos() {
suite.SetupTest()
queryClient := suite.queryClient

chainStartTime := s.ctx.BlockTime()
chainStartTime := suite.ctx.BlockTime()

// Invalid param
epochInfosResponse, err := queryClient.EpochInfos(gocontext.Background(), &types.QueryEpochsInfoRequest{})
s.Require().NoError(err)
s.Require().Len(epochInfosResponse.Epochs, 3)
suite.Require().NoError(err)
suite.Require().Len(epochInfosResponse.Epochs, 3)

// check if EpochInfos are correct
s.Require().Equal(epochInfosResponse.Epochs[0].Identifier, "day")
s.Require().Equal(epochInfosResponse.Epochs[0].StartTime, chainStartTime)
s.Require().Equal(epochInfosResponse.Epochs[0].Duration, time.Hour*24)
s.Require().Equal(epochInfosResponse.Epochs[0].CurrentEpoch, int64(0))
s.Require().Equal(epochInfosResponse.Epochs[0].CurrentEpochStartTime, chainStartTime)
s.Require().Equal(epochInfosResponse.Epochs[0].EpochCountingStarted, false)
s.Require().Equal(epochInfosResponse.Epochs[1].Identifier, "epoch")
s.Require().Equal(epochInfosResponse.Epochs[1].StartTime, chainStartTime)
s.Require().Equal(epochInfosResponse.Epochs[1].Duration, time.Second*240)
s.Require().Equal(epochInfosResponse.Epochs[1].CurrentEpoch, int64(0))
s.Require().Equal(epochInfosResponse.Epochs[1].CurrentEpochStartTime, chainStartTime)
s.Require().Equal(epochInfosResponse.Epochs[1].EpochCountingStarted, false)
s.Require().Equal(epochInfosResponse.Epochs[2].Identifier, "week")
s.Require().Equal(epochInfosResponse.Epochs[2].StartTime, chainStartTime)
s.Require().Equal(epochInfosResponse.Epochs[2].Duration, time.Hour*24*7)
s.Require().Equal(epochInfosResponse.Epochs[2].CurrentEpoch, int64(0))
s.Require().Equal(epochInfosResponse.Epochs[2].CurrentEpochStartTime, chainStartTime)
s.Require().Equal(epochInfosResponse.Epochs[2].EpochCountingStarted, false)
suite.Require().Equal(epochInfosResponse.Epochs[0].Identifier, "day")
suite.Require().Equal(epochInfosResponse.Epochs[0].StartTime, chainStartTime)
suite.Require().Equal(epochInfosResponse.Epochs[0].Duration, time.Hour*24)
suite.Require().Equal(epochInfosResponse.Epochs[0].CurrentEpoch, int64(0))
suite.Require().Equal(epochInfosResponse.Epochs[0].CurrentEpochStartTime, chainStartTime)
suite.Require().Equal(epochInfosResponse.Epochs[0].EpochCountingStarted, false)
suite.Require().Equal(epochInfosResponse.Epochs[1].Identifier, "epoch")
suite.Require().Equal(epochInfosResponse.Epochs[1].StartTime, chainStartTime)
suite.Require().Equal(epochInfosResponse.Epochs[1].Duration, time.Second*240)
suite.Require().Equal(epochInfosResponse.Epochs[1].CurrentEpoch, int64(0))
suite.Require().Equal(epochInfosResponse.Epochs[1].CurrentEpochStartTime, chainStartTime)
suite.Require().Equal(epochInfosResponse.Epochs[1].EpochCountingStarted, false)
suite.Require().Equal(epochInfosResponse.Epochs[2].Identifier, "week")
suite.Require().Equal(epochInfosResponse.Epochs[2].StartTime, chainStartTime)
suite.Require().Equal(epochInfosResponse.Epochs[2].Duration, time.Hour*24*7)
suite.Require().Equal(epochInfosResponse.Epochs[2].CurrentEpoch, int64(0))
suite.Require().Equal(epochInfosResponse.Epochs[2].CurrentEpochStartTime, chainStartTime)
suite.Require().Equal(epochInfosResponse.Epochs[2].EpochCountingStarted, false)
}
16 changes: 8 additions & 8 deletions x/epochs/keeper/keeper_test.go
Original file line number Diff line number Diff line change
@@ -23,21 +23,21 @@ type KeeperTestSuite struct {

// Test helpers.

func (s *KeeperTestSuite) DoSetupTest(t *testing.T) {
func (suite *KeeperTestSuite) DoSetupTest(t *testing.T) {
t.Helper()

checkTx := false
s.app = app.Setup(t, checkTx)
suite.app = app.Setup(t, checkTx)

s.ctx = s.app.BaseApp.NewContext(false, tmproto.Header{})
suite.ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{})

queryHelper := baseapp.NewQueryServerTestHelper(s.ctx, s.app.InterfaceRegistry())
types.RegisterQueryServer(queryHelper, &s.app.EpochsKeeper)
s.queryClient = types.NewQueryClient(queryHelper)
queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, suite.app.InterfaceRegistry())
types.RegisterQueryServer(queryHelper, &suite.app.EpochsKeeper)
suite.queryClient = types.NewQueryClient(queryHelper)
}

func (s *KeeperTestSuite) SetupTest() {
s.DoSetupTest(s.T())
func (suite *KeeperTestSuite) SetupTest() {
suite.DoSetupTest(suite.T())
}

func TestKeeperTestSuite(t *testing.T) {
38 changes: 19 additions & 19 deletions x/interchainquery/keeper/abci_test.go
Original file line number Diff line number Diff line change
@@ -7,21 +7,21 @@ import (
"github.com/quicksilver-zone/quicksilver/x/interchainquery/keeper"
)

func (s *KeeperTestSuite) TestEndBlocker() {
func (suite *KeeperTestSuite) TestEndBlocker() {
qvr := stakingtypes.QueryValidatorsResponse{
Validators: s.GetSimApp(s.chainB).StakingKeeper.GetBondedValidatorsByPower(s.chainB.GetContext()),
Validators: suite.GetSimApp(suite.chainB).StakingKeeper.GetBondedValidatorsByPower(suite.chainB.GetContext()),
}

bondedQuery := stakingtypes.QueryValidatorsRequest{Status: stakingtypes.BondStatusBonded}
bz, err := bondedQuery.Marshal()
s.NoError(err)
suite.NoError(err)

id := keeper.GenerateQueryHash(s.path.EndpointB.ConnectionID, s.chainB.ChainID, "cosmos.staking.v1beta1.Query/Validators", bz, "")
id := keeper.GenerateQueryHash(suite.path.EndpointB.ConnectionID, suite.chainB.ChainID, "cosmos.staking.v1beta1.Query/Validators", bz, "")

query := s.GetSimApp(s.chainA).InterchainQueryKeeper.NewQuery(
query := suite.GetSimApp(suite.chainA).InterchainQueryKeeper.NewQuery(
"",
s.path.EndpointB.ConnectionID,
s.chainB.ChainID,
suite.path.EndpointB.ConnectionID,
suite.chainB.ChainID,
"cosmos.staking.v1beta1.Query/Validators",
bz,
sdk.NewInt(200),
@@ -30,26 +30,26 @@ func (s *KeeperTestSuite) TestEndBlocker() {
)

// set the query
s.GetSimApp(s.chainA).InterchainQueryKeeper.SetQuery(s.chainA.GetContext(), *query)
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.SetQuery(suite.chainA.GetContext(), *query)

// call end blocker
s.GetSimApp(s.chainA).InterchainQueryKeeper.EndBlocker(s.chainA.GetContext())
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.EndBlocker(suite.chainA.GetContext())

err = s.GetSimApp(s.chainA).InterchainQueryKeeper.SetDatapointForID(
s.chainA.GetContext(),
err = suite.GetSimApp(suite.chainA).InterchainQueryKeeper.SetDatapointForID(
suite.chainA.GetContext(),
id,
s.GetSimApp(s.chainB).AppCodec().MustMarshalJSON(&qvr),
sdk.NewInt(s.chainB.CurrentHeader.Height),
suite.GetSimApp(suite.chainB).AppCodec().MustMarshalJSON(&qvr),
sdk.NewInt(suite.chainB.CurrentHeader.Height),
)
s.NoError(err)
suite.NoError(err)

dataPoint, err := s.GetSimApp(s.chainA).InterchainQueryKeeper.GetDatapointForID(s.chainA.GetContext(), id)
s.NoError(err)
s.NotNil(dataPoint)
dataPoint, err := suite.GetSimApp(suite.chainA).InterchainQueryKeeper.GetDatapointForID(suite.chainA.GetContext(), id)
suite.NoError(err)
suite.NotNil(dataPoint)

// set the query
s.GetSimApp(s.chainA).InterchainQueryKeeper.DeleteQuery(s.chainA.GetContext(), id)
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.DeleteQuery(suite.chainA.GetContext(), id)

// call end blocker
s.GetSimApp(s.chainA).InterchainQueryKeeper.EndBlocker(s.chainA.GetContext())
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.EndBlocker(suite.chainA.GetContext())
}
30 changes: 15 additions & 15 deletions x/interchainquery/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
@@ -7,15 +7,15 @@ import (
icqtypes "github.com/quicksilver-zone/quicksilver/x/interchainquery/types"
)

func (s *KeeperTestSuite) TestQueries() {
func (suite *KeeperTestSuite) TestQueries() {
bondedQuery := stakingtypes.QueryValidatorsRequest{Status: stakingtypes.BondStatusBonded}
bz, err := bondedQuery.Marshal()
s.NoError(err)
suite.NoError(err)

query := s.GetSimApp(s.chainA).InterchainQueryKeeper.NewQuery(
query := suite.GetSimApp(suite.chainA).InterchainQueryKeeper.NewQuery(
"",
s.path.EndpointB.ConnectionID,
s.chainB.ChainID,
suite.path.EndpointB.ConnectionID,
suite.chainB.ChainID,
"cosmos.staking.v1beta1.Query/Validators",
bz,
sdk.NewInt(200),
@@ -24,16 +24,16 @@ func (s *KeeperTestSuite) TestQueries() {
)

// set the query
s.GetSimApp(s.chainA).InterchainQueryKeeper.SetQuery(s.chainA.GetContext(), *query)
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.SetQuery(suite.chainA.GetContext(), *query)

icqsrvSrv := icqtypes.QuerySrvrServer(s.GetSimApp(s.chainA).InterchainQueryKeeper)
icqsrvSrv := icqtypes.QuerySrvrServer(suite.GetSimApp(suite.chainA).InterchainQueryKeeper)

res, err := icqsrvSrv.Queries(sdk.WrapSDKContext(s.chainA.GetContext()), &icqtypes.QueryRequestsRequest{ChainId: s.chainB.ChainID})
s.NoError(err)
s.Len(res.Queries, 1)
s.Equal(s.path.EndpointB.ConnectionID, res.Queries[0].ConnectionId)
s.Equal(s.chainB.ChainID, res.Queries[0].ChainId)
s.Equal("cosmos.staking.v1beta1.Query/Validators", res.Queries[0].QueryType)
s.Equal(sdk.NewInt(200), res.Queries[0].Period)
s.Equal("", res.Queries[0].CallbackId)
res, err := icqsrvSrv.Queries(sdk.WrapSDKContext(suite.chainA.GetContext()), &icqtypes.QueryRequestsRequest{ChainId: suite.chainB.ChainID})
suite.NoError(err)
suite.Len(res.Queries, 1)
suite.Equal(suite.path.EndpointB.ConnectionID, res.Queries[0].ConnectionId)
suite.Equal(suite.chainB.ChainID, res.Queries[0].ChainId)
suite.Equal("cosmos.staking.v1beta1.Query/Validators", res.Queries[0].QueryType)
suite.Equal(sdk.NewInt(200), res.Queries[0].Period)
suite.Equal("", res.Queries[0].CallbackId)
}
130 changes: 65 additions & 65 deletions x/interchainquery/keeper/keeper_test.go
Original file line number Diff line number Diff line change
@@ -36,7 +36,7 @@ type KeeperTestSuite struct {
path *ibctesting.Path
}

func (s *KeeperTestSuite) GetSimApp(chain *ibctesting.TestChain) *app.Quicksilver {
func (suite *KeeperTestSuite) GetSimApp(chain *ibctesting.TestChain) *app.Quicksilver {
quicksilver, ok := chain.App.(*app.Quicksilver)
if !ok {
panic("not quicksilver app")
@@ -45,24 +45,24 @@ func (s *KeeperTestSuite) GetSimApp(chain *ibctesting.TestChain) *app.Quicksilve
return quicksilver
}

func (s *KeeperTestSuite) SetupTest() {
s.coordinator = ibctesting.NewCoordinator(s.T(), 2)
s.chainA = s.coordinator.GetChain(ibctesting.GetChainID(1))
s.chainB = s.coordinator.GetChain(ibctesting.GetChainID(2))
func (suite *KeeperTestSuite) SetupTest() {
suite.coordinator = ibctesting.NewCoordinator(suite.T(), 2)
suite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(1))
suite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(2))

s.path = newSimAppPath(s.chainA, s.chainB)
s.coordinator.SetupConnections(s.path)
suite.path = newSimAppPath(suite.chainA, suite.chainB)
suite.coordinator.SetupConnections(suite.path)
}

func (s *KeeperTestSuite) TestMakeRequest() {
func (suite *KeeperTestSuite) TestMakeRequest() {
bondedQuery := stakingtypes.QueryValidatorsRequest{Status: stakingtypes.BondStatusBonded}
bz, err := bondedQuery.Marshal()
s.NoError(err)
suite.NoError(err)

s.GetSimApp(s.chainA).InterchainQueryKeeper.MakeRequest(
s.chainA.GetContext(),
s.path.EndpointB.ConnectionID,
s.chainB.ChainID,
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.MakeRequest(
suite.chainA.GetContext(),
suite.path.EndpointB.ConnectionID,
suite.chainB.ChainID,
"cosmos.staking.v1beta1.Query/Validators",
bz,
sdk.NewInt(200),
@@ -71,19 +71,19 @@ func (s *KeeperTestSuite) TestMakeRequest() {
0,
)

id := keeper.GenerateQueryHash(s.path.EndpointB.ConnectionID, s.chainB.ChainID, "cosmos.staking.v1beta1.Query/Validators", bz, "")
query, found := s.GetSimApp(s.chainA).InterchainQueryKeeper.GetQuery(s.chainA.GetContext(), id)
s.True(found)
s.Equal(s.path.EndpointB.ConnectionID, query.ConnectionId)
s.Equal(s.chainB.ChainID, query.ChainId)
s.Equal("cosmos.staking.v1beta1.Query/Validators", query.QueryType)
s.Equal(sdk.NewInt(200), query.Period)
s.Equal("", query.CallbackId)

s.GetSimApp(s.chainA).InterchainQueryKeeper.MakeRequest(
s.chainA.GetContext(),
s.path.EndpointB.ConnectionID,
s.chainB.ChainID,
id := keeper.GenerateQueryHash(suite.path.EndpointB.ConnectionID, suite.chainB.ChainID, "cosmos.staking.v1beta1.Query/Validators", bz, "")
query, found := suite.GetSimApp(suite.chainA).InterchainQueryKeeper.GetQuery(suite.chainA.GetContext(), id)
suite.True(found)
suite.Equal(suite.path.EndpointB.ConnectionID, query.ConnectionId)
suite.Equal(suite.chainB.ChainID, query.ChainId)
suite.Equal("cosmos.staking.v1beta1.Query/Validators", query.QueryType)
suite.Equal(sdk.NewInt(200), query.Period)
suite.Equal("", query.CallbackId)

suite.GetSimApp(suite.chainA).InterchainQueryKeeper.MakeRequest(
suite.chainA.GetContext(),
suite.path.EndpointB.ConnectionID,
suite.chainB.ChainID,
"cosmos.staking.v1beta1.Query/Validators",
bz,
sdk.NewInt(200),
@@ -93,13 +93,13 @@ func (s *KeeperTestSuite) TestMakeRequest() {
)
}

func (s *KeeperTestSuite) TestSubmitQueryResponse() {
func (suite *KeeperTestSuite) TestSubmitQueryResponse() {
bondedQuery := stakingtypes.QueryValidatorsRequest{Status: stakingtypes.BondStatusBonded}
bz, err := bondedQuery.Marshal()
s.NoError(err)
suite.NoError(err)

qvr := stakingtypes.QueryValidatorsResponse{
Validators: s.GetSimApp(s.chainB).StakingKeeper.GetBondedValidatorsByPower(s.chainB.GetContext()),
Validators: suite.GetSimApp(suite.chainB).StakingKeeper.GetBondedValidatorsByPower(suite.chainB.GetContext()),
}

tests := []struct {
@@ -108,11 +108,11 @@ func (s *KeeperTestSuite) TestSubmitQueryResponse() {
expectError error
}{
{
s.GetSimApp(s.chainA).InterchainQueryKeeper.
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.
NewQuery(
"",
s.path.EndpointB.ConnectionID,
s.chainB.ChainID,
suite.path.EndpointB.ConnectionID,
suite.chainB.ChainID,
"cosmos.staking.v1beta1.Query/Validators",
bz,
sdk.NewInt(200),
@@ -123,11 +123,11 @@ func (s *KeeperTestSuite) TestSubmitQueryResponse() {
nil,
},
{
s.GetSimApp(s.chainA).InterchainQueryKeeper.
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.
NewQuery(
"",
s.path.EndpointB.ConnectionID,
s.chainB.ChainID,
suite.path.EndpointB.ConnectionID,
suite.chainB.ChainID,
"cosmos.staking.v1beta1.Query/Validators",
bz,
sdk.NewInt(200),
@@ -138,11 +138,11 @@ func (s *KeeperTestSuite) TestSubmitQueryResponse() {
nil,
},
{
s.GetSimApp(s.chainA).InterchainQueryKeeper.
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.
NewQuery(
"",
s.path.EndpointB.ConnectionID,
s.chainB.ChainID,
suite.path.EndpointB.ConnectionID,
suite.chainB.ChainID,
"cosmos.staking.v1beta1.Query/Validators",
bz,
sdk.NewInt(-200),
@@ -153,11 +153,11 @@ func (s *KeeperTestSuite) TestSubmitQueryResponse() {
nil,
},
{
s.GetSimApp(s.chainA).InterchainQueryKeeper.
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.
NewQuery(
"",
s.path.EndpointB.ConnectionID,
s.chainB.ChainID,
suite.path.EndpointB.ConnectionID,
suite.chainB.ChainID,
"cosmos.staking.v1beta1.Query/Validators",
bz,
sdk.NewInt(100),
@@ -172,48 +172,48 @@ func (s *KeeperTestSuite) TestSubmitQueryResponse() {
for _, tc := range tests {
// set the query
if tc.setQuery {
s.GetSimApp(s.chainA).InterchainQueryKeeper.SetQuery(s.chainA.GetContext(), *tc.query)
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.SetQuery(suite.chainA.GetContext(), *tc.query)
}

icqmsgSrv := keeper.NewMsgServerImpl(s.GetSimApp(s.chainA).InterchainQueryKeeper)
icqmsgSrv := keeper.NewMsgServerImpl(suite.GetSimApp(suite.chainA).InterchainQueryKeeper)

qmsg := icqtypes.MsgSubmitQueryResponse{
ChainId: s.chainB.ChainID,
ChainId: suite.chainB.ChainID,
QueryId: keeper.GenerateQueryHash(tc.query.ConnectionId, tc.query.ChainId, tc.query.QueryType, bz, ""),
Result: s.GetSimApp(s.chainB).AppCodec().MustMarshalJSON(&qvr),
Height: s.chainB.CurrentHeader.Height,
Result: suite.GetSimApp(suite.chainB).AppCodec().MustMarshalJSON(&qvr),
Height: suite.chainB.CurrentHeader.Height,
FromAddress: TestOwnerAddress,
}

_, err = icqmsgSrv.SubmitQueryResponse(sdk.WrapSDKContext(s.chainA.GetContext()), &qmsg)
s.Equal(tc.expectError, err)
_, err = icqmsgSrv.SubmitQueryResponse(sdk.WrapSDKContext(suite.chainA.GetContext()), &qmsg)
suite.Equal(tc.expectError, err)
}
}

func (s *KeeperTestSuite) TestDataPoints() {
func (suite *KeeperTestSuite) TestDataPoints() {
bondedQuery := stakingtypes.QueryValidatorsRequest{Status: stakingtypes.BondStatusBonded}
bz, err := bondedQuery.Marshal()
s.NoError(err)
suite.NoError(err)

qvr := stakingtypes.QueryValidatorsResponse{
Validators: s.GetSimApp(s.chainB).StakingKeeper.GetBondedValidatorsByPower(s.chainB.GetContext()),
Validators: suite.GetSimApp(suite.chainB).StakingKeeper.GetBondedValidatorsByPower(suite.chainB.GetContext()),
}

id := keeper.GenerateQueryHash(s.path.EndpointB.ConnectionID, s.chainB.ChainID, "cosmos.staking.v1beta1.Query/Validators", bz, "")
id := keeper.GenerateQueryHash(suite.path.EndpointB.ConnectionID, suite.chainB.ChainID, "cosmos.staking.v1beta1.Query/Validators", bz, "")

err = s.GetSimApp(s.chainA).InterchainQueryKeeper.SetDatapointForID(
s.chainA.GetContext(),
err = suite.GetSimApp(suite.chainA).InterchainQueryKeeper.SetDatapointForID(
suite.chainA.GetContext(),
id,
s.GetSimApp(s.chainB).AppCodec().MustMarshalJSON(&qvr),
sdk.NewInt(s.chainB.CurrentHeader.Height),
suite.GetSimApp(suite.chainB).AppCodec().MustMarshalJSON(&qvr),
sdk.NewInt(suite.chainB.CurrentHeader.Height),
)
s.NoError(err)
suite.NoError(err)

dataPoint, err := s.GetSimApp(s.chainA).InterchainQueryKeeper.GetDatapointForID(s.chainA.GetContext(), id)
s.NoError(err)
s.NotNil(dataPoint)
dataPoint, err := suite.GetSimApp(suite.chainA).InterchainQueryKeeper.GetDatapointForID(suite.chainA.GetContext(), id)
suite.NoError(err)
suite.NotNil(dataPoint)

s.GetSimApp(s.chainA).InterchainQueryKeeper.DeleteDatapoint(s.chainA.GetContext(), id)
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.DeleteDatapoint(suite.chainA.GetContext(), id)
}

func newSimAppPath(chainA, chainB *ibctesting.TestChain) *ibctesting.Path {
@@ -224,11 +224,11 @@ func newSimAppPath(chainA, chainB *ibctesting.TestChain) *ibctesting.Path {
return path
}

func (s *KeeperTestSuite) TestLatestHeight() {
func (suite *KeeperTestSuite) TestLatestHeight() {
height := rand.Uint64()
chainID := "test"

s.GetSimApp(s.chainA).InterchainQueryKeeper.SetLatestHeight(s.chainA.GetContext(), chainID, height)
got := s.GetSimApp(s.chainA).InterchainQueryKeeper.GetLatestHeight(s.chainA.GetContext(), chainID)
s.Require().Equal(height, got)
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.SetLatestHeight(suite.chainA.GetContext(), chainID, height)
got := suite.GetSimApp(suite.chainA).InterchainQueryKeeper.GetLatestHeight(suite.chainA.GetContext(), chainID)
suite.Require().Equal(height, got)
}
42 changes: 21 additions & 21 deletions x/interchainquery/keeper/queries_test.go
Original file line number Diff line number Diff line change
@@ -7,15 +7,15 @@ import (
"github.com/quicksilver-zone/quicksilver/x/interchainquery/keeper"
)

func (s *KeeperTestSuite) TestQuery() {
func (suite *KeeperTestSuite) TestQuery() {
bondedQuery := stakingtypes.QueryValidatorsRequest{Status: stakingtypes.BondStatusBonded}
bz, err := bondedQuery.Marshal()
s.NoError(err)
suite.NoError(err)

query := s.GetSimApp(s.chainA).InterchainQueryKeeper.NewQuery(
query := suite.GetSimApp(suite.chainA).InterchainQueryKeeper.NewQuery(
"",
s.path.EndpointB.ConnectionID,
s.chainB.ChainID,
suite.path.EndpointB.ConnectionID,
suite.chainB.ChainID,
"cosmos.staking.v1beta1.Query/Validators",
bz,
sdk.NewInt(200),
@@ -24,30 +24,30 @@ func (s *KeeperTestSuite) TestQuery() {
)

// set the query
s.GetSimApp(s.chainA).InterchainQueryKeeper.SetQuery(s.chainA.GetContext(), *query)
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.SetQuery(suite.chainA.GetContext(), *query)

// get the stored query
id := keeper.GenerateQueryHash(query.ConnectionId, query.ChainId, query.QueryType, query.Request, "")
getQuery, found := s.GetSimApp(s.chainA).InterchainQueryKeeper.GetQuery(s.chainA.GetContext(), id)
s.True(found)
s.Equal(s.path.EndpointB.ConnectionID, getQuery.ConnectionId)
s.Equal(s.chainB.ChainID, getQuery.ChainId)
s.Equal("cosmos.staking.v1beta1.Query/Validators", getQuery.QueryType)
s.Equal(sdk.NewInt(200), getQuery.Period)
s.Equal(uint64(0), getQuery.Ttl)
s.Equal("", getQuery.CallbackId)
getQuery, found := suite.GetSimApp(suite.chainA).InterchainQueryKeeper.GetQuery(suite.chainA.GetContext(), id)
suite.True(found)
suite.Equal(suite.path.EndpointB.ConnectionID, getQuery.ConnectionId)
suite.Equal(suite.chainB.ChainID, getQuery.ChainId)
suite.Equal("cosmos.staking.v1beta1.Query/Validators", getQuery.QueryType)
suite.Equal(sdk.NewInt(200), getQuery.Period)
suite.Equal(uint64(0), getQuery.Ttl)
suite.Equal("", getQuery.CallbackId)

// get all the queries
queries := s.GetSimApp(s.chainA).InterchainQueryKeeper.AllQueries(s.chainA.GetContext())
s.Len(queries, 1)
queries := suite.GetSimApp(suite.chainA).InterchainQueryKeeper.AllQueries(suite.chainA.GetContext())
suite.Len(queries, 1)

// delete the query
s.GetSimApp(s.chainA).InterchainQueryKeeper.DeleteQuery(s.chainA.GetContext(), id)
suite.GetSimApp(suite.chainA).InterchainQueryKeeper.DeleteQuery(suite.chainA.GetContext(), id)

// get query
_, found = s.GetSimApp(s.chainA).InterchainQueryKeeper.GetQuery(s.chainA.GetContext(), id)
s.False(found)
_, found = suite.GetSimApp(suite.chainA).InterchainQueryKeeper.GetQuery(suite.chainA.GetContext(), id)
suite.False(found)

queries = s.GetSimApp(s.chainA).InterchainQueryKeeper.AllQueries(s.chainA.GetContext())
s.Len(queries, 0)
queries = suite.GetSimApp(suite.chainA).InterchainQueryKeeper.AllQueries(suite.chainA.GetContext())
suite.Len(queries, 0)
}
3 changes: 1 addition & 2 deletions x/interchainstaking/keeper/delegation.go
Original file line number Diff line number Diff line change
@@ -209,8 +209,7 @@ func (k *Keeper) DeterminePlanForDelegation(ctx sdk.Context, zone *types.Zone, a
if err != nil {
return nil, err
}
allocations := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
return allocations, nil
return types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
}

func (k *Keeper) WithdrawDelegationRewardsForResponse(ctx sdk.Context, zone *types.Zone, delegator string, response []byte) error {
159 changes: 115 additions & 44 deletions x/interchainstaking/keeper/delegation_test.go

Large diffs are not rendered by default.

26 changes: 17 additions & 9 deletions x/interchainstaking/keeper/keeper.go
Original file line number Diff line number Diff line change
@@ -603,38 +603,46 @@ func (k *Keeper) GetRatio(ctx sdk.Context, zone *types.Zone, epochRewards sdkmat
return sdk.NewDecFromInt(nativeAssetAmount.Add(epochRewards).Add(nativeAssetUnbondingAmount)).Quo(sdk.NewDecFromInt(qAssetAmount)), false
}

func (k *Keeper) GetAggregateIntentOrDefault(ctx sdk.Context, z *types.Zone) (types.ValidatorIntents, error) {
func (k *Keeper) GetAggregateIntentOrDefault(ctx sdk.Context, zone *types.Zone) (types.ValidatorIntents, error) {
var intents types.ValidatorIntents
var filteredIntents types.ValidatorIntents

if len(z.AggregateIntent) == 0 {
intents = k.DefaultAggregateIntents(ctx, z.ChainId)
if len(zone.AggregateIntent) == 0 {
intents = k.DefaultAggregateIntents(ctx, zone.ChainId)
} else {
intents = z.AggregateIntent
intents = zone.AggregateIntent
}

jailedThreshold := k.EpochsKeeper.GetEpochInfo(ctx, "epoch").Duration * 2

// filter intents here...
// check validators for tombstoned
for _, v := range intents {
valAddrBytes, err := addressutils.ValAddressFromBech32(v.ValoperAddress, z.GetValoperPrefix())
for _, validatorIntent := range intents {
valAddrBytes, err := addressutils.ValAddressFromBech32(validatorIntent.ValoperAddress, zone.GetValoperPrefix())
if err != nil {
return nil, err
}
val, found := k.GetValidator(ctx, z.ChainId, valAddrBytes)
validator, found := k.GetValidator(ctx, zone.ChainId, valAddrBytes)

// this case should not happen as we check the validity of a validator entry when intent is set.
if !found {
continue
}
// we should never let tombstoned validators into the list, even if they are explicitly selected
if val.Tombstoned {
if validator.Tombstoned {
continue
}

// if the validator has been jailed for > two epochs, remove them.
if validator.Jailed && validator.JailedSince.Add(jailedThreshold).Before(ctx.BlockTime()) {
continue
}

// we should never let denylist validators into the list, even if they are explicitly selected
// if in deny list {
// continue
// }
filteredIntents = append(filteredIntents, v)
filteredIntents = append(filteredIntents, validatorIntent)
}

return filteredIntents, nil
2 changes: 1 addition & 1 deletion x/interchainstaking/keeper/keeper_test.go
Original file line number Diff line number Diff line change
@@ -59,7 +59,7 @@ type KeeperTestSuite struct {
path *ibctesting.Path
}

func (*KeeperTestSuite) GetQuicksilverApp(chain *ibctesting.TestChain) *app.Quicksilver {
func (suite *KeeperTestSuite) GetQuicksilverApp(chain *ibctesting.TestChain) *app.Quicksilver {
quicksilver, ok := chain.App.(*app.Quicksilver)
if !ok {
panic("not quicksilver app")
229 changes: 229 additions & 0 deletions x/interchainstaking/types/allocation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
package types_test

import (
"reflect"
"testing"

"github.com/stretchr/testify/require"

sdkmath "cosmossdk.io/math"

sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/quicksilver-zone/quicksilver/x/interchainstaking/types"
)

// Delegation Allocation Tests

// Test with valid inputs and expected outputs
func TestValidInputs(t *testing.T) {
currentAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(100),
"validator2": sdkmath.NewInt(200),
}
currentSum := sdkmath.NewInt(300)
targetAllocations := types.ValidatorIntents{
{ValoperAddress: "validator1", Weight: sdk.NewDecWithPrec(5, 1)},
{ValoperAddress: "validator2", Weight: sdk.NewDecWithPrec(5, 1)},
}
amount := sdk.Coins{sdk.NewCoin("token", sdk.NewInt(1000))}

expectedAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(550),
"validator2": sdkmath.NewInt(450),
}

result, err := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
require.NoError(t, err)

if !reflect.DeepEqual(result, expectedAllocations) {
t.Errorf("Expected allocations %v, but got %v", expectedAllocations, result)
}
}

// Test with minimum input values - fail on zero amount
func TestMinimumInputs(t *testing.T) {
currentAllocations := map[string]sdkmath.Int{}
currentSum := sdkmath.ZeroInt()
targetAllocations := types.ValidatorIntents{}
amount := sdk.Coins{sdk.NewCoin("token", sdkmath.ZeroInt())}

_, err := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
require.Error(t, err)
}

// Test with maximum input values
func TestMaximumInputs(t *testing.T) {
currentAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(1000000000),
"validator2": sdkmath.NewInt(2000000000),
}
currentSum := sdkmath.NewInt(3000000000)
targetAllocations := types.ValidatorIntents{
{ValoperAddress: "validator1", Weight: sdk.NewDecWithPrec(5, 1)},
{ValoperAddress: "validator2", Weight: sdk.NewDecWithPrec(5, 1)},
}
amount := sdk.Coins{sdk.NewCoin("token", sdk.NewInt(10000000000))}

expectedAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(5500000000),
"validator2": sdkmath.NewInt(4500000000),
}

result, err := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
require.NoError(t, err)

if !reflect.DeepEqual(result, expectedAllocations) {
t.Errorf("Expected allocations %v, but got %v", expectedAllocations, result)
}
}

// Test with empty currentAllocations
func TestEmptyCurrentAllocations(t *testing.T) {
currentAllocations := map[string]sdkmath.Int{}
currentSum := sdkmath.ZeroInt()
targetAllocations := types.ValidatorIntents{
{ValoperAddress: "validator1", Weight: sdk.NewDecWithPrec(5, 1)},
{ValoperAddress: "validator2", Weight: sdk.NewDecWithPrec(5, 1)},
}
amount := sdk.Coins{sdk.NewCoin("token", sdk.NewInt(1000))}

expectedAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(500),
"validator2": sdkmath.NewInt(500),
}

result, err := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
require.NoError(t, err)

if !reflect.DeepEqual(result, expectedAllocations) {
t.Errorf("Expected allocations %v, but got %v", expectedAllocations, result)
}
}

// Test with empty targetAllocations - error on empty target list.
func TestEmptyTargetAllocations(t *testing.T) {
currentAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(100),
"validator2": sdkmath.NewInt(200),
}
currentSum := sdkmath.NewInt(300)
targetAllocations := types.ValidatorIntents{}
amount := sdk.Coins{sdk.NewCoin("token", sdk.NewInt(1000))}

_, err := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
require.Error(t, err)
}

// Test non-equal targetAllocations
func TestNonEqualTargetAllocations(t *testing.T) {
currentAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(100),
"validator2": sdkmath.NewInt(200),
}
currentSum := sdkmath.NewInt(300)
targetAllocations := types.ValidatorIntents{
{ValoperAddress: "validator1", Weight: sdk.NewDecWithPrec(3, 1)},
{ValoperAddress: "validator2", Weight: sdk.NewDecWithPrec(7, 1)},
}
amount := sdk.Coins{sdk.NewCoin("token", sdk.NewInt(1000))}

expectedAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(290),
"validator2": sdkmath.NewInt(710),
}

result, err := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
require.NoError(t, err)

if !reflect.DeepEqual(result, expectedAllocations) {
t.Errorf("Expected allocations %v, but got %v", expectedAllocations, result)
}
}

// Test with some validators having zero weight
func TestValidInputsWithZeroWeight(t *testing.T) {
currentAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(100),
"validator2": sdkmath.NewInt(200),
"validator3": sdkmath.NewInt(0),
}
currentSum := sdkmath.NewInt(300)
targetAllocations := types.ValidatorIntents{
{ValoperAddress: "validator1", Weight: sdk.NewDecWithPrec(5, 1)},
{ValoperAddress: "validator2", Weight: sdk.NewDecWithPrec(5, 1)},
{ValoperAddress: "validator3", Weight: sdk.NewDec(0)},
}
amount := sdk.Coins{sdk.NewCoin("token", sdk.NewInt(1000))}

expectedAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(550),
"validator2": sdkmath.NewInt(450),
}

result, err := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
require.NoError(t, err)

if !reflect.DeepEqual(result, expectedAllocations) {
t.Errorf("Expected allocations %v, but got %v", expectedAllocations, result)
}
}

// Test with targetAllocations having more validators than currentAllocations
func TestTargetAllocationsMoreValidators(t *testing.T) {
currentAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(100),
"validator2": sdkmath.NewInt(200),
}
currentSum := sdkmath.NewInt(300)
targetAllocations := types.ValidatorIntents{
{ValoperAddress: "validator1", Weight: sdk.NewDecWithPrec(5, 1)},
{ValoperAddress: "validator2", Weight: sdk.NewDecWithPrec(5, 1)},
{ValoperAddress: "validator3", Weight: sdk.NewDecWithPrec(5, 1)},
{ValoperAddress: "validator4", Weight: sdk.NewDecWithPrec(5, 1)},
}
amount := sdk.Coins{sdk.NewCoin("token", sdk.NewInt(1000))}

expectedAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(241),
"validator2": sdkmath.NewInt(195),
"validator3": sdkmath.NewInt(282),
"validator4": sdkmath.NewInt(282),
}

result, err := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
require.NoError(t, err)

if !reflect.DeepEqual(result, expectedAllocations) {
t.Errorf("Expected allocations %v, but got %v", expectedAllocations, result)
}
}

// Test with currentAllocations having more validators than targetAllocations
func TestCurrentAllocationsMoreValidators(t *testing.T) {
currentAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(100),
"validator2": sdkmath.NewInt(200),
"validator3": sdkmath.NewInt(300),
}
currentSum := sdkmath.NewInt(600)
targetAllocations := types.ValidatorIntents{
{ValoperAddress: "validator1", Weight: sdk.NewDecWithPrec(3, 1)},
{ValoperAddress: "validator2", Weight: sdk.NewDecWithPrec(4, 1)},
}
amount := sdk.Coins{sdk.NewCoin("token", sdk.NewInt(1000))}

expectedAllocations := map[string]sdkmath.Int{
"validator1": sdkmath.NewInt(489),
"validator2": sdkmath.NewInt(511),
}

result, err := types.DetermineAllocationsForDelegation(currentAllocations, currentSum, targetAllocations, amount)
require.NoError(t, err)

if !reflect.DeepEqual(result, expectedAllocations) {
t.Errorf("Expected allocations %v, but got %v", expectedAllocations, result)
}
}

// Deltas tests.
40 changes: 18 additions & 22 deletions x/interchainstaking/types/delegation.go
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@ package types

import (
"errors"
fmt "fmt"
"sort"

sdkmath "cosmossdk.io/math"
@@ -118,25 +119,16 @@ func (vi ValidatorIntents) Normalize() ValidatorIntents {
return out.Sort()
}

func DetermineAllocationsForDelegation(currentAllocations map[string]sdkmath.Int, currentSum sdkmath.Int, targetAllocations ValidatorIntents, amount sdk.Coins) map[string]sdkmath.Int {
input := amount[0].Amount
deltas, sources := CalculateAllocationDeltas(currentAllocations, map[string]bool{}, currentSum, targetAllocations)
// take targets and sources, and flip that shit.
// sources -> negate -> join -> sort.
largestSource := sources.MaxDelta()

// negate all values in sources.
sources.Negate()
deltas = append(deltas, sources...)

sum := sdk.ZeroInt()

// raise all deltas such that the minimum value is zero.
for idx := range deltas {
deltas[idx].Amount = deltas[idx].Amount.Add(largestSource)
// sum here instead of calling Sum() later to save looping over slice again.
sum = sum.Add(deltas[idx].Amount)
func DetermineAllocationsForDelegation(currentAllocations map[string]sdkmath.Int, currentSum sdkmath.Int, targetAllocations ValidatorIntents, amount sdk.Coins) (map[string]sdkmath.Int, error) {
if amount.IsZero() {
return make(map[string]sdkmath.Int, 0), fmt.Errorf("unable to delegate zero amount")
}
if len(targetAllocations) == 0 {
return make(map[string]sdkmath.Int, 0), fmt.Errorf("unable to process nil delegation targets")
}
input := amount[0].Amount
deltas, _ := CalculateAllocationDeltas(currentAllocations, map[string]bool{}, currentSum.Add(amount[0].Amount), targetAllocations)
sum := deltas.Sum()

// unequalSplit is the portion of input that should be distributed in attempt to make targets == 0
unequalSplit := sdk.MinInt(sum, input)
@@ -169,11 +161,15 @@ func DetermineAllocationsForDelegation(currentAllocations map[string]sdkmath.Int
outSum := sdk.ZeroInt()
outWeights := make(map[string]sdkmath.Int)
for _, delta := range deltas {
outWeights[delta.ValoperAddress] = delta.Amount
outSum = outSum.Add(delta.Amount)
if !delta.Amount.IsZero() {
outWeights[delta.ValoperAddress] = delta.Amount
outSum = outSum.Add(delta.Amount)
}
}
dust := input.Sub(outSum)
outWeights[deltas[0].ValoperAddress] = outWeights[deltas[0].ValoperAddress].Add(dust)
if !dust.IsZero() {
outWeights[deltas[0].ValoperAddress] = outWeights[deltas[0].ValoperAddress].Add(dust)
}

return outWeights
return outWeights, nil
}
25 changes: 12 additions & 13 deletions x/interchainstaking/types/delegation_test.go
Original file line number Diff line number Diff line change
@@ -133,9 +133,8 @@ func TestDetermineAllocationsForDelegation(t *testing.T) {
},
inAmount: sdk.NewCoins(sdk.NewCoin("uqck", sdk.NewInt(50000))),
expected: map[string]sdkmath.Int{
vals[0]: sdk.ZeroInt(),
vals[1]: sdk.NewInt(33182),
vals[2]: sdk.NewInt(16818),
vals[1]: sdk.NewInt(47000),
vals[2]: sdk.NewInt(3000),
},
},
{
@@ -153,18 +152,17 @@ func TestDetermineAllocationsForDelegation(t *testing.T) {
},
inAmount: sdk.NewCoins(sdk.NewCoin("uqck", sdk.NewInt(20))),
expected: map[string]sdkmath.Int{
vals[3]: sdk.NewInt(11),
vals[2]: sdk.ZeroInt(),
vals[1]: sdk.NewInt(6),
vals[0]: sdk.NewInt(3),
vals[3]: sdk.NewInt(7),
vals[1]: sdk.NewInt(5),
vals[0]: sdk.NewInt(8),
},
},
{
current: map[string]sdkmath.Int{
vals[0]: sdk.NewInt(52),
vals[1]: sdk.NewInt(24),
vals[2]: sdk.NewInt(20),
vals[3]: sdk.NewInt(4),
vals[3]: sdk.NewInt(3),
},
target: types.ValidatorIntents{
{ValoperAddress: vals[0], Weight: sdk.NewDecWithPrec(50, 2)},
@@ -174,10 +172,10 @@ func TestDetermineAllocationsForDelegation(t *testing.T) {
},
inAmount: sdk.NewCoins(sdk.NewCoin("uqck", sdk.NewInt(50))),
expected: map[string]sdkmath.Int{
vals[0]: sdk.NewInt(18),
vals[1]: sdk.NewInt(14),
vals[2]: sdk.NewInt(4),
vals[3]: sdk.NewInt(14),
vals[0]: sdk.NewInt(27),
vals[1]: sdk.NewInt(12),
vals[2]: sdk.NewInt(1),
vals[3]: sdk.NewInt(10),
},
},
}
@@ -188,7 +186,8 @@ func TestDetermineAllocationsForDelegation(t *testing.T) {
for _, amount := range val.current {
sum = sum.Add(amount)
}
allocations := types.DetermineAllocationsForDelegation(val.current, sum, val.target, val.inAmount)
allocations, err := types.DetermineAllocationsForDelegation(val.current, sum, val.target, val.inAmount)
require.NoError(t, err)
require.Equal(t, len(val.expected), len(allocations))
for valoper := range val.expected {
ex, ok := val.expected[valoper]
216 changes: 108 additions & 108 deletions x/tokenfactory/keeper/admins_test.go

Large diffs are not rendered by default.

94 changes: 47 additions & 47 deletions x/tokenfactory/keeper/createdenom_test.go
Original file line number Diff line number Diff line change
@@ -8,59 +8,59 @@ import (
"github.com/quicksilver-zone/quicksilver/x/tokenfactory/types"
)

func (s *KeeperTestSuite) TestMsgCreateDenom() {
func (suite *KeeperTestSuite) TestMsgCreateDenom() {
var (
tokenFactoryKeeper = s.App.TokenFactoryKeeper
bankKeeper = s.App.BankKeeper
denomCreationFee = tokenFactoryKeeper.GetParams(s.Ctx).DenomCreationFee
tokenFactoryKeeper = suite.App.TokenFactoryKeeper
bankKeeper = suite.App.BankKeeper
denomCreationFee = tokenFactoryKeeper.GetParams(suite.Ctx).DenomCreationFee
)

// Get balance of acc 0 before creating a denom
preCreateBalance := bankKeeper.GetBalance(s.Ctx, s.TestAccs[0], denomCreationFee[0].Denom)
preCreateBalance := bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], denomCreationFee[0].Denom)

// Creating a denom should work
res, err := s.msgServer.CreateDenom(sdk.WrapSDKContext(s.Ctx), types.NewMsgCreateDenom(s.TestAccs[0].String(), "bitcoin"))
s.Require().NoError(err)
s.Require().NotEmpty(res.GetNewTokenDenom())
res, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin"))
suite.Require().NoError(err)
suite.Require().NotEmpty(res.GetNewTokenDenom())

// Make sure that the admin is set correctly
queryRes, err := s.queryClient.DenomAuthorityMetadata(s.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{
queryRes, err := suite.queryClient.DenomAuthorityMetadata(suite.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{
Denom: res.GetNewTokenDenom(),
})
s.Require().NoError(err)
s.Require().Equal(s.TestAccs[0].String(), queryRes.AuthorityMetadata.Admin)
suite.Require().NoError(err)
suite.Require().Equal(suite.TestAccs[0].String(), queryRes.AuthorityMetadata.Admin)

// Make sure that creation fee was deducted
postCreateBalance := bankKeeper.GetBalance(s.Ctx, s.TestAccs[0], tokenFactoryKeeper.GetParams(s.Ctx).DenomCreationFee[0].Denom)
s.Require().True(preCreateBalance.Sub(postCreateBalance).IsEqual(denomCreationFee[0]))
postCreateBalance := bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], tokenFactoryKeeper.GetParams(suite.Ctx).DenomCreationFee[0].Denom)
suite.Require().True(preCreateBalance.Sub(postCreateBalance).IsEqual(denomCreationFee[0]))

// Make sure that a second version of the same denom can't be recreated
_, err = s.msgServer.CreateDenom(sdk.WrapSDKContext(s.Ctx), types.NewMsgCreateDenom(s.TestAccs[0].String(), "bitcoin"))
s.Require().Error(err)
_, err = suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin"))
suite.Require().Error(err)

// Creating a second denom should work
res, err = s.msgServer.CreateDenom(sdk.WrapSDKContext(s.Ctx), types.NewMsgCreateDenom(s.TestAccs[0].String(), "litecoin"))
s.Require().NoError(err)
s.Require().NotEmpty(res.GetNewTokenDenom())
res, err = suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "litecoin"))
suite.Require().NoError(err)
suite.Require().NotEmpty(res.GetNewTokenDenom())

// Try querying all the denoms created by suite.TestAccs[0]
queryRes2, err := s.queryClient.DenomsFromCreator(s.Ctx.Context(), &types.QueryDenomsFromCreatorRequest{
Creator: s.TestAccs[0].String(),
queryRes2, err := suite.queryClient.DenomsFromCreator(suite.Ctx.Context(), &types.QueryDenomsFromCreatorRequest{
Creator: suite.TestAccs[0].String(),
})
s.Require().NoError(err)
s.Require().Len(queryRes2.Denoms, 2)
suite.Require().NoError(err)
suite.Require().Len(queryRes2.Denoms, 2)

// Make sure that a second account can create a denom with the same subdenom
res, err = s.msgServer.CreateDenom(sdk.WrapSDKContext(s.Ctx), types.NewMsgCreateDenom(s.TestAccs[1].String(), "bitcoin"))
s.Require().NoError(err)
s.Require().NotEmpty(res.GetNewTokenDenom())
res, err = suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[1].String(), "bitcoin"))
suite.Require().NoError(err)
suite.Require().NotEmpty(res.GetNewTokenDenom())

// Make sure that an address with a "/" in it can't create denoms
_, err = s.msgServer.CreateDenom(sdk.WrapSDKContext(s.Ctx), types.NewMsgCreateDenom("quick.eth/creator", "bitcoin"))
s.Require().Error(err)
_, err = suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom("quick.eth/creator", "bitcoin"))
suite.Require().Error(err)
}

func (s *KeeperTestSuite) TestCreateDenom() {
func (suite *KeeperTestSuite) TestCreateDenom() {
var (
primaryDenom = types.DefaultParams().DenomCreationFee[0].Denom
secondaryDenom = SecondaryDenom
@@ -87,8 +87,8 @@ func (s *KeeperTestSuite) TestCreateDenom() {
desc: "subdenom and creator pair already exists",
denomCreationFee: defaultDenomCreationFee,
setup: func() {
_, err := s.msgServer.CreateDenom(sdk.WrapSDKContext(s.Ctx), types.NewMsgCreateDenom(s.TestAccs[0].String(), "bitcoin"))
s.Require().NoError(err)
_, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin"))
suite.Require().NoError(err)
},
subdenom: "bitcoin",
valid: false,
@@ -124,38 +124,38 @@ func (s *KeeperTestSuite) TestCreateDenom() {
valid: false,
},
} {
s.SetupTest()
s.Run(fmt.Sprintf("Case %s", tc.desc), func() {
suite.SetupTest()
suite.Run(fmt.Sprintf("Case %s", tc.desc), func() {
if tc.setup != nil {
tc.setup()
}
tokenFactoryKeeper := s.App.TokenFactoryKeeper
bankKeeper := s.App.BankKeeper
tokenFactoryKeeper := suite.App.TokenFactoryKeeper
bankKeeper := suite.App.BankKeeper
// Set denom creation fee in params
tokenFactoryKeeper.SetParams(s.Ctx, tc.denomCreationFee)
denomCreationFee := tokenFactoryKeeper.GetParams(s.Ctx).DenomCreationFee
s.Require().Equal(tc.denomCreationFee.DenomCreationFee, denomCreationFee)
tokenFactoryKeeper.SetParams(suite.Ctx, tc.denomCreationFee)
denomCreationFee := tokenFactoryKeeper.GetParams(suite.Ctx).DenomCreationFee
suite.Require().Equal(tc.denomCreationFee.DenomCreationFee, denomCreationFee)

// note balance, create a tokenfactory denom, then note balance again
preCreateBalance := bankKeeper.GetAllBalances(s.Ctx, s.TestAccs[0])
res, err := s.msgServer.CreateDenom(sdk.WrapSDKContext(s.Ctx), types.NewMsgCreateDenom(s.TestAccs[0].String(), tc.subdenom))
postCreateBalance := bankKeeper.GetAllBalances(s.Ctx, s.TestAccs[0])
preCreateBalance := bankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0])
res, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), tc.subdenom))
postCreateBalance := bankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0])
if tc.valid {
s.Require().NoError(err)
s.Require().True(preCreateBalance.Sub(postCreateBalance...).IsEqual(denomCreationFee))
suite.Require().NoError(err)
suite.Require().True(preCreateBalance.Sub(postCreateBalance...).IsEqual(denomCreationFee))

// Make sure that the admin is set correctly
queryRes, err := s.queryClient.DenomAuthorityMetadata(s.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{
queryRes, err := suite.queryClient.DenomAuthorityMetadata(suite.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{
Denom: res.GetNewTokenDenom(),
})

s.Require().NoError(err)
s.Require().Equal(s.TestAccs[0].String(), queryRes.AuthorityMetadata.Admin)
suite.Require().NoError(err)
suite.Require().Equal(suite.TestAccs[0].String(), queryRes.AuthorityMetadata.Admin)

} else {
s.Require().Error(err)
suite.Require().Error(err)
// Ensure we don't charge if we expect an error
s.Require().True(preCreateBalance.IsEqual(postCreateBalance))
suite.Require().True(preCreateBalance.IsEqual(postCreateBalance))
}
})
}
26 changes: 13 additions & 13 deletions x/tokenfactory/keeper/genesis_test.go
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ import (
"github.com/quicksilver-zone/quicksilver/x/tokenfactory/types"
)

func (s *KeeperTestSuite) TestGenesis() {
func (suite *KeeperTestSuite) TestGenesis() {
genesisState := types.GenesisState{
FactoryDenoms: []types.GenesisDenom{
{
@@ -31,29 +31,29 @@ func (s *KeeperTestSuite) TestGenesis() {
},
}

s.SetupTestForInitGenesis()
app := s.App
suite.SetupTestForInitGenesis()
app := suite.App

// Test both with bank denom metadata set, and not set.
for i, denom := range genesisState.FactoryDenoms {
// hacky, sets bank metadata to exist if i != 0, to cover both cases.
if i != 0 {
app.BankKeeper.SetDenomMetaData(s.Ctx, banktypes.Metadata{Base: denom.GetDenom()})
app.BankKeeper.SetDenomMetaData(suite.Ctx, banktypes.Metadata{Base: denom.GetDenom()})
}
}

// check before initGenesis that the module account is nil
tokenfactoryModuleAccount := app.AccountKeeper.GetAccount(s.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName))
s.Require().Nil(tokenfactoryModuleAccount)
tokenfactoryModuleAccount := app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName))
suite.Require().Nil(tokenfactoryModuleAccount)

app.TokenFactoryKeeper.SetParams(s.Ctx, types.Params{DenomCreationFee: sdk.Coins{sdk.NewInt64Coin("uqck", 100)}})
app.TokenFactoryKeeper.InitGenesis(s.Ctx, genesisState)
app.TokenFactoryKeeper.SetParams(suite.Ctx, types.Params{DenomCreationFee: sdk.Coins{sdk.NewInt64Coin("uqck", 100)}})
app.TokenFactoryKeeper.InitGenesis(suite.Ctx, genesisState)

// check that the module account is now initialized
tokenfactoryModuleAccount = app.AccountKeeper.GetAccount(s.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName))
s.Require().NotNil(tokenfactoryModuleAccount)
tokenfactoryModuleAccount = app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName))
suite.Require().NotNil(tokenfactoryModuleAccount)

exportedGenesis := app.TokenFactoryKeeper.ExportGenesis(s.Ctx)
s.Require().NotNil(exportedGenesis)
s.Require().Equal(genesisState, *exportedGenesis)
exportedGenesis := app.TokenFactoryKeeper.ExportGenesis(suite.Ctx)
suite.Require().NotNil(exportedGenesis)
suite.Require().Equal(genesisState, *exportedGenesis)
}
76 changes: 38 additions & 38 deletions x/tokenfactory/keeper/keeper_test.go
Original file line number Diff line number Diff line change
@@ -38,16 +38,16 @@ type KeeperTestSuite struct {
}

// Setup sets up basic environment for suite (App, Ctx, and test accounts).
func (s *KeeperTestSuite) Setup() {
func (suite *KeeperTestSuite) Setup() {
cmdcfg.SetBech32Prefixes(sdk.GetConfig())
s.App = app.Setup(s.T(), false)
s.Ctx = s.App.BaseApp.NewContext(false, tmproto.Header{Height: 1, ChainID: "quick-1", Time: time.Now().UTC()})
s.QueryHelper = &baseapp.QueryServiceTestHelper{
GRPCQueryRouter: s.App.GRPCQueryRouter(),
Ctx: s.Ctx,
suite.App = app.Setup(suite.T(), false)
suite.Ctx = suite.App.BaseApp.NewContext(false, tmproto.Header{Height: 1, ChainID: "quick-1", Time: time.Now().UTC()})
suite.QueryHelper = &baseapp.QueryServiceTestHelper{
GRPCQueryRouter: suite.App.GRPCQueryRouter(),
Ctx: suite.Ctx,
}

s.TestAccs = CreateRandomAccounts(3)
suite.TestAccs = CreateRandomAccounts(3)
}

// CreateRandomAccounts is a function return a list of randomly generated AccAddresses.
@@ -62,22 +62,22 @@ func CreateRandomAccounts(numAccts int) []sdk.AccAddress {
}

// FundAcc funds target address with specified amount.
func (s *KeeperTestSuite) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) {
err := s.App.BankKeeper.MintCoins(s.Ctx, minttypes.ModuleName, amounts)
s.NoError(err)
err = s.App.BankKeeper.SendCoinsFromModuleToAccount(s.Ctx, minttypes.ModuleName, acc, amounts)
s.NoError(err)
func (suite *KeeperTestSuite) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) {
err := suite.App.BankKeeper.MintCoins(suite.Ctx, minttypes.ModuleName, amounts)
suite.NoError(err)
err = suite.App.BankKeeper.SendCoinsFromModuleToAccount(suite.Ctx, minttypes.ModuleName, acc, amounts)
suite.NoError(err)
}

func (s *KeeperTestSuite) SetupTestForInitGenesis() {
func (suite *KeeperTestSuite) SetupTestForInitGenesis() {
// Setting to True, leads to init genesis not running
s.App = app.Setup(s.T(), true)
s.Ctx = s.App.BaseApp.NewContext(true, tmproto.Header{})
suite.App = app.Setup(suite.T(), true)
suite.Ctx = suite.App.BaseApp.NewContext(true, tmproto.Header{})
}

// AssertEventEmitted asserts that ctx's event manager has emitted the given number of events
// of the given type.
func (s *KeeperTestSuite) AssertEventEmitted(ctx sdk.Context, eventTypeExpected string, numEventsExpected int) {
func (suite *KeeperTestSuite) AssertEventEmitted(ctx sdk.Context, eventTypeExpected string, numEventsExpected int) {
allEvents := ctx.EventManager().Events()
// filter out other events
actualEvents := make([]sdk.Event, 0)
@@ -86,49 +86,49 @@ func (s *KeeperTestSuite) AssertEventEmitted(ctx sdk.Context, eventTypeExpected
actualEvents = append(actualEvents, event)
}
}
s.Equal(numEventsExpected, len(actualEvents))
suite.Equal(numEventsExpected, len(actualEvents))
}

func TestKeeperTestSuite(t *testing.T) {
suite.Run(t, new(KeeperTestSuite))
}

func (s *KeeperTestSuite) SetupTest() {
s.Setup()
func (suite *KeeperTestSuite) SetupTest() {
suite.Setup()
// Fund every TestAcc with two denoms, one of which is the denom creation fee
fundAccsAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100)), sdk.NewCoin(SecondaryDenom, SecondaryAmount))
for _, acc := range s.TestAccs {
s.FundAcc(acc, fundAccsAmount)
for _, acc := range suite.TestAccs {
suite.FundAcc(acc, fundAccsAmount)
}

s.queryClient = types.NewQueryClient(s.QueryHelper)
s.msgServer = keeper.NewMsgServerImpl(s.App.TokenFactoryKeeper)
suite.queryClient = types.NewQueryClient(suite.QueryHelper)
suite.msgServer = keeper.NewMsgServerImpl(suite.App.TokenFactoryKeeper)
}

func (s *KeeperTestSuite) CreateDefaultDenom() {
s.T().Helper()
func (suite *KeeperTestSuite) CreateDefaultDenom() {
suite.T().Helper()

res, err := s.msgServer.CreateDenom(sdk.WrapSDKContext(s.Ctx), types.NewMsgCreateDenom(s.TestAccs[0].String(), "bitcoin"))
s.Require().NoError(err)
s.defaultDenom = res.GetNewTokenDenom()
res, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin"))
suite.Require().NoError(err)
suite.defaultDenom = res.GetNewTokenDenom()
}

func (s *KeeperTestSuite) TestCreateModuleAccount() {
quicksilver := s.App
func (suite *KeeperTestSuite) TestCreateModuleAccount() {
quicksilver := suite.App

// remove module account
tokenfactoryModuleAccount := quicksilver.AccountKeeper.GetAccount(s.Ctx, quicksilver.AccountKeeper.GetModuleAddress(types.ModuleName))
quicksilver.AccountKeeper.RemoveAccount(s.Ctx, tokenfactoryModuleAccount)
tokenfactoryModuleAccount := quicksilver.AccountKeeper.GetAccount(suite.Ctx, quicksilver.AccountKeeper.GetModuleAddress(types.ModuleName))
quicksilver.AccountKeeper.RemoveAccount(suite.Ctx, tokenfactoryModuleAccount)

// ensure module account was removed
s.Ctx = quicksilver.BaseApp.NewContext(false, tmproto.Header{})
tokenfactoryModuleAccount = quicksilver.AccountKeeper.GetAccount(s.Ctx, quicksilver.AccountKeeper.GetModuleAddress(types.ModuleName))
s.Require().Nil(tokenfactoryModuleAccount)
suite.Ctx = quicksilver.BaseApp.NewContext(false, tmproto.Header{})
tokenfactoryModuleAccount = quicksilver.AccountKeeper.GetAccount(suite.Ctx, quicksilver.AccountKeeper.GetModuleAddress(types.ModuleName))
suite.Require().Nil(tokenfactoryModuleAccount)

// create module account
quicksilver.TokenFactoryKeeper.CreateModuleAccount(s.Ctx)
quicksilver.TokenFactoryKeeper.CreateModuleAccount(suite.Ctx)

// check that the module account is now initialized
tokenfactoryModuleAccount = quicksilver.AccountKeeper.GetAccount(s.Ctx, quicksilver.AccountKeeper.GetModuleAddress(types.ModuleName))
s.Require().NotNil(tokenfactoryModuleAccount)
tokenfactoryModuleAccount = quicksilver.AccountKeeper.GetAccount(suite.Ctx, quicksilver.AccountKeeper.GetModuleAddress(types.ModuleName))
suite.Require().NotNil(tokenfactoryModuleAccount)
}
Loading

0 comments on commit 108ebf4

Please sign in to comment.