From 5f42aacaae24ab92ecfaf4340f51b76d6a410405 Mon Sep 17 00:00:00 2001 From: godismercilex <98415576+godismercilex@users.noreply.github.com> Date: Mon, 15 Aug 2022 11:25:49 +0200 Subject: [PATCH 1/7] feat(oracle): remove tobin tax (#816) * change: remove tobin tax mentions from oracle protos * chore: rebuild protos * change: adjust code in genesis, pair list and params * change: remove query tobin taxes CLI cmd * remove: querier tobin taxes related functionality * change: rename tobin tax to pair * change: adjust code to not use TobinTax but Pair instead * change: fixes and test adjustments * change: adjust test * chore: increase coverage of ApplyWhitelist * chore: tobin tax=>pair renamings * chore: lint * chore: update CHANGELOG.md * chore: lint * Update CHANGELOG.md Co-authored-by: AgentSmithMatrix <98403347+AgentSmithMatrix@users.noreply.github.com> --- CHANGELOG.md | 3 +- proto/oracle/v1beta1/genesis.proto | 10 +- proto/oracle/v1beta1/oracle.proto | 5 - proto/oracle/v1beta1/query.proto | 41 -- x/oracle/abci.go | 15 +- x/oracle/abci_test.go | 52 +- x/oracle/client/cli/query.go | 54 -- x/oracle/genesis.go | 16 +- x/oracle/genesis_test.go | 4 +- x/oracle/keeper/ballot.go | 19 +- x/oracle/keeper/ballot_test.go | 74 ++- x/oracle/keeper/keeper.go | 42 +- x/oracle/keeper/keeper_test.go | 37 +- x/oracle/keeper/querier.go | 35 - x/oracle/keeper/querier_test.go | 50 +- x/oracle/keeper/reward.go | 2 +- x/oracle/keeper/reward_test.go | 2 +- x/oracle/keeper/test_utils.go | 2 +- x/oracle/keeper/vote_target.go | 5 +- x/oracle/keeper/vote_target_test.go | 10 +- x/oracle/simulation/decoder.go | 7 +- x/oracle/simulation/decoder_test.go | 10 +- x/oracle/simulation/genesis.go | 11 +- x/oracle/spec/06_params.md | 2 +- x/oracle/spec/README.md | 2 +- x/oracle/tally.go | 2 +- x/oracle/tally_fuzz_test.go | 2 +- x/oracle/types/errors.go | 3 +- x/oracle/types/genesis.go | 8 +- x/oracle/types/genesis.pb.go | 312 ++------- x/oracle/types/keys.go | 16 +- x/oracle/types/oracle.pb.go | 145 ++-- x/oracle/types/pair_list.go | 2 +- x/oracle/types/params.go | 27 +- x/oracle/types/params_test.go | 30 +- x/oracle/types/query.pb.go | 989 ++++------------------------ x/oracle/types/query.pb.gw.go | 160 ----- 37 files changed, 422 insertions(+), 1784 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38ac68d16..660aa1b68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,7 +58,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Features * [#791](https://github.com/NibiruChain/nibiru/pull/791) Add the x/oracle module -- [#813](https://github.com/NibiruChain/nibiru/pull/813) - (vpool): Expose mark price, mark TWAP, index price, and k (swap invariant) in the all-pools query +* [#816](https://github.com/NibiruChain/nibiru/pull/816) - Remove tobin tax from x/oracle +* [#813](https://github.com/NibiruChain/nibiru/pull/813) - (vpool): Expose mark price, mark TWAP, index price, and k (swap invariant) in the all-pools query * [#810](https://github.com/NibiruChain/nibiru/pull/810) - feat(x/perp): expose 'marginRatioIndex' and block number on QueryTraderPosition ## [v0.12.1](https://github.com/NibiruChain/nibiru/releases/tag/v0.12.1) - 2022-08-04 diff --git a/proto/oracle/v1beta1/genesis.proto b/proto/oracle/v1beta1/genesis.proto index 50005fe2e..c40beafd9 100644 --- a/proto/oracle/v1beta1/genesis.proto +++ b/proto/oracle/v1beta1/genesis.proto @@ -16,7 +16,7 @@ message GenesisState { repeated MissCounter miss_counters = 4 [(gogoproto.nullable) = false]; repeated AggregateExchangeRatePrevote aggregate_exchange_rate_prevotes = 5 [(gogoproto.nullable) = false]; repeated AggregateExchangeRateVote aggregate_exchange_rate_votes = 6 [(gogoproto.nullable) = false]; - repeated TobinTax tobin_taxes = 7 [(gogoproto.nullable) = false]; + repeated Pair pairs = 7 [(gogoproto.nullable) = false]; } // FeederDelegation is the address for where oracle feeder authority are @@ -33,11 +33,3 @@ message MissCounter { string validator_address = 1; uint64 miss_counter = 2; } - -// TobinTax defines a pair and tobin_tax pair used in -// oracle module's genesis state -message TobinTax { - string pair = 1; - string tobin_tax = 2 - [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; -} \ No newline at end of file diff --git a/proto/oracle/v1beta1/oracle.proto b/proto/oracle/v1beta1/oracle.proto index 80debcc06..744c21e05 100644 --- a/proto/oracle/v1beta1/oracle.proto +++ b/proto/oracle/v1beta1/oracle.proto @@ -48,11 +48,6 @@ message Pair { option (gogoproto.goproto_stringer) = false; string name = 1 [(gogoproto.moretags) = "yaml:\"name\""]; - string tobin_tax = 2 [ - (gogoproto.moretags) = "yaml:\"tobin_tax\"", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; } // struct for aggregate prevoting on the ExchangeRateVote. diff --git a/proto/oracle/v1beta1/query.proto b/proto/oracle/v1beta1/query.proto index 3e4b263f2..0e1fa66bf 100644 --- a/proto/oracle/v1beta1/query.proto +++ b/proto/oracle/v1beta1/query.proto @@ -20,16 +20,6 @@ service Query { option (google.api.http).get = "/nibiru/oracle/v1beta1/pairs/exchange_rates"; } - // TobinTax returns tobin tax of a pair - rpc TobinTax(QueryTobinTaxRequest) returns (QueryTobinTaxResponse) { - option (google.api.http).get = "/nibiru/oracle/v1beta1/pairs/{pair}/tobin_tax"; - } - - // TobinTaxes returns tobin taxes of all pairs - rpc TobinTaxes(QueryTobinTaxesRequest) returns (QueryTobinTaxesResponse) { - option (google.api.http).get = "/nibiru/oracle/v1beta1/pairs/tobin_taxes"; - } - // Actives returns all active pairs rpc Actives(QueryActivesRequest) returns (QueryActivesResponse) { option (google.api.http).get = "/nibiru/oracle/v1beta1/pairs/actives"; @@ -106,37 +96,6 @@ message QueryExchangeRatesResponse { ]; } -// QueryTobinTaxRequest is the request type for the Query/TobinTax RPC method. -message QueryTobinTaxRequest { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - // pair defines the asset to query for. - string pair = 1; -} - -// QueryTobinTaxResponse is response type for the -// Query/TobinTax RPC method. -message QueryTobinTaxResponse { - // tobin_taxe defines the tobin tax of a pair - string tobin_tax = 1 - [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; -} - -// QueryTobinTaxesRequest is the request type for the Query/TobinTaxes RPC method. -message QueryTobinTaxesRequest {} - -// QueryTobinTaxesResponse is response type for the -// Query/TobinTaxes RPC method. -message QueryTobinTaxesResponse { - // tobin_taxes defines a list of the tobin tax of all whitelisted pairs - repeated Pair tobin_taxes = 1 [ - (gogoproto.moretags) = "yaml:\"tobin_taxes\"", - (gogoproto.castrepeated) = "PairList", - (gogoproto.nullable) = false - ]; -} - // QueryActivesRequest is the request type for the Query/Actives RPC method. message QueryActivesRequest {} diff --git a/x/oracle/abci.go b/x/oracle/abci.go index 28fdf8b0d..a6076f465 100644 --- a/x/oracle/abci.go +++ b/x/oracle/abci.go @@ -37,10 +37,9 @@ func EndBlocker(ctx sdk.Context, k keeper.Keeper) { } } - // Pair-TobinTax map - pairTobinTaxMap := make(map[string]sdk.Dec) - k.IterateTobinTaxes(ctx, func(pair string, tobinTax sdk.Dec) bool { - pairTobinTaxMap[pair] = tobinTax + pairsMap := make(map[string]struct{}) + k.IteratePairs(ctx, func(pair string) bool { + pairsMap[pair] = struct{}{} return false }) @@ -55,7 +54,7 @@ func EndBlocker(ctx sdk.Context, k keeper.Keeper) { // NOTE: **Make abstain votes to have zero vote power** pairBallotMap := k.OrganizeBallotByPair(ctx, validatorClaimMap) - if referencePair := PickReferencePair(ctx, k, pairTobinTaxMap, pairBallotMap); referencePair != "" { + if referencePair := PickReferencePair(ctx, k, pairsMap, pairBallotMap); referencePair != "" { // make voteMap of reference pair to calculate cross exchange rates referenceBallot := pairBallotMap[referencePair] referenceValidatorExchangeRateMap := referenceBallot.ToMap() @@ -83,7 +82,7 @@ func EndBlocker(ctx sdk.Context, k keeper.Keeper) { //--------------------------- // Do miss counting & slashing - voteTargetsLen := len(pairTobinTaxMap) + voteTargetsLen := len(pairsMap) for _, claim := range validatorClaimMap { // Skip abstain & valid voters if int(claim.WinCount) == voteTargetsLen { @@ -99,7 +98,7 @@ func EndBlocker(ctx sdk.Context, k keeper.Keeper) { ctx, (int64)(params.VotePeriod), (int64)(params.RewardDistributionWindow), - pairTobinTaxMap, + pairsMap, validatorClaimMap, ) @@ -107,7 +106,7 @@ func EndBlocker(ctx sdk.Context, k keeper.Keeper) { k.ClearBallots(ctx, params.VotePeriod) // Update vote targets and tobin tax - k.ApplyWhitelist(ctx, params.Whitelist, pairTobinTaxMap) + k.ApplyWhitelist(ctx, params.Whitelist, pairsMap) } // Do slash who did miss voting over threshold and diff --git a/x/oracle/abci_test.go b/x/oracle/abci_test.go index a0eac9c3b..9e79f6a5e 100644 --- a/x/oracle/abci_test.go +++ b/x/oracle/abci_test.go @@ -263,12 +263,12 @@ func TestOracleRewardDistribution(t *testing.T) { func TestOracleRewardBand(t *testing.T) { input, h := setup(t) params := input.OracleKeeper.GetParams(input.Ctx) - params.Whitelist = types.PairList{{Name: common.PairGovStable.String(), TobinTax: types.DefaultTobinTax}} + params.Whitelist = types.PairList{{Name: common.PairGovStable.String()}} input.OracleKeeper.SetParams(input.Ctx, params) - // clear tobin tax to reset vote targets - input.OracleKeeper.ClearTobinTaxes(input.Ctx) - input.OracleKeeper.SetTobinTax(input.Ctx, common.PairGovStable.String(), types.DefaultTobinTax) + // clear pairs to reset vote targets + input.OracleKeeper.ClearPairs(input.Ctx) + input.OracleKeeper.SetPair(input.Ctx, common.PairGovStable.String()) rewardSpread := randomExchangeRate.Mul(input.OracleKeeper.RewardBand(input.Ctx).QuoInt64(2)) @@ -461,9 +461,9 @@ func TestOracleExchangeRateVal5(t *testing.T) { func TestInvalidVotesSlashing(t *testing.T) { input, h := setup(t) params := input.OracleKeeper.GetParams(input.Ctx) - params.Whitelist = types.PairList{{Name: common.PairGovStable.String(), TobinTax: types.DefaultTobinTax}} + params.Whitelist = types.PairList{{Name: common.PairGovStable.String()}} input.OracleKeeper.SetParams(input.Ctx, params) - input.OracleKeeper.SetTobinTax(input.Ctx, common.PairGovStable.String(), types.DefaultTobinTax) + input.OracleKeeper.SetPair(input.Ctx, common.PairGovStable.String()) votePeriodsPerWindow := sdk.NewDec(int64(input.OracleKeeper.SlashWindow(input.Ctx))).QuoInt64(int64(input.OracleKeeper.VotePeriod(input.Ctx))).TruncateInt64() slashFraction := input.OracleKeeper.SlashFraction(input.Ctx) @@ -542,12 +542,12 @@ func TestWhitelistSlashing(t *testing.T) { func TestNotPassedBallotSlashing(t *testing.T) { input, h := setup(t) params := input.OracleKeeper.GetParams(input.Ctx) - params.Whitelist = types.PairList{{Name: common.PairGovStable.String(), TobinTax: types.DefaultTobinTax}} + params.Whitelist = types.PairList{{Name: common.PairGovStable.String()}} input.OracleKeeper.SetParams(input.Ctx, params) // clear tobin tax to reset vote targets - input.OracleKeeper.ClearTobinTaxes(input.Ctx) - input.OracleKeeper.SetTobinTax(input.Ctx, common.PairGovStable.String(), types.DefaultTobinTax) + input.OracleKeeper.ClearPairs(input.Ctx) + input.OracleKeeper.SetPair(input.Ctx, common.PairGovStable.String()) input.Ctx = input.Ctx.WithBlockHeight(input.Ctx.BlockHeight() + 1) @@ -563,12 +563,12 @@ func TestNotPassedBallotSlashing(t *testing.T) { func TestAbstainSlashing(t *testing.T) { input, h := setup(t) params := input.OracleKeeper.GetParams(input.Ctx) - params.Whitelist = types.PairList{{Name: common.PairGovStable.String(), TobinTax: types.DefaultTobinTax}} + params.Whitelist = types.PairList{{Name: common.PairGovStable.String()}} input.OracleKeeper.SetParams(input.Ctx, params) // clear tobin tax to reset vote targets - input.OracleKeeper.ClearTobinTaxes(input.Ctx) - input.OracleKeeper.SetTobinTax(input.Ctx, common.PairGovStable.String(), types.DefaultTobinTax) + input.OracleKeeper.ClearPairs(input.Ctx) + input.OracleKeeper.SetPair(input.Ctx, common.PairGovStable.String()) votePeriodsPerWindow := sdk.NewDec(int64(input.OracleKeeper.SlashWindow(input.Ctx))).QuoInt64(int64(input.OracleKeeper.VotePeriod(input.Ctx))).TruncateInt64() minValidPerWindow := input.OracleKeeper.MinValidPerWindow(input.Ctx) @@ -596,12 +596,12 @@ func TestAbstainSlashing(t *testing.T) { func TestVoteTargets(t *testing.T) { input, h := setup(t) params := input.OracleKeeper.GetParams(input.Ctx) - params.Whitelist = types.PairList{{Name: common.PairGovStable.String(), TobinTax: types.DefaultTobinTax}, {Name: common.PairBTCStable.String(), TobinTax: types.DefaultTobinTax}} + params.Whitelist = types.PairList{{Name: common.PairGovStable.String()}, {Name: common.PairBTCStable.String()}} input.OracleKeeper.SetParams(input.Ctx, params) // clear tobin tax to reset vote targets - input.OracleKeeper.ClearTobinTaxes(input.Ctx) - input.OracleKeeper.SetTobinTax(input.Ctx, common.PairGovStable.String(), types.DefaultTobinTax) + input.OracleKeeper.ClearPairs(input.Ctx) + input.OracleKeeper.SetPair(input.Ctx, common.PairGovStable.String()) // govstable makeAggregatePrevoteAndVote(t, input, h, 0, types.ExchangeRateTuples{{Pair: common.PairGovStable.String(), ExchangeRate: randomExchangeRate}}, 0) @@ -618,13 +618,8 @@ func TestVoteTargets(t *testing.T) { // vote targets are {govstable, btcstable} require.Equal(t, []string{common.PairBTCStable.String(), common.PairGovStable.String()}, input.OracleKeeper.GetVoteTargets(input.Ctx)) - // tobin tax must be exists for btcstable - btcStableTax, err := input.OracleKeeper.GetTobinTax(input.Ctx, common.PairBTCStable.String()) - require.NoError(t, err) - require.Equal(t, types.DefaultTobinTax, btcStableTax) - // delete btcstable - params.Whitelist = types.PairList{{Name: common.PairGovStable.String(), TobinTax: types.DefaultTobinTax}} + params.Whitelist = types.PairList{{Name: common.PairGovStable.String()}} input.OracleKeeper.SetParams(input.Ctx, params) // govstable, missing @@ -641,11 +636,11 @@ func TestVoteTargets(t *testing.T) { // btcstable must be deleted require.Equal(t, []string{common.PairGovStable.String()}, input.OracleKeeper.GetVoteTargets(input.Ctx)) - _, err = input.OracleKeeper.GetTobinTax(input.Ctx, common.PairBTCStable.String()) - require.Error(t, err) + exists := input.OracleKeeper.PairExists(input.Ctx, common.PairBTCStable.String()) + require.False(t, exists) // change govstable tobin tax - params.Whitelist = types.PairList{{Name: common.PairGovStable.String(), TobinTax: sdk.ZeroDec()}} + params.Whitelist = types.PairList{{Name: common.PairGovStable.String()}} input.OracleKeeper.SetParams(input.Ctx, params) // govstable, no missing @@ -658,19 +653,14 @@ func TestVoteTargets(t *testing.T) { require.Equal(t, uint64(1), input.OracleKeeper.GetMissCounter(input.Ctx, keeper.ValAddrs[0])) require.Equal(t, uint64(1), input.OracleKeeper.GetMissCounter(input.Ctx, keeper.ValAddrs[1])) require.Equal(t, uint64(1), input.OracleKeeper.GetMissCounter(input.Ctx, keeper.ValAddrs[2])) - - // govstable tobin tax must be 0 - tobinTax, err := input.OracleKeeper.GetTobinTax(input.Ctx, common.PairGovStable.String()) - require.NoError(t, err) - require.True(t, sdk.ZeroDec().Equal(tobinTax)) } func TestAbstainWithSmallStakingPower(t *testing.T) { input, h := setupWithSmallVotingPower(t) // clear tobin tax to reset vote targets - input.OracleKeeper.ClearTobinTaxes(input.Ctx) - input.OracleKeeper.SetTobinTax(input.Ctx, common.PairGovStable.String(), types.DefaultTobinTax) + input.OracleKeeper.ClearPairs(input.Ctx) + input.OracleKeeper.SetPair(input.Ctx, common.PairGovStable.String()) makeAggregatePrevoteAndVote(t, input, h, 0, types.ExchangeRateTuples{{Pair: common.PairGovStable.String(), ExchangeRate: sdk.ZeroDec()}}, 0) oracle.EndBlocker(input.Ctx, input.OracleKeeper) diff --git a/x/oracle/client/cli/query.go b/x/oracle/client/cli/query.go index 15bf14cc7..1925965a4 100644 --- a/x/oracle/client/cli/query.go +++ b/x/oracle/client/cli/query.go @@ -32,7 +32,6 @@ func GetQueryCmd() *cobra.Command { GetCmdQueryAggregatePrevote(), GetCmdQueryAggregateVote(), GetCmdQueryVoteTargets(), - GetCmdQueryTobinTaxes(), ) return oracleQueryCmd @@ -365,56 +364,3 @@ func GetCmdQueryVoteTargets() *cobra.Command { flags.AddQueryFlagsToCmd(cmd) return cmd } - -// GetCmdQueryTobinTaxes implements the query params command. -func GetCmdQueryTobinTaxes() *cobra.Command { - cmd := &cobra.Command{ - Use: "tobin-taxes [pair]", - Args: cobra.RangeArgs(0, 1), - Short: "Query the current Oracle tobin taxes.", - Long: strings.TrimSpace(` -Query the current Oracle tobin taxes. - -$ nibid query oracle tobin-taxes - -Or, can filter with pair - -$ nibid query oracle tobin-taxes nibi:usd - -Or, can -`), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - if len(args) == 0 { - res, err := queryClient.TobinTaxes( - context.Background(), - &types.QueryTobinTaxesRequest{}, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - } - - pair := args[0] - res, err := queryClient.TobinTax( - context.Background(), - &types.QueryTobinTaxRequest{Pair: pair}, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} diff --git a/x/oracle/genesis.go b/x/oracle/genesis.go index 374654815..5f11a6921 100644 --- a/x/oracle/genesis.go +++ b/x/oracle/genesis.go @@ -57,13 +57,13 @@ func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, data *types.GenesisState keeper.SetAggregateExchangeRateVote(ctx, valAddr, av) } - if len(data.TobinTaxes) > 0 { - for _, tt := range data.TobinTaxes { - keeper.SetTobinTax(ctx, tt.Pair, tt.TobinTax) + if len(data.Pairs) > 0 { + for _, tt := range data.Pairs { + keeper.SetPair(ctx, tt.Name) } } else { for _, item := range data.Params.Whitelist { - keeper.SetTobinTax(ctx, item.Name, item.TobinTax) + keeper.SetPair(ctx, item.Name) } } @@ -117,9 +117,9 @@ func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { return false }) - tobinTaxes := []types.TobinTax{} - keeper.IterateTobinTaxes(ctx, func(pair string, tobinTax sdk.Dec) (stop bool) { - tobinTaxes = append(tobinTaxes, types.TobinTax{Pair: pair, TobinTax: tobinTax}) + pairs := []types.Pair{} + keeper.IteratePairs(ctx, func(pair string) (stop bool) { + pairs = append(pairs, types.Pair{Name: pair}) return false }) @@ -129,5 +129,5 @@ func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { missCounters, aggregateExchangeRatePrevotes, aggregateExchangeRateVotes, - tobinTaxes) + pairs) } diff --git a/x/oracle/genesis_test.go b/x/oracle/genesis_test.go index ed7c51039..30521aee6 100644 --- a/x/oracle/genesis_test.go +++ b/x/oracle/genesis_test.go @@ -19,8 +19,8 @@ func TestExportInitGenesis(t *testing.T) { input.OracleKeeper.SetExchangeRate(input.Ctx, "denom", sdk.NewDec(123)) input.OracleKeeper.SetAggregateExchangeRatePrevote(input.Ctx, keeper.ValAddrs[0], types.NewAggregateExchangeRatePrevote(types.AggregateVoteHash{123}, keeper.ValAddrs[0], uint64(2))) input.OracleKeeper.SetAggregateExchangeRateVote(input.Ctx, keeper.ValAddrs[0], types.NewAggregateExchangeRateVote(types.ExchangeRateTuples{{Pair: "foo", ExchangeRate: sdk.NewDec(123)}}, keeper.ValAddrs[0])) - input.OracleKeeper.SetTobinTax(input.Ctx, "denom", sdk.NewDecWithPrec(123, 3)) - input.OracleKeeper.SetTobinTax(input.Ctx, "denom2", sdk.NewDecWithPrec(123, 3)) + input.OracleKeeper.SetPair(input.Ctx, "pair1:pair1") + input.OracleKeeper.SetPair(input.Ctx, "pair2:pair2") input.OracleKeeper.SetMissCounter(input.Ctx, keeper.ValAddrs[0], 10) genesis := oracle.ExportGenesis(input.Ctx, input.OracleKeeper) diff --git a/x/oracle/keeper/ballot.go b/x/oracle/keeper/ballot.go index d2d977a75..88e24a38c 100644 --- a/x/oracle/keeper/ballot.go +++ b/x/oracle/keeper/ballot.go @@ -66,15 +66,19 @@ func (k Keeper) ClearBallots(ctx sdk.Context, votePeriod uint64) { }) } -// ApplyWhitelist update vote target pair list and set tobin tax with params whitelist -func (k Keeper) ApplyWhitelist(ctx sdk.Context, whitelist types.PairList, voteTargets map[string]sdk.Dec) { +// ApplyWhitelist updates the whitelist by detecting possible changes between +// the current vote targets and the current updated whitelist. +func (k Keeper) ApplyWhitelist(ctx sdk.Context, whitelist types.PairList, voteTargets map[string]struct{}) { // check is there any update in whitelist params updateRequired := false + // fast path if len(voteTargets) != len(whitelist) { updateRequired = true + // slow path, we need to check differences } else { - for _, item := range whitelist { - if tobinTax, ok := voteTargets[item.Name]; !ok || !tobinTax.Equal(item.TobinTax) { + for _, pair := range whitelist { + _, exists := voteTargets[pair.Name] + if !exists { updateRequired = true break } @@ -82,10 +86,9 @@ func (k Keeper) ApplyWhitelist(ctx sdk.Context, whitelist types.PairList, voteTa } if updateRequired { - k.ClearTobinTaxes(ctx) - - for _, item := range whitelist { - k.SetTobinTax(ctx, item.Name, item.TobinTax) + k.ClearPairs(ctx) + for _, pair := range whitelist { + k.SetPair(ctx, pair.Name) } } } diff --git a/x/oracle/keeper/ballot_test.go b/x/oracle/keeper/ballot_test.go index 5f4a33c54..982e95f0c 100644 --- a/x/oracle/keeper/ballot_test.go +++ b/x/oracle/keeper/ballot_test.go @@ -156,26 +156,70 @@ func TestClearBallots(t *testing.T) { func TestApplyWhitelist(t *testing.T) { input := CreateTestInput(t) - // no update - input.OracleKeeper.ApplyWhitelist(input.Ctx, types.PairList{ + whitelist := types.PairList{ types.Pair{ - Name: "nibi:usd", - TobinTax: sdk.OneDec(), + Name: "nibi:usd", }, types.Pair{ - Name: "btc:usd", - TobinTax: sdk.OneDec(), + Name: "btc:usd", }, - }, map[string]sdk.Dec{ - "nibi:usd": sdk.ZeroDec(), - "btc:usd": sdk.ZeroDec(), + } + + // prepare test by resetting the genesis pairs + input.OracleKeeper.ClearPairs(input.Ctx) + for _, p := range whitelist { + input.OracleKeeper.SetPair(input.Ctx, p.Name) + } + + voteTargets := map[string]struct{}{ + "nibi:usd": {}, + "btc:usd": {}, + } + // no updates case + input.OracleKeeper.ApplyWhitelist(input.Ctx, whitelist, voteTargets) + + gotPairs := types.PairList{} + + input.OracleKeeper.IteratePairs(input.Ctx, func(pair string) (stop bool) { + gotPairs = append(gotPairs, types.Pair{Name: pair}) + return false }) - price, err := input.OracleKeeper.GetTobinTax(input.Ctx, "nibi:usd") - require.NoError(t, err) - require.Equal(t, price, sdk.OneDec()) + sort.Slice(whitelist, func(i, j int) bool { + return whitelist[i].Name < whitelist[j].Name + }) + require.Equal(t, whitelist, gotPairs) - price, err = input.OracleKeeper.GetTobinTax(input.Ctx, "btc:usd") - require.NoError(t, err) - require.Equal(t, price, sdk.OneDec()) + // len update (fast path) + whitelist = append(whitelist, types.Pair{Name: "nibi:eth"}) + input.OracleKeeper.ApplyWhitelist(input.Ctx, whitelist, voteTargets) + + gotPairs = types.PairList{} + + input.OracleKeeper.IteratePairs(input.Ctx, func(pair string) (stop bool) { + gotPairs = append(gotPairs, types.Pair{Name: pair}) + return false + }) + + sort.Slice(whitelist, func(i, j int) bool { + return whitelist[i].Name < whitelist[j].Name + }) + require.Equal(t, whitelist, gotPairs) + + // diff update (slow path) + voteTargets["nibi:eth"] = struct{}{} // add previous pair + whitelist[0] = types.Pair{Name: "nibi:usdt"} // update first pair + input.OracleKeeper.ApplyWhitelist(input.Ctx, whitelist, voteTargets) + + gotPairs = types.PairList{} + + input.OracleKeeper.IteratePairs(input.Ctx, func(pair string) (stop bool) { + gotPairs = append(gotPairs, types.Pair{Name: pair}) + return false + }) + + sort.Slice(whitelist, func(i, j int) bool { + return whitelist[i].Name < whitelist[j].Name + }) + require.Equal(t, whitelist, gotPairs) } diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 82bbe9d54..75a04de2b 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -292,50 +292,38 @@ func (k Keeper) IterateAggregateExchangeRateVotes(ctx sdk.Context, handler func( } } -// GetTobinTax return tobin tax for the pair +// PairExists return tobin tax for the pair // TODO(mercilex): use AssetPair -func (k Keeper) GetTobinTax(ctx sdk.Context, pair string) (sdk.Dec, error) { +func (k Keeper) PairExists(ctx sdk.Context, pair string) bool { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.GetTobinTaxKey(pair)) - if bz == nil { - err := sdkerrors.Wrap(types.ErrNoTobinTax, pair) - return sdk.Dec{}, err - } - - tobinTax := sdk.DecProto{} - k.cdc.MustUnmarshal(bz, &tobinTax) - - return tobinTax.Dec, nil + bz := store.Get(types.GetPairKey(pair)) + return bz != nil } -// SetTobinTax updates tobin tax for the pair +// SetPair updates tobin tax for the pair // TODO(mercilex): use AssetPair -func (k Keeper) SetTobinTax(ctx sdk.Context, pair string, tobinTax sdk.Dec) { +func (k Keeper) SetPair(ctx sdk.Context, pair string) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshal(&sdk.DecProto{Dec: tobinTax}) - store.Set(types.GetTobinTaxKey(pair), bz) + store.Set(types.GetPairKey(pair), []byte{}) } -// IterateTobinTaxes iterates rate over tobin taxes in the store -func (k Keeper) IterateTobinTaxes(ctx sdk.Context, handler func(pair string, tobinTax sdk.Dec) (stop bool)) { +// IteratePairs iterates rate over tobin taxes in the store +func (k Keeper) IteratePairs(ctx sdk.Context, handler func(pair string) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.TobinTaxKey) + iter := sdk.KVStorePrefixIterator(store, types.PairsKey) defer iter.Close() for ; iter.Valid(); iter.Next() { - pair := types.ExtractPairFromTobinTaxKey(iter.Key()) - - var tobinTax sdk.DecProto - k.cdc.MustUnmarshal(iter.Value(), &tobinTax) - if handler(pair, tobinTax.Dec) { + pair := types.ExtractPairFromPairKey(iter.Key()) + if handler(pair) { break } } } -// ClearTobinTaxes clears tobin taxes -func (k Keeper) ClearTobinTaxes(ctx sdk.Context) { +// ClearPairs clears tobin taxes +func (k Keeper) ClearPairs(ctx sdk.Context) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.TobinTaxKey) + iter := sdk.KVStorePrefixIterator(store, types.PairsKey) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index ccf1e0699..4161efa86 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -106,8 +106,8 @@ func TestParams(t *testing.T) { slashWindow := uint64(1000) minValidPerWindow := sdk.NewDecWithPrec(1, 4) whitelist := types.PairList{ - {Name: common.PairETHStable.String(), TobinTax: types.DefaultTobinTax}, - {Name: common.PairBTCStable.String(), TobinTax: types.DefaultTobinTax}, + {Name: common.PairETHStable.String()}, + {Name: common.PairBTCStable.String()}, } // Should really test validateParams, but skipping because obvious @@ -299,32 +299,31 @@ func TestAggregateVoteIterate(t *testing.T) { }) } -func TestTobinTaxGetSet(t *testing.T) { +func TestPairGetSetIterate(t *testing.T) { input := CreateTestInput(t) - tobinTaxes := map[string]sdk.Dec{ - common.PairBTCStable.String(): sdk.NewDec(1), - common.PairGovStable.String(): sdk.NewDecWithPrec(123, 3), - common.PairCollStable.String(): sdk.NewDecWithPrec(1423, 4), - common.PairETHStable.String(): sdk.NewDecWithPrec(15956, 5), + pairs := []string{ + common.PairBTCStable.String(), + common.PairGovStable.String(), + common.PairCollStable.String(), + common.PairETHStable.String(), } - for denom, tobinTax := range tobinTaxes { - input.OracleKeeper.SetTobinTax(input.Ctx, denom, tobinTax) - factor, err := input.OracleKeeper.GetTobinTax(input.Ctx, denom) - require.NoError(t, err) - require.Equal(t, tobinTaxes[denom], factor) + for _, pair := range pairs { + input.OracleKeeper.SetPair(input.Ctx, pair) + exists := input.OracleKeeper.PairExists(input.Ctx, pair) + require.True(t, exists) } - input.OracleKeeper.IterateTobinTaxes(input.Ctx, func(denom string, tobinTax sdk.Dec) (stop bool) { - require.Equal(t, tobinTaxes[denom], tobinTax) + input.OracleKeeper.IteratePairs(input.Ctx, func(pair string) (stop bool) { + require.Contains(t, pairs, pair) return false }) - input.OracleKeeper.ClearTobinTaxes(input.Ctx) - for denom := range tobinTaxes { - _, err := input.OracleKeeper.GetTobinTax(input.Ctx, denom) - require.Error(t, err) + input.OracleKeeper.ClearPairs(input.Ctx) + for _, pair := range pairs { + exists := input.OracleKeeper.PairExists(input.Ctx, pair) + require.False(t, exists) } } diff --git a/x/oracle/keeper/querier.go b/x/oracle/keeper/querier.go index 67fa267e9..dcf8303d8 100644 --- a/x/oracle/keeper/querier.go +++ b/x/oracle/keeper/querier.go @@ -68,41 +68,6 @@ func (q querier) ExchangeRates(c context.Context, _ *types.QueryExchangeRatesReq return &types.QueryExchangeRatesResponse{ExchangeRates: exchangeRates}, nil } -// TobinTax queries tobin tax of a pair -func (q querier) TobinTax(c context.Context, req *types.QueryTobinTaxRequest) (*types.QueryTobinTaxResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - if len(req.Pair) == 0 { - return nil, status.Error(codes.InvalidArgument, "empty pair") - } - - ctx := sdk.UnwrapSDKContext(c) - tobinTax, err := q.GetTobinTax(ctx, req.Pair) - if err != nil { - return nil, err - } - - return &types.QueryTobinTaxResponse{TobinTax: tobinTax}, nil -} - -// TobinTaxes queries tobin taxes of all pairs -func (q querier) TobinTaxes(c context.Context, _ *types.QueryTobinTaxesRequest) (*types.QueryTobinTaxesResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - var tobinTaxes types.PairList - q.IterateTobinTaxes(ctx, func(pair string, rate sdk.Dec) (stop bool) { - tobinTaxes = append(tobinTaxes, types.Pair{ - Name: pair, - TobinTax: rate, - }) - return false - }) - - return &types.QueryTobinTaxesResponse{TobinTaxes: tobinTaxes}, nil -} - // Actives queries all pairs for which exchange rates exist func (q querier) Actives(c context.Context, _ *types.QueryActivesRequest) (*types.QueryActivesResponse, error) { ctx := sdk.UnwrapSDKContext(c) diff --git a/x/oracle/keeper/querier_test.go b/x/oracle/keeper/querier_test.go index 844611443..b4ba3d6d3 100644 --- a/x/oracle/keeper/querier_test.go +++ b/x/oracle/keeper/querier_test.go @@ -235,59 +235,15 @@ func TestQueryVoteTargets(t *testing.T) { ctx := sdk.WrapSDKContext(input.Ctx) querier := NewQuerier(input.OracleKeeper) - // clear tobin taxes - input.OracleKeeper.ClearTobinTaxes(input.Ctx) + // clear pairs + input.OracleKeeper.ClearPairs(input.Ctx) voteTargets := []string{"denom", "denom2", "denom3"} for _, target := range voteTargets { - input.OracleKeeper.SetTobinTax(input.Ctx, target, sdk.OneDec()) + input.OracleKeeper.SetPair(input.Ctx, target) } res, err := querier.VoteTargets(ctx, &types.QueryVoteTargetsRequest{}) require.NoError(t, err) require.Equal(t, voteTargets, res.VoteTargets) } - -func TestQueryTobinTaxes(t *testing.T) { - input := CreateTestInput(t) - ctx := sdk.WrapSDKContext(input.Ctx) - querier := NewQuerier(input.OracleKeeper) - - // clear tobin taxes - input.OracleKeeper.ClearTobinTaxes(input.Ctx) - - tobinTaxes := types.PairList{{ - Name: common.PairBTCStable.String(), - TobinTax: sdk.OneDec(), - }, { - Name: common.PairETHStable.String(), - TobinTax: sdk.NewDecWithPrec(123, 2), - }} - for _, item := range tobinTaxes { - input.OracleKeeper.SetTobinTax(input.Ctx, item.Name, item.TobinTax) - } - - res, err := querier.TobinTaxes(ctx, &types.QueryTobinTaxesRequest{}) - require.NoError(t, err) - require.Equal(t, tobinTaxes, res.TobinTaxes) -} - -func TestQueryTobinTax(t *testing.T) { - input := CreateTestInput(t) - ctx := sdk.WrapSDKContext(input.Ctx) - querier := NewQuerier(input.OracleKeeper) - - denom := types.Pair{Name: common.PairBTCStable.String(), TobinTax: sdk.OneDec()} - input.OracleKeeper.SetTobinTax(input.Ctx, denom.Name, denom.TobinTax) - - // empty request - _, err := querier.TobinTax(ctx, nil) - require.Error(t, err) - - res, err := querier.TobinTax(ctx, &types.QueryTobinTaxRequest{ - Pair: common.PairBTCStable.String(), - }) - require.NoError(t, err) - - require.Equal(t, denom.TobinTax, res.TobinTax) -} diff --git a/x/oracle/keeper/reward.go b/x/oracle/keeper/reward.go index a4117a4b7..acacb95da 100644 --- a/x/oracle/keeper/reward.go +++ b/x/oracle/keeper/reward.go @@ -18,7 +18,7 @@ func (k Keeper) RewardBallotWinners( ctx sdk.Context, votePeriod int64, rewardDistributionWindow int64, - voteTargets map[string]sdk.Dec, + voteTargets map[string]struct{}, ballotWinners map[string]types.Claim, ) { rewardDenoms := make([]string, len(voteTargets)+1) diff --git a/x/oracle/keeper/reward_test.go b/x/oracle/keeper/reward_test.go index a71845ec7..62d4f88f8 100644 --- a/x/oracle/keeper/reward_test.go +++ b/x/oracle/keeper/reward_test.go @@ -44,7 +44,7 @@ func TestRewardBallotWinners(t *testing.T) { require.NoError(t, err) voteTargets := make(map[string]sdk.Dec) - input.OracleKeeper.IterateTobinTaxes(ctx, func(denom string, tobinTax sdk.Dec) bool { + input.OracleKeeper.IteratePairs(ctx, func(denom string, tobinTax sdk.Dec) bool { voteTargets[denom] = tobinTax return false }) diff --git a/x/oracle/keeper/test_utils.go b/x/oracle/keeper/test_utils.go index edeef016e..904dc4c71 100644 --- a/x/oracle/keeper/test_utils.go +++ b/x/oracle/keeper/test_utils.go @@ -238,7 +238,7 @@ func CreateTestInput(t *testing.T) TestInput { keeper.SetParams(ctx, defaults) for _, denom := range defaults.Whitelist { - keeper.SetTobinTax(ctx, denom.Name, denom.TobinTax) + keeper.SetPair(ctx, denom.Name) } return TestInput{ctx, legacyAmino, accountKeeper, bankKeeper, keeper, stakingKeeper, distrKeeper} diff --git a/x/oracle/keeper/vote_target.go b/x/oracle/keeper/vote_target.go index 96930ed80..6a977386e 100644 --- a/x/oracle/keeper/vote_target.go +++ b/x/oracle/keeper/vote_target.go @@ -4,13 +4,12 @@ import sdk "github.com/cosmos/cosmos-sdk/types" // IsVoteTarget returns existence of a pair in the voting target list func (k Keeper) IsVoteTarget(ctx sdk.Context, pair string) bool { - _, err := k.GetTobinTax(ctx, pair) - return err == nil + return k.PairExists(ctx, pair) } // GetVoteTargets returns the voting target list on current vote period func (k Keeper) GetVoteTargets(ctx sdk.Context) (voteTargets []string) { - k.IterateTobinTaxes(ctx, func(pair string, _ sdk.Dec) bool { + k.IteratePairs(ctx, func(pair string) bool { voteTargets = append(voteTargets, pair) return false }) diff --git a/x/oracle/keeper/vote_target_test.go b/x/oracle/keeper/vote_target_test.go index 252323c09..631e755a7 100644 --- a/x/oracle/keeper/vote_target_test.go +++ b/x/oracle/keeper/vote_target_test.go @@ -4,18 +4,16 @@ import ( "testing" "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" ) func TestKeeper_GetVoteTargets(t *testing.T) { input := CreateTestInput(t) - input.OracleKeeper.ClearTobinTaxes(input.Ctx) + input.OracleKeeper.ClearPairs(input.Ctx) expectedTargets := []string{"bar", "foo", "whoowhoo"} for _, target := range expectedTargets { - input.OracleKeeper.SetTobinTax(input.Ctx, target, sdk.OneDec()) + input.OracleKeeper.SetPair(input.Ctx, target) } targets := input.OracleKeeper.GetVoteTargets(input.Ctx) @@ -25,11 +23,11 @@ func TestKeeper_GetVoteTargets(t *testing.T) { func TestKeeper_IsVoteTarget(t *testing.T) { input := CreateTestInput(t) - input.OracleKeeper.ClearTobinTaxes(input.Ctx) + input.OracleKeeper.ClearPairs(input.Ctx) validTargets := []string{"bar", "foo", "whoowhoo"} for _, target := range validTargets { - input.OracleKeeper.SetTobinTax(input.Ctx, target, sdk.OneDec()) + input.OracleKeeper.SetPair(input.Ctx, target) require.True(t, input.OracleKeeper.IsVoteTarget(input.Ctx, target)) } } diff --git a/x/oracle/simulation/decoder.go b/x/oracle/simulation/decoder.go index b90d8bea7..29e12cb41 100644 --- a/x/oracle/simulation/decoder.go +++ b/x/oracle/simulation/decoder.go @@ -40,11 +40,8 @@ func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { cdc.MustUnmarshal(kvA.Value, &voteA) cdc.MustUnmarshal(kvB.Value, &voteB) return fmt.Sprintf("%v\n%v", voteA, voteB) - case bytes.Equal(kvA.Key[:1], types.TobinTaxKey): - var tobinTaxA, tobinTaxB sdk.DecProto - cdc.MustUnmarshal(kvA.Value, &tobinTaxA) - cdc.MustUnmarshal(kvB.Value, &tobinTaxB) - return fmt.Sprintf("%v\n%v", tobinTaxA, tobinTaxB) + case bytes.Equal(kvA.Key[:1], types.PairsKey): + return fmt.Sprintf("%s\n%s", types.ExtractPairFromPairKey(kvA.Key), types.ExtractPairFromPairKey(kvB.Key)) default: panic(fmt.Sprintf("invalid oracle key prefix %X", kvA.Key[:1])) } diff --git a/x/oracle/simulation/decoder_test.go b/x/oracle/simulation/decoder_test.go index b6b8dc724..49e42f04b 100644 --- a/x/oracle/simulation/decoder_test.go +++ b/x/oracle/simulation/decoder_test.go @@ -34,11 +34,11 @@ func TestDecodeDistributionStore(t *testing.T) { aggregatePrevote := types.NewAggregateExchangeRatePrevote(types.AggregateVoteHash([]byte("12345")), valAddr, 123) aggregateVote := types.NewAggregateExchangeRateVote(types.ExchangeRateTuples{ - {Pair: common.DenomStable, ExchangeRate: sdk.NewDecWithPrec(1234, 1)}, - {Pair: common.DenomStable, ExchangeRate: sdk.NewDecWithPrec(4321, 1)}, + {Pair: common.PairGovStable.String(), ExchangeRate: sdk.NewDecWithPrec(1234, 1)}, + {Pair: common.PairETHStable.String(), ExchangeRate: sdk.NewDecWithPrec(4321, 1)}, }, valAddr) - tobinTax := sdk.NewDecWithPrec(2, 2) + pair := "btc:usd" kvPairs := kv.Pairs{ Pairs: []kv.Pair{ @@ -47,7 +47,7 @@ func TestDecodeDistributionStore(t *testing.T) { {Key: types.MissCounterKey, Value: cdc.MustMarshal(&gogotypes.UInt64Value{Value: missCounter})}, {Key: types.AggregateExchangeRatePrevoteKey, Value: cdc.MustMarshal(&aggregatePrevote)}, {Key: types.AggregateExchangeRateVoteKey, Value: cdc.MustMarshal(&aggregateVote)}, - {Key: types.TobinTaxKey, Value: cdc.MustMarshal(&sdk.DecProto{Dec: tobinTax})}, + {Key: types.GetPairKey(pair), Value: []byte{}}, {Key: []byte{0x99}, Value: []byte{0x99}}, }, } @@ -61,7 +61,7 @@ func TestDecodeDistributionStore(t *testing.T) { {"MissCounter", fmt.Sprintf("%v\n%v", missCounter, missCounter)}, {"AggregatePrevote", fmt.Sprintf("%v\n%v", aggregatePrevote, aggregatePrevote)}, {"AggregateVote", fmt.Sprintf("%v\n%v", aggregateVote, aggregateVote)}, - {"TobinTax", fmt.Sprintf("%v\n%v", tobinTax, tobinTax)}, + {"Pairs", fmt.Sprintf("%s\n%s", pair, pair)}, {"other", ""}, } diff --git a/x/oracle/simulation/genesis.go b/x/oracle/simulation/genesis.go index 0bd2a0f81..b50c89655 100644 --- a/x/oracle/simulation/genesis.go +++ b/x/oracle/simulation/genesis.go @@ -112,10 +112,11 @@ func RandomizedGenState(simState *module.SimulationState) { RewardBand: rewardBand, RewardDistributionWindow: rewardDistributionWindow, Whitelist: types.PairList{ - {Name: common.PairETHStable.String(), TobinTax: types.DefaultTobinTax}, - {Name: common.PairCollStable.String(), TobinTax: types.DefaultTobinTax}, - {Name: common.PairBTCStable.String(), TobinTax: types.DefaultTobinTax}, - {Name: common.PairGovStable.String(), TobinTax: sdk.NewDecWithPrec(2, 2)}}, + {Name: common.PairETHStable.String()}, + {Name: common.PairCollStable.String()}, + {Name: common.PairBTCStable.String()}, + {Name: common.PairGovStable.String()}, + }, SlashFraction: slashFraction, SlashWindow: slashWindow, MinValidPerWindow: minValidPerWindow, @@ -125,7 +126,7 @@ func RandomizedGenState(simState *module.SimulationState) { []types.MissCounter{}, []types.AggregateExchangeRatePrevote{}, []types.AggregateExchangeRateVote{}, - []types.TobinTax{}, + []types.Pair{}, ) bz, err := json.MarshalIndent(&oracleGenesis.Params, "", " ") diff --git a/x/oracle/spec/06_params.md b/x/oracle/spec/06_params.md index a95d3dbe5..00b02a854 100644 --- a/x/oracle/spec/06_params.md +++ b/x/oracle/spec/06_params.md @@ -13,7 +13,7 @@ The market module contains the following parameters: | votethreshold | string (dec) | "0.500000000000000000" | | rewardband | string (dec) | "0.020000000000000000" | | rewarddistributionwindow | string (int) | "5256000" | -| whitelist | []PairList | [{"name": "unibi:unusd", tobin_tax": "0.002000000000000000"}] | +| whitelist | []PairList | [{"name": "unibi:unusd"}] | | slashfraction | string (dec) | "0.001000000000000000" | | slashwindow | string (int) | "100800" | | minvalidperwindow | string (int) | "0.050000000000000000" | diff --git a/x/oracle/spec/README.md b/x/oracle/spec/README.md index 8f89a2faa..2d8b2f554 100644 --- a/x/oracle/spec/README.md +++ b/x/oracle/spec/README.md @@ -21,7 +21,7 @@ As price information is extrinsic to the blockchain, the Nibiru network relies o - [MissCounter](02_state.md#MissCounter) - [AggregateExchangeRatePrevote](02_state.md#AggregateExchangeRatePrevote) - [AggregateExchangeRateVote](02_state.md#AggregateExchangeRateVote) - - [TobinTax](02_state.md#TobinTax) + - [Pair](02_state.md#Pair) 3. **[EndBlock](03_end_block.md)** - [Tally Exchange Rate Votes](03_end_block.md#Tally-Exchange-Rate-Votes) 4. **[Messages](04_messages.md)** diff --git a/x/oracle/tally.go b/x/oracle/tally.go index 19be12db1..cbada8761 100644 --- a/x/oracle/tally.go +++ b/x/oracle/tally.go @@ -45,7 +45,7 @@ func ballotIsPassing(ballot types.ExchangeRateBallot, thresholdVotes sdk.Int) (s // PickReferencePair choose Reference pair with the highest voter turnout // If the voting power of the two denominations is the same, // select reference pair in alphabetical order. -func PickReferencePair(ctx sdk.Context, k keeper.Keeper, voteTargets map[string]sdk.Dec, voteMap map[string]types.ExchangeRateBallot) string { +func PickReferencePair(ctx sdk.Context, k keeper.Keeper, voteTargets map[string]struct{}, voteMap map[string]types.ExchangeRateBallot) string { largestBallotPower := int64(0) referencePair := "" diff --git a/x/oracle/tally_fuzz_test.go b/x/oracle/tally_fuzz_test.go index f33296c41..4fffb24d4 100644 --- a/x/oracle/tally_fuzz_test.go +++ b/x/oracle/tally_fuzz_test.go @@ -126,7 +126,7 @@ func TestFuzz_PickReferencePair(t *testing.T) { input, _ := setup(t) - voteTargets := map[string]sdk.Dec{} + voteTargets := map[string]struct{}{} f.Fuzz(&voteTargets) voteMap := map[string]types.ExchangeRateBallot{} diff --git a/x/oracle/types/errors.go b/x/oracle/types/errors.go index 0fa3fe99e..c3f866118 100644 --- a/x/oracle/types/errors.go +++ b/x/oracle/types/errors.go @@ -21,6 +21,5 @@ var ( ErrInvalidSaltLength = sdkerrors.Register(ModuleName, 10, "invalid salt length; should be 1~4") ErrNoAggregatePrevote = sdkerrors.Register(ModuleName, 11, "no aggregate prevote") ErrNoAggregateVote = sdkerrors.Register(ModuleName, 12, "no aggregate vote") - ErrNoTobinTax = sdkerrors.Register(ModuleName, 13, "no tobin tax") - ErrUnknownPair = sdkerrors.Register(ModuleName, 14, "unknown pair") + ErrUnknownPair = sdkerrors.Register(ModuleName, 13, "unknown pair") ) diff --git a/x/oracle/types/genesis.go b/x/oracle/types/genesis.go index c6b959033..baacaca8e 100644 --- a/x/oracle/types/genesis.go +++ b/x/oracle/types/genesis.go @@ -12,7 +12,7 @@ func NewGenesisState( feederDelegations []FeederDelegation, missCounters []MissCounter, aggregateExchangeRatePrevotes []AggregateExchangeRatePrevote, aggregateExchangeRateVotes []AggregateExchangeRateVote, - TobinTaxes []TobinTax, + pairs []Pair, ) *GenesisState { return &GenesisState{ Params: params, @@ -21,11 +21,11 @@ func NewGenesisState( MissCounters: missCounters, AggregateExchangeRatePrevotes: aggregateExchangeRatePrevotes, AggregateExchangeRateVotes: aggregateExchangeRateVotes, - TobinTaxes: TobinTaxes, + Pairs: pairs, } } -// DefaultGenesisState - default GenesisState used by columbus-2 +// DefaultGenesisState - default GenesisState func DefaultGenesisState() *GenesisState { return NewGenesisState(DefaultParams(), []ExchangeRateTuple{}, @@ -33,7 +33,7 @@ func DefaultGenesisState() *GenesisState { []MissCounter{}, []AggregateExchangeRatePrevote{}, []AggregateExchangeRateVote{}, - []TobinTax{}) + []Pair{}) } // ValidateGenesis validates the oracle genesis state diff --git a/x/oracle/types/genesis.pb.go b/x/oracle/types/genesis.pb.go index 874696aef..598491a71 100644 --- a/x/oracle/types/genesis.pb.go +++ b/x/oracle/types/genesis.pb.go @@ -6,7 +6,6 @@ package types import ( fmt "fmt" _ "github.com/cosmos/cosmos-sdk/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" @@ -33,7 +32,7 @@ type GenesisState struct { MissCounters []MissCounter `protobuf:"bytes,4,rep,name=miss_counters,json=missCounters,proto3" json:"miss_counters"` AggregateExchangeRatePrevotes []AggregateExchangeRatePrevote `protobuf:"bytes,5,rep,name=aggregate_exchange_rate_prevotes,json=aggregateExchangeRatePrevotes,proto3" json:"aggregate_exchange_rate_prevotes"` AggregateExchangeRateVotes []AggregateExchangeRateVote `protobuf:"bytes,6,rep,name=aggregate_exchange_rate_votes,json=aggregateExchangeRateVotes,proto3" json:"aggregate_exchange_rate_votes"` - TobinTaxes []TobinTax `protobuf:"bytes,7,rep,name=tobin_taxes,json=tobinTaxes,proto3" json:"tobin_taxes"` + Pairs []Pair `protobuf:"bytes,7,rep,name=pairs,proto3" json:"pairs"` } func (m *GenesisState) Reset() { *m = GenesisState{} } @@ -111,9 +110,9 @@ func (m *GenesisState) GetAggregateExchangeRateVotes() []AggregateExchangeRateVo return nil } -func (m *GenesisState) GetTobinTaxes() []TobinTax { +func (m *GenesisState) GetPairs() []Pair { if m != nil { - return m.TobinTaxes + return m.Pairs } return nil } @@ -227,100 +226,48 @@ func (m *MissCounter) GetMissCounter() uint64 { return 0 } -// TobinTax defines a pair and tobin_tax pair used in -// oracle module's genesis state -type TobinTax struct { - Pair string `protobuf:"bytes,1,opt,name=pair,proto3" json:"pair,omitempty"` - TobinTax github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=tobin_tax,json=tobinTax,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"tobin_tax"` -} - -func (m *TobinTax) Reset() { *m = TobinTax{} } -func (m *TobinTax) String() string { return proto.CompactTextString(m) } -func (*TobinTax) ProtoMessage() {} -func (*TobinTax) Descriptor() ([]byte, []int) { - return fileDescriptor_6d8ee91da7d45482, []int{3} -} -func (m *TobinTax) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TobinTax) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TobinTax.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TobinTax) XXX_Merge(src proto.Message) { - xxx_messageInfo_TobinTax.Merge(m, src) -} -func (m *TobinTax) XXX_Size() int { - return m.Size() -} -func (m *TobinTax) XXX_DiscardUnknown() { - xxx_messageInfo_TobinTax.DiscardUnknown(m) -} - -var xxx_messageInfo_TobinTax proto.InternalMessageInfo - -func (m *TobinTax) GetPair() string { - if m != nil { - return m.Pair - } - return "" -} - func init() { proto.RegisterType((*GenesisState)(nil), "nibiru.oracle.v1beta1.GenesisState") proto.RegisterType((*FeederDelegation)(nil), "nibiru.oracle.v1beta1.FeederDelegation") proto.RegisterType((*MissCounter)(nil), "nibiru.oracle.v1beta1.MissCounter") - proto.RegisterType((*TobinTax)(nil), "nibiru.oracle.v1beta1.TobinTax") } func init() { proto.RegisterFile("oracle/v1beta1/genesis.proto", fileDescriptor_6d8ee91da7d45482) } var fileDescriptor_6d8ee91da7d45482 = []byte{ - // 569 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xc1, 0x6e, 0xd3, 0x40, - 0x10, 0x86, 0xe3, 0x36, 0x2d, 0xed, 0xa6, 0xad, 0xda, 0x15, 0x48, 0x51, 0xa0, 0x4e, 0x89, 0x04, - 0x54, 0x02, 0x6c, 0xda, 0x1e, 0x39, 0x35, 0x2d, 0xe5, 0x80, 0x8a, 0x2a, 0x53, 0x71, 0x40, 0x20, - 0x6b, 0x6d, 0x4f, 0xdd, 0x55, 0x13, 0xaf, 0xe5, 0xd9, 0x54, 0xe9, 0x95, 0x27, 0xe0, 0x39, 0x90, - 0x78, 0x8f, 0x1e, 0x7b, 0x44, 0x1c, 0x0a, 0x4a, 0x5e, 0x04, 0x79, 0x77, 0x93, 0x98, 0x10, 0x23, - 0x71, 0x8a, 0x33, 0xf3, 0xcd, 0xff, 0xcf, 0xec, 0x8e, 0x4d, 0x1e, 0x88, 0x8c, 0x85, 0x1d, 0x70, - 0x2f, 0x77, 0x02, 0x90, 0x6c, 0xc7, 0x8d, 0x21, 0x01, 0xe4, 0xe8, 0xa4, 0x99, 0x90, 0x82, 0xde, - 0x4b, 0x78, 0xc0, 0xb3, 0x9e, 0xa3, 0x21, 0xc7, 0x40, 0x8d, 0xbb, 0xb1, 0x88, 0x85, 0x22, 0xdc, - 0xfc, 0x49, 0xc3, 0x8d, 0xfb, 0x53, 0x52, 0xa6, 0x48, 0x27, 0xed, 0x50, 0x60, 0x57, 0xa0, 0x1b, - 0x30, 0x9c, 0x10, 0xa1, 0xe0, 0x89, 0xce, 0xb7, 0xbe, 0x2d, 0x90, 0x95, 0xd7, 0xda, 0xfb, 0x9d, - 0x64, 0x12, 0xe8, 0x4b, 0xb2, 0x98, 0xb2, 0x8c, 0x75, 0xb1, 0x6e, 0x6d, 0x59, 0xdb, 0xb5, 0xdd, - 0x4d, 0x67, 0x66, 0x2f, 0xce, 0x89, 0x82, 0xda, 0xd5, 0xeb, 0xdb, 0x66, 0xc5, 0x33, 0x25, 0xf4, - 0x23, 0xa1, 0x67, 0x00, 0x11, 0x64, 0x7e, 0x04, 0x1d, 0x88, 0x99, 0xe4, 0x22, 0xc1, 0xfa, 0xdc, - 0xd6, 0xfc, 0x76, 0x6d, 0xf7, 0x49, 0x89, 0xd0, 0x91, 0x2a, 0x38, 0x1c, 0xf3, 0x46, 0x72, 0xe3, - 0x6c, 0x2a, 0x8e, 0xf4, 0x82, 0xac, 0x41, 0x3f, 0x3c, 0x67, 0x49, 0x0c, 0x7e, 0xc6, 0x24, 0x60, - 0x7d, 0x5e, 0x29, 0x6f, 0x97, 0x28, 0xbf, 0x32, 0xb0, 0xc7, 0x24, 0x9c, 0xf6, 0xd2, 0x0e, 0xb4, - 0x1b, 0xb9, 0xf4, 0xd7, 0x9f, 0x4d, 0xfa, 0x57, 0x0a, 0xbd, 0x55, 0x28, 0xc4, 0x90, 0x1e, 0x93, - 0xd5, 0x2e, 0x47, 0xf4, 0x43, 0xd1, 0x4b, 0x24, 0x64, 0x58, 0xaf, 0x2a, 0xaf, 0x56, 0x89, 0xd7, - 0x31, 0x47, 0x3c, 0xd0, 0xa8, 0x19, 0x60, 0xa5, 0x3b, 0x09, 0x21, 0xfd, 0x6c, 0x91, 0x2d, 0x16, - 0xc7, 0x59, 0x3e, 0x0c, 0xf8, 0x7f, 0x8c, 0xe1, 0xa7, 0x19, 0x5c, 0x8a, 0x7c, 0x9c, 0x05, 0x65, - 0xb1, 0x57, 0x62, 0xb1, 0x3f, 0x2a, 0x2f, 0x36, 0x7f, 0xa2, 0x6b, 0x8d, 0xe7, 0x26, 0xfb, 0x07, - 0x83, 0xf4, 0x8a, 0x6c, 0x96, 0xf5, 0xa0, 0x1b, 0x58, 0x54, 0x0d, 0xbc, 0xf8, 0x9f, 0x06, 0xde, - 0x4f, 0xdc, 0x1b, 0xac, 0x0c, 0x40, 0x7a, 0x44, 0x6a, 0x52, 0x04, 0x3c, 0xf1, 0x25, 0xeb, 0x03, - 0xd6, 0xef, 0x28, 0xa3, 0x66, 0x89, 0xd1, 0x69, 0x4e, 0x9e, 0xb2, 0xbe, 0xd1, 0x25, 0xd2, 0xfc, - 0x07, 0x6c, 0x9d, 0x91, 0xf5, 0xe9, 0x85, 0xa1, 0x8f, 0xc8, 0x9a, 0xd9, 0x3a, 0x16, 0x45, 0x19, - 0xa0, 0x5e, 0xdd, 0x65, 0x6f, 0x55, 0x47, 0xf7, 0x75, 0x90, 0x3e, 0x25, 0x1b, 0x97, 0xac, 0xc3, - 0x23, 0x26, 0xc5, 0x84, 0x9c, 0x53, 0xe4, 0xfa, 0x38, 0x61, 0xe0, 0xd6, 0x27, 0x52, 0x2b, 0x5c, - 0xe9, 0xec, 0x5a, 0x6b, 0x76, 0x2d, 0x7d, 0x48, 0x56, 0x8a, 0xab, 0xa3, 0x3c, 0xaa, 0x5e, 0xad, - 0xb0, 0x0f, 0xad, 0x0b, 0xb2, 0x34, 0x1a, 0x92, 0x52, 0x52, 0x4d, 0x19, 0xcf, 0x8c, 0x9c, 0x7a, - 0xa6, 0x6f, 0xc8, 0xf2, 0xf8, 0xb8, 0x74, 0x8f, 0x6d, 0x27, 0x3f, 0x8b, 0x1f, 0xb7, 0xcd, 0xc7, - 0x31, 0x97, 0xe7, 0xbd, 0xc0, 0x09, 0x45, 0xd7, 0x35, 0x2f, 0xb7, 0xfe, 0x79, 0x8e, 0xd1, 0x85, - 0x2b, 0xaf, 0x52, 0x40, 0xe7, 0x10, 0x42, 0x6f, 0x69, 0x74, 0x6a, 0xed, 0xa3, 0xeb, 0x81, 0x6d, - 0xdd, 0x0c, 0x6c, 0xeb, 0xd7, 0xc0, 0xb6, 0xbe, 0x0c, 0xed, 0xca, 0xcd, 0xd0, 0xae, 0x7c, 0x1f, - 0xda, 0x95, 0x0f, 0xcf, 0x0a, 0x5a, 0x6f, 0xd5, 0x55, 0x1c, 0x9c, 0x33, 0x9e, 0xb8, 0xfa, 0x5a, - 0xdc, 0xbe, 0xf9, 0x96, 0x68, 0xd5, 0x60, 0x51, 0x7d, 0x32, 0xf6, 0x7e, 0x07, 0x00, 0x00, 0xff, - 0xff, 0x7c, 0x61, 0x66, 0xd3, 0xbc, 0x04, 0x00, 0x00, + // 509 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x93, 0xc1, 0x6e, 0xd3, 0x40, + 0x10, 0x86, 0xe3, 0x36, 0x09, 0x62, 0x93, 0x54, 0xed, 0x0a, 0xa4, 0x28, 0x25, 0x6e, 0x88, 0x84, + 0x88, 0x04, 0xb2, 0x69, 0x7b, 0xe0, 0xc0, 0xa9, 0x29, 0x94, 0x53, 0x51, 0x15, 0x10, 0x07, 0x04, + 0x8a, 0x36, 0xf6, 0xc4, 0x59, 0x11, 0x7b, 0xad, 0x9d, 0x4d, 0xd4, 0x5e, 0x79, 0x02, 0x9e, 0x80, + 0x07, 0xe0, 0x49, 0x7a, 0xec, 0x91, 0x13, 0xa0, 0xe4, 0x45, 0x50, 0x76, 0xb7, 0x8d, 0x09, 0x31, + 0x52, 0x6f, 0xd6, 0xcc, 0xf7, 0xcf, 0x3f, 0x33, 0x9e, 0x25, 0x0f, 0x84, 0x64, 0xc1, 0x18, 0xfc, + 0xe9, 0xfe, 0x00, 0x14, 0xdb, 0xf7, 0x23, 0x48, 0x00, 0x39, 0x7a, 0xa9, 0x14, 0x4a, 0xd0, 0xfb, + 0x09, 0x1f, 0x70, 0x39, 0xf1, 0x0c, 0xe4, 0x59, 0xa8, 0x71, 0x2f, 0x12, 0x91, 0xd0, 0x84, 0xbf, + 0xf8, 0x32, 0x70, 0x63, 0x77, 0xa5, 0x94, 0x15, 0x99, 0xa4, 0x1b, 0x08, 0x8c, 0x05, 0xfa, 0x03, + 0x86, 0x4b, 0x22, 0x10, 0x3c, 0x31, 0xf9, 0xf6, 0xb7, 0x12, 0xa9, 0xbe, 0x36, 0xde, 0x6f, 0x15, + 0x53, 0x40, 0x5f, 0x90, 0x72, 0xca, 0x24, 0x8b, 0xb1, 0xee, 0xb4, 0x9c, 0x4e, 0xe5, 0xa0, 0xe9, + 0xad, 0xed, 0xc5, 0x3b, 0xd3, 0x50, 0xb7, 0x78, 0xf9, 0x73, 0xaf, 0xd0, 0xb3, 0x12, 0xfa, 0x91, + 0xd0, 0x21, 0x40, 0x08, 0xb2, 0x1f, 0xc2, 0x18, 0x22, 0xa6, 0xb8, 0x48, 0xb0, 0xbe, 0xd1, 0xda, + 0xec, 0x54, 0x0e, 0x1e, 0xe7, 0x14, 0x3a, 0xd1, 0x82, 0x97, 0x37, 0xbc, 0x2d, 0xb9, 0x33, 0x5c, + 0x89, 0x23, 0xfd, 0x4c, 0xb6, 0xe0, 0x3c, 0x18, 0xb1, 0x24, 0x82, 0xbe, 0x64, 0x0a, 0xb0, 0xbe, + 0xa9, 0x2b, 0x77, 0x72, 0x2a, 0xbf, 0xb2, 0x70, 0x8f, 0x29, 0x78, 0x37, 0x49, 0xc7, 0xd0, 0x6d, + 0x2c, 0x4a, 0x7f, 0xff, 0xb5, 0x47, 0xff, 0x49, 0x61, 0xaf, 0x06, 0x99, 0x18, 0xd2, 0x53, 0x52, + 0x8b, 0x39, 0x62, 0x3f, 0x10, 0x93, 0x44, 0x81, 0xc4, 0x7a, 0x51, 0x7b, 0xb5, 0x73, 0xbc, 0x4e, + 0x39, 0xe2, 0xb1, 0x41, 0xed, 0x00, 0xd5, 0x78, 0x19, 0x42, 0xfa, 0xc5, 0x21, 0x2d, 0x16, 0x45, + 0x72, 0x31, 0x0c, 0xf4, 0xff, 0x1a, 0xa3, 0x9f, 0x4a, 0x98, 0x8a, 0xc5, 0x38, 0x25, 0x6d, 0x71, + 0x98, 0x63, 0x71, 0x74, 0x2d, 0xcf, 0x36, 0x7f, 0x66, 0xb4, 0xd6, 0xb3, 0xc9, 0xfe, 0xc3, 0x20, + 0xbd, 0x20, 0xcd, 0xbc, 0x1e, 0x4c, 0x03, 0x65, 0xdd, 0xc0, 0xb3, 0xdb, 0x34, 0xf0, 0x7e, 0xe9, + 0xde, 0x60, 0x79, 0x00, 0xd2, 0xe7, 0xa4, 0x94, 0x32, 0x2e, 0xb1, 0x7e, 0x47, 0x5b, 0xec, 0xe6, + 0x5e, 0x15, 0xbf, 0xde, 0x9f, 0xe1, 0xdb, 0x43, 0xb2, 0xbd, 0x7a, 0x21, 0xf4, 0x11, 0xd9, 0xb2, + 0x67, 0xc6, 0xc2, 0x50, 0x02, 0x9a, 0x5b, 0xbd, 0xdb, 0xab, 0x99, 0xe8, 0x91, 0x09, 0xd2, 0x27, + 0x64, 0x67, 0xca, 0xc6, 0x3c, 0x64, 0x4a, 0x2c, 0xc9, 0x0d, 0x4d, 0x6e, 0xdf, 0x24, 0x2c, 0xdc, + 0xfe, 0x44, 0x2a, 0x99, 0x7f, 0xb8, 0x5e, 0xeb, 0xac, 0xd7, 0xd2, 0x87, 0xa4, 0x9a, 0xbd, 0x15, + 0xed, 0x51, 0xec, 0x55, 0x32, 0x07, 0xd0, 0x3d, 0xb9, 0x9c, 0xb9, 0xce, 0xd5, 0xcc, 0x75, 0x7e, + 0xcf, 0x5c, 0xe7, 0xeb, 0xdc, 0x2d, 0x5c, 0xcd, 0xdd, 0xc2, 0x8f, 0xb9, 0x5b, 0xf8, 0xf0, 0x34, + 0xe2, 0x6a, 0x34, 0x19, 0x78, 0x81, 0x88, 0xfd, 0x37, 0x7a, 0x29, 0xc7, 0x23, 0xc6, 0x13, 0xdf, + 0x2c, 0xc8, 0x3f, 0xb7, 0xef, 0xd9, 0x57, 0x17, 0x29, 0xe0, 0xa0, 0xac, 0x9f, 0xed, 0xe1, 0x9f, + 0x00, 0x00, 0x00, 0xff, 0xff, 0xe0, 0x3d, 0x9d, 0x94, 0x40, 0x04, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { @@ -343,10 +290,10 @@ func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.TobinTaxes) > 0 { - for iNdEx := len(m.TobinTaxes) - 1; iNdEx >= 0; iNdEx-- { + if len(m.Pairs) > 0 { + for iNdEx := len(m.Pairs) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.TobinTaxes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Pairs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -512,46 +459,6 @@ func (m *MissCounter) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *TobinTax) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TobinTax) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TobinTax) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TobinTax.Size() - i -= size - if _, err := m.TobinTax.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Pair) > 0 { - i -= len(m.Pair) - copy(dAtA[i:], m.Pair) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Pair))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { offset -= sovGenesis(v) base := offset @@ -601,8 +508,8 @@ func (m *GenesisState) Size() (n int) { n += 1 + l + sovGenesis(uint64(l)) } } - if len(m.TobinTaxes) > 0 { - for _, e := range m.TobinTaxes { + if len(m.Pairs) > 0 { + for _, e := range m.Pairs { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } @@ -643,21 +550,6 @@ func (m *MissCounter) Size() (n int) { return n } -func (m *TobinTax) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Pair) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.TobinTax.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - func sovGenesis(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -898,7 +790,7 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 7: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TobinTaxes", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Pairs", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -925,8 +817,8 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.TobinTaxes = append(m.TobinTaxes, TobinTax{}) - if err := m.TobinTaxes[len(m.TobinTaxes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Pairs = append(m.Pairs, Pair{}) + if err := m.Pairs[len(m.Pairs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -1166,122 +1058,6 @@ func (m *MissCounter) Unmarshal(dAtA []byte) error { } return nil } -func (m *TobinTax) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TobinTax: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TobinTax: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Pair = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TobinTax", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TobinTax.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} func skipGenesis(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/oracle/types/keys.go b/x/oracle/types/keys.go index 6094646f1..2e037ce34 100644 --- a/x/oracle/types/keys.go +++ b/x/oracle/types/keys.go @@ -38,9 +38,9 @@ var ( ExchangeRateKey = []byte{0x01} // prefix for each key to a rate FeederDelegationKey = []byte{0x02} // prefix for each key to a feeder delegation MissCounterKey = []byte{0x03} // prefix for each key to a miss counter - AggregateExchangeRatePrevoteKey = []byte{0x04} // prefix for each key to a aggregate prevote - AggregateExchangeRateVoteKey = []byte{0x05} // prefix for each key to a aggregate vote - TobinTaxKey = []byte{0x06} // prefix for each key to a tobin tax + AggregateExchangeRatePrevoteKey = []byte{0x04} // prefix for each key to an aggregate prevote + AggregateExchangeRateVoteKey = []byte{0x05} // prefix for each key to an aggregate vote + PairsKey = []byte{0x06} // prefix for each key to a pair ) // GetExchangeRateKey - stored by *pair* @@ -68,13 +68,13 @@ func GetAggregateExchangeRateVoteKey(v sdk.ValAddress) []byte { return append(AggregateExchangeRateVoteKey, address.MustLengthPrefix(v)...) } -// GetTobinTaxKey - stored by *pair* bytes -func GetTobinTaxKey(d string) []byte { - return append(TobinTaxKey, append([]byte(d), 0x00)...) +// GetPairKey - stored by *pair* bytes +func GetPairKey(d string) []byte { + return append(PairsKey, append([]byte(d), 0x00)...) } -// ExtractPairFromTobinTaxKey - split pair from the tobin tax key -func ExtractPairFromTobinTaxKey(key []byte) (pair string) { +// ExtractPairFromPairKey - split pair from the pair key +func ExtractPairFromPairKey(key []byte) (pair string) { pair = string(key[1 : len(key)-1]) return } diff --git a/x/oracle/types/oracle.pb.go b/x/oracle/types/oracle.pb.go index 6a3b1f6d0..4def9f4f2 100644 --- a/x/oracle/types/oracle.pb.go +++ b/x/oracle/types/oracle.pb.go @@ -99,8 +99,7 @@ func (m *Params) GetSlashWindow() uint64 { // Pair is the object that holds configuration of each pair. type Pair struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty" yaml:"name"` - TobinTax github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=tobin_tax,json=tobinTax,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"tobin_tax" yaml:"tobin_tax"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty" yaml:"name"` } func (m *Pair) Reset() { *m = Pair{} } @@ -264,55 +263,53 @@ func init() { func init() { proto.RegisterFile("oracle/v1beta1/oracle.proto", fileDescriptor_2784fd4b0e83b02f) } var fileDescriptor_2784fd4b0e83b02f = []byte{ - // 763 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0x31, 0x6f, 0xdb, 0x46, - 0x14, 0x16, 0x6b, 0x59, 0x95, 0x4f, 0x72, 0x6b, 0xb3, 0x72, 0xcb, 0xda, 0x85, 0xe8, 0x5e, 0x5b, - 0x43, 0x43, 0x2b, 0xc2, 0xed, 0x50, 0x44, 0x5b, 0x18, 0xc7, 0x59, 0x92, 0x40, 0x20, 0x0c, 0x07, - 0xc8, 0x42, 0x1c, 0xc9, 0x8b, 0x78, 0x30, 0xc9, 0x13, 0x8e, 0x27, 0x4b, 0x5e, 0x32, 0x67, 0xcc, - 0x90, 0x00, 0x41, 0x26, 0xcf, 0x59, 0x83, 0xfc, 0x07, 0x8f, 0x1e, 0x83, 0x0c, 0x4c, 0x60, 0x2f, - 0xc9, 0xaa, 0x5f, 0x10, 0xdc, 0xf1, 0x6c, 0x53, 0x96, 0x02, 0x44, 0xc8, 0x24, 0xbe, 0xf7, 0xbd, - 0xfb, 0xde, 0x77, 0xef, 0xe3, 0x13, 0xc1, 0x06, 0x65, 0xc8, 0x8f, 0xb0, 0x75, 0xb8, 0xed, 0x61, - 0x8e, 0xb6, 0xad, 0x3c, 0x6c, 0xf7, 0x19, 0xe5, 0x54, 0x5f, 0x4b, 0x88, 0x47, 0xd8, 0xa0, 0xad, - 0x92, 0xaa, 0x66, 0xbd, 0xd1, 0xa3, 0x3d, 0x2a, 0x2b, 0x2c, 0xf1, 0x94, 0x17, 0xaf, 0x37, 0x7d, - 0x9a, 0xc6, 0x34, 0xb5, 0x3c, 0x94, 0x5e, 0xd1, 0xf9, 0x94, 0x24, 0x39, 0x0e, 0x9f, 0x55, 0x40, - 0xa5, 0x8b, 0x18, 0x8a, 0x53, 0xfd, 0x7f, 0x50, 0x3b, 0xa4, 0x1c, 0xbb, 0x7d, 0xcc, 0x08, 0x0d, - 0x0c, 0x6d, 0x53, 0x6b, 0x95, 0xed, 0x9f, 0xc7, 0x99, 0xa9, 0x1f, 0xa1, 0x38, 0xea, 0xc0, 0x02, - 0x08, 0x1d, 0x20, 0xa2, 0xae, 0x0c, 0xf4, 0x04, 0xfc, 0x20, 0x31, 0x1e, 0x32, 0x9c, 0x86, 0x34, - 0x0a, 0x8c, 0xef, 0x36, 0xb5, 0xd6, 0x92, 0x7d, 0xe7, 0x24, 0x33, 0x4b, 0xef, 0x32, 0x73, 0xab, - 0x47, 0x78, 0x38, 0xf0, 0xda, 0x3e, 0x8d, 0x2d, 0x25, 0x27, 0xff, 0xf9, 0x27, 0x0d, 0x0e, 0x2c, - 0x7e, 0xd4, 0xc7, 0x69, 0x7b, 0x07, 0xfb, 0xe3, 0xcc, 0x5c, 0x2b, 0x74, 0xba, 0x64, 0x83, 0xce, - 0xb2, 0x48, 0xec, 0x5d, 0xc4, 0x3a, 0x06, 0x35, 0x86, 0x87, 0x88, 0x05, 0xae, 0x87, 0x92, 0xc0, - 0x58, 0x90, 0xcd, 0x76, 0xe6, 0x6e, 0xa6, 0xae, 0x55, 0xa0, 0x82, 0x0e, 0xc8, 0x23, 0x1b, 0x25, - 0x81, 0xee, 0x83, 0x75, 0x85, 0x05, 0x24, 0xe5, 0x8c, 0x78, 0x03, 0x4e, 0x68, 0xe2, 0x0e, 0x49, - 0x12, 0xd0, 0xa1, 0x51, 0x96, 0xe3, 0xf9, 0x6b, 0x9c, 0x99, 0xbf, 0x4f, 0xf0, 0xcc, 0xa8, 0x85, - 0x8e, 0x91, 0x83, 0x3b, 0x05, 0xec, 0x81, 0x84, 0x74, 0x17, 0x2c, 0x0d, 0x43, 0xc2, 0x71, 0x44, - 0x52, 0x6e, 0x2c, 0x6e, 0x2e, 0xb4, 0x6a, 0xff, 0x6e, 0xb4, 0x67, 0x1a, 0xdc, 0xee, 0x22, 0xc2, - 0xec, 0x3f, 0xc5, 0x35, 0xc7, 0x99, 0xb9, 0x92, 0x37, 0xbd, 0x3c, 0x0b, 0x5f, 0xbd, 0x37, 0xab, - 0xa2, 0xe2, 0x2e, 0x49, 0xb9, 0x73, 0xc5, 0x29, 0xcc, 0x49, 0x23, 0x94, 0x86, 0xee, 0x23, 0x86, - 0x7c, 0xd1, 0xd8, 0xa8, 0x7c, 0x9b, 0x39, 0x93, 0x6c, 0xd0, 0x59, 0x96, 0x89, 0x5d, 0x15, 0xeb, - 0x1d, 0x50, 0xcf, 0x2b, 0xd4, 0x9c, 0xbe, 0x97, 0x73, 0xfa, 0x65, 0x9c, 0x99, 0x3f, 0x15, 0xcf, - 0x5f, 0x4c, 0xa6, 0x26, 0x43, 0x35, 0x8c, 0xc7, 0xa0, 0x11, 0x93, 0xc4, 0x3d, 0x44, 0x11, 0x09, - 0xc4, 0x9b, 0x76, 0xc1, 0x51, 0x95, 0x8a, 0xef, 0xcd, 0xad, 0x78, 0x23, 0xef, 0x38, 0x8b, 0x13, - 0x3a, 0xab, 0x31, 0x49, 0xf6, 0x45, 0xb6, 0x8b, 0x59, 0xde, 0xbf, 0x53, 0x7d, 0x71, 0x6c, 0x96, - 0x3e, 0x1e, 0x9b, 0x1a, 0x7c, 0xa9, 0x81, 0xb2, 0x98, 0xa6, 0xfe, 0x07, 0x28, 0x27, 0x28, 0xc6, - 0x72, 0x1b, 0x96, 0xec, 0x1f, 0xc7, 0x99, 0x59, 0xcb, 0x49, 0x45, 0x16, 0x3a, 0x12, 0x14, 0x26, - 0x72, 0xea, 0x91, 0xc4, 0xe5, 0x68, 0xa4, 0xde, 0x7d, 0x7b, 0x6e, 0xb1, 0xca, 0xd1, 0x4b, 0x22, - 0xe8, 0x54, 0xe5, 0xf3, 0x1e, 0x1a, 0x75, 0xea, 0x4f, 0x8e, 0xcd, 0x92, 0x12, 0x57, 0x82, 0x6f, - 0x34, 0xf0, 0xdb, 0xcd, 0x5e, 0x8f, 0xe1, 0x1e, 0xe2, 0xf8, 0xf6, 0xc8, 0x0f, 0x51, 0xd2, 0xc3, - 0x0e, 0xe2, 0xb8, 0xcb, 0xb0, 0xd8, 0x14, 0x21, 0x3a, 0x44, 0x69, 0x38, 0x2d, 0x5a, 0x64, 0xa1, - 0x23, 0x41, 0x7d, 0x0b, 0x2c, 0x8a, 0x62, 0xa6, 0x04, 0xaf, 0x8c, 0x33, 0xb3, 0x7e, 0xb5, 0x7e, - 0x0c, 0x3a, 0x39, 0x2c, 0x0d, 0x1d, 0x78, 0x31, 0xe1, 0xae, 0x17, 0x51, 0xff, 0x40, 0xae, 0xdb, - 0xa4, 0xa1, 0x05, 0x54, 0x18, 0x2a, 0x43, 0x5b, 0x44, 0xd7, 0x74, 0x7f, 0xd2, 0xc0, 0xaf, 0x33, - 0x75, 0xef, 0x0b, 0xd1, 0xcf, 0x35, 0xd0, 0xc0, 0x2a, 0xe9, 0x32, 0x24, 0xfe, 0x01, 0x06, 0xfd, - 0x08, 0xa7, 0x86, 0x26, 0xb7, 0xa2, 0xf5, 0x85, 0xad, 0x28, 0xf2, 0xec, 0x89, 0x03, 0xf6, 0x0d, - 0xb5, 0x22, 0xca, 0xfd, 0x59, 0x9c, 0x62, 0x5b, 0xf4, 0xa9, 0x93, 0xa9, 0xa3, 0xe3, 0xa9, 0xdc, - 0xd7, 0xce, 0xe9, 0xda, 0x5d, 0x5f, 0x6b, 0x60, 0x75, 0xaa, 0x81, 0x30, 0xa6, 0x8f, 0x08, 0x9b, - 0x36, 0x46, 0x64, 0xa1, 0x23, 0x41, 0xfd, 0x00, 0x2c, 0x4f, 0x68, 0x56, 0x8d, 0x77, 0xe7, 0x7e, - 0xa3, 0x1a, 0x33, 0x06, 0x00, 0x9d, 0x7a, 0xf1, 0x8e, 0x93, 0xaa, 0xed, 0xdd, 0x93, 0xb3, 0xa6, - 0x76, 0x7a, 0xd6, 0xd4, 0x3e, 0x9c, 0x35, 0xb5, 0xa7, 0xe7, 0xcd, 0xd2, 0xe9, 0x79, 0xb3, 0xf4, - 0xf6, 0xbc, 0x59, 0x7a, 0xf8, 0x77, 0xa1, 0xeb, 0x7d, 0x69, 0xc4, 0xad, 0x10, 0x91, 0xc4, 0xca, - 0x4d, 0xb1, 0x46, 0xea, 0x13, 0x95, 0xf7, 0xf7, 0x2a, 0xf2, 0xe3, 0xf2, 0xdf, 0xe7, 0x00, 0x00, - 0x00, 0xff, 0xff, 0x16, 0xe3, 0xae, 0xaa, 0xc8, 0x06, 0x00, 0x00, + // 734 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0xb1, 0x6f, 0xd3, 0x4a, + 0x18, 0x8f, 0x5f, 0xd3, 0xbc, 0xf6, 0x92, 0xbe, 0xd7, 0xfa, 0xa5, 0x0f, 0xd3, 0xa2, 0xb8, 0x1c, + 0x50, 0x65, 0x80, 0x58, 0x85, 0x01, 0x35, 0x1b, 0xa6, 0x94, 0x05, 0x50, 0x64, 0x55, 0x45, 0x62, + 0xb1, 0xce, 0xf6, 0x11, 0x9f, 0x6a, 0xfb, 0xa2, 0x3b, 0xa7, 0x69, 0x17, 0x66, 0x46, 0x06, 0x90, + 0x18, 0x3b, 0xb3, 0x22, 0xfe, 0x87, 0x8e, 0x1d, 0x11, 0x83, 0x41, 0xed, 0x02, 0x6b, 0xfe, 0x02, + 0x74, 0xe7, 0x6b, 0xeb, 0x34, 0x41, 0xa2, 0x62, 0x4a, 0xbe, 0xef, 0xf7, 0xdd, 0xef, 0xf7, 0xdd, + 0xef, 0xfb, 0x2e, 0x01, 0xcb, 0x94, 0x21, 0x3f, 0xc2, 0xd6, 0xee, 0x9a, 0x87, 0x53, 0xb4, 0x66, + 0xe5, 0x61, 0xab, 0xc7, 0x68, 0x4a, 0xf5, 0xc5, 0x84, 0x78, 0x84, 0xf5, 0x5b, 0x2a, 0xa9, 0x6a, + 0x96, 0xea, 0x5d, 0xda, 0xa5, 0xb2, 0xc2, 0x12, 0xdf, 0xf2, 0xe2, 0xa5, 0x86, 0x4f, 0x79, 0x4c, + 0xb9, 0xe5, 0x21, 0x7e, 0x4e, 0xe7, 0x53, 0x92, 0xe4, 0x38, 0x7c, 0x5b, 0x01, 0x95, 0x0e, 0x62, + 0x28, 0xe6, 0xfa, 0x7d, 0x50, 0xdd, 0xa5, 0x29, 0x76, 0x7b, 0x98, 0x11, 0x1a, 0x18, 0xda, 0x8a, + 0xd6, 0x2c, 0xdb, 0xff, 0x0f, 0x33, 0x53, 0xdf, 0x47, 0x71, 0xd4, 0x86, 0x05, 0x10, 0x3a, 0x40, + 0x44, 0x1d, 0x19, 0xe8, 0x09, 0xf8, 0x47, 0x62, 0x69, 0xc8, 0x30, 0x0f, 0x69, 0x14, 0x18, 0x7f, + 0xad, 0x68, 0xcd, 0x59, 0xfb, 0xf1, 0x61, 0x66, 0x96, 0xbe, 0x64, 0xe6, 0x6a, 0x97, 0xa4, 0x61, + 0xdf, 0x6b, 0xf9, 0x34, 0xb6, 0x54, 0x3b, 0xf9, 0xc7, 0x1d, 0x1e, 0xec, 0x58, 0xe9, 0x7e, 0x0f, + 0xf3, 0xd6, 0x06, 0xf6, 0x87, 0x99, 0xb9, 0x58, 0x50, 0x3a, 0x63, 0x83, 0xce, 0x9c, 0x48, 0x6c, + 0x9d, 0xc6, 0x3a, 0x06, 0x55, 0x86, 0x07, 0x88, 0x05, 0xae, 0x87, 0x92, 0xc0, 0x98, 0x92, 0x62, + 0x1b, 0x97, 0x16, 0x53, 0xd7, 0x2a, 0x50, 0x41, 0x07, 0xe4, 0x91, 0x8d, 0x92, 0x40, 0xf7, 0xc1, + 0x92, 0xc2, 0x02, 0xc2, 0x53, 0x46, 0xbc, 0x7e, 0x4a, 0x68, 0xe2, 0x0e, 0x48, 0x12, 0xd0, 0x81, + 0x51, 0x96, 0xf6, 0xdc, 0x1a, 0x66, 0xe6, 0xf5, 0x11, 0x9e, 0x09, 0xb5, 0xd0, 0x31, 0x72, 0x70, + 0xa3, 0x80, 0x3d, 0x97, 0x90, 0xee, 0x82, 0xd9, 0x41, 0x48, 0x52, 0x1c, 0x11, 0x9e, 0x1a, 0xd3, + 0x2b, 0x53, 0xcd, 0xea, 0xdd, 0xe5, 0xd6, 0xc4, 0x01, 0xb7, 0x3a, 0x88, 0x30, 0xfb, 0xa6, 0xb8, + 0xe6, 0x30, 0x33, 0xe7, 0x73, 0xd1, 0xb3, 0xb3, 0xf0, 0xc3, 0x57, 0x73, 0x46, 0x54, 0x3c, 0x21, + 0x3c, 0x75, 0xce, 0x39, 0xc5, 0x70, 0x78, 0x84, 0x78, 0xe8, 0xbe, 0x64, 0xc8, 0x17, 0xc2, 0x46, + 0xe5, 0xcf, 0x86, 0x33, 0xca, 0x06, 0x9d, 0x39, 0x99, 0xd8, 0x54, 0xb1, 0xde, 0x06, 0xb5, 0xbc, + 0x42, 0xf9, 0xf4, 0xb7, 0xf4, 0xe9, 0xca, 0x30, 0x33, 0xff, 0x2b, 0x9e, 0x3f, 0x75, 0xa6, 0x2a, + 0x43, 0x65, 0xc6, 0x2b, 0x50, 0x8f, 0x49, 0xe2, 0xee, 0xa2, 0x88, 0x04, 0x62, 0xd3, 0x4e, 0x39, + 0x66, 0x64, 0xc7, 0x4f, 0x2f, 0xdd, 0xf1, 0x72, 0xae, 0x38, 0x89, 0x13, 0x3a, 0x0b, 0x31, 0x49, + 0xb6, 0x45, 0xb6, 0x83, 0x59, 0xae, 0xdf, 0x9e, 0x79, 0x7f, 0x60, 0x96, 0xbe, 0x1f, 0x98, 0x1a, + 0x5c, 0x07, 0x65, 0x61, 0xa6, 0x7e, 0x03, 0x94, 0x13, 0x14, 0x63, 0xf9, 0x18, 0x66, 0xed, 0x7f, + 0x87, 0x99, 0x59, 0xcd, 0x39, 0x45, 0x16, 0x3a, 0x12, 0x6c, 0xd7, 0x5e, 0x1f, 0x98, 0x25, 0x75, + 0xb4, 0x04, 0x3f, 0x69, 0xe0, 0xda, 0x83, 0x6e, 0x97, 0xe1, 0x2e, 0x4a, 0xf1, 0xa3, 0x3d, 0x3f, + 0x44, 0x49, 0x17, 0x3b, 0x28, 0xc5, 0x1d, 0x86, 0xc5, 0x1e, 0x0b, 0xce, 0x10, 0xf1, 0x70, 0x9c, + 0x53, 0x64, 0xa1, 0x23, 0x41, 0x7d, 0x15, 0x4c, 0x8b, 0x62, 0xa6, 0x9e, 0xd2, 0xfc, 0x30, 0x33, + 0x6b, 0xe7, 0x8f, 0x83, 0x41, 0x27, 0x87, 0xa5, 0xdd, 0x7d, 0x2f, 0x26, 0xa9, 0xeb, 0x45, 0xd4, + 0xdf, 0x91, 0x8f, 0x61, 0xd4, 0xee, 0x02, 0x2a, 0xec, 0x96, 0xa1, 0x2d, 0xa2, 0x0b, 0x7d, 0xff, + 0xd0, 0xc0, 0xd5, 0x89, 0x7d, 0x6f, 0x8b, 0xa6, 0xdf, 0x69, 0xa0, 0x8e, 0x55, 0xd2, 0x65, 0x48, + 0xbc, 0xcf, 0x7e, 0x2f, 0xc2, 0xdc, 0xd0, 0xe4, 0xce, 0x36, 0x7f, 0xb1, 0xb3, 0x45, 0x9e, 0x2d, + 0x71, 0xc0, 0x5e, 0x57, 0x0b, 0xac, 0x66, 0x33, 0x89, 0x53, 0xec, 0xb2, 0x3e, 0x76, 0x92, 0x3b, + 0x3a, 0x1e, 0xcb, 0xfd, 0xae, 0x4f, 0x17, 0xee, 0xfa, 0x51, 0x03, 0x0b, 0x63, 0x02, 0x62, 0x30, + 0x3d, 0x44, 0xd8, 0xf8, 0x60, 0x44, 0x16, 0x3a, 0x12, 0xd4, 0x77, 0xc0, 0xdc, 0x48, 0xcf, 0x4a, + 0x78, 0xf3, 0xd2, 0xcb, 0x59, 0x9f, 0x60, 0x00, 0x74, 0x6a, 0xc5, 0x3b, 0x8e, 0x76, 0x6d, 0x6f, + 0x1e, 0x1e, 0x37, 0xb4, 0xa3, 0xe3, 0x86, 0xf6, 0xed, 0xb8, 0xa1, 0xbd, 0x39, 0x69, 0x94, 0x8e, + 0x4e, 0x1a, 0xa5, 0xcf, 0x27, 0x8d, 0xd2, 0x8b, 0xdb, 0x05, 0xd5, 0x67, 0x72, 0x10, 0x0f, 0x43, + 0x44, 0x12, 0x2b, 0x1f, 0x8a, 0xb5, 0xa7, 0xfe, 0x40, 0x72, 0x7d, 0xaf, 0x22, 0x7f, 0xfa, 0xef, + 0xfd, 0x0c, 0x00, 0x00, 0xff, 0xff, 0x25, 0xf3, 0xda, 0xb8, 0x66, 0x06, 0x00, 0x00, } func (this *Params) Equal(that interface{}) bool { @@ -477,16 +474,6 @@ func (m *Pair) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - { - size := m.TobinTax.Size() - i -= size - if _, err := m.TobinTax.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintOracle(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 if len(m.Name) > 0 { i -= len(m.Name) copy(dAtA[i:], m.Name) @@ -676,8 +663,6 @@ func (m *Pair) Size() (n int) { if l > 0 { n += 1 + l + sovOracle(uint64(l)) } - l = m.TobinTax.Size() - n += 1 + l + sovOracle(uint64(l)) return n } @@ -1079,40 +1064,6 @@ func (m *Pair) Unmarshal(dAtA []byte) error { } m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TobinTax", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOracle - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOracle - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthOracle - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TobinTax.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipOracle(dAtA[iNdEx:]) diff --git a/x/oracle/types/pair_list.go b/x/oracle/types/pair_list.go index 7b7a26f4f..24e1ef816 100644 --- a/x/oracle/types/pair_list.go +++ b/x/oracle/types/pair_list.go @@ -14,7 +14,7 @@ func (m Pair) String() string { // Equal implements equal interface func (m Pair) Equal(pair *Pair) bool { - return m.Name == pair.Name && m.TobinTax.Equal(pair.TobinTax) + return m.Name == pair.Name } // PairList is array of Pair diff --git a/x/oracle/types/params.go b/x/oracle/types/params.go index 6a4be1271..6f85d0f82 100644 --- a/x/oracle/types/params.go +++ b/x/oracle/types/params.go @@ -38,23 +38,18 @@ const ( var ( DefaultVoteThreshold = sdk.NewDecWithPrec(50, 2) // 50% DefaultRewardBand = sdk.NewDecWithPrec(2, 2) // 2% (-1, 1) - DefaultTobinTax = sdk.NewDecWithPrec(25, 4) // 0.25% DefaultWhitelist = PairList{ { - Name: common.PairBTCStable.String(), - TobinTax: DefaultTobinTax, + Name: common.PairBTCStable.String(), }, { - Name: common.PairCollStable.String(), - TobinTax: DefaultTobinTax, + Name: common.PairCollStable.String(), }, { - Name: common.PairETHStable.String(), - TobinTax: DefaultTobinTax, + Name: common.PairETHStable.String(), }, { - Name: common.PairGovStable.String(), - TobinTax: DefaultTobinTax, + Name: common.PairGovStable.String(), }, } DefaultSlashFraction = sdk.NewDecWithPrec(1, 4) // 0.01% @@ -133,11 +128,8 @@ func (p Params) Validate() error { } for _, pair := range p.Whitelist { - if pair.TobinTax.GT(sdk.OneDec()) || pair.TobinTax.IsNegative() { - return fmt.Errorf("oracle parameter Whitelist Pair must have TobinTax between [0, 1]") - } - if len(pair.Name) == 0 { - return fmt.Errorf("oracle parameter Whitelist Pair must have name") + if _, err := common.NewAssetPair(pair.Name); err != nil { + return fmt.Errorf("oracle parameter Whitelist Pair invalid format: %w", err) } } return nil @@ -210,11 +202,8 @@ func validateWhitelist(i interface{}) error { } for _, d := range v { - if d.TobinTax.GT(sdk.OneDec()) || d.TobinTax.IsNegative() { - return fmt.Errorf("oracle parameter Whitelist Pair must have TobinTax between [0, 1]") - } - if len(d.Name) == 0 { - return fmt.Errorf("oracle parameter Whitelist Pair must have name") + if _, err := common.NewAssetPair(d.Name); err != nil { + return fmt.Errorf("oracle parameter Whitelist Pair invalid format: %w", err) } } diff --git a/x/oracle/types/params_test.go b/x/oracle/types/params_test.go index 8f72daf0f..406c31387 100644 --- a/x/oracle/types/params_test.go +++ b/x/oracle/types/params_test.go @@ -57,18 +57,6 @@ func TestParamsEqual(t *testing.T) { err = p7.Validate() require.Error(t, err) - // non-positive tobin tax - p8 := types.DefaultParams() - p8.Whitelist[0].Name = "" - err = p8.Validate() - require.Error(t, err) - - // invalid name tobin tax - p9 := types.DefaultParams() - p9.Whitelist[0].TobinTax = sdk.NewDec(-1) - err = p9.Validate() - require.Error(t, err) - // empty name p10 := types.DefaultParams() p10.Whitelist[0].Name = "" @@ -106,27 +94,13 @@ func TestValidate(t *testing.T) { case bytes.Equal(types.KeyWhitelist, pair.Key): require.NoError(t, pair.ValidatorFn(types.PairList{ { - Name: "BTC:USDT", - TobinTax: sdk.NewDecWithPrec(10, 2), + Name: "BTC:USDT", }, })) require.Error(t, pair.ValidatorFn("invalid")) require.Error(t, pair.ValidatorFn(types.PairList{ { - Name: "", - TobinTax: sdk.NewDecWithPrec(10, 2), - }, - })) - require.Error(t, pair.ValidatorFn(types.PairList{ - { - Name: "BTC:USD", - TobinTax: sdk.NewDecWithPrec(101, 2), - }, - })) - require.Error(t, pair.ValidatorFn(types.PairList{ - { - Name: "BTC:BTC", - TobinTax: sdk.NewDecWithPrec(-1, 2), + Name: "", }, })) } diff --git a/x/oracle/types/query.pb.go b/x/oracle/types/query.pb.go index 2f249e698..e1ee9f576 100644 --- a/x/oracle/types/query.pb.go +++ b/x/oracle/types/query.pb.go @@ -194,169 +194,6 @@ func (m *QueryExchangeRatesResponse) GetExchangeRates() ExchangeRateTuples { return nil } -// QueryTobinTaxRequest is the request type for the Query/TobinTax RPC method. -type QueryTobinTaxRequest struct { - // pair defines the asset to query for. - Pair string `protobuf:"bytes,1,opt,name=pair,proto3" json:"pair,omitempty"` -} - -func (m *QueryTobinTaxRequest) Reset() { *m = QueryTobinTaxRequest{} } -func (m *QueryTobinTaxRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTobinTaxRequest) ProtoMessage() {} -func (*QueryTobinTaxRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{4} -} -func (m *QueryTobinTaxRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTobinTaxRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTobinTaxRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTobinTaxRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTobinTaxRequest.Merge(m, src) -} -func (m *QueryTobinTaxRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTobinTaxRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTobinTaxRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTobinTaxRequest proto.InternalMessageInfo - -// QueryTobinTaxResponse is response type for the -// Query/TobinTax RPC method. -type QueryTobinTaxResponse struct { - // tobin_taxe defines the tobin tax of a pair - TobinTax github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=tobin_tax,json=tobinTax,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"tobin_tax"` -} - -func (m *QueryTobinTaxResponse) Reset() { *m = QueryTobinTaxResponse{} } -func (m *QueryTobinTaxResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTobinTaxResponse) ProtoMessage() {} -func (*QueryTobinTaxResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{5} -} -func (m *QueryTobinTaxResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTobinTaxResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTobinTaxResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTobinTaxResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTobinTaxResponse.Merge(m, src) -} -func (m *QueryTobinTaxResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTobinTaxResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTobinTaxResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTobinTaxResponse proto.InternalMessageInfo - -// QueryTobinTaxesRequest is the request type for the Query/TobinTaxes RPC method. -type QueryTobinTaxesRequest struct { -} - -func (m *QueryTobinTaxesRequest) Reset() { *m = QueryTobinTaxesRequest{} } -func (m *QueryTobinTaxesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTobinTaxesRequest) ProtoMessage() {} -func (*QueryTobinTaxesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{6} -} -func (m *QueryTobinTaxesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTobinTaxesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTobinTaxesRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTobinTaxesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTobinTaxesRequest.Merge(m, src) -} -func (m *QueryTobinTaxesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTobinTaxesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTobinTaxesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTobinTaxesRequest proto.InternalMessageInfo - -// QueryTobinTaxesResponse is response type for the -// Query/TobinTaxes RPC method. -type QueryTobinTaxesResponse struct { - // tobin_taxes defines a list of the tobin tax of all whitelisted pairs - TobinTaxes PairList `protobuf:"bytes,1,rep,name=tobin_taxes,json=tobinTaxes,proto3,castrepeated=PairList" json:"tobin_taxes" yaml:"tobin_taxes"` -} - -func (m *QueryTobinTaxesResponse) Reset() { *m = QueryTobinTaxesResponse{} } -func (m *QueryTobinTaxesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTobinTaxesResponse) ProtoMessage() {} -func (*QueryTobinTaxesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{7} -} -func (m *QueryTobinTaxesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTobinTaxesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTobinTaxesResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTobinTaxesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTobinTaxesResponse.Merge(m, src) -} -func (m *QueryTobinTaxesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTobinTaxesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTobinTaxesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTobinTaxesResponse proto.InternalMessageInfo - -func (m *QueryTobinTaxesResponse) GetTobinTaxes() PairList { - if m != nil { - return m.TobinTaxes - } - return nil -} - // QueryActivesRequest is the request type for the Query/Actives RPC method. type QueryActivesRequest struct { } @@ -365,7 +202,7 @@ func (m *QueryActivesRequest) Reset() { *m = QueryActivesRequest{} } func (m *QueryActivesRequest) String() string { return proto.CompactTextString(m) } func (*QueryActivesRequest) ProtoMessage() {} func (*QueryActivesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{8} + return fileDescriptor_812803c014dfa45a, []int{4} } func (m *QueryActivesRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -405,7 +242,7 @@ func (m *QueryActivesResponse) Reset() { *m = QueryActivesResponse{} } func (m *QueryActivesResponse) String() string { return proto.CompactTextString(m) } func (*QueryActivesResponse) ProtoMessage() {} func (*QueryActivesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{9} + return fileDescriptor_812803c014dfa45a, []int{5} } func (m *QueryActivesResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -449,7 +286,7 @@ func (m *QueryVoteTargetsRequest) Reset() { *m = QueryVoteTargetsRequest func (m *QueryVoteTargetsRequest) String() string { return proto.CompactTextString(m) } func (*QueryVoteTargetsRequest) ProtoMessage() {} func (*QueryVoteTargetsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{10} + return fileDescriptor_812803c014dfa45a, []int{6} } func (m *QueryVoteTargetsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -490,7 +327,7 @@ func (m *QueryVoteTargetsResponse) Reset() { *m = QueryVoteTargetsRespon func (m *QueryVoteTargetsResponse) String() string { return proto.CompactTextString(m) } func (*QueryVoteTargetsResponse) ProtoMessage() {} func (*QueryVoteTargetsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{11} + return fileDescriptor_812803c014dfa45a, []int{7} } func (m *QueryVoteTargetsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -536,7 +373,7 @@ func (m *QueryFeederDelegationRequest) Reset() { *m = QueryFeederDelegat func (m *QueryFeederDelegationRequest) String() string { return proto.CompactTextString(m) } func (*QueryFeederDelegationRequest) ProtoMessage() {} func (*QueryFeederDelegationRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{12} + return fileDescriptor_812803c014dfa45a, []int{8} } func (m *QueryFeederDelegationRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -576,7 +413,7 @@ func (m *QueryFeederDelegationResponse) Reset() { *m = QueryFeederDelega func (m *QueryFeederDelegationResponse) String() string { return proto.CompactTextString(m) } func (*QueryFeederDelegationResponse) ProtoMessage() {} func (*QueryFeederDelegationResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{13} + return fileDescriptor_812803c014dfa45a, []int{9} } func (m *QueryFeederDelegationResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -622,7 +459,7 @@ func (m *QueryMissCounterRequest) Reset() { *m = QueryMissCounterRequest func (m *QueryMissCounterRequest) String() string { return proto.CompactTextString(m) } func (*QueryMissCounterRequest) ProtoMessage() {} func (*QueryMissCounterRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{14} + return fileDescriptor_812803c014dfa45a, []int{10} } func (m *QueryMissCounterRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -662,7 +499,7 @@ func (m *QueryMissCounterResponse) Reset() { *m = QueryMissCounterRespon func (m *QueryMissCounterResponse) String() string { return proto.CompactTextString(m) } func (*QueryMissCounterResponse) ProtoMessage() {} func (*QueryMissCounterResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{15} + return fileDescriptor_812803c014dfa45a, []int{11} } func (m *QueryMissCounterResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -708,7 +545,7 @@ func (m *QueryAggregatePrevoteRequest) Reset() { *m = QueryAggregatePrev func (m *QueryAggregatePrevoteRequest) String() string { return proto.CompactTextString(m) } func (*QueryAggregatePrevoteRequest) ProtoMessage() {} func (*QueryAggregatePrevoteRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{16} + return fileDescriptor_812803c014dfa45a, []int{12} } func (m *QueryAggregatePrevoteRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -748,7 +585,7 @@ func (m *QueryAggregatePrevoteResponse) Reset() { *m = QueryAggregatePre func (m *QueryAggregatePrevoteResponse) String() string { return proto.CompactTextString(m) } func (*QueryAggregatePrevoteResponse) ProtoMessage() {} func (*QueryAggregatePrevoteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{17} + return fileDescriptor_812803c014dfa45a, []int{13} } func (m *QueryAggregatePrevoteResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -792,7 +629,7 @@ func (m *QueryAggregatePrevotesRequest) Reset() { *m = QueryAggregatePre func (m *QueryAggregatePrevotesRequest) String() string { return proto.CompactTextString(m) } func (*QueryAggregatePrevotesRequest) ProtoMessage() {} func (*QueryAggregatePrevotesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{18} + return fileDescriptor_812803c014dfa45a, []int{14} } func (m *QueryAggregatePrevotesRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -832,7 +669,7 @@ func (m *QueryAggregatePrevotesResponse) Reset() { *m = QueryAggregatePr func (m *QueryAggregatePrevotesResponse) String() string { return proto.CompactTextString(m) } func (*QueryAggregatePrevotesResponse) ProtoMessage() {} func (*QueryAggregatePrevotesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{19} + return fileDescriptor_812803c014dfa45a, []int{15} } func (m *QueryAggregatePrevotesResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -878,7 +715,7 @@ func (m *QueryAggregateVoteRequest) Reset() { *m = QueryAggregateVoteReq func (m *QueryAggregateVoteRequest) String() string { return proto.CompactTextString(m) } func (*QueryAggregateVoteRequest) ProtoMessage() {} func (*QueryAggregateVoteRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{20} + return fileDescriptor_812803c014dfa45a, []int{16} } func (m *QueryAggregateVoteRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -918,7 +755,7 @@ func (m *QueryAggregateVoteResponse) Reset() { *m = QueryAggregateVoteRe func (m *QueryAggregateVoteResponse) String() string { return proto.CompactTextString(m) } func (*QueryAggregateVoteResponse) ProtoMessage() {} func (*QueryAggregateVoteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{21} + return fileDescriptor_812803c014dfa45a, []int{17} } func (m *QueryAggregateVoteResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -962,7 +799,7 @@ func (m *QueryAggregateVotesRequest) Reset() { *m = QueryAggregateVotesR func (m *QueryAggregateVotesRequest) String() string { return proto.CompactTextString(m) } func (*QueryAggregateVotesRequest) ProtoMessage() {} func (*QueryAggregateVotesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{22} + return fileDescriptor_812803c014dfa45a, []int{18} } func (m *QueryAggregateVotesRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1002,7 +839,7 @@ func (m *QueryAggregateVotesResponse) Reset() { *m = QueryAggregateVotes func (m *QueryAggregateVotesResponse) String() string { return proto.CompactTextString(m) } func (*QueryAggregateVotesResponse) ProtoMessage() {} func (*QueryAggregateVotesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{23} + return fileDescriptor_812803c014dfa45a, []int{19} } func (m *QueryAggregateVotesResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1046,7 +883,7 @@ func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } func (*QueryParamsRequest) ProtoMessage() {} func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{24} + return fileDescriptor_812803c014dfa45a, []int{20} } func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1085,7 +922,7 @@ func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } func (*QueryParamsResponse) ProtoMessage() {} func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_812803c014dfa45a, []int{25} + return fileDescriptor_812803c014dfa45a, []int{21} } func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1126,10 +963,6 @@ func init() { proto.RegisterType((*QueryExchangeRateResponse)(nil), "nibiru.oracle.v1beta1.QueryExchangeRateResponse") proto.RegisterType((*QueryExchangeRatesRequest)(nil), "nibiru.oracle.v1beta1.QueryExchangeRatesRequest") proto.RegisterType((*QueryExchangeRatesResponse)(nil), "nibiru.oracle.v1beta1.QueryExchangeRatesResponse") - proto.RegisterType((*QueryTobinTaxRequest)(nil), "nibiru.oracle.v1beta1.QueryTobinTaxRequest") - proto.RegisterType((*QueryTobinTaxResponse)(nil), "nibiru.oracle.v1beta1.QueryTobinTaxResponse") - proto.RegisterType((*QueryTobinTaxesRequest)(nil), "nibiru.oracle.v1beta1.QueryTobinTaxesRequest") - proto.RegisterType((*QueryTobinTaxesResponse)(nil), "nibiru.oracle.v1beta1.QueryTobinTaxesResponse") proto.RegisterType((*QueryActivesRequest)(nil), "nibiru.oracle.v1beta1.QueryActivesRequest") proto.RegisterType((*QueryActivesResponse)(nil), "nibiru.oracle.v1beta1.QueryActivesResponse") proto.RegisterType((*QueryVoteTargetsRequest)(nil), "nibiru.oracle.v1beta1.QueryVoteTargetsRequest") @@ -1153,84 +986,75 @@ func init() { func init() { proto.RegisterFile("oracle/v1beta1/query.proto", fileDescriptor_812803c014dfa45a) } var fileDescriptor_812803c014dfa45a = []byte{ - // 1225 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x98, 0x4d, 0x6f, 0x1b, 0x45, - 0x18, 0xc7, 0x3d, 0x10, 0xd2, 0xe4, 0x71, 0x1c, 0x92, 0x21, 0x81, 0x74, 0x93, 0xd8, 0x65, 0x45, - 0xa3, 0x34, 0x2f, 0xde, 0xbc, 0x15, 0x48, 0x0b, 0x82, 0xbc, 0x10, 0x09, 0x08, 0x10, 0x4c, 0x94, - 0x03, 0x12, 0xb2, 0xc6, 0xf6, 0xd4, 0x59, 0xd5, 0xf6, 0xba, 0x3b, 0x63, 0x2b, 0x51, 0x54, 0x90, - 0x38, 0xf0, 0x76, 0xaa, 0xc4, 0x15, 0xa4, 0x72, 0xa4, 0x42, 0x42, 0xe2, 0x03, 0x00, 0xc7, 0x4a, - 0x5c, 0x2a, 0x71, 0x41, 0x08, 0xa5, 0x28, 0xe1, 0xc0, 0x99, 0x4f, 0x80, 0x76, 0x76, 0x76, 0xbd, - 0x6b, 0xef, 0x6e, 0xd7, 0xee, 0xc9, 0xce, 0xcc, 0xf3, 0xf2, 0x7b, 0xfe, 0xb3, 0x3b, 0xcf, 0xe3, - 0x80, 0x62, 0x98, 0xa4, 0x58, 0xa1, 0x5a, 0x73, 0xb9, 0x40, 0x39, 0x59, 0xd6, 0x6e, 0x35, 0xa8, - 0x79, 0x9c, 0xad, 0x9b, 0x06, 0x37, 0xf0, 0x78, 0x4d, 0x2f, 0xe8, 0x66, 0x23, 0x6b, 0x9b, 0x64, - 0xa5, 0x89, 0x32, 0x56, 0x36, 0xca, 0x86, 0xb0, 0xd0, 0xac, 0x6f, 0xb6, 0xb1, 0x32, 0x55, 0x36, - 0x8c, 0x72, 0x85, 0x6a, 0xa4, 0xae, 0x6b, 0xa4, 0x56, 0x33, 0x38, 0xe1, 0xba, 0x51, 0x63, 0x72, - 0x77, 0xb2, 0x2d, 0x8d, 0x0c, 0x69, 0x6f, 0xa6, 0x8b, 0x06, 0xab, 0x1a, 0x4c, 0x2b, 0x10, 0xd6, - 0xb2, 0x28, 0x1a, 0x7a, 0xcd, 0xde, 0x57, 0x5f, 0x86, 0x89, 0xf7, 0x2d, 0xac, 0x37, 0x8e, 0x8a, - 0x87, 0xa4, 0x56, 0xa6, 0x39, 0xc2, 0x69, 0x8e, 0xde, 0x6a, 0x50, 0xc6, 0x31, 0x86, 0xbe, 0x3a, - 0xd1, 0xcd, 0x09, 0x74, 0x09, 0xcd, 0x0e, 0xe6, 0xc4, 0xf7, 0x6b, 0x03, 0x5f, 0xdc, 0xcd, 0x24, - 0xfe, 0xbd, 0x9b, 0x49, 0xa8, 0x75, 0xb8, 0x18, 0xe0, 0xc9, 0xea, 0x46, 0x8d, 0x51, 0xfc, 0x01, - 0xa4, 0xa8, 0x5c, 0xcf, 0x9b, 0x84, 0x53, 0x3b, 0xc6, 0x66, 0xf6, 0xfe, 0x69, 0x26, 0xf1, 0xe7, - 0x69, 0x66, 0xa6, 0xac, 0xf3, 0xc3, 0x46, 0x21, 0x5b, 0x34, 0xaa, 0x9a, 0x04, 0xb4, 0x3f, 0x16, - 0x59, 0xe9, 0xa6, 0xc6, 0x8f, 0xeb, 0x94, 0x65, 0xb7, 0x69, 0x31, 0x37, 0x44, 0x3d, 0xc1, 0xd5, - 0xc9, 0x80, 0x8c, 0x4c, 0xc2, 0xaa, 0x5f, 0x22, 0x50, 0x82, 0x76, 0x25, 0xd0, 0x4d, 0x18, 0xf6, - 0x01, 0xb1, 0x09, 0x74, 0xe9, 0xc9, 0xd9, 0xe4, 0xca, 0x6c, 0x36, 0xf0, 0x20, 0xb2, 0xde, 0x28, - 0xfb, 0x8d, 0x7a, 0x85, 0x6e, 0x2a, 0x16, 0xfb, 0xbd, 0x87, 0x19, 0xdc, 0xb1, 0xc5, 0x72, 0x29, - 0x2f, 0x27, 0x53, 0xd7, 0x60, 0x4c, 0xa0, 0xec, 0x1b, 0x05, 0xbd, 0xb6, 0x4f, 0x8e, 0xe2, 0x09, - 0x5a, 0x82, 0xf1, 0x36, 0x2f, 0xc9, 0xfe, 0x36, 0x0c, 0x72, 0x6b, 0x2d, 0xcf, 0xc9, 0x51, 0x8f, - 0x42, 0x0e, 0x70, 0x19, 0x54, 0x9d, 0x80, 0x67, 0x7d, 0x59, 0x5a, 0x0a, 0x7e, 0x02, 0xcf, 0x75, - 0xec, 0x48, 0x82, 0x12, 0x24, 0x5d, 0x02, 0x57, 0xba, 0xc9, 0x10, 0xe9, 0xf6, 0x88, 0x6e, 0x6e, - 0xce, 0x58, 0x80, 0xff, 0x9d, 0x66, 0xf0, 0x31, 0xa9, 0x56, 0xae, 0xa9, 0x1e, 0x6f, 0xf5, 0xde, - 0xc3, 0xcc, 0x80, 0x65, 0xb3, 0xab, 0x33, 0x9e, 0x03, 0xee, 0x66, 0x53, 0xc7, 0xe1, 0x19, 0x01, - 0xb0, 0x51, 0xe4, 0x7a, 0xb3, 0xc5, 0xb5, 0x24, 0xd5, 0x74, 0x97, 0x25, 0xd4, 0x04, 0x5c, 0x20, - 0xf6, 0x92, 0x00, 0x1a, 0xcc, 0x39, 0x7f, 0xaa, 0x17, 0x65, 0x25, 0x07, 0x06, 0xa7, 0xfb, 0xc4, - 0x2c, 0x53, 0xee, 0x06, 0x7b, 0x55, 0x3e, 0xef, 0xbe, 0x2d, 0x19, 0xf0, 0x79, 0x18, 0x6a, 0x1a, - 0x9c, 0xe6, 0xb9, 0xbd, 0x2e, 0xa3, 0x26, 0x9b, 0x2d, 0x53, 0xf5, 0x3d, 0x98, 0x12, 0xee, 0x3b, - 0x94, 0x96, 0xa8, 0xb9, 0x4d, 0x2b, 0xb4, 0x2c, 0xde, 0x45, 0xe7, 0x84, 0x2f, 0xc3, 0x70, 0x93, - 0x54, 0xf4, 0x12, 0xe1, 0x86, 0x99, 0x27, 0xa5, 0x92, 0x73, 0xd6, 0x29, 0x77, 0x75, 0xa3, 0x54, - 0xf2, 0x1e, 0xfa, 0xeb, 0x30, 0x1d, 0x12, 0x50, 0x42, 0x65, 0x20, 0x79, 0x43, 0xec, 0x79, 0xc3, - 0x81, 0xbd, 0x64, 0xc5, 0x52, 0xdf, 0x92, 0xc5, 0xbe, 0xa3, 0x33, 0xb6, 0x65, 0x34, 0x6a, 0x9c, - 0x9a, 0x3d, 0xd3, 0x38, 0xea, 0xf8, 0x62, 0xb5, 0xd4, 0xa9, 0xea, 0x8c, 0xe5, 0x8b, 0xf6, 0xba, - 0x08, 0xd5, 0x97, 0x4b, 0x56, 0x5b, 0xa6, 0xae, 0x3a, 0x1b, 0xe5, 0xb2, 0x69, 0xd5, 0x41, 0xf7, - 0x4c, 0x6a, 0xa9, 0xd7, 0x33, 0xcf, 0xe7, 0x48, 0xca, 0xd3, 0x19, 0x51, 0x52, 0xdd, 0x80, 0x51, - 0xe2, 0xec, 0xe5, 0xeb, 0xf6, 0xa6, 0x88, 0x9a, 0x5c, 0x59, 0x0d, 0x79, 0x3e, 0xdd, 0x58, 0xde, - 0x17, 0x59, 0xc6, 0xdd, 0xec, 0xb3, 0x9e, 0xdb, 0xdc, 0x08, 0x69, 0xcb, 0xa7, 0x66, 0x42, 0x40, - 0xdc, 0x07, 0xeb, 0x2b, 0x04, 0xe9, 0x30, 0x0b, 0xc9, 0x7a, 0x08, 0xb8, 0x83, 0xd5, 0x79, 0x99, - 0x1e, 0x03, 0x76, 0xb4, 0x1d, 0x96, 0xa9, 0xbb, 0xf2, 0xa6, 0x74, 0xbd, 0x0f, 0x1e, 0xe7, 0x14, - 0x4e, 0xe4, 0xcd, 0xda, 0x16, 0x4d, 0x56, 0xf5, 0x11, 0x0c, 0xb7, 0xaa, 0xf2, 0xc8, 0xbf, 0xd4, - 0x4d, 0x45, 0x07, 0xad, 0x72, 0x52, 0xc4, 0x9b, 0x46, 0x9d, 0x0a, 0x4a, 0xee, 0xaa, 0xfe, 0x31, - 0x4c, 0x06, 0xee, 0x4a, 0xb6, 0x3c, 0x3c, 0xed, 0x67, 0x73, 0xe4, 0xee, 0x15, 0x6e, 0xd8, 0x07, - 0xc7, 0xd4, 0x31, 0xc0, 0x22, 0xff, 0x1e, 0x31, 0x49, 0xd5, 0xa5, 0xca, 0xc9, 0x8b, 0xcc, 0x59, - 0x95, 0x34, 0xd7, 0xa1, 0xbf, 0x2e, 0x56, 0xa4, 0x42, 0xd3, 0xa1, 0x17, 0xa8, 0x65, 0x24, 0x33, - 0x4a, 0x97, 0x95, 0xbf, 0x46, 0xe1, 0x29, 0x11, 0x14, 0xff, 0x80, 0x60, 0xc8, 0x8b, 0x87, 0xb5, - 0x90, 0x38, 0x61, 0x8d, 0x5d, 0x59, 0x8a, 0xef, 0x60, 0xa3, 0xab, 0xeb, 0x9f, 0xfe, 0xfe, 0xcf, - 0xd7, 0x4f, 0xac, 0xe2, 0x65, 0xcd, 0xf6, 0xd4, 0xda, 0x66, 0x0e, 0xab, 0x95, 0x31, 0xed, 0xc4, - 0xfa, 0xb8, 0xad, 0xf9, 0x1a, 0x2d, 0xfe, 0x1e, 0x41, 0xca, 0xd7, 0x93, 0x71, 0xec, 0xf4, 0x8e, - 0xa0, 0xca, 0x72, 0x17, 0x1e, 0x92, 0x78, 0x55, 0x10, 0x2f, 0xe2, 0xf9, 0x48, 0x62, 0xff, 0x4c, - 0x80, 0xbf, 0x41, 0x30, 0xe0, 0xb4, 0x3f, 0x3c, 0x1f, 0x95, 0xb4, 0xad, 0xb5, 0x2b, 0x0b, 0xf1, - 0x8c, 0x25, 0xdc, 0x55, 0x01, 0xa7, 0xe1, 0xc5, 0x38, 0x72, 0xba, 0xbd, 0x13, 0x7f, 0x8b, 0x00, - 0x5a, 0xdd, 0x19, 0x2f, 0xc6, 0xc9, 0xd9, 0x12, 0x31, 0x1b, 0xd7, 0x5c, 0x42, 0x2e, 0x09, 0xc8, - 0x39, 0x3c, 0x1b, 0x09, 0xe9, 0xe9, 0xec, 0xf8, 0x0e, 0x82, 0x0b, 0xb2, 0x4b, 0xe3, 0xb9, 0xa8, - 0x6c, 0xfe, 0x0e, 0xaf, 0xcc, 0xc7, 0xb2, 0x95, 0x58, 0x0b, 0x02, 0x6b, 0x06, 0xbf, 0x10, 0x89, - 0x25, 0x47, 0x01, 0xfc, 0x1d, 0x82, 0xa4, 0xa7, 0xd7, 0xe3, 0x48, 0x11, 0x3a, 0xe7, 0x05, 0x45, - 0x8b, 0x6d, 0x2f, 0xf1, 0x96, 0x05, 0xde, 0x3c, 0xbe, 0x12, 0x89, 0xe7, 0x9d, 0x33, 0xf0, 0xaf, - 0x08, 0x46, 0xda, 0xfb, 0x3f, 0x5e, 0x8d, 0x4a, 0x1c, 0x32, 0x7e, 0x28, 0x6b, 0xdd, 0x39, 0x49, - 0xe4, 0x0d, 0x81, 0x7c, 0x1d, 0xaf, 0x87, 0x20, 0xbb, 0x7d, 0x81, 0x69, 0x27, 0xfe, 0xce, 0x71, - 0x5b, 0xb3, 0x07, 0x11, 0xfc, 0x23, 0x82, 0xa4, 0x67, 0x68, 0x88, 0x96, 0xb9, 0x73, 0x52, 0x89, - 0x96, 0x39, 0x60, 0x1a, 0x51, 0x5f, 0x13, 0xcc, 0xeb, 0xf8, 0xa5, 0x1e, 0x98, 0xad, 0x91, 0x05, - 0xff, 0x86, 0x60, 0xa4, 0xbd, 0x55, 0x47, 0x8b, 0x1e, 0x32, 0xd5, 0x44, 0x8b, 0x1e, 0x36, 0xb8, - 0xa8, 0xbb, 0xa2, 0x80, 0x1d, 0xbc, 0xdd, 0x43, 0x01, 0x1d, 0x53, 0x04, 0xfe, 0x19, 0xc1, 0x68, - 0xc7, 0xe0, 0x81, 0xbb, 0x22, 0x73, 0x1f, 0xf9, 0xab, 0x5d, 0x7a, 0xc9, 0x82, 0x5e, 0x11, 0x05, - 0xbd, 0x88, 0xd7, 0x1e, 0x5d, 0x50, 0xe7, 0x14, 0x84, 0x7f, 0x41, 0x90, 0xf2, 0x35, 0xf1, 0xe8, - 0x2e, 0x11, 0x34, 0xd8, 0x44, 0x77, 0x89, 0xc0, 0xe1, 0x45, 0x7d, 0x53, 0x40, 0x6f, 0xe1, 0x8d, - 0x70, 0xe8, 0x92, 0xfe, 0xc8, 0x53, 0x10, 0x47, 0xf0, 0x13, 0x82, 0x61, 0xff, 0x18, 0x82, 0xe3, - 0x03, 0xb9, 0xe2, 0xaf, 0x74, 0xe3, 0x12, 0xb3, 0x39, 0x07, 0x2a, 0x6f, 0xcb, 0xfe, 0x19, 0x82, - 0x7e, 0x7b, 0xdc, 0xc0, 0x57, 0xa2, 0x32, 0xfb, 0xe6, 0x1b, 0x65, 0x2e, 0x8e, 0xa9, 0x84, 0xbb, - 0x2c, 0xe0, 0x32, 0x78, 0x3a, 0xf4, 0x3e, 0x14, 0xc3, 0xce, 0xce, 0xfd, 0xb3, 0x34, 0x7a, 0x70, - 0x96, 0x46, 0x7f, 0x9f, 0xa5, 0xd1, 0x9d, 0xf3, 0x74, 0xe2, 0xc1, 0x79, 0x3a, 0xf1, 0xc7, 0x79, - 0x3a, 0xf1, 0xe1, 0x82, 0xe7, 0x27, 0xee, 0xbb, 0x22, 0xc4, 0xd6, 0x21, 0xd1, 0x6b, 0x4e, 0xb8, - 0x23, 0x27, 0xa0, 0xf8, 0xb1, 0x5b, 0xe8, 0x17, 0xff, 0xd6, 0x58, 0xfd, 0x3f, 0x00, 0x00, 0xff, - 0xff, 0xb7, 0x31, 0x4f, 0x5b, 0x7c, 0x11, 0x00, 0x00, + // 1073 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x97, 0xcf, 0x6f, 0x1b, 0x45, + 0x14, 0xc7, 0x3d, 0x50, 0x52, 0xfa, 0x1c, 0xbb, 0xc9, 0x90, 0x8a, 0x74, 0x93, 0xd8, 0x65, 0x45, + 0xab, 0xb4, 0x69, 0xbd, 0x71, 0x5c, 0x7e, 0x84, 0x82, 0xc0, 0x49, 0x88, 0x04, 0x2a, 0x50, 0x96, + 0x2a, 0x07, 0x24, 0x64, 0x8d, 0xed, 0xe9, 0x66, 0x55, 0x7b, 0x67, 0xbb, 0xb3, 0xb6, 0x5a, 0x45, + 0xe5, 0xc0, 0x81, 0x5f, 0xa7, 0x4a, 0x9c, 0x91, 0xca, 0x11, 0x84, 0x84, 0xc4, 0x1f, 0x00, 0x1c, + 0x2b, 0x71, 0xa9, 0xc4, 0x05, 0x71, 0x28, 0x28, 0xe1, 0xc0, 0x9f, 0x81, 0x76, 0x76, 0x76, 0xbd, + 0x6b, 0xef, 0x6e, 0x6d, 0xf7, 0x14, 0x67, 0xe6, 0xbd, 0xef, 0xfb, 0xbc, 0x37, 0xe3, 0xf9, 0xca, + 0xa0, 0x30, 0x87, 0xb4, 0x3a, 0x54, 0xeb, 0x57, 0x9b, 0xd4, 0x25, 0x55, 0xed, 0x56, 0x8f, 0x3a, + 0x77, 0x2a, 0xb6, 0xc3, 0x5c, 0x86, 0x4f, 0x59, 0x66, 0xd3, 0x74, 0x7a, 0x15, 0x3f, 0xa4, 0x22, + 0x43, 0x94, 0x05, 0x83, 0x19, 0x4c, 0x44, 0x68, 0xde, 0x27, 0x3f, 0x58, 0x59, 0x36, 0x18, 0x33, + 0x3a, 0x54, 0x23, 0xb6, 0xa9, 0x11, 0xcb, 0x62, 0x2e, 0x71, 0x4d, 0x66, 0x71, 0xb9, 0xbb, 0x34, + 0x54, 0x46, 0x4a, 0xfa, 0x9b, 0xa5, 0x16, 0xe3, 0x5d, 0xc6, 0xb5, 0x26, 0xe1, 0x83, 0x88, 0x16, + 0x33, 0x2d, 0x7f, 0x5f, 0x7d, 0x15, 0x16, 0x3f, 0xf4, 0xb0, 0xde, 0xbe, 0xdd, 0xda, 0x27, 0x96, + 0x41, 0x75, 0xe2, 0x52, 0x9d, 0xde, 0xea, 0x51, 0xee, 0x62, 0x0c, 0xc7, 0x6c, 0x62, 0x3a, 0x8b, + 0xe8, 0x0c, 0x5a, 0x3d, 0xa1, 0x8b, 0xcf, 0xaf, 0x3d, 0xfb, 0xe5, 0xfd, 0x72, 0xee, 0xbf, 0xfb, + 0xe5, 0x9c, 0x6a, 0xc3, 0xe9, 0x84, 0x4c, 0x6e, 0x33, 0x8b, 0x53, 0xfc, 0x11, 0x14, 0xa8, 0x5c, + 0x6f, 0x38, 0xc4, 0xa5, 0xbe, 0xc6, 0x56, 0xe5, 0xc1, 0xa3, 0x72, 0xee, 0xaf, 0x47, 0xe5, 0x73, + 0x86, 0xe9, 0xee, 0xf7, 0x9a, 0x95, 0x16, 0xeb, 0x6a, 0x12, 0xd0, 0xff, 0x73, 0x89, 0xb7, 0x6f, + 0x6a, 0xee, 0x1d, 0x9b, 0xf2, 0xca, 0x0e, 0x6d, 0xe9, 0xb3, 0x34, 0x22, 0xae, 0x2e, 0x25, 0x54, + 0xe4, 0x12, 0x56, 0xfd, 0x0a, 0x81, 0x92, 0xb4, 0x2b, 0x81, 0x6e, 0x42, 0x31, 0x06, 0xc4, 0x17, + 0xd1, 0x99, 0xa7, 0x57, 0xf3, 0x1b, 0xab, 0x95, 0xc4, 0x83, 0xa8, 0x44, 0x55, 0xae, 0xf7, 0xec, + 0x0e, 0xdd, 0x52, 0x3c, 0xf6, 0x1f, 0xfe, 0x2e, 0xe3, 0x91, 0x2d, 0xae, 0x17, 0xa2, 0x9c, 0x5c, + 0x3d, 0x05, 0xcf, 0x09, 0x94, 0x7a, 0xcb, 0x35, 0xfb, 0x03, 0xc4, 0x75, 0x58, 0x88, 0x2f, 0x4b, + 0xb6, 0x45, 0x38, 0x4e, 0xfc, 0x25, 0x01, 0x75, 0x42, 0x0f, 0xfe, 0x55, 0x4f, 0xc3, 0xf3, 0x22, + 0x63, 0x8f, 0xb9, 0xf4, 0x3a, 0x71, 0x0c, 0xea, 0x86, 0x62, 0x6f, 0xc8, 0x83, 0x8b, 0x6d, 0x49, + 0xc1, 0x17, 0x60, 0xb6, 0xcf, 0x5c, 0xda, 0x70, 0xfd, 0x75, 0xa9, 0x9a, 0xef, 0x0f, 0x42, 0xd5, + 0x0f, 0x60, 0x59, 0xa4, 0xef, 0x52, 0xda, 0xa6, 0xce, 0x0e, 0xed, 0x50, 0x43, 0x5c, 0xaa, 0xe0, + 0xec, 0xcf, 0x42, 0xb1, 0x4f, 0x3a, 0x66, 0x9b, 0xb8, 0xcc, 0x69, 0x90, 0x76, 0x3b, 0xb8, 0x05, + 0x85, 0x70, 0xb5, 0xde, 0x6e, 0x47, 0xaf, 0xc3, 0x5b, 0xb0, 0x92, 0x22, 0x28, 0xa1, 0xca, 0x90, + 0xbf, 0x21, 0xf6, 0xa2, 0x72, 0xe0, 0x2f, 0x79, 0x5a, 0xea, 0xbb, 0xb2, 0xd9, 0xf7, 0x4c, 0xce, + 0xb7, 0x59, 0xcf, 0x72, 0xa9, 0x33, 0x35, 0x4d, 0x30, 0x9d, 0x98, 0xd6, 0x60, 0x3a, 0x5d, 0x93, + 0xf3, 0x46, 0xcb, 0x5f, 0x17, 0x52, 0xc7, 0xf4, 0x7c, 0x77, 0x10, 0x1a, 0x4e, 0xa7, 0x6e, 0x18, + 0x8e, 0xd7, 0x07, 0xbd, 0xe6, 0x50, 0x6f, 0x7a, 0x53, 0xf3, 0x7c, 0x81, 0xe4, 0x78, 0x46, 0x15, + 0x25, 0xd5, 0x0d, 0x98, 0x27, 0xc1, 0x5e, 0xc3, 0xf6, 0x37, 0x85, 0x6a, 0x7e, 0xa3, 0x96, 0x72, + 0x47, 0x43, 0xad, 0xe8, 0x8d, 0x94, 0xba, 0x5b, 0xc7, 0xbc, 0xeb, 0xaa, 0xcf, 0x91, 0xa1, 0x7a, + 0x6a, 0x39, 0x05, 0x24, 0xbc, 0x58, 0x5f, 0x23, 0x28, 0xa5, 0x45, 0x48, 0xd6, 0x7d, 0xc0, 0x23, + 0xac, 0xc1, 0x17, 0xea, 0x09, 0x60, 0xe7, 0x87, 0x61, 0xb9, 0x7a, 0x55, 0x7e, 0xe5, 0xc3, 0xec, + 0xbd, 0x27, 0x39, 0x85, 0x03, 0xf9, 0x44, 0x0c, 0xa9, 0xc9, 0xae, 0x3e, 0x81, 0xe2, 0xa0, 0xab, + 0xc8, 0xf8, 0xd7, 0x27, 0xe9, 0x68, 0x6f, 0xd0, 0x4e, 0x81, 0x44, 0xcb, 0xa8, 0xcb, 0x49, 0xc5, + 0xc3, 0xa9, 0x7f, 0x0a, 0x4b, 0x89, 0xbb, 0x92, 0xad, 0x01, 0x27, 0xe3, 0x6c, 0xc1, 0xb8, 0xa7, + 0x85, 0x2b, 0xc6, 0xe0, 0xb8, 0xba, 0x00, 0x58, 0xd4, 0xbf, 0x46, 0x1c, 0xd2, 0x0d, 0xa9, 0x74, + 0xf9, 0x90, 0x05, 0xab, 0x92, 0xe6, 0x0a, 0xcc, 0xd8, 0x62, 0x45, 0x4e, 0x68, 0x25, 0x05, 0xc2, + 0x4f, 0x93, 0x15, 0x65, 0xca, 0xc6, 0xb7, 0x27, 0xe1, 0x19, 0x21, 0x8a, 0x7f, 0x44, 0x30, 0x1b, + 0xc5, 0xc3, 0x5a, 0x8a, 0x4e, 0x9a, 0x43, 0x29, 0xeb, 0xe3, 0x27, 0xf8, 0xe8, 0xea, 0xe6, 0x67, + 0x7f, 0xfc, 0xfb, 0xcd, 0x53, 0x35, 0x5c, 0xd5, 0xfc, 0x4c, 0x6d, 0xc8, 0x3c, 0x3d, 0x93, 0xe3, + 0xda, 0x81, 0xf7, 0xe7, 0xae, 0x16, 0x73, 0x0c, 0xfc, 0x3d, 0x82, 0x42, 0xcc, 0x5c, 0xf0, 0xd8, + 0xe5, 0x83, 0x81, 0x2a, 0xd5, 0x09, 0x32, 0x24, 0x71, 0x4d, 0x10, 0x5f, 0xc2, 0x6b, 0x99, 0xc4, + 0x71, 0x73, 0xc3, 0xf7, 0x10, 0x1c, 0x97, 0x36, 0x83, 0x2f, 0x64, 0xd5, 0x8c, 0x5b, 0x94, 0xb2, + 0x36, 0x56, 0xac, 0x24, 0xbb, 0x28, 0xc8, 0xce, 0xe1, 0x17, 0x33, 0xc9, 0xa4, 0x97, 0xe1, 0xef, + 0x10, 0xe4, 0x23, 0x66, 0x85, 0x2b, 0x59, 0xa5, 0x46, 0x0d, 0x4f, 0xd1, 0xc6, 0x8e, 0x97, 0x78, + 0x55, 0x81, 0xb7, 0x86, 0xcf, 0x67, 0xe2, 0x45, 0x8d, 0x12, 0xff, 0x86, 0x60, 0x6e, 0xd8, 0xc0, + 0x70, 0x2d, 0xab, 0x70, 0x8a, 0x7f, 0x2a, 0x97, 0x27, 0x4b, 0x92, 0xc8, 0x75, 0x81, 0x7c, 0x05, + 0x6f, 0xa6, 0x20, 0x87, 0x0f, 0x1b, 0xd7, 0x0e, 0xe2, 0x4f, 0xdf, 0x5d, 0xcd, 0x77, 0x52, 0xfc, + 0x13, 0x82, 0x7c, 0xc4, 0xf5, 0xb2, 0xc7, 0x3c, 0x6a, 0xb5, 0xd9, 0x63, 0x4e, 0xb0, 0x53, 0xf5, + 0x4d, 0xc1, 0xbc, 0x89, 0x5f, 0x99, 0x82, 0xd9, 0xf3, 0x5c, 0xfc, 0x3b, 0x82, 0xb9, 0x61, 0xaf, + 0xc9, 0x1e, 0x7a, 0x8a, 0x2d, 0x67, 0x0f, 0x3d, 0xcd, 0x79, 0xd5, 0xab, 0xa2, 0x81, 0x5d, 0xbc, + 0x33, 0x45, 0x03, 0x23, 0x36, 0x88, 0x7f, 0x41, 0x30, 0x3f, 0xe2, 0x9c, 0x78, 0x22, 0xb2, 0xf0, + 0xca, 0xbf, 0x34, 0x61, 0x96, 0x6c, 0xe8, 0x75, 0xd1, 0xd0, 0xcb, 0xf8, 0xf2, 0xe3, 0x1b, 0x1a, + 0xb5, 0x71, 0xfc, 0x2b, 0x82, 0x42, 0xcc, 0x85, 0xb2, 0x9f, 0xb9, 0x24, 0x67, 0xce, 0x7e, 0xe6, + 0x12, 0xdd, 0x57, 0x7d, 0x47, 0x40, 0x6f, 0xe3, 0x7a, 0x3a, 0x74, 0xdb, 0x7c, 0xec, 0x29, 0x88, + 0x23, 0xf8, 0x19, 0x41, 0x31, 0xee, 0xa3, 0x78, 0x7c, 0xa0, 0x70, 0xf8, 0x1b, 0x93, 0xa4, 0x8c, + 0xe9, 0x2e, 0x89, 0x93, 0xf7, 0xc7, 0xfe, 0x39, 0x82, 0x19, 0xdf, 0x2f, 0xf1, 0xf9, 0xac, 0xca, + 0x31, 0x83, 0x56, 0x2e, 0x8c, 0x13, 0x2a, 0xe1, 0xce, 0x0a, 0xb8, 0x32, 0x5e, 0x49, 0x7d, 0x0f, + 0x85, 0x5b, 0xef, 0x3e, 0x38, 0x2c, 0xa1, 0x87, 0x87, 0x25, 0xf4, 0xcf, 0x61, 0x09, 0xdd, 0x3b, + 0x2a, 0xe5, 0x1e, 0x1e, 0x95, 0x72, 0x7f, 0x1e, 0x95, 0x72, 0x1f, 0x5f, 0x8c, 0xfc, 0x6a, 0x7b, + 0x5f, 0x48, 0x6c, 0xef, 0x13, 0xd3, 0x0a, 0xe4, 0x6e, 0x07, 0x82, 0xe2, 0xf7, 0x5b, 0x73, 0x46, + 0xfc, 0xc0, 0xac, 0xfd, 0x1f, 0x00, 0x00, 0xff, 0xff, 0x43, 0x4b, 0x5a, 0x52, 0x06, 0x0f, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -1249,10 +1073,6 @@ type QueryClient interface { ExchangeRate(ctx context.Context, in *QueryExchangeRateRequest, opts ...grpc.CallOption) (*QueryExchangeRateResponse, error) // ExchangeRates returns exchange rates of all pairs ExchangeRates(ctx context.Context, in *QueryExchangeRatesRequest, opts ...grpc.CallOption) (*QueryExchangeRatesResponse, error) - // TobinTax returns tobin tax of a pair - TobinTax(ctx context.Context, in *QueryTobinTaxRequest, opts ...grpc.CallOption) (*QueryTobinTaxResponse, error) - // TobinTaxes returns tobin taxes of all pairs - TobinTaxes(ctx context.Context, in *QueryTobinTaxesRequest, opts ...grpc.CallOption) (*QueryTobinTaxesResponse, error) // Actives returns all active pairs Actives(ctx context.Context, in *QueryActivesRequest, opts ...grpc.CallOption) (*QueryActivesResponse, error) // VoteTargets returns all vote target for pairs @@ -1299,24 +1119,6 @@ func (c *queryClient) ExchangeRates(ctx context.Context, in *QueryExchangeRatesR return out, nil } -func (c *queryClient) TobinTax(ctx context.Context, in *QueryTobinTaxRequest, opts ...grpc.CallOption) (*QueryTobinTaxResponse, error) { - out := new(QueryTobinTaxResponse) - err := c.cc.Invoke(ctx, "/nibiru.oracle.v1beta1.Query/TobinTax", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TobinTaxes(ctx context.Context, in *QueryTobinTaxesRequest, opts ...grpc.CallOption) (*QueryTobinTaxesResponse, error) { - out := new(QueryTobinTaxesResponse) - err := c.cc.Invoke(ctx, "/nibiru.oracle.v1beta1.Query/TobinTaxes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - func (c *queryClient) Actives(ctx context.Context, in *QueryActivesRequest, opts ...grpc.CallOption) (*QueryActivesResponse, error) { out := new(QueryActivesResponse) err := c.cc.Invoke(ctx, "/nibiru.oracle.v1beta1.Query/Actives", in, out, opts...) @@ -1404,10 +1206,6 @@ type QueryServer interface { ExchangeRate(context.Context, *QueryExchangeRateRequest) (*QueryExchangeRateResponse, error) // ExchangeRates returns exchange rates of all pairs ExchangeRates(context.Context, *QueryExchangeRatesRequest) (*QueryExchangeRatesResponse, error) - // TobinTax returns tobin tax of a pair - TobinTax(context.Context, *QueryTobinTaxRequest) (*QueryTobinTaxResponse, error) - // TobinTaxes returns tobin taxes of all pairs - TobinTaxes(context.Context, *QueryTobinTaxesRequest) (*QueryTobinTaxesResponse, error) // Actives returns all active pairs Actives(context.Context, *QueryActivesRequest) (*QueryActivesResponse, error) // VoteTargets returns all vote target for pairs @@ -1438,12 +1236,6 @@ func (*UnimplementedQueryServer) ExchangeRate(ctx context.Context, req *QueryExc func (*UnimplementedQueryServer) ExchangeRates(ctx context.Context, req *QueryExchangeRatesRequest) (*QueryExchangeRatesResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ExchangeRates not implemented") } -func (*UnimplementedQueryServer) TobinTax(ctx context.Context, req *QueryTobinTaxRequest) (*QueryTobinTaxResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TobinTax not implemented") -} -func (*UnimplementedQueryServer) TobinTaxes(ctx context.Context, req *QueryTobinTaxesRequest) (*QueryTobinTaxesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TobinTaxes not implemented") -} func (*UnimplementedQueryServer) Actives(ctx context.Context, req *QueryActivesRequest) (*QueryActivesResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Actives not implemented") } @@ -1512,42 +1304,6 @@ func _Query_ExchangeRates_Handler(srv interface{}, ctx context.Context, dec func return interceptor(ctx, in, info, handler) } -func _Query_TobinTax_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTobinTaxRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TobinTax(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.oracle.v1beta1.Query/TobinTax", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TobinTax(ctx, req.(*QueryTobinTaxRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TobinTaxes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTobinTaxesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TobinTaxes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.oracle.v1beta1.Query/TobinTaxes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TobinTaxes(ctx, req.(*QueryTobinTaxesRequest)) - } - return interceptor(ctx, in, info, handler) -} - func _Query_Actives_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryActivesRequest) if err := dec(in); err != nil { @@ -1722,14 +1478,6 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "ExchangeRates", Handler: _Query_ExchangeRates_Handler, }, - { - MethodName: "TobinTax", - Handler: _Query_TobinTax_Handler, - }, - { - MethodName: "TobinTaxes", - Handler: _Query_TobinTaxes_Handler, - }, { MethodName: "Actives", Handler: _Query_Actives_Handler, @@ -1894,7 +1642,7 @@ func (m *QueryExchangeRatesResponse) MarshalToSizedBuffer(dAtA []byte) (int, err return len(dAtA) - i, nil } -func (m *QueryTobinTaxRequest) Marshal() (dAtA []byte, err error) { +func (m *QueryActivesRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1904,27 +1652,20 @@ func (m *QueryTobinTaxRequest) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryTobinTaxRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryActivesRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryTobinTaxRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryActivesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.Pair) > 0 { - i -= len(m.Pair) - copy(dAtA[i:], m.Pair) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Pair))) - i-- - dAtA[i] = 0xa - } return len(dAtA) - i, nil } -func (m *QueryTobinTaxResponse) Marshal() (dAtA []byte, err error) { +func (m *QueryActivesResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1934,30 +1675,29 @@ func (m *QueryTobinTaxResponse) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryTobinTaxResponse) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryActivesResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryTobinTaxResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryActivesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - { - size := m.TobinTax.Size() - i -= size - if _, err := m.TobinTax.MarshalTo(dAtA[i:]); err != nil { - return 0, err + if len(m.Actives) > 0 { + for iNdEx := len(m.Actives) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Actives[iNdEx]) + copy(dAtA[i:], m.Actives[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Actives[iNdEx]))) + i-- + dAtA[i] = 0xa } - i = encodeVarintQuery(dAtA, i, uint64(size)) } - i-- - dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *QueryTobinTaxesRequest) Marshal() (dAtA []byte, err error) { +func (m *QueryVoteTargetsRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1967,12 +1707,12 @@ func (m *QueryTobinTaxesRequest) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryTobinTaxesRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryVoteTargetsRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryTobinTaxesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryVoteTargetsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int @@ -1980,7 +1720,7 @@ func (m *QueryTobinTaxesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) return len(dAtA) - i, nil } -func (m *QueryTobinTaxesResponse) Marshal() (dAtA []byte, err error) { +func (m *QueryVoteTargetsResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1990,26 +1730,21 @@ func (m *QueryTobinTaxesResponse) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryTobinTaxesResponse) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryVoteTargetsResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryTobinTaxesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryVoteTargetsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.TobinTaxes) > 0 { - for iNdEx := len(m.TobinTaxes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TobinTaxes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } + if len(m.VoteTargets) > 0 { + for iNdEx := len(m.VoteTargets) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.VoteTargets[iNdEx]) + copy(dAtA[i:], m.VoteTargets[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.VoteTargets[iNdEx]))) i-- dAtA[i] = 0xa } @@ -2017,7 +1752,7 @@ func (m *QueryTobinTaxesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) return len(dAtA) - i, nil } -func (m *QueryActivesRequest) Marshal() (dAtA []byte, err error) { +func (m *QueryFeederDelegationRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2027,20 +1762,27 @@ func (m *QueryActivesRequest) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryActivesRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryFeederDelegationRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryActivesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryFeederDelegationRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l + if len(m.ValidatorAddr) > 0 { + i -= len(m.ValidatorAddr) + copy(dAtA[i:], m.ValidatorAddr) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ValidatorAddr))) + i-- + dAtA[i] = 0xa + } return len(dAtA) - i, nil } -func (m *QueryActivesResponse) Marshal() (dAtA []byte, err error) { +func (m *QueryFeederDelegationResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2050,29 +1792,27 @@ func (m *QueryActivesResponse) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryActivesResponse) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryFeederDelegationResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryActivesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryFeederDelegationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.Actives) > 0 { - for iNdEx := len(m.Actives) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Actives[iNdEx]) - copy(dAtA[i:], m.Actives[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Actives[iNdEx]))) - i-- - dAtA[i] = 0xa - } + if len(m.FeederAddr) > 0 { + i -= len(m.FeederAddr) + copy(dAtA[i:], m.FeederAddr) + i = encodeVarintQuery(dAtA, i, uint64(len(m.FeederAddr))) + i-- + dAtA[i] = 0xa } return len(dAtA) - i, nil } -func (m *QueryVoteTargetsRequest) Marshal() (dAtA []byte, err error) { +func (m *QueryMissCounterRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2082,127 +1822,12 @@ func (m *QueryVoteTargetsRequest) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryVoteTargetsRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryMissCounterRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryVoteTargetsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryVoteTargetsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryVoteTargetsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVoteTargetsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.VoteTargets) > 0 { - for iNdEx := len(m.VoteTargets) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.VoteTargets[iNdEx]) - copy(dAtA[i:], m.VoteTargets[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.VoteTargets[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryFeederDelegationRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryFeederDelegationRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryFeederDelegationRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ValidatorAddr) > 0 { - i -= len(m.ValidatorAddr) - copy(dAtA[i:], m.ValidatorAddr) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ValidatorAddr))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryFeederDelegationResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryFeederDelegationResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryFeederDelegationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.FeederAddr) > 0 { - i -= len(m.FeederAddr) - copy(dAtA[i:], m.FeederAddr) - i = encodeVarintQuery(dAtA, i, uint64(len(m.FeederAddr))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryMissCounterRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryMissCounterRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryMissCounterRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryMissCounterRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int @@ -2606,54 +2231,6 @@ func (m *QueryExchangeRatesResponse) Size() (n int) { return n } -func (m *QueryTobinTaxRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Pair) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTobinTaxResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.TobinTax.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryTobinTaxesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTobinTaxesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.TobinTaxes) > 0 { - for _, e := range m.TobinTaxes { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - func (m *QueryActivesRequest) Size() (n int) { if m == nil { return 0 @@ -3175,306 +2752,6 @@ func (m *QueryExchangeRatesResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryTobinTaxRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTobinTaxRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTobinTaxRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Pair = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTobinTaxResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTobinTaxResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTobinTaxResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TobinTax", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TobinTax.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTobinTaxesRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTobinTaxesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTobinTaxesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTobinTaxesResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTobinTaxesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTobinTaxesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TobinTaxes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TobinTaxes = append(m.TobinTaxes, Pair{}) - if err := m.TobinTaxes[len(m.TobinTaxes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} func (m *QueryActivesRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/x/oracle/types/query.pb.gw.go b/x/oracle/types/query.pb.gw.go index 8d6dc99b9..05e1f8787 100644 --- a/x/oracle/types/query.pb.gw.go +++ b/x/oracle/types/query.pb.gw.go @@ -103,78 +103,6 @@ func local_request_Query_ExchangeRates_0(ctx context.Context, marshaler runtime. } -func request_Query_TobinTax_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTobinTaxRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pair"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pair") - } - - protoReq.Pair, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pair", err) - } - - msg, err := client.TobinTax(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TobinTax_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTobinTaxRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pair"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pair") - } - - protoReq.Pair, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pair", err) - } - - msg, err := server.TobinTax(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TobinTaxes_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTobinTaxesRequest - var metadata runtime.ServerMetadata - - msg, err := client.TobinTaxes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TobinTaxes_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTobinTaxesRequest - var metadata runtime.ServerMetadata - - msg, err := server.TobinTaxes(ctx, &protoReq) - return msg, metadata, err - -} - func request_Query_Actives_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq QueryActivesRequest var metadata runtime.ServerMetadata @@ -527,46 +455,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv }) - mux.Handle("GET", pattern_Query_TobinTax_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TobinTax_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TobinTax_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TobinTaxes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TobinTaxes_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TobinTaxes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - mux.Handle("GET", pattern_Query_Actives_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -828,46 +716,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie }) - mux.Handle("GET", pattern_Query_TobinTax_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TobinTax_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TobinTax_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TobinTaxes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TobinTaxes_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TobinTaxes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - mux.Handle("GET", pattern_Query_Actives_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -1056,10 +904,6 @@ var ( pattern_Query_ExchangeRates_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"nibiru", "oracle", "v1beta1", "pairs", "exchange_rates"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_TobinTax_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"nibiru", "oracle", "v1beta1", "pairs", "pair", "tobin_tax"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TobinTaxes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"nibiru", "oracle", "v1beta1", "pairs", "tobin_taxes"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_Actives_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"nibiru", "oracle", "v1beta1", "pairs", "actives"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_VoteTargets_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"nibiru", "oracle", "v1beta1", "pairs", "vote_targets"}, "", runtime.AssumeColonVerbOpt(false))) @@ -1084,10 +928,6 @@ var ( forward_Query_ExchangeRates_0 = runtime.ForwardResponseMessage - forward_Query_TobinTax_0 = runtime.ForwardResponseMessage - - forward_Query_TobinTaxes_0 = runtime.ForwardResponseMessage - forward_Query_Actives_0 = runtime.ForwardResponseMessage forward_Query_VoteTargets_0 = runtime.ForwardResponseMessage From 1880e4313c0f16a1df5617b6e81e558eeafae36f Mon Sep 17 00:00:00 2001 From: AgentSmithMatrix <98403347+AgentSmithMatrix@users.noreply.github.com> Date: Mon, 15 Aug 2022 13:16:17 +0200 Subject: [PATCH 2/7] ci: create docker image on release (#826) * test docker image on release * add pull request to test image creation * remove line that tested pull requiest * upgrade changelog --- .github/workflows/docker-release.yml | 35 ++++++++++++++++++++++++++++ CHANGELOG.md | 2 ++ Dockerfile | 24 +++++++++---------- 3 files changed, 49 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/docker-release.yml diff --git a/.github/workflows/docker-release.yml b/.github/workflows/docker-release.yml new file mode 100644 index 000000000..74cabdc6c --- /dev/null +++ b/.github/workflows/docker-release.yml @@ -0,0 +1,35 @@ +name: Publish Docker image + +on: + release: + types: [published] + +jobs: + push_to_registry: + name: Push Docker image to Docker Hub + runs-on: ubuntu-latest + steps: + - name: Check out the repo + uses: actions/checkout@v3 + + - name: Log in to the Container registry + uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38 + with: + images: | + ghcr.io/${{ github.repository }} + + - name: Build and push Docker images + uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 660aa1b68..a9e815376 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### CI * [#795](https://github.com/NibiruChain/nibiru/pull/795) Integration tests run when PR is approved +* [#826](https://github.com/NibiruChain/nibiru/pull/826) - create and push docker image on release + ### Improvements diff --git a/Dockerfile b/Dockerfile index 16a6fa4da..ba51595ae 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,15 +1,15 @@ -FROM ubuntu:18.04 +FROM golang:1.18 AS builder -RUN apt-get update && \ - apt-get -y upgrade && \ - apt-get -y install curl jq file +RUN apt-get update && apt-get install -y \ + jq \ + && rm -rf /var/lib/apt/lists/* -VOLUME [ /nibid ] WORKDIR /nibid -EXPOSE 26656 26657 -ENTRYPOINT ["/usr/bin/docker-wrapper.sh"] -CMD ["start"] -STOPSIGNAL SIGTERM - -COPY scripts/docker-wrapper.sh /usr/bin/docker-wrapper.sh - +COPY . ./ +RUN CGO_ENABLED=0 make build + +FROM alpine:latest +RUN apk --no-cache add ca-certificates +WORKDIR /root/ +COPY --from=builder /nibid/build/nibid /usr/local/bin/nibid +ENTRYPOINT ["nibid"] From 145d47711a8ad63d3869f43982386ba0ad4808cc Mon Sep 17 00:00:00 2001 From: NibiruHeisenberg <101130700+NibiruHeisenberg@users.noreply.github.com> Date: Mon, 15 Aug 2022 07:24:24 -0400 Subject: [PATCH 3/7] feat(pricefeed): TWAP in query price (#811) * Add twap to CurrentPriceResponse proto * Fix typo * Refactor TestKeeper_GetSetCurrentPrice * Refactor GetPrice keeper tests * Add twap in QueryPriceResponse * Update pricefeed cli test * Clean up cli tests * Update CHANGELOG.md Co-authored-by: Unique Divine <51418232+Unique-Divine@users.noreply.github.com> Co-authored-by: Agent Smith --- CHANGELOG.md | 3 +- proto/oracle/v1beta1/oracle.proto | 2 +- proto/pricefeed/query.proto | 5 + x/pricefeed/client/cli/cli_test.go | 46 +++---- x/pricefeed/keeper/grpc_query.go | 22 +++- x/pricefeed/keeper/grpc_query_test.go | 40 +++++++ x/pricefeed/keeper/keeper.go | 55 ++++----- x/pricefeed/keeper/keeper_test.go | 93 ++++----------- x/pricefeed/types/market.go | 5 - x/pricefeed/types/query.pb.go | 166 +++++++++++++++++--------- 10 files changed, 251 insertions(+), 186 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a9e815376..79af36d76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,8 +60,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Features * [#791](https://github.com/NibiruChain/nibiru/pull/791) Add the x/oracle module -* [#816](https://github.com/NibiruChain/nibiru/pull/816) - Remove tobin tax from x/oracle +* [#811](https://github.com/NibiruChain/nibiru/pull/811) Return the index twap in `QueryPrice` cmd * [#813](https://github.com/NibiruChain/nibiru/pull/813) - (vpool): Expose mark price, mark TWAP, index price, and k (swap invariant) in the all-pools query +* [#816](https://github.com/NibiruChain/nibiru/pull/816) - Remove tobin tax from x/oracle * [#810](https://github.com/NibiruChain/nibiru/pull/810) - feat(x/perp): expose 'marginRatioIndex' and block number on QueryTraderPosition ## [v0.12.1](https://github.com/NibiruChain/nibiru/releases/tag/v0.12.1) - 2022-08-04 diff --git a/proto/oracle/v1beta1/oracle.proto b/proto/oracle/v1beta1/oracle.proto index 744c21e05..41eff083b 100644 --- a/proto/oracle/v1beta1/oracle.proto +++ b/proto/oracle/v1beta1/oracle.proto @@ -52,7 +52,7 @@ message Pair { // struct for aggregate prevoting on the ExchangeRateVote. // The purpose of aggregate prevote is to hide vote exchange rates with hash -// which is formatted as hex string in SHA256("{salt}:({pair},{exchange_rate})|...,({pair},{exchange_rate}):{voter}") +// which is formatted as hex string in SHA256("{salt}:({pair},{exchange_rate})|...|({pair},{exchange_rate}):{voter}") message AggregateExchangeRatePrevote { option (gogoproto.equal) = false; option (gogoproto.goproto_getters) = false; diff --git a/proto/pricefeed/query.proto b/proto/pricefeed/query.proto index 11be29482..ce5ceec7e 100644 --- a/proto/pricefeed/query.proto +++ b/proto/pricefeed/query.proto @@ -136,7 +136,12 @@ message PostedPriceResponse { // module. message CurrentPriceResponse { string pair_id = 1 [(gogoproto.customname) = "PairID"]; + + // most current price of the trading pair string price = 2 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + + // twap of the trading pair + string twap = 3 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; } // Market defines an asset in the pricefeed. diff --git a/x/pricefeed/client/cli/cli_test.go b/x/pricefeed/client/cli/cli_test.go index 27932eb18..8288123f0 100644 --- a/x/pricefeed/client/cli/cli_test.go +++ b/x/pricefeed/client/cli/cli_test.go @@ -37,17 +37,15 @@ const ( type IntegrationTestSuite struct { suite.Suite - cfg testutilcli.Config - network *testutilcli.Network - oracleUIDs []string - oracleMap map[string]sdk.AccAddress + cfg testutilcli.Config + network *testutilcli.Network + oracleMap map[string]sdk.AccAddress } func (s *IntegrationTestSuite) setupOraclesForKeyring() { val := s.network.Validators[0] - s.oracleUIDs = []string{"oracle", "wrongOracle"} - for _, oracleUID := range s.oracleUIDs { + for _, oracleUID := range []string{"oracle", "wrongOracle"} { info, _, err := val.ClientCtx.Keyring.NewMnemonic( /* uid */ oracleUID, /* language */ keyring.English, @@ -234,6 +232,7 @@ func (s IntegrationTestSuite) TestGetRawPricesCmd() { }) } } + func expireWithinHours(t time.Time, hours time.Duration) bool { now := time.Now() return t.After(now) && t.Before(now.Add(hours*time.Hour)) @@ -283,20 +282,29 @@ func (s IntegrationTestSuite) TestPairsCmd() { }) } } + func (s IntegrationTestSuite) TestPricesCmd() { val := s.network.Validators[0] testCases := []struct { name string - expectedPricePairs []pricefeedtypes.CurrentPriceResponse - respType proto.Message + expectedPrices []pricefeedtypes.CurrentPriceResponse + respType proto.Message }{ { name: "Get current prices", - expectedPricePairs: []pricefeedtypes.CurrentPriceResponse{ - pricefeedtypes.NewCurrentPriceResponse(common.PairGovStable.String(), sdk.NewDec(10)), - pricefeedtypes.NewCurrentPriceResponse(common.PairCollStable.String(), sdk.NewDec(1)), + expectedPrices: []pricefeedtypes.CurrentPriceResponse{ + { + PairID: common.PairGovStable.String(), + Price: sdk.NewDec(10), + Twap: sdk.ZeroDec(), + }, + { + PairID: common.PairCollStable.String(), + Price: sdk.NewDec(1), + Twap: sdk.ZeroDec(), + }, }, respType: &pricefeedtypes.QueryPricesResponse{}, }, @@ -311,15 +319,13 @@ func (s IntegrationTestSuite) TestPricesCmd() { out, err := sdktestutilcli.ExecTestCLICmd(clientCtx, cmd, nil) s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*pricefeedtypes.QueryPricesResponse) - err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), txResp) - s.Require().NoError(err) - s.Assert().Equal(len(tc.expectedPricePairs), len(txResp.Prices)) + s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), txResp), out.String()) + s.Assert().Equal(len(tc.expectedPrices), len(txResp.Prices)) for _, priceResponse := range txResp.Prices { - s.Assert().Contains(tc.expectedPricePairs, priceResponse, tc.expectedPricePairs) + s.Assert().Contains(tc.expectedPrices, priceResponse, tc.expectedPrices) } }) } @@ -531,16 +537,14 @@ func (s IntegrationTestSuite) TestGetParamsCmd() { tc := tc s.Run(tc.name, func() { - cmd := cli.CmdQueryParams() clientCtx := val.ClientCtx.WithOutputFormat("json") - out, err := sdktestutilcli.ExecTestCLICmd(clientCtx, cmd, nil) + out, err := sdktestutilcli.ExecTestCLICmd(clientCtx, cli.CmdQueryParams(), nil) s.Require().NoError(err, out.String()) s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*pricefeedtypes.QueryParamsResponse) - err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), txResp) - s.Require().NoError(err) + s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), txResp)) s.Assert().Equal(tc.expectedParams, txResp.Params) }) } @@ -579,7 +583,7 @@ func (s IntegrationTestSuite) TestX_CmdAddOracleProposalAndVote() { "description": "%v", "oracles": ["%v"], "pairs": ["%v", "%v"] - } + } `, proposal.Title, proposal.Description, proposal.Oracles[0], proposal.Pairs[0], proposal.Pairs[1], ) diff --git a/x/pricefeed/keeper/grpc_query.go b/x/pricefeed/keeper/grpc_query.go index cd07a9077..d10852a7b 100644 --- a/x/pricefeed/keeper/grpc_query.go +++ b/x/pricefeed/keeper/grpc_query.go @@ -33,13 +33,22 @@ func (k Keeper) QueryPrice(goCtx context.Context, req *types.QueryPriceRequest) tokens := common.DenomsFromPoolName(req.PairId) token0, token1 := tokens[0], tokens[1] - currentPrice, sdkErr := k.GetCurrentPrice(ctx, token0, token1) - if sdkErr != nil { - return nil, sdkErr + currentPrice, err := k.GetCurrentPrice(ctx, token0, token1) + if err != nil { + return nil, err + } + + twap, err := k.GetCurrentTWAP(ctx, token0, token1) + if err != nil { + return nil, err } return &types.QueryPriceResponse{ - Price: types.CurrentPriceResponse{PairID: req.PairId, Price: currentPrice.Price}, + Price: types.CurrentPriceResponse{ + PairID: req.PairId, + Price: currentPrice.Price, + Twap: twap, + }, }, nil } @@ -81,7 +90,10 @@ func (k Keeper) QueryPrices(goCtx context.Context, req *types.QueryPricesRequest var currentPrices types.CurrentPriceResponses for _, currentPrice := range k.GetCurrentPrices(ctx) { if currentPrice.PairID != "" { - currentPrices = append(currentPrices, types.CurrentPriceResponse(currentPrice)) + currentPrices = append(currentPrices, types.CurrentPriceResponse{ + PairID: currentPrice.PairID, + Price: currentPrice.Price, + }) } } diff --git a/x/pricefeed/keeper/grpc_query_test.go b/x/pricefeed/keeper/grpc_query_test.go index e703a1671..0b8f9885b 100644 --- a/x/pricefeed/keeper/grpc_query_test.go +++ b/x/pricefeed/keeper/grpc_query_test.go @@ -2,6 +2,7 @@ package keeper_test import ( "testing" + "time" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" @@ -107,3 +108,42 @@ func TestMarketsQuery(t *testing.T) { assert.EqualValues(t, wantMarket, queryResp.Markets[idx]) } } + +func TestQueryPrice(t *testing.T) { + pair := common.MustNewAssetPair("ubtc:uusd") + keeper, ctx := testutilkeeper.PricefeedKeeper(t) + keeper.SetParams(ctx, types.Params{ + Pairs: common.AssetPairs{pair}, + TwapLookbackWindow: time.Minute * 15, + }) + + oracle := sample.AccAddress() + keeper.WhitelistOraclesForPairs(ctx, []sdk.AccAddress{oracle}, []common.AssetPair{pair}) + + // first block + _, err := keeper.PostRawPrice(ctx, oracle, pair.String(), sdk.NewDec(20_000), time.Now().Add(time.Hour)) + require.NoError(t, err) + err = keeper.GatherRawPrices(ctx, "ubtc", "uusd") + require.NoError(t, err) + + // second block + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(time.Second * 5)).WithBlockHeight(1) + _, err = keeper.PostRawPrice(ctx, oracle, "ubtc:uusd", sdk.NewDec(30_000), time.Now().Add(time.Hour)) + require.NoError(t, err) + err = keeper.GatherRawPrices(ctx, "ubtc", "uusd") + require.NoError(t, err) + + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(time.Second * 5)).WithBlockHeight(2) + resp, err := keeper.QueryPrice(sdk.WrapSDKContext(ctx), &types.QueryPriceRequest{ + PairId: "ubtc:uusd", + }) + + assert.Nil(t, err) + assert.Equal(t, types.QueryPriceResponse{ + Price: types.CurrentPriceResponse{ + PairID: "ubtc:uusd", + Price: sdk.NewDec(30_000), + Twap: sdk.NewDec(25_000), + }, + }, *resp) +} diff --git a/x/pricefeed/keeper/keeper.go b/x/pricefeed/keeper/keeper.go index 4607b137c..9da7e930f 100644 --- a/x/pricefeed/keeper/keeper.go +++ b/x/pricefeed/keeper/keeper.go @@ -80,27 +80,25 @@ func (k Keeper) PostRawPrice( } if !k.IsWhitelistedOracle(ctx, pair.String(), oracle) { - return types.PostedPrice{}, fmt.Errorf( - "oracle %s cannot post on pair %v", oracle, pair.String()) + return types.PostedPrice{}, fmt.Errorf("oracle %s cannot post on pair %v", oracle, pair.String()) } - newPostedPrice := types.NewPostedPrice(pair, oracle, price, expiry) - // Emit an event containing the oracle's new price - - err = ctx.EventManager().EmitTypedEvent(&types.EventOracleUpdatePrice{ + if err = ctx.EventManager().EmitTypedEvent(&types.EventOracleUpdatePrice{ PairId: pair.String(), Oracle: oracle.String(), PairPrice: price, Expiry: expiry, - }) - if err != nil { + }); err != nil { panic(err) } // Sets the raw price for a single oracle instead of an array of all oracle's raw prices - store := ctx.KVStore(k.storeKey) - store.Set(types.RawPriceKey(pair.String(), oracle), k.cdc.MustMarshal(&newPostedPrice)) + newPostedPrice := types.NewPostedPrice(pair, oracle, price, expiry) + ctx.KVStore(k.storeKey).Set( + types.RawPriceKey(pair.String(), oracle), + k.cdc.MustMarshal(&newPostedPrice), + ) return newPostedPrice, nil } @@ -129,19 +127,15 @@ func (k Keeper) GatherRawPrices(ctx sdk.Context, token0 string, token1 string) e validPrevPrice = false } - postedPrices := k.GetRawPrices(ctx, pairID) - - var notExpiredPrices []types.CurrentPrice + var unexpiredPrices []types.CurrentPrice // filter out expired prices - for _, post := range postedPrices { - if post.Expiry.After(ctx.BlockTime()) { - notExpiredPrices = append( - notExpiredPrices, - types.NewCurrentPrice(token0, token1, post.Price)) + for _, rawPrice := range k.GetRawPrices(ctx, pairID) { + if rawPrice.Expiry.After(ctx.BlockTime()) { + unexpiredPrices = append(unexpiredPrices, types.NewCurrentPrice(token0, token1, rawPrice.Price)) } } - if len(notExpiredPrices) == 0 { + if len(unexpiredPrices) == 0 { // NOTE: The current price stored will continue storing the most recent (expired) // price if this is not set. // This zero's out the current price stored value for that market and ensures @@ -150,7 +144,7 @@ func (k Keeper) GatherRawPrices(ctx sdk.Context, token0 string, token1 string) e return types.ErrNoValidPrice } - medianPrice := k.CalculateMedianPrice(notExpiredPrices) + medianPrice := k.CalculateMedianPrice(unexpiredPrices) // check case that market price was not set in genesis if validPrevPrice && !medianPrice.Equal(prevPrice.Price) { @@ -274,13 +268,16 @@ func (k Keeper) GetCurrentTWAP(ctx sdk.Context, token0 string, token1 string, if err := assetPair.Validate(); err != nil { return sdk.Dec{}, err } - givenIsActive := k.IsActivePair(ctx, assetPair.String()) - inverseIsActive := k.IsActivePair(ctx, assetPair.Inverse().String()) - if !givenIsActive && inverseIsActive { + + // invert the asset pair if the given is not existent + inverseIsActive := false + if !k.IsActivePair(ctx, assetPair.String()) && k.IsActivePair(ctx, assetPair.Inverse().String()) { assetPair = assetPair.Inverse() + inverseIsActive = true } - lookbackWindow := k.GetParams(ctx).TwapLookbackWindow + // earliest timestamp we'll look back until + lookbackWindow := k.GetParams(ctx).TwapLookbackWindow lowerLimitTimestampMs := ctx.BlockTime().Add(-lookbackWindow).UnixMilli() var cumulativePrice sdk.Dec = sdk.ZeroDec() @@ -289,7 +286,7 @@ func (k Keeper) GetCurrentTWAP(ctx sdk.Context, token0 string, token1 string, // traverse snapshots in reverse order startKey := types.PriceSnapshotKey(assetPair.String(), ctx.BlockHeight()) - var numShapshots int64 = 0 + var numSnapshots int64 = 0 var snapshotPriceBuffer []sdk.Dec // contains snapshots at time 0 k.IteratePriceSnapshotsFrom( /*ctx=*/ ctx, @@ -297,7 +294,7 @@ func (k Keeper) GetCurrentTWAP(ctx sdk.Context, token0 string, token1 string, /*end=*/ nil, /*reverse=*/ true, /*do=*/ func(ps *types.PriceSnapshot) (stop bool) { - numShapshots += 1 + numSnapshots += 1 var timeElapsedMs int64 if ps.TimestampMs <= lowerLimitTimestampMs { // current snapshot is below the lower limit @@ -323,13 +320,13 @@ func (k Keeper) GetCurrentTWAP(ctx sdk.Context, token0 string, token1 string, switch { case cumulativePeriodMs < 0: return sdk.Dec{}, fmt.Errorf("cumulativePeriodMs, %v, should never be negative", cumulativePeriodMs) - case (cumulativePeriodMs == 0) && (numShapshots > 0): + case (cumulativePeriodMs == 0) && (numSnapshots > 0): sum := sdk.ZeroDec() for _, price := range snapshotPriceBuffer { sum = sum.Add(price) } - return sum.QuoInt64(numShapshots), nil - case (cumulativePeriodMs == 0) && (numShapshots == 0): + return sum.QuoInt64(numSnapshots), nil + case (cumulativePeriodMs == 0) && (numSnapshots == 0): return sdk.Dec{}, fmt.Errorf(` failed to calculate twap, no time passed and no snapshots have been taken since ctx.BlockTime: %v, diff --git a/x/pricefeed/keeper/keeper_test.go b/x/pricefeed/keeper/keeper_test.go index 61f3cccf9..aa6464643 100644 --- a/x/pricefeed/keeper/keeper_test.go +++ b/x/pricefeed/keeper/keeper_test.go @@ -159,118 +159,73 @@ func TestKeeper_PostRawPriceWrongOracles(t *testing.T) { } } -// TestKeeper_GetSetCurrentPrice Test Setting the median price of an Asset +// Test Setting the current price of an Asset func TestKeeper_GetSetCurrentPrice(t *testing.T) { _, addrs := sample.PrivKeyAddressPairs(5) app, ctx := testapp.NewNibiruAppAndContext(true) keeper := app.PricefeedKeeper - token0, token1 := "tst", "usd" - pair := common.AssetPair{Token0: token0, Token1: token1} - params := types.Params{ + pair := common.PairBTCStable + keeper.OraclesStore().AddOracles(ctx, pair, addrs) + keeper.SetParams(ctx, types.Params{ Pairs: common.AssetPairs{pair}, TwapLookbackWindow: 15 * time.Minute, - } - keeper.OraclesStore().AddOracles(ctx, pair, addrs) - keeper.SetParams(ctx, params) + }) - _, err := keeper.PostRawPrice( - ctx, addrs[0], pair.String(), - sdk.MustNewDecFromStr("0.33"), - time.Now().Add(time.Hour*1)) + _, err := keeper.PostRawPrice(ctx, addrs[0], pair.String(), sdk.MustNewDecFromStr("0.33"), time.Now().Add(time.Hour)) require.NoError(t, err) - _, err = keeper.PostRawPrice( - ctx, addrs[1], pair.String(), - sdk.MustNewDecFromStr("0.35"), - time.Now().Add(time.Hour*1)) + _, err = keeper.PostRawPrice(ctx, addrs[1], pair.String(), sdk.MustNewDecFromStr("0.35"), time.Now().Add(time.Hour)) require.NoError(t, err) - _, err = keeper.PostRawPrice( - ctx, addrs[2], pair.String(), - sdk.MustNewDecFromStr("0.34"), - time.Now().Add(time.Hour*1)) + _, err = keeper.PostRawPrice(ctx, addrs[2], pair.String(), sdk.MustNewDecFromStr("0.34"), time.Now().Add(time.Hour)) require.NoError(t, err) t.Log("Add an expired one which should fail") - _, err = keeper.PostRawPrice( - ctx, addrs[3], pair.String(), - sdk.MustNewDecFromStr("0.9"), - ctx.BlockTime().Add(-time.Hour*1)) + _, err = keeper.PostRawPrice(ctx, addrs[3], pair.String(), sdk.MustNewDecFromStr("0.9"), ctx.BlockTime().Add(-time.Hour)) require.Error(t, err) t.Log("Add a non-expired price, but will not be counted when BlockTime is changed") - _, err = keeper.PostRawPrice( - ctx, addrs[3], pair.String(), - sdk.MustNewDecFromStr("0.9"), - time.Now().Add(time.Minute*30)) + _, err = keeper.PostRawPrice(ctx, addrs[3], pair.String(), sdk.MustNewDecFromStr("0.9"), time.Now().Add(time.Minute*30)) require.NoError(t, err) // Update block time such that first 3 prices valid but last one is expired ctx = ctx.WithBlockTime(time.Now().Add(time.Minute * 45)).WithBlockHeight(1) // Set current price - err = keeper.GatherRawPrices(ctx, token0, token1) - require.NoError(t, err) + require.NoError(t, keeper.GatherRawPrices(ctx, pair.Token0, pair.Token1)) - // Get current price - price, err := keeper.GetCurrentPrice(ctx, token0, token1) + // Get current currentPrice + currentPrice, err := keeper.GetCurrentPrice(ctx, pair.Token0, pair.Token1) require.NoError(t, err) + assert.Equal(t, sdk.MustNewDecFromStr("0.34"), currentPrice.Price) - expCurPrice := sdk.MustNewDecFromStr("0.34") - require.Truef( - t, - price.Price.Equal(expCurPrice), - "expected current price to equal %s, actual %s", - expCurPrice, price.Price, - ) - - // Allow some time to pass - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(1 * time.Minute)) // Check TWAP Price - twap, err := keeper.GetCurrentTWAP(ctx, token0, token1) - expectedTwap := sdk.MustNewDecFromStr("0.34") + twap, err := keeper.GetCurrentTWAP(ctx, pair.Token0, pair.Token1) require.NoError(t, err) - assert.Equal(t, expectedTwap, twap, "expected twap price to be: %s, got: %s", expectedTwap, twap) + assert.Equal(t, sdk.MustNewDecFromStr("0.34"), twap) // fast forward block height as twap snapshots are indexed by blockHeight ctx = ctx.WithBlockHeight(2).WithBlockTime(ctx.BlockTime().Add(10 * time.Second)) // Even number of oracles - _, err = keeper.PostRawPrice( - ctx, addrs[4], pair.String(), - sdk.MustNewDecFromStr("0.36"), - time.Now().Add(time.Hour*1)) - require.NoError(t, err) - - err = keeper.GatherRawPrices(ctx, token0, token1) + _, err = keeper.PostRawPrice(ctx, addrs[4], pair.String(), sdk.MustNewDecFromStr("0.36"), time.Now().Add(time.Hour)) require.NoError(t, err) + require.NoError(t, keeper.GatherRawPrices(ctx, pair.Token0, pair.Token1)) - price, err = keeper.GetCurrentPrice(ctx, "tst", "usd") + currentPrice, err = keeper.GetCurrentPrice(ctx, pair.Token0, pair.Token1) require.Nil(t, err) - - exp := sdk.MustNewDecFromStr("0.345") - require.Truef(t, price.Price.Equal(exp), - "current price %s should be %s", - price.Price.String(), - exp.String(), - ) + require.Equal(t, sdk.MustNewDecFromStr("0.345"), currentPrice.Price) prices := keeper.GetCurrentPrices(ctx) require.Equal(t, 1, len(prices)) - require.Equal(t, price, prices[0]) + require.Equal(t, currentPrice, prices[0]) - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(10 * time.Second)) // Check TWAP Price - twap, err = keeper.GetCurrentTWAP(ctx, token0, token1) - expectedTwap = sdk.MustNewDecFromStr("0.340625") + ctx = ctx.WithBlockHeight(3).WithBlockTime(ctx.BlockTime().Add(10 * time.Second)) + twap, err = keeper.GetCurrentTWAP(ctx, pair.Token0, pair.Token1) require.NoError(t, err) - require.Truef( - t, - twap.Equal(expectedTwap), - "expected twap price to be: %s, got: %s", - expectedTwap, twap, - ) + require.Equal(t, sdk.MustNewDecFromStr("0.3425"), twap) } func TestKeeper_ExpiredGatherRawPrices(t *testing.T) { diff --git a/x/pricefeed/types/market.go b/x/pricefeed/types/market.go index a7af8f3c9..e0f0fd669 100644 --- a/x/pricefeed/types/market.go +++ b/x/pricefeed/types/market.go @@ -75,11 +75,6 @@ func NewCurrentTWAP(token0 string, token1 string, numerator sdk.Dec, denominator // CurrentPrices is a slice of CurrentPrice type CurrentPrices []CurrentPrice -// NewCurrentPriceResponse returns an instance of CurrentPriceResponse -func NewCurrentPriceResponse(pairID string, price sdk.Dec) CurrentPriceResponse { - return CurrentPriceResponse{PairID: pairID, Price: price} -} - // CurrentPriceResponses is a slice of CurrentPriceResponse type CurrentPriceResponses []CurrentPriceResponse diff --git a/x/pricefeed/types/query.pb.go b/x/pricefeed/types/query.pb.go index e63a6e450..47669df7d 100644 --- a/x/pricefeed/types/query.pb.go +++ b/x/pricefeed/types/query.pb.go @@ -556,8 +556,11 @@ func (m *PostedPriceResponse) GetExpiry() time.Time { // CurrentPriceResponse defines a current price for a particular 'PairID' in the pricefeed // module. type CurrentPriceResponse struct { - PairID string `protobuf:"bytes,1,opt,name=pair_id,json=pairId,proto3" json:"pair_id,omitempty"` - Price github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=price,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"price"` + PairID string `protobuf:"bytes,1,opt,name=pair_id,json=pairId,proto3" json:"pair_id,omitempty"` + // most current price of the trading pair + Price github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=price,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"price"` + // twap of the trading pair + Twap github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=twap,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"twap"` } func (m *CurrentPriceResponse) Reset() { *m = CurrentPriceResponse{} } @@ -682,60 +685,61 @@ func init() { func init() { proto.RegisterFile("pricefeed/query.proto", fileDescriptor_d96dcacfb6f84073) } var fileDescriptor_d96dcacfb6f84073 = []byte{ - // 843 bytes of a gzipped FileDescriptorProto + // 854 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x94, 0x4f, 0x4f, 0x1b, 0x47, - 0x18, 0xc6, 0xbd, 0x06, 0x6c, 0x18, 0x5a, 0xaa, 0x0e, 0x36, 0xb5, 0x5c, 0xba, 0xa6, 0x8b, 0x0a, - 0x06, 0xca, 0xae, 0x30, 0x2d, 0x52, 0xab, 0x5e, 0x6a, 0x68, 0xa5, 0x1e, 0x9a, 0xc0, 0x2a, 0xca, - 0x21, 0x17, 0x67, 0xec, 0x1d, 0xcc, 0x0a, 0xec, 0x5d, 0x66, 0xd7, 0xfc, 0x51, 0xc4, 0x21, 0x51, - 0x22, 0x45, 0x39, 0x44, 0x44, 0xb9, 0xe4, 0xc8, 0x31, 0xca, 0x27, 0xe1, 0x88, 0x94, 0x4b, 0x94, - 0x03, 0x10, 0x93, 0x7c, 0x8f, 0x68, 0x67, 0xde, 0x35, 0xbb, 0x66, 0xfd, 0x27, 0xca, 0xc9, 0xde, - 0x99, 0x79, 0xde, 0xe7, 0x37, 0xef, 0xbe, 0xfb, 0xa0, 0xb4, 0xcd, 0xcc, 0x0a, 0xdd, 0xa4, 0xd4, - 0xd0, 0x76, 0x1b, 0x94, 0x1d, 0xaa, 0x36, 0xb3, 0x5c, 0x0b, 0x8f, 0xd7, 0xcd, 0xb2, 0xc9, 0x1a, - 0x6a, 0x6b, 0x57, 0xdd, 0x5b, 0xca, 0xa6, 0xaa, 0x56, 0xd5, 0xe2, 0xfb, 0x9a, 0xf7, 0x4f, 0x1c, - 0xcd, 0x4e, 0x56, 0x2d, 0xab, 0xba, 0x43, 0x35, 0x62, 0x9b, 0x1a, 0xa9, 0xd7, 0x2d, 0x97, 0xb8, - 0xa6, 0x55, 0x77, 0x60, 0x37, 0x07, 0xbb, 0xfc, 0xa9, 0xdc, 0xd8, 0xd4, 0x5c, 0xb3, 0x46, 0x1d, - 0x97, 0xd4, 0x6c, 0x38, 0x30, 0x71, 0x0d, 0x60, 0x13, 0x46, 0x6a, 0x20, 0x54, 0x52, 0x08, 0x6f, - 0x78, 0x40, 0xeb, 0x7c, 0x51, 0xa7, 0xbb, 0x0d, 0xea, 0xb8, 0xca, 0x5d, 0x34, 0x1e, 0x5a, 0x75, - 0x6c, 0xab, 0xee, 0x50, 0xfc, 0x07, 0x4a, 0x08, 0x71, 0x46, 0x9a, 0x92, 0xf2, 0xa3, 0x85, 0x1f, - 0xd5, 0x08, 0x7e, 0x55, 0x88, 0x8a, 0x83, 0xa7, 0xe7, 0xb9, 0x98, 0x0e, 0x82, 0x3f, 0x07, 0x9f, - 0x9e, 0xe4, 0x62, 0x4a, 0x01, 0x7d, 0x2f, 0xea, 0x7a, 0xe7, 0xc1, 0x0c, 0xff, 0x80, 0x92, 0x36, - 0x31, 0x59, 0xc9, 0x34, 0x78, 0xd9, 0x11, 0x4f, 0x63, 0xb2, 0xff, 0x0c, 0xd0, 0x10, 0x9f, 0x50, - 0x68, 0x00, 0xe5, 0x1f, 0x34, 0xc4, 0x4d, 0x81, 0x64, 0x2e, 0x92, 0x64, 0xb5, 0xc1, 0x18, 0xad, - 0xbb, 0x21, 0x25, 0x70, 0x09, 0x35, 0x58, 0xa4, 0x82, 0x16, 0xad, 0x26, 0x1c, 0xf9, 0x4d, 0x80, - 0x55, 0x70, 0xbe, 0x8f, 0x12, 0x5c, 0xeb, 0x35, 0x61, 0xe0, 0xcb, 0xac, 0x7f, 0xf2, 0xac, 0xdf, - 0x5c, 0xe4, 0xd2, 0x51, 0xbb, 0x8e, 0x0e, 0x75, 0x01, 0x6a, 0x05, 0xa5, 0xb9, 0xbd, 0x4e, 0xf6, - 0x43, 0x5c, 0xbd, 0xfa, 0xf5, 0x44, 0x42, 0x13, 0xed, 0x42, 0x40, 0xa7, 0x08, 0x31, 0xb2, 0x5f, - 0x0a, 0xe1, 0xe7, 0xa3, 0xdf, 0xa1, 0xe5, 0xb8, 0xd4, 0x08, 0xd3, 0x4f, 0x02, 0x7d, 0x2a, 0x62, - 0xd3, 0xd1, 0x47, 0x98, 0x6f, 0x07, 0x1c, 0xbf, 0x41, 0xfb, 0x6e, 0x33, 0x52, 0xd9, 0xe9, 0x9b, - 0x7e, 0x05, 0xa5, 0xc2, 0x2a, 0x40, 0xcf, 0xa0, 0xa4, 0x25, 0x96, 0x38, 0xf7, 0x88, 0xee, 0x3f, - 0x82, 0x2e, 0x0d, 0x6e, 0xff, 0x13, 0xb6, 0x4d, 0xdd, 0xd6, 0x3b, 0x34, 0xa0, 0x5c, 0x6b, 0x19, - 0xca, 0xfd, 0x8b, 0x92, 0x35, 0xb1, 0x04, 0x6d, 0x88, 0x1e, 0x65, 0x21, 0x2b, 0x7e, 0x07, 0x37, - 0x4f, 0xfa, 0x65, 0x7c, 0x31, 0x98, 0x7f, 0x92, 0xd0, 0x78, 0x44, 0x53, 0xf0, 0x74, 0xdb, 0x5d, - 0x8b, 0xa8, 0x79, 0x9e, 0x4b, 0xac, 0x7b, 0xf7, 0x5d, 0xf3, 0xef, 0x8d, 0x7f, 0x41, 0x63, 0xe2, - 0x2a, 0x25, 0x62, 0x18, 0x8c, 0x3a, 0x4e, 0x26, 0xce, 0xfb, 0xf2, 0xad, 0x58, 0xfd, 0x5b, 0x2c, - 0xe2, 0x35, 0x7f, 0xe0, 0x07, 0x78, 0x25, 0xd5, 0x43, 0x7a, 0x7f, 0x9e, 0x9b, 0xa9, 0x9a, 0xee, - 0x56, 0xa3, 0xac, 0x56, 0xac, 0x9a, 0x56, 0xb1, 0x9c, 0x9a, 0xe5, 0xc0, 0xcf, 0xa2, 0x63, 0x6c, - 0x6b, 0xee, 0xa1, 0x4d, 0x1d, 0x75, 0x8d, 0x56, 0x60, 0xde, 0xf1, 0x5f, 0x28, 0x41, 0x0f, 0x6c, - 0x93, 0x1d, 0x66, 0x06, 0xf9, 0x77, 0x93, 0x55, 0x45, 0x70, 0xa8, 0x7e, 0x70, 0xa8, 0x77, 0xfc, - 0xe0, 0x28, 0x0e, 0x7b, 0x16, 0xc7, 0x17, 0x39, 0x49, 0x07, 0x8d, 0xf2, 0x50, 0x42, 0xa9, 0xa8, - 0xd1, 0xed, 0xef, 0xa2, 0xad, 0x1b, 0xc4, 0xbf, 0xe2, 0x06, 0x4a, 0x09, 0x25, 0xc4, 0x5b, 0xe8, - 0xcf, 0x34, 0x30, 0x37, 0xf1, 0xd0, 0xdc, 0xe0, 0x09, 0x94, 0x20, 0x15, 0xd7, 0xdc, 0x13, 0x1d, - 0x1d, 0xd6, 0xe1, 0xa9, 0xf0, 0x38, 0x89, 0x86, 0xf8, 0xcc, 0xe0, 0x67, 0x12, 0x1a, 0x0d, 0xc4, - 0x20, 0x9e, 0x8d, 0x9c, 0x91, 0x9b, 0xf1, 0x99, 0xcd, 0xf7, 0x3e, 0x28, 0x1a, 0xa7, 0xe4, 0x1f, - 0xbd, 0xfd, 0xf8, 0x32, 0xae, 0xe0, 0x29, 0x4d, 0x28, 0xb4, 0xeb, 0x98, 0xde, 0x5b, 0x2a, 0x53, - 0x97, 0x2c, 0x41, 0x5c, 0xe3, 0x17, 0x12, 0x42, 0xd7, 0x71, 0x84, 0x67, 0xba, 0x58, 0x04, 0xc2, - 0x35, 0x3b, 0xdb, 0xf3, 0x1c, 0x90, 0x14, 0x38, 0xc9, 0xaf, 0x78, 0xbe, 0x0b, 0x09, 0xff, 0xbc, - 0xb5, 0x07, 0xd0, 0xf5, 0xa3, 0x40, 0x83, 0xf8, 0x0e, 0xee, 0x65, 0xd6, 0x57, 0x83, 0x42, 0x91, - 0xd5, 0x57, 0x83, 0x84, 0xf9, 0x89, 0x84, 0xc6, 0xc2, 0xb9, 0x87, 0xe7, 0x3b, 0xdb, 0xb4, 0xa7, - 0x6a, 0x76, 0xa1, 0xaf, 0xb3, 0x40, 0xf5, 0x3b, 0xa7, 0xd2, 0xf0, 0x62, 0x67, 0x2a, 0x46, 0xf6, - 0x6f, 0xf4, 0xeb, 0x95, 0x84, 0xbe, 0x09, 0xa6, 0x1b, 0xee, 0xd2, 0x87, 0x70, 0x6c, 0x66, 0xe7, - 0xfa, 0x38, 0x09, 0x70, 0xcb, 0x1c, 0x6e, 0x11, 0x2f, 0x74, 0x86, 0x83, 0x6f, 0x20, 0x80, 0xf6, - 0xdc, 0x47, 0x83, 0x88, 0xeb, 0x86, 0x16, 0xce, 0xd8, 0x6e, 0x68, 0x6d, 0xb1, 0xab, 0xcc, 0x71, - 0xb4, 0x69, 0xfc, 0x73, 0x67, 0x34, 0x48, 0xd6, 0xe2, 0xc6, 0xe5, 0x07, 0x59, 0x7a, 0xdd, 0x94, - 0xa5, 0xd3, 0xa6, 0x2c, 0x9d, 0x35, 0x65, 0xe9, 0xb2, 0x29, 0x4b, 0xc7, 0x57, 0x72, 0xec, 0xec, - 0x4a, 0x8e, 0xbd, 0xbb, 0x92, 0x63, 0xf7, 0xb4, 0x40, 0x70, 0xdc, 0xe2, 0xe5, 0x56, 0xb7, 0x88, - 0x59, 0xf7, 0x4b, 0x1f, 0x04, 0x8a, 0xf3, 0x14, 0x29, 0x27, 0x78, 0xc8, 0x2d, 0x7f, 0x0e, 0x00, - 0x00, 0xff, 0xff, 0x3a, 0x8f, 0x28, 0x79, 0x8d, 0x09, 0x00, 0x00, + 0x18, 0xc6, 0xbd, 0xc6, 0xd8, 0x30, 0xb4, 0x54, 0x1d, 0x6c, 0x6a, 0xb9, 0x74, 0x4d, 0x17, 0x15, + 0x0c, 0x94, 0x5d, 0x61, 0x5a, 0xa4, 0x56, 0xbd, 0xd4, 0xd0, 0x4a, 0x3d, 0xb4, 0x85, 0x55, 0xd5, + 0x43, 0x2f, 0xee, 0xd8, 0x3b, 0x98, 0x15, 0xd8, 0xbb, 0xcc, 0xae, 0x31, 0xa8, 0xe2, 0x52, 0xb5, + 0x52, 0x94, 0x43, 0x44, 0x94, 0x4b, 0x8e, 0x1c, 0xa3, 0x7c, 0x8f, 0x48, 0x1c, 0x91, 0x72, 0x89, + 0x72, 0x00, 0x62, 0x92, 0xef, 0x11, 0xed, 0xcc, 0xbb, 0x66, 0xd7, 0xac, 0xff, 0x24, 0x39, 0xc1, + 0xce, 0xcc, 0xf3, 0xbe, 0xbf, 0x79, 0xe6, 0xf5, 0x83, 0x32, 0x36, 0x33, 0xab, 0x74, 0x87, 0x52, + 0x43, 0x3b, 0x68, 0x52, 0x76, 0xac, 0xda, 0xcc, 0x72, 0x2d, 0x3c, 0xd5, 0x30, 0x2b, 0x26, 0x6b, + 0xaa, 0x9d, 0x5d, 0xf5, 0x70, 0x35, 0x97, 0xae, 0x59, 0x35, 0x8b, 0xef, 0x6b, 0xde, 0x7f, 0xe2, + 0x68, 0x6e, 0xa6, 0x66, 0x59, 0xb5, 0x7d, 0xaa, 0x11, 0xdb, 0xd4, 0x48, 0xa3, 0x61, 0xb9, 0xc4, + 0x35, 0xad, 0x86, 0x03, 0xbb, 0x79, 0xd8, 0xe5, 0x5f, 0x95, 0xe6, 0x8e, 0xe6, 0x9a, 0x75, 0xea, + 0xb8, 0xa4, 0x6e, 0xc3, 0x81, 0xe9, 0x5b, 0x00, 0x9b, 0x30, 0x52, 0x07, 0xa1, 0x92, 0x46, 0x78, + 0xdb, 0x03, 0xda, 0xe2, 0x8b, 0x3a, 0x3d, 0x68, 0x52, 0xc7, 0x55, 0xfe, 0x44, 0x53, 0xa1, 0x55, + 0xc7, 0xb6, 0x1a, 0x0e, 0xc5, 0xdf, 0xa1, 0xa4, 0x10, 0x67, 0xa5, 0x59, 0xa9, 0x30, 0x51, 0xfc, + 0x5c, 0x8d, 0xe0, 0x57, 0x85, 0xa8, 0x94, 0x38, 0xbf, 0xcc, 0xc7, 0x74, 0x10, 0x7c, 0x9f, 0xb8, + 0x77, 0x96, 0x8f, 0x29, 0x45, 0xf4, 0xa9, 0xa8, 0xeb, 0x9d, 0x87, 0x66, 0xf8, 0x33, 0x94, 0xb2, + 0x89, 0xc9, 0xca, 0xa6, 0xc1, 0xcb, 0x8e, 0x7b, 0x1a, 0x93, 0xfd, 0x62, 0x80, 0x86, 0xf8, 0x84, + 0x42, 0x03, 0x28, 0x3f, 0xa1, 0x51, 0xde, 0x14, 0x48, 0x16, 0x23, 0x49, 0x36, 0x9a, 0x8c, 0xd1, + 0x86, 0x1b, 0x52, 0x02, 0x97, 0x50, 0x43, 0x8b, 0x74, 0xb0, 0x45, 0xc7, 0x84, 0x13, 0xdf, 0x04, + 0x58, 0x85, 0xce, 0x7f, 0xa3, 0x24, 0xd7, 0x7a, 0x26, 0x8c, 0xbc, 0x5b, 0xeb, 0x2f, 0xbc, 0xd6, + 0x4f, 0xaf, 0xf2, 0x99, 0xa8, 0x5d, 0x47, 0x87, 0xba, 0x00, 0xb5, 0x8e, 0x32, 0xbc, 0xbd, 0x4e, + 0x5a, 0x21, 0xae, 0x41, 0x7e, 0xfd, 0x2f, 0xa1, 0xe9, 0x6e, 0x21, 0xa0, 0x53, 0x84, 0x18, 0x69, + 0x95, 0x43, 0xf8, 0x85, 0xe8, 0x37, 0xb4, 0x1c, 0x97, 0x1a, 0x61, 0xfa, 0x19, 0xa0, 0x4f, 0x47, + 0x6c, 0x3a, 0xfa, 0x38, 0xf3, 0xdb, 0x01, 0xc7, 0x37, 0x60, 0xdf, 0xef, 0x8c, 0x54, 0xf7, 0x87, + 0xa6, 0x5f, 0x47, 0xe9, 0xb0, 0x0a, 0xd0, 0xb3, 0x28, 0x65, 0x89, 0x25, 0xce, 0x3d, 0xae, 0xfb, + 0x9f, 0xa0, 0xcb, 0x40, 0xb7, 0x5f, 0x09, 0xdb, 0xa3, 0x6e, 0xe7, 0x0d, 0x0d, 0x28, 0xd7, 0x59, + 0x86, 0x72, 0x3f, 0xa3, 0x54, 0x5d, 0x2c, 0x81, 0x0d, 0xd1, 0xa3, 0x2c, 0x64, 0xa5, 0x4f, 0xe0, + 0xe6, 0x29, 0xbf, 0x8c, 0x2f, 0x86, 0xe6, 0x6f, 0x24, 0x34, 0x15, 0x61, 0x0a, 0x9e, 0xeb, 0xba, + 0x6b, 0x09, 0xb5, 0x2f, 0xf3, 0xc9, 0x2d, 0xef, 0xbe, 0x9b, 0xfe, 0xbd, 0xf1, 0x57, 0x68, 0x52, + 0x5c, 0xa5, 0x4c, 0x0c, 0x83, 0x51, 0xc7, 0xc9, 0xc6, 0xb9, 0x2f, 0x1f, 0x8b, 0xd5, 0x1f, 0xc5, + 0x22, 0xde, 0xf4, 0x07, 0x7e, 0x84, 0x57, 0x52, 0x3d, 0xa4, 0x97, 0x97, 0xf9, 0xf9, 0x9a, 0xe9, + 0xee, 0x36, 0x2b, 0x6a, 0xd5, 0xaa, 0x6b, 0x55, 0xcb, 0xa9, 0x5b, 0x0e, 0xfc, 0x59, 0x71, 0x8c, + 0x3d, 0xcd, 0x3d, 0xb6, 0xa9, 0xa3, 0x6e, 0xd2, 0x2a, 0xcc, 0x3b, 0xfe, 0x01, 0x25, 0xe9, 0x91, + 0x6d, 0xb2, 0xe3, 0x6c, 0x82, 0xff, 0x6e, 0x72, 0xaa, 0x08, 0x0e, 0xd5, 0x0f, 0x0e, 0xf5, 0x0f, + 0x3f, 0x38, 0x4a, 0x63, 0x5e, 0x8b, 0xd3, 0xab, 0xbc, 0xa4, 0x83, 0x46, 0x79, 0x26, 0xa1, 0x74, + 0xd4, 0xe8, 0x0e, 0x77, 0xd1, 0xce, 0x0d, 0xe2, 0x1f, 0x72, 0x83, 0x12, 0x4a, 0xb8, 0x2d, 0x62, + 0xbf, 0xa7, 0x0d, 0x5c, 0xab, 0x94, 0x51, 0x52, 0xbc, 0xe4, 0x70, 0xe0, 0x81, 0xd9, 0x8b, 0x87, + 0x66, 0x0f, 0x4f, 0xa3, 0x24, 0xa9, 0xba, 0xe6, 0xa1, 0x78, 0x95, 0x31, 0x1d, 0xbe, 0x8a, 0xff, + 0xa5, 0xd0, 0x28, 0x9f, 0x3b, 0x7c, 0x5f, 0x42, 0x13, 0x81, 0x28, 0xc5, 0x0b, 0x91, 0x73, 0x76, + 0x37, 0x82, 0x73, 0x85, 0xc1, 0x07, 0x85, 0xf9, 0x4a, 0xe1, 0xdf, 0xe7, 0xaf, 0x1f, 0xc5, 0x15, + 0x3c, 0xab, 0x09, 0x85, 0x76, 0x1b, 0xf5, 0x87, 0xab, 0x15, 0xea, 0x92, 0x55, 0x88, 0x7c, 0xfc, + 0x50, 0x42, 0xe8, 0x36, 0xd2, 0xf0, 0x7c, 0x9f, 0x16, 0x81, 0x80, 0xce, 0x2d, 0x0c, 0x3c, 0x07, + 0x24, 0x45, 0x4e, 0xf2, 0x35, 0x5e, 0xea, 0x43, 0xc2, 0x23, 0x42, 0xfb, 0x07, 0x5c, 0x3f, 0x09, + 0x18, 0xc4, 0x77, 0xf0, 0xa0, 0x66, 0x43, 0x19, 0x14, 0x8a, 0xbd, 0xa1, 0x0c, 0x12, 0xcd, 0xcf, + 0x24, 0x34, 0x19, 0xce, 0x4e, 0xbc, 0xd4, 0xbb, 0x4d, 0x77, 0x32, 0xe7, 0x96, 0x87, 0x3a, 0x0b, + 0x54, 0xdf, 0x72, 0x2a, 0x0d, 0xaf, 0xf4, 0xa6, 0x62, 0xa4, 0x75, 0xc7, 0xaf, 0xc7, 0x12, 0xfa, + 0x28, 0x98, 0x90, 0xb8, 0x8f, 0x0f, 0xe1, 0xe8, 0xcd, 0x2d, 0x0e, 0x71, 0x12, 0xe0, 0xd6, 0x38, + 0xdc, 0x0a, 0x5e, 0xee, 0x0d, 0x07, 0xbf, 0x81, 0x00, 0xda, 0x03, 0x1f, 0x0d, 0x62, 0xb2, 0x1f, + 0x5a, 0x38, 0xa7, 0xfb, 0xa1, 0x75, 0x45, 0xb7, 0xb2, 0xc8, 0xd1, 0xe6, 0xf0, 0x97, 0xbd, 0xd1, + 0x20, 0x9d, 0x4b, 0xdb, 0xd7, 0xaf, 0x64, 0xe9, 0x49, 0x5b, 0x96, 0xce, 0xdb, 0xb2, 0x74, 0xd1, + 0x96, 0xa5, 0xeb, 0xb6, 0x2c, 0x9d, 0xde, 0xc8, 0xb1, 0x8b, 0x1b, 0x39, 0xf6, 0xe2, 0x46, 0x8e, + 0xfd, 0xa5, 0x05, 0x72, 0xe3, 0x37, 0x5e, 0x6e, 0x63, 0x97, 0x98, 0x0d, 0xbf, 0xf4, 0x51, 0xa0, + 0x38, 0x0f, 0x91, 0x4a, 0x92, 0x07, 0xe5, 0xda, 0xdb, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7f, 0x5d, + 0x09, 0xba, 0xd1, 0x09, 0x00, 0x00, } func (this *QueryParamsRequest) VerboseEqual(that interface{}) error { @@ -1511,6 +1515,9 @@ func (this *CurrentPriceResponse) VerboseEqual(that interface{}) error { if !this.Price.Equal(that1.Price) { return fmt.Errorf("Price this(%v) Not Equal that(%v)", this.Price, that1.Price) } + if !this.Twap.Equal(that1.Twap) { + return fmt.Errorf("Twap this(%v) Not Equal that(%v)", this.Twap, that1.Twap) + } return nil } func (this *CurrentPriceResponse) Equal(that interface{}) bool { @@ -1538,6 +1545,9 @@ func (this *CurrentPriceResponse) Equal(that interface{}) bool { if !this.Price.Equal(that1.Price) { return false } + if !this.Twap.Equal(that1.Twap) { + return false + } return true } func (this *Market) VerboseEqual(that interface{}) error { @@ -2332,6 +2342,16 @@ func (m *CurrentPriceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + { + size := m.Twap.Size() + i -= size + if _, err := m.Twap.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a { size := m.Price.Size() i -= size @@ -2593,6 +2613,8 @@ func (m *CurrentPriceResponse) Size() (n int) { } l = m.Price.Size() n += 1 + l + sovQuery(uint64(l)) + l = m.Twap.Size() + n += 1 + l + sovQuery(uint64(l)) return n } @@ -3796,6 +3818,40 @@ func (m *CurrentPriceResponse) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Twap", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Twap.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) From 701b27fc9dc9418098258ddba9e6333da57186cb Mon Sep 17 00:00:00 2001 From: Mat-Cosmos <97468149+matthiasmatt@users.noreply.github.com> Date: Mon, 15 Aug 2022 09:35:01 -0300 Subject: [PATCH 4/7] feat(app): Make post price txs gasless (#817) * feat: Gasless txs for post price and liquidate * fix: Fix anteHandler call to include keepers * fix: Update changelog and lint fix * fix: merge with master * fix,docs: vpool gov cli test * docs(vpool,pricefeed): readadbility and cli commenets for the gov cli tests * fix: check for error on chainedhandler * wip: Update the fees to 0 in cli test for pricefeed * feat: Fork fee deduct ante-handler * fix: Remove unused function * tests: Add test for gas or no gas in post price cli test * feat: Update changelog * fix: Remove perpkeeper from gasless ante * fix: Remove println from codebase * test gasmeter infinite * change test for gassless decorator * update gasless test * remove unused code * fix comment * remove unused code * linter * linter 2 * final clean * remove unused func * remove comment * fix: Fix logic on pricefeed query tests for cli_test * test: Add test for simulation run * fix: Remove nil check for address of variable Co-authored-by: matthiasmatt Co-authored-by: Unique-Divine Co-authored-by: AgentSmithMatrix <98403347+AgentSmithMatrix@users.noreply.github.com> Co-authored-by: Agent Smith --- CHANGELOG.md | 1 + Makefile | 4 +- app/ante.go | 10 +- app/antedecorators/fee/fee.go | 84 ++++++++++++ app/antedecorators/fee/fee_test.go | 54 ++++++++ app/antedecorators/fee/testutil_test.go | 119 +++++++++++++++++ app/antedecorators/gasless/gasless.go | 57 ++++++++ app/antedecorators/gasless/gasless_test.go | 144 +++++++++++++++++++++ app/antedecorators/types/gas.go | 46 +++++++ app/app.go | 3 +- go.mod | 4 +- x/dex/client/testutil/cli_test.go | 3 - x/epochs/keeper/epoch.go | 1 - x/perp/keeper/clearing_house.go | 1 - x/perp/spec/01_concepts.md | 15 +-- x/pricefeed/client/cli/cli_test.go | 100 ++++++++++---- x/vpool/client/cli/cli_test.go | 48 ++++--- x/vpool/keeper/keeper.go | 3 +- 18 files changed, 626 insertions(+), 71 deletions(-) create mode 100644 app/antedecorators/fee/fee.go create mode 100644 app/antedecorators/fee/fee_test.go create mode 100644 app/antedecorators/fee/testutil_test.go create mode 100644 app/antedecorators/gasless/gasless.go create mode 100644 app/antedecorators/gasless/gasless_test.go create mode 100644 app/antedecorators/types/gas.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 79af36d76..a285db52d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#801](https://github.com/NibiruChain/nibiru/pull/801) - remove unused pair constants * [#788](https://github.com/NibiruChain/nibiru/pull/788) - add --overwrite flag to the nibid init call of localnet.sh * [#804](https://github.com/NibiruChain/nibiru/pull/804) - bump ibc-go to v3.1.1 +* [#817](https://github.com/NibiruChain/nibiru/pull/817) - Make post prices transactions gasless for whitelisted oracles * [#818](https://github.com/NibiruChain/nibiru/pull/818) - fix(localnet.sh): add max leverage to vpools in genesis to fix open-position * [#819](https://github.com/NibiruChain/nibiru/pull/819) - add golangci-linter using docker in Makefile diff --git a/Makefile b/Makefile index 2e30d1412..8eb773cad 100644 --- a/Makefile +++ b/Makefile @@ -124,10 +124,10 @@ PACKAGES_NOSIMULATION = $(shell go list ./... | grep -v '/simapp') RUNSIM = $(BINDIR)/runsim test-unit: - go test $(PACKAGES_NOSIMULATION) -short -cover + @go test $(PACKAGES_NOSIMULATION) -short -cover test-integration: - go test -v $(PACKAGES_NOSIMULATION) -cover + @go test -v $(PACKAGES_NOSIMULATION) -cover runsim: $(RUNSIM) $(RUNSIM): diff --git a/app/ante.go b/app/ante.go index c16cb8b23..1586937ae 100644 --- a/app/ante.go +++ b/app/ante.go @@ -6,11 +6,18 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/ante" ibcante "github.com/cosmos/ibc-go/v3/modules/core/ante" ibckeeper "github.com/cosmos/ibc-go/v3/modules/core/keeper" + + gaslessante "github.com/NibiruChain/nibiru/app/antedecorators/gasless" + + feeante "github.com/NibiruChain/nibiru/app/antedecorators/fee" + pricefeedkeeper "github.com/NibiruChain/nibiru/x/pricefeed/keeper" ) type AnteHandlerOptions struct { ante.HandlerOptions IBCKeeper *ibckeeper.Keeper + + PricefeedKeeper pricefeedkeeper.Keeper } /* @@ -43,7 +50,8 @@ func NewAnteHandler(options AnteHandlerOptions) (sdk.AnteHandler, error) { ante.NewTxTimeoutHeightDecorator(), ante.NewValidateMemoDecorator(options.AccountKeeper), ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), - ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper), + gaslessante.NewGaslessDecorator(options.PricefeedKeeper), + feeante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper), // Replace fee ante from cosmos auth with a custom one. // SetPubKeyDecorator must be called before all signature verification decorators ante.NewSetPubKeyDecorator(options.AccountKeeper), ante.NewValidateSigCountDecorator(options.AccountKeeper), diff --git a/app/antedecorators/fee/fee.go b/app/antedecorators/fee/fee.go new file mode 100644 index 000000000..f6b29f4e8 --- /dev/null +++ b/app/antedecorators/fee/fee.go @@ -0,0 +1,84 @@ +package fee + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/x/auth/ante" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// DeductFeeDecorator deducts fees from the first signer of the tx +// If the first signer does not have the funds to pay for the fees, return with InsufficientFunds error +// Call next AnteHandler if fees successfully deducted +// CONTRACT: Tx must implement FeeTx interface to use DeductFeeDecorator +type DeductFeeDecorator struct { + ak ante.AccountKeeper + bankKeeper types.BankKeeper + feegrantKeeper ante.FeegrantKeeper +} + +func NewDeductFeeDecorator(ak ante.AccountKeeper, bk types.BankKeeper, fk ante.FeegrantKeeper) DeductFeeDecorator { + return DeductFeeDecorator{ + ak: ak, + bankKeeper: bk, + feegrantKeeper: fk, + } +} + +func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { + feeTx, ok := tx.(sdk.FeeTx) + if !ok { + return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx") + } + + if addr := dfd.ak.GetModuleAddress(types.FeeCollectorName); addr == nil { + return ctx, fmt.Errorf("fee collector module account (%s) has not been set", types.FeeCollectorName) + } + + fee := feeTx.GetFee() + feePayer := feeTx.FeePayer() + feeGranter := feeTx.FeeGranter() + + deductFeesFrom := feePayer + + // if feegranter set deduct fee from feegranter account. + // this works with only when feegrant enabled. + if feeGranter != nil { + if dfd.feegrantKeeper == nil { + return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "fee grants are not enabled") + } else if !feeGranter.Equals(feePayer) { + err := dfd.feegrantKeeper.UseGrantedFees(ctx, feeGranter, feePayer, fee, tx.GetMsgs()) + + if err != nil { + return ctx, sdkerrors.Wrapf(err, "%s not allowed to pay fees from %s", feeGranter, feePayer) + } + } + + deductFeesFrom = feeGranter + } + + deductFeesFromAcc := dfd.ak.GetAccount(ctx, deductFeesFrom) + if deductFeesFromAcc == nil { + return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "fee payer address: %s does not exist", deductFeesFrom) + } + + // Gas meter is set to 1 for gasless transactions. + // Depends on GasLessDecorator for this to happen. + if ctx.GasMeter().GasConsumed() == 1 { + // do nothing + } else if !feeTx.GetFee().IsZero() { + err = ante.DeductFees(dfd.bankKeeper, ctx, deductFeesFromAcc, feeTx.GetFee()) + if err != nil { + return ctx, err + } + } + + events := sdk.Events{sdk.NewEvent(sdk.EventTypeTx, + sdk.NewAttribute(sdk.AttributeKeyFee, feeTx.GetFee().String()), + )} + ctx.EventManager().EmitEvents(events) + + return next(ctx, tx, simulate) +} diff --git a/app/antedecorators/fee/fee_test.go b/app/antedecorators/fee/fee_test.go new file mode 100644 index 000000000..5beec11fa --- /dev/null +++ b/app/antedecorators/fee/fee_test.go @@ -0,0 +1,54 @@ +package fee_test + +import ( + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/NibiruChain/nibiru/app" + "github.com/NibiruChain/nibiru/app/antedecorators/fee" +) + +func (suite *AnteTestSuite) TestDeductFees() { + suite.SetupTest(false) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + + // keys and addresses + priv1, _, addr1 := testdata.KeyTestPubAddr() + + // msg and signatures + msg := testdata.NewTestMsg(addr1) + feeAmount := sdk.NewCoins(sdk.NewInt64Coin(app.BondDenom, 150)) + gasLimit := testdata.NewTestGasLimit() + suite.Require().NoError(suite.txBuilder.SetMsgs(msg)) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) + + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) + suite.Require().NoError(err) + + // Set account with insufficient funds + acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) + coins := sdk.NewCoins(sdk.NewCoin(app.BondDenom, sdk.NewInt(10))) + err = simapp.FundAccount(suite.app.BankKeeper, suite.ctx, addr1, coins) + suite.Require().NoError(err) + + dfd := fee.NewDeductFeeDecorator(suite.app.AccountKeeper, suite.app.BankKeeper, nil) + antehandler := sdk.ChainAnteDecorators(dfd) + + _, err = antehandler(suite.ctx, tx, false) + + suite.Require().NotNil(err, "Tx did not error when fee payer had insufficient funds") + + // Set account with sufficient funds + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) + err = simapp.FundAccount(suite.app.BankKeeper, suite.ctx, addr1, sdk.NewCoins(sdk.NewCoin(app.BondDenom, sdk.NewInt(200)))) + suite.Require().NoError(err) + + _, err = antehandler(suite.ctx, tx, false) + + suite.Require().Nil(err, "Tx errored after account has been set with sufficient funds") +} diff --git a/app/antedecorators/fee/testutil_test.go b/app/antedecorators/fee/testutil_test.go new file mode 100644 index 000000000..e955cce54 --- /dev/null +++ b/app/antedecorators/fee/testutil_test.go @@ -0,0 +1,119 @@ +package fee_test + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + "github.com/cosmos/cosmos-sdk/x/auth/ante" + xauthsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/stretchr/testify/suite" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + + "github.com/NibiruChain/nibiru/app" + "github.com/NibiruChain/nibiru/x/testutil/testapp" +) + +// AnteTestSuite is a test suite to be used with ante handler tests. +type AnteTestSuite struct { + suite.Suite + + app *app.NibiruApp + anteHandler sdk.AnteHandler + ctx sdk.Context + clientCtx client.Context + txBuilder client.TxBuilder +} + +// returns context and app with params set on account keeper +func createTestApp(isCheckTx bool) (*app.NibiruApp, sdk.Context) { + app := testapp.NewNibiruApp(true) + ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{}) + app.AccountKeeper.SetParams(ctx, authtypes.DefaultParams()) + + return app, ctx +} + +// SetupTest setups a new test, with new app, context, and anteHandler. +func (suite *AnteTestSuite) SetupTest(isCheckTx bool) { + suite.app, suite.ctx = createTestApp(isCheckTx) + suite.ctx = suite.ctx.WithBlockHeight(1) + + // Set up TxConfig. + encodingConfig := app.MakeTestEncodingConfig() + // We're using TestMsg encoding in some tests, so register it here. + encodingConfig.Amino.RegisterConcrete(&testdata.TestMsg{}, "testdata.TestMsg", nil) + testdata.RegisterInterfaces(encodingConfig.InterfaceRegistry) + + suite.clientCtx = client.Context{}. + WithTxConfig(encodingConfig.TxConfig) + + anteHandler, err := ante.NewAnteHandler( + ante.HandlerOptions{ + AccountKeeper: suite.app.AccountKeeper, + BankKeeper: suite.app.BankKeeper, + FeegrantKeeper: suite.app.FeeGrantKeeper, + SignModeHandler: encodingConfig.TxConfig.SignModeHandler(), + SigGasConsumer: ante.DefaultSigVerificationGasConsumer, + }, + ) + + suite.Require().NoError(err) + suite.anteHandler = anteHandler +} + +// CreateTestTx is a helper function to create a tx given multiple inputs. +func (suite *AnteTestSuite) CreateTestTx(privs []cryptotypes.PrivKey, accNums []uint64, accSeqs []uint64, chainID string) (xauthsigning.Tx, error) { + // First round: we gather all the signer infos. We use the "set empty + // signature" hack to do that. + var sigsV2 []signing.SignatureV2 + for i, priv := range privs { + sigV2 := signing.SignatureV2{ + PubKey: priv.PubKey(), + Data: &signing.SingleSignatureData{ + SignMode: suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(), + Signature: nil, + }, + Sequence: accSeqs[i], + } + + sigsV2 = append(sigsV2, sigV2) + } + err := suite.txBuilder.SetSignatures(sigsV2...) + if err != nil { + return nil, err + } + + // Second round: all signer infos are set, so each signer can sign. + sigsV2 = []signing.SignatureV2{} + for i, priv := range privs { + signerData := xauthsigning.SignerData{ + ChainID: chainID, + AccountNumber: accNums[i], + Sequence: accSeqs[i], + } + sigV2, err := tx.SignWithPrivKey( + suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(), signerData, + suite.txBuilder, priv, suite.clientCtx.TxConfig, accSeqs[i]) + if err != nil { + return nil, err + } + + sigsV2 = append(sigsV2, sigV2) + } + err = suite.txBuilder.SetSignatures(sigsV2...) + if err != nil { + return nil, err + } + + return suite.txBuilder.GetTx(), nil +} + +func TestAnteTestSuite(t *testing.T) { + suite.Run(t, new(AnteTestSuite)) +} diff --git a/app/antedecorators/gasless/gasless.go b/app/antedecorators/gasless/gasless.go new file mode 100644 index 000000000..0c57c8a92 --- /dev/null +++ b/app/antedecorators/gasless/gasless.go @@ -0,0 +1,57 @@ +package gasless + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + types "github.com/NibiruChain/nibiru/app/antedecorators/types" + "github.com/NibiruChain/nibiru/x/common" + pricefeedkeeper "github.com/NibiruChain/nibiru/x/pricefeed/keeper" + pricefeedtypes "github.com/NibiruChain/nibiru/x/pricefeed/types" +) + +type GaslessDecorator struct { + pricefeedKeeper pricefeedkeeper.Keeper +} + +func NewGaslessDecorator(pricefeedKeeper pricefeedkeeper.Keeper) GaslessDecorator { + return GaslessDecorator{pricefeedKeeper: pricefeedKeeper} +} + +func (gd GaslessDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { + if simulate || !isTxGasless(tx, ctx, gd.pricefeedKeeper) { + return next(ctx, tx, simulate) + } + + gaslessMeter := types.GasLessMeter() + return next(ctx.WithGasMeter(gaslessMeter), tx, simulate) +} + +func isTxGasless(tx sdk.Tx, ctx sdk.Context, pricefeedKeeper pricefeedkeeper.Keeper) bool { + if len(tx.GetMsgs()) == 0 { + // empty TX shouldn't be gasless + return false + } + for _, msg := range tx.GetMsgs() { + switch m := msg.(type) { + case *pricefeedtypes.MsgPostPrice: + if pricefeedPostPriceIsGasless(m, ctx, pricefeedKeeper) { + continue + } + return false + default: + return false + } + } + return true +} + +// Check if the sender is a whitelisted oracle +func pricefeedPostPriceIsGasless(msg *pricefeedtypes.MsgPostPrice, ctx sdk.Context, keeper pricefeedkeeper.Keeper) bool { + valAddr, err := sdk.AccAddressFromBech32(msg.Oracle) + if err != nil { + return false + } + + pair := common.AssetPair{Token0: msg.Token0, Token1: msg.Token1} + return keeper.IsWhitelistedOracle(ctx, pair.String(), valAddr) +} diff --git a/app/antedecorators/gasless/gasless_test.go b/app/antedecorators/gasless/gasless_test.go new file mode 100644 index 000000000..bff2e8613 --- /dev/null +++ b/app/antedecorators/gasless/gasless_test.go @@ -0,0 +1,144 @@ +package gasless_test + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + types3 "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/stretchr/testify/require" + + gaslessante "github.com/NibiruChain/nibiru/app/antedecorators/gasless" + types2 "github.com/NibiruChain/nibiru/app/antedecorators/types" + "github.com/NibiruChain/nibiru/x/pricefeed/types" + "github.com/NibiruChain/nibiru/x/testutil/sample" + "github.com/NibiruChain/nibiru/x/testutil/testapp" +) + +var oracleAddr = sample.AccAddress() + +type DecoratorWithNormalGasMeterCheck struct { + t *testing.T +} + +func (ad DecoratorWithNormalGasMeterCheck) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { + require.IsType(ad.t, sdk.NewGasMeter(111), ctx.GasMeter()) + + return next(ctx, tx, simulate) +} + +type DecoratorWithInfiniteGasMeterCheck struct { + t *testing.T +} + +func (ad DecoratorWithInfiniteGasMeterCheck) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { + require.IsType(ad.t, types2.GasLessMeter(), ctx.GasMeter()) + + return next(ctx, tx, simulate) +} + +type TxWithPostPriceMsg struct{} + +func (tx TxWithPostPriceMsg) GetMsgs() []sdk.Msg { + return []sdk.Msg{ + &types.MsgPostPrice{ + Oracle: oracleAddr.String(), + Token0: "unibi", + Token1: "unusd", + }, + } +} + +func (tx TxWithPostPriceMsg) ValidateBasic() error { + return nil +} + +type TxWithoutPostPriceMsg struct{} + +func (tx TxWithoutPostPriceMsg) GetMsgs() []sdk.Msg { + return []sdk.Msg{ + &types3.MsgSend{}, + } +} + +func (tx TxWithoutPostPriceMsg) ValidateBasic() error { + return nil +} + +func TestGaslessDecorator_Whitelisted(t *testing.T) { + tests := []struct { + name string + isWhitelisted bool + shouldChangeMeter bool + tx sdk.Tx + simulate bool + }{ + { + /* name */ "whitelisted address", + /* isWhitelisted */ true, + /* shouldChangeMeter */ true, + /* tx */ TxWithPostPriceMsg{}, + /* simulate */ false, + }, + { + /* name */ "whitelisted address, simulation", + /* isWhitelisted */ true, + /* shouldChangeMeter */ false, + /* tx */ TxWithPostPriceMsg{}, + /* simulate */ true, + }, + { + /* name */ "whitelisted address but tx without price feed message", + /* isWhitelisted */ true, + /* shouldChangeMeter */ false, + /* tx */ TxWithoutPostPriceMsg{}, + /* simulate */ false, + }, + { + /* name */ "not whitelisted address with post price tx", + /* isWhitelisted */ false, + /* shouldChangeMeter */ false, + /* tx */ TxWithPostPriceMsg{}, + /* simulate */ false, + }, + { + /* name */ "not whitelisted address without post price tx", + /* isWhitelisted */ false, + /* shouldChangeMeter */ false, + /* tx */ TxWithoutPostPriceMsg{}, + /* simulate */ false, + }, + } + + for _, tc := range tests { + tc := tc + t.Run(tc.name, func(t *testing.T) { + app, ctx := testapp.NewNibiruAppAndContext(true) + ctx = ctx.WithGasMeter(sdk.NewGasMeter(10000000)) + + if tc.isWhitelisted { + // If we whitelist, the gas meter changes. + app.PricefeedKeeper.WhitelistOracles(ctx, []sdk.AccAddress{oracleAddr}) + } + + var anteDecorators []sdk.AnteDecorator + if tc.shouldChangeMeter { + anteDecorators = []sdk.AnteDecorator{ + DecoratorWithNormalGasMeterCheck{t}, + gaslessante.NewGaslessDecorator(app.PricefeedKeeper), + DecoratorWithInfiniteGasMeterCheck{t}, + } + } else { + anteDecorators = []sdk.AnteDecorator{ + DecoratorWithNormalGasMeterCheck{t}, + gaslessante.NewGaslessDecorator(app.PricefeedKeeper), + DecoratorWithNormalGasMeterCheck{t}, + } + } + + chainedHandler := sdk.ChainAnteDecorators(anteDecorators...) + + _, err := chainedHandler(ctx, tc.tx, tc.simulate) + require.NoError(t, err) + }) + } +} diff --git a/app/antedecorators/types/gas.go b/app/antedecorators/types/gas.go new file mode 100644 index 000000000..24064c4a4 --- /dev/null +++ b/app/antedecorators/types/gas.go @@ -0,0 +1,46 @@ +package types + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/types" +) + +type gaslessMeter struct { + consumed types.Gas +} + +// GasLessMeter returns a reference to a new gaslessMeter. +func GasLessMeter() types.GasMeter { + return &gaslessMeter{ + consumed: 1, + } +} + +func (g *gaslessMeter) GasConsumed() types.Gas { + return 1 +} + +func (g *gaslessMeter) GasConsumedToLimit() types.Gas { + return 1 +} + +func (g *gaslessMeter) Limit() types.Gas { + return 1 +} + +func (g *gaslessMeter) ConsumeGas(types.Gas, string) { +} +func (g *gaslessMeter) RefundGas(types.Gas, string) {} + +func (g *gaslessMeter) IsPastLimit() bool { + return false +} + +func (g *gaslessMeter) IsOutOfGas() bool { + return false +} + +func (g *gaslessMeter) String() string { + return fmt.Sprintf("GaslessMeter:\n consumed: %d", g.consumed) +} diff --git a/app/app.go b/app/app.go index 345c7850c..e3e9d6909 100644 --- a/app/app.go +++ b/app/app.go @@ -754,7 +754,8 @@ func NewNibiruApp( SignModeHandler: encodingConfig.TxConfig.SignModeHandler(), SigGasConsumer: ante.DefaultSigVerificationGasConsumer, }, - IBCKeeper: app.IBCKeeper, + PricefeedKeeper: app.PricefeedKeeper, + IBCKeeper: app.IBCKeeper, }) if err != nil { diff --git a/go.mod b/go.mod index 0d6152413..f898bd63b 100644 --- a/go.mod +++ b/go.mod @@ -8,8 +8,10 @@ require ( github.com/gogo/protobuf v1.3.3 github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.2 + github.com/google/gofuzz v1.2.0 github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 + github.com/pkg/errors v0.9.1 github.com/rakyll/statik v0.1.7 github.com/regen-network/cosmos-proto v0.3.1 github.com/spf13/cast v1.5.0 @@ -63,7 +65,6 @@ require ( github.com/gogo/gateway v1.1.0 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/btree v1.0.0 // indirect - github.com/google/gofuzz v1.2.0 // indirect github.com/google/orderedcode v0.0.1 // indirect github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect @@ -94,7 +95,6 @@ require ( github.com/pelletier/go-toml v1.9.5 // indirect github.com/pelletier/go-toml/v2 v2.0.1 // indirect github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect - github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_golang v1.12.1 // indirect github.com/prometheus/client_model v0.2.0 // indirect diff --git a/x/dex/client/testutil/cli_test.go b/x/dex/client/testutil/cli_test.go index 42f19f010..2411ea5ad 100644 --- a/x/dex/client/testutil/cli_test.go +++ b/x/dex/client/testutil/cli_test.go @@ -324,9 +324,6 @@ func (s IntegrationTestSuite) TestCNewExitPoolCmd() { var finalBalance banktypes.QueryAllBalancesResponse s.Require().NoError(ctx.Codec.UnmarshalJSON(resp.Bytes(), &finalBalance)) - fmt.Println("Final balance:") - fmt.Println(finalBalance) - s.Require().Equal( originalBalance.Balances.AmountOf("uusdc").Add(tc.expectedOtherToken), finalBalance.Balances.AmountOf("uusdc"), diff --git a/x/epochs/keeper/epoch.go b/x/epochs/keeper/epoch.go index a4f54c9c0..19645176b 100644 --- a/x/epochs/keeper/epoch.go +++ b/x/epochs/keeper/epoch.go @@ -48,7 +48,6 @@ func (k Keeper) IterateEpochInfo(ctx sdk.Context, fn func(index int64, epochInfo defer func(iterator sdk.Iterator) { err := iterator.Close() if err != nil { - fmt.Println(err) panic(err) } }(iterator) diff --git a/x/perp/keeper/clearing_house.go b/x/perp/keeper/clearing_house.go index 58f54105e..9f21eff83 100644 --- a/x/perp/keeper/clearing_house.go +++ b/x/perp/keeper/clearing_house.go @@ -95,7 +95,6 @@ func (k Keeper) OpenPosition( // - Checks that quote asset is not zero. // - Checks that leverage is not zero. // - Checks that leverage is below requirement. -// func (k Keeper) checkOpenPositionRequirements(ctx sdk.Context, pair common.AssetPair, quoteAssetAmount sdk.Int, leverage sdk.Dec) error { if err := k.requireVpool(ctx, pair); err != nil { return err diff --git a/x/perp/spec/01_concepts.md b/x/perp/spec/01_concepts.md index cbbf8d058..f3f7b3d14 100644 --- a/x/perp/spec/01_concepts.md +++ b/x/perp/spec/01_concepts.md @@ -46,11 +46,11 @@ position_size = baseReserves - baseReservesAfterSwap The notional value of the position, or **position notional**, is the total value a position controls in units of the quote asset. Notional value expresses the value a derivatives contract theoretically controls. On Nibiru, it is defined more concretely by ```go -positionNotional = abs(quoteReserves - k/(baseReserves + position_size)) +positionNotional = abs(quoteReserves - k / (baseReserves + position_size)) leverage = positionNotional / margin. ``` -Let's say that the mark price of ether is $3000 in our previous example. This implies that the trader with a long position of size 5 has a position notional of $15,000. And if the trader has 10x **leverage**, for example, she must have put down $1500 as margin (collateral backing the position). +Let's say that the mark price of ether is \$3000 in our previous example. This implies that the trader with a long position of size 5 has a position notional of \$15,000. And if the trader has 10x **leverage**, for example, she must have put down \$1500 as margin (collateral backing the position). ## Margin and Margin Ratio @@ -66,7 +66,7 @@ Here, `unrealizedPnL` is computed using either the mark price or the 15 minute T When the virtual price is not within the spread tolerance to the index price, the margin ratio used is the highest value between a calculation with the index price (oracle based on underlying) and the mark price (derivative price). -Another good way to think about margin ratio is as the inverse of a position's effective leverage. I.e. if a trader puts down $100 as margin with 5x leverage, the notional is $500 and the margin ratio is 20%, which is equivalent ot `1 / leverage`. +Another good way to think about margin ratio is as the inverse of a position's effective leverage. I.e. if a trader puts down $100 as margin with 5x leverage, the notional is \$500 and the margin ratio is 20%, which is equivalent ot `1 / leverage`. #### Cross Margin versus Isolated Margin @@ -91,17 +91,16 @@ Perpetual contracts rely on a scheduled payment between longs and shorts known a Longs and shorts are paid with the exact funding rate formula [used by FTX](https://help.ftx.com/hc/en-us/articles/360027946571-Funding). Realized and unrealized funding payments are updated every block directly on each position. Global funding calculations are recorded in a time-weighted fashion, where the **funding rate** is the difference between the mark TWAP and index TWAP divided by the number of funding payments per day: -```python -funding_rate -= (mark_TWAP - index_TWAP) / funding_payments_per_day +```go +fundingRate = (markTWAP - indexTWAP) / fundingPaymentsPerDay ``` In the initial version of Nibi-Perps, these payments will occur every half-hour, implying a `funding_payments_per_day` value of 48. This setup is analogous to a traditional future that expires once a day. If a perp trades consistently at 2% above its underlying index price, the funding payments would amount to 2% of the position size after a full day. If the funding rate is positive, mark price > index price and longs pay shorts. Nibi-Perps automatically deducts the funding payment amount from the margin of the long positions. -```python -funding_payment = position_size * funding_rate +```go +fundingPayment = positionSize * fundingRate ``` Here, position size refers to amount of base asset represented by the derivative. I.e., a BTC:USD perp with 7 BTC of exposure would have a position size of 7. diff --git a/x/pricefeed/client/cli/cli_test.go b/x/pricefeed/client/cli/cli_test.go index 8288123f0..e768c50ac 100644 --- a/x/pricefeed/client/cli/cli_test.go +++ b/x/pricefeed/client/cli/cli_test.go @@ -8,6 +8,10 @@ import ( "testing" "time" + "github.com/cosmos/cosmos-sdk/client" + banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -339,7 +343,7 @@ func (s IntegrationTestSuite) TestOraclesCmd() { args []string expectedOracles []string - expectErr bool + expectPass bool respType proto.Message }{ { @@ -363,7 +367,7 @@ func (s IntegrationTestSuite) TestOraclesCmd() { args: []string{ "invalid:pair", }, - expectErr: false, + expectPass: false, expectedOracles: []string{}, respType: &pricefeedtypes.QueryOraclesResponse{}, }, @@ -377,7 +381,8 @@ func (s IntegrationTestSuite) TestOraclesCmd() { clientCtx := val.ClientCtx.WithOutputFormat("json") out, err := sdktestutilcli.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { + + if tc.expectPass { s.Require().Error(err, out.String()) } else { s.Require().NoError(err, out.String()) @@ -391,6 +396,15 @@ func (s IntegrationTestSuite) TestOraclesCmd() { }) } } + +func queryBankBalance(ctx client.Context, s IntegrationTestSuite, account sdk.AccAddress) (finalBalance banktypes.QueryAllBalancesResponse) { + resp, err := banktestutil.QueryBalancesExec(ctx, account) + s.Require().NoError(err) + s.Require().NoError(ctx.Codec.UnmarshalJSON(resp.Bytes(), &finalBalance)) + + return +} + func (s IntegrationTestSuite) TestSetPriceCmd() { err := s.network.WaitForNextBlock() s.Require().NoError(err) @@ -402,11 +416,11 @@ func (s IntegrationTestSuite) TestSetPriceCmd() { expireInOneHour := strconv.Itoa(int(now.Add(1 * time.Hour).Unix())) expiredTS := strconv.Itoa(int(now.Add(-1 * time.Hour).Unix())) - gasFeeToken := sdk.NewCoins(sdk.NewInt64Coin(s.cfg.BondDenom, 1_000_000)) + gasFeeToken := sdk.NewCoins(sdk.NewInt64Coin(s.cfg.BondDenom, 1000)) for _, oracleName := range []string{"genOracle", "wrongOracle"} { _, err = testutilcli.FillWalletFromValidator( /*addr=*/ s.oracleMap[oracleName], - /*balanece=*/ gasFeeToken, + /*balance=*/ gasFeeToken, /*Validator=*/ val, /*feesDenom=*/ s.cfg.BondDenom) s.Require().NoError(err) @@ -423,6 +437,7 @@ func (s IntegrationTestSuite) TestSetPriceCmd() { args []string expectedPriceForPair map[string]sdk.Dec + expectedFeePaid sdk.Int respType proto.Message expectedCode uint32 fromOracle string @@ -434,8 +449,9 @@ func (s IntegrationTestSuite) TestSetPriceCmd() { }, expectedPriceForPair: map[string]sdk.Dec{ gov.String(): sdk.NewDec(100)}, - respType: &sdk.TxResponse{}, - fromOracle: "genOracle", + expectedFeePaid: sdk.NewInt(0), + respType: &sdk.TxResponse{}, + fromOracle: "genOracle", }, { name: "Set the price of the collateral token", @@ -444,35 +460,39 @@ func (s IntegrationTestSuite) TestSetPriceCmd() { }, expectedPriceForPair: map[string]sdk.Dec{ col.String(): sdk.MustNewDecFromStr("0.85")}, - respType: &sdk.TxResponse{}, - fromOracle: "genOracle", + expectedFeePaid: sdk.NewInt(0), + respType: &sdk.TxResponse{}, + fromOracle: "genOracle", }, { name: "Use invalid oracle", args: []string{ col.Token0, col.Token1, "0.5", expireInOneHour, }, - respType: &sdk.TxResponse{}, - expectedCode: 6, - fromOracle: "wrongOracle", + expectedFeePaid: sdk.NewInt(10), // Pay fee since this oracle is not whitelisted + respType: &sdk.TxResponse{}, + expectedCode: 6, + fromOracle: "wrongOracle", }, { name: "Set invalid pair returns an error", args: []string{ "invalid", "pair", "123", expireInOneHour, }, - expectedCode: 6, - respType: &sdk.TxResponse{}, - fromOracle: "genOracle", + expectedFeePaid: sdk.NewInt(10), // Invalid pair means that oracle is not whitelisted for this, needs to pay fees + expectedCode: 6, + respType: &sdk.TxResponse{}, + fromOracle: "genOracle", }, { name: "Set expired pair returns an error", args: []string{ col.Token0, col.Token1, "100", expiredTS, }, - expectedCode: 3, - respType: &sdk.TxResponse{}, - fromOracle: "genOracle", + expectedCode: 3, + expectedFeePaid: sdk.NewInt(0), + respType: &sdk.TxResponse{}, + fromOracle: "genOracle", }, } @@ -484,11 +504,23 @@ func (s IntegrationTestSuite) TestSetPriceCmd() { clientCtx := val.ClientCtx commonArgs = append(commonArgs, - fmt.Sprintf("--%s=%s", flags.FlagFrom, s.oracleMap[tc.fromOracle])) + fmt.Sprintf("--%s=%s", flags.FlagFrom, s.oracleMap[tc.fromOracle]), + ) + + bankBalanceStart := queryBankBalance(clientCtx, s, s.oracleMap[tc.fromOracle]) + out, err := sdktestutilcli.ExecTestCLICmd(clientCtx, cmd, append(tc.args, commonArgs...)) + bankBalanceEnd := queryBankBalance(clientCtx, s, s.oracleMap[tc.fromOracle]) + s.Require().NoError(err) s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType)) + s.Require().EqualValues( + tc.expectedFeePaid.Int64(), + bankBalanceStart.Balances.AmountOf(common.DenomGov). + Sub(bankBalanceEnd.Balances.AmountOf(common.DenomGov)).Int64(), + ) + txResp := tc.respType.(*sdk.TxResponse) err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), txResp) s.Require().NoError(err) @@ -570,7 +602,9 @@ func (s IntegrationTestSuite) TestX_CmdAddOracleProposalAndVote() { _, err = testutilcli.FillWalletFromValidator(oracle, gasTokens, val, s.cfg.BondDenom) s.Require().NoError(err) - s.T().Log("load example json as bytes") + // ---------------------------------------------------------------------- + s.T().Log("load example proposal json as bytes") + // ---------------------------------------------------------------------- proposal := &pricefeedtypes.AddOracleProposal{ Title: "Cataclysm-004", Description: "Whitelists Delphi to post prices for OHM and BTC", @@ -593,14 +627,19 @@ func (s IntegrationTestSuite) TestX_CmdAddOracleProposalAndVote() { contents, err := ioutil.ReadFile(proposalJSON.Name()) s.Assert().NoError(err) + // ---------------------------------------------------------------------- s.T().Log("Unmarshal json bytes into proposal object; check validity") + // ---------------------------------------------------------------------- encodingConfig := simappparams.MakeTestEncodingConfig() proposal = &pricefeedtypes.AddOracleProposal{} err = encodingConfig.Marshaler.UnmarshalJSON(contents, proposal) s.Assert().NoError(err) s.Require().NoError(proposal.Validate()) - s.T().Log("Submit proposal and unmarshal tx response") + // ---------------------------------------------------------------------- + s.T().Log(`Submit proposal and unmarshal tx response + $ nibid tx gov submit-proposal add-oracle [proposal-json] --deposit=[deposit] [flags]`) + // ---------------------------------------------------------------------- args := []string{ proposalJSON.Name(), fmt.Sprintf("--%s=1000unibi", govcli.FlagDeposit), @@ -622,8 +661,11 @@ func (s IntegrationTestSuite) TestX_CmdAddOracleProposalAndVote() { s.Assert().NoError(err) s.Assert().EqualValues(0, txResp.Code, out.String()) + // ---------------------------------------------------------------------- s.T().Log(`Check that proposal was correctly submitted with gov client - $ nibid query gov proposal 1`) + $ nibid query gov proposal 1 + `) + // ---------------------------------------------------------------------- // the proposal tx won't be included until next block s.Assert().NoError(s.network.WaitForNextBlock()) govQueryClient := govtypes.NewQueryClient(clientCtx) @@ -643,8 +685,10 @@ func (s IntegrationTestSuite) TestX_CmdAddOracleProposalAndVote() { proposalsQueryResponse.Proposals[0].TotalDeposit, ) + // ---------------------------------------------------------------------- s.T().Log(`Move proposal to vote status by meeting min deposit - $ nibid tx gov deposit [proposal-id] [deposit] [flags]`) + $ nibid tx gov deposit [proposal-id] [deposit] [flags]`) + // ---------------------------------------------------------------------- govDepositParams, err := govQueryClient.Params( context.Background(), &govtypes.QueryParamsRequest{ParamsType: govtypes.ParamDeposit}) s.Assert().NoError(err) @@ -668,9 +712,11 @@ func (s IntegrationTestSuite) TestX_CmdAddOracleProposalAndVote() { proposalsQueryResponse.Proposals[0].Status, "proposal should be in voting period since min deposit has been met") + // ---------------------------------------------------------------------- s.T().Log(`Vote on the proposal. - $ nibid tx gov vote [proposal-id] [option] [flags] - e.g. $ nibid tx gov vote 1 yes`) + $ nibid tx gov vote [proposal-id] [option] [flags] + For example, $ nibid tx gov vote 1 yes`) + // ---------------------------------------------------------------------- args = []string{ /*proposal-id=*/ "1", /*option=*/ "yes", @@ -694,7 +740,9 @@ func (s IntegrationTestSuite) TestX_CmdAddOracleProposalAndVote() { }, 20*time.Second, 2*time.Second, "proposal should pass after voting period") + // ---------------------------------------------------------------------- s.T().Log("verify that the new proposed pairs have been added to the params") + // ---------------------------------------------------------------------- cmd = cli.CmdQueryParams() args = []string{} queryResp := &pricefeedtypes.QueryParamsResponse{} @@ -703,7 +751,9 @@ func (s IntegrationTestSuite) TestX_CmdAddOracleProposalAndVote() { expectedPairs := append(pricefeedtypes.DefaultPairs, proposalPairs...) s.Assert().EqualValues(expectedPairs, queryResp.Params.Pairs) + // ---------------------------------------------------------------------- s.T().Log("verify that the oracle was whitelisted with a query") + // ---------------------------------------------------------------------- cmd = cli.CmdQueryOracles() for _, pair := range proposalPairs { args = []string{pair.String()} diff --git a/x/vpool/client/cli/cli_test.go b/x/vpool/client/cli/cli_test.go index 37c82d135..5b51e61a7 100644 --- a/x/vpool/client/cli/cli_test.go +++ b/x/vpool/client/cli/cli_test.go @@ -8,8 +8,6 @@ import ( "time" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" sdktestutil "github.com/cosmos/cosmos-sdk/testutil" sdktestutilcli "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" @@ -27,14 +25,14 @@ import ( vpooltypes "github.com/NibiruChain/nibiru/x/vpool/types" ) -type IntegrationTestSuite struct { +type VpoolCLISuite struct { suite.Suite cfg testutilcli.Config network *testutilcli.Network } -func (s *IntegrationTestSuite) SetupSuite() { +func (s *VpoolCLISuite) SetupSuite() { if testing.Short() { s.T().Skip("skipping integration test suite") } @@ -58,31 +56,19 @@ func (s *IntegrationTestSuite) SetupSuite() { s.Assert().Equal(sdk.NewDec(10), res.Price.Price) } -func (s *IntegrationTestSuite) TearDownSuite() { +func (s *VpoolCLISuite) TearDownSuite() { s.T().Log("tearing down integration test suite") s.network.Cleanup() } -func (s IntegrationTestSuite) TestX_CmdAddVpool() { +func (s VpoolCLISuite) TestX_CmdAddVpool() { s.Require().Len(s.network.Validators, 1) val := s.network.Validators[0] clientCtx := val.ClientCtx.WithOutputFormat("json") - proposer, _, err := val.ClientCtx.Keyring.NewMnemonic( - /* uid */ "proposer", - /* language */ keyring.English, - /* hdPath */ sdk.FullFundraiserPath, - /* bip39Passphrase */ "", - /* algo */ hd.Secp256k1, - ) - s.Require().NoError(err) - s.T().Log("Fill proposer wallet to pay gas for prosal") - gasTokens := sdk.NewCoins(sdk.NewInt64Coin(s.cfg.BondDenom, 100_000_000)) - oracle := sdk.AccAddress(proposer.GetPubKey().Address()) - _, err = testutilcli.FillWalletFromValidator(oracle, gasTokens, val, s.cfg.BondDenom) - s.Require().NoError(err) - - s.T().Log("load example json as bytes") + // ---------------------------------------------------------------------- + s.T().Log("load example proposal json as bytes") + // ---------------------------------------------------------------------- proposal := &vpooltypes.CreatePoolProposal{ Title: "Create ETH:USD pool", Description: "Creates an ETH:USD pool", @@ -107,7 +93,9 @@ func (s IntegrationTestSuite) TestX_CmdAddVpool() { val.ClientCtx.Codec.MustUnmarshalJSON(contents, proposal) s.Require().NoError(proposal.ValidateBasic()) + // ---------------------------------------------------------------------- s.T().Log("Submit proposal and unmarshal tx response") + // ---------------------------------------------------------------------- args := []string{ proposalJSON.Name(), fmt.Sprintf("--%s=1000unibi", govcli.FlagDeposit), @@ -129,8 +117,10 @@ func (s IntegrationTestSuite) TestX_CmdAddVpool() { s.Assert().NoError(err) s.Assert().EqualValues(0, txResp.Code, out.String()) + // ---------------------------------------------------------------------- s.T().Log(`Check that proposal was correctly submitted with gov client $ nibid query gov proposal 1`) + // ---------------------------------------------------------------------- // the proposal tx won't be included until next block s.Assert().NoError(s.network.WaitForNextBlock()) govQueryClient := govtypes.NewQueryClient(clientCtx) @@ -150,13 +140,16 @@ func (s IntegrationTestSuite) TestX_CmdAddVpool() { proposalsQueryResponse.Proposals[0].TotalDeposit, ) + // ---------------------------------------------------------------------- s.T().Log(`Move proposal to vote status by meeting min deposit $ nibid tx gov deposit [proposal-id] [deposit] [flags]`) + // ---------------------------------------------------------------------- + expectedProposalIDStr := "1" govDepositParams, err := govQueryClient.Params( context.Background(), &govtypes.QueryParamsRequest{ParamsType: govtypes.ParamDeposit}) s.Assert().NoError(err) args = []string{ - /*proposal-id=*/ "1", + /*proposal-id=*/ expectedProposalIDStr, /*deposit=*/ govDepositParams.DepositParams.MinDeposit.String(), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=test", flags.FlagKeyringBackend), @@ -175,11 +168,13 @@ func (s IntegrationTestSuite) TestX_CmdAddVpool() { proposalsQueryResponse.Proposals[0].Status, "proposal should be in voting period since min deposit has been met") + // ---------------------------------------------------------------------- s.T().Log(`Vote on the proposal. $ nibid tx gov vote [proposal-id] [option] [flags] e.g. $ nibid tx gov vote 1 yes`) + // ---------------------------------------------------------------------- args = []string{ - /*proposal-id=*/ "1", + /*proposal-id=*/ expectedProposalIDStr, /*option=*/ "yes", fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=test", flags.FlagKeyringBackend), @@ -201,7 +196,9 @@ func (s IntegrationTestSuite) TestX_CmdAddVpool() { }, 20*time.Second, 2*time.Second, "proposal should pass after voting period") + // ---------------------------------------------------------------------- s.T().Log("verify that the new proposed pool exists") + // ---------------------------------------------------------------------- cmd = cli.CmdGetVpools() args = []string{} queryResp := &vpooltypes.QueryAllPoolsResponse{} @@ -223,10 +220,9 @@ func (s IntegrationTestSuite) TestX_CmdAddVpool() { found = true } } - require.True(s.T(), found, "pool does not exist") } -func TestIntegrationTestSuite(t *testing.T) { - suite.Run(t, new(IntegrationTestSuite)) +func TestVpoolCLISuite(t *testing.T) { + suite.Run(t, new(VpoolCLISuite)) } diff --git a/x/vpool/keeper/keeper.go b/x/vpool/keeper/keeper.go index 9ab34f45e..effb52f91 100644 --- a/x/vpool/keeper/keeper.go +++ b/x/vpool/keeper/keeper.go @@ -355,7 +355,8 @@ func (k Keeper) GetMaintenanceMarginRatio(ctx sdk.Context, pair common.AssetPair return pool.MaintenanceMarginRatio } -/** +/* +* GetMaxLeverage returns the maximum leverage required to open a position in the pool. args: From 247b6cd1ccd6faa47b0ddc232e979baefdfcd8da Mon Sep 17 00:00:00 2001 From: Unique Divine <51418232+Unique-Divine@users.noreply.github.com> Date: Mon, 15 Aug 2022 07:48:15 -0500 Subject: [PATCH 5/7] docs(perp): Added events specification for the perp module. (#814) * docs(perp): events #wip * docs(perp): Added events specification for the perp module. * Squashed commit of the following: commit b496438338d5cd136661e6cf79a694e47a8198b9 Author: Unique-Divine Date: Fri Aug 12 18:03:02 2022 -0500 remove deperecated docs from x/perp/README commit fc260a5a69ed76034766361c3ea34b5d1e7e14cc Author: Unique Divine <51418232+Unique-Divine@users.noreply.github.com> Date: Thu Aug 11 16:37:34 2022 -0500 chore: release v0.12.1-alpha (#820) update changelog commit 8ec477ae6b181c67f486d1b7d2d2f04e4bbc3dba Author: AgentSmithMatrix <98403347+AgentSmithMatrix@users.noreply.github.com> Date: Thu Aug 11 19:47:03 2022 +0200 feat: add golangci-lint to makefile (#819) * add linter to makefile * update changelog commit 208a102cce439535d87febe81c40235187c1292c Author: Unique Divine <51418232+Unique-Divine@users.noreply.github.com> Date: Wed Aug 10 13:17:05 2022 -0500 fix: missing max leverage on the pools in app_state.vpool.vpools (#818) commit 75e8f032bf9a9ff5b65b83235e9064f388f33a41 Author: Unique Divine <51418232+Unique-Divine@users.noreply.github.com> Date: Wed Aug 10 07:38:00 2022 -0500 feat(vpool): expose markPrice, markTwap, indexPrice, (and blockHeight?) on the all-pools query #789 (#813) * (vpool): add logger to keeper.go * feat: GetPoolPrices, fn to return the mark price, mark twap, index price, and swap inv. for a pool * docs: fix the fn description for GetCurrentTWAP * feat(vpool): implemenet PoolPrices and add it to 'nibid q vpool all-pools' command * update changelog * (vpool): add block number to all-pools.prices. Fix changelog Co-authored-by: AgentSmithMatrix <98403347+AgentSmithMatrix@users.noreply.github.com> Co-authored-by: Agent Smith commit 674da1b94d2a2c08731881a68f3cd51701ff8231 Author: Unique Divine <51418232+Unique-Divine@users.noreply.github.com> Date: Wed Aug 10 07:01:20 2022 -0500 feat(perp): expose 'marginRatioIndex' and block number on QueryTraderPosition (#810) * feat(x/perp): add marginRatioIndex to the position query * add blockNumber to QueryTraderPosition * update CHANGELOG.md #763 * fix(CHANGELOG) commit c6ad354e2e5cb0a819b7696df276130e9c3c574d Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed Aug 10 01:52:40 2022 -0500 chore(deps): bump github.com/cosmos/ibc-go/v3 from 3.1.0 to 3.1.1 (#804) * chore(deps): bump github.com/cosmos/ibc-go/v3 from 3.1.0 to 3.1.1 Bumps [github.com/cosmos/ibc-go/v3](https://github.com/cosmos/ibc-go) from 3.1.0 to 3.1.1. - [Release notes](https://github.com/cosmos/ibc-go/releases) - [Changelog](https://github.com/cosmos/ibc-go/blob/main/CHANGELOG.md) - [Commits](https://github.com/cosmos/ibc-go/compare/v3.1.0...v3.1.1) --- updated-dependencies: - dependency-name: github.com/cosmos/ibc-go/v3 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] * Update CHANGELOG.md Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: NibiruHeisenberg <101130700+NibiruHeisenberg@users.noreply.github.com> Co-authored-by: AgentSmithMatrix <98403347+AgentSmithMatrix@users.noreply.github.com> Co-authored-by: NibiruHeisenberg <101130700+NibiruHeisenberg@users.noreply.github.com> --- CHANGELOG.md | 4 ++ proto/perp/v1/event.proto | 6 +- x/README.md | 2 + x/perp/README.md | 34 +--------- x/perp/spec/04_events.md | 133 ++++++++++++++++++++++++-------------- 5 files changed, 95 insertions(+), 84 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a285db52d..ce9509062 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#816](https://github.com/NibiruChain/nibiru/pull/816) - Remove tobin tax from x/oracle * [#810](https://github.com/NibiruChain/nibiru/pull/810) - feat(x/perp): expose 'marginRatioIndex' and block number on QueryTraderPosition +### Documentation + +* [#814](https://github.com/NibiruChain/nibiru/pull/814) - docs(perp): Added events specification for the perp module. + ## [v0.12.1](https://github.com/NibiruChain/nibiru/releases/tag/v0.12.1) - 2022-08-04 * [#796](https://github.com/NibiruChain/nibiru/pull/796) - fix bug that caused that epochKeeper was nil when running epoch hook from Perp module diff --git a/proto/perp/v1/event.proto b/proto/perp/v1/event.proto index c9ccb0d80..0327ca95e 100644 --- a/proto/perp/v1/event.proto +++ b/proto/perp/v1/event.proto @@ -59,7 +59,8 @@ message PositionChangedEvent { (gogoproto.nullable) = false ]; - // Amount of bad debt cleared by the PerpEF during the change. Bad debt is negative net margin past the liquidation point of a position. + // Amount of bad debt cleared by the PerpEF during the change. + // Bad debt is negative net margin past the liquidation point of a position. cosmos.base.v1beta1.Coin bad_debt = 10 [(gogoproto.nullable) = false]; // amt of margin (y) lost due to liquidation @@ -68,7 +69,8 @@ message PositionChangedEvent { (gogoproto.nullable) = false ]; - // vPrice defined as yRes / xRes for a vpool, where yRes is the quote reserves and xRes is the base reserves. + // Spot price, synonymous with mark price in this context, is the quotient of + // the quote reserves and base reserves string spot_price = 12 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false diff --git a/x/README.md b/x/README.md index 5bbc2bfcd..4879c9d93 100644 --- a/x/README.md +++ b/x/README.md @@ -8,6 +8,8 @@ - [pricefeed](pricefeed/spec/README.md): Handles the posting of prices for various asset pairs by whitelisted oracles and the logic for querying these prices. +- [perp](perp/README.md): The `x/perp` module powers the Nibi-Perps exchange. This module enables traders to open long and short leveraged positions and houses all of the PnL calculation and liquidation logic. + - [stablecoin](stablecoin/spec/README.md): `x/stablecoin` is resonsible for handling mint and redeem transactions with NUSD. - [testutil](testutil/spec/README.md): Helper functions for unit and integration tests. diff --git a/x/perp/README.md b/x/perp/README.md index 6d83ff438..63d29a94e 100644 --- a/x/perp/README.md +++ b/x/perp/README.md @@ -20,39 +20,7 @@ nibid tx perp --help nibid query perp --help ``` -CLI code is contained in the `/perp/client/cli` directory. +The implementation for this module's portion of the `nibid` CLI is contained within the `/perp/client/cli` directory. -## Perp Ecosystem Fund (PerpEF) - -The PerpEF is a module account on Nibiru Protocol. All of its interactions can be encapsulated in two keeper methods. -- `WithdrawFromPerpEF()` -- `DepositToPerpEF()` - - -## Queries - - -#### QueryPositionInfo - -Given the `vpool` and `trader`, one could query the -`QueryPositionInfo(vpool string, trader sdk.AccAddress) -> PositionInfo` - -```go -// A single trader's position information on a given Vpool. -type PositionInfo struct { - MarginRatio sdk.Dec - Position perptypes.Position -} -``` - -#### QueryAllVpools - -`QueryAllVpools() -> []string`: Returns a list of all of the pool names. - -#### QueryVpoolPrices - -`QueryVpoolPrices() -> map[string]sdk.Dec`: Returns ech virtual pool and its corresponding price. - - diff --git a/x/perp/spec/04_events.md b/x/perp/spec/04_events.md index e3f19c0fd..df7227e0e 100644 --- a/x/perp/spec/04_events.md +++ b/x/perp/spec/04_events.md @@ -1,6 +1,6 @@ # Events -Here, we list and describe the event types used in x/perp. +Here, we document the event types used in the `x/perp` module. Events in the Cosmos-SDK are Tendermint application blockchain interface (ABCI) events. These are returned by ABCI methods such as CheckTx, DeliverTx, and Query. @@ -14,51 +14,86 @@ For more information, see the [Tendermint Core ABCI methods and types specificat # Event Types -- [`transfer`](#transfer): Emitted when assets are transferred between addresses as a result of a Nibiru protocol. -- [`position_change`](#position_change): Emitted when a position state changes. -- [`position_liquidate`](#position_liquidate): -- [`position_settle`](#position_settle): -- [`margin_ratio_change`](#margin_ratio_change): -- [`margin_change`](#margin_change): Emitted when the margin of a single -- [`internal_position_response`](#internal_position_response): - - - -## `transfer` - -Attributes - "transfer: - -- "from": Sender address -- "to": Receiver address -- "denom": Cosmos-SDK token Bech 32 address for the token -- "amount": Amount of tokens sent in the transfer - - -## `position_change` - -Attributes - "position_change": - -- "owner": Address -- "vpool": -- "margin": -- "notional": -- "vsizeChange": magnitude of the change to the position size. Recall that the position size is the number of base assets for the perp position. E.g. an ETH:USD perp with 3 ETH of exposure has a posiiton size of 3. -- "txFee": -- "vsizeAfter": -- "realizedPnlAfter": -- "bad_debt": -- "unrealized_pnl_after": -- "liquidation_penalty": -- "mark_price": -- "funding_payment": A funding payment made or received by the trader on the current position. A "funding_payment" is positive if 'owner' is the sender and negative if 'owner' is the receiver of the payment. Its magnitude is abs(size * fundingRate). Funding payments act to converge the mark price and index price (average price on major spot exchanges). - -## `position_liquidate` - - -## `position_settle` - -## `margin_ratio_change` - -## `margin_change` - -## `internal_position_response` \ No newline at end of file +- [`nibiru.perp.v1.PositionChangedEvent`](#nibiruperpv1positionchangedevent): Event omitted when a position changes +- [`nibiru.perp.v1.PositionLiquidatedEvent`](#nibiruperpv1positionliquidatedevent): Event emitted when a position is liquidated. +- [`nibiru.perp.v1.PositionSettledEvent`](#nibiruperpv1positionsettledevent): Event emitted when a position is settled. +- [`nibiru.perp.v1.FundingRateChangedEvent`](#nibiruperpv1fundingratechangedevent): + + +```ts +interface Coin { + denom: string; // Cosmos token Bech 32 address + amount: number; // Amount of tokens +} +``` + +## `nibiru.perp.v1.PositionChangedEvent` + +| Attribute (type) | Description | +| ---------------- | ---------- | +| bad_debt (`Coin`) | Amount of bad debt cleared by the PerpEF during the change. Bad debt is negative net margin past the liquidation point of a position. | +| block_height (`int64`) | Block number at which the position changed | +| block_time_ms (`int64`) | Block time in Unix milliseconds at which the position changed. | +| exchanged_position_size (`Dec`) | magnitude of the change to the position size. Recall that the position size is the number of base assets for the perp position. E.g. an ETH:USD perp with 3 ETH of exposure has a posiiton size of 3. | +| funding_payment (`Dec`) | A funding payment made or received by the trader on the current position. A "funding_payment" is positive if 'owner' is the sender and negative if 'owner' is the receiver of the payment. Its magnitude is abs(size * fundingRate). Funding payments act to converge the mark price and index price (average price on major spot exchanges). | +| liquidation_penalty (`Dec`) | Amount of margin lost due to liquidation, whether partial or full. | +| margin (`Coin`) | Amount of margin backing the position | +| pair (`string`) | Identifier for the virtual pool corresponding to the position. A pair is of the form `basedenom:quote`. E.g. `uatom:unusd`. | +| position_notional (`Dec`) | | +| position_size (`Dec`) | Position size (base asset value) after the change | +| realized_pnl (`Dec`) | Realized profits and losses after the change | +| spot_price (`Dec`) | Spot price, synonymous with mark price in this context, is the quotient of the quote reserves and base reserves. | +| trader_address (`string`) | Owner of the position | +| transaction_fee (`Coin`) | Transaction fee paid | +| unrealized_pnl_after (`Dec`) | Unrealized PnL after the change | + +## `nibiru.perp.v1.PositionLiquidatedEvent` + +Event emitted when a position is liquidated. +Corresponds to the proto message, `PositionLiquidatedEvent`. + +| Attribute (type) | Description | +| ---------------- | ---------- | +| bad_debt (`Coin`) | Bad debt (margin units) cleared by the PerpEF during the tx. Bad debt is negative net margin past the liquidation point of a position. | +| block_height (`int64`) | Block number at which the position changed | +| block_time_ms (`int64`) | Block time in Unix milliseconds at which the position changed. | +| exchanged_position_size (`Dec`) | magnitude of the change to the position size (base) | +| exchanged_quote_amount (`Dec`) | magnitude of the change to the position notional (quote) | +| fee_to_liquidator (`Coin`) | Transaction fee paid to the liquidator | +| fee_to_ecosystem_fund (`Coin`) | Transaction fee paid to the Nibi-Perps Ecosystem Fund | +| liquidator_address (`string`) | Address of the account that executed the tx | +| mark_price (`Dec`) | Spot price of the virtual pool after liquidation | +| margin (`Coin`) | Amount of margin remaining in the position after the liquidation | +| pair (`string`) | Identifier for the virtual pool corresponding to the position. A pair is of the form `basedenom:quote`. E.g. `uatom:unusd`. | +| position_notional (`Dec`) | Reamining position notional (quote units) after liquiation | +| position_size (`Dec`) | Remaing position size (base units) after liquidation | +| trader_address (`string`) | Owner of the position | +| unrealized_pnl (`Dec`) | Unrealized PnL in the position after liquidation | + +## `nibiru.perp.v1.PositionSettledEvent` + +| Attribute (type) | Description | +| ---------------- | ---------- | +| pair (`string`) | Identifier for the virtual pool corresponding to the position. A pair is of the form `basedenom:quote`. E.g. `uatom:unusd`. | +| settled_coins (`[]Coin`) | Coins transferred during the settlement | +| trader_address (`string`) | Owner of the position | + +## `nibiru.perp.v1.FundingRateChangedEvent` + +| Attribute (type) | Description | +| ---------------- | ---------- | +| block_height (`int64`) | Block number at which the position changed | +| block_time_ms (`int64`) | Block time in Unix milliseconds at which the position changed. | +| cumulative_funding_rate (`Dec`) | Cumulative funding rate. The sum of the cumulative premium fractions (CFPs) for the pair. The funding payment paid by a user is the `(latestCPF - lastUpdateCPF) * positionSize`, where `lastUpdateCPF` is the last cumulative funding payment the position applied and `latestCPF` is the most recent CPF for the virtual pool. | +| index_price (`Dec`) | Price of the "underlying" for the perpetual swap. | +| latest_funding_rate (`Dec`) | Most recent value for the funding rate. | +| mark_price (`Dec`) | Instantaneous derivate price for the perp position. Equivalent to the quotient of the quote and base reserves. | +| pair (`string`) | Identifier for the virtual pool corresponding to the position. A pair is of the form `basedenom:quote`. E.g. `uatom:unusd`. | + + From 430613021f0f5575a49803dba8f1868a5d9627c7 Mon Sep 17 00:00:00 2001 From: AgentSmithMatrix <98403347+AgentSmithMatrix@users.noreply.github.com> Date: Tue, 16 Aug 2022 17:39:35 +0200 Subject: [PATCH 6/7] fix!: remove modules that are not required for v1 testnet (#831) * create app for testing only * use testapp for tests * Temp commit * temp commit on bug * fix: missing encoding configs * add genesis state * fix tests * return hooks * linter * add files apps * add changelog entry Co-authored-by: godismercilex --- CHANGELOG.md | 8 +- app/antedecorators/fee/testutil_test.go | 9 +- app/antedecorators/gasless/gasless_test.go | 5 +- app/app.go | 384 +++---- app/export.go | 48 +- app/ibc_test.go | 19 +- simapp/app.go | 1001 +++++++++++++++++ simapp/encoding.go | 19 + simapp/export.go | 194 ++++ simapp/genesis.go | 14 + simapp/sim_test.go | 6 +- {x/testutil/testapp => simapp}/testapp.go | 51 +- .../testapp => simapp}/testapp_test.go | 15 +- x/dex/client/testutil/cli_test.go | 5 +- x/dex/genesis_test.go | 5 +- x/dex/keeper/balances_test.go | 5 +- x/dex/keeper/grpc_query_test.go | 27 +- x/dex/keeper/keeper_test.go | 25 +- x/dex/keeper/liquidity_test.go | 14 +- x/dex/keeper/msg_server_test.go | 11 +- x/dex/keeper/params_test.go | 5 +- x/dex/keeper/swap_test.go | 5 +- x/epochs/abci_test.go | 11 +- x/epochs/genesis_test.go | 7 +- x/epochs/keeper/keeper_test.go | 8 +- x/incentivization/keeper/keeper_test.go | 13 +- x/incentivization/keeper/servers_test.go | 15 +- x/incentivization/module_test.go | 5 +- x/lockup/client/cli/cli_test.go | 5 +- x/lockup/keeper/keeper_test.go | 27 +- x/lockup/keeper/msg_server_test.go | 15 +- x/lockup/keeper/state_test.go | 7 +- x/lockup/module_test.go | 5 +- x/perp/client/cli/cli_test.go | 5 +- x/perp/genesis_test.go | 5 +- x/perp/keeper/calc_test.go | 9 +- .../keeper/clearing_house_integration_test.go | 11 +- x/perp/keeper/grpc_query_test.go | 5 +- x/perp/keeper/keeper_test.go | 11 +- x/perp/keeper/liquidate_test.go | 11 +- x/perp/keeper/margin_test.go | 11 +- x/perp/keeper/msg_server_test.go | 13 +- x/perp/keeper/perp_test.go | 15 +- x/perp/module_test.go | 5 +- x/perp/types/expected_keepers_test.go | 9 +- x/pricefeed/abci_test.go | 8 +- x/pricefeed/client/cli/cli_test.go | 5 +- x/pricefeed/genesis_test.go | 9 +- x/pricefeed/keeper/keeper_test.go | 15 +- x/pricefeed/keeper/params_test.go | 13 +- x/stablecoin/abci_test.go | 10 +- x/stablecoin/client/cli/cli_test.go | 5 +- x/stablecoin/genesis_test.go | 5 +- x/stablecoin/keeper/collateral_ratio_test.go | 39 +- x/stablecoin/keeper/grpc_query_test.go | 5 +- x/stablecoin/keeper/keeper_test.go | 11 +- x/stablecoin/keeper/mint_burn_stable_test.go | 15 +- x/stablecoin/keeper/msg_server_test.go | 7 +- x/stablecoin/keeper/params_test.go | 5 +- x/stablecoin/keeper/supply_test.go | 9 +- x/stablecoin/types/codec.go | 3 - x/stablecoin/types/expected_keepers_test.go | 11 +- x/testutil/cli/network.go | 12 +- x/testutil/cli/util.go | 6 +- x/vpool/client/cli/cli_test.go | 5 +- x/vpool/genesis_test.go | 5 +- 66 files changed, 1750 insertions(+), 556 deletions(-) create mode 100644 simapp/app.go create mode 100644 simapp/encoding.go create mode 100644 simapp/export.go rename {x/testutil/testapp => simapp}/testapp.go (75%) rename {x/testutil/testapp => simapp}/testapp_test.go (90%) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce9509062..18e640b91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,11 +40,17 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +[Unreleased] + +### State Machine Breaking + +* [#831](https://github.com/NibiruChain/nibiru/pull/831) - remove modules that are not used in testnet + ## [v0.12.1-alpha](https://github.com/NibiruChain/nibiru/releases/tag/v0.12.1-alpha) - 2022-08-11 ### CI -* [#795](https://github.com/NibiruChain/nibiru/pull/795) Integration tests run when PR is approved +* [#795](https://github.com/NibiruChain/nibiru/pull/795) - integration tests run when PR is approved * [#826](https://github.com/NibiruChain/nibiru/pull/826) - create and push docker image on release diff --git a/app/antedecorators/fee/testutil_test.go b/app/antedecorators/fee/testutil_test.go index e955cce54..404595047 100644 --- a/app/antedecorators/fee/testutil_test.go +++ b/app/antedecorators/fee/testutil_test.go @@ -3,6 +3,8 @@ package fee_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -16,14 +18,13 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) // AnteTestSuite is a test suite to be used with ante handler tests. type AnteTestSuite struct { suite.Suite - app *app.NibiruApp + app *simapp.NibiruTestApp anteHandler sdk.AnteHandler ctx sdk.Context clientCtx client.Context @@ -31,8 +32,8 @@ type AnteTestSuite struct { } // returns context and app with params set on account keeper -func createTestApp(isCheckTx bool) (*app.NibiruApp, sdk.Context) { - app := testapp.NewNibiruApp(true) +func createTestApp(isCheckTx bool) (*simapp.NibiruTestApp, sdk.Context) { + app := simapp.NewTestNibiruApp(true) ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{}) app.AccountKeeper.SetParams(ctx, authtypes.DefaultParams()) diff --git a/app/antedecorators/gasless/gasless_test.go b/app/antedecorators/gasless/gasless_test.go index bff2e8613..e56c587fe 100644 --- a/app/antedecorators/gasless/gasless_test.go +++ b/app/antedecorators/gasless/gasless_test.go @@ -3,6 +3,8 @@ package gasless_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" types3 "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/stretchr/testify/require" @@ -11,7 +13,6 @@ import ( types2 "github.com/NibiruChain/nibiru/app/antedecorators/types" "github.com/NibiruChain/nibiru/x/pricefeed/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) var oracleAddr = sample.AccAddress() @@ -112,7 +113,7 @@ func TestGaslessDecorator_Whitelisted(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) ctx = ctx.WithGasMeter(sdk.NewGasMeter(10000000)) if tc.isWhitelisted { diff --git a/app/app.go b/app/app.go index e3e9d6909..c5d183e36 100644 --- a/app/app.go +++ b/app/app.go @@ -99,18 +99,9 @@ import ( dbm "github.com/tendermint/tm-db" "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/dex" - dexkeeper "github.com/NibiruChain/nibiru/x/dex/keeper" - dextypes "github.com/NibiruChain/nibiru/x/dex/types" "github.com/NibiruChain/nibiru/x/epochs" epochskeeper "github.com/NibiruChain/nibiru/x/epochs/keeper" epochstypes "github.com/NibiruChain/nibiru/x/epochs/types" - "github.com/NibiruChain/nibiru/x/incentivization" - incentivizationkeeper "github.com/NibiruChain/nibiru/x/incentivization/keeper" - incentivizationtypes "github.com/NibiruChain/nibiru/x/incentivization/types" - "github.com/NibiruChain/nibiru/x/lockup" - lockupkeeper "github.com/NibiruChain/nibiru/x/lockup/keeper" - lockuptypes "github.com/NibiruChain/nibiru/x/lockup/types" "github.com/NibiruChain/nibiru/x/perp" perpkeeper "github.com/NibiruChain/nibiru/x/perp/keeper" perptypes "github.com/NibiruChain/nibiru/x/perp/types" @@ -118,9 +109,6 @@ import ( pricefeedcli "github.com/NibiruChain/nibiru/x/pricefeed/client/cli" pricefeedkeeper "github.com/NibiruChain/nibiru/x/pricefeed/keeper" pricefeedtypes "github.com/NibiruChain/nibiru/x/pricefeed/types" - "github.com/NibiruChain/nibiru/x/stablecoin" - stablecoinkeeper "github.com/NibiruChain/nibiru/x/stablecoin/keeper" - stablecointypes "github.com/NibiruChain/nibiru/x/stablecoin/types" "github.com/NibiruChain/nibiru/x/vpool" vpoolcli "github.com/NibiruChain/nibiru/x/vpool/client/cli" vpoolkeeper "github.com/NibiruChain/nibiru/x/vpool/keeper" @@ -129,7 +117,6 @@ import ( const ( AccountAddressPrefix = "nibi" - Name = "nibiru" AppName = "Nibiru" BondDenom = "unibi" DisplayDenom = "NIBI" @@ -173,35 +160,27 @@ var ( ibc.AppModuleBasic{}, ibctransfer.AppModuleBasic{}, // native x/ - dex.AppModuleBasic{}, pricefeed.AppModuleBasic{}, epochs.AppModuleBasic{}, - stablecoin.AppModuleBasic{}, perp.AppModuleBasic{}, - lockup.AppModuleBasic{}, - incentivization.AppModuleBasic{}, vpool.AppModuleBasic{}, ) // module account permissions maccPerms = map[string][]string{ - authtypes.FeeCollectorName: nil, - distrtypes.ModuleName: nil, - minttypes.ModuleName: {authtypes.Minter}, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - govtypes.ModuleName: {authtypes.Burner}, - dextypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - stablecointypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - perptypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - perptypes.VaultModuleAccount: {}, - perptypes.PerpEFModuleAccount: {}, - perptypes.FeePoolModuleAccount: {}, - epochstypes.ModuleName: {}, - lockuptypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - stablecointypes.StableEFModuleAccount: {authtypes.Burner}, - common.TreasuryPoolModuleAccount: {}, + authtypes.FeeCollectorName: nil, + distrtypes.ModuleName: nil, + minttypes.ModuleName: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + govtypes.ModuleName: {authtypes.Burner}, + ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + perptypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + perptypes.VaultModuleAccount: {}, + perptypes.PerpEFModuleAccount: {}, + perptypes.FeePoolModuleAccount: {}, + epochstypes.ModuleName: {}, + common.TreasuryPoolModuleAccount: {}, } ) @@ -228,54 +207,50 @@ type NibiruApp struct { memKeys map[string]*sdk.MemoryStoreKey // -------------------------------------------------------------------- - // NibiruApp Keepers + // NibiruTestApp Keepers // -------------------------------------------------------------------- - // AccountKeeper encodes/decodes accounts using the go-amino (binary) encoding/decoding library - AccountKeeper authkeeper.AccountKeeper - // BankKeeper defines a module interface that facilitates the transfer of coins between accounts - BankKeeper bankkeeper.Keeper - CapabilityKeeper *capabilitykeeper.Keeper - StakingKeeper stakingkeeper.Keeper - SlashingKeeper slashingkeeper.Keeper - MintKeeper mintkeeper.Keeper - /* DistrKeeper is the keeper of the distribution store */ - DistrKeeper distrkeeper.Keeper - GovKeeper govkeeper.Keeper - CrisisKeeper crisiskeeper.Keeper - UpgradeKeeper upgradekeeper.Keeper - ParamsKeeper paramskeeper.Keeper - AuthzKeeper authzkeeper.Keeper - FeeGrantKeeper feegrantkeeper.Keeper + // accountKeeper encodes/decodes accounts using the go-amino (binary) encoding/decoding library + accountKeeper authkeeper.AccountKeeper + // bankKeeper defines a module interface that facilitates the transfer of coins between accounts + bankKeeper bankkeeper.Keeper + capabilityKeeper *capabilitykeeper.Keeper + stakingKeeper stakingkeeper.Keeper + slashingKeeper slashingkeeper.Keeper + mintKeeper mintkeeper.Keeper + /* distrKeeper is the keeper of the distribution store */ + distrKeeper distrkeeper.Keeper + govKeeper govkeeper.Keeper + crisisKeeper crisiskeeper.Keeper + upgradeKeeper upgradekeeper.Keeper + paramsKeeper paramskeeper.Keeper + authzKeeper authzkeeper.Keeper + feeGrantKeeper feegrantkeeper.Keeper // -------------------------------------------------------------------- // IBC keepers // -------------------------------------------------------------------- - /* EvidenceKeeper is responsible for managing persistence, state transitions + /* evidenceKeeper is responsible for managing persistence, state transitions and query handling for the evidence module. It is required to set up the IBC light client misbehavior evidence route. */ - EvidenceKeeper evidencekeeper.Keeper - /* IBCKeeper defines each ICS keeper for IBC. IBCKeeper must be a pointer in + evidenceKeeper evidencekeeper.Keeper + /* ibcKeeper defines each ICS keeper for IBC. ibcKeeper must be a pointer in the app, so we can SetRouter on it correctly. */ - IBCKeeper *ibckeeper.Keeper - /* TransferKeeper is for cross-chain fungible token transfers. */ - TransferKeeper ibctransferkeeper.Keeper + ibcKeeper *ibckeeper.Keeper + /* transferKeeper is for cross-chain fungible token transfers. */ + transferKeeper ibctransferkeeper.Keeper // make scoped keepers public for test purposes - ScopedIBCKeeper capabilitykeeper.ScopedKeeper - ScopedTransferKeeper capabilitykeeper.ScopedKeeper + scopedIBCKeeper capabilitykeeper.ScopedKeeper + scopedTransferKeeper capabilitykeeper.ScopedKeeper // --------------- // Nibiru keepers // --------------- - DexKeeper dexkeeper.Keeper - StablecoinKeeper stablecoinkeeper.Keeper - PerpKeeper perpkeeper.Keeper - PricefeedKeeper pricefeedkeeper.Keeper - EpochsKeeper epochskeeper.Keeper - LockupKeeper lockupkeeper.Keeper - IncentivizationKeeper incentivizationkeeper.Keeper - VpoolKeeper vpoolkeeper.Keeper + epochsKeeper epochskeeper.Keeper + perpKeeper perpkeeper.Keeper + pricefeedKeeper pricefeedkeeper.Keeper + vpoolKeeper vpoolkeeper.Keeper // the module manager mm *module.Manager @@ -331,21 +306,16 @@ func NewNibiruApp( ibchost.StoreKey, ibctransfertypes.StoreKey, // nibiru x/ keys - dextypes.StoreKey, pricefeedtypes.StoreKey, - stablecointypes.StoreKey, epochstypes.StoreKey, - lockuptypes.StoreKey, perptypes.StoreKey, - incentivizationtypes.StoreKey, vpooltypes.StoreKey, ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) - // NOTE: The testingkey is just mounted for testing purposes. Actual applications should - // not include this key. + memKeys := sdk.NewMemoryStoreKeys( - capabilitytypes.MemStoreKey, "testingkey", - stablecointypes.MemStoreKey, pricefeedtypes.MemStoreKey, + capabilitytypes.MemStoreKey, + pricefeedtypes.MemStoreKey, ) app := &NibiruApp{ @@ -359,53 +329,53 @@ func NewNibiruApp( memKeys: memKeys, } - app.ParamsKeeper = initParamsKeeper( + app.paramsKeeper = initParamsKeeper( appCodec, legacyAmino, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey], ) // set the BaseApp's parameter store - bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace). + bApp.SetParamStore(app.paramsKeeper.Subspace(baseapp.Paramspace). WithKeyTable(paramskeeper.ConsensusParamsKeyTable())) - /* Add CapabilityKeeper and ScopeToModule for the ibc module + /* Add capabilityKeeper and ScopeToModule for the ibc module This allows authentication of object-capability permissions for each of the IBC channels. */ - app.CapabilityKeeper = capabilitykeeper.NewKeeper( + app.capabilityKeeper = capabilitykeeper.NewKeeper( appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey]) - app.ScopedIBCKeeper = app.CapabilityKeeper.ScopeToModule(ibchost.ModuleName) - app.ScopedTransferKeeper = app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) + app.scopedIBCKeeper = app.capabilityKeeper.ScopeToModule(ibchost.ModuleName) + app.scopedTransferKeeper = app.capabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) // add keepers - app.AccountKeeper = authkeeper.NewAccountKeeper( + app.accountKeeper = authkeeper.NewAccountKeeper( appCodec, keys[authtypes.StoreKey], app.GetSubspace(authtypes.ModuleName), authtypes.ProtoBaseAccount, maccPerms, ) - app.BankKeeper = bankkeeper.NewBaseKeeper( - appCodec, keys[banktypes.StoreKey], app.AccountKeeper, app.GetSubspace(banktypes.ModuleName), app.ModuleAccountAddrs(), + app.bankKeeper = bankkeeper.NewBaseKeeper( + appCodec, keys[banktypes.StoreKey], app.accountKeeper, app.GetSubspace(banktypes.ModuleName), app.ModuleAccountAddrs(), ) stakingKeeper := stakingkeeper.NewKeeper( - appCodec, keys[stakingtypes.StoreKey], app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName), + appCodec, keys[stakingtypes.StoreKey], app.accountKeeper, app.bankKeeper, app.GetSubspace(stakingtypes.ModuleName), ) - app.MintKeeper = mintkeeper.NewKeeper( + app.mintKeeper = mintkeeper.NewKeeper( appCodec, keys[minttypes.StoreKey], app.GetSubspace(minttypes.ModuleName), &stakingKeeper, - app.AccountKeeper, app.BankKeeper, authtypes.FeeCollectorName, + app.accountKeeper, app.bankKeeper, authtypes.FeeCollectorName, ) - app.DistrKeeper = distrkeeper.NewKeeper( - appCodec, keys[distrtypes.StoreKey], app.GetSubspace(distrtypes.ModuleName), app.AccountKeeper, app.BankKeeper, + app.distrKeeper = distrkeeper.NewKeeper( + appCodec, keys[distrtypes.StoreKey], app.GetSubspace(distrtypes.ModuleName), app.accountKeeper, app.bankKeeper, &stakingKeeper, authtypes.FeeCollectorName, app.ModuleAccountAddrs(), ) - app.SlashingKeeper = slashingkeeper.NewKeeper( + app.slashingKeeper = slashingkeeper.NewKeeper( appCodec, keys[slashingtypes.StoreKey], &stakingKeeper, app.GetSubspace(slashingtypes.ModuleName), ) - app.CrisisKeeper = crisiskeeper.NewKeeper( - app.GetSubspace(crisistypes.ModuleName), invCheckPeriod, app.BankKeeper, authtypes.FeeCollectorName, + app.crisisKeeper = crisiskeeper.NewKeeper( + app.GetSubspace(crisistypes.ModuleName), invCheckPeriod, app.bankKeeper, authtypes.FeeCollectorName, ) - app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.AccountKeeper) + app.feeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.accountKeeper) - /*UpgradeKeeper must be created before IBCKeeper. */ - app.UpgradeKeeper = upgradekeeper.NewKeeper( + /*upgradeKeeper must be created before ibcKeeper. */ + app.upgradeKeeper = upgradekeeper.NewKeeper( skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, @@ -414,66 +384,48 @@ func NewNibiruApp( // register the staking hooks // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks - app.StakingKeeper = *stakingKeeper.SetHooks( - stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), + app.stakingKeeper = *stakingKeeper.SetHooks( + stakingtypes.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()), ) - app.AuthzKeeper = authzkeeper.NewKeeper(keys[authzkeeper.StoreKey], appCodec, app.BaseApp.MsgServiceRouter()) + app.authzKeeper = authzkeeper.NewKeeper(keys[authzkeeper.StoreKey], appCodec, app.BaseApp.MsgServiceRouter()) // ---------------------------------- Nibiru Chain x/ keepers - app.DexKeeper = dexkeeper.NewKeeper( - appCodec, keys[dextypes.StoreKey], app.GetSubspace(dextypes.ModuleName), - app.AccountKeeper, app.BankKeeper, app.DistrKeeper) - - app.PricefeedKeeper = pricefeedkeeper.NewKeeper( + app.pricefeedKeeper = pricefeedkeeper.NewKeeper( appCodec, keys[pricefeedtypes.StoreKey], memKeys[pricefeedtypes.MemStoreKey], app.GetSubspace(pricefeedtypes.ModuleName), ) - app.StablecoinKeeper = stablecoinkeeper.NewKeeper( - appCodec, keys[stablecointypes.StoreKey], memKeys[stablecointypes.MemStoreKey], - app.GetSubspace(stablecointypes.ModuleName), - app.AccountKeeper, app.BankKeeper, app.PricefeedKeeper, app.DexKeeper, - ) - - app.VpoolKeeper = vpoolkeeper.NewKeeper( + app.vpoolKeeper = vpoolkeeper.NewKeeper( appCodec, keys[vpooltypes.StoreKey], - app.PricefeedKeeper, + app.pricefeedKeeper, ) - app.EpochsKeeper = epochskeeper.NewKeeper( + app.epochsKeeper = epochskeeper.NewKeeper( appCodec, keys[epochstypes.StoreKey], ) - app.PerpKeeper = perpkeeper.NewKeeper( + app.perpKeeper = perpkeeper.NewKeeper( appCodec, keys[perptypes.StoreKey], app.GetSubspace(perptypes.ModuleName), - app.AccountKeeper, app.BankKeeper, app.PricefeedKeeper, app.VpoolKeeper, app.EpochsKeeper, - ) - - app.EpochsKeeper.SetHooks( - epochstypes.NewMultiEpochHooks(app.StablecoinKeeper.Hooks(), app.PerpKeeper.Hooks()), + app.accountKeeper, app.bankKeeper, app.pricefeedKeeper, app.vpoolKeeper, app.epochsKeeper, ) - app.LockupKeeper = lockupkeeper.NewLockupKeeper(appCodec, - keys[lockuptypes.StoreKey], app.AccountKeeper, app.BankKeeper, - app.DistrKeeper) - - app.IncentivizationKeeper = incentivizationkeeper.NewKeeper(appCodec, - keys[incentivizationtypes.StoreKey], app.AccountKeeper, app.BankKeeper, app.DexKeeper, app.LockupKeeper, + app.epochsKeeper.SetHooks( + epochstypes.NewMultiEpochHooks(app.perpKeeper.Hooks()), ) // ---------------------------------- IBC keepers - app.IBCKeeper = ibckeeper.NewKeeper( + app.ibcKeeper = ibckeeper.NewKeeper( appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), - app.StakingKeeper, - app.UpgradeKeeper, - app.ScopedIBCKeeper, + app.stakingKeeper, + app.upgradeKeeper, + app.scopedIBCKeeper, ) // register the proposal types @@ -481,32 +433,32 @@ func NewNibiruApp( govRouter := govtypes.NewRouter() govRouter. AddRoute(govtypes.RouterKey, govtypes.ProposalHandler). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). - AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)). - AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)). - AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper)). - AddRoute(pricefeedtypes.RouterKey, pricefeed.NewPricefeedProposalHandler(app.PricefeedKeeper)). - AddRoute(vpooltypes.RouterKey, vpool.NewCreatePoolProposalHandler(app.VpoolKeeper)) - - app.TransferKeeper = ibctransferkeeper.NewKeeper( + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). + AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.distrKeeper)). + AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.upgradeKeeper)). + AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.ibcKeeper.ClientKeeper)). + AddRoute(pricefeedtypes.RouterKey, pricefeed.NewPricefeedProposalHandler(app.pricefeedKeeper)). + AddRoute(vpooltypes.RouterKey, vpool.NewCreatePoolProposalHandler(app.vpoolKeeper)) + + app.transferKeeper = ibctransferkeeper.NewKeeper( appCodec, keys[ibctransfertypes.StoreKey], /* paramSubspace */ app.GetSubspace(ibctransfertypes.ModuleName), - /* ibctransfertypes.ICS4Wrapper */ app.IBCKeeper.ChannelKeeper, - /* ibctransfertypes.ChannelKeeper */ app.IBCKeeper.ChannelKeeper, - /* ibctransfertypes.PortKeeper */ &app.IBCKeeper.PortKeeper, - app.AccountKeeper, - app.BankKeeper, - app.ScopedTransferKeeper, + /* ibctransfertypes.ICS4Wrapper */ app.ibcKeeper.ChannelKeeper, + /* ibctransfertypes.ChannelKeeper */ app.ibcKeeper.ChannelKeeper, + /* ibctransfertypes.PortKeeper */ &app.ibcKeeper.PortKeeper, + app.accountKeeper, + app.bankKeeper, + app.scopedTransferKeeper, ) - transferModule := ibctransfer.NewAppModule(app.TransferKeeper) - transferIBCModule := ibctransfer.NewIBCModule(app.TransferKeeper) + transferModule := ibctransfer.NewAppModule(app.transferKeeper) + transferIBCModule := ibctransfer.NewIBCModule(app.transferKeeper) // Create evidence keeper. // This keeper automatically includes an evidence router. - app.EvidenceKeeper = *evidencekeeper.NewKeeper( - appCodec, keys[evidencetypes.StoreKey], &app.StakingKeeper, - app.SlashingKeeper, + app.evidenceKeeper = *evidencekeeper.NewKeeper( + appCodec, keys[evidencetypes.StoreKey], &app.stakingKeeper, + app.slashingKeeper, ) /* Create IBC module and a static IBC router */ @@ -517,11 +469,11 @@ func NewNibiruApp( /* ibcModule */ transferIBCModule) /* SetRouter finalizes all routes by sealing the router. No more routes can be added. */ - app.IBCKeeper.SetRouter(ibcRouter) + app.ibcKeeper.SetRouter(ibcRouter) - app.GovKeeper = govkeeper.NewKeeper( + app.govKeeper = govkeeper.NewKeeper( appCodec, keys[govtypes.StoreKey], app.GetSubspace(govtypes.ModuleName), - app.AccountKeeper, app.BankKeeper, &app.StakingKeeper, govRouter, + app.accountKeeper, app.bankKeeper, &app.stakingKeeper, govRouter, ) // -------------------------- Module Options -------------------------- @@ -533,58 +485,48 @@ func NewNibiruApp( var skipGenesisInvariants = cast.ToBool( appOpts.Get(crisis.FlagSkipGenesisInvariants)) - dexModule := dex.NewAppModule( - appCodec, app.DexKeeper, app.AccountKeeper, app.BankKeeper) pricefeedModule := pricefeed.NewAppModule( - appCodec, app.PricefeedKeeper, app.AccountKeeper, app.BankKeeper) - epochsModule := epochs.NewAppModule(appCodec, app.EpochsKeeper) - stablecoinModule := stablecoin.NewAppModule( - appCodec, app.StablecoinKeeper, app.AccountKeeper, app.BankKeeper, - app.PricefeedKeeper, - ) - lockupModule := lockup.NewAppModule(appCodec, app.LockupKeeper, app.AccountKeeper, app.BankKeeper) + appCodec, app.pricefeedKeeper, app.accountKeeper, app.bankKeeper) + epochsModule := epochs.NewAppModule(appCodec, app.epochsKeeper) perpModule := perp.NewAppModule( - appCodec, app.PerpKeeper, app.AccountKeeper, app.BankKeeper, - app.PricefeedKeeper, + appCodec, app.perpKeeper, app.accountKeeper, app.bankKeeper, + app.pricefeedKeeper, ) vpoolModule := vpool.NewAppModule( - appCodec, app.VpoolKeeper, app.PricefeedKeeper, + appCodec, app.vpoolKeeper, app.pricefeedKeeper, ) - incentivizationModule := incentivization.NewAppModule(appCodec, app.IncentivizationKeeper, app.AccountKeeper) // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. app.mm = module.NewManager( genutil.NewAppModule( - app.AccountKeeper, app.StakingKeeper, app.BaseApp.DeliverTx, + app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx, encodingConfig.TxConfig, ), - auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), - vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), - capability.NewAppModule(appCodec, *app.CapabilityKeeper), - crisis.NewAppModule(&app.CrisisKeeper, skipGenesisInvariants), - feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), - gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), - upgrade.NewAppModule(app.UpgradeKeeper), - params.NewAppModule(app.ParamsKeeper), - authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), + auth.NewAppModule(appCodec, app.accountKeeper, authsims.RandomGenesisAccounts), + vesting.NewAppModule(app.accountKeeper, app.bankKeeper), + bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper), + capability.NewAppModule(appCodec, *app.capabilityKeeper), + crisis.NewAppModule(&app.crisisKeeper, skipGenesisInvariants), + feegrantmodule.NewAppModule(appCodec, app.accountKeeper, app.bankKeeper, app.feeGrantKeeper, app.interfaceRegistry), + gov.NewAppModule(appCodec, app.govKeeper, app.accountKeeper, app.bankKeeper), + mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper), + slashing.NewAppModule(appCodec, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper), + distr.NewAppModule(appCodec, app.distrKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper), + staking.NewAppModule(appCodec, app.stakingKeeper, app.accountKeeper, app.bankKeeper), + upgrade.NewAppModule(app.upgradeKeeper), + params.NewAppModule(app.paramsKeeper), + authzmodule.NewAppModule(appCodec, app.authzKeeper, app.accountKeeper, app.bankKeeper, app.interfaceRegistry), + // native x/ - dexModule, pricefeedModule, - stablecoinModule, - lockupModule, epochsModule, vpoolModule, perpModule, - incentivizationModule, + // ibc - evidence.NewAppModule(app.EvidenceKeeper), - ibc.NewAppModule(app.IBCKeeper), + evidence.NewAppModule(app.evidenceKeeper), + ibc.NewAppModule(app.ibcKeeper), transferModule, ) @@ -611,14 +553,10 @@ func NewNibiruApp( vestingtypes.ModuleName, stakingtypes.ModuleName, // native x/ - dextypes.ModuleName, pricefeedtypes.ModuleName, epochstypes.ModuleName, - stablecointypes.ModuleName, vpooltypes.ModuleName, perptypes.ModuleName, - lockuptypes.ModuleName, - incentivizationtypes.ModuleName, // ibc modules ibchost.ModuleName, ibctransfertypes.ModuleName, @@ -641,14 +579,10 @@ func NewNibiruApp( upgradetypes.ModuleName, vestingtypes.ModuleName, // native x/ - dextypes.ModuleName, epochstypes.ModuleName, pricefeedtypes.ModuleName, - stablecointypes.ModuleName, vpooltypes.ModuleName, perptypes.ModuleName, - lockuptypes.ModuleName, - incentivizationtypes.ModuleName, // ibc ibchost.ModuleName, ibctransfertypes.ModuleName, @@ -677,14 +611,10 @@ func NewNibiruApp( upgradetypes.ModuleName, vestingtypes.ModuleName, // native x/ - dextypes.ModuleName, pricefeedtypes.ModuleName, epochstypes.ModuleName, - stablecointypes.ModuleName, vpooltypes.ModuleName, perptypes.ModuleName, - lockuptypes.ModuleName, - incentivizationtypes.ModuleName, // ibc ibchost.ModuleName, ibctransfertypes.ModuleName, @@ -693,13 +623,13 @@ func NewNibiruApp( // Uncomment if you want to set a custom migration order here. // app.mm.SetOrderMigrations(custom order) - app.mm.RegisterInvariants(&app.CrisisKeeper) + app.mm.RegisterInvariants(&app.crisisKeeper) app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino) app.configurator = module.NewConfigurator( app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) app.mm.RegisterServices(app.configurator) - app.UpgradeKeeper.SetUpgradeHandler("v0.10.0", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + app.upgradeKeeper.SetUpgradeHandler("v0.10.0", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { // no-op return fromVM, nil }) @@ -712,27 +642,23 @@ func NewNibiruApp( // NOTE: this is not required apps that don't use the simulator for fuzz testing // transactions app.sm = module.NewSimulationManager( - auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), - feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), - gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - params.NewAppModule(app.ParamsKeeper), - authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), + auth.NewAppModule(appCodec, app.accountKeeper, authsims.RandomGenesisAccounts), + bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper), + feegrantmodule.NewAppModule(appCodec, app.accountKeeper, app.bankKeeper, app.feeGrantKeeper, app.interfaceRegistry), + gov.NewAppModule(appCodec, app.govKeeper, app.accountKeeper, app.bankKeeper), + mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper), + staking.NewAppModule(appCodec, app.stakingKeeper, app.accountKeeper, app.bankKeeper), + distr.NewAppModule(appCodec, app.distrKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper), + slashing.NewAppModule(appCodec, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper), + params.NewAppModule(app.paramsKeeper), + authzmodule.NewAppModule(appCodec, app.authzKeeper, app.accountKeeper, app.bankKeeper, app.interfaceRegistry), // native x/ - dexModule, pricefeedModule, epochsModule, - stablecoinModule, - lockupModule, - incentivizationModule, // ibc - capability.NewAppModule(appCodec, *app.CapabilityKeeper), - evidence.NewAppModule(app.EvidenceKeeper), - ibc.NewAppModule(app.IBCKeeper), + capability.NewAppModule(appCodec, *app.capabilityKeeper), + evidence.NewAppModule(app.evidenceKeeper), + ibc.NewAppModule(app.ibcKeeper), transferModule, ) @@ -748,14 +674,14 @@ func NewNibiruApp( app.SetBeginBlocker(app.BeginBlocker) anteHandler, err := NewAnteHandler(AnteHandlerOptions{ HandlerOptions: ante.HandlerOptions{ - AccountKeeper: app.AccountKeeper, - BankKeeper: app.BankKeeper, - FeegrantKeeper: app.FeeGrantKeeper, + AccountKeeper: app.accountKeeper, + BankKeeper: app.bankKeeper, + FeegrantKeeper: app.feeGrantKeeper, SignModeHandler: encodingConfig.TxConfig.SignModeHandler(), SigGasConsumer: ante.DefaultSigVerificationGasConsumer, }, - PricefeedKeeper: app.PricefeedKeeper, - IBCKeeper: app.IBCKeeper, + PricefeedKeeper: app.pricefeedKeeper, + IBCKeeper: app.ibcKeeper, }) if err != nil { @@ -772,10 +698,10 @@ func NewNibiruApp( /* Applications that wish to enforce statically created ScopedKeepers should call `Seal` after creating their scoped modules in `NewApp` with - `CapabilityKeeper.ScopeToModule`. + `capabilityKeeper.ScopeToModule`. - Calling 'app.CapabilityKeeper.Seal()' initializes and seals the capability + Calling 'app.capabilityKeeper.Seal()' initializes and seals the capability keeper such that all persistent capabilities are loaded in-memory and prevent any further modules from creating scoped sub-keepers. @@ -784,7 +710,7 @@ func NewNibiruApp( Note that since this reads from the store, we can only perform the seal when `loadLatest` is set to true. */ - app.CapabilityKeeper.Seal() + app.capabilityKeeper.Seal() } return app @@ -809,7 +735,7 @@ func (app *NibiruApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) ab if err := json.Unmarshal(req.AppStateBytes, &genesisState); err != nil { panic(err) } - app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()) + app.upgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()) return app.mm.InitGenesis(ctx, app.appCodec, genesisState) } @@ -874,7 +800,7 @@ func (app *NibiruApp) GetMemKey(storeKey string) *storetypes.MemoryStoreKey { // // NOTE: This is solely to be used for testing purposes. func (app *NibiruApp) GetSubspace(moduleName string) paramstypes.Subspace { - subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) + subspace, _ := app.paramsKeeper.GetSubspace(moduleName) return subspace } @@ -930,15 +856,15 @@ func (app *NibiruApp) GetBaseApp() *baseapp.BaseApp { } func (app *NibiruApp) GetStakingKeeper() stakingkeeper.Keeper { - return app.StakingKeeper + return app.stakingKeeper } func (app *NibiruApp) GetIBCKeeper() *ibckeeper.Keeper { - return app.IBCKeeper + return app.ibcKeeper } func (app *NibiruApp) GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper { - return app.ScopedIBCKeeper + return app.scopedIBCKeeper } /* EncodingConfig specifies the concrete encoding types to use for a given app. @@ -987,10 +913,8 @@ func initParamsKeeper( paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()) paramsKeeper.Subspace(crisistypes.ModuleName) // Native module params keepers - paramsKeeper.Subspace(dextypes.ModuleName) paramsKeeper.Subspace(pricefeedtypes.ModuleName) paramsKeeper.Subspace(epochstypes.ModuleName) - paramsKeeper.Subspace(stablecointypes.ModuleName) // ibc params keepers paramsKeeper.Subspace(ibctransfertypes.ModuleName) paramsKeeper.Subspace(ibchost.ModuleName) diff --git a/app/export.go b/app/export.go index 051be9b97..72a8342a3 100644 --- a/app/export.go +++ b/app/export.go @@ -35,7 +35,7 @@ func (app *NibiruApp) ExportAppStateAndValidators( return servertypes.ExportedApp{}, err } - validators, err := staking.WriteValidators(ctx, app.StakingKeeper) + validators, err := staking.WriteValidators(ctx, app.stakingKeeper) return servertypes.ExportedApp{ AppState: appState, Validators: validators, @@ -67,18 +67,18 @@ func (app *NibiruApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs } /* Just to be safe, assert the invariants on current state. */ - app.CrisisKeeper.AssertInvariants(ctx) + app.crisisKeeper.AssertInvariants(ctx) /* Handle fee distribution state. */ // withdraw all validator commission - app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + app.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + _, _ = app.distrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) return false }) // withdraw all delegator rewards - dels := app.StakingKeeper.GetAllDelegations(ctx) + dels := app.stakingKeeper.GetAllDelegations(ctx) for _, delegation := range dels { valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) if err != nil { @@ -89,28 +89,28 @@ func (app *NibiruApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs if err != nil { panic(err) } - _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) + _, _ = app.distrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) } // clear validator slash events - app.DistrKeeper.DeleteAllValidatorSlashEvents(ctx) + app.distrKeeper.DeleteAllValidatorSlashEvents(ctx) // clear validator historical rewards - app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx) + app.distrKeeper.DeleteAllValidatorHistoricalRewards(ctx) // set context height to zero height := ctx.BlockHeight() ctx = ctx.WithBlockHeight(0) // reinitialize all validators - app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + app.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) - feePool := app.DistrKeeper.GetFeePool(ctx) + scraps := app.distrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) + feePool := app.distrKeeper.GetFeePool(ctx) feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) - app.DistrKeeper.SetFeePool(ctx, feePool) + app.distrKeeper.SetFeePool(ctx, feePool) - app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + app.distrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) return false }) @@ -124,8 +124,8 @@ func (app *NibiruApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs if err != nil { panic(err) } - app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) - app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) + app.distrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) + app.distrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) } // reset context height @@ -134,20 +134,20 @@ func (app *NibiruApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs /* Handle staking state. */ // iterate through redelegations, reset creation height - app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { + app.stakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { for i := range red.Entries { red.Entries[i].CreationHeight = 0 } - app.StakingKeeper.SetRedelegation(ctx, red) + app.stakingKeeper.SetRedelegation(ctx, red) return false }) // iterate through unbonding delegations, reset creation height - app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { + app.stakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { for i := range ubd.Entries { ubd.Entries[i].CreationHeight = 0 } - app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) + app.stakingKeeper.SetUnbondingDelegation(ctx, ubd) return false }) @@ -159,7 +159,7 @@ func (app *NibiruApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs for ; iter.Valid(); iter.Next() { addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) - validator, found := app.StakingKeeper.GetValidator(ctx, addr) + validator, found := app.stakingKeeper.GetValidator(ctx, addr) if !found { panic("expected validator, not found") } @@ -169,13 +169,13 @@ func (app *NibiruApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs validator.Jailed = true } - app.StakingKeeper.SetValidator(ctx, validator) + app.stakingKeeper.SetValidator(ctx, validator) counter++ } iter.Close() - _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err := app.stakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) if err != nil { log.Fatal(err) } @@ -183,11 +183,11 @@ func (app *NibiruApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs /* Handle slashing state. */ // reset start height on signing infos - app.SlashingKeeper.IterateValidatorSigningInfos( + app.slashingKeeper.IterateValidatorSigningInfos( ctx, func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { info.StartHeight = 0 - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info) + app.slashingKeeper.SetValidatorSigningInfo(ctx, addr, info) return false }, ) diff --git a/app/ibc_test.go b/app/ibc_test.go index 2dc335f02..4920ef91f 100644 --- a/app/ibc_test.go +++ b/app/ibc_test.go @@ -16,13 +16,17 @@ import ( ibcmock "github.com/cosmos/ibc-go/v3/testing/mock" "github.com/stretchr/testify/suite" - "github.com/NibiruChain/nibiru/app" + "github.com/NibiruChain/nibiru/simapp" "github.com/NibiruChain/nibiru/x/common" pricefeedtypes "github.com/NibiruChain/nibiru/x/pricefeed/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) +// init changes the value of 'DefaultTestingAppInit' to use custom initialization. +func init() { + ibctesting.DefaultTestingAppInit = SetupNibiruTestingApp +} + /* SetupTestingApp returns the TestingApp and default genesis state used to @@ -33,7 +37,7 @@ func SetupNibiruTestingApp() ( defaultGenesis map[string]json.RawMessage, ) { // create testing app - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) // Whitelist a pair and oracle pair, err := common.NewAssetPair("uatom:unibi") @@ -60,17 +64,12 @@ func SetupNibiruTestingApp() ( } // Create genesis state - encCdc := app.MakeTestEncodingConfig() - genesisState := app.NewDefaultGenesisState(encCdc.Marshaler) + encCdc := simapp.MakeTestEncodingConfig() + genesisState := simapp.NewDefaultGenesisState(encCdc.Marshaler) return nibiruApp, genesisState } -// init changes the value of 'DefaultTestingAppInit' to use custom initialization. -func init() { - ibctesting.DefaultTestingAppInit = SetupNibiruTestingApp -} - // IBCTestSuite is a testing suite to test keeper functions. type IBCTestSuite struct { suite.Suite diff --git a/simapp/app.go b/simapp/app.go new file mode 100644 index 000000000..dd8af2422 --- /dev/null +++ b/simapp/app.go @@ -0,0 +1,1001 @@ +package simapp + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + _ "github.com/cosmos/cosmos-sdk/client/docs/statik" + "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/server/api" + "github.com/cosmos/cosmos-sdk/server/config" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + "github.com/cosmos/cosmos-sdk/simapp" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/version" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/ante" + authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" + authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + "github.com/cosmos/cosmos-sdk/x/authz" + authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" + authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module" + "github.com/cosmos/cosmos-sdk/x/bank" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/capability" + capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" + "github.com/cosmos/cosmos-sdk/x/crisis" + crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" + crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/evidence" + evidencekeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper" + evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" + "github.com/cosmos/cosmos-sdk/x/feegrant" + feegrantkeeper "github.com/cosmos/cosmos-sdk/x/feegrant/keeper" + feegrantmodule "github.com/cosmos/cosmos-sdk/x/feegrant/module" + "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + "github.com/cosmos/cosmos-sdk/x/gov" + govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/mint" + mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "github.com/cosmos/cosmos-sdk/x/params" + paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" + paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + "github.com/cosmos/cosmos-sdk/x/slashing" + slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/cosmos/cosmos-sdk/x/upgrade" + upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" + upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + ibctransfer "github.com/cosmos/ibc-go/v3/modules/apps/transfer" + ibctransferkeeper "github.com/cosmos/ibc-go/v3/modules/apps/transfer/keeper" + ibctransfertypes "github.com/cosmos/ibc-go/v3/modules/apps/transfer/types" + ibc "github.com/cosmos/ibc-go/v3/modules/core" + ibcclient "github.com/cosmos/ibc-go/v3/modules/core/02-client" + ibcclientclient "github.com/cosmos/ibc-go/v3/modules/core/02-client/client" + ibcclienttypes "github.com/cosmos/ibc-go/v3/modules/core/02-client/types" + porttypes "github.com/cosmos/ibc-go/v3/modules/core/05-port/types" + ibchost "github.com/cosmos/ibc-go/v3/modules/core/24-host" + ibckeeper "github.com/cosmos/ibc-go/v3/modules/core/keeper" + ibctesting "github.com/cosmos/ibc-go/v3/testing" + "github.com/gorilla/mux" + "github.com/rakyll/statik/fs" + "github.com/spf13/cast" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tmos "github.com/tendermint/tendermint/libs/os" + dbm "github.com/tendermint/tm-db" + + nibiapp "github.com/NibiruChain/nibiru/app" + "github.com/NibiruChain/nibiru/x/common" + "github.com/NibiruChain/nibiru/x/dex" + dexkeeper "github.com/NibiruChain/nibiru/x/dex/keeper" + dextypes "github.com/NibiruChain/nibiru/x/dex/types" + "github.com/NibiruChain/nibiru/x/epochs" + epochskeeper "github.com/NibiruChain/nibiru/x/epochs/keeper" + epochstypes "github.com/NibiruChain/nibiru/x/epochs/types" + "github.com/NibiruChain/nibiru/x/incentivization" + incentivizationkeeper "github.com/NibiruChain/nibiru/x/incentivization/keeper" + incentivizationtypes "github.com/NibiruChain/nibiru/x/incentivization/types" + "github.com/NibiruChain/nibiru/x/lockup" + lockupkeeper "github.com/NibiruChain/nibiru/x/lockup/keeper" + lockuptypes "github.com/NibiruChain/nibiru/x/lockup/types" + "github.com/NibiruChain/nibiru/x/perp" + perpkeeper "github.com/NibiruChain/nibiru/x/perp/keeper" + perptypes "github.com/NibiruChain/nibiru/x/perp/types" + "github.com/NibiruChain/nibiru/x/pricefeed" + pricefeedcli "github.com/NibiruChain/nibiru/x/pricefeed/client/cli" + pricefeedkeeper "github.com/NibiruChain/nibiru/x/pricefeed/keeper" + pricefeedtypes "github.com/NibiruChain/nibiru/x/pricefeed/types" + "github.com/NibiruChain/nibiru/x/stablecoin" + stablecoinkeeper "github.com/NibiruChain/nibiru/x/stablecoin/keeper" + stablecointypes "github.com/NibiruChain/nibiru/x/stablecoin/types" + "github.com/NibiruChain/nibiru/x/vpool" + vpoolcli "github.com/NibiruChain/nibiru/x/vpool/client/cli" + vpoolkeeper "github.com/NibiruChain/nibiru/x/vpool/keeper" + vpooltypes "github.com/NibiruChain/nibiru/x/vpool/types" +) + +const ( + Name = "nibiru" + AppName = "Nibiru" + BondDenom = "unibi" +) + +var ( + // DefaultNodeHome default home directories for the application daemon + DefaultNodeHome string + + // ModuleBasics defines the module BasicManager is in charge of setting up basic, + // non-dependant module elements, such as codec registration + // and genesis verification. + ModuleBasics = module.NewBasicManager( + auth.AppModuleBasic{}, + genutil.AppModuleBasic{}, + nibiapp.BankModule{}, + capability.AppModuleBasic{}, + nibiapp.StakingModule{}, + nibiapp.MintModule{}, + distr.AppModuleBasic{}, + nibiapp.NewGovModuleBasic( + paramsclient.ProposalHandler, + distrclient.ProposalHandler, + upgradeclient.ProposalHandler, + upgradeclient.CancelProposalHandler, + pricefeedcli.AddOracleProposalHandler, + vpoolcli.CreatePoolProposalHandler, + // pricefeedcli.RemoveOracleProposalHandler, // TODO + ibcclientclient.UpdateClientProposalHandler, + ibcclientclient.UpgradeProposalHandler, + ), + params.AppModuleBasic{}, + nibiapp.CrisisModule{}, + slashing.AppModuleBasic{}, + feegrantmodule.AppModuleBasic{}, + authzmodule.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + vesting.AppModuleBasic{}, + + // ibc 'AppModuleBasic's + ibc.AppModuleBasic{}, + ibctransfer.AppModuleBasic{}, + + // native x/ + dex.AppModuleBasic{}, + pricefeed.AppModuleBasic{}, + epochs.AppModuleBasic{}, + stablecoin.AppModuleBasic{}, + perp.AppModuleBasic{}, + lockup.AppModuleBasic{}, + incentivization.AppModuleBasic{}, + vpool.AppModuleBasic{}, + ) + + // module account permissions + maccPerms = map[string][]string{ + authtypes.FeeCollectorName: nil, + distrtypes.ModuleName: nil, + minttypes.ModuleName: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + govtypes.ModuleName: {authtypes.Burner}, + dextypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + stablecointypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + perptypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + perptypes.VaultModuleAccount: {}, + perptypes.PerpEFModuleAccount: {}, + perptypes.FeePoolModuleAccount: {}, + epochstypes.ModuleName: {}, + lockuptypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + stablecointypes.StableEFModuleAccount: {authtypes.Burner}, + common.TreasuryPoolModuleAccount: {}, + } +) + +var ( + _ simapp.App = (*NibiruTestApp)(nil) + _ servertypes.Application = (*NibiruTestApp)(nil) + _ ibctesting.TestingApp = (*NibiruTestApp)(nil) +) + +// NibiruTestApp extends an ABCI application, but with most of its parameters exported. +// They are exported for convenience in creating helper functions, as object +// capabilities aren't needed for testing. +type NibiruTestApp struct { + *baseapp.BaseApp + legacyAmino *codec.LegacyAmino + appCodec codec.Codec + interfaceRegistry codectypes.InterfaceRegistry + + invCheckPeriod uint + + // keys to access the substores + keys map[string]*sdk.KVStoreKey + tkeys map[string]*sdk.TransientStoreKey + memKeys map[string]*sdk.MemoryStoreKey + + // -------------------------------------------------------------------- + // NibiruTestApp Keepers + // -------------------------------------------------------------------- + + // AccountKeeper encodes/decodes accounts using the go-amino (binary) encoding/decoding library + AccountKeeper authkeeper.AccountKeeper + // BankKeeper defines a module interface that facilitates the transfer of coins between accounts + BankKeeper bankkeeper.Keeper + CapabilityKeeper *capabilitykeeper.Keeper + StakingKeeper stakingkeeper.Keeper + SlashingKeeper slashingkeeper.Keeper + MintKeeper mintkeeper.Keeper + /* DistrKeeper is the keeper of the distribution store */ + DistrKeeper distrkeeper.Keeper + GovKeeper govkeeper.Keeper + CrisisKeeper crisiskeeper.Keeper + UpgradeKeeper upgradekeeper.Keeper + ParamsKeeper paramskeeper.Keeper + AuthzKeeper authzkeeper.Keeper + FeeGrantKeeper feegrantkeeper.Keeper + + // -------------------------------------------------------------------- + // IBC keepers + // -------------------------------------------------------------------- + /* EvidenceKeeper is responsible for managing persistence, state transitions + and query handling for the evidence module. It is required to set up + the IBC light client misbehavior evidence route. */ + EvidenceKeeper evidencekeeper.Keeper + /* IBCKeeper defines each ICS keeper for IBC. IBCKeeper must be a pointer in + the nibiapp, so we can SetRouter on it correctly. */ + IBCKeeper *ibckeeper.Keeper + /* TransferKeeper is for cross-chain fungible token transfers. */ + TransferKeeper ibctransferkeeper.Keeper + + // make scoped keepers public for test purposes + ScopedIBCKeeper capabilitykeeper.ScopedKeeper + ScopedTransferKeeper capabilitykeeper.ScopedKeeper + + // --------------- + // Nibiru keepers + // --------------- + DexKeeper dexkeeper.Keeper + StablecoinKeeper stablecoinkeeper.Keeper + PerpKeeper perpkeeper.Keeper + PricefeedKeeper pricefeedkeeper.Keeper + EpochsKeeper epochskeeper.Keeper + LockupKeeper lockupkeeper.Keeper + IncentivizationKeeper incentivizationkeeper.Keeper + VpoolKeeper vpoolkeeper.Keeper + + // the module manager + mm *module.Manager + + // simulation manager + sm *module.SimulationManager + + // module configurator + configurator module.Configurator +} + +func init() { + userHomeDir, err := os.UserHomeDir() + if err != nil { + panic(err) + } + + DefaultNodeHome = filepath.Join(userHomeDir, ".nibid") +} + +// NewNibiruTestApp returns a reference to an initialized NibiruTestApp. +func NewNibiruTestApp( + logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, + skipUpgradeHeights map[int64]bool, homePath string, invCheckPeriod uint, + encodingConfig simappparams.EncodingConfig, + appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), +) *NibiruTestApp { + appCodec := encodingConfig.Marshaler + legacyAmino := encodingConfig.Amino + interfaceRegistry := encodingConfig.InterfaceRegistry + + bApp := baseapp.NewBaseApp( + AppName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...) + bApp.SetCommitMultiStoreTracer(traceStore) + bApp.SetVersion(version.Version) + bApp.SetInterfaceRegistry(interfaceRegistry) + + keys := sdk.NewKVStoreKeys( + authtypes.StoreKey, + banktypes.StoreKey, + stakingtypes.StoreKey, + minttypes.StoreKey, + distrtypes.StoreKey, + slashingtypes.StoreKey, + govtypes.StoreKey, + paramstypes.StoreKey, + upgradetypes.StoreKey, + feegrant.StoreKey, + evidencetypes.StoreKey, + capabilitytypes.StoreKey, + authzkeeper.StoreKey, + // ibc keys + ibchost.StoreKey, + ibctransfertypes.StoreKey, + // nibiru x/ keys + dextypes.StoreKey, + pricefeedtypes.StoreKey, + stablecointypes.StoreKey, + epochstypes.StoreKey, + lockuptypes.StoreKey, + perptypes.StoreKey, + incentivizationtypes.StoreKey, + vpooltypes.StoreKey, + ) + tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) + // NOTE: The testingkey is just mounted for testing purposes. Actual applications should + // not include this key. + memKeys := sdk.NewMemoryStoreKeys( + capabilitytypes.MemStoreKey, "testingkey", + stablecointypes.MemStoreKey, pricefeedtypes.MemStoreKey, + ) + + app := &NibiruTestApp{ + BaseApp: bApp, + legacyAmino: legacyAmino, + appCodec: appCodec, + interfaceRegistry: interfaceRegistry, + invCheckPeriod: invCheckPeriod, + keys: keys, + tkeys: tkeys, + memKeys: memKeys, + } + + app.ParamsKeeper = initParamsKeeper( + appCodec, legacyAmino, keys[paramstypes.StoreKey], + tkeys[paramstypes.TStoreKey], + ) + + // set the BaseApp's parameter store + bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace). + WithKeyTable(paramskeeper.ConsensusParamsKeyTable())) + + /* Add CapabilityKeeper and ScopeToModule for the ibc module + This allows authentication of object-capability permissions for each of + the IBC channels. + */ + app.CapabilityKeeper = capabilitykeeper.NewKeeper( + appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey]) + app.ScopedIBCKeeper = app.CapabilityKeeper.ScopeToModule(ibchost.ModuleName) + app.ScopedTransferKeeper = app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) + + // add keepers + app.AccountKeeper = authkeeper.NewAccountKeeper( + appCodec, keys[authtypes.StoreKey], app.GetSubspace(authtypes.ModuleName), authtypes.ProtoBaseAccount, maccPerms, + ) + app.BankKeeper = bankkeeper.NewBaseKeeper( + appCodec, keys[banktypes.StoreKey], app.AccountKeeper, app.GetSubspace(banktypes.ModuleName), app.ModuleAccountAddrs(), + ) + stakingKeeper := stakingkeeper.NewKeeper( + appCodec, keys[stakingtypes.StoreKey], app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName), + ) + app.MintKeeper = mintkeeper.NewKeeper( + appCodec, keys[minttypes.StoreKey], app.GetSubspace(minttypes.ModuleName), &stakingKeeper, + app.AccountKeeper, app.BankKeeper, authtypes.FeeCollectorName, + ) + app.DistrKeeper = distrkeeper.NewKeeper( + appCodec, keys[distrtypes.StoreKey], app.GetSubspace(distrtypes.ModuleName), app.AccountKeeper, app.BankKeeper, + &stakingKeeper, authtypes.FeeCollectorName, app.ModuleAccountAddrs(), + ) + app.SlashingKeeper = slashingkeeper.NewKeeper( + appCodec, keys[slashingtypes.StoreKey], &stakingKeeper, app.GetSubspace(slashingtypes.ModuleName), + ) + app.CrisisKeeper = crisiskeeper.NewKeeper( + app.GetSubspace(crisistypes.ModuleName), invCheckPeriod, app.BankKeeper, authtypes.FeeCollectorName, + ) + + app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.AccountKeeper) + + /*UpgradeKeeper must be created before IBCKeeper. */ + app.UpgradeKeeper = upgradekeeper.NewKeeper( + skipUpgradeHeights, + keys[upgradetypes.StoreKey], + appCodec, + homePath, + app.BaseApp) + + // register the staking hooks + // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks + app.StakingKeeper = *stakingKeeper.SetHooks( + stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), + ) + + app.AuthzKeeper = authzkeeper.NewKeeper(keys[authzkeeper.StoreKey], appCodec, app.BaseApp.MsgServiceRouter()) + + // ---------------------------------- Nibiru Chain x/ keepers + + app.DexKeeper = dexkeeper.NewKeeper( + appCodec, keys[dextypes.StoreKey], app.GetSubspace(dextypes.ModuleName), + app.AccountKeeper, app.BankKeeper, app.DistrKeeper) + + app.PricefeedKeeper = pricefeedkeeper.NewKeeper( + appCodec, keys[pricefeedtypes.StoreKey], memKeys[pricefeedtypes.MemStoreKey], + app.GetSubspace(pricefeedtypes.ModuleName), + ) + + app.StablecoinKeeper = stablecoinkeeper.NewKeeper( + appCodec, keys[stablecointypes.StoreKey], memKeys[stablecointypes.MemStoreKey], + app.GetSubspace(stablecointypes.ModuleName), + app.AccountKeeper, app.BankKeeper, app.PricefeedKeeper, app.DexKeeper, + ) + + app.VpoolKeeper = vpoolkeeper.NewKeeper( + appCodec, + keys[vpooltypes.StoreKey], + app.PricefeedKeeper, + ) + + app.EpochsKeeper = epochskeeper.NewKeeper( + appCodec, keys[epochstypes.StoreKey], + ) + + app.PerpKeeper = perpkeeper.NewKeeper( + appCodec, keys[perptypes.StoreKey], + app.GetSubspace(perptypes.ModuleName), + app.AccountKeeper, app.BankKeeper, app.PricefeedKeeper, app.VpoolKeeper, app.EpochsKeeper, + ) + + app.EpochsKeeper.SetHooks( + epochstypes.NewMultiEpochHooks(app.StablecoinKeeper.Hooks(), app.PerpKeeper.Hooks()), + ) + + app.LockupKeeper = lockupkeeper.NewLockupKeeper(appCodec, + keys[lockuptypes.StoreKey], app.AccountKeeper, app.BankKeeper, + app.DistrKeeper) + + app.IncentivizationKeeper = incentivizationkeeper.NewKeeper(appCodec, + keys[incentivizationtypes.StoreKey], app.AccountKeeper, app.BankKeeper, app.DexKeeper, app.LockupKeeper, + ) + + // ---------------------------------- IBC keepers + + app.IBCKeeper = ibckeeper.NewKeeper( + appCodec, + keys[ibchost.StoreKey], + app.GetSubspace(ibchost.ModuleName), + app.StakingKeeper, + app.UpgradeKeeper, + app.ScopedIBCKeeper, + ) + + // register the proposal types + + govRouter := govtypes.NewRouter() + govRouter. + AddRoute(govtypes.RouterKey, govtypes.ProposalHandler). + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). + AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)). + AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)). + AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper)). + AddRoute(pricefeedtypes.RouterKey, pricefeed.NewPricefeedProposalHandler(app.PricefeedKeeper)). + AddRoute(vpooltypes.RouterKey, vpool.NewCreatePoolProposalHandler(app.VpoolKeeper)) + + app.TransferKeeper = ibctransferkeeper.NewKeeper( + appCodec, + keys[ibctransfertypes.StoreKey], + /* paramSubspace */ app.GetSubspace(ibctransfertypes.ModuleName), + /* ibctransfertypes.ICS4Wrapper */ app.IBCKeeper.ChannelKeeper, + /* ibctransfertypes.ChannelKeeper */ app.IBCKeeper.ChannelKeeper, + /* ibctransfertypes.PortKeeper */ &app.IBCKeeper.PortKeeper, + app.AccountKeeper, + app.BankKeeper, + app.ScopedTransferKeeper, + ) + transferModule := ibctransfer.NewAppModule(app.TransferKeeper) + transferIBCModule := ibctransfer.NewIBCModule(app.TransferKeeper) + + // Create evidence keeper. + // This keeper automatically includes an evidence router. + app.EvidenceKeeper = *evidencekeeper.NewKeeper( + appCodec, keys[evidencetypes.StoreKey], &app.StakingKeeper, + app.SlashingKeeper, + ) + + /* Create IBC module and a static IBC router */ + ibcRouter := porttypes.NewRouter() + /* Add an ibc-transfer module route, then set it and seal it. */ + ibcRouter.AddRoute( + /* module */ ibctransfertypes.ModuleName, + /* ibcModule */ transferIBCModule) + /* SetRouter finalizes all routes by sealing the router. + No more routes can be added. */ + app.IBCKeeper.SetRouter(ibcRouter) + + app.GovKeeper = govkeeper.NewKeeper( + appCodec, keys[govtypes.StoreKey], app.GetSubspace(govtypes.ModuleName), + app.AccountKeeper, app.BankKeeper, &app.StakingKeeper, govRouter, + ) + + // -------------------------- Module Options -------------------------- + + /**** Module Options ****/ + + // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment + // we prefer to be more strict in what arguments the modules expect. + var skipGenesisInvariants = cast.ToBool( + appOpts.Get(crisis.FlagSkipGenesisInvariants)) + + dexModule := dex.NewAppModule( + appCodec, app.DexKeeper, app.AccountKeeper, app.BankKeeper) + pricefeedModule := pricefeed.NewAppModule( + appCodec, app.PricefeedKeeper, app.AccountKeeper, app.BankKeeper) + epochsModule := epochs.NewAppModule(appCodec, app.EpochsKeeper) + stablecoinModule := stablecoin.NewAppModule( + appCodec, app.StablecoinKeeper, app.AccountKeeper, app.BankKeeper, + app.PricefeedKeeper, + ) + lockupModule := lockup.NewAppModule(appCodec, app.LockupKeeper, app.AccountKeeper, app.BankKeeper) + perpModule := perp.NewAppModule( + appCodec, app.PerpKeeper, app.AccountKeeper, app.BankKeeper, + app.PricefeedKeeper, + ) + vpoolModule := vpool.NewAppModule( + appCodec, app.VpoolKeeper, app.PricefeedKeeper, + ) + incentivizationModule := incentivization.NewAppModule(appCodec, app.IncentivizationKeeper, app.AccountKeeper) + + // NOTE: Any module instantiated in the module manager that is later modified + // must be passed by reference here. + app.mm = module.NewManager( + genutil.NewAppModule( + app.AccountKeeper, app.StakingKeeper, app.BaseApp.DeliverTx, + encodingConfig.TxConfig, + ), + auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), + vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), + bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), + capability.NewAppModule(appCodec, *app.CapabilityKeeper), + crisis.NewAppModule(&app.CrisisKeeper, skipGenesisInvariants), + feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), + gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), + mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), + distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), + staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), + upgrade.NewAppModule(app.UpgradeKeeper), + params.NewAppModule(app.ParamsKeeper), + authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), + // native x/ + dexModule, + pricefeedModule, + stablecoinModule, + lockupModule, + epochsModule, + vpoolModule, + perpModule, + incentivizationModule, + // ibc + evidence.NewAppModule(app.EvidenceKeeper), + ibc.NewAppModule(app.IBCKeeper), + transferModule, + ) + + // During begin block slashing happens after distr.BeginBlocker so that + // there is nothing left over in the validator fee pool, so as to keep the + // CanWithdrawInvariant invariant. + // NOTE: staking module is required if HistoricalEntries param > 0 + // NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC) + app.mm.SetOrderBeginBlockers( + upgradetypes.ModuleName, + capabilitytypes.ModuleName, + minttypes.ModuleName, + distrtypes.ModuleName, + slashingtypes.ModuleName, + evidencetypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + govtypes.ModuleName, + crisistypes.ModuleName, + genutiltypes.ModuleName, + authz.ModuleName, + feegrant.ModuleName, + paramstypes.ModuleName, + vestingtypes.ModuleName, + stakingtypes.ModuleName, + // native x/ + dextypes.ModuleName, + pricefeedtypes.ModuleName, + epochstypes.ModuleName, + stablecointypes.ModuleName, + vpooltypes.ModuleName, + perptypes.ModuleName, + lockuptypes.ModuleName, + incentivizationtypes.ModuleName, + // ibc modules + ibchost.ModuleName, + ibctransfertypes.ModuleName, + ) + app.mm.SetOrderEndBlockers( + crisistypes.ModuleName, + govtypes.ModuleName, + stakingtypes.ModuleName, + capabilitytypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + distrtypes.ModuleName, + slashingtypes.ModuleName, + minttypes.ModuleName, + genutiltypes.ModuleName, + evidencetypes.ModuleName, + authz.ModuleName, + feegrant.ModuleName, + paramstypes.ModuleName, + upgradetypes.ModuleName, + vestingtypes.ModuleName, + // native x/ + dextypes.ModuleName, + epochstypes.ModuleName, + pricefeedtypes.ModuleName, + stablecointypes.ModuleName, + vpooltypes.ModuleName, + perptypes.ModuleName, + lockuptypes.ModuleName, + incentivizationtypes.ModuleName, + // ibc + ibchost.ModuleName, + ibctransfertypes.ModuleName, + ) + + // NOTE: The genutils module must occur after staking so that pools are + // properly initialized with tokens from genesis accounts. + // NOTE: Capability module must occur first so that it can initialize any capabilities + // so that other modules that want to create or claim capabilities afterwards in InitChain + // can do so safely. + app.mm.SetOrderInitGenesis( + capabilitytypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + distrtypes.ModuleName, + stakingtypes.ModuleName, + slashingtypes.ModuleName, + govtypes.ModuleName, + minttypes.ModuleName, + crisistypes.ModuleName, + genutiltypes.ModuleName, + evidencetypes.ModuleName, + authz.ModuleName, + feegrant.ModuleName, + paramstypes.ModuleName, + upgradetypes.ModuleName, + vestingtypes.ModuleName, + // native x/ + dextypes.ModuleName, + pricefeedtypes.ModuleName, + epochstypes.ModuleName, + stablecointypes.ModuleName, + vpooltypes.ModuleName, + perptypes.ModuleName, + lockuptypes.ModuleName, + incentivizationtypes.ModuleName, + // ibc + ibchost.ModuleName, + ibctransfertypes.ModuleName, + ) + + // Uncomment if you want to set a custom migration order here. + // nibiapp.mm.SetOrderMigrations(custom order) + + app.mm.RegisterInvariants(&app.CrisisKeeper) + app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino) + app.configurator = module.NewConfigurator( + app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) + app.mm.RegisterServices(app.configurator) + + app.UpgradeKeeper.SetUpgradeHandler("v0.10.0", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + // no-op + return fromVM, nil + }) + + // add test gRPC service for testing gRPC queries in isolation + testdata.RegisterQueryServer(app.GRPCQueryRouter(), testdata.QueryImpl{}) + + // create the simulation manager and define the order of the modules for deterministic simulations + // + // NOTE: this is not required apps that don't use the simulator for fuzz testing + // transactions + app.sm = module.NewSimulationManager( + auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), + bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), + feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), + gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), + mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), + staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), + distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), + params.NewAppModule(app.ParamsKeeper), + authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), + // native x/ + dexModule, + pricefeedModule, + epochsModule, + stablecoinModule, + lockupModule, + incentivizationModule, + // ibc + capability.NewAppModule(appCodec, *app.CapabilityKeeper), + evidence.NewAppModule(app.EvidenceKeeper), + ibc.NewAppModule(app.IBCKeeper), + transferModule, + ) + + app.sm.RegisterStoreDecoders() + + // initialize stores + app.MountKVStores(keys) + app.MountTransientStores(tkeys) + app.MountMemoryStores(memKeys) + + // initialize BaseApp + app.SetInitChainer(app.InitChainer) + app.SetBeginBlocker(app.BeginBlocker) + anteHandler, err := nibiapp.NewAnteHandler(nibiapp.AnteHandlerOptions{ + HandlerOptions: ante.HandlerOptions{ + AccountKeeper: app.AccountKeeper, + BankKeeper: app.BankKeeper, + FeegrantKeeper: app.FeeGrantKeeper, + SignModeHandler: encodingConfig.TxConfig.SignModeHandler(), + SigGasConsumer: ante.DefaultSigVerificationGasConsumer, + }, + PricefeedKeeper: app.PricefeedKeeper, + IBCKeeper: app.IBCKeeper, + }) + + if err != nil { + panic(fmt.Errorf("failed to create sdk.AnteHandler: %s", err)) + } + + app.SetAnteHandler(anteHandler) + app.SetEndBlocker(app.EndBlocker) + + if loadLatest { + if err := app.LoadLatestVersion(); err != nil { + tmos.Exit(err.Error()) + } + + /* Applications that wish to enforce statically created ScopedKeepers should + call `Seal` after creating their scoped modules in `NewApp` with + `CapabilityKeeper.ScopeToModule`. + + + Calling 'nibiapp.CapabilityKeeper.Seal()' initializes and seals the capability + keeper such that all persistent capabilities are loaded in-memory and prevent + any further modules from creating scoped sub-keepers. + + NOTE: This must be done during creation of baseapp rather than in InitChain so + that in-memory capabilities get regenerated on nibiapp restart. + Note that since this reads from the store, we can only perform the seal + when `loadLatest` is set to true. + */ + app.CapabilityKeeper.Seal() + } + + return app +} + +// Name returns the name of the App +func (app *NibiruTestApp) Name() string { return app.BaseApp.Name() } + +// BeginBlocker application updates every begin block +func (app *NibiruTestApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + return app.mm.BeginBlock(ctx, req) +} + +// EndBlocker application updates every end block +func (app *NibiruTestApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + return app.mm.EndBlock(ctx, req) +} + +// InitChainer application update at chain initialization +func (app *NibiruTestApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { + var genesisState nibiapp.GenesisState + if err := json.Unmarshal(req.AppStateBytes, &genesisState); err != nil { + panic(err) + } + app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()) + return app.mm.InitGenesis(ctx, app.appCodec, genesisState) +} + +// LoadHeight loads a particular height +func (app *NibiruTestApp) LoadHeight(height int64) error { + return app.LoadVersion(height) +} + +// ModuleAccountAddrs returns all the nibiapp's module account addresses. +func (app *NibiruTestApp) ModuleAccountAddrs() map[string]bool { + modAccAddrs := make(map[string]bool) + for acc := range maccPerms { + modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true + } + + return modAccAddrs +} + +// LegacyAmino returns SimApp's amino codec. +// +// NOTE: This is solely to be used for testing purposes as it may be desirable +// for modules to register their own custom testing types. +func (app *NibiruTestApp) LegacyAmino() *codec.LegacyAmino { + return app.legacyAmino +} + +// AppCodec returns SimApp's nibiapp codec. +// +// NOTE: This is solely to be used for testing purposes as it may be desirable +// for modules to register their own custom testing types. +func (app *NibiruTestApp) AppCodec() codec.Codec { + return app.appCodec +} + +// InterfaceRegistry returns App's InterfaceRegistry +func (app *NibiruTestApp) InterfaceRegistry() codectypes.InterfaceRegistry { + return app.interfaceRegistry +} + +// GetKey returns the KVStoreKey for the provided store key. +// +// NOTE: This is solely to be used for testing purposes. +func (app *NibiruTestApp) GetKey(storeKey string) *storetypes.KVStoreKey { + return app.keys[storeKey] +} + +// GetTKey returns the TransientStoreKey for the provided store key. +// +// NOTE: This is solely to be used for testing purposes. +func (app *NibiruTestApp) GetTKey(storeKey string) *storetypes.TransientStoreKey { + return app.tkeys[storeKey] +} + +// GetMemKey returns the MemStoreKey for the provided mem key. +// +// NOTE: This is solely used for testing purposes. +func (app *NibiruTestApp) GetMemKey(storeKey string) *storetypes.MemoryStoreKey { + return app.memKeys[storeKey] +} + +// GetSubspace returns a param subspace for a given module name. +// +// NOTE: This is solely to be used for testing purposes. +func (app *NibiruTestApp) GetSubspace(moduleName string) paramstypes.Subspace { + subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) + return subspace +} + +// SimulationManager implements the SimulationApp interface +func (app *NibiruTestApp) SimulationManager() *module.SimulationManager { + return app.sm +} + +// RegisterAPIRoutes registers all application module routes with the provided +// API server. +func (app *NibiruTestApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { + clientCtx := apiSvr.ClientCtx + rpc.RegisterRoutes(clientCtx, apiSvr.Router) + // Register legacy tx routes. + authrest.RegisterTxRoutes(clientCtx, apiSvr.Router) + // Register new tx routes from grpc-gateway. + authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + // Register new tendermint queries routes from grpc-gateway. + tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + + // Register legacy and grpc-gateway routes for all modules. + ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router) + ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + + // register swagger API from root so that other applications can override easily + if apiConfig.Swagger { + RegisterSwaggerAPI(clientCtx, apiSvr.Router) + } +} + +// RegisterTxService implements the Application.RegisterTxService method. +func (app *NibiruTestApp) RegisterTxService(clientCtx client.Context) { + authtx.RegisterTxService( + app.BaseApp.GRPCQueryRouter(), clientCtx, + app.BaseApp.Simulate, app.interfaceRegistry) +} + +// RegisterTendermintService implements the Application.RegisterTendermintService method. +func (app *NibiruTestApp) RegisterTendermintService(clientCtx client.Context) { + tmservice.RegisterTendermintService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.interfaceRegistry) +} + +// ------------------------------------------------------------------------ +// Functions for ibc-go TestingApp +// ------------------------------------------------------------------------ + +/* GetBaseApp, GetStakingKeeper, GetIBCKeeper, and GetScopedIBCKeeper are part + of the implementation of the TestingApp interface +*/ + +func (app *NibiruTestApp) GetBaseApp() *baseapp.BaseApp { + return app.BaseApp +} + +func (app *NibiruTestApp) GetStakingKeeper() stakingkeeper.Keeper { + return app.StakingKeeper +} + +func (app *NibiruTestApp) GetIBCKeeper() *ibckeeper.Keeper { + return app.IBCKeeper +} + +func (app *NibiruTestApp) GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper { + return app.ScopedIBCKeeper +} + +/* EncodingConfig specifies the concrete encoding types to use for a given nibiapp. + This is provided for compatibility between protobuf and amino implementations. */ + +func (app *NibiruTestApp) GetTxConfig() client.TxConfig { + return nibiapp.MakeTestEncodingConfig().TxConfig +} + +// ------------------------------------------------------------------------ +// Else +// ------------------------------------------------------------------------ + +// RegisterSwaggerAPI registers swagger route with API Server +func RegisterSwaggerAPI(ctx client.Context, rtr *mux.Router) { + statikFS, err := fs.New() + if err != nil { + panic(err) + } + + staticServer := http.FileServer(statikFS) + rtr.PathPrefix("/swagger/").Handler(http.StripPrefix("/swagger/", staticServer)) +} + +// GetMaccPerms returns a copy of the module account permissions +func GetMaccPerms() map[string][]string { + dupMaccPerms := make(map[string][]string) + for k, v := range maccPerms { + dupMaccPerms[k] = v + } + return dupMaccPerms +} + +// initParamsKeeper init params vpoolkeeper and its subspaces +func initParamsKeeper( + appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, + tkey storetypes.StoreKey) paramskeeper.Keeper { + paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) + + paramsKeeper.Subspace(authtypes.ModuleName) + paramsKeeper.Subspace(banktypes.ModuleName) + paramsKeeper.Subspace(stakingtypes.ModuleName) + paramsKeeper.Subspace(minttypes.ModuleName) + paramsKeeper.Subspace(distrtypes.ModuleName) + paramsKeeper.Subspace(slashingtypes.ModuleName) + paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()) + paramsKeeper.Subspace(crisistypes.ModuleName) + // Native module params keepers + paramsKeeper.Subspace(dextypes.ModuleName) + paramsKeeper.Subspace(pricefeedtypes.ModuleName) + paramsKeeper.Subspace(epochstypes.ModuleName) + paramsKeeper.Subspace(stablecointypes.ModuleName) + // ibc params keepers + paramsKeeper.Subspace(ibctransfertypes.ModuleName) + paramsKeeper.Subspace(ibchost.ModuleName) + paramsKeeper.Subspace(perptypes.ModuleName) + + return paramsKeeper +} diff --git a/simapp/encoding.go b/simapp/encoding.go new file mode 100644 index 000000000..21754ca00 --- /dev/null +++ b/simapp/encoding.go @@ -0,0 +1,19 @@ +package simapp + +import ( + "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/std" +) + +// MakeTestEncodingConfig creates an EncodingConfig for testing. This function +// should be used only in tests or when creating a new app instance (NewApp*()). +// App user shouldn't create new codecs - use the app.AppCodec instead. +// [DEPRECATED] +func MakeTestEncodingConfig() params.EncodingConfig { + encodingConfig := params.MakeTestEncodingConfig() + std.RegisterLegacyAminoCodec(encodingConfig.Amino) + std.RegisterInterfaces(encodingConfig.InterfaceRegistry) + ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino) + ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry) + return encodingConfig +} diff --git a/simapp/export.go b/simapp/export.go new file mode 100644 index 000000000..250bdfac9 --- /dev/null +++ b/simapp/export.go @@ -0,0 +1,194 @@ +package simapp + +import ( + "encoding/json" + "log" + + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + + servertypes "github.com/cosmos/cosmos-sdk/server/types" + sdk "github.com/cosmos/cosmos-sdk/types" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +// ExportAppStateAndValidators exports the state of the application for a genesis +// file. +func (app *NibiruTestApp) ExportAppStateAndValidators( + forZeroHeight bool, jailAllowedAddrs []string, +) (servertypes.ExportedApp, error) { + // as if they could withdraw from the start of the next block + ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) + + // We export at last height + 1, because that's the height at which + // Tendermint will start InitChain. + height := app.LastBlockHeight() + 1 + if forZeroHeight { + height = 0 + app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs) + } + + genState := app.mm.ExportGenesis(ctx, app.appCodec) + appState, err := json.MarshalIndent(genState, "", " ") + if err != nil { + return servertypes.ExportedApp{}, err + } + + validators, err := staking.WriteValidators(ctx, app.StakingKeeper) + return servertypes.ExportedApp{ + AppState: appState, + Validators: validators, + Height: height, + ConsensusParams: app.BaseApp.GetConsensusParams(ctx), + }, err +} + +// prepare for fresh start at zero height +// NOTE zero height genesis is a temporary feature which will be deprecated +// +// in favor of export at a block height +func (app *NibiruTestApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { + applyAllowedAddrs := false + + // check if there is a allowed address list + if len(jailAllowedAddrs) > 0 { + applyAllowedAddrs = true + } + + allowedAddrsMap := make(map[string]bool) + + for _, addr := range jailAllowedAddrs { + _, err := sdk.ValAddressFromBech32(addr) + if err != nil { + log.Fatal(err) + } + allowedAddrsMap[addr] = true + } + + /* Just to be safe, assert the invariants on current state. */ + app.CrisisKeeper.AssertInvariants(ctx) + + /* Handle fee distribution state. */ + + // withdraw all validator commission + app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + return false + }) + + // withdraw all delegator rewards + dels := app.StakingKeeper.GetAllDelegations(ctx) + for _, delegation := range dels { + valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) + if err != nil { + panic(err) + } + + delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + panic(err) + } + _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) + } + + // clear validator slash events + app.DistrKeeper.DeleteAllValidatorSlashEvents(ctx) + + // clear validator historical rewards + app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx) + + // set context height to zero + height := ctx.BlockHeight() + ctx = ctx.WithBlockHeight(0) + + // reinitialize all validators + app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + // donate any unwithdrawn outstanding reward fraction tokens to the community pool + scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) + feePool := app.DistrKeeper.GetFeePool(ctx) + feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) + app.DistrKeeper.SetFeePool(ctx, feePool) + + app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + return false + }) + + // reinitialize all delegations + for _, del := range dels { + valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) + if err != nil { + panic(err) + } + delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) + if err != nil { + panic(err) + } + app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) + app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) + } + + // reset context height + ctx = ctx.WithBlockHeight(height) + + /* Handle staking state. */ + + // iterate through redelegations, reset creation height + app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { + for i := range red.Entries { + red.Entries[i].CreationHeight = 0 + } + app.StakingKeeper.SetRedelegation(ctx, red) + return false + }) + + // iterate through unbonding delegations, reset creation height + app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { + for i := range ubd.Entries { + ubd.Entries[i].CreationHeight = 0 + } + app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) + return false + }) + + // Iterate through validators by power descending, reset bond heights, and + // update bond intra-tx counters. + store := ctx.KVStore(app.keys[stakingtypes.StoreKey]) + iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) + counter := int16(0) + + for ; iter.Valid(); iter.Next() { + addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) + validator, found := app.StakingKeeper.GetValidator(ctx, addr) + if !found { + panic("expected validator, not found") + } + + validator.UnbondingHeight = 0 + if applyAllowedAddrs && !allowedAddrsMap[addr.String()] { + validator.Jailed = true + } + + app.StakingKeeper.SetValidator(ctx, validator) + counter++ + } + + iter.Close() + + _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + if err != nil { + log.Fatal(err) + } + + /* Handle slashing state. */ + + // reset start height on signing infos + app.SlashingKeeper.IterateValidatorSigningInfos( + ctx, + func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { + info.StartHeight = 0 + app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info) + return false + }, + ) +} diff --git a/simapp/genesis.go b/simapp/genesis.go index 938cdab3f..30f9adce9 100644 --- a/simapp/genesis.go +++ b/simapp/genesis.go @@ -66,3 +66,17 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONCodec, genesisFile str return genesis, newAccs } + +// GenesisState of the blockchain is represented here as a map of raw json +// messages key'd by a identifier string. +// The identifier is used to determine which module genesis information belongs +// to so it may be appropriately routed during init chain. +// Within this application default genesis information is retrieved from +// the ModuleBasicManager which populates json from each BasicModule +// object provided to it during init. +type GenesisState map[string]json.RawMessage + +// NewDefaultGenesisState generates the default state for the application. +func NewDefaultGenesisState(cdc codec.JSONCodec) GenesisState { + return ModuleBasics.DefaultGenesis(cdc) +} diff --git a/simapp/sim_test.go b/simapp/sim_test.go index a275fa1ef..06bf7e140 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -14,8 +14,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/stretchr/testify/require" dbm "github.com/tendermint/tm-db" - - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func init() { @@ -37,7 +35,7 @@ func TestFullAppSimulation(tb *testing.T) { } }() - nibiru := testapp.NewNibiruApp( /*shouldUseDefaultGenesis*/ true) + nibiru := NewTestNibiruApp( /*shouldUseDefaultGenesis*/ true) // Run randomized simulation: _, simParams, simErr := simulation.SimulateFromSeed( @@ -87,7 +85,7 @@ func TestAppStateDeterminism(t *testing.T) { for j := 0; j < numTimesToRunPerSeed; j++ { db := dbm.NewMemDB() - app := testapp.NewNibiruApp( /*shouldUseDefaultGenesis*/ true) + app := NewTestNibiruApp( /*shouldUseDefaultGenesis*/ true) fmt.Printf( "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", diff --git a/x/testutil/testapp/testapp.go b/simapp/testapp.go similarity index 75% rename from x/testutil/testapp/testapp.go rename to simapp/testapp.go index 9a192554b..ebdb56d75 100644 --- a/x/testutil/testapp/testapp.go +++ b/simapp/testapp.go @@ -1,53 +1,49 @@ -package testapp +package simapp import ( "encoding/json" "os" "path/filepath" - "time" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmdb "github.com/tendermint/tm-db" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" "github.com/NibiruChain/nibiru/x/common" pricefeedtypes "github.com/NibiruChain/nibiru/x/pricefeed/types" - - "github.com/cosmos/cosmos-sdk/codec" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) -// NewTestApp creates an application instance ('app.NibiruApp') with an in-memory +// NewTestNibiruApp creates an application instance ('app.NibiruApp') with an in-memory // database ('tmdb.MemDB') and disabled logging. It either uses the application's // default genesis state or a blank one. -func NewNibiruApp(shouldUseDefaultGenesis bool) *app.NibiruApp { - encoding := app.MakeTestEncodingConfig() - var appGenesis app.GenesisState +func NewTestNibiruApp(shouldUseDefaultGenesis bool) *NibiruTestApp { + encoding := simapp.MakeTestEncodingConfig() + var appGenesis GenesisState if shouldUseDefaultGenesis { - appGenesis = app.NewDefaultGenesisState(encoding.Marshaler) + appGenesis = NewDefaultGenesisState(encoding.Marshaler) } - return NewNibiruAppWithGenesis(appGenesis) + return NewTestNibiruAppWithGenesis(appGenesis) } -// NewNibiruApp creates an 'app.NibiruApp' instance with an in-memory +// NewTestNibiruAppAndContext creates an 'app.NibiruApp' instance with an in-memory // 'tmdb.MemDB' and fresh 'sdk.Context'. -func NewNibiruAppAndContext(shouldUseDefaultGenesis bool) (*app.NibiruApp, sdk.Context) { - newNibiruApp := NewNibiruApp(shouldUseDefaultGenesis) +func NewTestNibiruAppAndContext(shouldUseDefaultGenesis bool) (*NibiruTestApp, sdk.Context) { + newNibiruApp := NewTestNibiruApp(shouldUseDefaultGenesis) ctx := newNibiruApp.NewContext(false, tmproto.Header{}) return newNibiruApp, ctx } -// NewTestAppWithGenesis initializes a chain with the given genesis state to +// NewTestNibiruAppWithGenesis initializes a chain with the given genesis state to // creates an application instance ('app.NibiruApp'). This app uses an // in-memory database ('tmdb.MemDB') and has logging disabled. -func NewNibiruAppWithGenesis(gen app.GenesisState) *app.NibiruApp { +func NewTestNibiruAppWithGenesis(gen GenesisState) *NibiruTestApp { userHomeDir, err := os.UserHomeDir() if err != nil { panic(err) @@ -57,9 +53,9 @@ func NewNibiruAppWithGenesis(gen app.GenesisState) *app.NibiruApp { db := tmdb.NewMemDB() logger := log.NewNopLogger() - encoding := app.MakeTestEncodingConfig() + encoding := MakeTestEncodingConfig() - nibiruApp := app.NewNibiruApp( + nibiruApp := NewNibiruTestApp( logger, db, /*traceStore=*/ nil, @@ -89,8 +85,7 @@ func NewNibiruAppWithGenesis(gen app.GenesisState) *app.NibiruApp { // ---------------------------------------------------------------------------- const ( - GenOracleAddress = "nibi1zuxt7fvuxgj69mjxu3auca96zemqef5u2yemly" - GenOracleMnemonic = "kit soon capital dry sadness balance rival embark behind coast online struggle deer crush hospital during man monkey prison action custom wink utility arrive" + GenOracleAddress = "nibi1zuxt7fvuxgj69mjxu3auca96zemqef5u2yemly" ) /* @@ -99,10 +94,10 @@ const ( genesis as input. The blockchain genesis state is represented as a map from module identifier strings to raw json messages. */ -func NewTestGenesisStateFromDefault() app.GenesisState { - encodingConfig := app.MakeTestEncodingConfig() +func NewTestGenesisStateFromDefault() GenesisState { + encodingConfig := MakeTestEncodingConfig() codec := encodingConfig.Marshaler - genState := app.NewDefaultGenesisState(codec) + genState := NewDefaultGenesisState(codec) return NewTestGenesisState(codec, genState) } @@ -116,8 +111,8 @@ Args: - codec: Serializer for the module genesis state proto.Messages - inGenState: Input genesis state before the custom test setup is applied */ -func NewTestGenesisState(codec codec.Codec, inGenState app.GenesisState, -) (testGenState app.GenesisState) { +func NewTestGenesisState(codec codec.Codec, inGenState GenesisState, +) (testGenState GenesisState) { testGenState = inGenState // Set short voting period to allow fast gov proposals in tests diff --git a/x/testutil/testapp/testapp_test.go b/simapp/testapp_test.go similarity index 90% rename from x/testutil/testapp/testapp_test.go rename to simapp/testapp_test.go index 655368a3f..74790ff81 100644 --- a/x/testutil/testapp/testapp_test.go +++ b/simapp/testapp_test.go @@ -1,9 +1,11 @@ -package testapp_test +package simapp_test import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -11,7 +13,6 @@ import ( "github.com/NibiruChain/nibiru/app" "github.com/NibiruChain/nibiru/x/common" pricefeedtypes "github.com/NibiruChain/nibiru/x/pricefeed/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) type TestappSuite struct { @@ -24,14 +25,14 @@ type TestappSuite struct { func (s *TestappSuite) SetupSuite() { app.SetPrefixes(app.AccountAddressPrefix) - s.genOracle = sdk.MustAccAddressFromBech32(testapp.GenOracleAddress) + s.genOracle = sdk.MustAccAddressFromBech32(simapp.GenOracleAddress) s.pairs = pricefeedtypes.DefaultPairs s.twapLookbackWindow = pricefeedtypes.DefaultLookbackWindow } // TestPricefeedGenesis verifies that the expected pricefeed state for integration tests func (s *TestappSuite) TestPricefeedGenesis() { - genPf := testapp.PricefeedGenesis() + genPf := simapp.PricefeedGenesis() s.Assert().EqualValues(pricefeedtypes.NewParams(s.pairs, s.twapLookbackWindow), genPf.Params) s.Assert().EqualValues(pricefeedtypes.NewParams(s.pairs, s.twapLookbackWindow), genPf.Params) s.Assert().EqualValues(s.pairs[0].String(), genPf.PostedPrices[0].PairID) @@ -47,7 +48,7 @@ func (s *TestappSuite) TestNewTestGenesisState() { codec := encodingConfig.Marshaler defaultGenState := app.NewDefaultGenesisState(codec) - testGenState := testapp.NewTestGenesisStateFromDefault() + testGenState := simapp.NewTestGenesisStateFromDefault() var testGenPfState pricefeedtypes.GenesisState testGenPfStateJSON := testGenState[pricefeedtypes.ModuleName] @@ -74,13 +75,13 @@ func (s *TestappSuite) TestNewTestGenesisState() { func (s *TestappSuite) TestPricefeedGenesis_PostedPrices() { s.T().Log("no prices posted for default genesis") - nibiruApp := testapp.NewNibiruApp(true) + nibiruApp := simapp.NewTestNibiruApp(true) ctx := nibiruApp.NewContext(false, tmproto.Header{}) currentPrices := nibiruApp.PricefeedKeeper.GetCurrentPrices(ctx) s.Assert().Len(currentPrices, 0) s.T().Log("prices posted for testing genesis") - nibiruApp = testapp.NewNibiruAppWithGenesis(testapp.NewTestGenesisStateFromDefault()) + nibiruApp = simapp.NewTestNibiruAppWithGenesis(simapp.NewTestGenesisStateFromDefault()) ctx = nibiruApp.NewContext(false, tmproto.Header{}) oracles := []sdk.AccAddress{s.genOracle} oracleMap := nibiruApp.PricefeedKeeper.GetOraclesForPairs(ctx, s.pairs) diff --git a/x/dex/client/testutil/cli_test.go b/x/dex/client/testutil/cli_test.go index 2411ea5ad..d911726b5 100644 --- a/x/dex/client/testutil/cli_test.go +++ b/x/dex/client/testutil/cli_test.go @@ -4,6 +4,8 @@ import ( "fmt" "testing" + "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -20,7 +22,6 @@ import ( "github.com/NibiruChain/nibiru/x/dex/client/cli" "github.com/NibiruChain/nibiru/x/dex/types" testutilcli "github.com/NibiruChain/nibiru/x/testutil/cli" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) type IntegrationTestSuite struct { @@ -45,7 +46,7 @@ func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") app.SetPrefixes(app.AccountAddressPrefix) - genesisState := testapp.NewTestGenesisStateFromDefault() + genesisState := simapp.NewTestGenesisStateFromDefault() s.cfg = testutilcli.BuildNetworkConfig(genesisState) s.cfg.StartingTokens = sdk.NewCoins( sdk.NewInt64Coin(common.DenomStable, 20000), diff --git a/x/dex/genesis_test.go b/x/dex/genesis_test.go index f78145bfc..7fcdc7c53 100644 --- a/x/dex/genesis_test.go +++ b/x/dex/genesis_test.go @@ -3,12 +3,13 @@ package dex_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + "github.com/stretchr/testify/require" "github.com/NibiruChain/nibiru/x/dex" "github.com/NibiruChain/nibiru/x/dex/types" "github.com/NibiruChain/nibiru/x/testutil/nullify" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestGenesis(t *testing.T) { @@ -16,7 +17,7 @@ func TestGenesis(t *testing.T) { Params: types.DefaultParams(), } - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) dex.InitGenesis(ctx, app.DexKeeper, genesisState) got := dex.ExportGenesis(ctx, app.DexKeeper) require.NotNil(t, got) diff --git a/x/dex/keeper/balances_test.go b/x/dex/keeper/balances_test.go index 45bcf0199..a671757ca 100644 --- a/x/dex/keeper/balances_test.go +++ b/x/dex/keeper/balances_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "testing" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -10,7 +12,6 @@ import ( "github.com/NibiruChain/nibiru/x/common" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestCheckBalances(t *testing.T) { @@ -52,7 +53,7 @@ func TestCheckBalances(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) // fund user account sender := sample.AccAddress() diff --git a/x/dex/keeper/grpc_query_test.go b/x/dex/keeper/grpc_query_test.go index 25ac93e91..9bbf9c3a8 100644 --- a/x/dex/keeper/grpc_query_test.go +++ b/x/dex/keeper/grpc_query_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "testing" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" @@ -13,11 +15,10 @@ import ( "github.com/NibiruChain/nibiru/x/dex/types" "github.com/NibiruChain/nibiru/x/testutil/mock" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestParamsQuery(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) params := types.DefaultParams() app.DexKeeper.SetParams(ctx, params) @@ -62,7 +63,7 @@ func TestQueryPoolHappyPath(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetPool(ctx, tc.existingPool) queryServer := keeper.NewQuerier(app.DexKeeper) @@ -88,7 +89,7 @@ func TestQueryPoolFail(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) queryServer := keeper.NewQuerier(app.DexKeeper) resp, err := queryServer.Pool(sdk.WrapSDKContext(ctx), nil) require.Error(t, err) @@ -205,7 +206,7 @@ func TestQueryPools(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) for _, existingPool := range tc.existingPools { app.DexKeeper.SetPool(ctx, existingPool) } @@ -284,7 +285,7 @@ func TestQueryNumPools(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) sender := sample.AccAddress() // need funds to create pools require.NoError(t, simapp.FundAccount( @@ -358,7 +359,7 @@ func TestQueryPoolParams(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetPool(ctx, tc.existingPool) queryServer := keeper.NewQuerier(app.DexKeeper) @@ -395,7 +396,7 @@ func TestQueryTotalShares(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetPool(ctx, tc.existingPool) @@ -468,7 +469,7 @@ func TestQuerySpotPrice(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetPool(ctx, tc.existingPool) @@ -530,7 +531,7 @@ func TestQueryEstimateSwapExactAmountIn(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetPool(ctx, tc.existingPool) queryServer := keeper.NewQuerier(app.DexKeeper) @@ -592,7 +593,7 @@ func TestQueryEstimateSwapExactAmountOut(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetPool(ctx, tc.existingPool) queryServer := keeper.NewQuerier(app.DexKeeper) @@ -660,7 +661,7 @@ func TestQueryEstimateJoinExactAmountIn(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetPool(ctx, tc.existingPool) queryServer := keeper.NewQuerier(app.DexKeeper) @@ -725,7 +726,7 @@ func TestQueryEstimateExitExactAmountIn(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetPool(ctx, tc.existingPool) queryServer := keeper.NewQuerier(app.DexKeeper) diff --git a/x/dex/keeper/keeper_test.go b/x/dex/keeper/keeper_test.go index f663065ea..f591d31d7 100644 --- a/x/dex/keeper/keeper_test.go +++ b/x/dex/keeper/keeper_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "testing" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" @@ -12,11 +14,10 @@ import ( "github.com/NibiruChain/nibiru/x/dex/types" "github.com/NibiruChain/nibiru/x/testutil/mock" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestGetAndSetNextPoolNumber(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) // Write to store app.DexKeeper.SetNextPoolNumber(ctx, 150) @@ -28,7 +29,7 @@ func TestGetAndSetNextPoolNumber(t *testing.T) { } func TestGetNextPoolNumberAndIncrement(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) // Write a pool number app.DexKeeper.SetNextPoolNumber(ctx, 200) @@ -43,7 +44,7 @@ func TestGetNextPoolNumberAndIncrement(t *testing.T) { } func TestSetAndFetchPool(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) pool := types.Pool{ Id: 150, @@ -150,7 +151,7 @@ func TestFetchPoolFromPair(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetPool(ctx, types.Pool{ Id: 1, @@ -208,7 +209,7 @@ func TestFetchPoolFromPair(t *testing.T) { } func TestNewPool(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) poolCreationFeeCoin := sdk.NewInt64Coin(common.DenomGov, 1000_000_000) app.DexKeeper.SetParams(ctx, types.NewParams( @@ -275,7 +276,7 @@ func TestNewPool(t *testing.T) { } func TestNewPoolNotEnoughFunds(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) app.DexKeeper.SetParams(ctx, types.NewParams( /*startingPoolNumber=*/ 1, @@ -315,7 +316,7 @@ func TestNewPoolNotEnoughFunds(t *testing.T) { } func TestNewPoolTooLittleAssets(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) userAddr, err := sdk.AccAddressFromBech32(sample.AccAddress().String()) require.NoError(t, err) @@ -335,7 +336,7 @@ func TestNewPoolTooLittleAssets(t *testing.T) { } func TestKeeperNewPoolNotWhitelistedAssets(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) userAddr, err := sdk.AccAddressFromBech32(sample.AccAddress().String()) require.NoError(t, err) @@ -359,7 +360,7 @@ func TestKeeperNewPoolNotWhitelistedAssets(t *testing.T) { } func TestNewPoolTooManyAssets(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) userAddr, err := sdk.AccAddressFromBech32(sample.AccAddress().String()) require.NoError(t, err) @@ -514,7 +515,7 @@ func TestJoinPool(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) poolAddr := sample.AccAddress() tc.initialPool.Address = poolAddr.String() @@ -626,7 +627,7 @@ func TestExitPool(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) poolAddr := sample.AccAddress() tc.initialPool.Address = poolAddr.String() diff --git a/x/dex/keeper/liquidity_test.go b/x/dex/keeper/liquidity_test.go index 52258202b..fc876ea22 100644 --- a/x/dex/keeper/liquidity_test.go +++ b/x/dex/keeper/liquidity_test.go @@ -3,14 +3,14 @@ package keeper_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestGetSetDenomLiquidity(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) // Write to store app.DexKeeper.SetDenomLiquidity(ctx, "nibi", sdk.NewInt(1000)) @@ -22,7 +22,7 @@ func TestGetSetDenomLiquidity(t *testing.T) { } func TestGetTotalLiquidity(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) // Write to store app.DexKeeper.SetDenomLiquidity(ctx, "atom", sdk.NewInt(123)) @@ -40,7 +40,7 @@ func TestGetTotalLiquidity(t *testing.T) { } func TestSetTotalLiquidity(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) // Write to store app.DexKeeper.SetTotalLiquidity(ctx, sdk.NewCoins( @@ -56,7 +56,7 @@ func TestSetTotalLiquidity(t *testing.T) { } func TestRecordTotalLiquidityIncrease(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) // Write to store app.DexKeeper.SetTotalLiquidity(ctx, sdk.NewCoins( @@ -73,7 +73,7 @@ func TestRecordTotalLiquidityIncrease(t *testing.T) { } func TestRecordTotalLiquidityDecrease(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) // Write to store app.DexKeeper.SetTotalLiquidity(ctx, sdk.NewCoins( diff --git a/x/dex/keeper/msg_server_test.go b/x/dex/keeper/msg_server_test.go index 1c638039a..e33d843b9 100644 --- a/x/dex/keeper/msg_server_test.go +++ b/x/dex/keeper/msg_server_test.go @@ -4,6 +4,8 @@ import ( "fmt" "testing" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -16,7 +18,6 @@ import ( "github.com/NibiruChain/nibiru/x/testutil/events" "github.com/NibiruChain/nibiru/x/testutil/mock" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestCreatePool(t *testing.T) { @@ -153,7 +154,7 @@ func TestCreatePool(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) msgServer := keeper.NewMsgServerImpl(app.DexKeeper) if tc.creatorAddr == nil { @@ -298,7 +299,7 @@ func TestMsgServerJoinPool(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) poolAddr := sample.AccAddress() tc.initialPool.Address = poolAddr.String() @@ -425,7 +426,7 @@ func TestMsgServerExitPool(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) poolAddr := sample.AccAddress() tc.initialPool.Address = poolAddr.String() @@ -627,7 +628,7 @@ func TestMsgServerSwapAssets(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) msgServer := keeper.NewMsgServerImpl(app.DexKeeper) // fund pool account diff --git a/x/dex/keeper/params_test.go b/x/dex/keeper/params_test.go index 42172fabb..e37eb30cb 100644 --- a/x/dex/keeper/params_test.go +++ b/x/dex/keeper/params_test.go @@ -3,14 +3,15 @@ package keeper_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + "github.com/stretchr/testify/require" "github.com/NibiruChain/nibiru/x/dex/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestGetParams(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) params := types.DefaultParams() app.DexKeeper.SetParams(ctx, params) diff --git a/x/dex/keeper/swap_test.go b/x/dex/keeper/swap_test.go index fff7cc40e..61e27f4ae 100644 --- a/x/dex/keeper/swap_test.go +++ b/x/dex/keeper/swap_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "testing" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -12,7 +14,6 @@ import ( "github.com/NibiruChain/nibiru/x/dex/types" "github.com/NibiruChain/nibiru/x/testutil/mock" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestSwapExactAmountIn(t *testing.T) { @@ -177,7 +178,7 @@ func TestSwapExactAmountIn(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) // fund pool account poolAddr := sample.AccAddress() diff --git a/x/epochs/abci_test.go b/x/epochs/abci_test.go index de803d14e..781fa9f5b 100644 --- a/x/epochs/abci_test.go +++ b/x/epochs/abci_test.go @@ -7,14 +7,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/NibiruChain/nibiru/app" + "github.com/NibiruChain/nibiru/simapp" "github.com/NibiruChain/nibiru/x/epochs" "github.com/NibiruChain/nibiru/x/epochs/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestEpochInfoChangesBeginBlockerAndInitGenesis(t *testing.T) { - var app *app.NibiruApp + var app *simapp.NibiruTestApp var ctx sdk.Context now := time.Now() @@ -97,7 +96,7 @@ func TestEpochInfoChangesBeginBlockerAndInitGenesis(t *testing.T) { } for _, test := range tests { - app, ctx = testapp.NewNibiruAppAndContext(true) + app, ctx = simapp.NewTestNibiruAppAndContext(true) // On init genesis, default epochs information is set // To check init genesis again, should make it fresh status @@ -138,7 +137,7 @@ func TestEpochInfoChangesBeginBlockerAndInitGenesis(t *testing.T) { } func TestEpochStartingOneMonthAfterInitGenesis(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) // On init genesis, default epochs information is set // To check init genesis again, should make it fresh status @@ -210,7 +209,7 @@ func TestLegacyEpochSerialization(t *testing.T) { } now := time.Now() - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) // On init genesis, default epochs information is set // To check init genesis again, should make it fresh status epochInfos := app.EpochsKeeper.AllEpochInfos(ctx) diff --git a/x/epochs/genesis_test.go b/x/epochs/genesis_test.go index 48a054533..f1a46c8f0 100644 --- a/x/epochs/genesis_test.go +++ b/x/epochs/genesis_test.go @@ -4,15 +4,16 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + "github.com/stretchr/testify/require" "github.com/NibiruChain/nibiru/x/epochs" "github.com/NibiruChain/nibiru/x/epochs/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestEpochsExportGenesis(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) chainStartTime := ctx.BlockTime() chainStartHeight := ctx.BlockHeight() @@ -54,7 +55,7 @@ func TestEpochsExportGenesis(t *testing.T) { } func TestEpochsInitGenesis(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) // On init genesis, default epochs information is set // To check init genesis again, should make it fresh status epochInfos := app.EpochsKeeper.AllEpochInfos(ctx) diff --git a/x/epochs/keeper/keeper_test.go b/x/epochs/keeper/keeper_test.go index 9a2e27e09..28eab34b5 100644 --- a/x/epochs/keeper/keeper_test.go +++ b/x/epochs/keeper/keeper_test.go @@ -4,26 +4,26 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/NibiruChain/nibiru/app" "github.com/NibiruChain/nibiru/x/epochs/keeper" "github.com/NibiruChain/nibiru/x/epochs/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) type KeeperTestSuite struct { suite.Suite - app *app.NibiruApp + app *simapp.NibiruTestApp ctx sdk.Context queryClient types.QueryClient } func (suite *KeeperTestSuite) SetupTest() { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) suite.app = nibiruApp suite.ctx = ctx diff --git a/x/incentivization/keeper/keeper_test.go b/x/incentivization/keeper/keeper_test.go index 0304a2887..7e22c945e 100644 --- a/x/incentivization/keeper/keeper_test.go +++ b/x/incentivization/keeper/keeper_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/NibiruChain/nibiru/x/incentivization/types" @@ -15,12 +17,11 @@ import ( "github.com/NibiruChain/nibiru/x/incentivization/keeper" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestKeeper_CreateIncentivizationProgram(t *testing.T) { t.Run("success", func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(false) + app, ctx := simapp2.NewTestNibiruAppAndContext(false) createdProgram, err := app.IncentivizationKeeper.CreateIncentivizationProgram(ctx, "denom", 48*time.Hour, ctx.BlockTime(), 1000) require.NoError(t, err) @@ -33,7 +34,7 @@ func TestKeeper_CreateIncentivizationProgram(t *testing.T) { require.Equal(t, authtypes.NewModuleAddress(keeper.NewEscrowAccountName(0)).String(), createdProgram.EscrowAddress) }) t.Run("min lockup duration too low", func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(false) + app, ctx := simapp2.NewTestNibiruAppAndContext(false) _, err := app.IncentivizationKeeper.CreateIncentivizationProgram(ctx, "denom", 1*time.Second, ctx.BlockTime(), keeper.MinEpochs) @@ -41,7 +42,7 @@ func TestKeeper_CreateIncentivizationProgram(t *testing.T) { }) t.Run("epochs lower than minimum", func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(false) + app, ctx := simapp2.NewTestNibiruAppAndContext(false) _, err := app.IncentivizationKeeper.CreateIncentivizationProgram(ctx, "denom", 48*time.Hour, ctx.BlockTime(), keeper.MinEpochs-1) @@ -49,7 +50,7 @@ func TestKeeper_CreateIncentivizationProgram(t *testing.T) { }) t.Run("start time before block time", func(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) _, err := app.IncentivizationKeeper.CreateIncentivizationProgram(ctx, "denom", 48*time.Hour, ctx.BlockTime().Add(-1*time.Second), keeper.MinEpochs+1) @@ -59,7 +60,7 @@ func TestKeeper_CreateIncentivizationProgram(t *testing.T) { func TestKeeper_FundIncentivizationProgram(t *testing.T) { t.Run("success", func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(false) + app, ctx := simapp2.NewTestNibiruAppAndContext(false) addr := sample.AccAddress() fundingAmount := sdk.NewCoins(sdk.NewInt64Coin("test", 100)) require.NoError(t, simapp.FundAccount(app.BankKeeper, ctx, addr, fundingAmount)) diff --git a/x/incentivization/keeper/servers_test.go b/x/incentivization/keeper/servers_test.go index ad2ad154c..92b642a4b 100644 --- a/x/incentivization/keeper/servers_test.go +++ b/x/incentivization/keeper/servers_test.go @@ -4,23 +4,24 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/simapp" + simapp2 "github.com/NibiruChain/nibiru/simapp" - "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "github.com/NibiruChain/nibiru/x/testutil/sample" + "github.com/NibiruChain/nibiru/x/incentivization/keeper" "github.com/NibiruChain/nibiru/x/incentivization/types" ) func TestMsgServer_CreateIncentivizationProgram(t *testing.T) { t.Run("success", func(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) s := keeper.NewMsgServer(app.IncentivizationKeeper) ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) @@ -55,7 +56,7 @@ func TestMsgServer_CreateIncentivizationProgram(t *testing.T) { func TestMsgServer_FundIncentivizationProgram(t *testing.T) { t.Run("success", func(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) s := keeper.NewMsgServer(app.IncentivizationKeeper) ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) @@ -94,7 +95,7 @@ func TestMsgServer_FundIncentivizationProgram(t *testing.T) { } func TestQueryServer_IncentivizationProgram(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) q := keeper.NewQueryServer(app.IncentivizationKeeper) ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) @@ -108,7 +109,7 @@ func TestQueryServer_IncentivizationProgram(t *testing.T) { } func TestQueryServer_IncentivizationPrograms(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) q := keeper.NewQueryServer(app.IncentivizationKeeper) ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) diff --git a/x/incentivization/module_test.go b/x/incentivization/module_test.go index a7dc09adb..3f35ed725 100644 --- a/x/incentivization/module_test.go +++ b/x/incentivization/module_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/require" @@ -12,11 +14,10 @@ import ( "github.com/NibiruChain/nibiru/x/incentivization" "github.com/NibiruChain/nibiru/x/incentivization/keeper" "github.com/NibiruChain/nibiru/x/incentivization/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestAppModule_InitGenesis_ExportGenesis(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp.NewTestNibiruApp(false) am := incentivization.NewAppModule(app.AppCodec(), app.IncentivizationKeeper, app.AccountKeeper) ctxUncached := app.NewContext(false, tmproto.Header{Time: time.Now()}) diff --git a/x/lockup/client/cli/cli_test.go b/x/lockup/client/cli/cli_test.go index df125b25b..22d3443b6 100644 --- a/x/lockup/client/cli/cli_test.go +++ b/x/lockup/client/cli/cli_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + "github.com/NibiruChain/nibiru/x/lockup/types" "github.com/cosmos/cosmos-sdk/crypto/hd" @@ -15,7 +17,6 @@ import ( "github.com/NibiruChain/nibiru/app" "github.com/NibiruChain/nibiru/x/lockup/client/cli" testutilcli "github.com/NibiruChain/nibiru/x/testutil/cli" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) type IntegrationTestSuite struct { @@ -35,7 +36,7 @@ func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up lockup CLI testing suite") app.SetPrefixes(app.AccountAddressPrefix) - s.cfg = testutilcli.BuildNetworkConfig(testapp.NewTestGenesisStateFromDefault()) + s.cfg = testutilcli.BuildNetworkConfig(simapp.NewTestGenesisStateFromDefault()) s.cfg.StartingTokens = sdk.NewCoins( sdk.NewInt64Coin("ATOM", 1_000_000), sdk.NewInt64Coin("OSMO", 1_000_000), diff --git a/x/lockup/keeper/keeper_test.go b/x/lockup/keeper/keeper_test.go index ddb072841..e79dfcb0d 100644 --- a/x/lockup/keeper/keeper_test.go +++ b/x/lockup/keeper/keeper_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" @@ -12,7 +14,6 @@ import ( "github.com/NibiruChain/nibiru/x/lockup/keeper" "github.com/NibiruChain/nibiru/x/lockup/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestCreateLock(t *testing.T) { @@ -45,7 +46,7 @@ func TestCreateLock(t *testing.T) { for _, testcase := range tests { tc := testcase t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) require.NoError(t, simapp.FundAccount(app.BankKeeper, ctx, tc.ownerAddr, tc.accountInitialFunds)) lock, err := app.LockupKeeper.LockTokens(ctx, tc.ownerAddr, tc.coins, tc.duration) @@ -68,7 +69,7 @@ func TestCreateLock(t *testing.T) { func TestLockupKeeper_InitiateUnlocking(t *testing.T) { t.Run("success", func(t *testing.T) { - app, _ := testapp.NewNibiruAppAndContext(false) + app, _ := simapp2.NewTestNibiruAppAndContext(false) addr := sample.AccAddress() coins := sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(1000))) @@ -90,12 +91,12 @@ func TestLockupKeeper_InitiateUnlocking(t *testing.T) { require.Equal(t, updatedLock.EndTime, ctx.BlockTime().Add(lock.Duration)) }) t.Run("err lock does not exist", func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(false) + app, ctx := simapp2.NewTestNibiruAppAndContext(false) _, err := app.LockupKeeper.InitiateUnlocking(ctx, 0) require.ErrorIs(t, err, types.ErrLockupNotFound) }) t.Run("err already unlocking", func(t *testing.T) { - app, _ := testapp.NewNibiruAppAndContext(false) + app, _ := simapp2.NewTestNibiruAppAndContext(false) addr := sample.AccAddress() coins := sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(1000))) @@ -119,7 +120,7 @@ func TestLockupKeeper_InitiateUnlocking(t *testing.T) { func TestLockupKeeper_UnlockTokens(t *testing.T) { t.Run("success", func(t *testing.T) { - app, _ := testapp.NewNibiruAppAndContext(true) + app, _ := simapp2.NewTestNibiruAppAndContext(true) addr := sample.AccAddress() coins := sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(1000))) @@ -146,14 +147,14 @@ func TestLockupKeeper_UnlockTokens(t *testing.T) { }) t.Run("lock not found", func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) _, err := app.LockupKeeper.UnlockTokens(ctx, 1) require.ErrorIs(t, err, types.ErrLockupNotFound) }) t.Run("lock not matured", func(t *testing.T) { - app, _ := testapp.NewNibiruAppAndContext(true) + app, _ := simapp2.NewTestNibiruAppAndContext(true) addr := sample.AccAddress() coins := sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(1000))) @@ -171,7 +172,7 @@ func TestLockupKeeper_UnlockTokens(t *testing.T) { func TestLockupKeeper_AccountLockedCoins(t *testing.T) { t.Run("success", func(t *testing.T) { - app, _ := testapp.NewNibiruAppAndContext(true) + app, _ := simapp2.NewTestNibiruAppAndContext(true) addr := sample.AccAddress() ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) @@ -197,7 +198,7 @@ func TestLockupKeeper_AccountLockedCoins(t *testing.T) { func TestLockupKeeper_AccountUnlockedCoins(t *testing.T) { t.Run("success", func(t *testing.T) { - app, _ := testapp.NewNibiruAppAndContext(false) + app, _ := simapp2.NewTestNibiruAppAndContext(false) addr := sample.AccAddress() ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) @@ -227,7 +228,7 @@ func TestLockupKeeper_AccountUnlockedCoins(t *testing.T) { func TestLockupKeeper_LockedCoins(t *testing.T) { t.Run("success", func(t *testing.T) { - app, _ := testapp.NewNibiruAppAndContext(false) + app, _ := simapp2.NewTestNibiruAppAndContext(false) ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) addr := sample.AccAddress() @@ -258,7 +259,7 @@ func TestLockupKeeper_LockedCoins(t *testing.T) { func TestLockupKeeper_UnlockAvailableCoins(t *testing.T) { t.Run("success", func(t *testing.T) { - app, _ := testapp.NewNibiruAppAndContext(false) + app, _ := simapp2.NewTestNibiruAppAndContext(false) ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) addr := sample.AccAddress() @@ -290,7 +291,7 @@ func TestLockupKeeper_UnlockAvailableCoins(t *testing.T) { func TestLockupKeeper_LocksByDenomUnlockingAfter(t *testing.T) { t.Run("success", func(t *testing.T) { - app, _ := testapp.NewNibiruAppAndContext(false) + app, _ := simapp2.NewTestNibiruAppAndContext(false) ctx := app.NewContext(false, tmproto.Header{Time: time.Now().UTC()}) addr := sample.AccAddress() diff --git a/x/lockup/keeper/msg_server_test.go b/x/lockup/keeper/msg_server_test.go index 295238c04..ba2f3a222 100644 --- a/x/lockup/keeper/msg_server_test.go +++ b/x/lockup/keeper/msg_server_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/cosmos-sdk/simapp" @@ -14,11 +16,10 @@ import ( "github.com/NibiruChain/nibiru/x/lockup/keeper" "github.com/NibiruChain/nibiru/x/lockup/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestMsgServer_LockTokens(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) uncachedCtx := app.NewContext(false, tmproto.Header{Time: time.Now()}) s := keeper.NewMsgServerImpl(app.LockupKeeper) @@ -38,7 +39,7 @@ func TestMsgServer_LockTokens(t *testing.T) { } func TestMsgServer_InitiateUnlock(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) uncachedCtx := app.NewContext(false, tmproto.Header{Time: time.Now()}) s := keeper.NewMsgServerImpl(app.LockupKeeper) @@ -64,7 +65,7 @@ func TestMsgServer_InitiateUnlock(t *testing.T) { } func TestMsgServer_Unlock(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) uncachedCtx := app.NewContext(false, tmproto.Header{Time: time.Now()}) s := keeper.NewMsgServerImpl(app.LockupKeeper) @@ -98,7 +99,7 @@ func TestMsgServer_Unlock(t *testing.T) { } func TestQueryServer_Lock(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) uncachedCtx := app.NewContext(false, tmproto.Header{Time: time.Now()}) s := keeper.NewMsgServerImpl(app.LockupKeeper) q := keeper.NewQueryServerImpl(app.LockupKeeper) @@ -127,7 +128,7 @@ func TestQueryServer_Lock(t *testing.T) { } func TestQueryServer_LockedCoins(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) uncachedCtx := app.NewContext(false, tmproto.Header{Time: time.Now()}) s := keeper.NewMsgServerImpl(app.LockupKeeper) q := keeper.NewQueryServerImpl(app.LockupKeeper) @@ -153,7 +154,7 @@ func TestQueryServer_LockedCoins(t *testing.T) { } func TestQueryServer_LocksByAddress(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) uncachedCtx := app.NewContext(false, tmproto.Header{Time: time.Now()}) s := keeper.NewMsgServerImpl(app.LockupKeeper) q := keeper.NewQueryServerImpl(app.LockupKeeper) diff --git a/x/lockup/keeper/state_test.go b/x/lockup/keeper/state_test.go index 9e758a0ee..1515f5464 100644 --- a/x/lockup/keeper/state_test.go +++ b/x/lockup/keeper/state_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" @@ -12,11 +14,10 @@ import ( "github.com/NibiruChain/nibiru/x/lockup/keeper" "github.com/NibiruChain/nibiru/x/lockup/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestLockState(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) addr := sample.AccAddress() lock := &types.Lock{ LockId: 0, @@ -62,7 +63,7 @@ func Test_LocksState_232(t *testing.T) { addr1 := sdk.AccAddress{197, 74, 130, 194, 229, 233, 119, 113, 119, 172, 13, 56, 95, 110, 234, 199, 255, 102, 24, 142} addr2 := sdk.AccAddress{198, 74, 130, 194, 229, 233, 119, 113, 119, 172, 13, 56, 95, 110, 234, 199, 255, 102, 24, 143} - app, _ := testapp.NewNibiruAppAndContext(false) + app, _ := simapp2.NewTestNibiruAppAndContext(false) ctx := app.NewContext(false, tmproto.Header{Time: time.Now()}) // we create two locks for each addr one expired the other one not diff --git a/x/lockup/module_test.go b/x/lockup/module_test.go index e802777df..32a044d01 100644 --- a/x/lockup/module_test.go +++ b/x/lockup/module_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" @@ -12,11 +14,10 @@ import ( "github.com/NibiruChain/nibiru/x/lockup" "github.com/NibiruChain/nibiru/x/lockup/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestAppModule_ExportGenesis_ImportGenesis(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) am := lockup.NewAppModule(app.AppCodec(), app.LockupKeeper, app.AccountKeeper, app.BankKeeper) ctxUncached := app.NewContext(false, tmproto.Header{Time: time.Now()}) diff --git a/x/perp/client/cli/cli_test.go b/x/perp/client/cli/cli_test.go index 5b62a362c..705f7bea6 100644 --- a/x/perp/client/cli/cli_test.go +++ b/x/perp/client/cli/cli_test.go @@ -5,6 +5,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -21,7 +23,6 @@ import ( perptypes "github.com/NibiruChain/nibiru/x/perp/types" pftypes "github.com/NibiruChain/nibiru/x/pricefeed/types" testutilcli "github.com/NibiruChain/nibiru/x/testutil/cli" - "github.com/NibiruChain/nibiru/x/testutil/testapp" vpooltypes "github.com/NibiruChain/nibiru/x/vpool/types" ) @@ -73,7 +74,7 @@ func (s *IntegrationTestSuite) SetupSuite() { app.SetPrefixes(app.AccountAddressPrefix) encodingConfig := app.MakeTestEncodingConfig() - genesisState := testapp.NewTestGenesisStateFromDefault() + genesisState := simapp.NewTestGenesisStateFromDefault() // setup vpool vpoolGenesis := vpooltypes.DefaultGenesis() diff --git a/x/perp/genesis_test.go b/x/perp/genesis_test.go index 128c16a9c..6e68287d5 100644 --- a/x/perp/genesis_test.go +++ b/x/perp/genesis_test.go @@ -5,6 +5,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" @@ -14,12 +16,11 @@ import ( "github.com/NibiruChain/nibiru/x/perp" "github.com/NibiruChain/nibiru/x/perp/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestGenesis(t *testing.T) { t.Run("success", func(t *testing.T) { - app := testapp.NewNibiruApp(false) + app := simapp2.NewTestNibiruApp(false) ctxUncached := app.NewContext(false, tmproto.Header{}) ctx, _ := ctxUncached.CacheContext() // fund module accounts diff --git a/x/perp/keeper/calc_test.go b/x/perp/keeper/calc_test.go index 157a49e73..98c60ec93 100644 --- a/x/perp/keeper/calc_test.go +++ b/x/perp/keeper/calc_test.go @@ -3,13 +3,14 @@ package keeper_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" "github.com/NibiruChain/nibiru/x/common" "github.com/NibiruChain/nibiru/x/perp/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestCalcRemainMarginWithFundingPayment(t *testing.T) { @@ -20,7 +21,7 @@ func TestCalcRemainMarginWithFundingPayment(t *testing.T) { { name: "get - no positions set raises vpool not found error", test: func() { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) marginDelta := sdk.OneDec() _, err := nibiruApp.PerpKeeper.CalcRemainMarginWithFundingPayment( @@ -35,7 +36,7 @@ func TestCalcRemainMarginWithFundingPayment(t *testing.T) { name: "signedRemainMargin negative bc of marginDelta", test: func() { t.Log("Setup Nibiru app, pair, and trader") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) trader := sample.AccAddress() pair := common.MustNewAssetPair("osmo:nusd") @@ -88,7 +89,7 @@ func TestCalcRemainMarginWithFundingPayment(t *testing.T) { name: "large fPayment lowers pos value by half", test: func() { t.Log("Setup Nibiru app, pair, and trader") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) trader := sample.AccAddress() pair := common.MustNewAssetPair("osmo:nusd") diff --git a/x/perp/keeper/clearing_house_integration_test.go b/x/perp/keeper/clearing_house_integration_test.go index ee41959df..e5b7137ae 100644 --- a/x/perp/keeper/clearing_house_integration_test.go +++ b/x/perp/keeper/clearing_house_integration_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -13,7 +15,6 @@ import ( "github.com/NibiruChain/nibiru/x/common" "github.com/NibiruChain/nibiru/x/perp/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" vpooltypes "github.com/NibiruChain/nibiru/x/vpool/types" ) @@ -245,7 +246,7 @@ func TestOpenPositionSuccess(t *testing.T) { tc := testCase t.Run(tc.name, func(t *testing.T) { t.Log("Setup Nibiru app and constants") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) traderAddr := sample.AccAddress() oracle := sample.AccAddress() exchangedSize := tc.expectedSize @@ -445,7 +446,7 @@ func TestOpenPositionError(t *testing.T) { tc := testCase t.Run(tc.name, func(t *testing.T) { t.Log("Setup Nibiru app and constants") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) traderAddr := sample.AccAddress() oracle := sample.AccAddress() @@ -498,7 +499,7 @@ func TestOpenPositionInvalidPair(t *testing.T) { name: "open pos - uninitialized pool raised pair not supported error", test: func() { t.Log("Setup Nibiru app, pair, and trader without a vpool.") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) pair := common.MustNewAssetPair("xxx:yyy") trader := sample.AccAddress() @@ -518,7 +519,7 @@ func TestOpenPositionInvalidPair(t *testing.T) { name: "open pos - vpool not set on the perp PairMetadata ", test: func() { t.Log("Setup Nibiru app, pair, and trader") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) pair := common.MustNewAssetPair("xxx:yyy") t.Log("Set vpool defined by pair on VpoolKeeper") diff --git a/x/perp/keeper/grpc_query_test.go b/x/perp/keeper/grpc_query_test.go index 8299b7152..2fc09a278 100644 --- a/x/perp/keeper/grpc_query_test.go +++ b/x/perp/keeper/grpc_query_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -12,7 +14,6 @@ import ( "github.com/NibiruChain/nibiru/x/perp/keeper" "github.com/NibiruChain/nibiru/x/perp/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestQueryPosition(t *testing.T) { @@ -88,7 +89,7 @@ func TestQueryPosition(t *testing.T) { tc.initialPosition.TraderAddress = traderAddr.String() t.Log("initialize app and keeper") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) perpKeeper := &nibiruApp.PerpKeeper vpoolKeeper := &nibiruApp.VpoolKeeper queryServer := keeper.NewQuerier(*perpKeeper) diff --git a/x/perp/keeper/keeper_test.go b/x/perp/keeper/keeper_test.go index 90e188728..e8d8ed451 100644 --- a/x/perp/keeper/keeper_test.go +++ b/x/perp/keeper/keeper_test.go @@ -4,12 +4,13 @@ import ( "testing" "time" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/NibiruChain/nibiru/simapp" - "github.com/NibiruChain/nibiru/x/perp/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + "github.com/NibiruChain/nibiru/x/perp/types" ) // Params @@ -43,7 +44,7 @@ func TestGetAndSetParams(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) perpKeeper := &nibiruApp.PerpKeeper params := tc.requiredParams() @@ -56,7 +57,7 @@ func TestGetAndSetParams(t *testing.T) { func TestGetAndSetParams_Errors(t *testing.T) { t.Run("Calling Get without setting causes a panic", func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(false) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(false) perpKeeper := &nibiruApp.PerpKeeper require.Panics( diff --git a/x/perp/keeper/liquidate_test.go b/x/perp/keeper/liquidate_test.go index a0c469c5f..0562d9cb7 100644 --- a/x/perp/keeper/liquidate_test.go +++ b/x/perp/keeper/liquidate_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" @@ -13,7 +15,6 @@ import ( "github.com/NibiruChain/nibiru/x/perp/types" testutilevents "github.com/NibiruChain/nibiru/x/testutil/events" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestExecuteFullLiquidation(t *testing.T) { @@ -75,7 +76,7 @@ func TestExecuteFullLiquidation(t *testing.T) { for name, testCase := range testCases { tc := testCase t.Run(name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) perpKeeper := &nibiruApp.PerpKeeper t.Log("create vpool") @@ -125,7 +126,7 @@ func TestExecuteFullLiquidation(t *testing.T) { ctx, tokenPair, tc.positionSide, traderAddr, tc.quoteAmount, tc.leverage, tc.baseAssetLimit) require.NoError(t, err) - t.Log("Artificially populate Vault and PerpEF to prevent BankKeeper errors") + t.Log("Artificially populate Vault and PerpEF to prevent bankKeeper errors") startingModuleFunds := sdk.NewCoins(sdk.NewInt64Coin( tokenPair.QuoteDenom(), 1_000_000)) assert.NoError(t, simapp.FundModuleAccount( @@ -250,7 +251,7 @@ func TestExecutePartialLiquidation(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) t.Log("Set vpool defined by pair on VpoolKeeper") vpoolKeeper := &nibiruApp.VpoolKeeper @@ -302,7 +303,7 @@ func TestExecutePartialLiquidation(t *testing.T) { ctx, tokenPair, tc.side, traderAddr, tc.quote, tc.leverage, tc.baseLimit) require.NoError(t, err) - t.Log("Artificially populate Vault and PerpEF to prevent BankKeeper errors") + t.Log("Artificially populate Vault and PerpEF to prevent bankKeeper errors") startingModuleFunds := sdk.NewCoins(sdk.NewInt64Coin( tokenPair.QuoteDenom(), 1_000_000)) assert.NoError(t, simapp.FundModuleAccount( diff --git a/x/perp/keeper/margin_test.go b/x/perp/keeper/margin_test.go index 80d555b4d..48a0453e7 100644 --- a/x/perp/keeper/margin_test.go +++ b/x/perp/keeper/margin_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" @@ -13,7 +15,6 @@ import ( "github.com/NibiruChain/nibiru/x/perp/types" testutilevents "github.com/NibiruChain/nibiru/x/testutil/events" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestAddMarginSuccess(t *testing.T) { @@ -48,7 +49,7 @@ func TestAddMarginSuccess(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) traderAddr := sdk.MustAccAddressFromBech32(tc.initialPosition.TraderAddress) t.Log("add trader funds") @@ -113,7 +114,7 @@ func TestRemoveMargin(t *testing.T) { test: func() { removeAmt := sdk.NewInt(5) - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) trader := sample.AccAddress() pair := common.MustNewAssetPair("osmo:nusd") @@ -126,7 +127,7 @@ func TestRemoveMargin(t *testing.T) { name: "pool exists but trader doesn't have position - fail", test: func() { t.Log("Setup Nibiru app, pair, and trader") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) trader := sample.AccAddress() pair := common.MustNewAssetPair("osmo:nusd") @@ -156,7 +157,7 @@ func TestRemoveMargin(t *testing.T) { name: "remove margin from healthy position", test: func() { t.Log("Setup Nibiru app, pair, and trader") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) traderAddr := sample.AccAddress() pair := common.MustNewAssetPair("xxx:yyy") diff --git a/x/perp/keeper/msg_server_test.go b/x/perp/keeper/msg_server_test.go index 5f8a3d265..b15319128 100644 --- a/x/perp/keeper/msg_server_test.go +++ b/x/perp/keeper/msg_server_test.go @@ -5,6 +5,8 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -15,7 +17,6 @@ import ( "github.com/NibiruChain/nibiru/x/perp/keeper" "github.com/NibiruChain/nibiru/x/perp/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestMsgServerAddMargin(t *testing.T) { @@ -68,7 +69,7 @@ func TestMsgServerAddMargin(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) msgServer := keeper.NewMsgServerImpl(app.PerpKeeper) traderAddr := sample.AccAddress() @@ -187,7 +188,7 @@ func TestMsgServerRemoveMargin(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) msgServer := keeper.NewMsgServerImpl(app.PerpKeeper) traderAddr := sample.AccAddress() @@ -274,7 +275,7 @@ func TestMsgServerOpenPosition(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) msgServer := keeper.NewMsgServerImpl(app.PerpKeeper) t.Log("create vpool") @@ -358,7 +359,7 @@ func TestMsgServerClosePosition(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) msgServer := keeper.NewMsgServerImpl(app.PerpKeeper) t.Log("create vpool") @@ -456,7 +457,7 @@ func TestMsgServerLiquidate(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp2.NewTestNibiruAppAndContext(true) msgServer := keeper.NewMsgServerImpl(app.PerpKeeper) t.Log("create vpool") diff --git a/x/perp/keeper/perp_test.go b/x/perp/keeper/perp_test.go index e5a0786d1..e73ccb87d 100644 --- a/x/perp/keeper/perp_test.go +++ b/x/perp/keeper/perp_test.go @@ -4,17 +4,18 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/NibiruChain/nibiru/x/common" + "github.com/stretchr/testify/require" + "github.com/NibiruChain/nibiru/x/perp/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" - - "github.com/stretchr/testify/require" ) func TestGetAndSetPosition(t *testing.T) { @@ -26,7 +27,7 @@ func TestGetAndSetPosition(t *testing.T) { name: "get - no positions set raises vpool not found error", test: func() { trader := sample.AccAddress() - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) pair := common.MustNewAssetPair("osmo:nusd") _, err := nibiruApp.PerpKeeper.PositionsState(ctx).Get(pair, trader) @@ -40,7 +41,7 @@ func TestGetAndSetPosition(t *testing.T) { vpoolPair := common.MustNewAssetPair("osmo:nusd") traderAddr := sample.AccAddress() - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) _, err := nibiruApp.PerpKeeper.PositionsState(ctx).Get(vpoolPair, traderAddr) require.Error(t, err) @@ -81,7 +82,7 @@ func TestDeletePosition(t *testing.T) { traders := []sdk.AccAddress{ sample.AccAddress(), sample.AccAddress(), } - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) t.Log("vpool contains no positions to start") for _, trader := range traders { @@ -147,7 +148,7 @@ func TestKeeperClosePosition(t *testing.T) { // TODO(mercilex): simulate funding payments t.Run("success", func(t *testing.T) { t.Log("Setup Nibiru app, pair, and trader") - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) pair := common.MustNewAssetPair("xxx:yyy") t.Log("Set vpool defined by pair on VpoolKeeper") diff --git a/x/perp/module_test.go b/x/perp/module_test.go index 156ef8b86..601b2c6a9 100644 --- a/x/perp/module_test.go +++ b/x/perp/module_test.go @@ -3,16 +3,17 @@ package perp_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + "github.com/stretchr/testify/assert" "github.com/NibiruChain/nibiru/x/perp/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) // TestModuleAccounts verifies that all x/perp module accounts are connected // to the base application func TestModuleAccounts(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) perpAcc := nibiruApp.PerpKeeper.AccountKeeper.GetModuleAccount( ctx, types.ModuleName) diff --git a/x/perp/types/expected_keepers_test.go b/x/perp/types/expected_keepers_test.go index 636411867..10c88eaf1 100644 --- a/x/perp/types/expected_keepers_test.go +++ b/x/perp/types/expected_keepers_test.go @@ -4,10 +4,11 @@ import ( "reflect" "testing" + "github.com/NibiruChain/nibiru/simapp" + "github.com/stretchr/testify/assert" "github.com/NibiruChain/nibiru/x/perp/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) /* @@ -17,7 +18,7 @@ TestExpectedKeepers verifies that the expected keeper interfaces in x/perp 'NibiruApp.KeeperName' */ func TestExpectedKeepers(t *testing.T) { - nibiruApp, _ := testapp.NewNibiruAppAndContext(true) + nibiruApp, _ := simapp.NewTestNibiruAppAndContext(true) testCases := []struct { name string expectedKeeper interface{} @@ -29,12 +30,12 @@ func TestExpectedKeepers(t *testing.T) { appKeeper: nibiruApp.PricefeedKeeper, }, { - name: "BankKeeper from the cosmos-sdk", + name: "bankKeeper from the cosmos-sdk", expectedKeeper: (*types.BankKeeper)(nil), appKeeper: nibiruApp.BankKeeper, }, { - name: "AccountKeeper from the cosmos-sdk", + name: "accountKeeper from the cosmos-sdk", expectedKeeper: (*types.AccountKeeper)(nil), appKeeper: nibiruApp.AccountKeeper, }, diff --git a/x/pricefeed/abci_test.go b/x/pricefeed/abci_test.go index 80597b074..e0ce6dd0b 100644 --- a/x/pricefeed/abci_test.go +++ b/x/pricefeed/abci_test.go @@ -4,20 +4,20 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/NibiruChain/nibiru/app" "github.com/NibiruChain/nibiru/x/common" "github.com/NibiruChain/nibiru/x/pricefeed" pricefeedkeeper "github.com/NibiruChain/nibiru/x/pricefeed/keeper" ptypes "github.com/NibiruChain/nibiru/x/pricefeed/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestTWAPriceUpdates(t *testing.T) { - var nibiruApp *app.NibiruApp + var nibiruApp *simapp.NibiruTestApp var ctx sdk.Context oracle := sample.AccAddress() @@ -39,7 +39,7 @@ func TestTWAPriceUpdates(t *testing.T) { require.NoError(t, err) } - nibiruApp, ctx = testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx = simapp.NewTestNibiruAppAndContext(true) ctx = ctx.WithBlockTime(time.Date(2015, 10, 21, 0, 0, 0, 0, time.UTC)) diff --git a/x/pricefeed/client/cli/cli_test.go b/x/pricefeed/client/cli/cli_test.go index e768c50ac..772dd293b 100644 --- a/x/pricefeed/client/cli/cli_test.go +++ b/x/pricefeed/client/cli/cli_test.go @@ -8,6 +8,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/client" banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -30,7 +32,6 @@ import ( "github.com/NibiruChain/nibiru/x/pricefeed/client/cli" pricefeedtypes "github.com/NibiruChain/nibiru/x/pricefeed/types" testutilcli "github.com/NibiruChain/nibiru/x/testutil/cli" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) const ( @@ -94,7 +95,7 @@ func (s *IntegrationTestSuite) SetupSuite() { app.SetPrefixes(app.AccountAddressPrefix) - s.cfg = testutilcli.BuildNetworkConfig(testapp.NewTestGenesisStateFromDefault()) + s.cfg = testutilcli.BuildNetworkConfig(simapp.NewTestGenesisStateFromDefault()) s.network = testutilcli.NewNetwork(s.T(), s.cfg) s.oracleMap = make(map[string]sdk.AccAddress) diff --git a/x/pricefeed/genesis_test.go b/x/pricefeed/genesis_test.go index 282697f49..da1107bc5 100644 --- a/x/pricefeed/genesis_test.go +++ b/x/pricefeed/genesis_test.go @@ -5,6 +5,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + tmtypes "github.com/tendermint/tendermint/types" "github.com/NibiruChain/nibiru/x/common" @@ -20,7 +22,6 @@ import ( "github.com/NibiruChain/nibiru/x/pricefeed/types" testutilkeeper "github.com/NibiruChain/nibiru/x/testutil/keeper" "github.com/NibiruChain/nibiru/x/testutil/nullify" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestGenesis_DefaultGenesis(t *testing.T) { @@ -45,10 +46,10 @@ func TestGenesis_DefaultGenesis(t *testing.T) { func TestGenesis_TestGenesis(t *testing.T) { app.SetPrefixes(app.AccountAddressPrefix) - appGenesis := testapp.NewTestGenesisStateFromDefault() - pfGenesisState := testapp.PricefeedGenesis() + appGenesis := simapp.NewTestGenesisStateFromDefault() + pfGenesisState := simapp.PricefeedGenesis() - nibiruApp := testapp.NewNibiruAppWithGenesis(appGenesis) + nibiruApp := simapp.NewTestNibiruAppWithGenesis(appGenesis) ctx := nibiruApp.NewContext(false, tmproto.Header{}) k := nibiruApp.PricefeedKeeper pricefeed.InitGenesis(ctx, k, pfGenesisState) diff --git a/x/pricefeed/keeper/keeper_test.go b/x/pricefeed/keeper/keeper_test.go index aa6464643..414fe3851 100644 --- a/x/pricefeed/keeper/keeper_test.go +++ b/x/pricefeed/keeper/keeper_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -11,11 +13,10 @@ import ( "github.com/NibiruChain/nibiru/x/common" "github.com/NibiruChain/nibiru/x/pricefeed/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestKeeper_SetGetPair(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) pairs := common.AssetPairs{ common.MustNewAssetPair("tst:usd"), @@ -43,7 +44,7 @@ func TestKeeper_SetGetPair(t *testing.T) { } func TestKeeper_GetPostRawPrice(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) keeper := app.PricefeedKeeper _, addrs := sample.PrivKeyAddressPairs(2) @@ -97,7 +98,7 @@ Test case where two oracles try to set prices for a market and only one of the oracles is valid (i.e. registered with keeper.SetParams). */ func TestKeeper_PostRawPriceWrongOracle(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) keeper := app.PricefeedKeeper pair := common.MustNewAssetPair("tst:usd") @@ -129,7 +130,7 @@ Test case where several oracles try to set prices for a market and "k" (int) of the oracles are valid (i.e. registered with keeper.SetParams). */ func TestKeeper_PostRawPriceWrongOracles(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) keeper := app.PricefeedKeeper pair := common.MustNewAssetPair("tst:usd") @@ -162,7 +163,7 @@ func TestKeeper_PostRawPriceWrongOracles(t *testing.T) { // Test Setting the current price of an Asset func TestKeeper_GetSetCurrentPrice(t *testing.T) { _, addrs := sample.PrivKeyAddressPairs(5) - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) keeper := app.PricefeedKeeper pair := common.PairBTCStable @@ -230,7 +231,7 @@ func TestKeeper_GetSetCurrentPrice(t *testing.T) { func TestKeeper_ExpiredGatherRawPrices(t *testing.T) { _, oracles := sample.PrivKeyAddressPairs(5) - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) keeper := app.PricefeedKeeper token0, token1 := "usd", "tst" diff --git a/x/pricefeed/keeper/params_test.go b/x/pricefeed/keeper/params_test.go index 02447368f..3490f9624 100644 --- a/x/pricefeed/keeper/params_test.go +++ b/x/pricefeed/keeper/params_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" @@ -11,7 +13,6 @@ import ( "github.com/NibiruChain/nibiru/x/common" "github.com/NibiruChain/nibiru/x/pricefeed/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestGetParams(t *testing.T) { @@ -22,7 +23,7 @@ func TestGetParams(t *testing.T) { { name: "calling GetParams without setting returns default", test: func() { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) k := nibiruApp.PricefeedKeeper require.EqualValues(t, types.DefaultParams(), k.GetParams(ctx)) }, @@ -30,7 +31,7 @@ func TestGetParams(t *testing.T) { { name: "params match after manual set and include default", test: func() { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) k := nibiruApp.PricefeedKeeper params := types.Params{ Pairs: common.NewAssetPairs("btc:usd", "xrp:usd"), @@ -61,7 +62,7 @@ func TestWhitelistOracles(t *testing.T) { { name: "genesis - no oracle provided", test: func() { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) pk := &nibiruApp.PricefeedKeeper oracle := sample.AccAddress() @@ -77,7 +78,7 @@ func TestWhitelistOracles(t *testing.T) { { name: "multiple oracles whitelisted at different times ", test: func() { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) pk := &nibiruApp.PricefeedKeeper paramsPairs := pk.GetParams(ctx).Pairs @@ -132,7 +133,7 @@ func TestWhitelistOraclesForPairs(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) pricefeedKeeper := &nibiruApp.PricefeedKeeper pricefeedKeeper.SetParams(ctx, tc.startParams) diff --git a/x/stablecoin/abci_test.go b/x/stablecoin/abci_test.go index 4766e2fc8..ed5a9c80b 100644 --- a/x/stablecoin/abci_test.go +++ b/x/stablecoin/abci_test.go @@ -4,16 +4,16 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/NibiruChain/nibiru/app" "github.com/NibiruChain/nibiru/x/common" "github.com/NibiruChain/nibiru/x/epochs" "github.com/NibiruChain/nibiru/x/pricefeed" ptypes "github.com/NibiruChain/nibiru/x/pricefeed/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) type test struct { @@ -25,7 +25,7 @@ type test struct { } func TestEpochInfoChangesBeginBlockerAndInitGenesis(t *testing.T) { - var app *app.NibiruApp + var app *simapp.NibiruTestApp var ctx sdk.Context tests := []test{ @@ -108,7 +108,7 @@ func TestEpochInfoChangesBeginBlockerAndInitGenesis(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.Name, func(t *testing.T) { - app, ctx = testapp.NewNibiruAppAndContext(true) + app, ctx = simapp.NewTestNibiruAppAndContext(true) ctx = ctx.WithBlockHeight(1) @@ -143,7 +143,7 @@ func TestEpochInfoChangesBeginBlockerAndInitGenesis(t *testing.T) { } func TestEpochInfoChangesCollateralValidity(t *testing.T) { - app, ctx := testapp.NewNibiruAppAndContext(true) + app, ctx := simapp.NewTestNibiruAppAndContext(true) runBlock := func(duration time.Duration) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1).WithBlockTime(ctx.BlockTime().Add(duration)) diff --git a/x/stablecoin/client/cli/cli_test.go b/x/stablecoin/client/cli/cli_test.go index bb46d6b66..e95e5b94f 100644 --- a/x/stablecoin/client/cli/cli_test.go +++ b/x/stablecoin/client/cli/cli_test.go @@ -5,6 +5,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -22,7 +24,6 @@ import ( "github.com/NibiruChain/nibiru/x/stablecoin/client/cli" stabletypes "github.com/NibiruChain/nibiru/x/stablecoin/types" testutilcli "github.com/NibiruChain/nibiru/x/testutil/cli" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) const ( @@ -78,7 +79,7 @@ func (s *IntegrationTestSuite) SetupSuite() { app.SetPrefixes(app.AccountAddressPrefix) encodingConfig := app.MakeTestEncodingConfig() - genesisState := testapp.NewTestGenesisStateFromDefault() + genesisState := simapp.NewTestGenesisStateFromDefault() // x/stablecoin genesis state stableGen := stabletypes.DefaultGenesis() diff --git a/x/stablecoin/genesis_test.go b/x/stablecoin/genesis_test.go index 460796edd..df4234caa 100644 --- a/x/stablecoin/genesis_test.go +++ b/x/stablecoin/genesis_test.go @@ -3,6 +3,8 @@ package stablecoin_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" @@ -10,7 +12,6 @@ import ( "github.com/NibiruChain/nibiru/x/stablecoin" "github.com/NibiruChain/nibiru/x/stablecoin/types" "github.com/NibiruChain/nibiru/x/testutil/nullify" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestGenesis(t *testing.T) { @@ -19,7 +20,7 @@ func TestGenesis(t *testing.T) { ModuleAccountBalance: sdk.NewCoin(common.DenomColl, sdk.ZeroInt()), } - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) k := nibiruApp.StablecoinKeeper stablecoin.InitGenesis(ctx, k, genesisState) got := stablecoin.ExportGenesis(ctx, k) diff --git a/x/stablecoin/keeper/collateral_ratio_test.go b/x/stablecoin/keeper/collateral_ratio_test.go index 64f734eaa..f52734228 100644 --- a/x/stablecoin/keeper/collateral_ratio_test.go +++ b/x/stablecoin/keeper/collateral_ratio_test.go @@ -5,16 +5,17 @@ import ( "testing" "time" - "github.com/NibiruChain/nibiru/x/common" - pftypes "github.com/NibiruChain/nibiru/x/pricefeed/types" - "github.com/NibiruChain/nibiru/x/stablecoin/types" - "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" + simapp2 "github.com/NibiruChain/nibiru/simapp" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/NibiruChain/nibiru/x/common" + pftypes "github.com/NibiruChain/nibiru/x/pricefeed/types" + "github.com/NibiruChain/nibiru/x/stablecoin/types" + "github.com/NibiruChain/nibiru/x/testutil/sample" ) func TestSetCollRatio_Input(t *testing.T) { @@ -27,7 +28,7 @@ func TestSetCollRatio_Input(t *testing.T) { executeTest := func(t *testing.T, testCase TestCase) { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper err := stablecoinKeeper.SetCollRatio(ctx, tc.inCollRatio) @@ -76,7 +77,7 @@ func TestSetCollRatioUpdate(t *testing.T) { executeTest := func(t *testing.T, testCase TestCase) { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper priceKeeper := &nibiruApp.PricefeedKeeper @@ -162,7 +163,7 @@ func TestSetCollRatioUpdate(t *testing.T) { func TestGetCollRatio_Input(t *testing.T) { testName := "GetCollRatio after setting default params returns expected value" t.Run(testName, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper stablecoinKeeper.SetParams(ctx, types.DefaultParams()) @@ -175,7 +176,7 @@ func TestGetCollRatio_Input(t *testing.T) { testName = "Setting to non-default value returns expected value" t.Run(testName, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper expectedCollRatio := sdk.MustNewDecFromStr("0.5") @@ -237,7 +238,7 @@ func TestStableRequiredForTargetCollRatio(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper require.NoError(t, stablecoinKeeper.SetCollRatio(ctx, tc.targetCollRatio)) require.NoError(t, nibiruApp.BankKeeper.MintCoins( @@ -329,7 +330,7 @@ func TestRecollateralizeCollAmtForTargetCollRatio(t *testing.T) { for _, testCase := range expectedPasses { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper require.NoError(t, stablecoinKeeper.SetCollRatio(ctx, tc.targetCollRatio)) require.NoError(t, nibiruApp.BankKeeper.MintCoins( @@ -386,7 +387,7 @@ func TestRecollateralizeCollAmtForTargetCollRatio(t *testing.T) { for _, testCase := range expectedFails { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper require.NoError(t, stablecoinKeeper.SetCollRatio(ctx, tc.targetCollRatio)) require.NoError(t, nibiruApp.BankKeeper.MintCoins( @@ -514,7 +515,7 @@ func TestGovAmtFromFullRecollateralize(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper require.NoError(t, stablecoinKeeper.SetCollRatio(ctx, tc.targetCollRatio)) require.NoError(t, nibiruApp.BankKeeper.MintCoins( @@ -792,7 +793,7 @@ func TestRecollateralize(t *testing.T) { t.Run(tc.name, func(t *testing.T) { require.EqualValues(t, tc.expectedNeededUSD, tc.scenario.CalcNeededUSD()) - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper require.NoError(t, stablecoinKeeper.SetCollRatio(ctx, tc.scenario.collRatio)) require.NoError(t, nibiruApp.BankKeeper.MintCoins( @@ -877,7 +878,7 @@ func TestRecollateralize_Short(t *testing.T) { { name: "invalid address - error", test: func() { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) goCtx := sdk.WrapSDKContext(ctx) msg := &types.MsgRecollateralize{ @@ -890,7 +891,7 @@ func TestRecollateralize_Short(t *testing.T) { { name: "prices expired - error", test: func() { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) goCtx := sdk.WrapSDKContext(ctx) sender := sample.AccAddress() msg := &types.MsgRecollateralize{ @@ -935,7 +936,7 @@ func TestBuyback_MsgFormat(t *testing.T) { } { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) msg := types.MsgBuyback{ Creator: tc.caller, Gov: tc.gov, @@ -1188,7 +1189,7 @@ func TestBuyback(t *testing.T) { t.Run(tc.name, func(t *testing.T) { require.EqualValues(t, tc.expectedNeededUSD, tc.scenario.CalcNeededUSD()) - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper require.NoError(t, stablecoinKeeper.SetCollRatio(ctx, tc.scenario.collRatio)) @@ -1328,7 +1329,7 @@ func TestBuybackGovAmtForTargetCollRatio(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) stablecoinKeeper := &nibiruApp.StablecoinKeeper require.NoError(t, stablecoinKeeper.SetCollRatio(ctx, tc.scenario.collRatio)) require.NoError(t, nibiruApp.BankKeeper.MintCoins( diff --git a/x/stablecoin/keeper/grpc_query_test.go b/x/stablecoin/keeper/grpc_query_test.go index f65c328e5..f346b2c0c 100644 --- a/x/stablecoin/keeper/grpc_query_test.go +++ b/x/stablecoin/keeper/grpc_query_test.go @@ -3,15 +3,16 @@ package keeper_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" "github.com/NibiruChain/nibiru/x/stablecoin/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestParamsQuery(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) keeper := &nibiruApp.StablecoinKeeper wctx := sdk.WrapSDKContext(ctx) params := types.DefaultParams() diff --git a/x/stablecoin/keeper/keeper_test.go b/x/stablecoin/keeper/keeper_test.go index 87e58bb28..ecab7b51f 100644 --- a/x/stablecoin/keeper/keeper_test.go +++ b/x/stablecoin/keeper/keeper_test.go @@ -3,12 +3,13 @@ package keeper_test import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/NibiruChain/nibiru/simapp" - "github.com/NibiruChain/nibiru/x/stablecoin/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + "github.com/NibiruChain/nibiru/x/stablecoin/types" ) // Params @@ -47,7 +48,7 @@ func TestGetAndSetParams(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) stableKeeper := nibiruApp.StablecoinKeeper params := tc.requiredParams() @@ -60,7 +61,7 @@ func TestGetAndSetParams(t *testing.T) { func TestGetAndSetParams_Errors(t *testing.T) { t.Run("Calling Get without setting causes a panic", func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(false) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(false) stableKeeper := nibiruApp.StablecoinKeeper require.Panics( diff --git a/x/stablecoin/keeper/mint_burn_stable_test.go b/x/stablecoin/keeper/mint_burn_stable_test.go index 27c5467d4..bc74a88f4 100644 --- a/x/stablecoin/keeper/mint_burn_stable_test.go +++ b/x/stablecoin/keeper/mint_burn_stable_test.go @@ -4,18 +4,19 @@ import ( "testing" "time" + simapp2 "github.com/NibiruChain/nibiru/simapp" + "github.com/NibiruChain/nibiru/x/common" pricefeedTypes "github.com/NibiruChain/nibiru/x/pricefeed/types" "github.com/NibiruChain/nibiru/x/stablecoin/types" - "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" - "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/NibiruChain/nibiru/x/testutil/sample" ) // ------------------------------------------------------------------ @@ -114,7 +115,7 @@ func TestMsgMintStableResponse_HappyPath(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) acc, _ := sdk.AccAddressFromBech32(tc.msgMint.Creator) oracle := sample.AccAddress() @@ -296,7 +297,7 @@ func TestMsgMintStableResponse_NotEnoughFunds(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) acc, _ := sdk.AccAddressFromBech32(tc.msgMint.Creator) oracle := sample.AccAddress() @@ -466,7 +467,7 @@ func TestMsgBurnResponse_NotEnoughFunds(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) acc, _ := sdk.AccAddressFromBech32(tc.msgBurn.Creator) oracle := sample.AccAddress() @@ -621,7 +622,7 @@ func TestMsgBurnResponse_HappyPath(t *testing.T) { for _, tc := range tests { tc := tc t.Run(tc.name, func(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp2.NewTestNibiruAppAndContext(true) acc, _ := sdk.AccAddressFromBech32(tc.msgBurn.Creator) oracle := sample.AccAddress() diff --git a/x/stablecoin/keeper/msg_server_test.go b/x/stablecoin/keeper/msg_server_test.go index 24e6c9d11..c44ae2bb9 100644 --- a/x/stablecoin/keeper/msg_server_test.go +++ b/x/stablecoin/keeper/msg_server_test.go @@ -3,10 +3,11 @@ package keeper_test import ( "testing" - sckeeper "github.com/NibiruChain/nibiru/x/stablecoin/keeper" - "github.com/NibiruChain/nibiru/x/testutil/testapp" + "github.com/NibiruChain/nibiru/simapp" "github.com/stretchr/testify/require" + + sckeeper "github.com/NibiruChain/nibiru/x/stablecoin/keeper" ) func TestNewMsgServerImpl(t *testing.T) { @@ -23,7 +24,7 @@ func TestNewMsgServerImpl(t *testing.T) { }) } - nibiruApp, _ := testapp.NewNibiruAppAndContext(true) + nibiruApp, _ := simapp.NewTestNibiruAppAndContext(true) testCases := []TestCase{ { name: "Default NibiruApp.StablecoinKeeper, should pass", diff --git a/x/stablecoin/keeper/params_test.go b/x/stablecoin/keeper/params_test.go index 4acf0868f..10e72b6da 100644 --- a/x/stablecoin/keeper/params_test.go +++ b/x/stablecoin/keeper/params_test.go @@ -4,15 +4,16 @@ import ( "fmt" "testing" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" "github.com/NibiruChain/nibiru/x/stablecoin/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestGetParams(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) stableKeeper := &nibiruApp.StablecoinKeeper params := types.DefaultParams() diff --git a/x/stablecoin/keeper/supply_test.go b/x/stablecoin/keeper/supply_test.go index 6366c8fa2..08667798a 100644 --- a/x/stablecoin/keeper/supply_test.go +++ b/x/stablecoin/keeper/supply_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + sdktypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" @@ -11,11 +13,10 @@ import ( "github.com/NibiruChain/nibiru/x/stablecoin/mock" "github.com/NibiruChain/nibiru/x/stablecoin/types" "github.com/NibiruChain/nibiru/x/testutil/sample" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) func TestKeeper_GetStableMarketCap(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(false) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(false) k := nibiruApp.StablecoinKeeper // We set some supply @@ -31,7 +32,7 @@ func TestKeeper_GetStableMarketCap(t *testing.T) { } func TestKeeper_GetGovMarketCap(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(false) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(false) keeper := nibiruApp.StablecoinKeeper poolAccountAddr := sample.AccAddress() @@ -67,7 +68,7 @@ func TestKeeper_GetGovMarketCap(t *testing.T) { } func TestKeeper_GetLiquidityRatio_AndBands(t *testing.T) { - nibiruApp, ctx := testapp.NewNibiruAppAndContext(false) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(false) keeper := nibiruApp.StablecoinKeeper poolAccountAddr := sample.AccAddress() diff --git a/x/stablecoin/types/codec.go b/x/stablecoin/types/codec.go index 93dc1c797..5057f13d0 100644 --- a/x/stablecoin/types/codec.go +++ b/x/stablecoin/types/codec.go @@ -15,9 +15,6 @@ func RegisterCodec(cdc *codec.LegacyAmino) { func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgMintStable{}, - ) - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgBurnStable{}, ) diff --git a/x/stablecoin/types/expected_keepers_test.go b/x/stablecoin/types/expected_keepers_test.go index 3a539d503..bc6ce3bd3 100644 --- a/x/stablecoin/types/expected_keepers_test.go +++ b/x/stablecoin/types/expected_keepers_test.go @@ -4,10 +4,11 @@ import ( "reflect" "testing" - sctypes "github.com/NibiruChain/nibiru/x/stablecoin/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" + "github.com/NibiruChain/nibiru/simapp" "github.com/stretchr/testify/assert" + + sctypes "github.com/NibiruChain/nibiru/x/stablecoin/types" ) // Verifies that the expected keepers (e.g. 'KeeperName') in x/stablecoin are @@ -19,7 +20,7 @@ func TestExpectedKeepers(t *testing.T) { appKeeper interface{} } - nibiruApp, _ := testapp.NewNibiruAppAndContext(true) + nibiruApp, _ := simapp.NewTestNibiruAppAndContext(true) testCases := []TestCase{ { name: "PricefeedKeeper from x/pricefeed", @@ -27,12 +28,12 @@ func TestExpectedKeepers(t *testing.T) { appKeeper: nibiruApp.PricefeedKeeper, }, { - name: "BankKeeper from the cosmos-sdk", + name: "bankKeeper from the cosmos-sdk", expectedKeeper: (*sctypes.BankKeeper)(nil), appKeeper: nibiruApp.BankKeeper, }, { - name: "AccountKeeper from the cosmos-sdk", + name: "accountKeeper from the cosmos-sdk", expectedKeeper: (*sctypes.AccountKeeper)(nil), appKeeper: nibiruApp.AccountKeeper, }, diff --git a/x/testutil/cli/network.go b/x/testutil/cli/network.go index 0f027dcd8..b3363dc6a 100644 --- a/x/testutil/cli/network.go +++ b/x/testutil/cli/network.go @@ -6,7 +6,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "net/http" "net/url" "os" @@ -15,6 +14,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" @@ -44,7 +45,6 @@ import ( "github.com/NibiruChain/nibiru/app" "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/testutil/testapp" ) // package-wide network lock to only allow one test network at a time @@ -127,7 +127,7 @@ type ( ) // BuildNetworkConfig returns a configuration for a local in-testing network -func BuildNetworkConfig(appGenesis app.GenesisState) Config { +func BuildNetworkConfig(appGenesis simapp.GenesisState) Config { encCfg := app.MakeTestEncodingConfig() return Config{ @@ -137,7 +137,7 @@ func BuildNetworkConfig(appGenesis app.GenesisState) Config { InterfaceRegistry: encCfg.InterfaceRegistry, AccountRetriever: authtypes.AccountRetriever{}, AppConstructor: func(val Validator) servertypes.Application { - return testapp.NewNibiruAppWithGenesis(appGenesis) + return simapp.NewTestNibiruAppWithGenesis(appGenesis) }, GenesisState: appGenesis, TimeoutCommit: time.Second / 2, @@ -160,13 +160,13 @@ func BuildNetworkConfig(appGenesis app.GenesisState) Config { } } -// New creates a new Network for integration tests. +// NewNetwork creates a new Network for integration tests. func NewNetwork(t *testing.T, cfg Config) *Network { // only one caller/test can create and use a network at a time t.Log("acquiring test network lock") lock.Lock() - baseDir, err := ioutil.TempDir(t.TempDir(), cfg.ChainID) + baseDir, err := os.MkdirTemp(t.TempDir(), cfg.ChainID) require.NoError(t, err) t.Logf("created temporary directory: %s", baseDir) diff --git a/x/testutil/cli/util.go b/x/testutil/cli/util.go index fd9e48987..735063eaf 100644 --- a/x/testutil/cli/util.go +++ b/x/testutil/cli/util.go @@ -6,11 +6,11 @@ import ( "path/filepath" "time" + "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/codec" tmtypes "github.com/tendermint/tendermint/abci/types" - "github.com/NibiruChain/nibiru/x/testutil/testapp" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server/api" servergrpc "github.com/cosmos/cosmos-sdk/server/grpc" @@ -183,7 +183,7 @@ func initGenFiles( bankGenState.Balances = append(bankGenState.Balances, genBalances...) cfg.GenesisState[banktypes.ModuleName] = cfg.Codec.MustMarshalJSON(&bankGenState) - cfg.GenesisState = testapp.NewTestGenesisState(cfg.Codec, cfg.GenesisState) + cfg.GenesisState = simapp.NewTestGenesisState(cfg.Codec, cfg.GenesisState) appGenStateJSON, err := json.MarshalIndent(cfg.GenesisState, "", " ") if err != nil { return cfg, err diff --git a/x/vpool/client/cli/cli_test.go b/x/vpool/client/cli/cli_test.go index 5b51e61a7..6b8632550 100644 --- a/x/vpool/client/cli/cli_test.go +++ b/x/vpool/client/cli/cli_test.go @@ -7,6 +7,8 @@ import ( "testing" "time" + "github.com/NibiruChain/nibiru/simapp" + "github.com/cosmos/cosmos-sdk/client/flags" sdktestutil "github.com/cosmos/cosmos-sdk/testutil" sdktestutilcli "github.com/cosmos/cosmos-sdk/testutil/cli" @@ -20,7 +22,6 @@ import ( "github.com/NibiruChain/nibiru/app" "github.com/NibiruChain/nibiru/x/common" testutilcli "github.com/NibiruChain/nibiru/x/testutil/cli" - "github.com/NibiruChain/nibiru/x/testutil/testapp" "github.com/NibiruChain/nibiru/x/vpool/client/cli" vpooltypes "github.com/NibiruChain/nibiru/x/vpool/types" ) @@ -41,7 +42,7 @@ func (s *VpoolCLISuite) SetupSuite() { app.SetPrefixes(app.AccountAddressPrefix) - genesisState := testapp.NewTestGenesisStateFromDefault() + genesisState := simapp.NewTestGenesisStateFromDefault() s.cfg = testutilcli.BuildNetworkConfig(genesisState) s.network = testutilcli.NewNetwork(s.T(), s.cfg) diff --git a/x/vpool/genesis_test.go b/x/vpool/genesis_test.go index 8f50916f6..262e7e9d3 100644 --- a/x/vpool/genesis_test.go +++ b/x/vpool/genesis_test.go @@ -3,11 +3,12 @@ package vpool_test import ( "testing" + "github.com/NibiruChain/nibiru/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/testutil/testapp" "github.com/NibiruChain/nibiru/x/vpool" "github.com/NibiruChain/nibiru/x/vpool/types" ) @@ -39,7 +40,7 @@ func TestGenesis(t *testing.T) { genesisState := types.GenesisState{Vpools: vpools} - nibiruApp, ctx := testapp.NewNibiruAppAndContext(true) + nibiruApp, ctx := simapp.NewTestNibiruAppAndContext(true) k := nibiruApp.VpoolKeeper vpool.InitGenesis(ctx, k, genesisState) From 756ebf11af4fa912cfbf6616af510b16fd25bda9 Mon Sep 17 00:00:00 2001 From: NibiruHeisenberg <101130700+NibiruHeisenberg@users.noreply.github.com> Date: Tue, 16 Aug 2022 14:25:19 -0400 Subject: [PATCH 7/7] Update CHANGELOG.md --- CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18e640b91..5d379a185 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,7 +40,9 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -[Unreleased] +## Unreleased + +## [v0.13.0](https://github.com/NibiruChain/nibiru/releases/tag/v0.13.0) - 2022-08-16 ### State Machine Breaking @@ -53,7 +55,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#795](https://github.com/NibiruChain/nibiru/pull/795) - integration tests run when PR is approved * [#826](https://github.com/NibiruChain/nibiru/pull/826) - create and push docker image on release - ### Improvements * [#798](https://github.com/NibiruChain/nibiru/pull/798) - fix integration tests caused by PR #786 @@ -68,7 +69,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#791](https://github.com/NibiruChain/nibiru/pull/791) Add the x/oracle module * [#811](https://github.com/NibiruChain/nibiru/pull/811) Return the index twap in `QueryPrice` cmd -* [#813](https://github.com/NibiruChain/nibiru/pull/813) - (vpool): Expose mark price, mark TWAP, index price, and k (swap invariant) in the all-pools query +* [#813](https://github.com/NibiruChain/nibiru/pull/813) - (vpool): Expose mark price, mark TWAP, index price, and k (swap invariant) in the all-pools query * [#816](https://github.com/NibiruChain/nibiru/pull/816) - Remove tobin tax from x/oracle * [#810](https://github.com/NibiruChain/nibiru/pull/810) - feat(x/perp): expose 'marginRatioIndex' and block number on QueryTraderPosition