From ee48cf581d020f28ed250a9c4c5d13338cdd94c1 Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 30 Jun 2022 10:43:18 -0400 Subject: [PATCH 001/376] chore: x/mint docs and clean up, excluding mint keeper (#1857) * chore: mint module docs and clean up * rename LasteHalvenEpoch to LastReductionEpoch * lint * revert proto comments * spec * try removing simulation * client module changes * client/rest * more proto fixes * avoid listing minting params in spec * Update proto/osmosis/mint/v1beta1/mint.proto Co-authored-by: Dev Ojha * update comment in hooks.go * Revert "try removing simulation" w/o Makefile change This reverts commit 5a06bf1af4d4a421e4890935e36ab4d11d69609c. * randomize mint gen state simulation * fix full sim tests * fix TestAppStateDeterminism * fix TestAppStateDeterminism * change expected epochIdentifier to day * address Dev's comments to hardcode certain parameters * Update x/mint/types/minter_test.go Co-authored-by: Dev Ojha * remove unused variable * Update proto/osmosis/mint/v1beta1/genesis.proto Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update proto/osmosis/mint/v1beta1/mint.proto Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update x/mint/types/hooks.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * make prot-all * remove unused Co-authored-by: Dev Ojha Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> --- Makefile | 1 - docs/core/proto-docs.md | 2 +- go.mod | 2 +- proto/osmosis/mint/v1beta1/genesis.proto | 11 +- proto/osmosis/mint/v1beta1/mint.proto | 42 +++-- proto/osmosis/mint/v1beta1/query.proto | 2 +- proto/osmosis/superfluid/query.proto | 19 +-- x/mint/{spec => }/README.md | 107 ++++-------- x/mint/client/cli/cli_test.go | 1 - x/mint/client/rest/grpc_query_test.go | 1 - x/mint/keeper/genesis.go | 6 +- x/mint/keeper/genesis_test.go | 2 +- x/mint/keeper/hooks.go | 16 +- x/mint/keeper/hooks_test.go | 33 ++-- x/mint/keeper/keeper.go | 15 +- x/mint/module.go | 6 +- x/mint/simulation/export_test.go | 10 ++ x/mint/simulation/genesis.go | 169 ++++++++++++++++--- x/mint/simulation/genesis_test.go | 63 ++++++- x/mint/types/events.go | 10 +- x/mint/types/expected_keepers.go | 1 - x/mint/types/export_test.go | 6 + x/mint/types/genesis.go | 16 +- x/mint/types/genesis.pb.go | 49 +++--- x/mint/types/hooks.go | 7 +- x/mint/types/keys.go | 18 +- x/mint/types/mint.pb.go | 42 +++-- x/mint/types/minter.go | 18 +- x/mint/types/minter_test.go | 52 +++++- x/mint/types/params.go | 11 +- x/mint/types/query.pb.go | 4 +- x/pool-incentives/keeper/hooks.go | 2 + x/superfluid/types/query.pb.go | 206 ++++++++++++----------- 33 files changed, 605 insertions(+), 345 deletions(-) rename x/mint/{spec => }/README.md (79%) create mode 100644 x/mint/simulation/export_test.go create mode 100644 x/mint/types/export_test.go diff --git a/Makefile b/Makefile index 1210ead7ae2..5c759929f7b 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,5 @@ #!/usr/bin/make -f -PACKAGES_SIMTEST=$(shell go list ./... | grep '/simulation') VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//') COMMIT := $(shell git log -1 --format='%H') LEDGER_ENABLED ?= true diff --git a/docs/core/proto-docs.md b/docs/core/proto-docs.md index eb34b54b013..8b6c79f08d8 100644 --- a/docs/core/proto-docs.md +++ b/docs/core/proto-docs.md @@ -2626,7 +2626,7 @@ GenesisState defines the mint module's genesis state. | ----- | ---- | ----- | ----------- | | `minter` | [Minter](#osmosis.mint.v1beta1.Minter) | | minter is a space for holding current rewards information. | | `params` | [Params](#osmosis.mint.v1beta1.Params) | | params defines all the paramaters of the module. | -| `halven_started_epoch` | [int64](#int64) | | current halven period start epoch | +| `reduction_started_epoch` | [int64](#int64) | | current reduction period start epoch | diff --git a/go.mod b/go.mod index 192e7445dee..c2c941e6294 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.18 require ( github.com/CosmWasm/wasmd v0.24.0 github.com/cosmos/cosmos-proto v1.0.0-alpha7 - github.com/cosmos/cosmos-sdk v0.45.5 + github.com/cosmos/cosmos-sdk v0.45.6 github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/iavl v0.17.3 github.com/cosmos/ibc-go/v3 v3.0.0 diff --git a/proto/osmosis/mint/v1beta1/genesis.proto b/proto/osmosis/mint/v1beta1/genesis.proto index 3a9112b639a..80ebfa46bc7 100644 --- a/proto/osmosis/mint/v1beta1/genesis.proto +++ b/proto/osmosis/mint/v1beta1/genesis.proto @@ -8,13 +8,14 @@ option go_package = "github.com/osmosis-labs/osmosis/v7/x/mint/types"; // GenesisState defines the mint module's genesis state. message GenesisState { - // minter is a space for holding current rewards information. + // minter is an abstraction for holding current rewards information. Minter minter = 1 [ (gogoproto.nullable) = false ]; - // params defines all the paramaters of the module. + // params defines all the paramaters of the mint module. Params params = 2 [ (gogoproto.nullable) = false ]; - // current halven period start epoch - int64 halven_started_epoch = 3 - [ (gogoproto.moretags) = "yaml:\"halven_started_epoch\"" ]; + // reduction_started_epoch is the first epoch in which the reduction of mint + // begins. + int64 reduction_started_epoch = 3 + [ (gogoproto.moretags) = "yaml:\"reduction_started_epoch\"" ]; } diff --git a/proto/osmosis/mint/v1beta1/mint.proto b/proto/osmosis/mint/v1beta1/mint.proto index 95490b849a5..ebbca045887 100644 --- a/proto/osmosis/mint/v1beta1/mint.proto +++ b/proto/osmosis/mint/v1beta1/mint.proto @@ -10,7 +10,7 @@ import "google/protobuf/duration.proto"; // Minter represents the minting state. message Minter { - // current epoch provisions + // epoch_provisions represent rewards for the current epoch. string epoch_provisions = 1 [ (gogoproto.moretags) = "yaml:\"epoch_provisions\"", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", @@ -18,6 +18,9 @@ message Minter { ]; } +// WeightedAddress represents an address with a weight assigned to it. +// The weight is used to determine the proportion of the total minted +// tokens to be minted to the address. message WeightedAddress { string address = 1 [ (gogoproto.moretags) = "yaml:\"address\"" ]; string weight = 2 [ @@ -27,29 +30,32 @@ message WeightedAddress { ]; } +// DistributionProportions defines the distribution proportions of the minted +// denom. In other words, defines which stakeholders will receive the minted +// denoms and how much. message DistributionProportions { - // staking defines the proportion of the minted minted_denom that is to be + // staking defines the proportion of the minted mint_denom that is to be // allocated as staking rewards. string staking = 1 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.moretags) = "yaml:\"staking\"", (gogoproto.nullable) = false ]; - // pool_incentives defines the proportion of the minted minted_denom that is + // pool_incentives defines the proportion of the minted mint_denom that is // to be allocated as pool incentives. string pool_incentives = 2 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.moretags) = "yaml:\"pool_incentives\"", (gogoproto.nullable) = false ]; - // developer_rewards defines the proportion of the minted minted_denom that is + // developer_rewards defines the proportion of the minted mint_denom that is // to be allocated to developer rewards address. string developer_rewards = 3 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.moretags) = "yaml:\"developer_rewards\"", (gogoproto.nullable) = false ]; - // community_pool defines the proportion of the minted minted_denom that is + // community_pool defines the proportion of the minted mint_denom that is // to be allocated to the community pool. string community_pool = 4 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", @@ -58,39 +64,47 @@ message DistributionProportions { ]; } -// Params holds parameters for the mint module. +// Params holds parameters for the x/mint module. message Params { option (gogoproto.goproto_stringer) = false; - // type of coin to mint + // mint_denom is the denom of the coin to mint. string mint_denom = 1; - // epoch provisions from the first epoch + // genesis_epoch_provisions epoch provisions from the first epoch. string genesis_epoch_provisions = 2 [ (gogoproto.moretags) = "yaml:\"genesis_epoch_provisions\"", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; - // mint epoch identifier + // epoch_identifier mint epoch identifier e.g. (day, week). string epoch_identifier = 3 [ (gogoproto.moretags) = "yaml:\"epoch_identifier\"" ]; - // number of epochs take to reduce rewards + // reduction_period_in_epochs the number of epochs it takes + // to reduce the rewards. int64 reduction_period_in_epochs = 4 [ (gogoproto.moretags) = "yaml:\"reduction_period_in_epochs\"" ]; - // reduction multiplier to execute on each period + // reduction_factor is the reduction multiplier to execute + // at the end of each period set by reduction_period_in_epochs. string reduction_factor = 5 [ (gogoproto.moretags) = "yaml:\"reduction_factor\"", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; - // distribution_proportions defines the proportion of the minted denom + // distribution_proportions defines the distribution proportions of the minted + // denom. In other words, defines which stakeholders will receive the minted + // denoms and how much. DistributionProportions distribution_proportions = 6 [ (gogoproto.nullable) = false ]; - // address to receive developer rewards + // weighted_developer_rewards_receivers is the address to receive developer + // rewards with weights assignedt to each address. The final amount that each + // address receives is: epoch_provisions * + // distribution_proportions.developer_rewards * Address's Weight. repeated WeightedAddress weighted_developer_rewards_receivers = 7 [ (gogoproto.moretags) = "yaml:\"developer_rewards_receiver\"", (gogoproto.nullable) = false ]; - // start epoch to distribute minting rewards + // minting_rewards_distribution_start_epoch start epoch to distribute minting + // rewards int64 minting_rewards_distribution_start_epoch = 8 [ (gogoproto.moretags) = "yaml:\"minting_rewards_distribution_start_epoch\"" ]; diff --git a/proto/osmosis/mint/v1beta1/query.proto b/proto/osmosis/mint/v1beta1/query.proto index 83c55a5e0ad..90bbdfb252d 100644 --- a/proto/osmosis/mint/v1beta1/query.proto +++ b/proto/osmosis/mint/v1beta1/query.proto @@ -14,7 +14,7 @@ service Query { option (google.api.http).get = "/osmosis/mint/v1beta1/params"; } - // EpochProvisions current minting epoch provisions value. + // EpochProvisions returns the current minting epoch provisions value. rpc EpochProvisions(QueryEpochProvisionsRequest) returns (QueryEpochProvisionsResponse) { option (google.api.http).get = "/osmosis/mint/v1beta1/epoch_provisions"; diff --git a/proto/osmosis/superfluid/query.proto b/proto/osmosis/superfluid/query.proto index 65c18b34b05..aac8702d5b4 100644 --- a/proto/osmosis/superfluid/query.proto +++ b/proto/osmosis/superfluid/query.proto @@ -114,10 +114,12 @@ service Query { // "/osmosis/superfluid/v1beta1/superfluid_unbondings_by_validator_denom"; // } -// Returns the specified delegations for a specific delegator - rpc TotalDelegationByDelegator (QueryTotalDelegationByDelegatorRequest) returns (QueryTotalDelegationByDelegatorResponse) { - option (google.api.http).get = "/osmosis/superfluid/v1beta1/" - "total_delegation_by_delegator/{delegator_address}"; + // Returns the specified delegations for a specific delegator + rpc TotalDelegationByDelegator(QueryTotalDelegationByDelegatorRequest) + returns (QueryTotalDelegationByDelegatorResponse) { + option (google.api.http).get = + "/osmosis/superfluid/v1beta1/" + "total_delegation_by_delegator/{delegator_address}"; } } @@ -265,17 +267,14 @@ message EstimateSuperfluidDelegatedAmountByValidatorDenomResponse { // ]; // } -message QueryTotalDelegationByDelegatorRequest { - string delegator_address = 1; -} +message QueryTotalDelegationByDelegatorRequest { string delegator_address = 1; } message QueryTotalDelegationByDelegatorResponse { repeated SuperfluidDelegationRecord superfluid_delegation_records = 1 [ (gogoproto.nullable) = false ]; - repeated cosmos.staking.v1beta1.DelegationResponse delegation_response = 2 [ - (gogoproto.nullable) = false - ]; + repeated cosmos.staking.v1beta1.DelegationResponse delegation_response = 2 + [ (gogoproto.nullable) = false ]; repeated cosmos.base.v1beta1.Coin total_delegated_coins = 3 [ (gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" diff --git a/x/mint/spec/README.md b/x/mint/README.md similarity index 79% rename from x/mint/spec/README.md rename to x/mint/README.md index c4b30dca5c1..2ba6a0bdd66 100644 --- a/x/mint/spec/README.md +++ b/x/mint/README.md @@ -1,11 +1,13 @@ # Mint -The ```mint``` module is responsible for creating tokens in a flexible way to reward -validators, incentivize providing pool liquidity, provide funds for Osmosis governance, and pay developers to maintain and improve Osmosis. +The `mint` module is responsible for creating tokens in a flexible way to reward +validators, incentivize providing pool liquidity, provide funds for Osmosis governance, +and pay developers to maintain and improve Osmosis. -The module is also responsible for reducing the token creation and distribution by a set amount and a set period of time until it reaches its maximum supply (see ```reduction_factor``` and ```reduction_period_in_epochs```) +The module is also responsible for reducing the token creation and distribution by a set period +until it reaches its maximum supply (see `reduction_factor` and `reduction_period_in_epochs`) -Module uses time basis epochs supported by ```epochs``` module. +The module uses time basis epochs supported by the `epochs` module. ## Contents @@ -23,19 +25,19 @@ The `x/mint` module is designed to handle the regular printing of new tokens within a chain. The design taken within Osmosis is to - Mint new tokens once per epoch (default one week) -- To have a "Reductioning factor" every period, which reduces the - amount of rewards per epoch. (default: period is 3 years, where a +- To have a "Reductioning factor" every period, which reduces the number of + rewards per epoch. (default: period is 3 years, where a year is 52 epochs. The next period's rewards are 2/3 of the prior period's rewards) -### Reductioning factor +### Reduction factor -This is a generalization over the Bitcoin style halvenings. Every year, -the amount of rewards issued per week will reduce by a governance -specified factor, instead of a fixed `1/2`. So +This is a generalization over the Bitcoin-style halvenings. Every year, the number + of rewards issued per week will reduce by a governance-specified +factor, instead of a fixed `1/2`. So `RewardsPerEpochNextPeriod = ReductionFactor * CurrentRewardsPerEpoch)`. When `ReductionFactor = 1/2`, the Bitcoin halvenings are recreated. We -default to having a reduction factor of `2/3`, and thus reduce rewards +default to having a reduction factor of `2/3` and thus reduce rewards at the end of every year by `33%`. The implication of this is that the total supply is finite, according to @@ -47,7 +49,7 @@ the following formula: ### Minter -The minter is a space for holding current rewards information. +The [`Minter`](https://github.com/osmosis-labs/osmosis/blob/cbb683e8395655042b4421355cd54a8c96bfa507/x/mint/types/mint.pb.go#L30) is an abstraction for holding current rewards information. ```go type Minter struct { @@ -57,65 +59,33 @@ type Minter struct { ### Params -Minting params are held in the global params store. +Minting [`Params`](https://github.com/osmosis-labs/osmosis/blob/cbb683e8395655042b4421355cd54a8c96bfa507/x/mint/types/mint.pb.go#L168) are held in the global params store. -```go -type Params struct { - MintDenom string // type of coin to mint - GenesisEpochProvisions sdk.Dec // initial epoch provisions at genesis - EpochIdentifier string // identifier of epoch - ReductionPeriodInEpochs int64 // number of epochs between reward reductions - ReductionFactor sdk.Dec // reduction multiplier to execute on each period - DistributionProportions DistributionProportions // distribution_proportions defines the proportion of the minted denom - WeightedDeveloperRewardsReceivers []WeightedAddress // address to receive developer rewards - MintingRewardsDistributionStartEpoch int64 // start epoch to distribute minting rewards -} -``` +### LastReductionEpoch -### LastHalvenEpoch - -Last halven epoch stores the epoch number when the last reduction of +Last reduction epoch stores the epoch number when the last reduction of coin mint amount per epoch has happened. -**TODO:** - -- Update the name to LastReductionEpoch as the reduction amount could - be set by governance. - ## Begin-Epoch -Minting parameters are recalculated and inflation paid at the beginning -of each epoch. An epoch is signalled by x/epochs +Minting parameters are recalculated and inflation is paid at the beginning +of each epoch. An epoch is signaled by x/epochs ### NextEpochProvisions The target epoch provision is recalculated on each reduction period -(default 3 years). At the time of reduction, the current provision is -multiplied by reduction factor (default `2/3`), to calculate the +(default 3 years). At the time of the reduction, the current provision is +multiplied by the reduction factor (default `2/3`), to calculate the provisions for the next epoch. Consequently, the rewards of the next -period will be lowered by `1 - reduction factor`. - -``` go -func (m Minter) NextEpochProvisions(params Params) sdk.Dec { - return m.EpochProvisions.Mul(params.ReductionFactor) -} -``` +period will be lowered by a `1` - reduction factor. ### EpochProvision Calculate the provisions generated for each epoch based on current epoch provisions. The provisions are then minted by the `mint` module's `ModuleMinterAccount`. These rewards are transferred to a -`FeeCollector`, which handles distributing the rewards per the chains -needs. (See TODO.md for details) This fee collector is specified as the -`auth` module's `FeeCollector` `ModuleAccount`. - -``` go -func (m Minter) EpochProvision(params Params) sdk.Coin { - provisionAmt := m.EpochProvisions.QuoInt(sdk.NewInt(int64(params.EpochsPerYear))) - return sdk.NewCoin(params.MintDenom, provisionAmt.TruncateInt()) -} -``` +`FeeCollector`, which handles distributing the rewards per the chain's needs. +This fee collector is specified as the `auth` module's `FeeCollector` `ModuleAccount`. ## Network Parameters @@ -139,10 +109,10 @@ The minting module contains the following parameters: Below are all the network parameters for the ```mint``` module: - **```mint_denom```** - Token type being minted -- **```genesis_epoch_provisions```** - Amount of tokens generated at epoch to the distribution categories (see distribution_proportions) +- **```genesis_epoch_provisions```** - Amount of tokens generated at the epoch to the distribution categories (see distribution_proportions) - **```epoch_identifier```** - Type of epoch that triggers token issuance (day, week, etc.) - **```reduction_period_in_epochs```** - How many epochs must occur before implementing the reduction factor -- **```reduction_factor```** - What the total token issuance factor will reduce by after reduction period passes (if set to 66.66%, token issuance will reduce by 1/3) +- **```reduction_factor```** - What the total token issuance factor will reduce by after the reduction period passes (if set to 66.66%, token issuance will reduce by 1/3) - **```distribution_proportions```** - Categories in which the specified proportion of newly released tokens are distributed to - **```staking```** - Proportion of minted funds to incentivize staking OSMO - **```pool_incentives```** - Proportion of minted funds to incentivize pools on Osmosis @@ -154,21 +124,16 @@ Below are all the network parameters for the ```mint``` module: **Notes** 1. `mint_denom` defines denom for minting token - uosmo -2. `genesis_epoch_provisions` provides minting tokens per epoch at - genesis. -3. `epoch_identifier` defines the epoch identifier to be used for mint - module e.g. "weekly" -4. `reduction_period_in_epochs` defines the number of epochs to pass to - reduce mint amount -5. `reduction_factor` defines the reduction factor of tokens at every - `reduction_period_in_epochs` -6. `distribution_proportions` defines distribution rules for minted - tokens, when developer rewards address is empty, it distribute - tokens to community pool. -7. `weighted_developer_rewards_receivers` provides the addresses that - receives developer rewards by weight -8. `minting_rewards_distribution_start_epoch` defines the start epoch - of minting to make sure minting start after initial pools are set +2. `genesis_epoch_provisions` provides minting tokens per epoch at genesis. +3. `epoch_identifier` defines the epoch identifier to be used for the mint module e.g. "weekly" +4. `reduction_period_in_epochs` defines the number of epochs to pass to reduce the mint amount +5. `reduction_factor` defines the reduction factor of tokens at every `reduction_period_in_epochs` +6. `distribution_proportions` defines distribution rules for minted tokens, when the developer + rewards address is empty, it distributes tokens to the community pool. +7. `weighted_developer_rewards_receivers` provides the addresses that receive developer + rewards by weight +8. `minting_rewards_distribution_start_epoch` defines the start epoch of minting to make sure + minting start after initial pools are set ## Events diff --git a/x/mint/client/cli/cli_test.go b/x/mint/client/cli/cli_test.go index c9c2061806f..f4e926ddd81 100644 --- a/x/mint/client/cli/cli_test.go +++ b/x/mint/client/cli/cli_test.go @@ -1,5 +1,4 @@ //go:build norace -// +build norace package cli_test diff --git a/x/mint/client/rest/grpc_query_test.go b/x/mint/client/rest/grpc_query_test.go index e1334390367..b7aa537000a 100644 --- a/x/mint/client/rest/grpc_query_test.go +++ b/x/mint/client/rest/grpc_query_test.go @@ -1,5 +1,4 @@ //go:build norace -// +build norace package rest_test diff --git a/x/mint/keeper/genesis.go b/x/mint/keeper/genesis.go index db27bf7d21a..b794a64c0fc 100644 --- a/x/mint/keeper/genesis.go +++ b/x/mint/keeper/genesis.go @@ -19,13 +19,13 @@ func (k Keeper) InitGenesis(ctx sdk.Context, ak types.AccountKeeper, bk types.Ba bk.AddSupplyOffset(ctx, data.Params.MintDenom, sdk.NewInt(225_000_000_000_000).Neg()) } - k.SetLastHalvenEpochNum(ctx, data.HalvenStartedEpoch) + k.SetLastReductionEpochNum(ctx, data.ReductionStartedEpoch) } // ExportGenesis returns a GenesisState for a given context and keeper. func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { minter := k.GetMinter(ctx) params := k.GetParams(ctx) - lastHalvenEpoch := k.GetLastHalvenEpochNum(ctx) - return types.NewGenesisState(minter, params, lastHalvenEpoch) + lastReductionEpoch := k.GetLastReductionEpochNum(ctx) + return types.NewGenesisState(minter, params, lastReductionEpoch) } diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index 17d1e4a95a7..44b79563e11 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -25,5 +25,5 @@ func TestMintInitGenesis(t *testing.T) { expectedVestingCoins, ok := sdk.NewIntFromString("225000000000000") require.True(t, ok) require.Equal(t, expectedVestingCoins, initialVestingCoins.Amount) - require.Equal(t, int64(0), app.MintKeeper.GetLastHalvenEpochNum(ctx)) + require.Equal(t, int64(0), app.MintKeeper.GetLastReductionEpochNum(ctx)) } diff --git a/x/mint/keeper/hooks.go b/x/mint/keeper/hooks.go index bce090cbafe..9c3e520e7fd 100644 --- a/x/mint/keeper/hooks.go +++ b/x/mint/keeper/hooks.go @@ -21,20 +21,22 @@ func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumb if epochNumber < params.MintingRewardsDistributionStartEpoch { return } else if epochNumber == params.MintingRewardsDistributionStartEpoch { - k.SetLastHalvenEpochNum(ctx, epochNumber) + k.SetLastReductionEpochNum(ctx, epochNumber) } // fetch stored minter & params minter := k.GetMinter(ctx) params := k.GetParams(ctx) // Check if we have hit an epoch where we update the inflation parameter. - // Since epochs only update based on BFT time data, it is safe to store the "halvening period time" - // in terms of the number of epochs that have transpired. - if epochNumber >= k.GetParams(ctx).ReductionPeriodInEpochs+k.GetLastHalvenEpochNum(ctx) { - // Halven the reward per halven period + // We measure time between reductions in number of epochs. + // This avoids issues with measuring in block numbers, as epochs have fixed intervals, with very + // low variance at the relevant sizes. As a result, it is safe to store the epoch number + // of the last reduction to be later retrieved for comparison. + if epochNumber >= k.GetParams(ctx).ReductionPeriodInEpochs+k.GetLastReductionEpochNum(ctx) { + // Reduce the reward per reduction period minter.EpochProvisions = minter.NextEpochProvisions(params) k.SetMinter(ctx, minter) - k.SetLastHalvenEpochNum(ctx, epochNumber) + k.SetLastReductionEpochNum(ctx, epochNumber) } // mint coins, update supply @@ -59,7 +61,7 @@ func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumb ctx.EventManager().EmitEvent( sdk.NewEvent( - types.EventTypeMint, + types.ModuleName, sdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprintf("%d", epochNumber)), sdk.NewAttribute(types.AttributeKeyEpochProvisions, minter.EpochProvisions.String()), sdk.NewAttribute(sdk.AttributeKeyAmount, mintedCoin.Amount.String()), diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index 91f75affda6..74571d0bafa 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -4,13 +4,14 @@ import ( "testing" "time" - osmoapp "github.com/osmosis-labs/osmosis/v7/app" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + osmoapp "github.com/osmosis-labs/osmosis/v7/app" + lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -42,9 +43,9 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { ctx, sdk.NewCoin("stake", sdk.NewInt(156*500000*2))) height := int64(1) - lastHalvenPeriod := app.MintKeeper.GetLastHalvenEpochNum(ctx) + lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) // correct rewards - for ; height < lastHalvenPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { + for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) devRewardsModuleOrigin := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) @@ -81,10 +82,10 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - lastHalvenPeriod = app.MintKeeper.GetLastHalvenEpochNum(ctx) - require.Equal(t, lastHalvenPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) + lastReductionPeriod = app.MintKeeper.GetLastReductionEpochNum(ctx) + require.Equal(t, lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) - for ; height < lastHalvenPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { + for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) devRewardsModuleOrigin := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) @@ -125,9 +126,9 @@ func TestMintedCoinDistributionWhenDevRewardsAddressEmpty(t *testing.T) { ctx, sdk.NewCoin("stake", sdk.NewInt(156*500000*2))) height := int64(1) - lastHalvenPeriod := app.MintKeeper.GetLastHalvenEpochNum(ctx) + lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) // correct rewards - for ; height < lastHalvenPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { + for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) devRewardsModuleOrigin := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) @@ -152,10 +153,10 @@ func TestMintedCoinDistributionWhenDevRewardsAddressEmpty(t *testing.T) { app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - lastHalvenPeriod = app.MintKeeper.GetLastHalvenEpochNum(ctx) - require.Equal(t, lastHalvenPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) + lastReductionPeriod = app.MintKeeper.GetLastReductionEpochNum(ctx) + require.Equal(t, lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) - for ; height < lastHalvenPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { + for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) devRewardsModuleOrigin := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) @@ -214,9 +215,9 @@ func TestEndOfEpochNoDistributionWhenIsNotYetStartTime(t *testing.T) { require.NotEqual(t, sdk.DecCoins{}, app.DistrKeeper.GetFeePool(ctx).CommunityPool, "Tokens to community pool at start distribution epoch") - // halven period should be set to mintParams.MintingRewardsDistributionStartEpoch - lastHalvenPeriod := app.MintKeeper.GetLastHalvenEpochNum(ctx) - require.Equal(t, lastHalvenPeriod, mintParams.MintingRewardsDistributionStartEpoch) + // reduction period should be set to mintParams.MintingRewardsDistributionStartEpoch + lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) + require.Equal(t, lastReductionPeriod, mintParams.MintingRewardsDistributionStartEpoch) } func setupGaugeForLPIncentives(t *testing.T, app *osmoapp.OsmosisApp, ctx sdk.Context) { diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index dcb08f27c96..3ae53908c10 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -1,9 +1,10 @@ package keeper import ( + "github.com/tendermint/tendermint/libs/log" + "github.com/osmosis-labs/osmosis/v7/x/mint/types" poolincentivestypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" - "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -92,10 +93,10 @@ func (k *Keeper) SetHooks(h types.MintHooks) *Keeper { return k } -// GetLastHalvenEpochNum returns last halven epoch number. -func (k Keeper) GetLastHalvenEpochNum(ctx sdk.Context) int64 { +// GetLastReductionEpochNum returns last reduction epoch number. +func (k Keeper) GetLastReductionEpochNum(ctx sdk.Context) int64 { store := ctx.KVStore(k.storeKey) - b := store.Get(types.LastHalvenEpochKey) + b := store.Get(types.LastReductionEpochKey) if b == nil { return 0 } @@ -103,10 +104,10 @@ func (k Keeper) GetLastHalvenEpochNum(ctx sdk.Context) int64 { return int64(sdk.BigEndianToUint64(b)) } -// SetLastHalvenEpochNum set last halven epoch number. -func (k Keeper) SetLastHalvenEpochNum(ctx sdk.Context, epochNum int64) { +// SetLastReductionEpochNum set last reduction epoch number. +func (k Keeper) SetLastReductionEpochNum(ctx sdk.Context, epochNum int64) { store := ctx.KVStore(k.storeKey) - store.Set(types.LastHalvenEpochKey, sdk.Uint64ToBigEndian(uint64(epochNum))) + store.Set(types.LastReductionEpochKey, sdk.Uint64ToBigEndian(uint64(epochNum))) } // get the minter. diff --git a/x/mint/module.go b/x/mint/module.go index 8cb8d6c2f1f..54a123ec844 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -162,6 +162,9 @@ func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Validato return []abci.ValidatorUpdate{} } +// ConsensusVersion implements AppModule/ConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return 1 } + // ___________________________________________________________________________ // AppModuleSimulation functions @@ -190,6 +193,3 @@ func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { func (AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { return nil } - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } diff --git a/x/mint/simulation/export_test.go b/x/mint/simulation/export_test.go new file mode 100644 index 00000000000..4e7719ebdaf --- /dev/null +++ b/x/mint/simulation/export_test.go @@ -0,0 +1,10 @@ +package simulation + +const ( + ExpectedEpochIdentifier = epochIdentifier +) + +var ( + ExpectedDistributionProportions = distributionProportions + ExpectedDevRewardReceivers = weightedDevRewardReceivers +) diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index 1aa8a68b278..f11118c7943 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -5,6 +5,7 @@ package simulation import ( "encoding/json" "fmt" + "math/rand" "github.com/osmosis-labs/osmosis/v7/x/mint/types" @@ -12,39 +13,163 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" ) +// Simulation parameter constants. +const ( + epochProvisionsKey = "genesis_epoch_provisions" + epochIdentifierKey = "epoch_identifier" + reductionFactorKey = "reduction_factor" + reductionPeriodInEpochsKey = "reduction_period_in_epochs" + + stakingDistributionProportionKey = "staking_distribution_proportion" + poolIncentivesDistributionProportionKey = "pool_incentives_distribution_proportion" + developerRewardsDistributionProportionKey = "developer_rewards_distribution_proportion" + communityPoolDistributionProportionKey = "community_pool_distribution_proportion" + weightedDevRewardReceiversKey = "weighted_developer_rewards_receivers" + mintingRewardsDistributionStartEpochKey = "minting_rewards_distribution_start_epoch" + + epochIdentifier = "day" + maxInt64 = int(^uint(0) >> 1) +) + +var ( + // Taken from: // https://github.com/osmosis-labs/networks/raw/main/osmosis-1/genesis.json + distributionProportions = types.DistributionProportions{ + Staking: sdk.NewDecWithPrec(25, 2), + PoolIncentives: sdk.NewDecWithPrec(45, 2), + DeveloperRewards: sdk.NewDecWithPrec(25, 2), + CommunityPool: sdk.NewDecWithPrec(05, 2), + } + weightedDevRewardReceivers = []types.WeightedAddress{ + { + Address: "osmo14kjcwdwcqsujkdt8n5qwpd8x8ty2rys5rjrdjj", + Weight: sdk.NewDecWithPrec(2887, 4), + }, + { + Address: "osmo1gw445ta0aqn26suz2rg3tkqfpxnq2hs224d7gq", + Weight: sdk.NewDecWithPrec(229, 3), + }, + { + Address: "osmo13lt0hzc6u3htsk7z5rs6vuurmgg4hh2ecgxqkf", + Weight: sdk.NewDecWithPrec(1625, 4), + }, + { + Address: "osmo1kvc3he93ygc0us3ycslwlv2gdqry4ta73vk9hu", + Weight: sdk.NewDecWithPrec(109, 3), + }, + { + Address: "osmo19qgldlsk7hdv3ddtwwpvzff30pxqe9phq9evxf", + Weight: sdk.NewDecWithPrec(995, 3).Quo(sdk.NewDec(10)), // 0.0995 + }, + { + Address: "osmo19fs55cx4594een7qr8tglrjtt5h9jrxg458htd", + Weight: sdk.NewDecWithPrec(6, 1).Quo(sdk.NewDec(10)), // 0.06 + }, + { + Address: "osmo1ssp6px3fs3kwreles3ft6c07mfvj89a544yj9k", + Weight: sdk.NewDecWithPrec(15, 2).Quo(sdk.NewDec(10)), // 0.015 + }, + { + Address: "osmo1c5yu8498yzqte9cmfv5zcgtl07lhpjrj0skqdx", + Weight: sdk.NewDecWithPrec(1, 1).Quo(sdk.NewDec(10)), // 0.01 + }, + { + Address: "osmo1yhj3r9t9vw7qgeg22cehfzj7enwgklw5k5v7lj", + Weight: sdk.NewDecWithPrec(75, 2).Quo(sdk.NewDec(100)), // 0.0075 + }, + { + Address: "osmo18nzmtyn5vy5y45dmcdnta8askldyvehx66lqgm", + Weight: sdk.NewDecWithPrec(7, 1).Quo(sdk.NewDec(100)), // 0.007 + }, + { + Address: "osmo1z2x9z58cg96ujvhvu6ga07yv9edq2mvkxpgwmc", + Weight: sdk.NewDecWithPrec(5, 1).Quo(sdk.NewDec(100)), // 0.005 + }, + { + Address: "osmo1tvf3373skua8e6480eyy38avv8mw3hnt8jcxg9", + Weight: sdk.NewDecWithPrec(25, 2).Quo(sdk.NewDec(100)), // 0.0025 + }, + { + Address: "osmo1zs0txy03pv5crj2rvty8wemd3zhrka2ne8u05n", + Weight: sdk.NewDecWithPrec(25, 2).Quo(sdk.NewDec(100)), // 0.0025 + }, + { + Address: "osmo1djgf9p53n7m5a55hcn6gg0cm5mue4r5g3fadee", + Weight: sdk.NewDecWithPrec(1, 1).Quo(sdk.NewDec(100)), // 0.001 + }, + { + Address: "osmo1488zldkrn8xcjh3z40v2mexq7d088qkna8ceze", + Weight: sdk.NewDecWithPrec(8, 1).Quo(sdk.NewDec(1000)), // 0.0008 + }, + } +) + // RandomizedGenState generates a random GenesisState for mint. func RandomizedGenState(simState *module.SimulationState) { - // minter + var epochProvisions sdk.Dec + simState.AppParams.GetOrGenerate( + simState.Cdc, epochProvisionsKey, &epochProvisions, simState.Rand, + func(r *rand.Rand) { epochProvisions = genEpochProvisions(r) }, + ) + + var reductionFactor sdk.Dec + simState.AppParams.GetOrGenerate( + simState.Cdc, reductionFactorKey, &reductionFactor, simState.Rand, + func(r *rand.Rand) { reductionFactor = genReductionFactor(r) }, + ) - // var maxRewardPerEpoch sdk.Dec - // simState.AppParams.GetOrGenerate( - // simState.Cdc, MaxRewardPerEpoch, &maxRewardPerEpoch, simState.Rand, - // func(r *rand.Rand) { maxRewardPerEpoch = GenMaxRewardPerEpoch(r) }, - // ) + var reductionPeriodInEpochs int64 + simState.AppParams.GetOrGenerate( + simState.Cdc, reductionPeriodInEpochsKey, &reductionPeriodInEpochs, simState.Rand, + func(r *rand.Rand) { reductionPeriodInEpochs = genReductionPeriodInEpochs(r) }, + ) - // var minRewardPerEpoch sdk.Dec - // simState.AppParams.GetOrGenerate( - // simState.Cdc, MinRewardPerEpoch, &minRewardPerEpoch, simState.Rand, - // func(r *rand.Rand) { minRewardPerEpoch = GenMinRewardPerEpoch(r) }, - // ) - // Leaving as sample code + var mintintRewardsDistributionStartEpoch int64 + simState.AppParams.GetOrGenerate( + simState.Cdc, mintingRewardsDistributionStartEpochKey, &mintintRewardsDistributionStartEpoch, simState.Rand, + func(r *rand.Rand) { mintintRewardsDistributionStartEpoch = genMintintRewardsDistributionStartEpoch(r) }, + ) + + reductionStartedEpoch := genReductionStartedEpoch(simState.Rand) mintDenom := sdk.DefaultBondDenom - epochProvisions := sdk.NewDec(500000) // TODO: Randomize this - params := types.NewParams(mintDenom, epochProvisions, "week", sdk.NewDecWithPrec(5, 1), 156, types.DistributionProportions{ - Staking: sdk.NewDecWithPrec(4, 1), // 0.4 - PoolIncentives: sdk.NewDecWithPrec(3, 1), // 0.3 - DeveloperRewards: sdk.NewDecWithPrec(2, 1), // 0.2 - CommunityPool: sdk.NewDecWithPrec(1, 1), // 0.1 - }, []types.WeightedAddress{}, 0) + params := types.NewParams( + mintDenom, + epochProvisions, + epochIdentifier, + reductionFactor, + reductionPeriodInEpochs, + distributionProportions, + weightedDevRewardReceivers, + mintintRewardsDistributionStartEpoch) + + minter := types.NewMinter(epochProvisions) - mintGenesis := types.NewGenesisState(types.InitialMinter(), params, 0) + mintGenesis := types.NewGenesisState(minter, params, reductionStartedEpoch) bz, err := json.MarshalIndent(&mintGenesis, "", " ") if err != nil { panic(err) } - // TODO: Do some randomization later - fmt.Printf("Selected deterministically generated minting parameters:\n%s\n", bz) + fmt.Printf("Selected pseudo-randomly generated minting parameters:\n%s\n", bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(mintGenesis) } + +func genEpochProvisions(r *rand.Rand) sdk.Dec { + return sdk.NewDec(int64(r.Intn(maxInt64))) +} + +func genReductionFactor(r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(int64(r.Intn(10)), 1) +} + +func genReductionPeriodInEpochs(r *rand.Rand) int64 { + return int64(r.Intn(maxInt64)) +} + +func genMintintRewardsDistributionStartEpoch(r *rand.Rand) int64 { + return int64(r.Intn(maxInt64)) +} + +func genReductionStartedEpoch(r *rand.Rand) int64 { + return int64(r.Intn(maxInt64)) +} diff --git a/x/mint/simulation/genesis_test.go b/x/mint/simulation/genesis_test.go index 913bd8bfe00..130760e45c8 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -2,6 +2,7 @@ package simulation_test import ( "encoding/json" + "fmt" "math/rand" "testing" @@ -12,17 +13,18 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" ) // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. -// Abonormal scenarios are not tested here. +// Abnormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - s := rand.NewSource(1) + s := rand.NewSource(5) r := rand.New(s) simState := module.SimulationState{ @@ -40,14 +42,59 @@ func TestRandomizedGenState(t *testing.T) { var mintGenesis types.GenesisState simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &mintGenesis) - require.Equal(t, "stake", mintGenesis.Params.MintDenom) - require.Equal(t, "0stake", mintGenesis.Minter.EpochProvision(mintGenesis.Params).String()) - require.Equal(t, "0.000000000000000000", mintGenesis.Minter.NextEpochProvisions(mintGenesis.Params).String()) - require.Equal(t, "0.000000000000000000", mintGenesis.Minter.EpochProvisions.String()) + const ( + expectedEpochProvisionsStr = "7913048388940673156" + expectedReductionFactorStr = "0.6" + expectedReductionPeriodInEpochs = int64(9171281239991390334) + + expectedMintintRewardsDistributionStartEpoch = int64(14997548954463330) + + expectedReductionStartedEpoch = int64(6009281777831789783) + + expectedNextEpochProvisionsStr = "3956524194470336578" + expectedDenom = sdk.DefaultBondDenom + ) + + // Epoch provisions from Minter. + epochProvisionsDec, err := sdk.NewDecFromStr(expectedEpochProvisionsStr) + require.NoError(t, err) + require.Equal(t, epochProvisionsDec, mintGenesis.Minter.EpochProvisions) + + // Epoch identifier. + require.Equal(t, simulation.ExpectedEpochIdentifier, mintGenesis.Params.EpochIdentifier) + + // Reduction factor. + reductionFactorDec, err := sdk.NewDecFromStr(expectedReductionFactorStr) + require.NoError(t, err) + require.Equal(t, reductionFactorDec, mintGenesis.Params.ReductionFactor) + + // Reduction perion in epochs. + require.Equal(t, expectedReductionPeriodInEpochs, mintGenesis.Params.ReductionPeriodInEpochs) + + // Distribution proportions. + require.Equal(t, simulation.ExpectedDistributionProportions, mintGenesis.Params.DistributionProportions) + + // Weighted developer rewards receivers. + require.Equal(t, simulation.ExpectedDevRewardReceivers, mintGenesis.Params.WeightedDeveloperRewardsReceivers) + + // Minting rewards distribution start epoch + require.Equal(t, expectedMintintRewardsDistributionStartEpoch, mintGenesis.Params.MintingRewardsDistributionStartEpoch) + + // Reduction started epoch. + require.Equal(t, expectedReductionStartedEpoch, mintGenesis.ReductionStartedEpoch) + + // Next epoch provisions. + nextEpochProvisionsDec := epochProvisionsDec.Mul(reductionFactorDec) + require.NoError(t, err) + require.Equal(t, nextEpochProvisionsDec, mintGenesis.Minter.NextEpochProvisions(mintGenesis.Params)) + + // Denom and Epoch provisions from Params. + require.Equal(t, expectedDenom, mintGenesis.Params.MintDenom) + require.Equal(t, fmt.Sprintf("%s%s", expectedEpochProvisionsStr, expectedDenom), mintGenesis.Minter.EpochProvision(mintGenesis.Params).String()) } -// TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. -func TestRandomizedGenState1(t *testing.T) { +// TestRandomizedGenState_Invalid tests abnormal scenarios of applying RandomizedGenState. +func TestRandomizedGenState_Invalid(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) diff --git a/x/mint/types/events.go b/x/mint/types/events.go index 6ad8f851868..4f1ca5464b6 100644 --- a/x/mint/types/events.go +++ b/x/mint/types/events.go @@ -1,9 +1,11 @@ package types -// Minting module event types. +// Minting module event constants. const ( - EventTypeMint = ModuleName - + // AttributeKeyEpochProvisions is the string representation of the + // epoch provisions event attribute. AttributeKeyEpochProvisions = "epoch_provisions" - AttributeEpochNumber = "epoch_number" + // AttributeEpochNumber is the string representation of the + // epoch number event attribute. + AttributeEpochNumber = "epoch_number" ) diff --git a/x/mint/types/expected_keepers.go b/x/mint/types/expected_keepers.go index b23f5e53040..29f1c7d3a78 100644 --- a/x/mint/types/expected_keepers.go +++ b/x/mint/types/expected_keepers.go @@ -12,7 +12,6 @@ type AccountKeeper interface { GetModuleAddress(name string) sdk.AccAddress HasAccount(ctx sdk.Context, addr sdk.AccAddress) bool - // TODO remove with genesis 2-phases refactor https://github.com/cosmos/cosmos-sdk/issues/2862 SetModuleAccount(sdk.Context, types.ModuleAccountI) GetModuleAccount(ctx sdk.Context, moduleName string) types.ModuleAccountI } diff --git a/x/mint/types/export_test.go b/x/mint/types/export_test.go new file mode 100644 index 00000000000..103197e146c --- /dev/null +++ b/x/mint/types/export_test.go @@ -0,0 +1,6 @@ +package types + +var ( + ErrNilEpochProvisions = errNilEpochProvisions + ErrNegativeEpochProvisions = errNegativeEpochProvisions +) diff --git a/x/mint/types/genesis.go b/x/mint/types/genesis.go index eae6321d589..17756127b7e 100644 --- a/x/mint/types/genesis.go +++ b/x/mint/types/genesis.go @@ -1,20 +1,20 @@ package types // NewGenesisState creates a new GenesisState object. -func NewGenesisState(minter Minter, params Params, halvenStartedEpoch int64) *GenesisState { +func NewGenesisState(minter Minter, params Params, reductionStartedEpoch int64) *GenesisState { return &GenesisState{ - Minter: minter, - Params: params, - HalvenStartedEpoch: halvenStartedEpoch, + Minter: minter, + Params: params, + ReductionStartedEpoch: reductionStartedEpoch, } } // DefaultGenesisState creates a default GenesisState object. func DefaultGenesisState() *GenesisState { return &GenesisState{ - Minter: DefaultInitialMinter(), - Params: DefaultParams(), - HalvenStartedEpoch: 0, + Minter: DefaultInitialMinter(), + Params: DefaultParams(), + ReductionStartedEpoch: 0, } } @@ -25,5 +25,5 @@ func ValidateGenesis(data GenesisState) error { return err } - return ValidateMinter(data.Minter) + return data.Minter.Validate() } diff --git a/x/mint/types/genesis.pb.go b/x/mint/types/genesis.pb.go index 7aca546b4bc..f93c2d59a1d 100644 --- a/x/mint/types/genesis.pb.go +++ b/x/mint/types/genesis.pb.go @@ -25,12 +25,13 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // GenesisState defines the mint module's genesis state. type GenesisState struct { - // minter is a space for holding current rewards information. + // minter is an abstraction for holding current rewards information. Minter Minter `protobuf:"bytes,1,opt,name=minter,proto3" json:"minter"` - // params defines all the paramaters of the module. + // params defines all the paramaters of the mint module. Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` - // current halven period start epoch - HalvenStartedEpoch int64 `protobuf:"varint,3,opt,name=halven_started_epoch,json=halvenStartedEpoch,proto3" json:"halven_started_epoch,omitempty" yaml:"halven_started_epoch"` + // reduction_started_epoch is the first epoch in which the reduction of mint + // begins. + ReductionStartedEpoch int64 `protobuf:"varint,3,opt,name=reduction_started_epoch,json=reductionStartedEpoch,proto3" json:"reduction_started_epoch,omitempty" yaml:"reduction_started_epoch"` } func (m *GenesisState) Reset() { *m = GenesisState{} } @@ -80,9 +81,9 @@ func (m *GenesisState) GetParams() Params { return Params{} } -func (m *GenesisState) GetHalvenStartedEpoch() int64 { +func (m *GenesisState) GetReductionStartedEpoch() int64 { if m != nil { - return m.HalvenStartedEpoch + return m.ReductionStartedEpoch } return 0 } @@ -96,25 +97,25 @@ func init() { } var fileDescriptor_12e6a5511ad3feeb = []byte{ - // 279 bytes of a gzipped FileDescriptorProto + // 282 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xca, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0xcf, 0xcd, 0xcc, 0x2b, 0xd1, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x81, 0xaa, 0xd1, 0x03, 0xa9, 0xd1, 0x83, 0xaa, 0x91, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x2b, - 0xd0, 0x07, 0xb1, 0x20, 0x6a, 0xa5, 0xe4, 0xb1, 0x9a, 0x07, 0xd6, 0x08, 0x56, 0xa0, 0x74, 0x93, + 0xd0, 0x07, 0xb1, 0x20, 0x6a, 0xa5, 0xe4, 0xb1, 0x9a, 0x07, 0xd6, 0x08, 0x56, 0xa0, 0xf4, 0x88, 0x91, 0x8b, 0xc7, 0x1d, 0x62, 0x7c, 0x70, 0x49, 0x62, 0x49, 0xaa, 0x90, 0x15, 0x17, 0x1b, 0x48, 0x3a, 0xb5, 0x48, 0x82, 0x51, 0x81, 0x51, 0x83, 0xdb, 0x48, 0x46, 0x0f, 0x9b, 0x75, 0x7a, 0xbe, 0x60, 0x35, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x41, 0x75, 0x80, 0xf4, 0x16, 0x24, 0x16, 0x25, 0xe6, 0x16, 0x4b, 0x30, 0xe1, 0xd3, 0x1b, 0x00, 0x56, 0x03, 0xd3, 0x0b, 0xd1, 0x21, 0x14, - 0xc8, 0x25, 0x92, 0x91, 0x98, 0x53, 0x96, 0x9a, 0x17, 0x5f, 0x5c, 0x92, 0x58, 0x54, 0x92, 0x9a, - 0x12, 0x9f, 0x5a, 0x90, 0x9f, 0x9c, 0x21, 0xc1, 0xac, 0xc0, 0xa8, 0xc1, 0xec, 0x24, 0xff, 0xe9, - 0x9e, 0xbc, 0x74, 0x65, 0x62, 0x6e, 0x8e, 0x95, 0x12, 0x36, 0x55, 0x4a, 0x41, 0x42, 0x10, 0xe1, - 0x60, 0x88, 0xa8, 0x2b, 0x48, 0xd0, 0xc9, 0xf3, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, - 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, - 0x18, 0xa2, 0xf4, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0xa1, 0x4e, - 0xd4, 0xcd, 0x49, 0x4c, 0x2a, 0x86, 0x71, 0xf4, 0xcb, 0xcc, 0xf5, 0x2b, 0x20, 0x61, 0x56, 0x52, - 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x0e, 0x2d, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf7, - 0x5d, 0xab, 0xdd, 0xa0, 0x01, 0x00, 0x00, + 0xc5, 0x25, 0x5e, 0x94, 0x9a, 0x52, 0x9a, 0x5c, 0x92, 0x99, 0x9f, 0x17, 0x5f, 0x5c, 0x92, 0x58, + 0x54, 0x92, 0x9a, 0x12, 0x9f, 0x5a, 0x90, 0x9f, 0x9c, 0x21, 0xc1, 0xac, 0xc0, 0xa8, 0xc1, 0xec, + 0xa4, 0xf4, 0xe9, 0x9e, 0xbc, 0x5c, 0x65, 0x62, 0x6e, 0x8e, 0x95, 0x12, 0x0e, 0x85, 0x4a, 0x41, + 0xa2, 0x70, 0x99, 0x60, 0x88, 0x84, 0x2b, 0x48, 0xdc, 0xc9, 0xf3, 0xc4, 0x23, 0x39, 0xc6, 0x0b, + 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, + 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xf4, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, + 0xf5, 0xa1, 0x6e, 0xd5, 0xcd, 0x49, 0x4c, 0x2a, 0x86, 0x71, 0xf4, 0xcb, 0xcc, 0xf5, 0x2b, 0x20, + 0x81, 0x57, 0x52, 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x0e, 0x36, 0x63, 0x40, 0x00, 0x00, 0x00, + 0xff, 0xff, 0xa2, 0xcc, 0xdf, 0xaf, 0xa9, 0x01, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { @@ -137,8 +138,8 @@ func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if m.HalvenStartedEpoch != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.HalvenStartedEpoch)) + if m.ReductionStartedEpoch != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.ReductionStartedEpoch)) i-- dAtA[i] = 0x18 } @@ -186,8 +187,8 @@ func (m *GenesisState) Size() (n int) { n += 1 + l + sovGenesis(uint64(l)) l = m.Params.Size() n += 1 + l + sovGenesis(uint64(l)) - if m.HalvenStartedEpoch != 0 { - n += 1 + sovGenesis(uint64(m.HalvenStartedEpoch)) + if m.ReductionStartedEpoch != 0 { + n += 1 + sovGenesis(uint64(m.ReductionStartedEpoch)) } return n } @@ -295,9 +296,9 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 3: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HalvenStartedEpoch", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ReductionStartedEpoch", wireType) } - m.HalvenStartedEpoch = 0 + m.ReductionStartedEpoch = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis @@ -307,7 +308,7 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.HalvenStartedEpoch |= int64(b&0x7F) << shift + m.ReductionStartedEpoch |= int64(b&0x7F) << shift if b < 0x80 { break } diff --git a/x/mint/types/hooks.go b/x/mint/types/hooks.go index ff2b3c3d4d1..1cffa07ccd4 100644 --- a/x/mint/types/hooks.go +++ b/x/mint/types/hooks.go @@ -4,19 +4,24 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// MintHooks defines an interface for mint module's hooks. type MintHooks interface { AfterDistributeMintedCoin(ctx sdk.Context, mintedCoin sdk.Coin) } var _ MintHooks = MultiMintHooks{} -// combine multiple mint hooks, all hook functions are run in array sequence. +// MultiMintHooks is a container for mint hooks. +// All hooks are run in sequence. type MultiMintHooks []MintHooks +// NewMultiMintHooks returns new MultiMintHooks given hooks. func NewMultiMintHooks(hooks ...MintHooks) MultiMintHooks { return hooks } +// AfterDistributeMintedCoin is a hook that runs after minter mints and distributes coins +// at the beginning of each epoch. func (h MultiMintHooks) AfterDistributeMintedCoin(ctx sdk.Context, mintedCoin sdk.Coin) { for i := range h { h[i].AfterDistributeMintedCoin(ctx, mintedCoin) diff --git a/x/mint/types/keys.go b/x/mint/types/keys.go index 6812a631889..f2c40c0871d 100644 --- a/x/mint/types/keys.go +++ b/x/mint/types/keys.go @@ -1,15 +1,17 @@ package types -// MinterKey is the key to use for the keeper store. +// MinterKey is the key to use for the keeper store at which +// the Minter and its EpochProvisions are stored. var MinterKey = []byte{0x00} -// LastHalvenEpochKey is the key to use for the keeper store. -var LastHalvenEpochKey = []byte{0x03} +// LastReductionEpochKey is the key to use for the keeper store +// for storing the last epoch at which reduction occurred. +var LastReductionEpochKey = []byte{0x03} const ( - // module name. + // ModuleName is the module name. ModuleName = "mint" - // module acct name for developer vesting. + // DeveloperVestingModuleAcctName is the module acct name for developer vesting. DeveloperVestingModuleAcctName = "developer_vesting_unvested" // StoreKey is the default store key for mint. @@ -18,7 +20,9 @@ const ( // QuerierRoute is the querier route for the minting store. QuerierRoute = StoreKey - // Query endpoints supported by the minting querier. - QueryParameters = "parameters" + // QueryParameters is an endpoint path for querying mint parameters. + QueryParameters = "parameters" + + // QueryEpochProvisions is an endpoint path for querying mint epoch provisions. QueryEpochProvisions = "epoch_provisions" ) diff --git a/x/mint/types/mint.pb.go b/x/mint/types/mint.pb.go index e3bae5c43db..954fdc0fc56 100644 --- a/x/mint/types/mint.pb.go +++ b/x/mint/types/mint.pb.go @@ -28,7 +28,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Minter represents the minting state. type Minter struct { - // current epoch provisions + // epoch_provisions represent rewards for the current epoch. EpochProvisions github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=epoch_provisions,json=epochProvisions,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"epoch_provisions" yaml:"epoch_provisions"` } @@ -65,6 +65,9 @@ func (m *Minter) XXX_DiscardUnknown() { var xxx_messageInfo_Minter proto.InternalMessageInfo +// WeightedAddress represents an address with a weight assigned to it. +// The weight is used to determine the proportion of the total minted +// tokens to be minted to the address. type WeightedAddress struct { Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty" yaml:"address"` Weight github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=weight,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"weight" yaml:"weight"` @@ -110,17 +113,20 @@ func (m *WeightedAddress) GetAddress() string { return "" } +// DistributionProportions defines the distribution proportions of the minted +// denom. In other words, defines which stakeholders will receive the minted +// denoms and how much. type DistributionProportions struct { - // staking defines the proportion of the minted minted_denom that is to be + // staking defines the proportion of the minted mint_denom that is to be // allocated as staking rewards. Staking github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=staking,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"staking" yaml:"staking"` - // pool_incentives defines the proportion of the minted minted_denom that is + // pool_incentives defines the proportion of the minted mint_denom that is // to be allocated as pool incentives. PoolIncentives github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=pool_incentives,json=poolIncentives,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"pool_incentives" yaml:"pool_incentives"` - // developer_rewards defines the proportion of the minted minted_denom that is + // developer_rewards defines the proportion of the minted mint_denom that is // to be allocated to developer rewards address. DeveloperRewards github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=developer_rewards,json=developerRewards,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"developer_rewards" yaml:"developer_rewards"` - // community_pool defines the proportion of the minted minted_denom that is + // community_pool defines the proportion of the minted mint_denom that is // to be allocated to the community pool. CommunityPool github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=community_pool,json=communityPool,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"community_pool" yaml:"community_pool"` } @@ -158,23 +164,31 @@ func (m *DistributionProportions) XXX_DiscardUnknown() { var xxx_messageInfo_DistributionProportions proto.InternalMessageInfo -// Params holds parameters for the mint module. +// Params holds parameters for the x/mint module. type Params struct { - // type of coin to mint + // mint_denom is the denom of the coin to mint. MintDenom string `protobuf:"bytes,1,opt,name=mint_denom,json=mintDenom,proto3" json:"mint_denom,omitempty"` - // epoch provisions from the first epoch + // genesis_epoch_provisions epoch provisions from the first epoch. GenesisEpochProvisions github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=genesis_epoch_provisions,json=genesisEpochProvisions,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"genesis_epoch_provisions" yaml:"genesis_epoch_provisions"` - // mint epoch identifier + // epoch_identifier mint epoch identifier e.g. (day, week). EpochIdentifier string `protobuf:"bytes,3,opt,name=epoch_identifier,json=epochIdentifier,proto3" json:"epoch_identifier,omitempty" yaml:"epoch_identifier"` - // number of epochs take to reduce rewards + // reduction_period_in_epochs the number of epochs it takes + // to reduce the rewards. ReductionPeriodInEpochs int64 `protobuf:"varint,4,opt,name=reduction_period_in_epochs,json=reductionPeriodInEpochs,proto3" json:"reduction_period_in_epochs,omitempty" yaml:"reduction_period_in_epochs"` - // reduction multiplier to execute on each period + // reduction_factor is the reduction multiplier to execute + // at the end of each period set by reduction_period_in_epochs. ReductionFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=reduction_factor,json=reductionFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"reduction_factor" yaml:"reduction_factor"` - // distribution_proportions defines the proportion of the minted denom + // distribution_proportions defines the distribution proportions of the minted + // denom. In other words, defines which stakeholders will receive the minted + // denoms and how much. DistributionProportions DistributionProportions `protobuf:"bytes,6,opt,name=distribution_proportions,json=distributionProportions,proto3" json:"distribution_proportions"` - // address to receive developer rewards + // weighted_developer_rewards_receivers is the address to receive developer + // rewards with weights assignedt to each address. The final amount that each + // address receives is: epoch_provisions * + // distribution_proportions.developer_rewards * Address's Weight. WeightedDeveloperRewardsReceivers []WeightedAddress `protobuf:"bytes,7,rep,name=weighted_developer_rewards_receivers,json=weightedDeveloperRewardsReceivers,proto3" json:"weighted_developer_rewards_receivers" yaml:"developer_rewards_receiver"` - // start epoch to distribute minting rewards + // minting_rewards_distribution_start_epoch start epoch to distribute minting + // rewards MintingRewardsDistributionStartEpoch int64 `protobuf:"varint,8,opt,name=minting_rewards_distribution_start_epoch,json=mintingRewardsDistributionStartEpoch,proto3" json:"minting_rewards_distribution_start_epoch,omitempty" yaml:"minting_rewards_distribution_start_epoch"` } diff --git a/x/mint/types/minter.go b/x/mint/types/minter.go index e9ba2b5d5f3..c4037c71aaa 100644 --- a/x/mint/types/minter.go +++ b/x/mint/types/minter.go @@ -1,9 +1,16 @@ package types import ( + "errors" + sdk "github.com/cosmos/cosmos-sdk/types" ) +var ( + errNilEpochProvisions = errors.New("epoch provisions was nil in genesis") + errNegativeEpochProvisions = errors.New("epoch provisions should be non-negative") +) + // NewMinter returns a new Minter object with the given epoch // provisions values. func NewMinter(epochProvisions sdk.Dec) Minter { @@ -22,8 +29,15 @@ func DefaultInitialMinter() Minter { return InitialMinter() } -// validate minter. -func ValidateMinter(minter Minter) error { +// Validate validates minter. Returns nil on success, error otherewise. +func (m Minter) Validate() error { + if m.EpochProvisions.IsNil() { + return errNilEpochProvisions + } + + if m.EpochProvisions.IsNegative() { + return errNegativeEpochProvisions + } return nil } diff --git a/x/mint/types/minter_test.go b/x/mint/types/minter_test.go index 1865228a274..cb841155a9f 100644 --- a/x/mint/types/minter_test.go +++ b/x/mint/types/minter_test.go @@ -1,10 +1,13 @@ -package types +package types_test import ( "math/rand" "testing" + "github.com/osmosis-labs/osmosis/v7/x/mint/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" ) // Benchmarking :) @@ -15,8 +18,8 @@ import ( // BenchmarkEpochProvision-4 3000000 429 ns/op func BenchmarkEpochProvision(b *testing.B) { b.ReportAllocs() - minter := InitialMinter() - params := DefaultParams() + minter := types.InitialMinter() + params := types.DefaultParams() s1 := rand.NewSource(100) r1 := rand.New(s1) @@ -32,11 +35,50 @@ func BenchmarkEpochProvision(b *testing.B) { // BenchmarkNextEpochProvisions-4 5000000 251 ns/op func BenchmarkNextEpochProvisions(b *testing.B) { b.ReportAllocs() - minter := InitialMinter() - params := DefaultParams() + minter := types.InitialMinter() + params := types.DefaultParams() // run the NextEpochProvisions function b.N times for n := 0; n < b.N; n++ { minter.NextEpochProvisions(params) } } + +func TestMinterValidate(t *testing.T) { + + testcases := []struct { + name string + minter types.Minter + expected error + }{ + { + "valid - success", + types.InitialMinter(), + nil, + }, + { + "negative -errir", + types.Minter{ + EpochProvisions: sdk.NewDec(-1), + }, + types.ErrNegativeEpochProvisions, + }, + { + "nil -error", + types.Minter{}, + types.ErrNilEpochProvisions, + }, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + actual := tc.minter.Validate() + if tc.expected != nil { + require.Error(t, actual) + require.Equal(t, actual, tc.expected) + } else { + require.NoError(t, actual) + } + }) + } +} diff --git a/x/mint/types/params.go b/x/mint/types/params.go index 31f6d964685..19dc168260b 100644 --- a/x/mint/types/params.go +++ b/x/mint/types/params.go @@ -5,9 +5,10 @@ import ( "fmt" "strings" - epochtypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" yaml "gopkg.in/yaml.v2" + epochtypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) @@ -29,6 +30,7 @@ func ParamKeyTable() paramtypes.KeyTable { return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) } +// NewParams returns new mint module parameters initialized to the given values. func NewParams( mintDenom string, genesisEpochProvisions sdk.Dec, epochIdentifier string, ReductionFactor sdk.Dec, reductionPeriodInEpochs int64, distrProportions DistributionProportions, @@ -46,7 +48,7 @@ func NewParams( } } -// default minting module parameters. +// DefaultParams returns the default minting module parameters. func DefaultParams() Params { return Params{ MintDenom: sdk.DefaultBondDenom, @@ -65,7 +67,8 @@ func DefaultParams() Params { } } -// validate params. +// Validate validates mint module parameters. Returns nil if valid, +// error otherwise func (p Params) Validate() error { if err := validateMintDenom(p.MintDenom); err != nil { return err @@ -192,8 +195,6 @@ func validateDistributionProportions(i interface{}) error { return errors.New("developer rewards distribution ratio should not be negative") } - // TODO: Maybe we should allow this :joy:, lets you burn osmo from community pool - // for new chains if v.CommunityPool.IsNegative() { return errors.New("community pool distribution ratio should not be negative") } diff --git a/x/mint/types/query.pb.go b/x/mint/types/query.pb.go index a7c1a564082..d394f9f53d7 100644 --- a/x/mint/types/query.pb.go +++ b/x/mint/types/query.pb.go @@ -243,7 +243,7 @@ const _ = grpc.SupportPackageIsVersion4 type QueryClient interface { // Params returns the total set of minting parameters. Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // EpochProvisions current minting epoch provisions value. + // EpochProvisions returns the current minting epoch provisions value. EpochProvisions(ctx context.Context, in *QueryEpochProvisionsRequest, opts ...grpc.CallOption) (*QueryEpochProvisionsResponse, error) } @@ -277,7 +277,7 @@ func (c *queryClient) EpochProvisions(ctx context.Context, in *QueryEpochProvisi type QueryServer interface { // Params returns the total set of minting parameters. Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // EpochProvisions current minting epoch provisions value. + // EpochProvisions returns the current minting epoch provisions value. EpochProvisions(context.Context, *QueryEpochProvisionsRequest) (*QueryEpochProvisionsResponse, error) } diff --git a/x/pool-incentives/keeper/hooks.go b/x/pool-incentives/keeper/hooks.go index 4fe21bf1979..af099cbc535 100644 --- a/x/pool-incentives/keeper/hooks.go +++ b/x/pool-incentives/keeper/hooks.go @@ -4,6 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" ) type Hooks struct { @@ -11,6 +12,7 @@ type Hooks struct { } var _ gammtypes.GammHooks = Hooks{} +var _ minttypes.MintHooks = Hooks{} // Create new pool incentives hooks. func (k Keeper) Hooks() Hooks { return Hooks{k} } diff --git a/x/superfluid/types/query.pb.go b/x/superfluid/types/query.pb.go index 9c911b9637e..db7120f64d1 100644 --- a/x/superfluid/types/query.pb.go +++ b/x/superfluid/types/query.pb.go @@ -1386,105 +1386,111 @@ func init() { func init() { proto.RegisterFile("osmosis/superfluid/query.proto", fileDescriptor_e3d9448e4ed3943f) } var fileDescriptor_e3d9448e4ed3943f = []byte{ - // 1555 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x58, 0xcd, 0x6f, 0xd4, 0x46, - 0x1b, 0xcf, 0x24, 0x90, 0xc0, 0x83, 0x04, 0xc9, 0xc0, 0xfb, 0xb2, 0x18, 0xd8, 0x80, 0x03, 0xc9, - 0x36, 0x80, 0x5d, 0x42, 0x03, 0x29, 0x2d, 0x88, 0x0d, 0x01, 0x1a, 0x29, 0x34, 0x74, 0x21, 0x41, - 0xea, 0x87, 0x2c, 0xef, 0x7a, 0x58, 0xac, 0x78, 0xed, 0xcd, 0x8e, 0x9d, 0xb2, 0x42, 0xa8, 0x12, - 0x55, 0xa5, 0xa2, 0x1e, 0x5a, 0x89, 0x7f, 0xa0, 0x57, 0x7a, 0xa8, 0x7a, 0xeb, 0xa5, 0x97, 0xaa, - 0x17, 0xa4, 0xaa, 0x12, 0x52, 0x2f, 0x55, 0x0f, 0x50, 0x41, 0xaf, 0xbd, 0xf4, 0xd8, 0x5e, 0x2a, - 0xcf, 0x8c, 0x3f, 0x36, 0x6b, 0x7b, 0x77, 0x53, 0x0a, 0xa7, 0xb5, 0xe7, 0xf9, 0xfc, 0x3d, 0x1f, - 0xe3, 0xe7, 0x59, 0xc8, 0x3b, 0xb4, 0xe6, 0x50, 0x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0x1e, - 0xed, 0x2b, 0x09, 0x7e, 0xb9, 0x00, 0xc3, 0x45, 0x4a, 0x89, 0x7b, 0xad, 0x59, 0x27, 0xc2, 0x08, - 0xde, 0x05, 0x9b, 0x0d, 0x62, 0x3b, 0x35, 0xa6, 0x6c, 0x6b, 0x89, 0xbf, 0xc8, 0xef, 0xc1, 0x48, - 0x8c, 0x53, 0x18, 0xbe, 0x08, 0xa0, 0xfb, 0x87, 0x9a, 0xdb, 0xac, 0x13, 0xc6, 0xbf, 0x7d, 0x6a, - 0x22, 0xc9, 0xf8, 0xd5, 0xf0, 0x31, 0x52, 0xb2, 0x55, 0x0f, 0x1e, 0x65, 0x0c, 0xc3, 0x45, 0xcb, - 0x62, 0xa4, 0x10, 0xeb, 0x32, 0x8c, 0xc4, 0xce, 0x84, 0xc1, 0x22, 0x0c, 0x32, 0x29, 0x1f, 0xe9, - 0x40, 0x61, 0xdb, 0xd4, 0x58, 0x17, 0xc6, 0x02, 0xc8, 0x5c, 0x50, 0x56, 0xe0, 0xff, 0xec, 0xf8, - 0xb2, 0x67, 0xb9, 0x66, 0xdd, 0x32, 0x49, 0x23, 0x1b, 0xf8, 0x67, 0x08, 0x76, 0xb7, 0x09, 0x08, - 0x77, 0xea, 0x20, 0xf9, 0xf6, 0x35, 0xb2, 0xea, 0x99, 0x6b, 0xba, 0x45, 0x6c, 0x57, 0xab, 0x85, - 0x5c, 0x22, 0x19, 0x53, 0x49, 0x2e, 0x2e, 0xd2, 0x9a, 0x73, 0x21, 0x14, 0x8a, 0x6b, 0xae, 0x38, - 0x0d, 0xa3, 0x94, 0x73, 0x52, 0xe8, 0xf2, 0x3d, 0x04, 0x07, 0x23, 0x7c, 0xf3, 0xb6, 0x4b, 0x1a, - 0x35, 0x62, 0x98, 0x7a, 0xa3, 0x59, 0xac, 0x54, 0x1c, 0xcf, 0x76, 0xe7, 0xed, 0x1b, 0x4e, 0x32, - 0x12, 0xbc, 0x07, 0xb6, 0xac, 0xe9, 0x96, 0x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78, 0xa9, 0x4b, 0xd4, 0x5e, 0x5c, 0xa1, 0x56, - 0x6e, 0x6a, 0x21, 0xf2, 0xc4, 0x20, 0xfc, 0x8d, 0xe0, 0x70, 0x57, 0xd3, 0x16, 0x3e, 0xd7, 0x43, - 0xf2, 0x12, 0x27, 0x1e, 0xa9, 0xf8, 0x2f, 0x34, 0x88, 0x68, 0x5c, 0x66, 0xd1, 0xb8, 0x84, 0x2f, - 0xf4, 0x5e, 0x03, 0x7e, 0x2c, 0xa2, 0x81, 0x8b, 0xff, 0x13, 0xf6, 0x75, 0x3f, 0x1c, 0xef, 0x79, - 0x80, 0xc2, 0x0b, 0x49, 0x38, 0x36, 0x3a, 0x07, 0x4a, 0x97, 0x9f, 0x93, 0x36, 0x11, 0xa1, 0xf7, - 0x59, 0x84, 0x96, 0xf1, 0xb5, 0xac, 0x08, 0x11, 0xa1, 0x5e, 0xcb, 0xba, 0x10, 0x12, 0x02, 0x36, - 0xbb, 0xf8, 0xf0, 0x69, 0x1e, 0x3d, 0x7a, 0x9a, 0x47, 0xbf, 0x3d, 0xcd, 0xa3, 0x2f, 0x9e, 0xe5, - 0xfb, 0x1e, 0x3d, 0xcb, 0xf7, 0xfd, 0xf2, 0x2c, 0xdf, 0xf7, 0xee, 0x74, 0x6c, 0x16, 0x14, 0x96, - 0x8f, 0x59, 0x7a, 0x99, 0x86, 0x6e, 0xac, 0x9d, 0x52, 0x6f, 0xc5, 0x7d, 0x61, 0xe3, 0x61, 0x79, - 0x90, 0xfd, 0xcd, 0x7d, 0xe2, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfd, 0x21, 0x0e, 0xbf, 0x3e, - 0x18, 0x00, 0x00, + // 1660 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x59, 0x4b, 0x6c, 0xd4, 0xc6, + 0x1b, 0xcf, 0x24, 0x21, 0x81, 0x0f, 0x09, 0x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 0x85, 0xcf, 0x13, 0xd1, 0x03, + 0xca, 0x15, 0xbd, 0xe4, 0x97, 0x61, 0x21, 0x22, 0x29, 0x7f, 0x8f, 0x60, 0x20, 0xd1, 0x94, 0xc8, + 0xc5, 0x35, 0xd8, 0xaa, 0x8b, 0x77, 0xa2, 0x38, 0x26, 0xd2, 0x8b, 0x23, 0x21, 0x78, 0xa2, 0x5c, + 0x02, 0x65, 0xf8, 0x72, 0x03, 0x88, 0x76, 0x06, 0x62, 0x24, 0x13, 0x04, 0xf7, 0xaa, 0x01, 0xc5, + 0x39, 0x18, 0xbc, 0xe0, 0xd8, 0x36, 0x29, 0xba, 0x24, 0xce, 0xb8, 0x1f, 0xb4, 0x3e, 0xe8, 0xf6, + 0x46, 0x8b, 0x97, 0x0a, 0xc4, 0x52, 0xd1, 0xe5, 0x3d, 0xce, 0x18, 0xf2, 0xfb, 0x30, 0x94, 0x2e, + 0x2f, 0x22, 0x31, 0x0f, 0xdd, 0xc2, 0x79, 0x11, 0xf2, 0xcd, 0x05, 0xa2, 0xe0, 0x6b, 0x91, 0x07, + 0xe1, 0xd0, 0x82, 0xe3, 0xea, 0x56, 0x28, 0x32, 0x4d, 0x2c, 0x52, 0xe2, 0x43, 0xda, 0xef, 0xd7, + 0xfb, 0x08, 0xe4, 0x34, 0x2e, 0xe1, 0xdc, 0x1d, 0x04, 0xbd, 0xae, 0xc7, 0xa6, 0x19, 0x21, 0x95, + 0xd7, 0xe9, 0xd4, 0xa2, 0x17, 0xf9, 0x5f, 0x1e, 0x0d, 0x0c, 0x97, 0x4c, 0xf7, 0x46, 0x6d, 0x59, + 0x29, 0x3a, 0x65, 0x55, 0x4c, 0x4b, 0xfe, 0xe7, 0x18, 0x35, 0x56, 0x54, 0x6f, 0xd6, 0x50, 0x65, + 0xc6, 0x76, 0xff, 0x7c, 0x34, 0x30, 0x58, 0xd7, 0xcb, 0xd6, 0x69, 0x99, 0x2b, 0x0c, 0xc1, 0x45, + 0x75, 0xcb, 0x85,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imports to suppress errors if they are not otherwise used. @@ -1527,6 +1533,7 @@ type QueryClient interface { // This is labeled an estimate, because the way it calculates the amount can // lead rounding errors from the true delegated amount EstimateSuperfluidDelegatedAmountByValidatorDenom(ctx context.Context, in *EstimateSuperfluidDelegatedAmountByValidatorDenomRequest, opts ...grpc.CallOption) (*EstimateSuperfluidDelegatedAmountByValidatorDenomResponse, error) + // Returns the specified delegations for a specific delegator TotalDelegationByDelegator(ctx context.Context, in *QueryTotalDelegationByDelegatorRequest, opts ...grpc.CallOption) (*QueryTotalDelegationByDelegatorResponse, error) } @@ -1685,6 +1692,7 @@ type QueryServer interface { // This is labeled an estimate, because the way it calculates the amount can // lead rounding errors from the true delegated amount EstimateSuperfluidDelegatedAmountByValidatorDenom(context.Context, *EstimateSuperfluidDelegatedAmountByValidatorDenomRequest) (*EstimateSuperfluidDelegatedAmountByValidatorDenomResponse, error) + // Returns the specified delegations for a specific delegator TotalDelegationByDelegator(context.Context, *QueryTotalDelegationByDelegatorRequest) (*QueryTotalDelegationByDelegatorResponse, error) } From d9a4f94c15c9237289408689131acb04023f3c63 Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 30 Jun 2022 14:37:31 -0400 Subject: [PATCH 002/376] test: x/mint thirdening - identify rounding errors (#1874) * test: x/mint thirdening * add logic for estimating supply * estimate expected supply w/o offset * identify the sources of rounding issues * transcribe calculations * clean up for readability * Update x/mint/keeper/hooks_test.go Co-authored-by: Aleksandr Bezobchuk * fix merge conflicts and link a correct issue Co-authored-by: Aleksandr Bezobchuk --- x/mint/keeper/hooks_test.go | 214 ++++++++++++++++++++++++++++++++++++ 1 file changed, 214 insertions(+) diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index 74571d0bafa..fcfd5a67380 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -220,6 +220,220 @@ func TestEndOfEpochNoDistributionWhenIsNotYetStartTime(t *testing.T) { require.Equal(t, lastReductionPeriod, mintParams.MintingRewardsDistributionStartEpoch) } +// TODO: Remove after rounding errors are addressed and resolved. +// Make sure that more specific test specs are added to validate the expected +// supply for correctness. +// +// Ref: https://github.com/osmosis-labs/osmosis/issues/1917 +func TestAfterEpochEnd_FirstYearThirdening_RealParameters(t *testing.T) { + // Most values in this test are taken from mainnet genesis to mimic real-world behavior: + // https://github.com/osmosis-labs/networks/raw/main/osmosis-1/genesis.json + const ( + reductionPeriodInEpochs = 365 + mintingRewardsDistributionStartEpoch int64 = 1 + thirdeningEpochNum int64 = reductionPeriodInEpochs + mintingRewardsDistributionStartEpoch + + // different from mainnet since the difference is insignificant for testing purposes. + mintDenom = "stake" + genesisEpochProvisions = "821917808219.178082191780821917" + epochIdentifier = "day" + + // actual value taken from mainnet for sanity checking calculations. + mainnetThirdenedProvisions = "547945205479.452055068493150684" + + developerAccountBalance = 225_000_000_000_000 + ) + + var ( + reductionFactor = sdk.NewDec(2).Quo(sdk.NewDec(3)) + ) + + app := osmoapp.Setup(false) + ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + + genesisEpochProvisionsDec, err := sdk.NewDecFromStr(genesisEpochProvisions) + require.NoError(t, err) + + mintParams := types.Params{ + MintDenom: mintDenom, + GenesisEpochProvisions: genesisEpochProvisionsDec, + EpochIdentifier: epochIdentifier, + ReductionPeriodInEpochs: reductionPeriodInEpochs, + ReductionFactor: reductionFactor, + DistributionProportions: types.DistributionProportions{ + Staking: sdk.NewDecWithPrec(25, 2), + PoolIncentives: sdk.NewDecWithPrec(45, 2), + DeveloperRewards: sdk.NewDecWithPrec(25, 2), + CommunityPool: sdk.NewDecWithPrec(05, 2), + }, + WeightedDeveloperRewardsReceivers: []types.WeightedAddress{ + { + Address: "osmo14kjcwdwcqsujkdt8n5qwpd8x8ty2rys5rjrdjj", + Weight: sdk.NewDecWithPrec(2887, 4), + }, + { + Address: "osmo1gw445ta0aqn26suz2rg3tkqfpxnq2hs224d7gq", + Weight: sdk.NewDecWithPrec(229, 3), + }, + { + Address: "osmo13lt0hzc6u3htsk7z5rs6vuurmgg4hh2ecgxqkf", + Weight: sdk.NewDecWithPrec(1625, 4), + }, + { + Address: "osmo1kvc3he93ygc0us3ycslwlv2gdqry4ta73vk9hu", + Weight: sdk.NewDecWithPrec(109, 3), + }, + { + Address: "osmo19qgldlsk7hdv3ddtwwpvzff30pxqe9phq9evxf", + Weight: sdk.NewDecWithPrec(995, 3).Quo(sdk.NewDec(10)), // 0.0995 + }, + { + Address: "osmo19fs55cx4594een7qr8tglrjtt5h9jrxg458htd", + Weight: sdk.NewDecWithPrec(6, 1).Quo(sdk.NewDec(10)), // 0.06 + }, + { + Address: "osmo1ssp6px3fs3kwreles3ft6c07mfvj89a544yj9k", + Weight: sdk.NewDecWithPrec(15, 2).Quo(sdk.NewDec(10)), // 0.015 + }, + { + Address: "osmo1c5yu8498yzqte9cmfv5zcgtl07lhpjrj0skqdx", + Weight: sdk.NewDecWithPrec(1, 1).Quo(sdk.NewDec(10)), // 0.01 + }, + { + Address: "osmo1yhj3r9t9vw7qgeg22cehfzj7enwgklw5k5v7lj", + Weight: sdk.NewDecWithPrec(75, 2).Quo(sdk.NewDec(100)), // 0.0075 + }, + { + Address: "osmo18nzmtyn5vy5y45dmcdnta8askldyvehx66lqgm", + Weight: sdk.NewDecWithPrec(7, 1).Quo(sdk.NewDec(100)), // 0.007 + }, + { + Address: "osmo1z2x9z58cg96ujvhvu6ga07yv9edq2mvkxpgwmc", + Weight: sdk.NewDecWithPrec(5, 1).Quo(sdk.NewDec(100)), // 0.005 + }, + { + Address: "osmo1tvf3373skua8e6480eyy38avv8mw3hnt8jcxg9", + Weight: sdk.NewDecWithPrec(25, 2).Quo(sdk.NewDec(100)), // 0.0025 + }, + { + Address: "osmo1zs0txy03pv5crj2rvty8wemd3zhrka2ne8u05n", + Weight: sdk.NewDecWithPrec(25, 2).Quo(sdk.NewDec(100)), // 0.0025 + }, + { + Address: "osmo1djgf9p53n7m5a55hcn6gg0cm5mue4r5g3fadee", + Weight: sdk.NewDecWithPrec(1, 1).Quo(sdk.NewDec(100)), // 0.001 + }, + { + Address: "osmo1488zldkrn8xcjh3z40v2mexq7d088qkna8ceze", + Weight: sdk.NewDecWithPrec(8, 1).Quo(sdk.NewDec(1000)), // 0.0008 + }, + }, + MintingRewardsDistributionStartEpoch: mintingRewardsDistributionStartEpoch, + } + + sumOfWeights := sdk.ZeroDec() + // As a sanity check, ensure developer reward receivers add up to 1. + for _, w := range mintParams.WeightedDeveloperRewardsReceivers { + sumOfWeights = sumOfWeights.Add(w.Weight) + } + require.Equal(t, sdk.OneDec(), sumOfWeights) + + // Test setup parameters are not identical with mainnet. + // Therfore, we set them here to the desired mainnet values. + app.MintKeeper.SetParams(ctx, mintParams) + app.MintKeeper.SetLastReductionEpochNum(ctx, 0) + app.MintKeeper.SetMinter(ctx, types.Minter{ + EpochProvisions: genesisEpochProvisionsDec, + }) + + expectedSupplyWithOffset := sdk.NewDec(0) + expectedSupply := sdk.NewDec(developerAccountBalance) + + supplyWithOffset := app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom) + require.Equal(t, expectedSupplyWithOffset.TruncateInt64(), supplyWithOffset.Amount.Int64()) + + supply := app.BankKeeper.GetSupply(ctx, mintDenom) + require.Equal(t, expectedSupply.TruncateInt64(), supply.Amount.Int64()) + + devRewardsDelta := sdk.ZeroDec() + epochProvisionsDelta := genesisEpochProvisionsDec.Sub(genesisEpochProvisionsDec.TruncateInt().ToDec()).Mul(sdk.NewDec(reductionPeriodInEpochs)) + + // Actual test for running AfterEpochEnd hook thirdeningEpoch times. + for i := int64(1); i <= reductionPeriodInEpochs; i++ { + developerAccountBalanceBeforeHook := app.BankKeeper.GetBalance(ctx, app.AccountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), mintDenom) + + // System undert test. + app.MintKeeper.AfterEpochEnd(ctx, epochIdentifier, i) + + // System truncates EpochProvisions because bank takes an Int. + // This causes rounding errors. Let's refer to this source as #1. + // + // Since this is truncated, our total supply calculation at the end will + // be off by reductionPeriodInEpochs * (genesisEpochProvisionsDec - truncatedEpochProvisions) + // Therefore, we store this delta in epochProvisionsDelta to add to the actual supply to compare + // to expected at the end. + truncatedEpochProvisions := genesisEpochProvisionsDec.TruncateInt().ToDec() + + // We want supply with offset to exclude unvested developer rewards + // Truncation also happens when subtracting dev rewards. + // Potential source of minor rounding errors #2. + devRewards := truncatedEpochProvisions.Mul(mintParams.DistributionProportions.DeveloperRewards).TruncateInt().ToDec() + + // We aim to exclude developer account balance from the supply with offset calculation. + developerAccountBalance := app.BankKeeper.GetBalance(ctx, app.AccountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), mintDenom) + + // Make sure developer account balance has decreased by devRewards. + // This check is now failing because of rounding errors. + // To prove that this is the source of errors, we keep accumulating + // the delta and add it to the expected supply validation after the loop. + if !developerAccountBalanceBeforeHook.Amount.ToDec().Sub(devRewards).Equal(developerAccountBalance.Amount.ToDec()) { + expectedDeveloperAccountBalanceAfterHook := developerAccountBalanceBeforeHook.Amount.ToDec().Sub(devRewards) + actualDeveloperAccountBalanceAfterHook := developerAccountBalance.Amount.ToDec() + + // This is supposed to be equal but is failing due to the rounding errors from devRewards. + require.NotEqual(t, expectedDeveloperAccountBalanceAfterHook, actualDeveloperAccountBalanceAfterHook) + + devRewardsDelta = devRewardsDelta.Add(actualDeveloperAccountBalanceAfterHook.Sub(expectedDeveloperAccountBalanceAfterHook)) + } + + expectedSupply = expectedSupply.Add(truncatedEpochProvisions).Sub(devRewards) + require.Equal(t, expectedSupply.RoundInt(), app.BankKeeper.GetSupply(ctx, mintDenom).Amount) + + expectedSupplyWithOffset = expectedSupply.Sub(developerAccountBalance.Amount.ToDec()) + require.Equal(t, expectedSupplyWithOffset.RoundInt(), app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount) + + // Validate that the epoch provisions have not been reduced. + require.Equal(t, mintingRewardsDistributionStartEpoch, app.MintKeeper.GetLastReductionEpochNum(ctx)) + require.Equal(t, genesisEpochProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions.String()) + } + + // Validate total supply. + // This test check is now failing due to rounding errors. + // Every epoch, we accumulate the rounding delta from every problematic component + // Here, we add the deltas to the actual supply and compare against expected. + // + // expectedTotalProvisionedSupply = 365 * 821917808219.178082191780821917 = 299_999_999_999_999.999999999999999705 + expectedTotalProvisionedSupply := sdk.NewDec(reductionPeriodInEpochs).Mul(genesisEpochProvisionsDec) + // actualTotalProvisionedSupply = 299_999_999_997_380 (off by 2619.999999999999999705) + // devRewardsDelta = 2555 (hard to estimate but the source is from truncating dev rewards ) + // epochProvisionsDelta = 0.178082191780821917 * 365 = 64.999999999999999705 + actualTotalProvisionedSupply := app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount.ToDec() + + // 299_999_999_999_999.999999999999999705 == 299_999_999_997_380 + 2555 + 64.999999999999999705 + require.Equal(t, expectedTotalProvisionedSupply, actualTotalProvisionedSupply.Add(devRewardsDelta).Add(epochProvisionsDelta)) + + // This end of epoch should trigger thirdening. It will utilize the updated + // (reduced) provisions. + app.MintKeeper.AfterEpochEnd(ctx, epochIdentifier, thirdeningEpochNum) + + require.Equal(t, thirdeningEpochNum, app.MintKeeper.GetLastReductionEpochNum(ctx)) + + expectedThirdenedProvisions := mintParams.ReductionFactor.Mul(genesisEpochProvisionsDec) + // Sanity check with the actual value on mainnet. + require.Equal(t, mainnetThirdenedProvisions, expectedThirdenedProvisions.String()) + require.Equal(t, expectedThirdenedProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions) +} + func setupGaugeForLPIncentives(t *testing.T, app *osmoapp.OsmosisApp, ctx sdk.Context) { addr := sdk.AccAddress([]byte("addr1---------------")) coins := sdk.Coins{sdk.NewInt64Coin("stake", 10000)} From 15736e5512924a840b85d6807e477bd6cad98cd4 Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Thu, 30 Jun 2022 16:13:00 -0500 Subject: [PATCH 003/376] x/gamm: Internal audit and documentation (#1858) * add many clarifying comments and docs for logic that was confusing during audit * update comments for clarity * Update x/gamm/keeper/multihop.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update x/gamm/keeper/genesis.go Co-authored-by: Aleksandr Bezobchuk * Update x/gamm/keeper/genesis.go Co-authored-by: Aleksandr Bezobchuk * Update x/gamm/keeper/multihop.go Co-authored-by: Aleksandr Bezobchuk * Apply suggestions from code review Co-authored-by: Aleksandr Bezobchuk * add more clarifying comments * apply suggestions from review Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> Co-authored-by: Aleksandr Bezobchuk --- x/gamm/keeper/genesis.go | 6 ++++-- x/gamm/keeper/multihop.go | 22 +++++++++++++++++++- x/gamm/keeper/pool.go | 2 +- x/gamm/keeper/pool_service.go | 3 ++- x/gamm/keeper/swap.go | 4 ++++ x/gamm/pool-models/balancer/balancer_pool.go | 2 +- x/tokenfactory/keeper/admins_test.go | 8 ++----- x/tokenfactory/keeper/createdenom_test.go | 1 - x/tokenfactory/keeper/keeper_test.go | 4 ++-- 9 files changed, 37 insertions(+), 15 deletions(-) diff --git a/x/gamm/keeper/genesis.go b/x/gamm/keeper/genesis.go index eaac980d3ee..bdccb8a4921 100644 --- a/x/gamm/keeper/genesis.go +++ b/x/gamm/keeper/genesis.go @@ -7,12 +7,14 @@ import ( "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) -// InitGenesis initializes the capability module's state from a provided genesis -// state. +// InitGenesis initializes the x/gamm module's state from a provided genesis +// state, which includes the current live pools, global pool parameters (e.g. pool creation fee), next pool number etc. func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState, unpacker codectypes.AnyUnpacker) { k.SetParams(ctx, genState.Params) k.SetNextPoolNumber(ctx, genState.NextPoolNumber) + // Sums up the liquidity in all genesis state pools to find the total liquidity across all pools. + // Also adds each genesis state pool to the x/gamm module's state liquidity := sdk.Coins{} for _, any := range genState.Pools { var pool types.PoolI diff --git a/x/gamm/keeper/multihop.go b/x/gamm/keeper/multihop.go index fa67fc2bb00..852cdd9cb7b 100644 --- a/x/gamm/keeper/multihop.go +++ b/x/gamm/keeper/multihop.go @@ -17,15 +17,20 @@ func (k Keeper) MultihopSwapExactAmountIn( tokenOutMinAmount sdk.Int, ) (tokenOutAmount sdk.Int, err error) { for i, route := range routes { + // To prevent the multihop swap from being interrupted prematurely, we keep + // the minimum expected output at a very low number until the last pool _outMinAmount := sdk.NewInt(1) if len(routes)-1 == i { _outMinAmount = tokenOutMinAmount } + // Execute the expected swap on the current routed pool tokenOutAmount, err = k.SwapExactAmountIn(ctx, sender, route.PoolId, tokenIn, route.TokenOutDenom, _outMinAmount) if err != nil { return sdk.Int{}, err } + + // Chain output of current pool as the input for the next routed pool tokenIn = sdk.NewCoin(route.TokenOutDenom, tokenOutAmount) } return @@ -42,6 +47,7 @@ func (k Keeper) MultihopSwapExactAmountOut( tokenInMaxAmount sdk.Int, tokenOut sdk.Coin, ) (tokenInAmount sdk.Int, err error) { + // Determine what the estimated input would be for each pool along the multihop route insExpected, err := k.createMultihopExpectedSwapOuts(ctx, routes, tokenOut) if err != nil { return sdk.Int{}, err @@ -49,17 +55,27 @@ func (k Keeper) MultihopSwapExactAmountOut( insExpected[0] = tokenInMaxAmount + // Iterates through each routed pool and executes their respective swaps. Note that all of the work to get the return + // value of this method is done when we calculate insExpected – this for loop primarily serves to execute the actual + // swaps on each pool. for i, route := range routes { _tokenOut := tokenOut + + // If there is one pool left in the route, set the expected output of the current swap + // to the estimated input of the final pool. if i != len(routes)-1 { _tokenOut = sdk.NewCoin(routes[i+1].TokenInDenom, insExpected[i+1]) } + // Execute the expected swap on the current routed pool _tokenInAmount, err := k.SwapExactAmountOut(ctx, sender, route.PoolId, route.TokenInDenom, insExpected[i], _tokenOut) if err != nil { return sdk.Int{}, err } + // Sets the final amount of tokens that need to be input into the first pool. Even though this is the final return value for the + // whole method and will not change after the first iteration, we still iterate through the rest of the pools to execute their respective + // swaps. if i == 0 { tokenInAmount = _tokenInAmount } @@ -68,7 +84,11 @@ func (k Keeper) MultihopSwapExactAmountOut( return tokenInAmount, nil } -// TODO: Document this function. +// createMultihopExpectedSwapOuts defines the output denom and output amount for the last pool in +// the route of pools the caller is intending to hop through in a fixed-output multihop tx. It estimates the input +// amount for this last pool and then chains that input as the output of the previous pool in the route, repeating +// until the first pool is reached. It returns an array of inputs, each of which correspond to a pool ID in the +// route of pools for the original multihop transaction. func (k Keeper) createMultihopExpectedSwapOuts(ctx sdk.Context, routes []types.SwapAmountOutRoute, tokenOut sdk.Coin) ([]sdk.Int, error) { insExpected := make([]sdk.Int, len(routes)) for i := len(routes) - 1; i >= 0; i-- { diff --git a/x/gamm/keeper/pool.go b/x/gamm/keeper/pool.go index 02b5c49115a..357d96a293c 100644 --- a/x/gamm/keeper/pool.go +++ b/x/gamm/keeper/pool.go @@ -43,7 +43,7 @@ func (k Keeper) GetPoolAndPoke(ctx sdk.Context, poolId uint64) (types.PoolI, err return pool, nil } -// Get pool, and check if the pool is active / allowed to be swapped against +// Get pool and check if the pool is active, i.e. allowed to be swapped against. func (k Keeper) getPoolForSwap(ctx sdk.Context, poolId uint64) (types.PoolI, error) { pool, err := k.GetPoolAndPoke(ctx, poolId) if err != nil { diff --git a/x/gamm/keeper/pool_service.go b/x/gamm/keeper/pool_service.go index 5247868a76e..d8e82c3bc55 100644 --- a/x/gamm/keeper/pool_service.go +++ b/x/gamm/keeper/pool_service.go @@ -220,7 +220,7 @@ func (k Keeper) JoinPoolNoSwap( return err } -// getMaximalNoSwapLPAmount returns the coins(lp liquidity) needed to get the specified amount of share of the pool. +// getMaximalNoSwapLPAmount returns the coins(lp liquidity) needed to get the specified amount of shares in the pool. // Steps to getting the needed lp liquidity coins needed for the share of the pools are // 1. calculate how much percent of the pool does given share account for(# of input shares / # of current total shares) // 2. since we know how much % of the pool we want, iterate through all pool liquidity to calculate how much coins we need for @@ -317,6 +317,7 @@ func (k Keeper) JoinSwapShareAmountOut( } tokenIn := sdk.NewCoins(sdk.NewCoin(tokenInDenom, tokenInAmount)) + // Not using generic JoinPool because we want to guarantee exact shares out extendedPool.IncreaseLiquidity(shareOutAmount, tokenIn) err = k.applyJoinPoolStateChange(ctx, pool, sender, shareOutAmount, tokenIn) diff --git a/x/gamm/keeper/swap.go b/x/gamm/keeper/swap.go index 49264c99c9b..ec3f6f71acb 100644 --- a/x/gamm/keeper/swap.go +++ b/x/gamm/keeper/swap.go @@ -49,6 +49,8 @@ func (k Keeper) swapExactAmountIn( } tokensIn := sdk.Coins{tokenIn} + // Executes the swap in the pool and stores the output. Updates pool assets but + // does not actually transfer any tokens to or from the pool. tokenOutCoin, err := pool.SwapOutAmtGivenIn(ctx, tokensIn, tokenOutDenom, swapFee) if err != nil { return sdk.Int{}, err @@ -64,6 +66,8 @@ func (k Keeper) swapExactAmountIn( return sdk.Int{}, sdkerrors.Wrapf(types.ErrLimitMinAmount, "%s token is lesser than min amount", tokenOutDenom) } + // Settles balances between the tx sender and the pool to match the swap that was executed earlier. + // Also emits swap event and updates related liquidity metrics if err := k.updatePoolForSwap(ctx, pool, sender, tokenIn, tokenOutCoin); err != nil { return sdk.Int{}, err } diff --git a/x/gamm/pool-models/balancer/balancer_pool.go b/x/gamm/pool-models/balancer/balancer_pool.go index c773533b665..9735d976086 100644 --- a/x/gamm/pool-models/balancer/balancer_pool.go +++ b/x/gamm/pool-models/balancer/balancer_pool.go @@ -388,7 +388,7 @@ func (pa *Pool) updateAllWeights(newWeights []PoolAsset) { } // PokePool checks to see if the pool's token weights need to be updated, and -// if so, does so. +// if so, does so. Currently doesn't do anything outside out LBPs. func (pa *Pool) PokePool(blockTime time.Time) { // check if pool weights didn't change poolWeightsChanging := pa.PoolParams.SmoothWeightChangeParams != nil diff --git a/x/tokenfactory/keeper/admins_test.go b/x/tokenfactory/keeper/admins_test.go index 4d720a067e7..958d52643a2 100644 --- a/x/tokenfactory/keeper/admins_test.go +++ b/x/tokenfactory/keeper/admins_test.go @@ -71,9 +71,7 @@ func (suite *KeeperTestSuite) TestAdminMsgs() { // * Only the admin of a denom can mint tokens for it // * The admin of a denom can mint tokens for it func (suite *KeeperTestSuite) TestMintDenom() { - var ( - addr0bal = int64(0) - ) + var addr0bal int64 // Create a denom suite.CreateDefaultDenom() @@ -122,9 +120,7 @@ func (suite *KeeperTestSuite) TestMintDenom() { } func (suite *KeeperTestSuite) TestBurnDenom() { - var ( - addr0bal = int64(0) - ) + var addr0bal int64 // Create a denom. suite.CreateDefaultDenom() diff --git a/x/tokenfactory/keeper/createdenom_test.go b/x/tokenfactory/keeper/createdenom_test.go index e7809364012..77696ed7afb 100644 --- a/x/tokenfactory/keeper/createdenom_test.go +++ b/x/tokenfactory/keeper/createdenom_test.go @@ -74,7 +74,6 @@ func (suite *KeeperTestSuite) TestCreateDenom() { setup: func() { _, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin")) suite.Require().NoError(err) - }, subdenom: "bitcoin", valid: false, diff --git a/x/tokenfactory/keeper/keeper_test.go b/x/tokenfactory/keeper/keeper_test.go index 1737f3b5ef6..587fa7d030e 100644 --- a/x/tokenfactory/keeper/keeper_test.go +++ b/x/tokenfactory/keeper/keeper_test.go @@ -14,8 +14,8 @@ import ( type KeeperTestSuite struct { apptesting.KeeperTestHelper - queryClient types.QueryClient - msgServer types.MsgServer + queryClient types.QueryClient + msgServer types.MsgServer // defaultDenom is on the suite, as it depends on the creator test address. defaultDenom string } From e2d49117ea16b41cdf17e23aee590e60d384dc32 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Thu, 30 Jun 2022 18:20:34 -0400 Subject: [PATCH 004/376] refactor: consolidate pool implementation (#1868) --- x/gamm/pool-models/balancer/amm.go | 556 +------- x/gamm/pool-models/balancer/amm_test.go | 362 +---- x/gamm/pool-models/balancer/balancer_pool.go | 601 -------- .../balancer/balancer_pool_test.go | 567 -------- x/gamm/pool-models/balancer/marshal_test.go | 16 +- x/gamm/pool-models/balancer/pool.go | 949 +++++++++++++ x/gamm/pool-models/balancer/pool_params.go | 78 ++ ...mm_joinpool_test.go => pool_suite_test.go} | 584 ++------ x/gamm/pool-models/balancer/pool_test.go | 1243 +++++++++++++++++ x/gamm/pool-models/balancer/suite_test.go | 28 - 10 files changed, 2494 insertions(+), 2490 deletions(-) delete mode 100644 x/gamm/pool-models/balancer/balancer_pool.go delete mode 100644 x/gamm/pool-models/balancer/balancer_pool_test.go create mode 100644 x/gamm/pool-models/balancer/pool.go create mode 100644 x/gamm/pool-models/balancer/pool_params.go rename x/gamm/pool-models/balancer/{amm_joinpool_test.go => pool_suite_test.go} (64%) create mode 100644 x/gamm/pool-models/balancer/pool_test.go delete mode 100644 x/gamm/pool-models/balancer/suite_test.go diff --git a/x/gamm/pool-models/balancer/amm.go b/x/gamm/pool-models/balancer/amm.go index 9f5d7a8a72c..cd05a5c3ef6 100644 --- a/x/gamm/pool-models/balancer/amm.go +++ b/x/gamm/pool-models/balancer/amm.go @@ -1,26 +1,85 @@ package balancer import ( - "errors" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/osmosis-labs/osmosis/v7/osmomath" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/cfmm_common" "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) -const ( - errMsgFormatSharesAmountNotPositive = "shares amount must be positive, was %d" - errMsgFormatTokenAmountNotPositive = "token amount must be positive, was %d" - errMsgFormatTokensLargerThanMax = "%d resulted tokens is larger than the max amount of %d" - errMsgFormatSharesLargerThanMax = "%d resulted shares is larger than the max amount of %d" - errMsgFormatFailedInterimLiquidityUpdate = "failed to update interim liquidity - pool asset %s does not exist" - errMsgFormatRepeatingPoolAssetsNotAllowed = "repeating pool assets not allowed, found %s" - v10Fork = 4713065 -) +// subPoolAssetWeights subtracts the weights of two different pool asset slices. +// It assumes that both pool assets have the same token denominations, +// with the denominations in the same order. +// Returned weights can (and probably will have some) be negative. +func subPoolAssetWeights(base []PoolAsset, other []PoolAsset) []PoolAsset { + weightDifference := make([]PoolAsset, len(base)) + // TODO: Consider deleting these panics for performance + if len(base) != len(other) { + panic("subPoolAssetWeights called with invalid input, len(base) != len(other)") + } + for i, asset := range base { + if asset.Token.Denom != other[i].Token.Denom { + panic(fmt.Sprintf("subPoolAssetWeights called with invalid input, "+ + "expected other's %vth asset to be %v, got %v", + i, asset.Token.Denom, other[i].Token.Denom)) + } + curWeightDiff := asset.Weight.Sub(other[i].Weight) + weightDifference[i] = PoolAsset{Token: asset.Token, Weight: curWeightDiff} + } + return weightDifference +} + +// addPoolAssetWeights adds the weights of two different pool asset slices. +// It assumes that both pool assets have the same token denominations, +// with the denominations in the same order. +// Returned weights can be negative. +func addPoolAssetWeights(base []PoolAsset, other []PoolAsset) []PoolAsset { + weightSum := make([]PoolAsset, len(base)) + // TODO: Consider deleting these panics for performance + if len(base) != len(other) { + panic("addPoolAssetWeights called with invalid input, len(base) != len(other)") + } + for i, asset := range base { + if asset.Token.Denom != other[i].Token.Denom { + panic(fmt.Sprintf("addPoolAssetWeights called with invalid input, "+ + "expected other's %vth asset to be %v, got %v", + i, asset.Token.Denom, other[i].Token.Denom)) + } + curWeightSum := asset.Weight.Add(other[i].Weight) + weightSum[i] = PoolAsset{Token: asset.Token, Weight: curWeightSum} + } + return weightSum +} + +// assumes 0 < d < 1 +func poolAssetsMulDec(base []PoolAsset, d sdk.Dec) []PoolAsset { + newWeights := make([]PoolAsset, len(base)) + for i, asset := range base { + // TODO: This can adversarially panic at the moment! (as can Pool.TotalWeight) + // Ensure this won't be able to panic in the future PR where we bound + // each assets weight, and add precision + newWeight := d.MulInt(asset.Weight).RoundInt() + newWeights[i] = PoolAsset{Token: asset.Token, Weight: newWeight} + } + return newWeights +} + +// ValidateUserSpecifiedWeight ensures that a weight that is provided from user-input anywhere +// for creating a pool obeys the expected guarantees. +// Namely, that the weight is in the range [1, MaxUserSpecifiedWeight) +func ValidateUserSpecifiedWeight(weight sdk.Int) error { + if !weight.IsPositive() { + return sdkerrors.Wrap(types.ErrNotPositiveWeight, weight.String()) + } + + if weight.GTE(MaxUserSpecifiedWeight) { + return sdkerrors.Wrap(types.ErrWeightTooLarge, weight.String()) + } + return nil +} // solveConstantFunctionInvariant solves the constant function of an AMM // that determines the relationship between the differences of two sides @@ -52,158 +111,6 @@ func solveConstantFunctionInvariant( return amountY } -// CalcOutAmtGivenIn calculates tokens to be swapped out given the provided -// amount and fee deducted, using solveConstantFunctionInvariant. -func (p Pool) CalcOutAmtGivenIn( - ctx sdk.Context, - tokensIn sdk.Coins, - tokenOutDenom string, - swapFee sdk.Dec, -) (sdk.Coin, error) { - tokenIn, poolAssetIn, poolAssetOut, err := p.parsePoolAssets(tokensIn, tokenOutDenom) - if err != nil { - return sdk.Coin{}, err - } - - tokenAmountInAfterFee := tokenIn.Amount.ToDec().Mul(sdk.OneDec().Sub(swapFee)) - poolTokenInBalance := poolAssetIn.Token.Amount.ToDec() - poolPostSwapInBalance := poolTokenInBalance.Add(tokenAmountInAfterFee) - - // deduct swapfee on the tokensIn - // delta balanceOut is positive(tokens inside the pool decreases) - tokenAmountOut := solveConstantFunctionInvariant( - poolTokenInBalance, - poolPostSwapInBalance, - poolAssetIn.Weight.ToDec(), - poolAssetOut.Token.Amount.ToDec(), - poolAssetOut.Weight.ToDec(), - ) - - // We ignore the decimal component, as we round down the token amount out. - tokenAmountOutInt := tokenAmountOut.TruncateInt() - if !tokenAmountOutInt.IsPositive() { - return sdk.Coin{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "token amount must be positive") - } - - return sdk.NewCoin(tokenOutDenom, tokenAmountOutInt), nil -} - -// SwapOutAmtGivenIn is a mutative method for CalcOutAmtGivenIn, which includes the actual swap. -func (p *Pool) SwapOutAmtGivenIn( - ctx sdk.Context, - tokensIn sdk.Coins, - tokenOutDenom string, - swapFee sdk.Dec, -) ( - tokenOut sdk.Coin, err error, -) { - tokenOutCoin, err := p.CalcOutAmtGivenIn(ctx, tokensIn, tokenOutDenom, swapFee) - if err != nil { - return sdk.Coin{}, err - } - - err = p.applySwap(ctx, tokensIn, sdk.Coins{tokenOutCoin}) - if err != nil { - return sdk.Coin{}, err - } - return tokenOutCoin, nil -} - -// CalcInAmtGivenOut calculates token to be provided, fee added, -// given the swapped out amount, using solveConstantFunctionInvariant. -func (p Pool) CalcInAmtGivenOut( - ctx sdk.Context, tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( - tokenIn sdk.Coin, err error, -) { - tokenOut, poolAssetOut, poolAssetIn, err := p.parsePoolAssets(tokensOut, tokenInDenom) - if err != nil { - return sdk.Coin{}, err - } - - // delta balanceOut is positive(tokens inside the pool decreases) - poolTokenOutBalance := poolAssetOut.Token.Amount.ToDec() - poolPostSwapOutBalance := poolTokenOutBalance.Sub(tokenOut.Amount.ToDec()) - // (x_0)(y_0) = (x_0 + in)(y_0 - out) - tokenAmountIn := solveConstantFunctionInvariant( - poolTokenOutBalance, poolPostSwapOutBalance, poolAssetOut.Weight.ToDec(), - poolAssetIn.Token.Amount.ToDec(), poolAssetIn.Weight.ToDec()).Neg() - - // We deduct a swap fee on the input asset. The swap happens by following the invariant curve on the input * (1 - swap fee) - // and then the swap fee is added to the pool. - // Thus in order to give X amount out, we solve the invariant for the invariant input. However invariant input = (1 - swapfee) * trade input. - // Therefore we divide by (1 - swapfee) here - tokenAmountInBeforeFee := tokenAmountIn.Quo(sdk.OneDec().Sub(swapFee)) - - // We round up tokenInAmt, as this is whats charged for the swap, for the precise amount out. - // Otherwise, the pool would under-charge by this rounding error. - tokenInAmt := tokenAmountInBeforeFee.Ceil().TruncateInt() - - if !tokenInAmt.IsPositive() { - return sdk.Coin{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "token amount must be positive") - } - return sdk.NewCoin(tokenInDenom, tokenInAmt), nil -} - -// SwapInAmtGivenOut is a mutative method for CalcOutAmtGivenIn, which includes the actual swap. -func (p *Pool) SwapInAmtGivenOut( - ctx sdk.Context, tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( - tokenIn sdk.Coin, err error, -) { - tokenInCoin, err := p.CalcInAmtGivenOut(ctx, tokensOut, tokenInDenom, swapFee) - if err != nil { - return sdk.Coin{}, err - } - - err = p.applySwap(ctx, sdk.Coins{tokenInCoin}, tokensOut) - if err != nil { - return sdk.Coin{}, err - } - return tokenInCoin, nil -} - -// ApplySwap. -func (p *Pool) applySwap(ctx sdk.Context, tokensIn sdk.Coins, tokensOut sdk.Coins) error { - // Also ensures that len(tokensIn) = 1 = len(tokensOut) - inPoolAsset, outPoolAsset, err := p.parsePoolAssetsCoins(tokensIn, tokensOut) - if err != nil { - return err - } - inPoolAsset.Token.Amount = inPoolAsset.Token.Amount.Add(tokensIn[0].Amount) - outPoolAsset.Token.Amount = outPoolAsset.Token.Amount.Sub(tokensOut[0].Amount) - - return p.UpdatePoolAssetBalances(sdk.NewCoins( - inPoolAsset.Token, - outPoolAsset.Token, - )) -} - -// SpotPrice returns the spot price of the pool -// This is the weight-adjusted balance of the tokens in the pool. -// In order reduce the propagated effect of incorrect trailing digits, -// we take the ratio of weights and divide this by ratio of supplies -// this is equivalent to spot_price = (Base_supply / Weight_base) / (Quote_supply / Weight_quote) -// but cancels out the common term in weight. -// -// panics if pool is misconfigured and has any weight as 0. -func (p Pool) SpotPrice(ctx sdk.Context, baseAsset, quoteAsset string) (sdk.Dec, error) { - quote, base, err := p.parsePoolAssetsByDenoms(quoteAsset, baseAsset) - if err != nil { - return sdk.Dec{}, err - } - if base.Weight.IsZero() || quote.Weight.IsZero() { - return sdk.Dec{}, errors.New("pool is misconfigured, got 0 weight") - } - - // spot_price = (Base_supply / Weight_base) / (Quote_supply / Weight_quote) - // spot_price = (weight_quote / weight_base) * (base_supply / quote_supply) - invWeightRatio := quote.Weight.ToDec().Quo(base.Weight.ToDec()) - supplyRatio := base.Token.Amount.ToDec().Quo(quote.Token.Amount.ToDec()) - fullRatio := supplyRatio.Mul(invWeightRatio) - // we want to round this to `SigFigs` of precision - ratio := osmomath.SigFigRound(fullRatio, types.SigFigs) - return ratio, nil -} - // balancer notation: pAo - pool shares amount out, given single asset in // the second argument requires the tokenWeightIn / total token weight. func calcPoolSharesOutGivenSingleAssetIn( @@ -236,178 +143,6 @@ func calcPoolSharesOutGivenSingleAssetIn( return poolAmountOut } -// calcPoolOutGivenSingleIn - balance pAo. -func (p *Pool) calcSingleAssetJoin(tokenIn sdk.Coin, swapFee sdk.Dec, tokenInPoolAsset PoolAsset, totalShares sdk.Int) (numShares sdk.Int, err error) { - _, err = p.GetPoolAsset(tokenIn.Denom) - if err != nil { - return sdk.ZeroInt(), err - } - - totalWeight := p.GetTotalWeight() - if totalWeight.IsZero() { - return sdk.ZeroInt(), errors.New("pool misconfigured, total weight = 0") - } - normalizedWeight := tokenInPoolAsset.Weight.ToDec().Quo(totalWeight.ToDec()) - return calcPoolSharesOutGivenSingleAssetIn( - tokenInPoolAsset.Token.Amount.ToDec(), - normalizedWeight, - totalShares.ToDec(), - tokenIn.Amount.ToDec(), - swapFee, - ).TruncateInt(), nil -} - -// JoinPool calculates the number of shares needed given tokensIn with swapFee applied. -// It updates the liquidity if the pool is joined successfully. If not, returns error. -// and updates pool accordingly. -func (p *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) { - numShares, newLiquidity, err := p.CalcJoinPoolShares(ctx, tokensIn, swapFee) - if err != nil { - return sdk.Int{}, err - } - - // update pool with the calculated share and liquidity needed to join pool - p.IncreaseLiquidity(numShares, newLiquidity) - return numShares, nil -} - -func (p *Pool) calcJoinPoolSharesBroken(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) { - poolAssets := p.GetAllPoolAssets() - poolAssetsByDenom := make(map[string]PoolAsset) - for _, poolAsset := range poolAssets { - poolAssetsByDenom[poolAsset.Token.Denom] = poolAsset - } - - totalShares := p.GetTotalShares() - - if tokensIn.Len() == 1 { - numShares, err = p.calcSingleAssetJoin(tokensIn[0], swapFee, poolAssetsByDenom[tokensIn[0].Denom], totalShares) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - - newLiquidity = tokensIn - - return numShares, newLiquidity, nil - } else if tokensIn.Len() != p.NumAssets() { - return sdk.ZeroInt(), sdk.NewCoins(), errors.New("balancer pool only supports LP'ing with one asset or all assets in pool") - } - - // Add all exact coins we can (no swap). ctx arg doesn't matter for Balancer. - numShares, remCoins, err := cfmm_common.MaximalExactRatioJoinBroken(p, sdk.Context{}, tokensIn) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - - // update liquidity for accurate calcSingleAssetJoin calculation - newLiquidity = tokensIn.Sub(remCoins) - for _, coin := range newLiquidity { - poolAsset := poolAssetsByDenom[coin.Denom] - poolAsset.Token.Amount = poolAssetsByDenom[coin.Denom].Token.Amount.Add(coin.Amount) - poolAssetsByDenom[coin.Denom] = poolAsset - } - - totalShares = totalShares.Add(numShares) - - // If there are coins that couldn't be perfectly joined, do single asset joins - // for each of them. - if !remCoins.Empty() { - for _, coin := range remCoins { - newShares, err := p.calcSingleAssetJoin(coin, swapFee, poolAssetsByDenom[coin.Denom], totalShares) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - - newLiquidity = newLiquidity.Add(coin) - numShares = numShares.Add(newShares) - } - } - - return numShares, newLiquidity, nil -} - -// CalcJoinPoolShares calculates the number of shares created to join pool with the provided amount of `tokenIn`. -// The input tokens must either be: -// - a single token -// - contain exactly the same tokens as the pool contains -// -// It returns the number of shares created, the amount of coins actually joined into the pool -// (in case of not being able to fully join), or an error. -func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { - if ctx.BlockHeight() < v10Fork { - return p.calcJoinPoolSharesBroken(ctx, tokensIn, swapFee) - } - // 1) Get pool current liquidity + and token weights - // 2) If single token provided, do single asset join and exit. - // 3) If multi-asset join, first do as much of a join as we can with no swaps. - // 4) Update pool shares / liquidity / remaining tokens to join accordingly - // 5) For every remaining token to LP, do a single asset join, and update pool shares / liquidity. - // - // Note that all single asset joins do incur swap fee. - // - // Since CalcJoinPoolShares is non-mutative, the steps for updating pool shares / liquidity are - // more complex / don't just alter the state. - // We should simplify this logic further in the future, using balancer multi-join equations. - - // 1) get all 'pool assets' (aka current pool liquidity + balancer weight) - poolAssetsByDenom, err := getPoolAssetsByDenom(p.GetAllPoolAssets()) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - - totalShares := p.GetTotalShares() - if tokensIn.Len() == 1 { - // 2) Single token provided, so do single asset join and exit. - numShares, err = p.calcSingleAssetJoin(tokensIn[0], swapFee, poolAssetsByDenom[tokensIn[0].Denom], totalShares) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - // we join all the tokens. - tokensJoined = tokensIn - return numShares, tokensJoined, nil - } else if tokensIn.Len() != p.NumAssets() { - return sdk.ZeroInt(), sdk.NewCoins(), errors.New("balancer pool only supports LP'ing with one asset or all assets in pool") - } - - // 3) JoinPoolNoSwap with as many tokens as we can. (What is in perfect ratio) - // * numShares is how many shares are perfectly matched. - // * remainingTokensIn is how many coins we have left to join, that have not already been used. - // if remaining coins is empty, logic is done (we joined all tokensIn) - numShares, remainingTokensIn, err := cfmm_common.MaximalExactRatioJoin(p, sdk.Context{}, tokensIn) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - if remainingTokensIn.Empty() { - tokensJoined = tokensIn - return numShares, tokensJoined, nil - } - - // 4) Still more coins to join, so we update the effective pool state here to account for - // join that just happened. - // * We add the joined coins to our "current pool liquidity" object (poolAssetsByDenom) - // * We increment a variable for our "newTotalShares" to add in the shares that've been added. - tokensJoined = tokensIn.Sub(remainingTokensIn) - if err := updateIntermediaryPoolAssetsLiquidity(tokensJoined, poolAssetsByDenom); err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - newTotalShares := totalShares.Add(numShares) - - // 5) Now single asset join each remaining coin. - newNumSharesFromRemaining, newLiquidityFromRemaining, err := p.calcJoinSingleAssetTokensIn(remainingTokensIn, newTotalShares, poolAssetsByDenom, swapFee) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - // update total amount LP'd variable, and total new LP shares variable, run safety check, and return - numShares = numShares.Add(newNumSharesFromRemaining) - tokensJoined = tokensJoined.Add(newLiquidityFromRemaining...) - - if tokensJoined.IsAnyGT(tokensIn) { - return sdk.ZeroInt(), sdk.NewCoins(), errors.New("An error has occurred, more coins joined than token In") - } - - return numShares, tokensJoined, nil -} - // getPoolAssetsByDenom return a mapping from pool asset // denom to the pool asset itself. There must be no duplicates. // Returns error, if any found. @@ -448,60 +183,6 @@ func updateIntermediaryPoolAssetsLiquidity(liquidity sdk.Coins, poolAssetsByDeno return nil } -// calcJoinSingleAssetTokensIn attempts to calculate single -// asset join for all tokensIn given totalShares in pool, -// poolAssetsByDenom and swapFee. totalShares is the number -// of shares in pool before beginnning to join any of the tokensIn. -// -// Returns totalNewShares and totalNewLiquidity from joining all tokensIn -// by mimicking individually single asset joining each. -// or error if fails to calculate join for any of the tokensIn. -func (p *Pool) calcJoinSingleAssetTokensIn(tokensIn sdk.Coins, totalShares sdk.Int, poolAssetsByDenom map[string]PoolAsset, swapFee sdk.Dec) (sdk.Int, sdk.Coins, error) { - totalNewShares := sdk.ZeroInt() - totalNewLiquidity := sdk.NewCoins() - for _, coin := range tokensIn { - newShares, err := p.calcSingleAssetJoin(coin, swapFee, poolAssetsByDenom[coin.Denom], totalShares.Add(totalNewShares)) - if err != nil { - return sdk.ZeroInt(), sdk.Coins{}, err - } - - totalNewLiquidity = totalNewLiquidity.Add(coin) - totalNewShares = totalNewShares.Add(newShares) - } - return totalNewShares, totalNewLiquidity, nil -} - -func (p *Pool) ExitPool(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { - exitingCoins, err = p.CalcExitPoolShares(ctx, exitingShares, exitFee) - if err != nil { - return sdk.Coins{}, err - } - - if err := p.exitPool(ctx, exitingCoins, exitingShares); err != nil { - return sdk.Coins{}, err - } - - return exitingCoins, nil -} - -// exitPool exits the pool given exitingCoins and exitingShares. -// updates the pool's liquidity and totalShares. -func (p *Pool) exitPool(ctx sdk.Context, exitingCoins sdk.Coins, exitingShares sdk.Int) error { - balances := p.GetTotalPoolLiquidity(ctx).Sub(exitingCoins) - if err := p.UpdatePoolAssetBalances(balances); err != nil { - return err - } - - totalShares := p.GetTotalShares() - p.TotalShares = sdk.NewCoin(p.TotalShares.Denom, totalShares.Sub(exitingShares)) - - return nil -} - -func (p *Pool) CalcExitPoolShares(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) { - return cfmm_common.CalcExitPool(ctx, p, exitingShares, exitFee) -} - // feeRatio returns the fee ratio that is defined as follows: // 1 - ((1 - normalizedTokenWeightOut) * swapFee) func feeRatio(normalizedWeight, swapFee sdk.Dec) sdk.Dec { @@ -525,69 +206,6 @@ func calcSingleAssetInGivenPoolSharesOut( return tokenAmountInFeeIncluded } -func (p *Pool) CalcTokenInShareAmountOut( - ctx sdk.Context, - tokenInDenom string, - shareOutAmount sdk.Int, - swapFee sdk.Dec, -) (tokenInAmount sdk.Int, err error) { - _, poolAssetIn, err := p.getPoolAssetAndIndex(tokenInDenom) - if err != nil { - return sdk.Int{}, err - } - - normalizedWeight := poolAssetIn.Weight.ToDec().Quo(p.GetTotalWeight().ToDec()) - - // We round up tokenInAmount, as this is whats charged for the swap, for the precise amount out. - // Otherwise, the pool would under-charge by this rounding error. - tokenInAmount = calcSingleAssetInGivenPoolSharesOut( - poolAssetIn.Token.Amount.ToDec(), - normalizedWeight, - p.GetTotalShares().ToDec(), - shareOutAmount.ToDec(), - swapFee, - ).Ceil().TruncateInt() - - if !tokenInAmount.IsPositive() { - return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatTokenAmountNotPositive, tokenInAmount.Int64()) - } - - return tokenInAmount, nil -} - -func (p *Pool) JoinPoolTokenInMaxShareAmountOut( - ctx sdk.Context, - tokenInDenom string, - shareOutAmount sdk.Int, -) (tokenInAmount sdk.Int, err error) { - _, poolAssetIn, err := p.getPoolAssetAndIndex(tokenInDenom) - if err != nil { - return sdk.Int{}, err - } - - normalizedWeight := poolAssetIn.Weight.ToDec().Quo(p.GetTotalWeight().ToDec()) - - tokenInAmount = calcSingleAssetInGivenPoolSharesOut( - poolAssetIn.Token.Amount.ToDec(), - normalizedWeight, - p.GetTotalShares().ToDec(), - shareOutAmount.ToDec(), - p.GetSwapFee(ctx), - ).TruncateInt() - - if !tokenInAmount.IsPositive() { - return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatTokenAmountNotPositive, tokenInAmount.Int64()) - } - - poolAssetIn.Token.Amount = poolAssetIn.Token.Amount.Add(tokenInAmount) - err = p.UpdatePoolAssetBalance(poolAssetIn.Token) - if err != nil { - return sdk.Int{}, err - } - - return tokenInAmount, nil -} - // calcPoolSharesInGivenSingleAssetOut returns pool shares amount in, given single asset out. // the returned shares in have the fee included in them. // the second argument requires the tokenWeightOut / total token weight. @@ -610,37 +228,3 @@ func calcPoolSharesInGivenSingleAssetOut( sharesInFeeIncluded := sharesIn.Quo(sdk.OneDec().Sub(exitFee)) return sharesInFeeIncluded } - -func (p *Pool) ExitSwapExactAmountOut( - ctx sdk.Context, - tokenOut sdk.Coin, - shareInMaxAmount sdk.Int, -) (shareInAmount sdk.Int, err error) { - _, poolAssetOut, err := p.getPoolAssetAndIndex(tokenOut.Denom) - if err != nil { - return sdk.Int{}, err - } - - sharesIn := calcPoolSharesInGivenSingleAssetOut( - poolAssetOut.Token.Amount.ToDec(), - poolAssetOut.Weight.ToDec().Quo(p.TotalWeight.ToDec()), - p.GetTotalShares().ToDec(), - tokenOut.Amount.ToDec(), - p.GetSwapFee(ctx), - p.GetExitFee(ctx), - ).TruncateInt() - - if !sharesIn.IsPositive() { - return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatSharesAmountNotPositive, sharesIn.Int64()) - } - - if sharesIn.GT(shareInMaxAmount) { - return sdk.Int{}, sdkerrors.Wrapf(types.ErrLimitMaxAmount, errMsgFormatSharesLargerThanMax, sharesIn.Int64(), shareInMaxAmount.Uint64()) - } - - if err := p.exitPool(ctx, sdk.NewCoins(tokenOut), sharesIn); err != nil { - return sdk.Int{}, err - } - - return sharesIn, nil -} diff --git a/x/gamm/pool-models/balancer/amm_test.go b/x/gamm/pool-models/balancer/amm_test.go index a0efc586ce1..ad26cc556f8 100644 --- a/x/gamm/pool-models/balancer/amm_test.go +++ b/x/gamm/pool-models/balancer/amm_test.go @@ -1,344 +1,52 @@ package balancer_test import ( - "fmt" "testing" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/osmoutils" "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) -// This test sets up 2 asset pools, and then checks the spot price on them. -// It uses the pools spot price method, rather than the Gamm keepers spot price method. -func (suite *KeeperTestSuite) TestBalancerSpotPrice() { - baseDenom := "uosmo" - quoteDenom := "uion" - +func TestBalancerPoolParams(t *testing.T) { + // Tests that creating a pool with the given pair of swapfee and exit fee + // errors or succeeds as intended. Furthermore, it checks that + // NewPool panics in the error case. tests := []struct { - name string - baseDenomPoolInput sdk.Coin - quoteDenomPoolInput sdk.Coin - expectError bool - expectedOutput sdk.Dec + SwapFee sdk.Dec + ExitFee sdk.Dec + shouldErr bool }{ - { - name: "equal value", - baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 100), - quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 100), - expectError: false, - expectedOutput: sdk.MustNewDecFromStr("1"), - }, - { - name: "1:2 ratio", - baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 100), - quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 200), - expectError: false, - expectedOutput: sdk.MustNewDecFromStr("0.500000000000000000"), - }, - { - name: "2:1 ratio", - baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 200), - quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 100), - expectError: false, - expectedOutput: sdk.MustNewDecFromStr("2.000000000000000000"), - }, - { - name: "rounding after sigfig ratio", - baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 220), - quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 115), - expectError: false, - expectedOutput: sdk.MustNewDecFromStr("1.913043480000000000"), // ans is 1.913043478260869565, rounded is 1.91304348 - }, - { - name: "check number of sig figs", - baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 100), - quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 300), - expectError: false, - expectedOutput: sdk.MustNewDecFromStr("0.333333330000000000"), - }, - { - name: "check number of sig figs high sizes", - baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 343569192534), - quoteDenomPoolInput: sdk.NewCoin(quoteDenom, sdk.MustNewDecFromStr("186633424395479094888742").TruncateInt()), - expectError: false, - expectedOutput: sdk.MustNewDecFromStr("0.000000000001840877"), - }, - } - - for _, tc := range tests { - suite.SetupTest() - - poolId := suite.PrepareUni2PoolWithAssets( - tc.baseDenomPoolInput, - tc.quoteDenomPoolInput, - ) - - pool, err := suite.App.GAMMKeeper.GetPoolAndPoke(suite.Ctx, poolId) - suite.Require().NoError(err, "test: %s", tc.name) - balancerPool, isPool := pool.(*balancer.Pool) - suite.Require().True(isPool, "test: %s", tc.name) - - sut := func() { - spotPrice, err := balancerPool.SpotPrice( - suite.Ctx, - tc.baseDenomPoolInput.Denom, - tc.quoteDenomPoolInput.Denom) - - if tc.expectError { - suite.Require().Error(err, "test: %s", tc.name) - } else { - suite.Require().NoError(err, "test: %s", tc.name) - suite.Require().True(spotPrice.Equal(tc.expectedOutput), - "test: %s\nSpot price wrong, got %s, expected %s\n", tc.name, - spotPrice, tc.expectedOutput) - } + // Should work + {defaultSwapFee, defaultExitFee, noErr}, + // Can't set the swap fee as negative + {sdk.NewDecWithPrec(-1, 2), defaultExitFee, wantErr}, + // Can't set the swap fee as 1 + {sdk.NewDec(1), defaultExitFee, wantErr}, + // Can't set the swap fee above 1 + {sdk.NewDecWithPrec(15, 1), defaultExitFee, wantErr}, + // Can't set the exit fee as negative + {defaultSwapFee, sdk.NewDecWithPrec(-1, 2), wantErr}, + // Can't set the exit fee as 1 + {defaultSwapFee, sdk.NewDec(1), wantErr}, + // Can't set the exit fee above 1 + {defaultSwapFee, sdk.NewDecWithPrec(15, 1), wantErr}, + } + + for i, params := range tests { + PoolParams := balancer.PoolParams{ + SwapFee: params.SwapFee, + ExitFee: params.ExitFee, } - assertPoolStateNotModified(suite.T(), balancerPool, sut) - } -} - -// TestCalculateAmountOutAndIn_InverseRelationship tests that the same amount of token is guaranteed upon -// sequential operation of CalcInAmtGivenOut and CalcOutAmtGivenIn. -func TestCalculateAmountOutAndIn_InverseRelationship(t *testing.T) { - type testcase struct { - denomOut string - initialPoolOut int64 - initialWeightOut int64 - initialCalcOut int64 - - denomIn string - initialPoolIn int64 - initialWeightIn int64 - } - - // For every test case in testcases, apply a swap fee in swapFeeCases. - testcases := []testcase{ - { - denomOut: "uosmo", - initialPoolOut: 1_000_000_000_000, - initialWeightOut: 100, - initialCalcOut: 100, - - denomIn: "ion", - initialPoolIn: 1_000_000_000_000, - initialWeightIn: 100, - }, - { - denomOut: "uosmo", - initialPoolOut: 1_000, - initialWeightOut: 100, - initialCalcOut: 100, - - denomIn: "ion", - initialPoolIn: 1_000_000, - initialWeightIn: 100, - }, - { - denomOut: "uosmo", - initialPoolOut: 1_000, - initialWeightOut: 100, - initialCalcOut: 100, - - denomIn: "ion", - initialPoolIn: 1_000_000, - initialWeightIn: 100, - }, - { - denomOut: "uosmo", - initialPoolOut: 1_000, - initialWeightOut: 200, - initialCalcOut: 100, - - denomIn: "ion", - initialPoolIn: 1_000_000, - initialWeightIn: 50, - }, - { - denomOut: "uosmo", - initialPoolOut: 1_000_000, - initialWeightOut: 200, - initialCalcOut: 100000, - - denomIn: "ion", - initialPoolIn: 1_000_000_000, - initialWeightIn: 50, - }, - } - - swapFeeCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} - - getTestCaseName := func(tc testcase, swapFeeCase string) string { - return fmt.Sprintf("tokenOutInitial: %d, tokenInInitial: %d, initialOut: %d, swapFee: %s", - tc.initialPoolOut, - tc.initialPoolIn, - tc.initialCalcOut, - swapFeeCase, - ) - } - - for _, tc := range testcases { - for _, swapFee := range swapFeeCases { - t.Run(getTestCaseName(tc, swapFee), func(t *testing.T) { - ctx := createTestContext(t) - - poolAssetOut := balancer.PoolAsset{ - Token: sdk.NewInt64Coin(tc.denomOut, tc.initialPoolOut), - Weight: sdk.NewInt(tc.initialWeightOut), - } - - poolAssetIn := balancer.PoolAsset{ - Token: sdk.NewInt64Coin(tc.denomIn, tc.initialPoolIn), - Weight: sdk.NewInt(tc.initialWeightIn), - } - - swapFeeDec, err := sdk.NewDecFromStr(swapFee) - require.NoError(t, err) - - exitFeeDec, err := sdk.NewDecFromStr("0") - require.NoError(t, err) - - pool := createTestPool(t, swapFeeDec, exitFeeDec, poolAssetOut, poolAssetIn) - require.NotNil(t, pool) - - initialOut := sdk.NewInt64Coin(poolAssetOut.Token.Denom, tc.initialCalcOut) - initialOutCoins := sdk.NewCoins(initialOut) - - sut := func() { - actualTokenIn, err := pool.CalcInAmtGivenOut(ctx, initialOutCoins, poolAssetIn.Token.Denom, swapFeeDec) - require.NoError(t, err) - - inverseTokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(actualTokenIn), poolAssetOut.Token.Denom, swapFeeDec) - require.NoError(t, err) - - require.Equal(t, initialOut.Denom, inverseTokenOut.Denom) - - expected := initialOut.Amount.ToDec() - actual := inverseTokenOut.Amount.ToDec() - - // allow a rounding error of up to 1 for this relation - tol := sdk.NewDec(1) - require.True(osmoutils.DecApproxEq(t, expected, actual, tol)) - } - - balancerPool, ok := pool.(*balancer.Pool) - require.True(t, ok) - - assertPoolStateNotModified(t, balancerPool, sut) - }) - } - } -} - -func TestCalcSingleAssetInAndOut_InverseRelationship(t *testing.T) { - type testcase struct { - initialPoolOut int64 - initialPoolIn int64 - initialWeightOut int64 - tokenOut int64 - initialWeightIn int64 - } - - // For every test case in testcases, apply a swap fee in swapFeeCases. - testcases := []testcase{ - { - initialPoolOut: 1_000_000_000_000, - tokenOut: 100, - initialWeightOut: 100, - initialWeightIn: 100, - }, - { - initialPoolOut: 1_000_000_000_000, - tokenOut: 100, - initialWeightOut: 50, - initialWeightIn: 100, - }, - { - initialPoolOut: 1_000_000_000_000, - tokenOut: 50, - initialWeightOut: 100, - initialWeightIn: 100, - }, - { - initialPoolOut: 1_000_000_000_000, - tokenOut: 100, - initialWeightOut: 100, - initialWeightIn: 50, - }, - { - initialPoolOut: 1_000_000, - tokenOut: 100, - initialWeightOut: 100, - initialWeightIn: 100, - }, - { - initialPoolOut: 2_351_333, - tokenOut: 7, - initialWeightOut: 148, - initialWeightIn: 57, - }, - { - initialPoolOut: 1_000, - tokenOut: 25, - initialWeightOut: 100, - initialWeightIn: 100, - }, - { - initialPoolOut: 1_000, - tokenOut: 26, - initialWeightOut: 100, - initialWeightIn: 100, - }, - } - - swapFeeCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} - - getTestCaseName := func(tc testcase, swapFeeCase string) string { - return fmt.Sprintf("initialPoolOut: %d, initialCalcOut: %d, initialWeightOut: %d, initialWeightIn: %d, swapFee: %s", - tc.initialPoolOut, - tc.tokenOut, - tc.initialWeightOut, - tc.initialWeightIn, - swapFeeCase, - ) - } - - for _, tc := range testcases { - for _, swapFee := range swapFeeCases { - t.Run(getTestCaseName(tc, swapFee), func(t *testing.T) { - swapFeeDec, err := sdk.NewDecFromStr(swapFee) - require.NoError(t, err) - - initialPoolBalanceOut := sdk.NewInt(tc.initialPoolOut) - - initialWeightOut := sdk.NewInt(tc.initialWeightOut) - initialWeightIn := sdk.NewInt(tc.initialWeightIn) - - initialTotalShares := types.InitPoolSharesSupply.ToDec() - initialCalcTokenOut := sdk.NewInt(tc.tokenOut) - - actualSharesOut := balancer.CalcPoolSharesOutGivenSingleAssetIn( - initialPoolBalanceOut.ToDec(), - initialWeightOut.ToDec().Quo(initialWeightOut.Add(initialWeightIn).ToDec()), - initialTotalShares, - initialCalcTokenOut.ToDec(), - swapFeeDec, - ) - - inverseCalcTokenOut := balancer.CalcSingleAssetInGivenPoolSharesOut( - initialPoolBalanceOut.Add(initialCalcTokenOut).ToDec(), - initialWeightOut.ToDec().Quo(initialWeightOut.Add(initialWeightIn).ToDec()), - initialTotalShares.Add(actualSharesOut), - actualSharesOut, - swapFeeDec, - ) - - tol := sdk.NewDec(1) - require.True(osmoutils.DecApproxEq(t, initialCalcTokenOut.ToDec(), inverseCalcTokenOut, tol)) - }) + err := PoolParams.Validate(dummyPoolAssets) + if params.shouldErr { + require.Error(t, err, "unexpected lack of error, tc %v", i) + // Check that these are also caught if passed to the underlying pool creation func + _, err = balancer.NewBalancerPool(1, PoolParams, dummyPoolAssets, defaultFutureGovernor, defaultCurBlockTime) + require.Error(t, err) + } else { + require.NoError(t, err, "unexpected error, tc %v", i) } } } diff --git a/x/gamm/pool-models/balancer/balancer_pool.go b/x/gamm/pool-models/balancer/balancer_pool.go deleted file mode 100644 index 9735d976086..00000000000 --- a/x/gamm/pool-models/balancer/balancer_pool.go +++ /dev/null @@ -1,601 +0,0 @@ -package balancer - -import ( - "errors" - "fmt" - "sort" - "strings" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" -) - -const ( - errMsgFormatNoPoolAssetFound = "can't find the PoolAsset (%s)" -) - -var ( - _ types.PoolI = &Pool{} - _ types.PoolAmountOutExtension = &Pool{} -) - -// NewPool returns a weighted CPMM pool with the provided parameters, and initial assets. -// Invariants that are assumed to be satisfied and not checked: -// (This is handled in ValidateBasic) -// * 2 <= len(assets) <= 8 -// * FutureGovernor is valid -// * poolID doesn't already exist -func NewBalancerPool(poolId uint64, balancerPoolParams PoolParams, assets []PoolAsset, futureGovernor string, blockTime time.Time) (Pool, error) { - poolAddr := types.NewPoolAddress(poolId) - - // pool thats created up to ensuring the assets and params are valid. - // We assume that FuturePoolGovernor is valid. - pool := &Pool{ - Address: poolAddr.String(), - Id: poolId, - PoolParams: PoolParams{}, - TotalWeight: sdk.ZeroInt(), - TotalShares: sdk.NewCoin(types.GetPoolShareDenom(poolId), types.InitPoolSharesSupply), - PoolAssets: nil, - FuturePoolGovernor: futureGovernor, - } - - err := pool.setInitialPoolAssets(assets) - if err != nil { - return Pool{}, err - } - - sortedPoolAssets := pool.GetAllPoolAssets() - err = balancerPoolParams.Validate(sortedPoolAssets) - if err != nil { - return Pool{}, err - } - - err = pool.setInitialPoolParams(balancerPoolParams, sortedPoolAssets, blockTime) - if err != nil { - return Pool{}, err - } - - return *pool, nil -} - -// GetAddress returns the address of a pool. -// If the pool address is not bech32 valid, it returns an empty address. -func (pa Pool) GetAddress() sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(pa.Address) - if err != nil { - panic(fmt.Sprintf("could not bech32 decode address of pool with id: %d", pa.GetId())) - } - return addr -} - -func (pa Pool) GetId() uint64 { - return pa.Id -} - -func (pa Pool) GetSwapFee(_ sdk.Context) sdk.Dec { - return pa.PoolParams.SwapFee -} - -func (pa Pool) GetTotalPoolLiquidity(_ sdk.Context) sdk.Coins { - return PoolAssetsCoins(pa.PoolAssets) -} - -func (pa Pool) GetExitFee(_ sdk.Context) sdk.Dec { - return pa.PoolParams.ExitFee -} - -func (pa Pool) GetPoolParams() PoolParams { - return pa.PoolParams -} - -func (pa Pool) GetTotalWeight() sdk.Int { - return pa.TotalWeight -} - -func (pa Pool) GetTotalShares() sdk.Int { - return pa.TotalShares.Amount -} - -func (pa *Pool) AddTotalShares(amt sdk.Int) { - pa.TotalShares.Amount = pa.TotalShares.Amount.Add(amt) -} - -func (pa *Pool) SubTotalShares(amt sdk.Int) { - pa.TotalShares.Amount = pa.TotalShares.Amount.Sub(amt) -} - -// setInitialPoolAssets sets the PoolAssets in the pool. -// It is only designed to be called at the pool's creation. -// If the same denom's PoolAsset exists, will return error. -// The list of PoolAssets must be sorted. This is done to enable fast searching for a PoolAsset by denomination. -// TODO: Unify story for validation of []PoolAsset, some is here, some is in CreatePool.ValidateBasic() -func (pa *Pool) setInitialPoolAssets(PoolAssets []PoolAsset) error { - exists := make(map[string]bool) - for _, asset := range pa.PoolAssets { - exists[asset.Token.Denom] = true - } - - newTotalWeight := pa.TotalWeight - scaledPoolAssets := make([]PoolAsset, 0, len(PoolAssets)) - - // TODO: Refactor this into PoolAsset.validate() - for _, asset := range PoolAssets { - if asset.Token.Amount.LTE(sdk.ZeroInt()) { - return fmt.Errorf("can't add the zero or negative balance of token") - } - - err := asset.ValidateWeight() - if err != nil { - return err - } - - if exists[asset.Token.Denom] { - return fmt.Errorf("same PoolAsset already exists") - } - exists[asset.Token.Denom] = true - - // Scale weight from the user provided weight to the correct internal weight - asset.Weight = asset.Weight.MulRaw(GuaranteedWeightPrecision) - scaledPoolAssets = append(scaledPoolAssets, asset) - newTotalWeight = newTotalWeight.Add(asset.Weight) - } - - // TODO: Change this to a more efficient sorted insert algorithm. - // Furthermore, consider changing the underlying data type to allow in-place modification if the - // number of PoolAssets is expected to be large. - pa.PoolAssets = append(pa.PoolAssets, scaledPoolAssets...) - SortPoolAssetsByDenom(pa.PoolAssets) - - pa.TotalWeight = newTotalWeight - - return nil -} - -// ValidateUserSpecifiedWeight ensures that a weight that is provided from user-input anywhere -// for creating a pool obeys the expected guarantees. -// Namely, that the weight is in the range [1, MaxUserSpecifiedWeight) -func ValidateUserSpecifiedWeight(weight sdk.Int) error { - if !weight.IsPositive() { - return sdkerrors.Wrap(types.ErrNotPositiveWeight, weight.String()) - } - - if weight.GTE(MaxUserSpecifiedWeight) { - return sdkerrors.Wrap(types.ErrWeightTooLarge, weight.String()) - } - return nil -} - -// setInitialPoolParams -func (pa *Pool) setInitialPoolParams(params PoolParams, sortedAssets []PoolAsset, curBlockTime time.Time) error { - pa.PoolParams = params - if params.SmoothWeightChangeParams != nil { - // set initial assets - initialWeights := make([]PoolAsset, len(sortedAssets)) - for i, v := range sortedAssets { - initialWeights[i] = PoolAsset{ - Weight: v.Weight, - Token: sdk.Coin{Denom: v.Token.Denom, Amount: sdk.ZeroInt()}, - } - } - params.SmoothWeightChangeParams.InitialPoolWeights = initialWeights - - // sort target weights by denom - targetPoolWeights := params.SmoothWeightChangeParams.TargetPoolWeights - SortPoolAssetsByDenom(targetPoolWeights) - - // scale target pool weights by GuaranteedWeightPrecision - for i, v := range targetPoolWeights { - err := ValidateUserSpecifiedWeight(v.Weight) - if err != nil { - return err - } - pa.PoolParams.SmoothWeightChangeParams.TargetPoolWeights[i] = PoolAsset{ - Weight: v.Weight.MulRaw(GuaranteedWeightPrecision), - Token: v.Token, - } - } - - // Set start time if not present. - if params.SmoothWeightChangeParams.StartTime.Unix() <= 0 { - // Per https://golang.org/pkg/time/#Time.Unix, should be timezone independent - params.SmoothWeightChangeParams.StartTime = time.Unix(curBlockTime.Unix(), 0) - } - } - - return nil -} - -// GetPoolAssets returns the denom's PoolAsset, If the PoolAsset doesn't exist, will return error. -// As above, it will search the denom's PoolAsset by using binary search. -// So, it is important to make sure that the PoolAssets are sorted. -func (pa Pool) GetPoolAsset(denom string) (PoolAsset, error) { - _, asset, err := pa.getPoolAssetAndIndex(denom) - return asset, err -} - -// Returns a pool asset, and its index. If err != nil, then the index will be valid. -func (pa Pool) getPoolAssetAndIndex(denom string) (int, PoolAsset, error) { - if denom == "" { - return -1, PoolAsset{}, fmt.Errorf("you tried to find the PoolAsset with empty denom") - } - - if len(pa.PoolAssets) == 0 { - return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) - } - - i := sort.Search(len(pa.PoolAssets), func(i int) bool { - PoolAssetA := pa.PoolAssets[i] - - compare := strings.Compare(PoolAssetA.Token.Denom, denom) - return compare >= 0 - }) - - if i < 0 || i >= len(pa.PoolAssets) { - return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) - } - - if pa.PoolAssets[i].Token.Denom != denom { - return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) - } - - return i, pa.PoolAssets[i], nil -} - -func (p Pool) parsePoolAssetsByDenoms(tokenADenom, tokenBDenom string) ( - Aasset PoolAsset, Basset PoolAsset, err error, -) { - Aasset, found1 := GetPoolAssetByDenom(p.PoolAssets, tokenADenom) - Basset, found2 := GetPoolAssetByDenom(p.PoolAssets, tokenBDenom) - if !(found1 && found2) { - return Aasset, Basset, errors.New("one of the provided pool denoms does not exist in pool") - } - return Aasset, Basset, nil -} - -func (p Pool) parsePoolAssets(tokensA sdk.Coins, tokenBDenom string) ( - tokenA sdk.Coin, Aasset PoolAsset, Basset PoolAsset, err error, -) { - if len(tokensA) != 1 { - return tokenA, Aasset, Basset, errors.New("expected tokensB to be of length one") - } - Aasset, Basset, err = p.parsePoolAssetsByDenoms(tokensA[0].Denom, tokenBDenom) - return tokensA[0], Aasset, Basset, err -} - -func (p Pool) parsePoolAssetsCoins(tokensA sdk.Coins, tokensB sdk.Coins) ( - Aasset PoolAsset, Basset PoolAsset, err error, -) { - if len(tokensB) != 1 { - return Aasset, Basset, errors.New("expected tokensA to be of length one") - } - _, Aasset, Basset, err = p.parsePoolAssets(tokensA, tokensB[0].Denom) - return Aasset, Basset, err -} - -func (p *Pool) IncreaseLiquidity(sharesOut sdk.Int, coinsIn sdk.Coins) { - err := p.addToPoolAssetBalances(coinsIn) - if err != nil { - panic(err) - } - p.AddTotalShares(sharesOut) -} - -func (pa *Pool) UpdatePoolAssetBalance(coin sdk.Coin) error { - // Check that PoolAsset exists. - assetIndex, existingAsset, err := pa.getPoolAssetAndIndex(coin.Denom) - if err != nil { - return err - } - - if coin.Amount.LTE(sdk.ZeroInt()) { - return fmt.Errorf("can't set the pool's balance of a token to be zero or negative") - } - - // Update the supply of the asset - existingAsset.Token = coin - pa.PoolAssets[assetIndex] = existingAsset - return nil -} - -func (pa *Pool) UpdatePoolAssetBalances(coins sdk.Coins) error { - // Ensures that there are no duplicate denoms, all denom's are valid, - // and amount is > 0 - err := coins.Validate() - if err != nil { - return fmt.Errorf("provided coins are invalid, %v", err) - } - - for _, coin := range coins { - // TODO: We may be able to make this log(|coins|) faster in how it - // looks up denom -> Coin by doing a multi-search, - // but as we don't anticipate |coins| to be large, we omit this. - err = pa.UpdatePoolAssetBalance(coin) - if err != nil { - return err - } - } - - return nil -} - -func (pa *Pool) addToPoolAssetBalances(coins sdk.Coins) error { - for _, coin := range coins { - i, poolAsset, err := pa.getPoolAssetAndIndex(coin.Denom) - if err != nil { - return err - } - poolAsset.Token.Amount = poolAsset.Token.Amount.Add(coin.Amount) - pa.PoolAssets[i] = poolAsset - } - return nil -} - -func (pa Pool) GetPoolAssets(denoms ...string) ([]PoolAsset, error) { - result := make([]PoolAsset, 0, len(denoms)) - - for _, denom := range denoms { - PoolAsset, err := pa.GetPoolAsset(denom) - if err != nil { - return nil, err - } - - result = append(result, PoolAsset) - } - - return result, nil -} - -func (pa Pool) GetAllPoolAssets() []PoolAsset { - copyslice := make([]PoolAsset, len(pa.PoolAssets)) - copy(copyslice, pa.PoolAssets) - return copyslice -} - -// updateAllWeights updates all of the pool's internal weights to be equal to -// the new weights. It assumes that `newWeights` are sorted by denomination, -// and only contain the same denominations as the pool already contains. -// This does not affect the asset balances. -// If any of the above are not satisfied, this will panic. -// (As all input to this should be generated from the state machine) -// TODO: (post-launch) If newWeights includes a new denomination, -// add the balance as well to the pool's internal measurements. -// TODO: (post-launch) If newWeights excludes an existing denomination, -// remove the weight from the pool, and figure out something to do -// with any remaining coin. -func (pa *Pool) updateAllWeights(newWeights []PoolAsset) { - if len(pa.PoolAssets) != len(newWeights) { - panic("updateAllWeights called with invalid input, len(newWeights) != len(existingWeights)") - } - totalWeight := sdk.ZeroInt() - for i, asset := range pa.PoolAssets { - if asset.Token.Denom != newWeights[i].Token.Denom { - panic(fmt.Sprintf("updateAllWeights called with invalid input, "+ - "expected new weights' %vth asset to be %v, got %v", - i, asset.Token.Denom, newWeights[i].Token.Denom)) - } - err := newWeights[i].ValidateWeight() - if err != nil { - panic("updateAllWeights: Tried to set an invalid weight") - } - pa.PoolAssets[i].Weight = newWeights[i].Weight - totalWeight = totalWeight.Add(pa.PoolAssets[i].Weight) - } - pa.TotalWeight = totalWeight -} - -// PokePool checks to see if the pool's token weights need to be updated, and -// if so, does so. Currently doesn't do anything outside out LBPs. -func (pa *Pool) PokePool(blockTime time.Time) { - // check if pool weights didn't change - poolWeightsChanging := pa.PoolParams.SmoothWeightChangeParams != nil - if !poolWeightsChanging { - return - } - - params := *pa.PoolParams.SmoothWeightChangeParams - - // The weights w(t) for the pool at time `t` is defined in one of three - // possible ways: - // - // 1. t <= start_time: w(t) = initial_pool_weights - // - // 2. start_time < t <= start_time + duration: - // w(t) = initial_pool_weights + (t - start_time) * - // (target_pool_weights - initial_pool_weights) / (duration) - // - // 3. t > start_time + duration: w(t) = target_pool_weights - switch { - case blockTime.Before(params.StartTime) || params.StartTime.Equal(blockTime): - // case 1: t <= start_time - return - - case blockTime.After(params.StartTime.Add(params.Duration)): - // case 2: start_time < t <= start_time + duration: - - // Update weights to be the target weights. - // - // TODO: When we add support for adding new assets via this method, ensure - // the new asset has some token sent with it. - pa.updateAllWeights(params.TargetPoolWeights) - - // we've finished updating the weights, so reset the following fields - pa.PoolParams.SmoothWeightChangeParams = nil - return - - default: - // case 3: t > start_time + duration: w(t) = target_pool_weights - - shiftedBlockTime := blockTime.Sub(params.StartTime).Milliseconds() - percentDurationElapsed := sdk.NewDec(shiftedBlockTime).QuoInt64(params.Duration.Milliseconds()) - - // If the duration elapsed is equal to the total time, or a rounding error - // makes it seem like it is, just set to target weight. - if percentDurationElapsed.GTE(sdk.OneDec()) { - pa.updateAllWeights(params.TargetPoolWeights) - return - } - - // below will be auto-truncated according to internal weight precision routine - totalWeightsDiff := subPoolAssetWeights(params.TargetPoolWeights, params.InitialPoolWeights) - scaledDiff := poolAssetsMulDec(totalWeightsDiff, percentDurationElapsed) - updatedWeights := addPoolAssetWeights(params.InitialPoolWeights, scaledDiff) - - pa.updateAllWeights(updatedWeights) - } -} - -func (pa Pool) GetTokenWeight(denom string) (sdk.Int, error) { - PoolAsset, err := pa.GetPoolAsset(denom) - if err != nil { - return sdk.Int{}, err - } - - return PoolAsset.Weight, nil -} - -func (pa Pool) GetTokenBalance(denom string) (sdk.Int, error) { - PoolAsset, err := pa.GetPoolAsset(denom) - if err != nil { - return sdk.Int{}, err - } - - return PoolAsset.Token.Amount, nil -} - -func (pa Pool) NumAssets() int { - return len(pa.PoolAssets) -} - -func (pa Pool) IsActive(ctx sdk.Context) bool { - return true -} - -func NewPoolParams(swapFee, exitFee sdk.Dec, params *SmoothWeightChangeParams) PoolParams { - return PoolParams{ - SwapFee: swapFee, - ExitFee: exitFee, - SmoothWeightChangeParams: params, - } -} - -func (params PoolParams) Validate(poolWeights []PoolAsset) error { - if params.ExitFee.IsNegative() { - return types.ErrNegativeExitFee - } - - if params.ExitFee.GTE(sdk.OneDec()) { - return types.ErrTooMuchExitFee - } - - if params.SwapFee.IsNegative() { - return types.ErrNegativeSwapFee - } - - if params.SwapFee.GTE(sdk.OneDec()) { - return types.ErrTooMuchSwapFee - } - - if params.SmoothWeightChangeParams != nil { - targetWeights := params.SmoothWeightChangeParams.TargetPoolWeights - // Ensure it has the right number of weights - if len(targetWeights) != len(poolWeights) { - return types.ErrPoolParamsInvalidNumDenoms - } - // Validate all user specified weights - for _, v := range targetWeights { - err := ValidateUserSpecifiedWeight(v.Weight) - if err != nil { - return err - } - } - // Ensure that all the target weight denoms are same as pool asset weights - sortedTargetPoolWeights := SortPoolAssetsOutOfPlaceByDenom(targetWeights) - sortedPoolWeights := SortPoolAssetsOutOfPlaceByDenom(poolWeights) - for i, v := range sortedPoolWeights { - if sortedTargetPoolWeights[i].Token.Denom != v.Token.Denom { - return types.ErrPoolParamsInvalidDenom - } - } - - // No start time validation needed - - // We do not need to validate InitialPoolWeights, as we set that ourselves - // in setInitialPoolParams - - // TODO: Is there anything else we can validate for duration? - if params.SmoothWeightChangeParams.Duration <= 0 { - return errors.New("params.SmoothWeightChangeParams must have a positive duration") - } - } - - return nil -} - -func (params PoolParams) GetPoolSwapFee() sdk.Dec { - return params.SwapFee -} - -func (params PoolParams) GetPoolExitFee() sdk.Dec { - return params.ExitFee -} - -// subPoolAssetWeights subtracts the weights of two different pool asset slices. -// It assumes that both pool assets have the same token denominations, -// with the denominations in the same order. -// Returned weights can (and probably will have some) be negative. -func subPoolAssetWeights(base []PoolAsset, other []PoolAsset) []PoolAsset { - weightDifference := make([]PoolAsset, len(base)) - // TODO: Consider deleting these panics for performance - if len(base) != len(other) { - panic("subPoolAssetWeights called with invalid input, len(base) != len(other)") - } - for i, asset := range base { - if asset.Token.Denom != other[i].Token.Denom { - panic(fmt.Sprintf("subPoolAssetWeights called with invalid input, "+ - "expected other's %vth asset to be %v, got %v", - i, asset.Token.Denom, other[i].Token.Denom)) - } - curWeightDiff := asset.Weight.Sub(other[i].Weight) - weightDifference[i] = PoolAsset{Token: asset.Token, Weight: curWeightDiff} - } - return weightDifference -} - -// addPoolAssetWeights adds the weights of two different pool asset slices. -// It assumes that both pool assets have the same token denominations, -// with the denominations in the same order. -// Returned weights can be negative. -func addPoolAssetWeights(base []PoolAsset, other []PoolAsset) []PoolAsset { - weightSum := make([]PoolAsset, len(base)) - // TODO: Consider deleting these panics for performance - if len(base) != len(other) { - panic("addPoolAssetWeights called with invalid input, len(base) != len(other)") - } - for i, asset := range base { - if asset.Token.Denom != other[i].Token.Denom { - panic(fmt.Sprintf("addPoolAssetWeights called with invalid input, "+ - "expected other's %vth asset to be %v, got %v", - i, asset.Token.Denom, other[i].Token.Denom)) - } - curWeightSum := asset.Weight.Add(other[i].Weight) - weightSum[i] = PoolAsset{Token: asset.Token, Weight: curWeightSum} - } - return weightSum -} - -// assumes 0 < d < 1 -func poolAssetsMulDec(base []PoolAsset, d sdk.Dec) []PoolAsset { - newWeights := make([]PoolAsset, len(base)) - for i, asset := range base { - // TODO: This can adversarially panic at the moment! (as can Pool.TotalWeight) - // Ensure this won't be able to panic in the future PR where we bound - // each assets weight, and add precision - newWeight := d.MulInt(asset.Weight).RoundInt() - newWeights[i] = PoolAsset{Token: asset.Token, Weight: newWeight} - } - return newWeights -} diff --git a/x/gamm/pool-models/balancer/balancer_pool_test.go b/x/gamm/pool-models/balancer/balancer_pool_test.go deleted file mode 100644 index 646b8d6f351..00000000000 --- a/x/gamm/pool-models/balancer/balancer_pool_test.go +++ /dev/null @@ -1,567 +0,0 @@ -package balancer - -import ( - "fmt" - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - defaultSwapFee = sdk.MustNewDecFromStr("0.025") - defaultExitFee = sdk.MustNewDecFromStr("0.025") - defaultPoolId = uint64(10) - defaultBalancerPoolParams = PoolParams{ - SwapFee: defaultSwapFee, - ExitFee: defaultExitFee, - } - defaultFutureGovernor = "" - defaultCurBlockTime = time.Unix(1618700000, 0) - // - dummyPoolAssets = []PoolAsset{} - wantErr = true - noErr = false -) - -// Expected is un-scaled -func testTotalWeight(t *testing.T, expected sdk.Int, pool Pool) { - scaledExpected := expected.MulRaw(GuaranteedWeightPrecision) - require.Equal(t, - scaledExpected.String(), - pool.GetTotalWeight().String()) -} - -func TestBalancerPoolParams(t *testing.T) { - // Tests that creating a pool with the given pair of swapfee and exit fee - // errors or succeeds as intended. Furthermore, it checks that - // NewPool panics in the error case. - tests := []struct { - SwapFee sdk.Dec - ExitFee sdk.Dec - shouldErr bool - }{ - // Should work - {defaultSwapFee, defaultExitFee, noErr}, - // Can't set the swap fee as negative - {sdk.NewDecWithPrec(-1, 2), defaultExitFee, wantErr}, - // Can't set the swap fee as 1 - {sdk.NewDec(1), defaultExitFee, wantErr}, - // Can't set the swap fee above 1 - {sdk.NewDecWithPrec(15, 1), defaultExitFee, wantErr}, - // Can't set the exit fee as negative - {defaultSwapFee, sdk.NewDecWithPrec(-1, 2), wantErr}, - // Can't set the exit fee as 1 - {defaultSwapFee, sdk.NewDec(1), wantErr}, - // Can't set the exit fee above 1 - {defaultSwapFee, sdk.NewDecWithPrec(15, 1), wantErr}, - } - - for i, params := range tests { - PoolParams := PoolParams{ - SwapFee: params.SwapFee, - ExitFee: params.ExitFee, - } - err := PoolParams.Validate(dummyPoolAssets) - if params.shouldErr { - require.Error(t, err, "unexpected lack of error, tc %v", i) - // Check that these are also caught if passed to the underlying pool creation func - _, err = NewBalancerPool(1, PoolParams, dummyPoolAssets, defaultFutureGovernor, defaultCurBlockTime) - require.Error(t, err) - } else { - require.NoError(t, err, "unexpected error, tc %v", i) - } - } -} - -// TODO: Refactor this into multiple tests -func TestBalancerPoolUpdatePoolAssetBalance(t *testing.T) { - var poolId uint64 = 10 - - initialAssets := []PoolAsset{ - { - Weight: sdk.NewInt(100), - Token: sdk.NewCoin("test1", sdk.NewInt(50000)), - }, - { - Weight: sdk.NewInt(200), - Token: sdk.NewCoin("test2", sdk.NewInt(50000)), - }, - } - - pacc, err := NewBalancerPool(poolId, defaultBalancerPoolParams, initialAssets, defaultFutureGovernor, defaultCurBlockTime) - require.NoError(t, err) - - _, err = pacc.GetPoolAsset("unknown") - require.Error(t, err) - _, err = pacc.GetPoolAsset("") - require.Error(t, err) - - testTotalWeight(t, sdk.NewInt(300), pacc) - - // Break abstractions and start reasoning about the underlying internal representation's APIs. - // TODO: This test actually just needs to be refactored to not be doing this, and just - // create a different pool each time. - - err = pacc.setInitialPoolAssets([]PoolAsset{{ - Weight: sdk.NewInt(-1), - Token: sdk.NewCoin("negativeWeight", sdk.NewInt(50000)), - }}) - - require.Error(t, err) - - err = pacc.setInitialPoolAssets([]PoolAsset{{ - Weight: sdk.NewInt(0), - Token: sdk.NewCoin("zeroWeight", sdk.NewInt(50000)), - }}) - require.Error(t, err) - - err = pacc.UpdatePoolAssetBalance( - sdk.NewCoin("test1", sdk.NewInt(0))) - require.Error(t, err) - - err = pacc.UpdatePoolAssetBalance( - sdk.Coin{Denom: "test1", Amount: sdk.NewInt(-1)}, - ) - require.Error(t, err) - - err = pacc.UpdatePoolAssetBalance( - sdk.NewCoin("test1", sdk.NewInt(1))) - require.NoError(t, err) - - testTotalWeight(t, sdk.NewInt(300), pacc) - - PoolAsset, err := pacc.GetPoolAsset("test1") - require.NoError(t, err) - require.Equal(t, sdk.NewInt(1).String(), PoolAsset.Token.Amount.String()) -} - -func TestBalancerPoolAssetsWeightAndTokenBalance(t *testing.T) { - // TODO: Add more cases - // asset names should be i ascending order, starting from test1 - tests := []struct { - assets []PoolAsset - shouldErr bool - }{ - // weight 0 - { - []PoolAsset{ - { - Weight: sdk.NewInt(0), - Token: sdk.NewCoin("test1", sdk.NewInt(50000)), - }, - }, - wantErr, - }, - // negative weight - { - []PoolAsset{ - { - Weight: sdk.NewInt(-1), - Token: sdk.NewCoin("test1", sdk.NewInt(50000)), - }, - }, - wantErr, - }, - // 0 token amount - { - []PoolAsset{ - { - Weight: sdk.NewInt(100), - Token: sdk.NewCoin("test1", sdk.NewInt(0)), - }, - }, - wantErr, - }, - // negative token amount - { - []PoolAsset{ - { - Weight: sdk.NewInt(100), - Token: sdk.Coin{ - Denom: "test1", - Amount: sdk.NewInt(-1), - }, - }, - }, - wantErr, - }, - // total weight 300 - { - []PoolAsset{ - { - Weight: sdk.NewInt(200), - Token: sdk.NewCoin("test2", sdk.NewInt(50000)), - }, - { - Weight: sdk.NewInt(100), - Token: sdk.NewCoin("test1", sdk.NewInt(10000)), - }, - }, - noErr, - }, - // two of the same token - { - []PoolAsset{ - { - Weight: sdk.NewInt(200), - Token: sdk.NewCoin("test2", sdk.NewInt(50000)), - }, - { - Weight: sdk.NewInt(300), - Token: sdk.NewCoin("test1", sdk.NewInt(10000)), - }, - { - Weight: sdk.NewInt(100), - Token: sdk.NewCoin("test2", sdk.NewInt(10000)), - }, - }, - wantErr, - }, - // total weight 7300 - { - []PoolAsset{ - { - Weight: sdk.NewInt(200), - Token: sdk.NewCoin("test2", sdk.NewInt(50000)), - }, - { - Weight: sdk.NewInt(100), - Token: sdk.NewCoin("test1", sdk.NewInt(10000)), - }, - { - Weight: sdk.NewInt(7000), - Token: sdk.NewCoin("test3", sdk.NewInt(10000)), - }, - }, - noErr, - }, - } - - var poolId uint64 = 10 - - for i, tc := range tests { - pacc, err := NewBalancerPool(poolId, defaultBalancerPoolParams, tc.assets, defaultFutureGovernor, defaultCurBlockTime) - if tc.shouldErr { - require.Error(t, err, "unexpected lack of error, tc %v", i) - } else { - require.NoError(t, err, "unexpected error, tc %v", i) - expectedTotalWeight := sdk.ZeroInt() - for i, asset := range tc.assets { - expectedTotalWeight = expectedTotalWeight.Add(asset.Weight) - - // Ensure pool assets are sorted - require.Equal(t, "test"+fmt.Sprint(i+1), pacc.PoolAssets[i].Token.Denom) - } - testTotalWeight(t, expectedTotalWeight, pacc) - } - } -} - -// TODO: Figure out what parts of this test, if any, make sense. -func TestGetBalancerPoolAssets(t *testing.T) { - // Adds []PoolAssets, one after another - // if the addition doesn't error, adds the weight of the pool assets to a running total, - // and ensures the pool's total weight is equal to the expected. - // This also ensures that the pool assets remain sorted within the pool. - // Furthermore, it ensures that GetPoolAsset succeeds for everything in the pool, - // and fails for things not in it. - denomNotInPool := "xyzCoin" - - assets := []PoolAsset{ - { - Weight: sdk.NewInt(200), - Token: sdk.NewCoin("test2", sdk.NewInt(50000)), - }, - { - Weight: sdk.NewInt(100), - Token: sdk.NewCoin("test1", sdk.NewInt(10000)), - }, - { - Weight: sdk.NewInt(200), - Token: sdk.NewCoin("test3", sdk.NewInt(50000)), - }, - { - Weight: sdk.NewInt(100), - Token: sdk.NewCoin("test4", sdk.NewInt(10000)), - }, - } - - // TODO: We need way more robust test cases here, and should table drive these cases - pacc, err := NewBalancerPool(defaultPoolId, defaultBalancerPoolParams, assets, defaultFutureGovernor, defaultCurBlockTime) - require.NoError(t, err) - - // Hardcoded GetPoolAssets tests. - assets, err = pacc.GetPoolAssets("test1", "test2") - require.NoError(t, err) - require.Equal(t, 2, len(assets)) - - assets, err = pacc.GetPoolAssets("test1", "test2", "test3", "test4") - require.NoError(t, err) - require.Equal(t, 4, len(assets)) - - _, err = pacc.GetPoolAssets("test1", "test5") - require.Error(t, err) - _, err = pacc.GetPoolAssets(denomNotInPool) - require.Error(t, err) - - assets, err = pacc.GetPoolAssets() - require.NoError(t, err) - require.Equal(t, 0, len(assets)) -} - -func TestLBPParamsEmptyStartTime(t *testing.T) { - // Test that when the start time is empty, the pool - // sets its start time to be the first start time it is called on - defaultDuration := 100 * time.Second - - initialPoolAssets := []PoolAsset{ - { - Weight: sdk.NewInt(1), - Token: sdk.NewCoin("asset1", sdk.NewInt(1000)), - }, - { - Weight: sdk.NewInt(1), - Token: sdk.NewCoin("asset2", sdk.NewInt(1000)), - }, - } - - params := SmoothWeightChangeParams{ - Duration: defaultDuration, - TargetPoolWeights: []PoolAsset{ - { - Weight: sdk.NewInt(1), - Token: sdk.NewCoin("asset1", sdk.NewInt(0)), - }, - { - Weight: sdk.NewInt(2), - Token: sdk.NewCoin("asset2", sdk.NewInt(0)), - }, - }, - } - - pacc, err := NewBalancerPool(defaultPoolId, PoolParams{ - SmoothWeightChangeParams: ¶ms, - SwapFee: defaultSwapFee, - ExitFee: defaultExitFee, - }, initialPoolAssets, defaultFutureGovernor, defaultCurBlockTime) - require.NoError(t, err) - - // Consistency check that SmoothWeightChangeParams params are set - require.NotNil(t, pacc.PoolParams.SmoothWeightChangeParams) - // Ensure that the start time got set - require.Equal(t, pacc.PoolParams.SmoothWeightChangeParams.StartTime, defaultCurBlockTime) -} - -func TestBalancerPoolPokeTokenWeights(t *testing.T) { - // Set default date - defaultStartTime := time.Unix(1618703511, 0) - defaultStartTimeUnix := defaultStartTime.Unix() - defaultDuration := 100 * time.Second - floatGuaranteedPrecision := float64(GuaranteedWeightPrecision) - - // testCases don't need to be ordered by time. but the blockTime should be - // less than the end time of the SmoothWeightChange. Testing past the end time - // is already handled. - type testCase struct { - blockTime time.Time - expectedWeights []sdk.Int - } - - // Tests how the pool weights get updated via PokeTokenWeights at different block times. - // The framework underneath will automatically add tests for times before the start time, - // at the start time, at the end time, and after the end time. It is up to the test writer to - // test the behavior at times in-between. - tests := []struct { - // We take the initial weights from here - params SmoothWeightChangeParams - cases []testCase - }{ - { - // 1:1 pool, between asset1 and asset2 - // transitioning to a 1:2 pool - params: SmoothWeightChangeParams{ - StartTime: defaultStartTime, - Duration: defaultDuration, - InitialPoolWeights: []PoolAsset{ - { - Weight: sdk.NewInt(1), - Token: sdk.NewCoin("asset1", sdk.NewInt(0)), - }, - { - Weight: sdk.NewInt(1), - Token: sdk.NewCoin("asset2", sdk.NewInt(0)), - }, - }, - TargetPoolWeights: []PoolAsset{ - { - Weight: sdk.NewInt(1), - Token: sdk.NewCoin("asset1", sdk.NewInt(0)), - }, - { - Weight: sdk.NewInt(2), - Token: sdk.NewCoin("asset2", sdk.NewInt(0)), - }, - }, - }, - cases: []testCase{ - { - // Halfway through at 50 seconds elapsed - blockTime: time.Unix(defaultStartTimeUnix+50, 0), - expectedWeights: []sdk.Int{ - sdk.NewInt(1 * GuaranteedWeightPrecision), - // Halfway between 1 & 2 - sdk.NewInt(3 * GuaranteedWeightPrecision / 2), - }, - }, - { - // Quarter way through at 25 seconds elapsed - blockTime: time.Unix(defaultStartTimeUnix+25, 0), - expectedWeights: []sdk.Int{ - sdk.NewInt(1 * GuaranteedWeightPrecision), - // Quarter way between 1 & 2 = 1.25 - sdk.NewInt(int64(1.25 * floatGuaranteedPrecision)), - }, - }, - }, - }, - { - // 2:2 pool, between asset1 and asset2 - // transitioning to a 4:1 pool - params: SmoothWeightChangeParams{ - StartTime: defaultStartTime, - Duration: defaultDuration, - InitialPoolWeights: []PoolAsset{ - { - Weight: sdk.NewInt(2), - Token: sdk.NewCoin("asset1", sdk.NewInt(0)), - }, - { - Weight: sdk.NewInt(2), - Token: sdk.NewCoin("asset2", sdk.NewInt(0)), - }, - }, - TargetPoolWeights: []PoolAsset{ - { - Weight: sdk.NewInt(4), - Token: sdk.NewCoin("asset1", sdk.NewInt(0)), - }, - { - Weight: sdk.NewInt(1), - Token: sdk.NewCoin("asset2", sdk.NewInt(0)), - }, - }, - }, - cases: []testCase{ - { - // Halfway through at 50 seconds elapsed - blockTime: time.Unix(defaultStartTimeUnix+50, 0), - expectedWeights: []sdk.Int{ - // Halfway between 2 & 4 - sdk.NewInt(6 * GuaranteedWeightPrecision / 2), - // Halfway between 1 & 2 - sdk.NewInt(3 * GuaranteedWeightPrecision / 2), - }, - }, - { - // Quarter way through at 25 seconds elapsed - blockTime: time.Unix(defaultStartTimeUnix+25, 0), - expectedWeights: []sdk.Int{ - // Quarter way between 2 & 4 = 2.5 - sdk.NewInt(int64(2.5 * floatGuaranteedPrecision)), - // Quarter way between 2 & 1 = 1.75 - sdk.NewInt(int64(1.75 * floatGuaranteedPrecision)), - }, - }, - }, - }, - } - - // Add test cases at a time before the start, the start, the end, and a time after the end. - addDefaultCases := func(params SmoothWeightChangeParams, cases []testCase) []testCase { - // Set times one second before the start, and one second after the end - timeBeforeWeightChangeStart := time.Unix(params.StartTime.Unix()-1, 0) - timeAtWeightChangeEnd := params.StartTime.Add(params.Duration) - timeAfterWeightChangeEnd := time.Unix(timeAtWeightChangeEnd.Unix()+1, 0) - initialWeights := make([]sdk.Int, len(params.InitialPoolWeights)) - finalWeights := make([]sdk.Int, len(params.TargetPoolWeights)) - for i, v := range params.InitialPoolWeights { - initialWeights[i] = v.Weight.MulRaw(GuaranteedWeightPrecision) - } - for i, v := range params.TargetPoolWeights { - // Doesn't need to be scaled, due to this being done already in param initialization, - // and because params is only shallow copied - finalWeights[i] = v.Weight - } - // Set the test cases for times before the start, and the start - updatedCases := []testCase{ - { - blockTime: timeBeforeWeightChangeStart, - expectedWeights: initialWeights, - }, - { - blockTime: params.StartTime, - expectedWeights: initialWeights, - }, - } - // Append the provided cases - updatedCases = append(updatedCases, cases...) - finalCases := []testCase{ - { - blockTime: timeAtWeightChangeEnd, - expectedWeights: finalWeights, - }, - { - blockTime: timeAfterWeightChangeEnd, - expectedWeights: finalWeights, - }, - } - // Append the final cases - updatedCases = append(updatedCases, finalCases...) - return updatedCases - } - - for poolNum, tc := range tests { - paramsCopy := tc.params - // First we create the initial pool assets we will use - initialPoolAssets := make([]PoolAsset, len(paramsCopy.InitialPoolWeights)) - for i, asset := range paramsCopy.InitialPoolWeights { - assetCopy := PoolAsset{ - Weight: asset.Weight, - Token: sdk.NewInt64Coin(asset.Token.Denom, 10000), - } - initialPoolAssets[i] = assetCopy - } - // Initialize the pool - pacc, err := NewBalancerPool(uint64(poolNum), PoolParams{ - SwapFee: defaultSwapFee, - ExitFee: defaultExitFee, - SmoothWeightChangeParams: &tc.params, - }, initialPoolAssets, defaultFutureGovernor, defaultCurBlockTime) - require.NoError(t, err, "poolNumber %v", poolNum) - - // Consistency check that SmoothWeightChangeParams params are set - require.NotNil(t, pacc.PoolParams.SmoothWeightChangeParams) - - testCases := addDefaultCases(paramsCopy, tc.cases) - for caseNum, testCase := range testCases { - pacc.PokePool(testCase.blockTime) - - totalWeight := sdk.ZeroInt() - - for assetNum, asset := range pacc.GetAllPoolAssets() { - require.Equal(t, testCase.expectedWeights[assetNum], asset.Weight, - "Didn't get the expected weights, poolNumber %v, caseNumber %v, assetNumber %v", - poolNum, caseNum, assetNum) - - totalWeight = totalWeight.Add(asset.Weight) - } - - require.Equal(t, totalWeight, pacc.GetTotalWeight()) - } - // Should have been deleted by the last test case of after PokeTokenWeights pokes past end time. - require.Nil(t, pacc.PoolParams.SmoothWeightChangeParams) - } -} diff --git a/x/gamm/pool-models/balancer/marshal_test.go b/x/gamm/pool-models/balancer/marshal_test.go index 867886fde20..56756466942 100644 --- a/x/gamm/pool-models/balancer/marshal_test.go +++ b/x/gamm/pool-models/balancer/marshal_test.go @@ -1,4 +1,4 @@ -package balancer +package balancer_test import ( "encoding/hex" @@ -8,10 +8,12 @@ import ( "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/require" + "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" + sdk "github.com/cosmos/cosmos-sdk/types" ) -var ymlAssetTest = []PoolAsset{ +var ymlAssetTest = []balancer.PoolAsset{ { Weight: sdk.NewInt(200), Token: sdk.NewCoin("test2", sdk.NewInt(50000)), @@ -25,7 +27,7 @@ var ymlAssetTest = []PoolAsset{ func TestPoolJson(t *testing.T) { var poolId uint64 = 10 - jsonAssetTest := []PoolAsset{ + jsonAssetTest := []balancer.PoolAsset{ { Weight: sdk.NewInt(200), Token: sdk.NewCoin("test2", sdk.NewInt(50000)), @@ -35,7 +37,7 @@ func TestPoolJson(t *testing.T) { Token: sdk.NewCoin("test1", sdk.NewInt(10000)), }, } - pacc, err := NewBalancerPool(poolId, PoolParams{ + pacc, err := balancer.NewBalancerPool(poolId, balancer.PoolParams{ SwapFee: defaultSwapFee, ExitFee: defaultExitFee, }, jsonAssetTest, defaultFutureGovernor, defaultCurBlockTime) @@ -48,7 +50,7 @@ func TestPoolJson(t *testing.T) { require.NoError(t, err) require.Equal(t, string(bz1), string(bz)) - var a Pool + var a balancer.Pool require.NoError(t, json.Unmarshal(bz, &a)) require.Equal(t, pacc.String(), a.String()) } @@ -58,7 +60,7 @@ func TestPoolProtoMarshal(t *testing.T) { decodedByteArray, err := hex.DecodeString("0a3f6f736d6f316b727033387a7a63337a7a356173396e64716b79736b686b7a76367839653330636b63713567346c637375357770776371793073613364656132100a1a260a113235303030303030303030303030303030121132353030303030303030303030303030302a110a0c67616d6d2f706f6f6c2f3130120130321e0a0e0a05746573743112053130303030120c313037333734313832343030321e0a0e0a05746573743212053530303030120c3231343734383336343830303a0c333232313232353437323030") require.NoError(t, err) - pool2 := Pool{} + pool2 := balancer.Pool{} err = proto.Unmarshal(decodedByteArray, &pool2) require.NoError(t, err) @@ -67,7 +69,7 @@ func TestPoolProtoMarshal(t *testing.T) { require.Equal(t, pool2.PoolParams.ExitFee, defaultExitFee) require.Equal(t, pool2.FuturePoolGovernor, "") require.Equal(t, pool2.TotalShares, sdk.Coin{Denom: "gamm/pool/10", Amount: sdk.ZeroInt()}) - require.Equal(t, pool2.PoolAssets, []PoolAsset{ + require.Equal(t, pool2.PoolAssets, []balancer.PoolAsset{ { Token: sdk.Coin{ Denom: "test1", diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go new file mode 100644 index 00000000000..a1da2389e1b --- /dev/null +++ b/x/gamm/pool-models/balancer/pool.go @@ -0,0 +1,949 @@ +package balancer + +import ( + "errors" + "fmt" + "sort" + "strings" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/osmosis-labs/osmosis/v7/osmomath" + "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/cfmm_common" + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +const ( + errMsgFormatSharesAmountNotPositive = "shares amount must be positive, was %d" + errMsgFormatTokenAmountNotPositive = "token amount must be positive, was %d" + errMsgFormatTokensLargerThanMax = "%d resulted tokens is larger than the max amount of %d" + errMsgFormatSharesLargerThanMax = "%d resulted shares is larger than the max amount of %d" + errMsgFormatFailedInterimLiquidityUpdate = "failed to update interim liquidity - pool asset %s does not exist" + errMsgFormatRepeatingPoolAssetsNotAllowed = "repeating pool assets not allowed, found %s" + errMsgFormatNoPoolAssetFound = "can't find the PoolAsset (%s)" + + v10Fork = 4713065 +) + +var ( + _ types.PoolI = &Pool{} + _ types.PoolAmountOutExtension = &Pool{} +) + +// NewPool returns a weighted CPMM pool with the provided parameters, and initial assets. +// Invariants that are assumed to be satisfied and not checked: +// (This is handled in ValidateBasic) +// * 2 <= len(assets) <= 8 +// * FutureGovernor is valid +// * poolID doesn't already exist +func NewBalancerPool(poolId uint64, balancerPoolParams PoolParams, assets []PoolAsset, futureGovernor string, blockTime time.Time) (Pool, error) { + poolAddr := types.NewPoolAddress(poolId) + + // pool thats created up to ensuring the assets and params are valid. + // We assume that FuturePoolGovernor is valid. + pool := &Pool{ + Address: poolAddr.String(), + Id: poolId, + PoolParams: PoolParams{}, + TotalWeight: sdk.ZeroInt(), + TotalShares: sdk.NewCoin(types.GetPoolShareDenom(poolId), types.InitPoolSharesSupply), + PoolAssets: nil, + FuturePoolGovernor: futureGovernor, + } + + err := pool.SetInitialPoolAssets(assets) + if err != nil { + return Pool{}, err + } + + sortedPoolAssets := pool.GetAllPoolAssets() + err = balancerPoolParams.Validate(sortedPoolAssets) + if err != nil { + return Pool{}, err + } + + err = pool.setInitialPoolParams(balancerPoolParams, sortedPoolAssets, blockTime) + if err != nil { + return Pool{}, err + } + + return *pool, nil +} + +// GetAddress returns the address of a pool. +// If the pool address is not bech32 valid, it returns an empty address. +func (pa Pool) GetAddress() sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(pa.Address) + if err != nil { + panic(fmt.Sprintf("could not bech32 decode address of pool with id: %d", pa.GetId())) + } + return addr +} + +func (pa Pool) GetId() uint64 { + return pa.Id +} + +func (pa Pool) GetSwapFee(_ sdk.Context) sdk.Dec { + return pa.PoolParams.SwapFee +} + +func (pa Pool) GetTotalPoolLiquidity(_ sdk.Context) sdk.Coins { + return PoolAssetsCoins(pa.PoolAssets) +} + +func (pa Pool) GetExitFee(_ sdk.Context) sdk.Dec { + return pa.PoolParams.ExitFee +} + +func (pa Pool) GetPoolParams() PoolParams { + return pa.PoolParams +} + +func (pa Pool) GetTotalWeight() sdk.Int { + return pa.TotalWeight +} + +func (pa Pool) GetTotalShares() sdk.Int { + return pa.TotalShares.Amount +} + +func (pa *Pool) AddTotalShares(amt sdk.Int) { + pa.TotalShares.Amount = pa.TotalShares.Amount.Add(amt) +} + +func (pa *Pool) SubTotalShares(amt sdk.Int) { + pa.TotalShares.Amount = pa.TotalShares.Amount.Sub(amt) +} + +// SetInitialPoolAssets sets the PoolAssets in the pool. It is only designed to +// be called at the pool's creation. If the same denom's PoolAsset exists, will +// return error. +// +// The list of PoolAssets must be sorted. This is done to enable fast searching +// for a PoolAsset by denomination. +// TODO: Unify story for validation of []PoolAsset, some is here, some is in +// CreatePool.ValidateBasic() +func (pa *Pool) SetInitialPoolAssets(PoolAssets []PoolAsset) error { + exists := make(map[string]bool) + for _, asset := range pa.PoolAssets { + exists[asset.Token.Denom] = true + } + + newTotalWeight := pa.TotalWeight + scaledPoolAssets := make([]PoolAsset, 0, len(PoolAssets)) + + // TODO: Refactor this into PoolAsset.validate() + for _, asset := range PoolAssets { + if asset.Token.Amount.LTE(sdk.ZeroInt()) { + return fmt.Errorf("can't add the zero or negative balance of token") + } + + err := asset.ValidateWeight() + if err != nil { + return err + } + + if exists[asset.Token.Denom] { + return fmt.Errorf("same PoolAsset already exists") + } + exists[asset.Token.Denom] = true + + // Scale weight from the user provided weight to the correct internal weight + asset.Weight = asset.Weight.MulRaw(GuaranteedWeightPrecision) + scaledPoolAssets = append(scaledPoolAssets, asset) + newTotalWeight = newTotalWeight.Add(asset.Weight) + } + + // TODO: Change this to a more efficient sorted insert algorithm. + // Furthermore, consider changing the underlying data type to allow in-place modification if the + // number of PoolAssets is expected to be large. + pa.PoolAssets = append(pa.PoolAssets, scaledPoolAssets...) + SortPoolAssetsByDenom(pa.PoolAssets) + + pa.TotalWeight = newTotalWeight + + return nil +} + +// setInitialPoolParams +func (pa *Pool) setInitialPoolParams(params PoolParams, sortedAssets []PoolAsset, curBlockTime time.Time) error { + pa.PoolParams = params + if params.SmoothWeightChangeParams != nil { + // set initial assets + initialWeights := make([]PoolAsset, len(sortedAssets)) + for i, v := range sortedAssets { + initialWeights[i] = PoolAsset{ + Weight: v.Weight, + Token: sdk.Coin{Denom: v.Token.Denom, Amount: sdk.ZeroInt()}, + } + } + params.SmoothWeightChangeParams.InitialPoolWeights = initialWeights + + // sort target weights by denom + targetPoolWeights := params.SmoothWeightChangeParams.TargetPoolWeights + SortPoolAssetsByDenom(targetPoolWeights) + + // scale target pool weights by GuaranteedWeightPrecision + for i, v := range targetPoolWeights { + err := ValidateUserSpecifiedWeight(v.Weight) + if err != nil { + return err + } + pa.PoolParams.SmoothWeightChangeParams.TargetPoolWeights[i] = PoolAsset{ + Weight: v.Weight.MulRaw(GuaranteedWeightPrecision), + Token: v.Token, + } + } + + // Set start time if not present. + if params.SmoothWeightChangeParams.StartTime.Unix() <= 0 { + // Per https://golang.org/pkg/time/#Time.Unix, should be timezone independent + params.SmoothWeightChangeParams.StartTime = time.Unix(curBlockTime.Unix(), 0) + } + } + + return nil +} + +// GetPoolAssets returns the denom's PoolAsset, If the PoolAsset doesn't exist, will return error. +// As above, it will search the denom's PoolAsset by using binary search. +// So, it is important to make sure that the PoolAssets are sorted. +func (pa Pool) GetPoolAsset(denom string) (PoolAsset, error) { + _, asset, err := pa.getPoolAssetAndIndex(denom) + return asset, err +} + +// Returns a pool asset, and its index. If err != nil, then the index will be valid. +func (pa Pool) getPoolAssetAndIndex(denom string) (int, PoolAsset, error) { + if denom == "" { + return -1, PoolAsset{}, fmt.Errorf("you tried to find the PoolAsset with empty denom") + } + + if len(pa.PoolAssets) == 0 { + return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) + } + + i := sort.Search(len(pa.PoolAssets), func(i int) bool { + PoolAssetA := pa.PoolAssets[i] + + compare := strings.Compare(PoolAssetA.Token.Denom, denom) + return compare >= 0 + }) + + if i < 0 || i >= len(pa.PoolAssets) { + return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) + } + + if pa.PoolAssets[i].Token.Denom != denom { + return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) + } + + return i, pa.PoolAssets[i], nil +} + +func (p Pool) parsePoolAssetsByDenoms(tokenADenom, tokenBDenom string) ( + Aasset PoolAsset, Basset PoolAsset, err error, +) { + Aasset, found1 := GetPoolAssetByDenom(p.PoolAssets, tokenADenom) + Basset, found2 := GetPoolAssetByDenom(p.PoolAssets, tokenBDenom) + if !(found1 && found2) { + return Aasset, Basset, errors.New("one of the provided pool denoms does not exist in pool") + } + return Aasset, Basset, nil +} + +func (p Pool) parsePoolAssets(tokensA sdk.Coins, tokenBDenom string) ( + tokenA sdk.Coin, Aasset PoolAsset, Basset PoolAsset, err error, +) { + if len(tokensA) != 1 { + return tokenA, Aasset, Basset, errors.New("expected tokensB to be of length one") + } + Aasset, Basset, err = p.parsePoolAssetsByDenoms(tokensA[0].Denom, tokenBDenom) + return tokensA[0], Aasset, Basset, err +} + +func (p Pool) parsePoolAssetsCoins(tokensA sdk.Coins, tokensB sdk.Coins) ( + Aasset PoolAsset, Basset PoolAsset, err error, +) { + if len(tokensB) != 1 { + return Aasset, Basset, errors.New("expected tokensA to be of length one") + } + _, Aasset, Basset, err = p.parsePoolAssets(tokensA, tokensB[0].Denom) + return Aasset, Basset, err +} + +func (p *Pool) IncreaseLiquidity(sharesOut sdk.Int, coinsIn sdk.Coins) { + err := p.addToPoolAssetBalances(coinsIn) + if err != nil { + panic(err) + } + p.AddTotalShares(sharesOut) +} + +func (pa *Pool) UpdatePoolAssetBalance(coin sdk.Coin) error { + // Check that PoolAsset exists. + assetIndex, existingAsset, err := pa.getPoolAssetAndIndex(coin.Denom) + if err != nil { + return err + } + + if coin.Amount.LTE(sdk.ZeroInt()) { + return fmt.Errorf("can't set the pool's balance of a token to be zero or negative") + } + + // Update the supply of the asset + existingAsset.Token = coin + pa.PoolAssets[assetIndex] = existingAsset + return nil +} + +func (pa *Pool) UpdatePoolAssetBalances(coins sdk.Coins) error { + // Ensures that there are no duplicate denoms, all denom's are valid, + // and amount is > 0 + err := coins.Validate() + if err != nil { + return fmt.Errorf("provided coins are invalid, %v", err) + } + + for _, coin := range coins { + // TODO: We may be able to make this log(|coins|) faster in how it + // looks up denom -> Coin by doing a multi-search, + // but as we don't anticipate |coins| to be large, we omit this. + err = pa.UpdatePoolAssetBalance(coin) + if err != nil { + return err + } + } + + return nil +} + +func (pa *Pool) addToPoolAssetBalances(coins sdk.Coins) error { + for _, coin := range coins { + i, poolAsset, err := pa.getPoolAssetAndIndex(coin.Denom) + if err != nil { + return err + } + poolAsset.Token.Amount = poolAsset.Token.Amount.Add(coin.Amount) + pa.PoolAssets[i] = poolAsset + } + return nil +} + +func (pa Pool) GetPoolAssets(denoms ...string) ([]PoolAsset, error) { + result := make([]PoolAsset, 0, len(denoms)) + + for _, denom := range denoms { + PoolAsset, err := pa.GetPoolAsset(denom) + if err != nil { + return nil, err + } + + result = append(result, PoolAsset) + } + + return result, nil +} + +func (pa Pool) GetAllPoolAssets() []PoolAsset { + copyslice := make([]PoolAsset, len(pa.PoolAssets)) + copy(copyslice, pa.PoolAssets) + return copyslice +} + +// updateAllWeights updates all of the pool's internal weights to be equal to +// the new weights. It assumes that `newWeights` are sorted by denomination, +// and only contain the same denominations as the pool already contains. +// This does not affect the asset balances. +// If any of the above are not satisfied, this will panic. +// (As all input to this should be generated from the state machine) +// TODO: (post-launch) If newWeights includes a new denomination, +// add the balance as well to the pool's internal measurements. +// TODO: (post-launch) If newWeights excludes an existing denomination, +// remove the weight from the pool, and figure out something to do +// with any remaining coin. +func (pa *Pool) updateAllWeights(newWeights []PoolAsset) { + if len(pa.PoolAssets) != len(newWeights) { + panic("updateAllWeights called with invalid input, len(newWeights) != len(existingWeights)") + } + totalWeight := sdk.ZeroInt() + for i, asset := range pa.PoolAssets { + if asset.Token.Denom != newWeights[i].Token.Denom { + panic(fmt.Sprintf("updateAllWeights called with invalid input, "+ + "expected new weights' %vth asset to be %v, got %v", + i, asset.Token.Denom, newWeights[i].Token.Denom)) + } + err := newWeights[i].ValidateWeight() + if err != nil { + panic("updateAllWeights: Tried to set an invalid weight") + } + pa.PoolAssets[i].Weight = newWeights[i].Weight + totalWeight = totalWeight.Add(pa.PoolAssets[i].Weight) + } + pa.TotalWeight = totalWeight +} + +// PokePool checks to see if the pool's token weights need to be updated, and +// if so, does so. Currently doesn't do anything outside out LBPs. +func (pa *Pool) PokePool(blockTime time.Time) { + // check if pool weights didn't change + poolWeightsChanging := pa.PoolParams.SmoothWeightChangeParams != nil + if !poolWeightsChanging { + return + } + + params := *pa.PoolParams.SmoothWeightChangeParams + + // The weights w(t) for the pool at time `t` is defined in one of three + // possible ways: + // + // 1. t <= start_time: w(t) = initial_pool_weights + // + // 2. start_time < t <= start_time + duration: + // w(t) = initial_pool_weights + (t - start_time) * + // (target_pool_weights - initial_pool_weights) / (duration) + // + // 3. t > start_time + duration: w(t) = target_pool_weights + switch { + case blockTime.Before(params.StartTime) || params.StartTime.Equal(blockTime): + // case 1: t <= start_time + return + + case blockTime.After(params.StartTime.Add(params.Duration)): + // case 2: start_time < t <= start_time + duration: + + // Update weights to be the target weights. + // + // TODO: When we add support for adding new assets via this method, ensure + // the new asset has some token sent with it. + pa.updateAllWeights(params.TargetPoolWeights) + + // we've finished updating the weights, so reset the following fields + pa.PoolParams.SmoothWeightChangeParams = nil + return + + default: + // case 3: t > start_time + duration: w(t) = target_pool_weights + + shiftedBlockTime := blockTime.Sub(params.StartTime).Milliseconds() + percentDurationElapsed := sdk.NewDec(shiftedBlockTime).QuoInt64(params.Duration.Milliseconds()) + + // If the duration elapsed is equal to the total time, or a rounding error + // makes it seem like it is, just set to target weight. + if percentDurationElapsed.GTE(sdk.OneDec()) { + pa.updateAllWeights(params.TargetPoolWeights) + return + } + + // below will be auto-truncated according to internal weight precision routine + totalWeightsDiff := subPoolAssetWeights(params.TargetPoolWeights, params.InitialPoolWeights) + scaledDiff := poolAssetsMulDec(totalWeightsDiff, percentDurationElapsed) + updatedWeights := addPoolAssetWeights(params.InitialPoolWeights, scaledDiff) + + pa.updateAllWeights(updatedWeights) + } +} + +func (pa Pool) GetTokenWeight(denom string) (sdk.Int, error) { + PoolAsset, err := pa.GetPoolAsset(denom) + if err != nil { + return sdk.Int{}, err + } + + return PoolAsset.Weight, nil +} + +func (pa Pool) GetTokenBalance(denom string) (sdk.Int, error) { + PoolAsset, err := pa.GetPoolAsset(denom) + if err != nil { + return sdk.Int{}, err + } + + return PoolAsset.Token.Amount, nil +} + +func (pa Pool) NumAssets() int { + return len(pa.PoolAssets) +} + +func (pa Pool) IsActive(ctx sdk.Context) bool { + return true +} + +// CalcOutAmtGivenIn calculates tokens to be swapped out given the provided +// amount and fee deducted, using solveConstantFunctionInvariant. +func (p Pool) CalcOutAmtGivenIn( + ctx sdk.Context, + tokensIn sdk.Coins, + tokenOutDenom string, + swapFee sdk.Dec, +) (sdk.Coin, error) { + tokenIn, poolAssetIn, poolAssetOut, err := p.parsePoolAssets(tokensIn, tokenOutDenom) + if err != nil { + return sdk.Coin{}, err + } + + tokenAmountInAfterFee := tokenIn.Amount.ToDec().Mul(sdk.OneDec().Sub(swapFee)) + poolTokenInBalance := poolAssetIn.Token.Amount.ToDec() + poolPostSwapInBalance := poolTokenInBalance.Add(tokenAmountInAfterFee) + + // deduct swapfee on the tokensIn + // delta balanceOut is positive(tokens inside the pool decreases) + tokenAmountOut := solveConstantFunctionInvariant( + poolTokenInBalance, + poolPostSwapInBalance, + poolAssetIn.Weight.ToDec(), + poolAssetOut.Token.Amount.ToDec(), + poolAssetOut.Weight.ToDec(), + ) + + // We ignore the decimal component, as we round down the token amount out. + tokenAmountOutInt := tokenAmountOut.TruncateInt() + if !tokenAmountOutInt.IsPositive() { + return sdk.Coin{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "token amount must be positive") + } + + return sdk.NewCoin(tokenOutDenom, tokenAmountOutInt), nil +} + +// SwapOutAmtGivenIn is a mutative method for CalcOutAmtGivenIn, which includes the actual swap. +func (p *Pool) SwapOutAmtGivenIn( + ctx sdk.Context, + tokensIn sdk.Coins, + tokenOutDenom string, + swapFee sdk.Dec, +) ( + tokenOut sdk.Coin, err error, +) { + tokenOutCoin, err := p.CalcOutAmtGivenIn(ctx, tokensIn, tokenOutDenom, swapFee) + if err != nil { + return sdk.Coin{}, err + } + + err = p.applySwap(ctx, tokensIn, sdk.Coins{tokenOutCoin}) + if err != nil { + return sdk.Coin{}, err + } + return tokenOutCoin, nil +} + +// CalcInAmtGivenOut calculates token to be provided, fee added, +// given the swapped out amount, using solveConstantFunctionInvariant. +func (p Pool) CalcInAmtGivenOut( + ctx sdk.Context, tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( + tokenIn sdk.Coin, err error, +) { + tokenOut, poolAssetOut, poolAssetIn, err := p.parsePoolAssets(tokensOut, tokenInDenom) + if err != nil { + return sdk.Coin{}, err + } + + // delta balanceOut is positive(tokens inside the pool decreases) + poolTokenOutBalance := poolAssetOut.Token.Amount.ToDec() + poolPostSwapOutBalance := poolTokenOutBalance.Sub(tokenOut.Amount.ToDec()) + // (x_0)(y_0) = (x_0 + in)(y_0 - out) + tokenAmountIn := solveConstantFunctionInvariant( + poolTokenOutBalance, poolPostSwapOutBalance, poolAssetOut.Weight.ToDec(), + poolAssetIn.Token.Amount.ToDec(), poolAssetIn.Weight.ToDec()).Neg() + + // We deduct a swap fee on the input asset. The swap happens by following the invariant curve on the input * (1 - swap fee) + // and then the swap fee is added to the pool. + // Thus in order to give X amount out, we solve the invariant for the invariant input. However invariant input = (1 - swapfee) * trade input. + // Therefore we divide by (1 - swapfee) here + tokenAmountInBeforeFee := tokenAmountIn.Quo(sdk.OneDec().Sub(swapFee)) + + // We round up tokenInAmt, as this is whats charged for the swap, for the precise amount out. + // Otherwise, the pool would under-charge by this rounding error. + tokenInAmt := tokenAmountInBeforeFee.Ceil().TruncateInt() + + if !tokenInAmt.IsPositive() { + return sdk.Coin{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "token amount must be positive") + } + return sdk.NewCoin(tokenInDenom, tokenInAmt), nil +} + +// SwapInAmtGivenOut is a mutative method for CalcOutAmtGivenIn, which includes the actual swap. +func (p *Pool) SwapInAmtGivenOut( + ctx sdk.Context, tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( + tokenIn sdk.Coin, err error, +) { + tokenInCoin, err := p.CalcInAmtGivenOut(ctx, tokensOut, tokenInDenom, swapFee) + if err != nil { + return sdk.Coin{}, err + } + + err = p.applySwap(ctx, sdk.Coins{tokenInCoin}, tokensOut) + if err != nil { + return sdk.Coin{}, err + } + return tokenInCoin, nil +} + +// ApplySwap. +func (p *Pool) applySwap(ctx sdk.Context, tokensIn sdk.Coins, tokensOut sdk.Coins) error { + // Also ensures that len(tokensIn) = 1 = len(tokensOut) + inPoolAsset, outPoolAsset, err := p.parsePoolAssetsCoins(tokensIn, tokensOut) + if err != nil { + return err + } + inPoolAsset.Token.Amount = inPoolAsset.Token.Amount.Add(tokensIn[0].Amount) + outPoolAsset.Token.Amount = outPoolAsset.Token.Amount.Sub(tokensOut[0].Amount) + + return p.UpdatePoolAssetBalances(sdk.NewCoins( + inPoolAsset.Token, + outPoolAsset.Token, + )) +} + +// SpotPrice returns the spot price of the pool +// This is the weight-adjusted balance of the tokens in the pool. +// In order reduce the propagated effect of incorrect trailing digits, +// we take the ratio of weights and divide this by ratio of supplies +// this is equivalent to spot_price = (Base_supply / Weight_base) / (Quote_supply / Weight_quote) +// but cancels out the common term in weight. +// +// panics if pool is misconfigured and has any weight as 0. +func (p Pool) SpotPrice(ctx sdk.Context, baseAsset, quoteAsset string) (sdk.Dec, error) { + quote, base, err := p.parsePoolAssetsByDenoms(quoteAsset, baseAsset) + if err != nil { + return sdk.Dec{}, err + } + if base.Weight.IsZero() || quote.Weight.IsZero() { + return sdk.Dec{}, errors.New("pool is misconfigured, got 0 weight") + } + + // spot_price = (Base_supply / Weight_base) / (Quote_supply / Weight_quote) + // spot_price = (weight_quote / weight_base) * (base_supply / quote_supply) + invWeightRatio := quote.Weight.ToDec().Quo(base.Weight.ToDec()) + supplyRatio := base.Token.Amount.ToDec().Quo(quote.Token.Amount.ToDec()) + fullRatio := supplyRatio.Mul(invWeightRatio) + // we want to round this to `SigFigs` of precision + ratio := osmomath.SigFigRound(fullRatio, types.SigFigs) + return ratio, nil +} + +// calcPoolOutGivenSingleIn - balance pAo. +func (p *Pool) calcSingleAssetJoin(tokenIn sdk.Coin, swapFee sdk.Dec, tokenInPoolAsset PoolAsset, totalShares sdk.Int) (numShares sdk.Int, err error) { + _, err = p.GetPoolAsset(tokenIn.Denom) + if err != nil { + return sdk.ZeroInt(), err + } + + totalWeight := p.GetTotalWeight() + if totalWeight.IsZero() { + return sdk.ZeroInt(), errors.New("pool misconfigured, total weight = 0") + } + normalizedWeight := tokenInPoolAsset.Weight.ToDec().Quo(totalWeight.ToDec()) + return calcPoolSharesOutGivenSingleAssetIn( + tokenInPoolAsset.Token.Amount.ToDec(), + normalizedWeight, + totalShares.ToDec(), + tokenIn.Amount.ToDec(), + swapFee, + ).TruncateInt(), nil +} + +// JoinPool calculates the number of shares needed given tokensIn with swapFee applied. +// It updates the liquidity if the pool is joined successfully. If not, returns error. +// and updates pool accordingly. +func (p *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) { + numShares, newLiquidity, err := p.CalcJoinPoolShares(ctx, tokensIn, swapFee) + if err != nil { + return sdk.Int{}, err + } + + // update pool with the calculated share and liquidity needed to join pool + p.IncreaseLiquidity(numShares, newLiquidity) + return numShares, nil +} + +func (p *Pool) calcJoinPoolSharesBroken(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) { + poolAssets := p.GetAllPoolAssets() + poolAssetsByDenom := make(map[string]PoolAsset) + for _, poolAsset := range poolAssets { + poolAssetsByDenom[poolAsset.Token.Denom] = poolAsset + } + + totalShares := p.GetTotalShares() + + if tokensIn.Len() == 1 { + numShares, err = p.calcSingleAssetJoin(tokensIn[0], swapFee, poolAssetsByDenom[tokensIn[0].Denom], totalShares) + if err != nil { + return sdk.ZeroInt(), sdk.NewCoins(), err + } + + newLiquidity = tokensIn + + return numShares, newLiquidity, nil + } else if tokensIn.Len() != p.NumAssets() { + return sdk.ZeroInt(), sdk.NewCoins(), errors.New("balancer pool only supports LP'ing with one asset or all assets in pool") + } + + // Add all exact coins we can (no swap). ctx arg doesn't matter for Balancer. + numShares, remCoins, err := cfmm_common.MaximalExactRatioJoinBroken(p, sdk.Context{}, tokensIn) + if err != nil { + return sdk.ZeroInt(), sdk.NewCoins(), err + } + + // update liquidity for accurate calcSingleAssetJoin calculation + newLiquidity = tokensIn.Sub(remCoins) + for _, coin := range newLiquidity { + poolAsset := poolAssetsByDenom[coin.Denom] + poolAsset.Token.Amount = poolAssetsByDenom[coin.Denom].Token.Amount.Add(coin.Amount) + poolAssetsByDenom[coin.Denom] = poolAsset + } + + totalShares = totalShares.Add(numShares) + + // If there are coins that couldn't be perfectly joined, do single asset joins + // for each of them. + if !remCoins.Empty() { + for _, coin := range remCoins { + newShares, err := p.calcSingleAssetJoin(coin, swapFee, poolAssetsByDenom[coin.Denom], totalShares) + if err != nil { + return sdk.ZeroInt(), sdk.NewCoins(), err + } + + newLiquidity = newLiquidity.Add(coin) + numShares = numShares.Add(newShares) + } + } + + return numShares, newLiquidity, nil +} + +// CalcJoinPoolShares calculates the number of shares created to join pool with the provided amount of `tokenIn`. +// The input tokens must either be: +// - a single token +// - contain exactly the same tokens as the pool contains +// +// It returns the number of shares created, the amount of coins actually joined into the pool +// (in case of not being able to fully join), or an error. +func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { + if ctx.BlockHeight() < v10Fork { + return p.calcJoinPoolSharesBroken(ctx, tokensIn, swapFee) + } + // 1) Get pool current liquidity + and token weights + // 2) If single token provided, do single asset join and exit. + // 3) If multi-asset join, first do as much of a join as we can with no swaps. + // 4) Update pool shares / liquidity / remaining tokens to join accordingly + // 5) For every remaining token to LP, do a single asset join, and update pool shares / liquidity. + // + // Note that all single asset joins do incur swap fee. + // + // Since CalcJoinPoolShares is non-mutative, the steps for updating pool shares / liquidity are + // more complex / don't just alter the state. + // We should simplify this logic further in the future, using balancer multi-join equations. + + // 1) get all 'pool assets' (aka current pool liquidity + balancer weight) + poolAssetsByDenom, err := getPoolAssetsByDenom(p.GetAllPoolAssets()) + if err != nil { + return sdk.ZeroInt(), sdk.NewCoins(), err + } + + totalShares := p.GetTotalShares() + if tokensIn.Len() == 1 { + // 2) Single token provided, so do single asset join and exit. + numShares, err = p.calcSingleAssetJoin(tokensIn[0], swapFee, poolAssetsByDenom[tokensIn[0].Denom], totalShares) + if err != nil { + return sdk.ZeroInt(), sdk.NewCoins(), err + } + // we join all the tokens. + tokensJoined = tokensIn + return numShares, tokensJoined, nil + } else if tokensIn.Len() != p.NumAssets() { + return sdk.ZeroInt(), sdk.NewCoins(), errors.New("balancer pool only supports LP'ing with one asset or all assets in pool") + } + + // 3) JoinPoolNoSwap with as many tokens as we can. (What is in perfect ratio) + // * numShares is how many shares are perfectly matched. + // * remainingTokensIn is how many coins we have left to join, that have not already been used. + // if remaining coins is empty, logic is done (we joined all tokensIn) + numShares, remainingTokensIn, err := cfmm_common.MaximalExactRatioJoin(p, sdk.Context{}, tokensIn) + if err != nil { + return sdk.ZeroInt(), sdk.NewCoins(), err + } + if remainingTokensIn.Empty() { + tokensJoined = tokensIn + return numShares, tokensJoined, nil + } + + // 4) Still more coins to join, so we update the effective pool state here to account for + // join that just happened. + // * We add the joined coins to our "current pool liquidity" object (poolAssetsByDenom) + // * We increment a variable for our "newTotalShares" to add in the shares that've been added. + tokensJoined = tokensIn.Sub(remainingTokensIn) + if err := updateIntermediaryPoolAssetsLiquidity(tokensJoined, poolAssetsByDenom); err != nil { + return sdk.ZeroInt(), sdk.NewCoins(), err + } + newTotalShares := totalShares.Add(numShares) + + // 5) Now single asset join each remaining coin. + newNumSharesFromRemaining, newLiquidityFromRemaining, err := p.calcJoinSingleAssetTokensIn(remainingTokensIn, newTotalShares, poolAssetsByDenom, swapFee) + if err != nil { + return sdk.ZeroInt(), sdk.NewCoins(), err + } + // update total amount LP'd variable, and total new LP shares variable, run safety check, and return + numShares = numShares.Add(newNumSharesFromRemaining) + tokensJoined = tokensJoined.Add(newLiquidityFromRemaining...) + + if tokensJoined.IsAnyGT(tokensIn) { + return sdk.ZeroInt(), sdk.NewCoins(), errors.New("An error has occurred, more coins joined than token In") + } + + return numShares, tokensJoined, nil +} + +// calcJoinSingleAssetTokensIn attempts to calculate single +// asset join for all tokensIn given totalShares in pool, +// poolAssetsByDenom and swapFee. totalShares is the number +// of shares in pool before beginnning to join any of the tokensIn. +// +// Returns totalNewShares and totalNewLiquidity from joining all tokensIn +// by mimicking individually single asset joining each. +// or error if fails to calculate join for any of the tokensIn. +func (p *Pool) calcJoinSingleAssetTokensIn(tokensIn sdk.Coins, totalShares sdk.Int, poolAssetsByDenom map[string]PoolAsset, swapFee sdk.Dec) (sdk.Int, sdk.Coins, error) { + totalNewShares := sdk.ZeroInt() + totalNewLiquidity := sdk.NewCoins() + for _, coin := range tokensIn { + newShares, err := p.calcSingleAssetJoin(coin, swapFee, poolAssetsByDenom[coin.Denom], totalShares.Add(totalNewShares)) + if err != nil { + return sdk.ZeroInt(), sdk.Coins{}, err + } + + totalNewLiquidity = totalNewLiquidity.Add(coin) + totalNewShares = totalNewShares.Add(newShares) + } + return totalNewShares, totalNewLiquidity, nil +} + +func (p *Pool) ExitPool(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { + exitingCoins, err = p.CalcExitPoolShares(ctx, exitingShares, exitFee) + if err != nil { + return sdk.Coins{}, err + } + + if err := p.exitPool(ctx, exitingCoins, exitingShares); err != nil { + return sdk.Coins{}, err + } + + return exitingCoins, nil +} + +// exitPool exits the pool given exitingCoins and exitingShares. +// updates the pool's liquidity and totalShares. +func (p *Pool) exitPool(ctx sdk.Context, exitingCoins sdk.Coins, exitingShares sdk.Int) error { + balances := p.GetTotalPoolLiquidity(ctx).Sub(exitingCoins) + if err := p.UpdatePoolAssetBalances(balances); err != nil { + return err + } + + totalShares := p.GetTotalShares() + p.TotalShares = sdk.NewCoin(p.TotalShares.Denom, totalShares.Sub(exitingShares)) + + return nil +} + +func (p *Pool) CalcExitPoolShares(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) { + return cfmm_common.CalcExitPool(ctx, p, exitingShares, exitFee) +} + +func (p *Pool) CalcTokenInShareAmountOut( + ctx sdk.Context, + tokenInDenom string, + shareOutAmount sdk.Int, + swapFee sdk.Dec, +) (tokenInAmount sdk.Int, err error) { + _, poolAssetIn, err := p.getPoolAssetAndIndex(tokenInDenom) + if err != nil { + return sdk.Int{}, err + } + + normalizedWeight := poolAssetIn.Weight.ToDec().Quo(p.GetTotalWeight().ToDec()) + + // We round up tokenInAmount, as this is whats charged for the swap, for the precise amount out. + // Otherwise, the pool would under-charge by this rounding error. + tokenInAmount = calcSingleAssetInGivenPoolSharesOut( + poolAssetIn.Token.Amount.ToDec(), + normalizedWeight, + p.GetTotalShares().ToDec(), + shareOutAmount.ToDec(), + swapFee, + ).Ceil().TruncateInt() + + if !tokenInAmount.IsPositive() { + return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatTokenAmountNotPositive, tokenInAmount.Int64()) + } + + return tokenInAmount, nil +} + +func (p *Pool) JoinPoolTokenInMaxShareAmountOut( + ctx sdk.Context, + tokenInDenom string, + shareOutAmount sdk.Int, +) (tokenInAmount sdk.Int, err error) { + _, poolAssetIn, err := p.getPoolAssetAndIndex(tokenInDenom) + if err != nil { + return sdk.Int{}, err + } + + normalizedWeight := poolAssetIn.Weight.ToDec().Quo(p.GetTotalWeight().ToDec()) + + tokenInAmount = calcSingleAssetInGivenPoolSharesOut( + poolAssetIn.Token.Amount.ToDec(), + normalizedWeight, + p.GetTotalShares().ToDec(), + shareOutAmount.ToDec(), + p.GetSwapFee(ctx), + ).TruncateInt() + + if !tokenInAmount.IsPositive() { + return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatTokenAmountNotPositive, tokenInAmount.Int64()) + } + + poolAssetIn.Token.Amount = poolAssetIn.Token.Amount.Add(tokenInAmount) + err = p.UpdatePoolAssetBalance(poolAssetIn.Token) + if err != nil { + return sdk.Int{}, err + } + + return tokenInAmount, nil +} + +func (p *Pool) ExitSwapExactAmountOut( + ctx sdk.Context, + tokenOut sdk.Coin, + shareInMaxAmount sdk.Int, +) (shareInAmount sdk.Int, err error) { + _, poolAssetOut, err := p.getPoolAssetAndIndex(tokenOut.Denom) + if err != nil { + return sdk.Int{}, err + } + + sharesIn := calcPoolSharesInGivenSingleAssetOut( + poolAssetOut.Token.Amount.ToDec(), + poolAssetOut.Weight.ToDec().Quo(p.TotalWeight.ToDec()), + p.GetTotalShares().ToDec(), + tokenOut.Amount.ToDec(), + p.GetSwapFee(ctx), + p.GetExitFee(ctx), + ).TruncateInt() + + if !sharesIn.IsPositive() { + return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatSharesAmountNotPositive, sharesIn.Int64()) + } + + if sharesIn.GT(shareInMaxAmount) { + return sdk.Int{}, sdkerrors.Wrapf(types.ErrLimitMaxAmount, errMsgFormatSharesLargerThanMax, sharesIn.Int64(), shareInMaxAmount.Uint64()) + } + + if err := p.exitPool(ctx, sdk.NewCoins(tokenOut), sharesIn); err != nil { + return sdk.Int{}, err + } + + return sharesIn, nil +} diff --git a/x/gamm/pool-models/balancer/pool_params.go b/x/gamm/pool-models/balancer/pool_params.go new file mode 100644 index 00000000000..58c5bd82336 --- /dev/null +++ b/x/gamm/pool-models/balancer/pool_params.go @@ -0,0 +1,78 @@ +package balancer + +import ( + "errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +func NewPoolParams(swapFee, exitFee sdk.Dec, params *SmoothWeightChangeParams) PoolParams { + return PoolParams{ + SwapFee: swapFee, + ExitFee: exitFee, + SmoothWeightChangeParams: params, + } +} + +func (params PoolParams) Validate(poolWeights []PoolAsset) error { + if params.ExitFee.IsNegative() { + return types.ErrNegativeExitFee + } + + if params.ExitFee.GTE(sdk.OneDec()) { + return types.ErrTooMuchExitFee + } + + if params.SwapFee.IsNegative() { + return types.ErrNegativeSwapFee + } + + if params.SwapFee.GTE(sdk.OneDec()) { + return types.ErrTooMuchSwapFee + } + + if params.SmoothWeightChangeParams != nil { + targetWeights := params.SmoothWeightChangeParams.TargetPoolWeights + // Ensure it has the right number of weights + if len(targetWeights) != len(poolWeights) { + return types.ErrPoolParamsInvalidNumDenoms + } + // Validate all user specified weights + for _, v := range targetWeights { + err := ValidateUserSpecifiedWeight(v.Weight) + if err != nil { + return err + } + } + // Ensure that all the target weight denoms are same as pool asset weights + sortedTargetPoolWeights := SortPoolAssetsOutOfPlaceByDenom(targetWeights) + sortedPoolWeights := SortPoolAssetsOutOfPlaceByDenom(poolWeights) + for i, v := range sortedPoolWeights { + if sortedTargetPoolWeights[i].Token.Denom != v.Token.Denom { + return types.ErrPoolParamsInvalidDenom + } + } + + // No start time validation needed + + // We do not need to validate InitialPoolWeights, as we set that ourselves + // in setInitialPoolParams + + // TODO: Is there anything else we can validate for duration? + if params.SmoothWeightChangeParams.Duration <= 0 { + return errors.New("params.SmoothWeightChangeParams must have a positive duration") + } + } + + return nil +} + +func (params PoolParams) GetPoolSwapFee() sdk.Dec { + return params.SwapFee +} + +func (params PoolParams) GetPoolExitFee() sdk.Dec { + return params.ExitFee +} diff --git a/x/gamm/pool-models/balancer/amm_joinpool_test.go b/x/gamm/pool-models/balancer/pool_suite_test.go similarity index 64% rename from x/gamm/pool-models/balancer/amm_joinpool_test.go rename to x/gamm/pool-models/balancer/pool_suite_test.go index 8419de7528d..afd071d0acb 100644 --- a/x/gamm/pool-models/balancer/amm_joinpool_test.go +++ b/x/gamm/pool-models/balancer/pool_suite_test.go @@ -1,8 +1,7 @@ package balancer_test import ( - "errors" - "fmt" + fmt "fmt" "math/rand" "testing" time "time" @@ -10,7 +9,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + "github.com/osmosis-labs/osmosis/v7/app/apptesting" + v10 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v10" "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) @@ -421,6 +423,112 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ }, } +type KeeperTestSuite struct { + apptesting.KeeperTestHelper + + queryClient types.QueryClient +} + +func TestKeeperTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} + +func (suite *KeeperTestSuite) SetupTest() { + suite.Setup() + suite.queryClient = types.NewQueryClient(suite.QueryHelper) + // be post-bug + suite.Ctx = suite.Ctx.WithBlockHeight(v10.ForkHeight) +} + +// This test sets up 2 asset pools, and then checks the spot price on them. +// It uses the pools spot price method, rather than the Gamm keepers spot price method. +func (suite *KeeperTestSuite) TestBalancerSpotPrice() { + baseDenom := "uosmo" + quoteDenom := "uion" + + tests := []struct { + name string + baseDenomPoolInput sdk.Coin + quoteDenomPoolInput sdk.Coin + expectError bool + expectedOutput sdk.Dec + }{ + { + name: "equal value", + baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 100), + quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 100), + expectError: false, + expectedOutput: sdk.MustNewDecFromStr("1"), + }, + { + name: "1:2 ratio", + baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 100), + quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 200), + expectError: false, + expectedOutput: sdk.MustNewDecFromStr("0.500000000000000000"), + }, + { + name: "2:1 ratio", + baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 200), + quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 100), + expectError: false, + expectedOutput: sdk.MustNewDecFromStr("2.000000000000000000"), + }, + { + name: "rounding after sigfig ratio", + baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 220), + quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 115), + expectError: false, + expectedOutput: sdk.MustNewDecFromStr("1.913043480000000000"), // ans is 1.913043478260869565, rounded is 1.91304348 + }, + { + name: "check number of sig figs", + baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 100), + quoteDenomPoolInput: sdk.NewInt64Coin(quoteDenom, 300), + expectError: false, + expectedOutput: sdk.MustNewDecFromStr("0.333333330000000000"), + }, + { + name: "check number of sig figs high sizes", + baseDenomPoolInput: sdk.NewInt64Coin(baseDenom, 343569192534), + quoteDenomPoolInput: sdk.NewCoin(quoteDenom, sdk.MustNewDecFromStr("186633424395479094888742").TruncateInt()), + expectError: false, + expectedOutput: sdk.MustNewDecFromStr("0.000000000001840877"), + }, + } + + for _, tc := range tests { + suite.SetupTest() + + poolId := suite.PrepareUni2PoolWithAssets( + tc.baseDenomPoolInput, + tc.quoteDenomPoolInput, + ) + + pool, err := suite.App.GAMMKeeper.GetPoolAndPoke(suite.Ctx, poolId) + suite.Require().NoError(err, "test: %s", tc.name) + balancerPool, isPool := pool.(*balancer.Pool) + suite.Require().True(isPool, "test: %s", tc.name) + + sut := func() { + spotPrice, err := balancerPool.SpotPrice( + suite.Ctx, + tc.baseDenomPoolInput.Denom, + tc.quoteDenomPoolInput.Denom) + + if tc.expectError { + suite.Require().Error(err, "test: %s", tc.name) + } else { + suite.Require().NoError(err, "test: %s", tc.name) + suite.Require().True(spotPrice.Equal(tc.expectedOutput), + "test: %s\nSpot price wrong, got %s, expected %s\n", tc.name, + spotPrice, tc.expectedOutput) + } + } + assertPoolStateNotModified(suite.T(), balancerPool, sut) + } +} + func (suite *KeeperTestSuite) TestCalcJoinPoolShares() { // We append shared calcSingleAssetJoinTestCases with multi-asset and edge // test cases. @@ -618,478 +726,6 @@ func (suite *KeeperTestSuite) TestCalcJoinPoolShares() { } } -// TestUpdateIntermediaryPoolAssetsLiquidity tests if `updateIntermediaryPoolAssetsLiquidity` returns poolAssetsByDenom map -// with the updated liquidity given by the parameter -func TestUpdateIntermediaryPoolAssetsLiquidity(t *testing.T) { - testCases := []struct { - name string - - // returns newLiquidity, originalPoolAssetsByDenom, expectedPoolAssetsByDenom - setup func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) - - err error - }{ - { - name: "regular case with multiple pool assets and a subset of newLiquidity to update", - - setup: func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) { - const ( - uosmoValueOriginal = 1_000_000_000_000 - atomValueOriginal = 123 - ionValueOriginal = 657 - - // Weight does not affect calculations so it is shared - weight = 100 - ) - - newLiquidity := sdk.NewCoins( - sdk.NewInt64Coin("uosmo", 1_000), - sdk.NewInt64Coin("atom", 2_000), - sdk.NewInt64Coin("ion", 3_000)) - - originalPoolAssetsByDenom := map[string]balancer.PoolAsset{ - "uosmo": { - Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), - Weight: sdk.NewInt(weight), - }, - "atom": { - Token: sdk.NewInt64Coin("atom", atomValueOriginal), - Weight: sdk.NewInt(weight), - }, - "ion": { - Token: sdk.NewInt64Coin("ion", ionValueOriginal), - Weight: sdk.NewInt(weight), - }, - } - - expectedPoolAssetsByDenom := map[string]balancer.PoolAsset{} - for k, v := range originalPoolAssetsByDenom { - expectedValue := balancer.PoolAsset{Token: v.Token, Weight: v.Weight} - expectedValue.Token.Amount = expectedValue.Token.Amount.Add(newLiquidity.AmountOf(k)) - expectedPoolAssetsByDenom[k] = expectedValue - } - - return newLiquidity, originalPoolAssetsByDenom, expectedPoolAssetsByDenom - }, - }, - { - name: "new liquidity has no coins", - - setup: func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) { - const ( - uosmoValueOriginal = 1_000_000_000_000 - atomValueOriginal = 123 - ionValueOriginal = 657 - - // Weight does not affect calculations so it is shared - weight = 100 - ) - - newLiquidity := sdk.NewCoins() - - originalPoolAssetsByDenom := map[string]balancer.PoolAsset{ - "uosmo": { - Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), - Weight: sdk.NewInt(weight), - }, - "atom": { - Token: sdk.NewInt64Coin("atom", atomValueOriginal), - Weight: sdk.NewInt(weight), - }, - "ion": { - Token: sdk.NewInt64Coin("ion", ionValueOriginal), - Weight: sdk.NewInt(weight), - }, - } - - return newLiquidity, originalPoolAssetsByDenom, originalPoolAssetsByDenom - }, - }, - { - name: "newLiquidity has a coin that poolAssets don't", - - setup: func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) { - const ( - uosmoValueOriginal = 1_000_000_000_000 - - // Weight does not affect calculations so it is shared - weight = 100 - ) - - newLiquidity := sdk.NewCoins( - sdk.NewInt64Coin("juno", 1_000)) - - originalPoolAssetsByDenom := map[string]balancer.PoolAsset{ - "uosmo": { - Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), - Weight: sdk.NewInt(weight), - }, - } - - return newLiquidity, originalPoolAssetsByDenom, originalPoolAssetsByDenom - }, - - err: fmt.Errorf(balancer.ErrMsgFormatFailedInterimLiquidityUpdate, "juno"), - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - newLiquidity, originalPoolAssetsByDenom, expectedPoolAssetsByDenom := tc.setup() - - err := balancer.UpdateIntermediaryPoolAssetsLiquidity(newLiquidity, originalPoolAssetsByDenom) - - require.Equal(t, tc.err, err) - - if tc.err != nil { - return - } - - require.Equal(t, expectedPoolAssetsByDenom, originalPoolAssetsByDenom) - }) - } -} - -func TestCalcSingleAssetJoin(t *testing.T) { - for _, tc := range calcSingleAssetJoinTestCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - pool := createTestPool(t, tc.swapFee, sdk.MustNewDecFromStr("0"), tc.poolAssets...) - - balancerPool, ok := pool.(*balancer.Pool) - require.True(t, ok) - - tokenIn := tc.tokensIn[0] - - poolAssetInDenom := tokenIn.Denom - // when testing a case with tokenIn that does not exist in pool, we just want - // to provide any pool asset. - if tc.expErr != nil && errors.Is(tc.expErr, types.ErrDenomNotFoundInPool) { - poolAssetInDenom = tc.poolAssets[0].Token.Denom - } - - // find pool asset in pool - // must be in pool since weights get scaled in Balancer pool - // constructor - poolAssetIn, err := balancerPool.GetPoolAsset(poolAssetInDenom) - require.NoError(t, err) - - // system under test - sut := func() { - shares, err := balancerPool.CalcSingleAssetJoin(tokenIn, tc.swapFee, poolAssetIn, pool.GetTotalShares()) - - if tc.expErr != nil { - require.Error(t, err) - require.ErrorAs(t, tc.expErr, &err) - require.Equal(t, sdk.ZeroInt(), shares) - return - } - - require.NoError(t, err) - assertExpectedSharesErrRatio(t, tc.expectShares, shares) - } - - assertPoolStateNotModified(t, balancerPool, func() { - assertPanic(t, tc.expectPanic, sut) - }) - }) - } -} - -func TestCalcJoinSingleAssetTokensIn(t *testing.T) { - testCases := []struct { - name string - swapFee sdk.Dec - poolAssets []balancer.PoolAsset - tokensIn sdk.Coins - expectShares sdk.Int - expectLiqudity sdk.Coins - expErr error - }{ - { - // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: - // P_issued = P_supply * ((1 + (A_t / B_t))^W_t - 1) - // - // 2_499_999_968_750 = 1e20 * (( 1 + (50,000 / 1e12))^0.5 - 1) - // - // where: - // P_supply = initial pool supply = 1e20 - // A_t = amount of deposited asset = 50,000 - // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 - // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // Plugging all of this in, we get: - // Full solution: https://www.wolframalpha.com/input?i=100000000000000000000*%28%281+%2B+%2850000%2F1000000000000%29%29%5E0.5+-+1%29 - // Simplified: P_issued = 2,499,999,968,750 - name: "one token in - equal weights with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), - poolAssets: oneTrillionEvenPoolAssets, - tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000)), - expectShares: sdk.NewInt(2_499_999_968_750), - }, - { - // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: - // P_issued = P_supply * ((1 + (A_t / B_t))^W_t - 1) - // - // 2_499_999_968_750 = 1e20 * (( 1 + (50,000 / 1e12))^0.5 - 1) - // - // where: - // P_supply = initial pool supply = 1e20 - // A_t = amount of deposited asset = 50,000 - // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 - // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // Plugging all of this in, we get: - // Full solution: https://www.wolframalpha.com/input?i=100000000000000000000*%28%281+%2B+%2850000%2F1000000000000%29%29%5E0.5+-+1%29 - // Simplified: P_issued = 2,499,999,968,750 - name: "two tokens in - equal weights with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), - poolAssets: oneTrillionEvenPoolAssets, - tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin("uatom", 50_000)), - expectShares: sdk.NewInt(2_499_999_968_750 * 2), - }, - { - // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 - // with swapFeeRatio added: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) - // - // 2_487_500_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.5) * 0.01) / 1e12))^0.5 - 1) - // - // where: - // P_supply = initial pool supply = 1e20 - // A_t = amount of deposited asset = 50,000 - // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 - // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) - // Plugging all of this in, we get: - // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-0.5%29+*+0.01%29%2F1000000000000%29%29%5E0.5+-+1%29 - // Simplified: P_issued = 2_487_500_000_000 - name: "one token in - equal weights with swap fee of 0.01", - swapFee: sdk.MustNewDecFromStr("0.01"), - poolAssets: oneTrillionEvenPoolAssets, - tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000)), - expectShares: sdk.NewInt(2_487_500_000_000), - }, - { - // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 - // with swapFeeRatio added: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) - // - // 2_487_500_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.5) * 0.01) / 1e12))^0.5 - 1) - // - // where: - // P_supply = initial pool supply = 1e20 - // A_t = amount of deposited asset = 50,000 - // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 - // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) - // Plugging all of this in, we get: - // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-0.5%29+*+0.01%29%2F1000000000000%29%29%5E0.5+-+1%29 - // Simplified: P_issued = 2_487_500_000_000 - name: "two tokens in - equal weights with swap fee of 0.01", - swapFee: sdk.MustNewDecFromStr("0.01"), - poolAssets: oneTrillionEvenPoolAssets, - tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin("uatom", 50_000)), - expectShares: sdk.NewInt(2_487_500_000_000 * 2), - }, - { - // For uosmo: - // - // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 - // with swapFeeRatio added: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) - // - // 2_072_912_400_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.83) * 0.03) / 2_000_000_000))^0.83 - 1) - // - // where: - // P_supply = initial pool supply = 1e20 - // A_t = amount of deposited asset = 50,000 - // B_t = existing balance of deposited asset in the pool prior to deposit = 2_000_000_000 - // W_t = normalized weight of deposited asset in pool = 500 / 500 + 100 = 0.83 - // swapFeeRatio = (1 - (1 - W_t) * swapFee) - // Plugging all of this in, we get: - // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-%28500+%2F+%28500+%2B+100%29%29%29+*+0.03%29%2F2000000000%29%29%5E%28500+%2F+%28500+%2B+100%29%29+-+1%29 - // Simplified: P_issued = 2_072_912_400_000_000 - // - // - // For uatom: - // - // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 - // with swapFeeRatio added: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) - // - // 1_624_999_900_000 = 1e20 * (( 1 + (100_000 * (1 - (1 - 0.167) * 0.03) / 1e12))^0.167 - 1) - // - // where: - // P_supply = initial pool supply = 1e20 - // A_t = amount of deposited asset = 50,000 - // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 - // W_t = normalized weight of deposited asset in pool = 100 / 500 + 100 = 0.167 - // swapFeeRatio = (1 - (1 - W_t) * swapFee) - // Plugging all of this in, we get: - // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%28100000*%281+-+%281-%28100+%2F+%28500+%2B+100%29%29%29+*+0.03%29%2F1000000000000%29%29%5E%28100+%2F+%28500+%2B+100%29%29+-+1%29 - // Simplified: P_issued = 1_624_999_900_000 - name: "two varying tokens in, varying weights, with swap fee of 0.03", - swapFee: sdk.MustNewDecFromStr("0.03"), - poolAssets: []balancer.PoolAsset{ - { - Token: sdk.NewInt64Coin("uosmo", 2_000_000_000), - Weight: sdk.NewInt(500), - }, - { - Token: sdk.NewInt64Coin("uatom", 1e12), - Weight: sdk.NewInt(100), - }, - }, - tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin("uatom", 100_000)), - expectShares: sdk.NewInt(2_072_912_400_000_000 + 1_624_999_900_000), - }, - { - name: "no tokens in", - swapFee: sdk.MustNewDecFromStr("0.03"), - poolAssets: oneTrillionEvenPoolAssets, - tokensIn: sdk.NewCoins(), - expectShares: sdk.NewInt(0), - }, - { - name: "one of the tokensIn asset does not exist in pool", - swapFee: sdk.ZeroDec(), - poolAssets: oneTrillionEvenPoolAssets, - // Second tokenIn does not exist. - tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin(doesNotExistDenom, 50_000)), - expectShares: sdk.ZeroInt(), - expErr: fmt.Errorf(balancer.ErrMsgFormatNoPoolAssetFound, doesNotExistDenom), - }, - } - - for _, tc := range testCases { - tc := tc - - t.Run(tc.name, func(t *testing.T) { - pool := createTestPool(t, tc.swapFee, sdk.ZeroDec(), tc.poolAssets...) - - balancerPool, ok := pool.(*balancer.Pool) - require.True(t, ok) - - poolAssetsByDenom, err := balancer.GetPoolAssetsByDenom(balancerPool.GetAllPoolAssets()) - require.NoError(t, err) - - // estimate expected liquidity - expectedNewLiquidity := sdk.NewCoins() - for _, tokenIn := range tc.tokensIn { - expectedNewLiquidity = expectedNewLiquidity.Add(tokenIn) - } - - sut := func() { - totalNumShares, totalNewLiquidity, err := balancerPool.CalcJoinSingleAssetTokensIn(tc.tokensIn, pool.GetTotalShares(), poolAssetsByDenom, tc.swapFee) - - if tc.expErr != nil { - require.Error(t, err) - require.ErrorAs(t, tc.expErr, &err) - require.Equal(t, sdk.ZeroInt(), totalNumShares) - require.Equal(t, sdk.Coins{}, totalNewLiquidity) - return - } - - require.NoError(t, err) - - require.Equal(t, expectedNewLiquidity, totalNewLiquidity) - - if tc.expectShares.Int64() == 0 { - require.Equal(t, tc.expectShares, totalNumShares) - return - } - - assertExpectedSharesErrRatio(t, tc.expectShares, totalNumShares) - } - - assertPoolStateNotModified(t, balancerPool, sut) - }) - } -} - -// TestGetPoolAssetsByDenom tests if `GetPoolAssetsByDenom` succesfully creates a map of denom to pool asset -// given pool asset as parameter -func TestGetPoolAssetsByDenom(t *testing.T) { - testCases := []struct { - name string - poolAssets []balancer.PoolAsset - expectedPoolAssetsByDenom map[string]balancer.PoolAsset - - err error - }{ - { - name: "zero pool assets", - poolAssets: []balancer.PoolAsset{}, - expectedPoolAssetsByDenom: make(map[string]balancer.PoolAsset), - }, - { - name: "one pool asset", - poolAssets: []balancer.PoolAsset{ - { - Token: sdk.NewInt64Coin("uosmo", 1e12), - Weight: sdk.NewInt(100), - }, - }, - expectedPoolAssetsByDenom: map[string]balancer.PoolAsset{ - "uosmo": { - Token: sdk.NewInt64Coin("uosmo", 1e12), - Weight: sdk.NewInt(100), - }, - }, - }, - { - name: "two pool assets", - poolAssets: []balancer.PoolAsset{ - { - Token: sdk.NewInt64Coin("uosmo", 1e12), - Weight: sdk.NewInt(100), - }, - { - Token: sdk.NewInt64Coin("atom", 123), - Weight: sdk.NewInt(400), - }, - }, - expectedPoolAssetsByDenom: map[string]balancer.PoolAsset{ - "uosmo": { - Token: sdk.NewInt64Coin("uosmo", 1e12), - Weight: sdk.NewInt(100), - }, - "atom": { - Token: sdk.NewInt64Coin("atom", 123), - Weight: sdk.NewInt(400), - }, - }, - }, - { - name: "duplicate pool assets", - poolAssets: []balancer.PoolAsset{ - { - Token: sdk.NewInt64Coin("uosmo", 1e12), - Weight: sdk.NewInt(100), - }, - { - Token: sdk.NewInt64Coin("uosmo", 123), - Weight: sdk.NewInt(400), - }, - }, - err: fmt.Errorf(balancer.ErrMsgFormatRepeatingPoolAssetsNotAllowed, "uosmo"), - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - actualPoolAssetsByDenom, err := balancer.GetPoolAssetsByDenom(tc.poolAssets) - - require.Equal(t, tc.err, err) - - if tc.err != nil { - return - } - - require.Equal(t, tc.expectedPoolAssetsByDenom, actualPoolAssetsByDenom) - }) - } -} - // Tests selecting a random amount of coins to LP, and then that ExitPool(JoinPool(tokens)) // preserves the pools number of LP shares, and returns fewer coins to the acter than they started with. func (suite *KeeperTestSuite) TestRandomizedJoinPoolExitPoolInvariants() { diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go new file mode 100644 index 00000000000..677c63dbe69 --- /dev/null +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -0,0 +1,1243 @@ +package balancer_test + +import ( + "errors" + "fmt" + "testing" + time "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + + "github.com/osmosis-labs/osmosis/v7/osmoutils" + "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +var ( + defaultSwapFee = sdk.MustNewDecFromStr("0.025") + defaultExitFee = sdk.MustNewDecFromStr("0.025") + defaultPoolId = uint64(10) + defaultBalancerPoolParams = balancer.PoolParams{ + SwapFee: defaultSwapFee, + ExitFee: defaultExitFee, + } + defaultFutureGovernor = "" + defaultCurBlockTime = time.Unix(1618700000, 0) + // + dummyPoolAssets = []balancer.PoolAsset{} + wantErr = true + noErr = false +) + +// TestUpdateIntermediaryPoolAssetsLiquidity tests if `updateIntermediaryPoolAssetsLiquidity` returns poolAssetsByDenom map +// with the updated liquidity given by the parameter +func TestUpdateIntermediaryPoolAssetsLiquidity(t *testing.T) { + testCases := []struct { + name string + + // returns newLiquidity, originalPoolAssetsByDenom, expectedPoolAssetsByDenom + setup func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) + + err error + }{ + { + name: "regular case with multiple pool assets and a subset of newLiquidity to update", + + setup: func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) { + const ( + uosmoValueOriginal = 1_000_000_000_000 + atomValueOriginal = 123 + ionValueOriginal = 657 + + // Weight does not affect calculations so it is shared + weight = 100 + ) + + newLiquidity := sdk.NewCoins( + sdk.NewInt64Coin("uosmo", 1_000), + sdk.NewInt64Coin("atom", 2_000), + sdk.NewInt64Coin("ion", 3_000)) + + originalPoolAssetsByDenom := map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), + Weight: sdk.NewInt(weight), + }, + "atom": { + Token: sdk.NewInt64Coin("atom", atomValueOriginal), + Weight: sdk.NewInt(weight), + }, + "ion": { + Token: sdk.NewInt64Coin("ion", ionValueOriginal), + Weight: sdk.NewInt(weight), + }, + } + + expectedPoolAssetsByDenom := map[string]balancer.PoolAsset{} + for k, v := range originalPoolAssetsByDenom { + expectedValue := balancer.PoolAsset{Token: v.Token, Weight: v.Weight} + expectedValue.Token.Amount = expectedValue.Token.Amount.Add(newLiquidity.AmountOf(k)) + expectedPoolAssetsByDenom[k] = expectedValue + } + + return newLiquidity, originalPoolAssetsByDenom, expectedPoolAssetsByDenom + }, + }, + { + name: "new liquidity has no coins", + + setup: func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) { + const ( + uosmoValueOriginal = 1_000_000_000_000 + atomValueOriginal = 123 + ionValueOriginal = 657 + + // Weight does not affect calculations so it is shared + weight = 100 + ) + + newLiquidity := sdk.NewCoins() + + originalPoolAssetsByDenom := map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), + Weight: sdk.NewInt(weight), + }, + "atom": { + Token: sdk.NewInt64Coin("atom", atomValueOriginal), + Weight: sdk.NewInt(weight), + }, + "ion": { + Token: sdk.NewInt64Coin("ion", ionValueOriginal), + Weight: sdk.NewInt(weight), + }, + } + + return newLiquidity, originalPoolAssetsByDenom, originalPoolAssetsByDenom + }, + }, + { + name: "newLiquidity has a coin that poolAssets don't", + + setup: func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) { + const ( + uosmoValueOriginal = 1_000_000_000_000 + + // Weight does not affect calculations so it is shared + weight = 100 + ) + + newLiquidity := sdk.NewCoins( + sdk.NewInt64Coin("juno", 1_000)) + + originalPoolAssetsByDenom := map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), + Weight: sdk.NewInt(weight), + }, + } + + return newLiquidity, originalPoolAssetsByDenom, originalPoolAssetsByDenom + }, + + err: fmt.Errorf(balancer.ErrMsgFormatFailedInterimLiquidityUpdate, "juno"), + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + newLiquidity, originalPoolAssetsByDenom, expectedPoolAssetsByDenom := tc.setup() + + err := balancer.UpdateIntermediaryPoolAssetsLiquidity(newLiquidity, originalPoolAssetsByDenom) + + require.Equal(t, tc.err, err) + + if tc.err != nil { + return + } + + require.Equal(t, expectedPoolAssetsByDenom, originalPoolAssetsByDenom) + }) + } +} + +func TestCalcSingleAssetJoin(t *testing.T) { + for _, tc := range calcSingleAssetJoinTestCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + pool := createTestPool(t, tc.swapFee, sdk.MustNewDecFromStr("0"), tc.poolAssets...) + + balancerPool, ok := pool.(*balancer.Pool) + require.True(t, ok) + + tokenIn := tc.tokensIn[0] + + poolAssetInDenom := tokenIn.Denom + // when testing a case with tokenIn that does not exist in pool, we just want + // to provide any pool asset. + if tc.expErr != nil && errors.Is(tc.expErr, types.ErrDenomNotFoundInPool) { + poolAssetInDenom = tc.poolAssets[0].Token.Denom + } + + // find pool asset in pool + // must be in pool since weights get scaled in Balancer pool + // constructor + poolAssetIn, err := balancerPool.GetPoolAsset(poolAssetInDenom) + require.NoError(t, err) + + // system under test + sut := func() { + shares, err := balancerPool.CalcSingleAssetJoin(tokenIn, tc.swapFee, poolAssetIn, pool.GetTotalShares()) + + if tc.expErr != nil { + require.Error(t, err) + require.ErrorAs(t, tc.expErr, &err) + require.Equal(t, sdk.ZeroInt(), shares) + return + } + + require.NoError(t, err) + assertExpectedSharesErrRatio(t, tc.expectShares, shares) + } + + assertPoolStateNotModified(t, balancerPool, func() { + assertPanic(t, tc.expectPanic, sut) + }) + }) + } +} + +func TestCalcJoinSingleAssetTokensIn(t *testing.T) { + testCases := []struct { + name string + swapFee sdk.Dec + poolAssets []balancer.PoolAsset + tokensIn sdk.Coins + expectShares sdk.Int + expectLiqudity sdk.Coins + expErr error + }{ + { + // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: + // P_issued = P_supply * ((1 + (A_t / B_t))^W_t - 1) + // + // 2_499_999_968_750 = 1e20 * (( 1 + (50,000 / 1e12))^0.5 - 1) + // + // where: + // P_supply = initial pool supply = 1e20 + // A_t = amount of deposited asset = 50,000 + // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 + // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) + // Plugging all of this in, we get: + // Full solution: https://www.wolframalpha.com/input?i=100000000000000000000*%28%281+%2B+%2850000%2F1000000000000%29%29%5E0.5+-+1%29 + // Simplified: P_issued = 2,499,999,968,750 + name: "one token in - equal weights with zero swap fee", + swapFee: sdk.MustNewDecFromStr("0"), + poolAssets: oneTrillionEvenPoolAssets, + tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000)), + expectShares: sdk.NewInt(2_499_999_968_750), + }, + { + // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: + // P_issued = P_supply * ((1 + (A_t / B_t))^W_t - 1) + // + // 2_499_999_968_750 = 1e20 * (( 1 + (50,000 / 1e12))^0.5 - 1) + // + // where: + // P_supply = initial pool supply = 1e20 + // A_t = amount of deposited asset = 50,000 + // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 + // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) + // Plugging all of this in, we get: + // Full solution: https://www.wolframalpha.com/input?i=100000000000000000000*%28%281+%2B+%2850000%2F1000000000000%29%29%5E0.5+-+1%29 + // Simplified: P_issued = 2,499,999,968,750 + name: "two tokens in - equal weights with zero swap fee", + swapFee: sdk.MustNewDecFromStr("0"), + poolAssets: oneTrillionEvenPoolAssets, + tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin("uatom", 50_000)), + expectShares: sdk.NewInt(2_499_999_968_750 * 2), + }, + { + // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 + // with swapFeeRatio added: + // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // + // 2_487_500_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.5) * 0.01) / 1e12))^0.5 - 1) + // + // where: + // P_supply = initial pool supply = 1e20 + // A_t = amount of deposited asset = 50,000 + // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 + // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) + // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // Plugging all of this in, we get: + // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-0.5%29+*+0.01%29%2F1000000000000%29%29%5E0.5+-+1%29 + // Simplified: P_issued = 2_487_500_000_000 + name: "one token in - equal weights with swap fee of 0.01", + swapFee: sdk.MustNewDecFromStr("0.01"), + poolAssets: oneTrillionEvenPoolAssets, + tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000)), + expectShares: sdk.NewInt(2_487_500_000_000), + }, + { + // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 + // with swapFeeRatio added: + // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // + // 2_487_500_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.5) * 0.01) / 1e12))^0.5 - 1) + // + // where: + // P_supply = initial pool supply = 1e20 + // A_t = amount of deposited asset = 50,000 + // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 + // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) + // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // Plugging all of this in, we get: + // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-0.5%29+*+0.01%29%2F1000000000000%29%29%5E0.5+-+1%29 + // Simplified: P_issued = 2_487_500_000_000 + name: "two tokens in - equal weights with swap fee of 0.01", + swapFee: sdk.MustNewDecFromStr("0.01"), + poolAssets: oneTrillionEvenPoolAssets, + tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin("uatom", 50_000)), + expectShares: sdk.NewInt(2_487_500_000_000 * 2), + }, + { + // For uosmo: + // + // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 + // with swapFeeRatio added: + // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // + // 2_072_912_400_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.83) * 0.03) / 2_000_000_000))^0.83 - 1) + // + // where: + // P_supply = initial pool supply = 1e20 + // A_t = amount of deposited asset = 50,000 + // B_t = existing balance of deposited asset in the pool prior to deposit = 2_000_000_000 + // W_t = normalized weight of deposited asset in pool = 500 / 500 + 100 = 0.83 + // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // Plugging all of this in, we get: + // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-%28500+%2F+%28500+%2B+100%29%29%29+*+0.03%29%2F2000000000%29%29%5E%28500+%2F+%28500+%2B+100%29%29+-+1%29 + // Simplified: P_issued = 2_072_912_400_000_000 + // + // + // For uatom: + // + // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 + // with swapFeeRatio added: + // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // + // 1_624_999_900_000 = 1e20 * (( 1 + (100_000 * (1 - (1 - 0.167) * 0.03) / 1e12))^0.167 - 1) + // + // where: + // P_supply = initial pool supply = 1e20 + // A_t = amount of deposited asset = 50,000 + // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 + // W_t = normalized weight of deposited asset in pool = 100 / 500 + 100 = 0.167 + // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // Plugging all of this in, we get: + // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%28100000*%281+-+%281-%28100+%2F+%28500+%2B+100%29%29%29+*+0.03%29%2F1000000000000%29%29%5E%28100+%2F+%28500+%2B+100%29%29+-+1%29 + // Simplified: P_issued = 1_624_999_900_000 + name: "two varying tokens in, varying weights, with swap fee of 0.03", + swapFee: sdk.MustNewDecFromStr("0.03"), + poolAssets: []balancer.PoolAsset{ + { + Token: sdk.NewInt64Coin("uosmo", 2_000_000_000), + Weight: sdk.NewInt(500), + }, + { + Token: sdk.NewInt64Coin("uatom", 1e12), + Weight: sdk.NewInt(100), + }, + }, + tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin("uatom", 100_000)), + expectShares: sdk.NewInt(2_072_912_400_000_000 + 1_624_999_900_000), + }, + { + name: "no tokens in", + swapFee: sdk.MustNewDecFromStr("0.03"), + poolAssets: oneTrillionEvenPoolAssets, + tokensIn: sdk.NewCoins(), + expectShares: sdk.NewInt(0), + }, + { + name: "one of the tokensIn asset does not exist in pool", + swapFee: sdk.ZeroDec(), + poolAssets: oneTrillionEvenPoolAssets, + // Second tokenIn does not exist. + tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin(doesNotExistDenom, 50_000)), + expectShares: sdk.ZeroInt(), + expErr: fmt.Errorf(balancer.ErrMsgFormatNoPoolAssetFound, doesNotExistDenom), + }, + } + + for _, tc := range testCases { + tc := tc + + t.Run(tc.name, func(t *testing.T) { + pool := createTestPool(t, tc.swapFee, sdk.ZeroDec(), tc.poolAssets...) + + balancerPool, ok := pool.(*balancer.Pool) + require.True(t, ok) + + poolAssetsByDenom, err := balancer.GetPoolAssetsByDenom(balancerPool.GetAllPoolAssets()) + require.NoError(t, err) + + // estimate expected liquidity + expectedNewLiquidity := sdk.NewCoins() + for _, tokenIn := range tc.tokensIn { + expectedNewLiquidity = expectedNewLiquidity.Add(tokenIn) + } + + sut := func() { + totalNumShares, totalNewLiquidity, err := balancerPool.CalcJoinSingleAssetTokensIn(tc.tokensIn, pool.GetTotalShares(), poolAssetsByDenom, tc.swapFee) + + if tc.expErr != nil { + require.Error(t, err) + require.ErrorAs(t, tc.expErr, &err) + require.Equal(t, sdk.ZeroInt(), totalNumShares) + require.Equal(t, sdk.Coins{}, totalNewLiquidity) + return + } + + require.NoError(t, err) + + require.Equal(t, expectedNewLiquidity, totalNewLiquidity) + + if tc.expectShares.Int64() == 0 { + require.Equal(t, tc.expectShares, totalNumShares) + return + } + + assertExpectedSharesErrRatio(t, tc.expectShares, totalNumShares) + } + + assertPoolStateNotModified(t, balancerPool, sut) + }) + } +} + +// TestGetPoolAssetsByDenom tests if `GetPoolAssetsByDenom` succesfully creates a map of denom to pool asset +// given pool asset as parameter +func TestGetPoolAssetsByDenom(t *testing.T) { + testCases := []struct { + name string + poolAssets []balancer.PoolAsset + expectedPoolAssetsByDenom map[string]balancer.PoolAsset + + err error + }{ + { + name: "zero pool assets", + poolAssets: []balancer.PoolAsset{}, + expectedPoolAssetsByDenom: make(map[string]balancer.PoolAsset), + }, + { + name: "one pool asset", + poolAssets: []balancer.PoolAsset{ + { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + }, + expectedPoolAssetsByDenom: map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + }, + }, + { + name: "two pool assets", + poolAssets: []balancer.PoolAsset{ + { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + { + Token: sdk.NewInt64Coin("atom", 123), + Weight: sdk.NewInt(400), + }, + }, + expectedPoolAssetsByDenom: map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + "atom": { + Token: sdk.NewInt64Coin("atom", 123), + Weight: sdk.NewInt(400), + }, + }, + }, + { + name: "duplicate pool assets", + poolAssets: []balancer.PoolAsset{ + { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + { + Token: sdk.NewInt64Coin("uosmo", 123), + Weight: sdk.NewInt(400), + }, + }, + err: fmt.Errorf(balancer.ErrMsgFormatRepeatingPoolAssetsNotAllowed, "uosmo"), + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + actualPoolAssetsByDenom, err := balancer.GetPoolAssetsByDenom(tc.poolAssets) + + require.Equal(t, tc.err, err) + + if tc.err != nil { + return + } + + require.Equal(t, tc.expectedPoolAssetsByDenom, actualPoolAssetsByDenom) + }) + } +} + +// TestCalculateAmountOutAndIn_InverseRelationship tests that the same amount of token is guaranteed upon +// sequential operation of CalcInAmtGivenOut and CalcOutAmtGivenIn. +func TestCalculateAmountOutAndIn_InverseRelationship(t *testing.T) { + type testcase struct { + denomOut string + initialPoolOut int64 + initialWeightOut int64 + initialCalcOut int64 + + denomIn string + initialPoolIn int64 + initialWeightIn int64 + } + + // For every test case in testcases, apply a swap fee in swapFeeCases. + testcases := []testcase{ + { + denomOut: "uosmo", + initialPoolOut: 1_000_000_000_000, + initialWeightOut: 100, + initialCalcOut: 100, + + denomIn: "ion", + initialPoolIn: 1_000_000_000_000, + initialWeightIn: 100, + }, + { + denomOut: "uosmo", + initialPoolOut: 1_000, + initialWeightOut: 100, + initialCalcOut: 100, + + denomIn: "ion", + initialPoolIn: 1_000_000, + initialWeightIn: 100, + }, + { + denomOut: "uosmo", + initialPoolOut: 1_000, + initialWeightOut: 100, + initialCalcOut: 100, + + denomIn: "ion", + initialPoolIn: 1_000_000, + initialWeightIn: 100, + }, + { + denomOut: "uosmo", + initialPoolOut: 1_000, + initialWeightOut: 200, + initialCalcOut: 100, + + denomIn: "ion", + initialPoolIn: 1_000_000, + initialWeightIn: 50, + }, + { + denomOut: "uosmo", + initialPoolOut: 1_000_000, + initialWeightOut: 200, + initialCalcOut: 100000, + + denomIn: "ion", + initialPoolIn: 1_000_000_000, + initialWeightIn: 50, + }, + } + + swapFeeCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} + + getTestCaseName := func(tc testcase, swapFeeCase string) string { + return fmt.Sprintf("tokenOutInitial: %d, tokenInInitial: %d, initialOut: %d, swapFee: %s", + tc.initialPoolOut, + tc.initialPoolIn, + tc.initialCalcOut, + swapFeeCase, + ) + } + + for _, tc := range testcases { + for _, swapFee := range swapFeeCases { + t.Run(getTestCaseName(tc, swapFee), func(t *testing.T) { + ctx := createTestContext(t) + + poolAssetOut := balancer.PoolAsset{ + Token: sdk.NewInt64Coin(tc.denomOut, tc.initialPoolOut), + Weight: sdk.NewInt(tc.initialWeightOut), + } + + poolAssetIn := balancer.PoolAsset{ + Token: sdk.NewInt64Coin(tc.denomIn, tc.initialPoolIn), + Weight: sdk.NewInt(tc.initialWeightIn), + } + + swapFeeDec, err := sdk.NewDecFromStr(swapFee) + require.NoError(t, err) + + exitFeeDec, err := sdk.NewDecFromStr("0") + require.NoError(t, err) + + pool := createTestPool(t, swapFeeDec, exitFeeDec, poolAssetOut, poolAssetIn) + require.NotNil(t, pool) + + initialOut := sdk.NewInt64Coin(poolAssetOut.Token.Denom, tc.initialCalcOut) + initialOutCoins := sdk.NewCoins(initialOut) + + sut := func() { + actualTokenIn, err := pool.CalcInAmtGivenOut(ctx, initialOutCoins, poolAssetIn.Token.Denom, swapFeeDec) + require.NoError(t, err) + + inverseTokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(actualTokenIn), poolAssetOut.Token.Denom, swapFeeDec) + require.NoError(t, err) + + require.Equal(t, initialOut.Denom, inverseTokenOut.Denom) + + expected := initialOut.Amount.ToDec() + actual := inverseTokenOut.Amount.ToDec() + + // allow a rounding error of up to 1 for this relation + tol := sdk.NewDec(1) + require.True(osmoutils.DecApproxEq(t, expected, actual, tol)) + } + + balancerPool, ok := pool.(*balancer.Pool) + require.True(t, ok) + + assertPoolStateNotModified(t, balancerPool, sut) + }) + } + } +} + +func TestCalcSingleAssetInAndOut_InverseRelationship(t *testing.T) { + type testcase struct { + initialPoolOut int64 + initialPoolIn int64 + initialWeightOut int64 + tokenOut int64 + initialWeightIn int64 + } + + // For every test case in testcases, apply a swap fee in swapFeeCases. + testcases := []testcase{ + { + initialPoolOut: 1_000_000_000_000, + tokenOut: 100, + initialWeightOut: 100, + initialWeightIn: 100, + }, + { + initialPoolOut: 1_000_000_000_000, + tokenOut: 100, + initialWeightOut: 50, + initialWeightIn: 100, + }, + { + initialPoolOut: 1_000_000_000_000, + tokenOut: 50, + initialWeightOut: 100, + initialWeightIn: 100, + }, + { + initialPoolOut: 1_000_000_000_000, + tokenOut: 100, + initialWeightOut: 100, + initialWeightIn: 50, + }, + { + initialPoolOut: 1_000_000, + tokenOut: 100, + initialWeightOut: 100, + initialWeightIn: 100, + }, + { + initialPoolOut: 2_351_333, + tokenOut: 7, + initialWeightOut: 148, + initialWeightIn: 57, + }, + { + initialPoolOut: 1_000, + tokenOut: 25, + initialWeightOut: 100, + initialWeightIn: 100, + }, + { + initialPoolOut: 1_000, + tokenOut: 26, + initialWeightOut: 100, + initialWeightIn: 100, + }, + } + + swapFeeCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} + + getTestCaseName := func(tc testcase, swapFeeCase string) string { + return fmt.Sprintf("initialPoolOut: %d, initialCalcOut: %d, initialWeightOut: %d, initialWeightIn: %d, swapFee: %s", + tc.initialPoolOut, + tc.tokenOut, + tc.initialWeightOut, + tc.initialWeightIn, + swapFeeCase, + ) + } + + for _, tc := range testcases { + for _, swapFee := range swapFeeCases { + t.Run(getTestCaseName(tc, swapFee), func(t *testing.T) { + swapFeeDec, err := sdk.NewDecFromStr(swapFee) + require.NoError(t, err) + + initialPoolBalanceOut := sdk.NewInt(tc.initialPoolOut) + + initialWeightOut := sdk.NewInt(tc.initialWeightOut) + initialWeightIn := sdk.NewInt(tc.initialWeightIn) + + initialTotalShares := types.InitPoolSharesSupply.ToDec() + initialCalcTokenOut := sdk.NewInt(tc.tokenOut) + + actualSharesOut := balancer.CalcPoolSharesOutGivenSingleAssetIn( + initialPoolBalanceOut.ToDec(), + initialWeightOut.ToDec().Quo(initialWeightOut.Add(initialWeightIn).ToDec()), + initialTotalShares, + initialCalcTokenOut.ToDec(), + swapFeeDec, + ) + + inverseCalcTokenOut := balancer.CalcSingleAssetInGivenPoolSharesOut( + initialPoolBalanceOut.Add(initialCalcTokenOut).ToDec(), + initialWeightOut.ToDec().Quo(initialWeightOut.Add(initialWeightIn).ToDec()), + initialTotalShares.Add(actualSharesOut), + actualSharesOut, + swapFeeDec, + ) + + tol := sdk.NewDec(1) + require.True(osmoutils.DecApproxEq(t, initialCalcTokenOut.ToDec(), inverseCalcTokenOut, tol)) + }) + } + } +} + +// Expected is un-scaled +func testTotalWeight(t *testing.T, expected sdk.Int, pool balancer.Pool) { + scaledExpected := expected.MulRaw(balancer.GuaranteedWeightPrecision) + require.Equal(t, + scaledExpected.String(), + pool.GetTotalWeight().String()) +} + +// TODO: Refactor this into multiple tests +func TestBalancerPoolUpdatePoolAssetBalance(t *testing.T) { + var poolId uint64 = 10 + + initialAssets := []balancer.PoolAsset{ + { + Weight: sdk.NewInt(100), + Token: sdk.NewCoin("test1", sdk.NewInt(50000)), + }, + { + Weight: sdk.NewInt(200), + Token: sdk.NewCoin("test2", sdk.NewInt(50000)), + }, + } + + pacc, err := balancer.NewBalancerPool(poolId, defaultBalancerPoolParams, initialAssets, defaultFutureGovernor, defaultCurBlockTime) + require.NoError(t, err) + + _, err = pacc.GetPoolAsset("unknown") + require.Error(t, err) + _, err = pacc.GetPoolAsset("") + require.Error(t, err) + + testTotalWeight(t, sdk.NewInt(300), pacc) + + // Break abstractions and start reasoning about the underlying internal representation's APIs. + // TODO: This test actually just needs to be refactored to not be doing this, and just + // create a different pool each time. + + err = pacc.SetInitialPoolAssets([]balancer.PoolAsset{{ + Weight: sdk.NewInt(-1), + Token: sdk.NewCoin("negativeWeight", sdk.NewInt(50000)), + }}) + + require.Error(t, err) + + err = pacc.SetInitialPoolAssets([]balancer.PoolAsset{{ + Weight: sdk.NewInt(0), + Token: sdk.NewCoin("zeroWeight", sdk.NewInt(50000)), + }}) + require.Error(t, err) + + err = pacc.UpdatePoolAssetBalance( + sdk.NewCoin("test1", sdk.NewInt(0))) + require.Error(t, err) + + err = pacc.UpdatePoolAssetBalance( + sdk.Coin{Denom: "test1", Amount: sdk.NewInt(-1)}, + ) + require.Error(t, err) + + err = pacc.UpdatePoolAssetBalance( + sdk.NewCoin("test1", sdk.NewInt(1))) + require.NoError(t, err) + + testTotalWeight(t, sdk.NewInt(300), pacc) + + PoolAsset, err := pacc.GetPoolAsset("test1") + require.NoError(t, err) + require.Equal(t, sdk.NewInt(1).String(), PoolAsset.Token.Amount.String()) +} + +func TestBalancerPoolAssetsWeightAndTokenBalance(t *testing.T) { + // TODO: Add more cases + // asset names should be i ascending order, starting from test1 + tests := []struct { + assets []balancer.PoolAsset + shouldErr bool + }{ + // weight 0 + { + []balancer.PoolAsset{ + { + Weight: sdk.NewInt(0), + Token: sdk.NewCoin("test1", sdk.NewInt(50000)), + }, + }, + wantErr, + }, + // negative weight + { + []balancer.PoolAsset{ + { + Weight: sdk.NewInt(-1), + Token: sdk.NewCoin("test1", sdk.NewInt(50000)), + }, + }, + wantErr, + }, + // 0 token amount + { + []balancer.PoolAsset{ + { + Weight: sdk.NewInt(100), + Token: sdk.NewCoin("test1", sdk.NewInt(0)), + }, + }, + wantErr, + }, + // negative token amount + { + []balancer.PoolAsset{ + { + Weight: sdk.NewInt(100), + Token: sdk.Coin{ + Denom: "test1", + Amount: sdk.NewInt(-1), + }, + }, + }, + wantErr, + }, + // total weight 300 + { + []balancer.PoolAsset{ + { + Weight: sdk.NewInt(200), + Token: sdk.NewCoin("test2", sdk.NewInt(50000)), + }, + { + Weight: sdk.NewInt(100), + Token: sdk.NewCoin("test1", sdk.NewInt(10000)), + }, + }, + noErr, + }, + // two of the same token + { + []balancer.PoolAsset{ + { + Weight: sdk.NewInt(200), + Token: sdk.NewCoin("test2", sdk.NewInt(50000)), + }, + { + Weight: sdk.NewInt(300), + Token: sdk.NewCoin("test1", sdk.NewInt(10000)), + }, + { + Weight: sdk.NewInt(100), + Token: sdk.NewCoin("test2", sdk.NewInt(10000)), + }, + }, + wantErr, + }, + // total weight 7300 + { + []balancer.PoolAsset{ + { + Weight: sdk.NewInt(200), + Token: sdk.NewCoin("test2", sdk.NewInt(50000)), + }, + { + Weight: sdk.NewInt(100), + Token: sdk.NewCoin("test1", sdk.NewInt(10000)), + }, + { + Weight: sdk.NewInt(7000), + Token: sdk.NewCoin("test3", sdk.NewInt(10000)), + }, + }, + noErr, + }, + } + + var poolId uint64 = 10 + + for i, tc := range tests { + pacc, err := balancer.NewBalancerPool(poolId, defaultBalancerPoolParams, tc.assets, defaultFutureGovernor, defaultCurBlockTime) + if tc.shouldErr { + require.Error(t, err, "unexpected lack of error, tc %v", i) + } else { + require.NoError(t, err, "unexpected error, tc %v", i) + expectedTotalWeight := sdk.ZeroInt() + for i, asset := range tc.assets { + expectedTotalWeight = expectedTotalWeight.Add(asset.Weight) + + // Ensure pool assets are sorted + require.Equal(t, "test"+fmt.Sprint(i+1), pacc.PoolAssets[i].Token.Denom) + } + testTotalWeight(t, expectedTotalWeight, pacc) + } + } +} + +// TODO: Figure out what parts of this test, if any, make sense. +func TestGetBalancerPoolAssets(t *testing.T) { + // Adds []PoolAssets, one after another + // if the addition doesn't error, adds the weight of the pool assets to a running total, + // and ensures the pool's total weight is equal to the expected. + // This also ensures that the pool assets remain sorted within the pool. + // Furthermore, it ensures that GetPoolAsset succeeds for everything in the pool, + // and fails for things not in it. + denomNotInPool := "xyzCoin" + + assets := []balancer.PoolAsset{ + { + Weight: sdk.NewInt(200), + Token: sdk.NewCoin("test2", sdk.NewInt(50000)), + }, + { + Weight: sdk.NewInt(100), + Token: sdk.NewCoin("test1", sdk.NewInt(10000)), + }, + { + Weight: sdk.NewInt(200), + Token: sdk.NewCoin("test3", sdk.NewInt(50000)), + }, + { + Weight: sdk.NewInt(100), + Token: sdk.NewCoin("test4", sdk.NewInt(10000)), + }, + } + + // TODO: We need way more robust test cases here, and should table drive these cases + pacc, err := balancer.NewBalancerPool(defaultPoolId, defaultBalancerPoolParams, assets, defaultFutureGovernor, defaultCurBlockTime) + require.NoError(t, err) + + // Hardcoded GetPoolAssets tests. + assets, err = pacc.GetPoolAssets("test1", "test2") + require.NoError(t, err) + require.Equal(t, 2, len(assets)) + + assets, err = pacc.GetPoolAssets("test1", "test2", "test3", "test4") + require.NoError(t, err) + require.Equal(t, 4, len(assets)) + + _, err = pacc.GetPoolAssets("test1", "test5") + require.Error(t, err) + _, err = pacc.GetPoolAssets(denomNotInPool) + require.Error(t, err) + + assets, err = pacc.GetPoolAssets() + require.NoError(t, err) + require.Equal(t, 0, len(assets)) +} + +func TestLBPParamsEmptyStartTime(t *testing.T) { + // Test that when the start time is empty, the pool + // sets its start time to be the first start time it is called on + defaultDuration := 100 * time.Second + + initialPoolAssets := []balancer.PoolAsset{ + { + Weight: sdk.NewInt(1), + Token: sdk.NewCoin("asset1", sdk.NewInt(1000)), + }, + { + Weight: sdk.NewInt(1), + Token: sdk.NewCoin("asset2", sdk.NewInt(1000)), + }, + } + + params := balancer.SmoothWeightChangeParams{ + Duration: defaultDuration, + TargetPoolWeights: []balancer.PoolAsset{ + { + Weight: sdk.NewInt(1), + Token: sdk.NewCoin("asset1", sdk.NewInt(0)), + }, + { + Weight: sdk.NewInt(2), + Token: sdk.NewCoin("asset2", sdk.NewInt(0)), + }, + }, + } + + pacc, err := balancer.NewBalancerPool(defaultPoolId, balancer.PoolParams{ + SmoothWeightChangeParams: ¶ms, + SwapFee: defaultSwapFee, + ExitFee: defaultExitFee, + }, initialPoolAssets, defaultFutureGovernor, defaultCurBlockTime) + require.NoError(t, err) + + // Consistency check that SmoothWeightChangeParams params are set + require.NotNil(t, pacc.PoolParams.SmoothWeightChangeParams) + // Ensure that the start time got set + require.Equal(t, pacc.PoolParams.SmoothWeightChangeParams.StartTime, defaultCurBlockTime) +} + +func TestBalancerPoolPokeTokenWeights(t *testing.T) { + // Set default date + defaultStartTime := time.Unix(1618703511, 0) + defaultStartTimeUnix := defaultStartTime.Unix() + defaultDuration := 100 * time.Second + floatGuaranteedPrecision := float64(balancer.GuaranteedWeightPrecision) + + // testCases don't need to be ordered by time. but the blockTime should be + // less than the end time of the SmoothWeightChange. Testing past the end time + // is already handled. + type testCase struct { + blockTime time.Time + expectedWeights []sdk.Int + } + + // Tests how the pool weights get updated via PokeTokenWeights at different block times. + // The framework underneath will automatically add tests for times before the start time, + // at the start time, at the end time, and after the end time. It is up to the test writer to + // test the behavior at times in-between. + tests := []struct { + // We take the initial weights from here + params balancer.SmoothWeightChangeParams + cases []testCase + }{ + { + // 1:1 pool, between asset1 and asset2 + // transitioning to a 1:2 pool + params: balancer.SmoothWeightChangeParams{ + StartTime: defaultStartTime, + Duration: defaultDuration, + InitialPoolWeights: []balancer.PoolAsset{ + { + Weight: sdk.NewInt(1), + Token: sdk.NewCoin("asset1", sdk.NewInt(0)), + }, + { + Weight: sdk.NewInt(1), + Token: sdk.NewCoin("asset2", sdk.NewInt(0)), + }, + }, + TargetPoolWeights: []balancer.PoolAsset{ + { + Weight: sdk.NewInt(1), + Token: sdk.NewCoin("asset1", sdk.NewInt(0)), + }, + { + Weight: sdk.NewInt(2), + Token: sdk.NewCoin("asset2", sdk.NewInt(0)), + }, + }, + }, + cases: []testCase{ + { + // Halfway through at 50 seconds elapsed + blockTime: time.Unix(defaultStartTimeUnix+50, 0), + expectedWeights: []sdk.Int{ + sdk.NewInt(1 * balancer.GuaranteedWeightPrecision), + // Halfway between 1 & 2 + sdk.NewInt(3 * balancer.GuaranteedWeightPrecision / 2), + }, + }, + { + // Quarter way through at 25 seconds elapsed + blockTime: time.Unix(defaultStartTimeUnix+25, 0), + expectedWeights: []sdk.Int{ + sdk.NewInt(1 * balancer.GuaranteedWeightPrecision), + // Quarter way between 1 & 2 = 1.25 + sdk.NewInt(int64(1.25 * floatGuaranteedPrecision)), + }, + }, + }, + }, + { + // 2:2 pool, between asset1 and asset2 + // transitioning to a 4:1 pool + params: balancer.SmoothWeightChangeParams{ + StartTime: defaultStartTime, + Duration: defaultDuration, + InitialPoolWeights: []balancer.PoolAsset{ + { + Weight: sdk.NewInt(2), + Token: sdk.NewCoin("asset1", sdk.NewInt(0)), + }, + { + Weight: sdk.NewInt(2), + Token: sdk.NewCoin("asset2", sdk.NewInt(0)), + }, + }, + TargetPoolWeights: []balancer.PoolAsset{ + { + Weight: sdk.NewInt(4), + Token: sdk.NewCoin("asset1", sdk.NewInt(0)), + }, + { + Weight: sdk.NewInt(1), + Token: sdk.NewCoin("asset2", sdk.NewInt(0)), + }, + }, + }, + cases: []testCase{ + { + // Halfway through at 50 seconds elapsed + blockTime: time.Unix(defaultStartTimeUnix+50, 0), + expectedWeights: []sdk.Int{ + // Halfway between 2 & 4 + sdk.NewInt(6 * balancer.GuaranteedWeightPrecision / 2), + // Halfway between 1 & 2 + sdk.NewInt(3 * balancer.GuaranteedWeightPrecision / 2), + }, + }, + { + // Quarter way through at 25 seconds elapsed + blockTime: time.Unix(defaultStartTimeUnix+25, 0), + expectedWeights: []sdk.Int{ + // Quarter way between 2 & 4 = 2.5 + sdk.NewInt(int64(2.5 * floatGuaranteedPrecision)), + // Quarter way between 2 & 1 = 1.75 + sdk.NewInt(int64(1.75 * floatGuaranteedPrecision)), + }, + }, + }, + }, + } + + // Add test cases at a time before the start, the start, the end, and a time after the end. + addDefaultCases := func(params balancer.SmoothWeightChangeParams, cases []testCase) []testCase { + // Set times one second before the start, and one second after the end + timeBeforeWeightChangeStart := time.Unix(params.StartTime.Unix()-1, 0) + timeAtWeightChangeEnd := params.StartTime.Add(params.Duration) + timeAfterWeightChangeEnd := time.Unix(timeAtWeightChangeEnd.Unix()+1, 0) + initialWeights := make([]sdk.Int, len(params.InitialPoolWeights)) + finalWeights := make([]sdk.Int, len(params.TargetPoolWeights)) + for i, v := range params.InitialPoolWeights { + initialWeights[i] = v.Weight.MulRaw(balancer.GuaranteedWeightPrecision) + } + for i, v := range params.TargetPoolWeights { + // Doesn't need to be scaled, due to this being done already in param initialization, + // and because params is only shallow copied + finalWeights[i] = v.Weight + } + // Set the test cases for times before the start, and the start + updatedCases := []testCase{ + { + blockTime: timeBeforeWeightChangeStart, + expectedWeights: initialWeights, + }, + { + blockTime: params.StartTime, + expectedWeights: initialWeights, + }, + } + // Append the provided cases + updatedCases = append(updatedCases, cases...) + finalCases := []testCase{ + { + blockTime: timeAtWeightChangeEnd, + expectedWeights: finalWeights, + }, + { + blockTime: timeAfterWeightChangeEnd, + expectedWeights: finalWeights, + }, + } + // Append the final cases + updatedCases = append(updatedCases, finalCases...) + return updatedCases + } + + for poolNum, tc := range tests { + paramsCopy := tc.params + // First we create the initial pool assets we will use + initialPoolAssets := make([]balancer.PoolAsset, len(paramsCopy.InitialPoolWeights)) + for i, asset := range paramsCopy.InitialPoolWeights { + assetCopy := balancer.PoolAsset{ + Weight: asset.Weight, + Token: sdk.NewInt64Coin(asset.Token.Denom, 10000), + } + initialPoolAssets[i] = assetCopy + } + // Initialize the pool + pacc, err := balancer.NewBalancerPool(uint64(poolNum), balancer.PoolParams{ + SwapFee: defaultSwapFee, + ExitFee: defaultExitFee, + SmoothWeightChangeParams: &tc.params, + }, initialPoolAssets, defaultFutureGovernor, defaultCurBlockTime) + require.NoError(t, err, "poolNumber %v", poolNum) + + // Consistency check that SmoothWeightChangeParams params are set + require.NotNil(t, pacc.PoolParams.SmoothWeightChangeParams) + + testCases := addDefaultCases(paramsCopy, tc.cases) + for caseNum, testCase := range testCases { + pacc.PokePool(testCase.blockTime) + + totalWeight := sdk.ZeroInt() + + for assetNum, asset := range pacc.GetAllPoolAssets() { + require.Equal(t, testCase.expectedWeights[assetNum], asset.Weight, + "Didn't get the expected weights, poolNumber %v, caseNumber %v, assetNumber %v", + poolNum, caseNum, assetNum) + + totalWeight = totalWeight.Add(asset.Weight) + } + + require.Equal(t, totalWeight, pacc.GetTotalWeight()) + } + // Should have been deleted by the last test case of after PokeTokenWeights pokes past end time. + require.Nil(t, pacc.PoolParams.SmoothWeightChangeParams) + } +} diff --git a/x/gamm/pool-models/balancer/suite_test.go b/x/gamm/pool-models/balancer/suite_test.go deleted file mode 100644 index 13bcbbaec47..00000000000 --- a/x/gamm/pool-models/balancer/suite_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package balancer_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - v10 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v10" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" -) - -type KeeperTestSuite struct { - apptesting.KeeperTestHelper - - queryClient types.QueryClient -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - -func (suite *KeeperTestSuite) SetupTest() { - suite.Setup() - suite.queryClient = types.NewQueryClient(suite.QueryHelper) - // be post-bug - suite.Ctx = suite.Ctx.WithBlockHeight(v10.ForkHeight) -} From 28fe6698a239b5dfd6e27cbe51cf64f6ed4b1a69 Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 30 Jun 2022 19:42:38 -0400 Subject: [PATCH 005/376] e2e: remove unused skipRunValidatorIndexes (#1923) * e2e: remove unused skipRunValidatorIndexes * remove error log --- tests/e2e/e2e_setup_test.go | 51 ++++++++----------------------------- tests/e2e/e2e_util_test.go | 7 ----- 2 files changed, 10 insertions(+), 48 deletions(-) diff --git a/tests/e2e/e2e_setup_test.go b/tests/e2e/e2e_setup_test.go index 167687e017e..0ce8235868c 100644 --- a/tests/e2e/e2e_setup_test.go +++ b/tests/e2e/e2e_setup_test.go @@ -41,16 +41,12 @@ type chainConfig struct { // voting period is number of blocks it takes to deposit, 1.2 seconds per validator to vote on the prop, and a buffer. votingPeriod float32 // upgrade proposal height for chain. - propHeight int - forkHeight int - // Indexes of the validators to skip from running during initialization. - // This is needed for testing functionality like state-sync where we would - // like to start a node during tests post-initialization. - skipRunValidatorIndexes map[int]struct{} - latestProposalNumber int - latestLockNumber int - meta initialization.ChainMeta - validators []*validatorConfig + propHeight int + forkHeight int + latestProposalNumber int + latestLockNumber int + meta initialization.ChainMeta + validators []*validatorConfig } const ( @@ -271,15 +267,7 @@ func (s *IntegrationTestSuite) TearDownSuite() { func (s *IntegrationTestSuite) runValidators(chainConfig *chainConfig, portOffset int) { s.T().Logf("starting %s validator containers...", chainConfig.meta.Id) - for i, val := range chainConfig.validators { - // Skip some validators from running during set up. - // This is needed for testing functionality like - // state-sync where we might want to start some validators during tests. - if _, ok := chainConfig.skipRunValidatorIndexes[i]; ok { - s.T().Logf("skipping %s validator with index %d from running...", val.validator.Name, i) - continue - } - + for _, val := range chainConfig.validators { validatorResource, err := s.containerManager.RunValidatorResource(chainConfig.meta.Id, val.validator.Name, val.validator.ConfigDir) require.NoError(s.T(), err) s.T().Logf("started %s validator container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) @@ -388,8 +376,7 @@ func (s *IntegrationTestSuite) configureChain(chainId string, validatorConfigs [ numVal := float32(len(validatorConfigs)) newChainConfig := chainConfig{ - votingPeriod: propDepositBlocks + numVal*propVoteBlocks + propBufferBlocks, - skipRunValidatorIndexes: skipValidatorIndexes, + votingPeriod: propDepositBlocks + numVal*propVoteBlocks + propBufferBlocks, } // If upgrade is skipped, we can use the chain initialization logic from @@ -470,10 +457,6 @@ func (s *IntegrationTestSuite) upgrade() { // wait till all chains halt at upgrade height for _, chainConfig := range s.chainConfigs { for i := range chainConfig.validators { - if _, ok := chainConfig.skipRunValidatorIndexes[i]; ok { - continue - } - validatorResource, exists := s.containerManager.GetValidatorResource(chainConfig.meta.Id, i) require.True(s.T(), exists) containerId := validatorResource.Container.ID @@ -505,10 +488,7 @@ func (s *IntegrationTestSuite) upgrade() { // remove all containers so we can upgrade them to the new version for _, chainConfig := range s.chainConfigs { - for valIdx, val := range chainConfig.validators { - if _, ok := chainConfig.skipRunValidatorIndexes[valIdx]; ok { - continue - } + for _, val := range chainConfig.validators { containerName := val.validator.Name err := s.containerManager.RemoveValidatorResource(chainConfig.meta.Id, containerName) s.Require().NoError(err) @@ -526,10 +506,6 @@ func (s *IntegrationTestSuite) upgradeFork() { for _, chainConfig := range s.chainConfigs { for i := range chainConfig.validators { - if _, ok := chainConfig.skipRunValidatorIndexes[i]; ok { - continue - } - validatorResource, exists := s.containerManager.GetValidatorResource(chainConfig.meta.Id, i) require.True(s.T(), exists) containerId := validatorResource.Container.ID @@ -561,10 +537,7 @@ func (s *IntegrationTestSuite) upgradeContainers(chainConfig *chainConfig, propH s.containerManager.OsmosisRepository = containers.CurrentBranchOsmoRepository s.containerManager.OsmosisTag = containers.CurrentBranchOsmoTag - for i, val := range chain.validators { - if _, ok := chainConfig.skipRunValidatorIndexes[i]; ok { - continue - } + for _, val := range chain.validators { validatorResource, err := s.containerManager.RunValidatorResource(chainConfig.meta.Id, val.validator.Name, val.validator.ConfigDir) require.NoError(s.T(), err) s.T().Logf("started %s validator container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) @@ -572,10 +545,6 @@ func (s *IntegrationTestSuite) upgradeContainers(chainConfig *chainConfig, propH // check that we are creating blocks again for i := range chain.validators { - if _, ok := chainConfig.skipRunValidatorIndexes[i]; ok { - continue - } - validatorResource, exists := s.containerManager.GetValidatorResource(chainConfig.meta.Id, i) require.True(s.T(), exists) diff --git a/tests/e2e/e2e_util_test.go b/tests/e2e/e2e_util_test.go index 0b0671de7f2..4ee3f927a23 100644 --- a/tests/e2e/e2e_util_test.go +++ b/tests/e2e/e2e_util_test.go @@ -142,9 +142,6 @@ func (s *IntegrationTestSuite) voteProposal(c *chainConfig) { s.T().Logf("voting yes on proposal for chain-id: %s", c.meta.Id) cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "yes", "--from=val", fmt.Sprintf("--chain-id=%s", c.meta.Id), "-b=block", "--yes", "--keyring-backend=test"} for i := range c.validators { - if _, ok := c.skipRunValidatorIndexes[i]; ok { - continue - } _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, i, cmd, "code: 0") s.Require().NoError(err) validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, i) @@ -267,10 +264,6 @@ func (s *IntegrationTestSuite) sendTx(c *chainConfig, validatorIndex int, amount func (s *IntegrationTestSuite) extractValidatorOperatorAddresses(config *chainConfig) { for i, val := range config.validators { - if _, ok := config.skipRunValidatorIndexes[i]; ok { - s.T().Logf("skipping %s validator with index %d from running...", val.validator.Name, i) - continue - } cmd := []string{"osmosisd", "debug", "addr", val.validator.PublicKey} s.T().Logf("extracting validator operator addresses for chain-id: %s", config.meta.Id) _, errBuf, err := s.containerManager.ExecCmd(s.T(), config.meta.Id, i, cmd, "") From add306ebc9f588648cfa8c626350c85ad28da6e4 Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 30 Jun 2022 19:42:49 -0400 Subject: [PATCH 006/376] e2e: fix image choice when upgrade logic is disabled (#1922) --- tests/e2e/containers/config.go | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/e2e/containers/config.go b/tests/e2e/containers/config.go index d7ed6659dde..e25d765cce5 100644 --- a/tests/e2e/containers/config.go +++ b/tests/e2e/containers/config.go @@ -52,6 +52,7 @@ func NewImageConfig(isUpgrade, isFork bool) ImageConfig { // the need for Docker. config.OsmosisRepository = CurrentBranchOsmoRepository config.OsmosisTag = CurrentBranchOsmoTag + return config } // If upgrade is tested, we need to utilize InitRepository and InitTag From 25bf1d8bf62acff9ab90a10025f6552fc2379e67 Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Fri, 1 Jul 2022 11:44:39 +0900 Subject: [PATCH 007/376] chore: x/lockup documentation, module cleanup (#1900) --- x/lockup/client/cli/query.go | 30 +- x/lockup/client/cli/tx.go | 6 +- x/lockup/keeper/grpc_query.go | 27 +- x/lockup/keeper/invariants.go | 1 + x/lockup/keeper/iterator.go | 2 +- x/lockup/keeper/lock.go | 765 +++++++++++++++--------------- x/lockup/keeper/lock_refs.go | 11 +- x/lockup/keeper/lock_test.go | 10 +- x/lockup/keeper/msg_server.go | 47 +- x/lockup/keeper/synthetic_lock.go | 103 ++-- 10 files changed, 534 insertions(+), 468 deletions(-) diff --git a/x/lockup/client/cli/query.go b/x/lockup/client/cli/query.go index faeb5494aaa..81fea436d16 100644 --- a/x/lockup/client/cli/query.go +++ b/x/lockup/client/cli/query.go @@ -53,7 +53,9 @@ func GetQueryCmd() *cobra.Command { return cmd } -// GetCmdModuleBalance returns full balance of the module. +// GetCmdModuleBalance returns full balance of the lockup module. +// Lockup module is where coins of locks are held. +// This includes locked balance and unlocked balance of the module. func GetCmdModuleBalance() *cobra.Command { cmd := &cobra.Command{ Use: "module-balance", @@ -89,7 +91,8 @@ $ %s query lockup module-balance return cmd } -// GetCmdModuleLockedAmount returns locked balance of the module. +// GetCmdModuleLockedAmount returns locked balance of the module, +// which are all the tokens not unlocking + tokens that are not finished unlocking. func GetCmdModuleLockedAmount() *cobra.Command { cmd := &cobra.Command{ Use: "module-locked-amount", @@ -125,7 +128,7 @@ $ %s query lockup module-locked-amount return cmd } -// GetCmdAccountUnlockableCoins returns unlockable coins which are not withdrawn yet. +// GetCmdAccountUnlockableCoins returns unlockable coins which has finsihed unlocking. func GetCmdAccountUnlockableCoins() *cobra.Command { cmd := &cobra.Command{ Use: "account-unlockable-coins
", @@ -162,7 +165,7 @@ $ %s query lockup account-unlockable-coins
return cmd } -// GetCmdAccountUnlockingCoins returns unlocking coins. +// GetCmdAccountUnlockingCoins returns unlocking coins of a specific account. func GetCmdAccountUnlockingCoins() *cobra.Command { cmd := &cobra.Command{ Use: "account-unlocking-coins
", @@ -199,7 +202,7 @@ $ %s query lockup account-unlocking-coins
return cmd } -// GetCmdAccountLockedCoins returns locked coins that can't be withdrawn. +// GetCmdAccountLockedCoins returns locked coins that can't be withdrawn of a specific account. func GetCmdAccountLockedCoins() *cobra.Command { cmd := &cobra.Command{ Use: "account-locked-coins
", @@ -236,7 +239,7 @@ $ %s query lockup account-locked-coins
return cmd } -// GetCmdAccountLockedPastTime returns locked records of an account with unlock time beyond timestamp. +// GetCmdAccountLockedPastTime returns locks of an account with unlock time beyond timestamp. func GetCmdAccountLockedPastTime() *cobra.Command { cmd := &cobra.Command{ Use: "account-locked-pastime
", @@ -279,7 +282,8 @@ $ %s query lockup account-locked-pastime
return cmd } -// GetCmdAccountLockedPastTimeNotUnlockingOnly returns locked records of an account with unlock time beyond timestamp within not unlocking queue. +// GetCmdAccountLockedPastTimeNotUnlockingOnly returns locks of an account with unlock time beyond provided timestamp +// amongst the locks that are in the unlocking queue. func GetCmdAccountLockedPastTimeNotUnlockingOnly() *cobra.Command { cmd := &cobra.Command{ Use: "account-locked-pastime-not-unlocking
", @@ -322,7 +326,7 @@ $ %s query lockup account-locked-pastime-not-unlocking
return cmd } -// GetCmdAccountUnlockedBeforeTime returns unlocked records with unlock time before timestamp. +// GetCmdAccountUnlockedBeforeTime returns locks with unlock time before the provided timestamp. func GetCmdAccountUnlockedBeforeTime() *cobra.Command { cmd := &cobra.Command{ Use: "account-locked-beforetime
", @@ -365,7 +369,8 @@ $ %s query lockup account-locked-pastime
return cmd } -// GetCmdAccountLockedPastTimeDenom returns lock records by address, timestamp, denom. +// GetCmdAccountLockedPastTimeDenom returns locks of an account whose unlock time is +// beyond given timestamp, and locks with the specified denom. func GetCmdAccountLockedPastTimeDenom() *cobra.Command { cmd := &cobra.Command{ Use: "account-locked-pastime-denom
", @@ -410,7 +415,7 @@ $ %s query lockup account-locked-pastime-denom
return cmd } -// GetCmdLockedByID returns lock record by id. +// GetCmdLockedByID returns lock by id. func GetCmdLockedByID() *cobra.Command { cmd := &cobra.Command{ Use: "lock-by-id ", @@ -619,7 +624,8 @@ $ %s query lockup account-locked-longer-duration-not-unlocking
", @@ -663,7 +669,7 @@ $ %s query lockup account-locked-pastime
return cmd } -// GetCmdTotalBondedByDenom returns total amount of locked asset. +// GetCmdTotalBondedByDenom returns total amount of locked asset of a specific denom. func GetCmdTotalLockedByDenom() *cobra.Command { cmd := &cobra.Command{ Use: "total-locked-of-denom ", diff --git a/x/lockup/client/cli/tx.go b/x/lockup/client/cli/tx.go index fc655af30fd..b6ff1ea510a 100644 --- a/x/lockup/client/cli/tx.go +++ b/x/lockup/client/cli/tx.go @@ -34,7 +34,7 @@ func GetTxCmd() *cobra.Command { return cmd } -// NewLockTokensCmd lock tokens into lockup pool from user's account. +// NewLockTokensCmd creates a new lock with the specified duration and tokens from the user's account. func NewLockTokensCmd() *cobra.Command { cmd := &cobra.Command{ Use: "lock-tokens [tokens]", @@ -81,7 +81,7 @@ func NewLockTokensCmd() *cobra.Command { return cmd } -// NewBeginUnlockingCmd unlock all unlockable tokens from user's account. +// NewBeginUnlockingCmd starts unlocking all unlockable locks from user's account. func NewBeginUnlockingCmd() *cobra.Command { cmd := &cobra.Command{ Use: "begin-unlock-tokens", @@ -107,7 +107,7 @@ func NewBeginUnlockingCmd() *cobra.Command { return cmd } -// NewBeginUnlockByIDCmd unlock individual period lock by ID. +// NewBeginUnlockByIDCmd unlocks individual period lock by ID. func NewBeginUnlockByIDCmd() *cobra.Command { cmd := &cobra.Command{ Use: "begin-unlock-by-id [id]", diff --git a/x/lockup/keeper/grpc_query.go b/x/lockup/keeper/grpc_query.go index 7fe5f76ef6c..607d9e325cd 100644 --- a/x/lockup/keeper/grpc_query.go +++ b/x/lockup/keeper/grpc_query.go @@ -29,7 +29,8 @@ func (q Querier) ModuleBalance(goCtx context.Context, _ *types.ModuleBalanceRequ return &types.ModuleBalanceResponse{Coins: q.Keeper.GetModuleBalance(ctx)}, nil } -// ModuleLockedAmount Returns locked balance of the module. +// ModuleLockedAmount returns locked balance of the module, +// which are all the tokens not unlocking + tokens that are not finished unlocking. func (q Querier) ModuleLockedAmount(goCtx context.Context, _ *types.ModuleLockedAmountRequest) (*types.ModuleLockedAmountResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) return &types.ModuleLockedAmountResponse{Coins: q.Keeper.GetModuleLockedCoins(ctx)}, nil @@ -54,7 +55,7 @@ func (q Querier) AccountUnlockableCoins(goCtx context.Context, req *types.Accoun return &types.AccountUnlockableCoinsResponse{Coins: q.Keeper.GetAccountUnlockableCoins(ctx, owner)}, nil } -// AccountUnlockingCoins returns whole unlocking coins. +// AccountUnlockingCoins returns the total amount of unlocking coins for a specific account. func (q Querier) AccountUnlockingCoins(goCtx context.Context, req *types.AccountUnlockingCoinsRequest) (*types.AccountUnlockingCoinsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -73,7 +74,7 @@ func (q Querier) AccountUnlockingCoins(goCtx context.Context, req *types.Account return &types.AccountUnlockingCoinsResponse{Coins: q.Keeper.GetAccountUnlockingCoins(ctx, owner)}, nil } -// AccountLockedCoins Returns a locked coins that can't be withdrawn. +// AccountLockedCoins returns the total amount of locked coins that can't be withdrawn for a specific account. func (q Querier) AccountLockedCoins(goCtx context.Context, req *types.AccountLockedCoinsRequest) (*types.AccountLockedCoinsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -92,7 +93,7 @@ func (q Querier) AccountLockedCoins(goCtx context.Context, req *types.AccountLoc return &types.AccountLockedCoinsResponse{Coins: q.Keeper.GetAccountLockedCoins(ctx, owner)}, nil } -// AccountLockedPastTime Returns the total locks of an account whose unlock time is beyond timestamp. +// AccountLockedPastTime returns the locks of an account whose unlock time is beyond provided timestamp. func (q Querier) AccountLockedPastTime(goCtx context.Context, req *types.AccountLockedPastTimeRequest) (*types.AccountLockedPastTimeResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -111,7 +112,7 @@ func (q Querier) AccountLockedPastTime(goCtx context.Context, req *types.Account return &types.AccountLockedPastTimeResponse{Locks: q.Keeper.GetAccountLockedPastTime(ctx, owner, req.Timestamp)}, nil } -// AccountUnlockedBeforeTime Returns the total unlocks of an account whose unlock time is before timestamp. +// AccountUnlockedBeforeTime returns locks of an account of which unlock time is before the provided timestamp. func (q Querier) AccountUnlockedBeforeTime(goCtx context.Context, req *types.AccountUnlockedBeforeTimeRequest) (*types.AccountUnlockedBeforeTimeResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -130,7 +131,8 @@ func (q Querier) AccountUnlockedBeforeTime(goCtx context.Context, req *types.Acc return &types.AccountUnlockedBeforeTimeResponse{Locks: q.Keeper.GetAccountUnlockedBeforeTime(ctx, owner, req.Timestamp)}, nil } -// AccountLockedPastTimeDenom is equal to GetAccountLockedPastTime but denom specific. +// AccountLockedPastTimeDenom returns the locks of an account whose unlock time is beyond provided timestamp, limited to locks with +// the specified denom. Equivalent to `AccountLockedPastTime` but denom specific. func (q Querier) AccountLockedPastTimeDenom(goCtx context.Context, req *types.AccountLockedPastTimeDenomRequest) (*types.AccountLockedPastTimeDenomResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -149,7 +151,7 @@ func (q Querier) AccountLockedPastTimeDenom(goCtx context.Context, req *types.Ac return &types.AccountLockedPastTimeDenomResponse{Locks: q.Keeper.GetAccountLockedPastTimeDenom(ctx, owner, req.Denom, req.Timestamp)}, nil } -// LockedByID Returns lock by lock ID. +// LockedByID returns lock by lock ID. func (q Querier) LockedByID(goCtx context.Context, req *types.LockedRequest) (*types.LockedResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -171,7 +173,7 @@ func (q Querier) SyntheticLockupsByLockupID(goCtx context.Context, req *types.Sy return &types.SyntheticLockupsByLockupIDResponse{SyntheticLocks: synthLocks}, nil } -// AccountLockedLongerDuration Returns account locked with duration longer than specified. +// AccountLockedLongerDuration returns locks of an account with duration longer than specified. func (q Querier) AccountLockedLongerDuration(goCtx context.Context, req *types.AccountLockedLongerDurationRequest) (*types.AccountLockedLongerDurationResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -191,7 +193,7 @@ func (q Querier) AccountLockedLongerDuration(goCtx context.Context, req *types.A return &types.AccountLockedLongerDurationResponse{Locks: locks}, nil } -// AccountLockedLongerDurationDenom Returns account locked with duration longer than specified with specific denom. +// AccountLockedLongerDurationDenom returns locks of an account with duration longer than specified with specific denom. func (q Querier) AccountLockedLongerDurationDenom(goCtx context.Context, req *types.AccountLockedLongerDurationDenomRequest) (*types.AccountLockedLongerDurationDenomResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -231,7 +233,8 @@ func (q Querier) AccountLockedDuration(goCtx context.Context, req *types.Account return &types.AccountLockedDurationResponse{Locks: locks}, nil } -// AccountLockedPastTimeNotUnlockingOnly Returns locked records of an account with unlock time beyond timestamp excluding tokens started unlocking. +// AccountLockedPastTimeNotUnlockingOnly returns locks of an account with unlock time beyond +// given timestamp excluding locks that has started unlocking. func (q Querier) AccountLockedPastTimeNotUnlockingOnly(goCtx context.Context, req *types.AccountLockedPastTimeNotUnlockingOnlyRequest) (*types.AccountLockedPastTimeNotUnlockingOnlyResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -250,7 +253,8 @@ func (q Querier) AccountLockedPastTimeNotUnlockingOnly(goCtx context.Context, re return &types.AccountLockedPastTimeNotUnlockingOnlyResponse{Locks: q.Keeper.GetAccountLockedPastTimeNotUnlockingOnly(ctx, owner, req.Timestamp)}, nil } -// AccountLockedLongerDurationNotUnlockingOnly Returns account locked records with longer duration excluding tokens started unlocking. +// AccountLockedLongerDurationNotUnlockingOnly returns locks of an account with longer duration +// than the specified duration, excluding tokens that has started unlocking. func (q Querier) AccountLockedLongerDurationNotUnlockingOnly(goCtx context.Context, req *types.AccountLockedLongerDurationNotUnlockingOnlyRequest) (*types.AccountLockedLongerDurationNotUnlockingOnlyResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -269,6 +273,7 @@ func (q Querier) AccountLockedLongerDurationNotUnlockingOnly(goCtx context.Conte return &types.AccountLockedLongerDurationNotUnlockingOnlyResponse{Locks: q.Keeper.GetAccountLockedLongerDurationNotUnlockingOnly(ctx, owner, req.Duration)}, nil } +// LockedDenom returns the total amount of denom locked throughout all locks. func (q Querier) LockedDenom(goCtx context.Context, req *types.LockedDenomRequest) (*types.LockedDenomResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") diff --git a/x/lockup/keeper/invariants.go b/x/lockup/keeper/invariants.go index 903b5678b08..e8d1a94f23f 100644 --- a/x/lockup/keeper/invariants.go +++ b/x/lockup/keeper/invariants.go @@ -18,6 +18,7 @@ func RegisterInvariants(ir sdk.InvariantRegistry, keeper Keeper) { ir.RegisterRoute(types.ModuleName, "locks-amount-invariant", LocksBalancesInvariant(keeper)) } +// SyntheticLockupInvariant ensures that synthetic lock's underlying lock id and the actual lock's id has the same id. func SyntheticLockupInvariant(keeper Keeper) sdk.Invariant { return func(ctx sdk.Context) (string, bool) { synthlocks := keeper.GetAllSyntheticLockups(ctx) diff --git a/x/lockup/keeper/iterator.go b/x/lockup/keeper/iterator.go index cf49e0616b7..e1196d71d81 100644 --- a/x/lockup/keeper/iterator.go +++ b/x/lockup/keeper/iterator.go @@ -194,7 +194,7 @@ func (k Keeper) unlockFromIterator(ctx sdk.Context, iterator db.Iterator) ([]typ coins := sdk.Coins{} locks := k.getLocksFromIterator(ctx, iterator) for _, lock := range locks { - err := k.Unlock(ctx, lock.ID) + err := k.UnlockMaturedLock(ctx, lock.ID) if err != nil { panic(err) } diff --git a/x/lockup/keeper/lock.go b/x/lockup/keeper/lock.go index 0ba7a8d2aa3..052a09e8905 100644 --- a/x/lockup/keeper/lock.go +++ b/x/lockup/keeper/lock.go @@ -14,29 +14,14 @@ import ( "github.com/osmosis-labs/osmosis/v7/x/lockup/types" ) -// TODO: Reorganize functions in this file - // WithdrawAllMaturedLocks withdraws every lock thats in the process of unlocking, and has finished unlocking by // the current block time. func (k Keeper) WithdrawAllMaturedLocks(ctx sdk.Context) { k.unlockFromIterator(ctx, k.LockIteratorBeforeTime(ctx, ctx.BlockTime())) } -func (k Keeper) getCoinsFromLocks(locks []types.PeriodLock) sdk.Coins { - coins := sdk.Coins{} - for _, lock := range locks { - coins = coins.Add(lock.Coins...) - } - return coins -} - -func (k Keeper) accumulationStore(ctx sdk.Context, denom string) store.Tree { - return store.NewTree(prefix.NewStore(ctx.KVStore(k.storeKey), accumulationStorePrefix(denom)), 10) -} - -// GetModuleBalance Returns full balance of the module. +// GetModuleBalance returns full balance of the module. func (k Keeper) GetModuleBalance(ctx sdk.Context) sdk.Coins { - // TODO: should add invariant test for module balance and lock items acc := k.ak.GetModuleAccount(ctx, types.ModuleName) return k.bk.GetAllBalances(ctx, acc.GetAddress()) } @@ -56,62 +41,14 @@ func (k Keeper) GetPeriodLocksAccumulation(ctx sdk.Context, query types.QueryCon return k.accumulationStore(ctx, query.Denom).SubsetAccumulation(beginKey, nil) } -// BeginUnlockAllNotUnlockings begins unlock for all not unlocking coins. +// BeginUnlockAllNotUnlockings begins unlock for all not unlocking locks of the given account. func (k Keeper) BeginUnlockAllNotUnlockings(ctx sdk.Context, account sdk.AccAddress) ([]types.PeriodLock, error) { locks, err := k.beginUnlockFromIterator(ctx, k.AccountLockIterator(ctx, false, account)) return locks, err } -func (k Keeper) addTokenToLock(ctx sdk.Context, lock *types.PeriodLock, coin sdk.Coin) error { - lock.Coins = lock.Coins.Add(coin) - - err := k.setLock(ctx, *lock) - if err != nil { - return err - } - - // modifications to accumulation store - k.accumulationStore(ctx, coin.Denom).Increase(accumulationKey(lock.Duration), coin.Amount) - // modifications to accumulation store by synthlocks - // CONTRACT: lock will have synthetic lock only if it has a single coin - lockedCoin, err := lock.SingleCoin() - if err == nil { - for _, synthlock := range k.GetAllSyntheticLockupsByLockup(ctx, lock.ID) { - k.accumulationStore(ctx, synthlock.SynthDenom).Increase(accumulationKey(synthlock.Duration), sdk.NewCoins(coin).AmountOf(lockedCoin.Denom)) - } - } - - k.hooks.AfterAddTokensToLock(ctx, lock.OwnerAddress(), lock.GetID(), sdk.NewCoins(coin)) - - return nil -} - -// removeTokensFromLock is called by lockup slash function - called by superfluid module only. -func (k Keeper) removeTokensFromLock(ctx sdk.Context, lock *types.PeriodLock, coins sdk.Coins) error { - // TODO: Handle 100% slash eventually, not needed for osmosis codebase atm. - lock.Coins = lock.Coins.Sub(coins) - - err := k.setLock(ctx, *lock) - if err != nil { - return err - } - - // modifications to accumulation store - for _, coin := range coins { - k.accumulationStore(ctx, coin.Denom).Decrease(accumulationKey(lock.Duration), coin.Amount) - } - - // increase synthetic lockup's accumulation store - synthLocks := k.GetAllSyntheticLockupsByLockup(ctx, lock.ID) - - // Note: since synthetic lockup deletion is using native lockup's coins to reduce accumulation store - // all the synthetic lockups' accumulation should be decreased - for _, synthlock := range synthLocks { - k.accumulationStore(ctx, synthlock.SynthDenom).Decrease(accumulationKey(synthlock.Duration), coins[0].Amount) - } - return nil -} - +// AddToExistingLock adds the given coin to the existing lock with the same owner and duration. +// Returns an empty array of period lock when a lock with the given condition does not exist. func (k Keeper) AddToExistingLock(ctx sdk.Context, owner sdk.AccAddress, coin sdk.Coin, duration time.Duration) ([]types.PeriodLock, error) { locks := k.GetAccountLockedDurationNotUnlockingOnly(ctx, owner, coin.Denom, duration) // if existing lock with same duration and denom exists, just add there @@ -125,8 +62,10 @@ func (k Keeper) AddToExistingLock(ctx sdk.Context, owner sdk.AccAddress, coin sd return locks, nil } -// AddTokensToLock locks more tokens into a lockup -// This also saves the lock to the store. +// AddTokensToLock locks additional tokens into an existing lock with the given ID. +// Tokens locked are sent and kept in the module account. +// This method alters the lock state in store, thus we do a sanity check to ensure +// lock owner matches the given owner. func (k Keeper) AddTokensToLockByID(ctx sdk.Context, lockID uint64, owner sdk.AccAddress, coin sdk.Coin) (*types.PeriodLock, error) { lock, err := k.GetLockByID(ctx, lockID) @@ -154,36 +93,37 @@ func (k Keeper) AddTokensToLockByID(ctx sdk.Context, lockID uint64, owner sdk.Ac return lock, nil } -// SlashTokensFromLockByID send slashed tokens to community pool - called by superfluid module only. -func (k Keeper) SlashTokensFromLockByID(ctx sdk.Context, lockID uint64, coins sdk.Coins) (*types.PeriodLock, error) { - lock, err := k.GetLockByID(ctx, lockID) - if err != nil { - return nil, err - } +// addTokenToLock adds token to lock and modifies the state of the lock and the accumulation store. +func (k Keeper) addTokenToLock(ctx sdk.Context, lock *types.PeriodLock, coin sdk.Coin) error { + lock.Coins = lock.Coins.Add(coin) - modAddr := k.ak.GetModuleAddress(types.ModuleName) - err = k.dk.FundCommunityPool(ctx, coins, modAddr) + err := k.setLock(ctx, *lock) if err != nil { - return nil, err + return err } - err = k.removeTokensFromLock(ctx, lock, coins) - if err != nil { - return nil, err - } + // modifications to accumulation store + k.accumulationStore(ctx, coin.Denom).Increase(accumulationKey(lock.Duration), coin.Amount) - if k.hooks == nil { - return lock, nil + // CONTRACT: lock will have synthetic lock only if it has a single coin + // accumulation store for its synthetic denom is increased if exists. + lockedCoin, err := lock.SingleCoin() + if err == nil { + for _, synthlock := range k.GetAllSyntheticLockupsByLockup(ctx, lock.ID) { + k.accumulationStore(ctx, synthlock.SynthDenom).Increase(accumulationKey(synthlock.Duration), sdk.NewCoins(coin).AmountOf(lockedCoin.Denom)) + } } - k.hooks.OnTokenSlashed(ctx, lock.ID, coins) - return lock, nil + k.hooks.AfterAddTokensToLock(ctx, lock.OwnerAddress(), lock.GetID(), sdk.NewCoins(coin)) + + return nil } -// LockTokens lock tokens from an account for specified duration. +// CreateLock creates a new lock with the specified duration for the owner. func (k Keeper) CreateLock(ctx sdk.Context, owner sdk.AccAddress, coins sdk.Coins, duration time.Duration) (types.PeriodLock, error) { ID := k.GetLastLockID(ctx) + 1 - // unlock time is set at the beginning of unlocking time + // unlock time is initially set without a value, gets set as unlock start time + duration + // when unlocking starts. lock := types.NewPeriodLock(ID, owner, duration, time.Time{}, coins) err := k.Lock(ctx, lock) if err != nil { @@ -193,304 +133,127 @@ func (k Keeper) CreateLock(ctx sdk.Context, owner sdk.AccAddress, coins sdk.Coin return lock, nil } -func (k Keeper) clearKeysByPrefix(ctx sdk.Context, prefix []byte) { +// Lock is a utility method to lock tokens into the module account. This method includes setting the +// lock within the state machine and increasing the value of accumulation store. +func (k Keeper) Lock(ctx sdk.Context, lock types.PeriodLock) error { + owner, err := sdk.AccAddressFromBech32(lock.Owner) + if err != nil { + return err + } + if err := k.bk.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, lock.Coins); err != nil { + return err + } + + // store lock object into the store store := ctx.KVStore(k.storeKey) - iterator := sdk.KVStorePrefixIterator(store, prefix) - defer iterator.Close() + bz, err := proto.Marshal(&lock) + if err != nil { + return err + } + store.Set(lockStoreKey(lock.ID), bz) - for ; iterator.Valid(); iterator.Next() { - store.Delete(iterator.Key()) + // add lock refs into not unlocking queue + err = k.addLockRefs(ctx, lock) + if err != nil { + return err } -} -func (k Keeper) ClearAccumulationStores(ctx sdk.Context) { - k.clearKeysByPrefix(ctx, types.KeyPrefixLockAccumulation) -} + // add to accumulation store + for _, coin := range lock.Coins { + k.accumulationStore(ctx, coin.Denom).Increase(accumulationKey(lock.Duration), coin.Amount) + } -// ResetAllLocks takes a set of locks, and initializes state to be storing -// them all correctly. This utilizes batch optimizations to improve efficiency, -// as this becomes a bottleneck at chain initialization & upgrades. -func (k Keeper) ResetAllLocks(ctx sdk.Context, locks []types.PeriodLock) error { - // index by coin.Denom, them duration -> amt - // We accumulate the accumulation store entries separately, - // to avoid hitting the myriad of slowdowns in the SDK iterator creation process. - // We then save these once to the accumulation store at the end. - accumulationStoreEntries := make(map[string]map[time.Duration]sdk.Int) - denoms := []string{} - for i, lock := range locks { - if i%25000 == 0 { - msg := fmt.Sprintf("Reset %d lock refs, cur lock ID %d", i, lock.ID) - ctx.Logger().Info(msg) - } - err := k.setLockAndResetLockRefs(ctx, lock) - if err != nil { - return err - } + k.hooks.OnTokenLocked(ctx, owner, lock.ID, lock.Coins, lock.Duration, lock.EndTime) + return nil +} - // Add to the accumlation store cache - for _, coin := range lock.Coins { - // update or create the new map from duration -> Int for this denom. - var curDurationMap map[time.Duration]sdk.Int - if durationMap, ok := accumulationStoreEntries[coin.Denom]; ok { - curDurationMap = durationMap - // update or create new amount in the duration map - newAmt := coin.Amount - if curAmt, ok := durationMap[lock.Duration]; ok { - newAmt = newAmt.Add(curAmt) - } - curDurationMap[lock.Duration] = newAmt - } else { - denoms = append(denoms, coin.Denom) - curDurationMap = map[time.Duration]sdk.Int{lock.Duration: coin.Amount} - } - accumulationStoreEntries[coin.Denom] = curDurationMap - } +// BeginUnlock is a utility to start unlocking coins from NotUnlocking queue. +// Returns an error if the lock has a synthetic lock. +func (k Keeper) BeginUnlock(ctx sdk.Context, lockID uint64, coins sdk.Coins) error { + // prohibit BeginUnlock if synthetic locks are referring to this + // TODO: In the future, make synthetic locks only get partial restrictions on the main lock. + lock, err := k.GetLockByID(ctx, lockID) + if err != nil { + return err } - - // deterministically iterate over durationMap cache. - sort.Strings(denoms) - for _, denom := range denoms { - curDurationMap := accumulationStoreEntries[denom] - durations := make([]time.Duration, 0, len(curDurationMap)) - for duration := range curDurationMap { - durations = append(durations, duration) - } - sort.Slice(durations, func(i, j int) bool { return durations[i] < durations[j] }) - // now that we have a sorted list of durations for this denom, - // add them all to accumulation store - msg := fmt.Sprintf("Setting accumulation entries for locks for %s, there are %d distinct durations", - denom, len(durations)) - ctx.Logger().Info(msg) - for _, d := range durations { - amt := curDurationMap[d] - k.accumulationStore(ctx, denom).Increase(accumulationKey(d), amt) - } + if k.HasAnySyntheticLockups(ctx, lock.ID) { + return fmt.Errorf("cannot BeginUnlocking a lock with synthetic lockup") } - return nil + return k.beginUnlock(ctx, *lock, coins) } -func (k Keeper) ResetAllSyntheticLocks(ctx sdk.Context, syntheticLocks []types.SyntheticLock) error { - // index by coin.Denom, them duration -> amt - // We accumulate the accumulation store entries separately, - // to avoid hitting the myriad of slowdowns in the SDK iterator creation process. - // We then save these once to the accumulation store at the end. - accumulationStoreEntries := make(map[string]map[time.Duration]sdk.Int) - denoms := []string{} - for i, synthLock := range syntheticLocks { - if i%25000 == 0 { - msg := fmt.Sprintf("Reset %d synthetic lock refs", i) - ctx.Logger().Info(msg) - } +// BeginForceUnlock begins force unlock of the given lock. +// This method should be called by the superfluid module ONLY, as it does not check whether +// the lock has a synthetic lock or not before unlocking. +func (k Keeper) BeginForceUnlock(ctx sdk.Context, lockID uint64, coins sdk.Coins) error { + lock, err := k.GetLockByID(ctx, lockID) + if err != nil { + return err + } + return k.beginUnlock(ctx, *lock, coins) +} - // Add to the accumlation store cache - lock, err := k.GetLockByID(ctx, synthLock.UnderlyingLockId) - if err != nil { - return err - } +// beginUnlock unlocks specified tokens from the given lock. Existing lock refs +// of not unlocking queue are deleted and new lock refs are then added. +// EndTime of the lock is set within this method. +// Coins provided as the parameter does not require to have all the tokens in the lock, +// as we allow partial unlockings of a lock. +func (k Keeper) beginUnlock(ctx sdk.Context, lock types.PeriodLock, coins sdk.Coins) error { + // sanity check + if !coins.IsAllLTE(lock.Coins) { + return fmt.Errorf("requested amount to unlock exceeds locked tokens") + } - err = k.setSyntheticLockAndResetRefs(ctx, *lock, synthLock) + // If the amount were unlocking is empty, or the entire coins amount, unlock the entire lock. + // Otherwise, split the lock into two locks, and fully unlock the newly created lock. + // (By virtue, the newly created lock we split into should have the unlock amount) + if len(coins) != 0 && !coins.IsEqual(lock.Coins) { + splitLock, err := k.splitLock(ctx, lock, coins) if err != nil { return err } + lock = splitLock + } - coin, err := lock.SingleCoin() - if err != nil { - return err - } + // remove existing lock refs from not unlocking queue + err := k.deleteLockRefs(ctx, types.KeyPrefixNotUnlocking, lock) + if err != nil { + return err + } - var curDurationMap map[time.Duration]sdk.Int - if durationMap, ok := accumulationStoreEntries[synthLock.SynthDenom]; ok { - curDurationMap = durationMap - newAmt := coin.Amount - if curAmt, ok := durationMap[synthLock.Duration]; ok { - newAmt = newAmt.Add(curAmt) - } - curDurationMap[synthLock.Duration] = newAmt - } else { - denoms = append(denoms, synthLock.SynthDenom) - curDurationMap = map[time.Duration]sdk.Int{synthLock.Duration: coin.Amount} - } - accumulationStoreEntries[synthLock.SynthDenom] = curDurationMap + // store lock with the end time set to current block time + duration + lock.EndTime = ctx.BlockTime().Add(lock.Duration) + err = k.setLock(ctx, lock) + if err != nil { + return err } - // deterministically iterate over durationMap cache. - sort.Strings(denoms) - for _, denom := range denoms { - curDurationMap := accumulationStoreEntries[denom] - durations := make([]time.Duration, 0, len(curDurationMap)) - for duration := range curDurationMap { - durations = append(durations, duration) - } - sort.Slice(durations, func(i, j int) bool { return durations[i] < durations[j] }) - // now that we have a sorted list of durations for this denom, - // add them all to accumulation store - msg := fmt.Sprintf("Setting accumulation entries for locks for %s, there are %d distinct durations", - denom, len(durations)) - ctx.Logger().Info(msg) - for _, d := range durations { - amt := curDurationMap[d] - k.accumulationStore(ctx, denom).Increase(accumulationKey(d), amt) - } - } - - return nil -} - -func (k Keeper) setSyntheticLockAndResetRefs(ctx sdk.Context, lock types.PeriodLock, synthLock types.SyntheticLock) error { - err := k.setSyntheticLockupObject(ctx, &synthLock) - if err != nil { - return err - } - - // store synth lock refs - return k.addSyntheticLockRefs(ctx, lock, synthLock) -} - -// setLockAndResetLockRefs sets the lock, and resets all of its lock references -// This puts the lock into a 'clean' state, aside from the AccumulationStore. -func (k Keeper) setLockAndResetLockRefs(ctx sdk.Context, lock types.PeriodLock) error { - err := k.setLock(ctx, lock) - if err != nil { - return err - } - - return k.addLockRefs(ctx, lock) -} - -// setLock is a utility to store lock object into the store. -func (k Keeper) setLock(ctx sdk.Context, lock types.PeriodLock) error { - store := ctx.KVStore(k.storeKey) - bz, err := proto.Marshal(&lock) - if err != nil { - return err - } - store.Set(lockStoreKey(lock.ID), bz) - return nil -} - -// deleteLock removes the lock object from the state. -func (k Keeper) deleteLock(ctx sdk.Context, id uint64) { - store := ctx.KVStore(k.storeKey) - store.Delete(lockStoreKey(id)) -} - -// Lock is a utility to lock coins into module account. -func (k Keeper) Lock(ctx sdk.Context, lock types.PeriodLock) error { - owner, err := sdk.AccAddressFromBech32(lock.Owner) - if err != nil { - return err - } - if err := k.bk.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, lock.Coins); err != nil { - return err - } - - // store lock object into the store - store := ctx.KVStore(k.storeKey) - bz, err := proto.Marshal(&lock) - if err != nil { - return err - } - store.Set(lockStoreKey(lock.ID), bz) - - // add lock refs into not unlocking queue + // add lock refs into unlocking queue err = k.addLockRefs(ctx, lock) if err != nil { return err } - // add to accumulation store - for _, coin := range lock.Coins { - k.accumulationStore(ctx, coin.Denom).Increase(accumulationKey(lock.Duration), coin.Amount) + if k.hooks != nil { + k.hooks.OnStartUnlock(ctx, lock.OwnerAddress(), lock.ID, lock.Coins, lock.Duration, lock.EndTime) } - k.hooks.OnTokenLocked(ctx, owner, lock.ID, lock.Coins, lock.Duration, lock.EndTime) return nil } -// splitLock splits a lock with the given amount, and stores split new lock to the state. -func (k Keeper) splitLock(ctx sdk.Context, lock types.PeriodLock, coins sdk.Coins) (types.PeriodLock, error) { - if lock.IsUnlocking() { - return types.PeriodLock{}, fmt.Errorf("cannot split unlocking lock") - } - lock.Coins = lock.Coins.Sub(coins) - err := k.setLock(ctx, lock) - if err != nil { - return types.PeriodLock{}, err - } - - splitLockID := k.GetLastLockID(ctx) + 1 - k.SetLastLockID(ctx, splitLockID) - - splitLock := types.NewPeriodLock(splitLockID, lock.OwnerAddress(), lock.Duration, lock.EndTime, coins) - err = k.setLock(ctx, splitLock) - return splitLock, err -} - -// BeginUnlock is a utility to start unlocking coins from NotUnlocking queue. -func (k Keeper) BeginUnlock(ctx sdk.Context, lockID uint64, coins sdk.Coins) error { - // prohibit BeginUnlock if synthetic locks are referring to this - // TODO: In the future, make synthetic locks only get partial restrictions on the main lock. - lock, err := k.GetLockByID(ctx, lockID) - if err != nil { - return err - } - if k.HasAnySyntheticLockups(ctx, lock.ID) { - return fmt.Errorf("cannot BeginUnlocking a lock with synthetic lockup") - } - - return k.beginForceUnlock(ctx, *lock, coins) -} +func (k Keeper) clearKeysByPrefix(ctx sdk.Context, prefix []byte) { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, prefix) + defer iterator.Close() -func (k Keeper) BeginForceUnlock(ctx sdk.Context, lockID uint64, coins sdk.Coins) error { - lock, err := k.GetLockByID(ctx, lockID) - if err != nil { - return err + for ; iterator.Valid(); iterator.Next() { + store.Delete(iterator.Key()) } - return k.beginForceUnlock(ctx, *lock, coins) } -func (k Keeper) beginForceUnlock(ctx sdk.Context, lock types.PeriodLock, coins sdk.Coins) error { - // sanity check - if !coins.IsAllLTE(lock.Coins) { - return fmt.Errorf("requested amount to unlock exceeds locked tokens") - } - - // If the amount were unlocking is empty, or the entire coins amount, unlock the entire lock. - // Otherwise, split the lock into two locks, and fully unlock the newly created lock. - // (By virtue, the newly created lock we split into should have the unlock amount) - if len(coins) != 0 && !coins.IsEqual(lock.Coins) { - splitLock, err := k.splitLock(ctx, lock, coins) - if err != nil { - return err - } - lock = splitLock - } - - // remove lock refs from not unlocking queue if exists - err := k.deleteLockRefs(ctx, types.KeyPrefixNotUnlocking, lock) - if err != nil { - return err - } - - // store lock with end time set - lock.EndTime = ctx.BlockTime().Add(lock.Duration) - err = k.setLock(ctx, lock) - if err != nil { - return err - } - - // add lock refs into unlocking queue - err = k.addLockRefs(ctx, lock) - if err != nil { - return err - } - - if k.hooks != nil { - k.hooks.OnStartUnlock(ctx, lock.OwnerAddress(), lock.ID, lock.Coins, lock.Duration, lock.EndTime) - } - - return nil +func (k Keeper) ClearAccumulationStores(ctx sdk.Context) { + k.clearKeysByPrefix(ctx, types.KeyPrefixLockAccumulation) } func (k Keeper) BeginForceUnlockWithEndTime(ctx sdk.Context, lockID uint64, endTime time.Time) error { @@ -528,8 +291,9 @@ func (k Keeper) beginForceUnlockWithEndTime(ctx sdk.Context, lock types.PeriodLo return nil } -// Unlock is a utility to unlock coins from module account. -func (k Keeper) Unlock(ctx sdk.Context, lockID uint64) error { +// UnlockMaturedLock finishes unlocking by sending back the locked tokens from the module accounts +// to the owner. This method requires lock to be matured, having passed the endtime of the lock. +func (k Keeper) UnlockMaturedLock(ctx sdk.Context, lockID uint64) error { lock, err := k.GetLockByID(ctx, lockID) if err != nil { return err @@ -544,10 +308,10 @@ func (k Keeper) Unlock(ctx sdk.Context, lockID uint64) error { return fmt.Errorf("lock is not unlockable yet: %s >= %s", curTime.String(), lock.EndTime.String()) } - return k.unlockInternalLogic(ctx, *lock) + return k.unlockMaturedLockInternalLogic(ctx, *lock) } -// ForceUnlock ignores unlock duration and immediately unlocks the lock and refunds tokens to lock owner.. +// ForceUnlock ignores unlock duration and immediately unlocks the lock and refunds tokens to lock owner. func (k Keeper) ForceUnlock(ctx sdk.Context, lock types.PeriodLock) error { // Steps: // 1) Break associated synthetic locks. (Superfluid data) @@ -555,7 +319,7 @@ func (k Keeper) ForceUnlock(ctx sdk.Context, lock types.PeriodLock) error { // 3) Run logic to delete unlocking metadata, and send tokens to owner. synthLocks := k.GetAllSyntheticLockupsByLockup(ctx, lock.ID) - err := k.BreakAllSyntheticLocks(ctx, lock, synthLocks) + err := k.DeleteAllSyntheticLocks(ctx, lock, synthLocks) if err != nil { return err } @@ -572,32 +336,11 @@ func (k Keeper) ForceUnlock(ctx sdk.Context, lock types.PeriodLock) error { if err != nil { return err } - return k.unlockInternalLogic(ctx, *lockPtr) + return k.unlockMaturedLockInternalLogic(ctx, *lockPtr) } -func (k Keeper) BreakAllSyntheticLocks(ctx sdk.Context, lock types.PeriodLock, synthLocks []types.SyntheticLock) error { - if len(synthLocks) == 0 { - return nil - } - - // Synth locks have data set in two places, accumulation store & setSyntheticLockAndResetRefs - // see that [CreateSyntheticLock](https://github.com/osmosis-labs/osmosis/blob/v7.3.0/x/lockup/keeper/synthetic_lock.go#L105) - // only has 3 set locations: - // - k.setSyntheticLockupObject(ctx, &synthLock) - // - k.addSyntheticLockRefs(ctx, *lock, synthLock) - // - k.accumulationStore(ctx, synthLock.SynthDenom).Increase(accumulationKey(unlockDuration), coin.Amount) - // ALL of which are reverted in the method DeleteSyntheticLock, here: - // https://github.com/osmosis-labs/osmosis/blob/v7.3.0/x/lockup/keeper/synthetic_lock.go#L156 - for _, synthLock := range synthLocks { - err := k.DeleteSyntheticLockup(ctx, lock.ID, synthLock.SynthDenom) - if err != nil { - return err - } - } - return nil -} - -func (k Keeper) unlockInternalLogic(ctx sdk.Context, lock types.PeriodLock) error { +// unlockMaturedLockInternalLogic handles internal logic for finishing unlocking matured locks. +func (k Keeper) unlockMaturedLockInternalLogic(ctx sdk.Context, lock types.PeriodLock) error { owner, err := sdk.AccAddressFromBech32(lock.Owner) if err != nil { return err @@ -625,6 +368,12 @@ func (k Keeper) unlockInternalLogic(ctx sdk.Context, lock types.PeriodLock) erro return nil } +// ExtendLockup changes the existing lock duration to the given lock duration. +// Updating lock duration would fail on either of the following conditions. +// 1. Only lock owner is able to change the duration of the lock. +// 2. Locks that are unlokcing are not allowed to change duration. +// 3. Locks that have synthetic lockup are not allowed to change. +// 4. Provided duration should be greater than the original duration. func (k Keeper) ExtendLockup(ctx sdk.Context, lock types.PeriodLock, newDuration time.Duration) error { if lock.IsUnlocking() { return fmt.Errorf("cannot edit unlocking lockup for lock %d", lock.ID) @@ -675,3 +424,257 @@ func (k Keeper) ExtendLockup(ctx sdk.Context, lock types.PeriodLock, newDuration return nil } + +// ResetAllLocks takes a set of locks, and initializes state to be storing +// them all correctly. This utilizes batch optimizations to improve efficiency, +// as this becomes a bottleneck at chain initialization & upgrades. +func (k Keeper) ResetAllLocks(ctx sdk.Context, locks []types.PeriodLock) error { + // index by coin.Denom, them duration -> amt + // We accumulate the accumulation store entries separately, + // to avoid hitting the myriad of slowdowns in the SDK iterator creation process. + // We then save these once to the accumulation store at the end. + accumulationStoreEntries := make(map[string]map[time.Duration]sdk.Int) + denoms := []string{} + for i, lock := range locks { + if i%25000 == 0 { + msg := fmt.Sprintf("Reset %d lock refs, cur lock ID %d", i, lock.ID) + ctx.Logger().Info(msg) + } + err := k.setLockAndResetLockRefs(ctx, lock) + if err != nil { + return err + } + + // Add to the accumlation store cache + for _, coin := range lock.Coins { + // update or create the new map from duration -> Int for this denom. + var curDurationMap map[time.Duration]sdk.Int + if durationMap, ok := accumulationStoreEntries[coin.Denom]; ok { + curDurationMap = durationMap + // update or create new amount in the duration map + newAmt := coin.Amount + if curAmt, ok := durationMap[lock.Duration]; ok { + newAmt = newAmt.Add(curAmt) + } + curDurationMap[lock.Duration] = newAmt + } else { + denoms = append(denoms, coin.Denom) + curDurationMap = map[time.Duration]sdk.Int{lock.Duration: coin.Amount} + } + accumulationStoreEntries[coin.Denom] = curDurationMap + } + } + + // deterministically iterate over durationMap cache. + sort.Strings(denoms) + for _, denom := range denoms { + curDurationMap := accumulationStoreEntries[denom] + durations := make([]time.Duration, 0, len(curDurationMap)) + for duration := range curDurationMap { + durations = append(durations, duration) + } + sort.Slice(durations, func(i, j int) bool { return durations[i] < durations[j] }) + // now that we have a sorted list of durations for this denom, + // add them all to accumulation store + msg := fmt.Sprintf("Setting accumulation entries for locks for %s, there are %d distinct durations", + denom, len(durations)) + ctx.Logger().Info(msg) + for _, d := range durations { + amt := curDurationMap[d] + k.accumulationStore(ctx, denom).Increase(accumulationKey(d), amt) + } + } + + return nil +} + +func (k Keeper) ResetAllSyntheticLocks(ctx sdk.Context, syntheticLocks []types.SyntheticLock) error { + // index by coin.Denom, them duration -> amt + // We accumulate the accumulation store entries separately, + // to avoid hitting the myriad of slowdowns in the SDK iterator creation process. + // We then save these once to the accumulation store at the end. + accumulationStoreEntries := make(map[string]map[time.Duration]sdk.Int) + denoms := []string{} + for i, synthLock := range syntheticLocks { + if i%25000 == 0 { + msg := fmt.Sprintf("Reset %d synthetic lock refs", i) + ctx.Logger().Info(msg) + } + + // Add to the accumlation store cache + lock, err := k.GetLockByID(ctx, synthLock.UnderlyingLockId) + if err != nil { + return err + } + + err = k.setSyntheticLockAndResetRefs(ctx, *lock, synthLock) + if err != nil { + return err + } + + coin, err := lock.SingleCoin() + if err != nil { + return err + } + + var curDurationMap map[time.Duration]sdk.Int + if durationMap, ok := accumulationStoreEntries[synthLock.SynthDenom]; ok { + curDurationMap = durationMap + newAmt := coin.Amount + if curAmt, ok := durationMap[synthLock.Duration]; ok { + newAmt = newAmt.Add(curAmt) + } + curDurationMap[synthLock.Duration] = newAmt + } else { + denoms = append(denoms, synthLock.SynthDenom) + curDurationMap = map[time.Duration]sdk.Int{synthLock.Duration: coin.Amount} + } + accumulationStoreEntries[synthLock.SynthDenom] = curDurationMap + } + + // deterministically iterate over durationMap cache. + sort.Strings(denoms) + for _, denom := range denoms { + curDurationMap := accumulationStoreEntries[denom] + durations := make([]time.Duration, 0, len(curDurationMap)) + for duration := range curDurationMap { + durations = append(durations, duration) + } + sort.Slice(durations, func(i, j int) bool { return durations[i] < durations[j] }) + // now that we have a sorted list of durations for this denom, + // add them all to accumulation store + msg := fmt.Sprintf("Setting accumulation entries for locks for %s, there are %d distinct durations", + denom, len(durations)) + ctx.Logger().Info(msg) + for _, d := range durations { + amt := curDurationMap[d] + k.accumulationStore(ctx, denom).Increase(accumulationKey(d), amt) + } + } + + return nil +} + +// SlashTokensFromLockByID sends slashed tokens directly from the lock to the community pool. +// Called by the superfluid module ONLY. +func (k Keeper) SlashTokensFromLockByID(ctx sdk.Context, lockID uint64, coins sdk.Coins) (*types.PeriodLock, error) { + lock, err := k.GetLockByID(ctx, lockID) + if err != nil { + return nil, err + } + + modAddr := k.ak.GetModuleAddress(types.ModuleName) + err = k.dk.FundCommunityPool(ctx, coins, modAddr) + if err != nil { + return nil, err + } + + err = k.removeTokensFromLock(ctx, lock, coins) + if err != nil { + return nil, err + } + + if k.hooks == nil { + return lock, nil + } + + k.hooks.OnTokenSlashed(ctx, lock.ID, coins) + return lock, nil +} + +func (k Keeper) accumulationStore(ctx sdk.Context, denom string) store.Tree { + return store.NewTree(prefix.NewStore(ctx.KVStore(k.storeKey), accumulationStorePrefix(denom)), 10) +} + +// removeTokensFromLock is called by lockup slash function. +// Called by the superfluid module ONLY. +func (k Keeper) removeTokensFromLock(ctx sdk.Context, lock *types.PeriodLock, coins sdk.Coins) error { + // TODO: Handle 100% slash eventually, not needed for osmosis codebase atm. + lock.Coins = lock.Coins.Sub(coins) + + err := k.setLock(ctx, *lock) + if err != nil { + return err + } + + // modifications to accumulation store + for _, coin := range coins { + k.accumulationStore(ctx, coin.Denom).Decrease(accumulationKey(lock.Duration), coin.Amount) + } + + // increase synthetic lockup's accumulation store + synthLocks := k.GetAllSyntheticLockupsByLockup(ctx, lock.ID) + + // Note: since synthetic lockup deletion is using native lockup's coins to reduce accumulation store + // all the synthetic lockups' accumulation should be decreased + for _, synthlock := range synthLocks { + k.accumulationStore(ctx, synthlock.SynthDenom).Decrease(accumulationKey(synthlock.Duration), coins[0].Amount) + } + return nil +} + +// setLock is a utility to store lock object into the store. +func (k Keeper) setLock(ctx sdk.Context, lock types.PeriodLock) error { + store := ctx.KVStore(k.storeKey) + bz, err := proto.Marshal(&lock) + if err != nil { + return err + } + store.Set(lockStoreKey(lock.ID), bz) + return nil +} + +// setLockAndResetLockRefs sets the lock, and resets all of its lock references +// This puts the lock into a 'clean' state, aside from the AccumulationStore. +func (k Keeper) setLockAndResetLockRefs(ctx sdk.Context, lock types.PeriodLock) error { + err := k.setLock(ctx, lock) + if err != nil { + return err + } + + return k.addLockRefs(ctx, lock) +} + +// setSyntheticLockAndResetRefs sets the synthetic lock object, and resets all of its lock references +func (k Keeper) setSyntheticLockAndResetRefs(ctx sdk.Context, lock types.PeriodLock, synthLock types.SyntheticLock) error { + err := k.setSyntheticLockupObject(ctx, &synthLock) + if err != nil { + return err + } + + // store synth lock refs + return k.addSyntheticLockRefs(ctx, lock, synthLock) +} + +// deleteLock removes the lock object from the state. +func (k Keeper) deleteLock(ctx sdk.Context, id uint64) { + store := ctx.KVStore(k.storeKey) + store.Delete(lockStoreKey(id)) +} + +// splitLock splits a lock with the given amount, and stores split new lock to the state. +func (k Keeper) splitLock(ctx sdk.Context, lock types.PeriodLock, coins sdk.Coins) (types.PeriodLock, error) { + if lock.IsUnlocking() { + return types.PeriodLock{}, fmt.Errorf("cannot split unlocking lock") + } + lock.Coins = lock.Coins.Sub(coins) + err := k.setLock(ctx, lock) + if err != nil { + return types.PeriodLock{}, err + } + + splitLockID := k.GetLastLockID(ctx) + 1 + k.SetLastLockID(ctx, splitLockID) + + splitLock := types.NewPeriodLock(splitLockID, lock.OwnerAddress(), lock.Duration, lock.EndTime, coins) + err = k.setLock(ctx, splitLock) + return splitLock, err +} + +func (k Keeper) getCoinsFromLocks(locks []types.PeriodLock) sdk.Coins { + coins := sdk.Coins{} + for _, lock := range locks { + coins = coins.Add(lock.Coins...) + } + return coins +} diff --git a/x/lockup/keeper/lock_refs.go b/x/lockup/keeper/lock_refs.go index 2dee37ca0da..68af9947b66 100644 --- a/x/lockup/keeper/lock_refs.go +++ b/x/lockup/keeper/lock_refs.go @@ -6,6 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// addLockRefs adds appropriate reference keys preceded by a prefix. +// A prefix indicates whether the lock is unlocking or not. func (k Keeper) addLockRefs(ctx sdk.Context, lock types.PeriodLock) error { refKeys, err := durationLockRefKeys(lock) if lock.IsUnlocking() { @@ -23,6 +25,7 @@ func (k Keeper) addLockRefs(ctx sdk.Context, lock types.PeriodLock) error { return nil } +// deleteLockRefs deletes all the lock references of the lock with the given lock prefix. func (k Keeper) deleteLockRefs(ctx sdk.Context, lockRefPrefix []byte, lock types.PeriodLock) error { refKeys, err := lockRefKeys(lock) if err != nil { @@ -34,7 +37,7 @@ func (k Keeper) deleteLockRefs(ctx sdk.Context, lockRefPrefix []byte, lock types return nil } -// make references for. +// addSyntheticLockRefs adds lock refs for the synthetic lock object. func (k Keeper) addSyntheticLockRefs(ctx sdk.Context, lock types.PeriodLock, synthLock types.SyntheticLock) error { refKeys, err := syntheticLockRefKeys(lock, synthLock) if err != nil { @@ -49,6 +52,7 @@ func (k Keeper) addSyntheticLockRefs(ctx sdk.Context, lock types.PeriodLock, syn return nil } +// deleteSyntheticLockRefs deletes all lock refs for the synthetic lock object. func (k Keeper) deleteSyntheticLockRefs(ctx sdk.Context, lock types.PeriodLock, synthLock types.SyntheticLock) error { refKeys, err := syntheticLockRefKeys(lock, synthLock) if err != nil { @@ -60,8 +64,3 @@ func (k Keeper) deleteSyntheticLockRefs(ctx sdk.Context, lock types.PeriodLock, } return nil } - -func (k Keeper) ClearAllLockRefKeys(ctx sdk.Context) { - k.clearKeysByPrefix(ctx, types.KeyPrefixNotUnlocking) - k.clearKeysByPrefix(ctx, types.KeyPrefixUnlocking) -} diff --git a/x/lockup/keeper/lock_test.go b/x/lockup/keeper/lock_test.go index 76c55a058c7..5afecbd678e 100644 --- a/x/lockup/keeper/lock_test.go +++ b/x/lockup/keeper/lock_test.go @@ -114,7 +114,7 @@ func (suite *KeeperTestSuite) TestUnlockPeriodLockByID() { // unlock lock just now lock, err := lockKeeper.GetLockByID(suite.Ctx, 1) suite.Require().NoError(err) - err = lockKeeper.Unlock(suite.Ctx, lock.ID) + err = lockKeeper.UnlockMaturedLock(suite.Ctx, lock.ID) suite.Require().Error(err) // move start time to 1 second in the future. @@ -123,7 +123,7 @@ func (suite *KeeperTestSuite) TestUnlockPeriodLockByID() { // Try to finish unlocking a lock, before starting unlock. lock, err = lockKeeper.GetLockByID(suite.Ctx, 1) suite.Require().NoError(err) - err = lockKeeper.Unlock(suite.Ctx, lock.ID) + err = lockKeeper.UnlockMaturedLock(suite.Ctx, lock.ID) suite.Require().Error(err) // begin unlock @@ -135,7 +135,7 @@ func (suite *KeeperTestSuite) TestUnlockPeriodLockByID() { // unlock 1s after begin unlock lock, err = lockKeeper.GetLockByID(suite.Ctx, 1) suite.Require().NoError(err) - err = lockKeeper.Unlock(suite.Ctx.WithBlockTime(now.Add(time.Second*2)), lock.ID) + err = lockKeeper.UnlockMaturedLock(suite.Ctx.WithBlockTime(now.Add(time.Second*2)), lock.ID) suite.Require().NoError(err) // check locks @@ -195,7 +195,7 @@ func (suite *KeeperTestSuite) TestUnlock() { suite.Require().NoError(err) // unlock with lock object - err = suite.App.LockupKeeper.Unlock(suite.Ctx.WithBlockTime(now.Add(time.Second)), lockPtr.ID) + err = suite.App.LockupKeeper.UnlockMaturedLock(suite.Ctx.WithBlockTime(now.Add(time.Second)), lockPtr.ID) suite.Require().NoError(err) } @@ -252,7 +252,7 @@ func (suite *KeeperTestSuite) TestPartialUnlock() { // Finish unlocking partial unlock partialUnlock := suite.App.LockupKeeper.GetAccountPeriodLocks(suite.Ctx, addr1)[1] - err = suite.App.LockupKeeper.Unlock(suite.Ctx.WithBlockTime(now.Add(time.Second)), partialUnlock.ID) + err = suite.App.LockupKeeper.UnlockMaturedLock(suite.Ctx.WithBlockTime(now.Add(time.Second)), partialUnlock.ID) suite.Require().NoError(err) // check unlocking coins diff --git a/x/lockup/keeper/msg_server.go b/x/lockup/keeper/msg_server.go index b91b48ed3dd..725570bad6c 100644 --- a/x/lockup/keeper/msg_server.go +++ b/x/lockup/keeper/msg_server.go @@ -24,6 +24,11 @@ func NewMsgServerImpl(keeper *Keeper) types.MsgServer { var _ types.MsgServer = msgServer{} +// LockTokens locks tokens in either two ways. +// 1. Add to an existing lock if a lock with the same owner and same duration exists. +// 2. Create a new lock if not. +// A sanity check to ensure given tokens is a single token is done in ValidateBaic. +// That is, a lock with multiple tokens cannot be created. func (server msgServer) LockTokens(goCtx context.Context, msg *types.MsgLockTokens) (*types.MsgLockTokensResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) @@ -32,25 +37,27 @@ func (server msgServer) LockTokens(goCtx context.Context, msg *types.MsgLockToke return nil, err } - // if there is an existing lock - if len(msg.Coins) == 1 { - locks, err := server.keeper.AddToExistingLock(ctx, owner, msg.Coins[0], msg.Duration) - if err != nil { - return nil, err - } - if len(locks) > 0 { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.TypeEvtAddTokensToLock, - sdk.NewAttribute(types.AttributePeriodLockID, utils.Uint64ToString(locks[0].ID)), - sdk.NewAttribute(types.AttributePeriodLockOwner, msg.Owner), - sdk.NewAttribute(types.AttributePeriodLockAmount, msg.Coins.String()), - ), - }) - return &types.MsgLockTokensResponse{ID: locks[0].ID}, nil - } + // check if there's an existing lock from the same owner with the same duration. + // If so, simply add tokens to the existing lock. + locks, err := server.keeper.AddToExistingLock(ctx, owner, msg.Coins[0], msg.Duration) + if err != nil { + return nil, err + } + + // return the lock id of the existing lock when successfully added to the existing lock. + if len(locks) > 0 { + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + types.TypeEvtAddTokensToLock, + sdk.NewAttribute(types.AttributePeriodLockID, utils.Uint64ToString(locks[0].ID)), + sdk.NewAttribute(types.AttributePeriodLockOwner, msg.Owner), + sdk.NewAttribute(types.AttributePeriodLockAmount, msg.Coins.String()), + ), + }) + return &types.MsgLockTokensResponse{ID: locks[0].ID}, nil } + // if the owner + duration combination is new, create a new lock. lock, err := server.keeper.CreateLock(ctx, owner, msg.Coins, msg.Duration) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) @@ -70,6 +77,8 @@ func (server msgServer) LockTokens(goCtx context.Context, msg *types.MsgLockToke return &types.MsgLockTokensResponse{ID: lock.ID}, nil } +// BeginUnlocking begins unlocking of the specified lock. +// The lock would enter the unlocking queue, with the endtime of the lock set as block time + duration. func (server msgServer) BeginUnlocking(goCtx context.Context, msg *types.MsgBeginUnlocking) (*types.MsgBeginUnlockingResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) @@ -99,6 +108,7 @@ func (server msgServer) BeginUnlocking(goCtx context.Context, msg *types.MsgBegi return &types.MsgBeginUnlockingResponse{}, nil } +// BeginUnlockingAll begins unlocking for all the locks that the account has by iterating all the not-unlocking locks the account holds. func (server msgServer) BeginUnlockingAll(goCtx context.Context, msg *types.MsgBeginUnlockingAll) (*types.MsgBeginUnlockingAllResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) @@ -140,6 +150,9 @@ func createBeginUnlockEvent(lock *types.PeriodLock) sdk.Event { ) } +// ExtendLockup extends the duration of the existing lock. +// ExtendLockup would fail if the original lock's duration is longer than the new duration, +// OR if the lock is currently unlocking OR if the original lock has a synthetic lock. func (server msgServer) ExtendLockup(goCtx context.Context, msg *types.MsgExtendLockup) (*types.MsgExtendLockupResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) diff --git a/x/lockup/keeper/synthetic_lock.go b/x/lockup/keeper/synthetic_lock.go index ffb3a3d8e36..a97b6bc830a 100644 --- a/x/lockup/keeper/synthetic_lock.go +++ b/x/lockup/keeper/synthetic_lock.go @@ -5,41 +5,25 @@ import ( "time" "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" -) - -func (k Keeper) setSyntheticLockupObject(ctx sdk.Context, synthLock *types.SyntheticLock) error { - store := ctx.KVStore(k.storeKey) - bz, err := proto.Marshal(synthLock) - if err != nil { - return err - } - store.Set(syntheticLockStoreKey(synthLock.UnderlyingLockId, synthLock.SynthDenom), bz) - if !synthLock.EndTime.Equal(time.Time{}) { - store.Set(syntheticLockTimeStoreKey(synthLock.UnderlyingLockId, synthLock.SynthDenom, synthLock.EndTime), bz) - } - return nil -} - -func (k Keeper) deleteSyntheticLockupObject(ctx sdk.Context, lockID uint64, synthdenom string) { - store := ctx.KVStore(k.storeKey) - synthLock, _ := k.GetSyntheticLockup(ctx, lockID, synthdenom) - if synthLock != nil && !synthLock.EndTime.Equal(time.Time{}) { - store.Delete(syntheticLockTimeStoreKey(lockID, synthdenom, synthLock.EndTime)) - } - store.Delete(syntheticLockStoreKey(lockID, synthdenom)) -} -func (k Keeper) GetUnderlyingLock(ctx sdk.Context, synthlock types.SyntheticLock) types.PeriodLock { - lock, err := k.GetLockByID(ctx, synthlock.UnderlyingLockId) - if err != nil { - panic(err) // Synthetic lock MUST have underlying lock - } - return *lock -} + "github.com/osmosis-labs/osmosis/v7/x/lockup/types" +) +// A synthetic lock object is a lock obejct used for the superfluid module. +// Each synthetic lock object is stored in state using lock id and synthetic denom +// as it's key, where a synthetic denom would be consisted of the original denom of the lock, +// validator address, and the staking positiion of the lock. +// Unlike the original lock objects, synthetic locks are mainly used to indicate the staking +// position of the lock. +// Synthetic use different accumulation store from the original lock objects. +// Note that locks with synthetic objects cannot be directly deleted or cannot directly start +// unlocking. locks with synthetic lock objects are to be unlocked via superfluid module. +// The Endtime and the Duration fields of the synthetic locks do not need to have the same values +// as the underlying lock objects. + +// GetSyntheticLockup gets the synthetic lock object using lock ID and synthetic denom as key. func (k Keeper) GetSyntheticLockup(ctx sdk.Context, lockID uint64, synthdenom string) (*types.SyntheticLock, error) { synthLock := types.SyntheticLock{} store := ctx.KVStore(k.storeKey) @@ -52,6 +36,7 @@ func (k Keeper) GetSyntheticLockup(ctx sdk.Context, lockID uint64, synthdenom st return &synthLock, err } +// GetAllSyntheticLockupsByLockup gets all the synthetic lockup object of the original lockup. func (k Keeper) GetAllSyntheticLockupsByLockup(ctx sdk.Context, lockID uint64) []types.SyntheticLock { store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, combineKeys(types.KeyPrefixSyntheticLockup, sdk.Uint64ToBigEndian(lockID))) @@ -69,6 +54,7 @@ func (k Keeper) GetAllSyntheticLockupsByLockup(ctx sdk.Context, lockID uint64) [ return synthLocks } +// GetAllSyntheticLockupsByAddr gets all the synthetic lockups from all the locks owned by the given address. func (k Keeper) GetAllSyntheticLockupsByAddr(ctx sdk.Context, owner sdk.AccAddress) []types.SyntheticLock { synthLocks := []types.SyntheticLock{} locks := k.GetAccountPeriodLocks(ctx, owner) @@ -78,6 +64,7 @@ func (k Keeper) GetAllSyntheticLockupsByAddr(ctx sdk.Context, owner sdk.AccAddre return synthLocks } +// HasAnySyntheticLockups returns true if the lock has a synthetic lock. func (k Keeper) HasAnySyntheticLockups(ctx sdk.Context, lockID uint64) bool { store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, combineKeys(types.KeyPrefixSyntheticLockup, sdk.Uint64ToBigEndian(lockID))) @@ -85,6 +72,7 @@ func (k Keeper) HasAnySyntheticLockups(ctx sdk.Context, lockID uint64) bool { return iterator.Valid() } +// GetAllSyntheticLockups gets all synthetic locks within the store. func (k Keeper) GetAllSyntheticLockups(ctx sdk.Context) []types.SyntheticLock { store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, types.KeyPrefixSyntheticLockup) @@ -106,7 +94,7 @@ func (k Keeper) GetAllSyntheticLockups(ctx sdk.Context) []types.SyntheticLock { func (k Keeper) CreateSyntheticLockup(ctx sdk.Context, lockID uint64, synthDenom string, unlockDuration time.Duration, isUnlocking bool) error { // Note: synthetic lockup is doing everything same as lockup except coin movement // There is no relationship between unbonding and bonding synthetic lockup, it's managed separately - // Accumulation store works without caring about unlocking synthetic or not + // A separate accumulation store is incremented with the synth denom. _, err := k.GetSyntheticLockup(ctx, lockID, synthDenom) if err == nil { @@ -153,7 +141,27 @@ func (k Keeper) CreateSyntheticLockup(ctx sdk.Context, lockID uint64, synthDenom return nil } +// DeleteAllSyntheticLocks iterates over given array of synthetic locks and deletes all individual synthetic locks. +func (k Keeper) DeleteAllSyntheticLocks(ctx sdk.Context, lock types.PeriodLock, synthLocks []types.SyntheticLock) error { + if len(synthLocks) == 0 { + return nil + } + + for _, synthLock := range synthLocks { + err := k.DeleteSyntheticLockup(ctx, lock.ID, synthLock.SynthDenom) + if err != nil { + return err + } + } + return nil +} + // DeleteSyntheticLockup delete synthetic lockup with lock id and synthdenom. +// Synthetic lock has three relevant state entries. +// - synthetic lock object itself +// - synthetic lock refs +// - accumulation store for the synthetic lock. +// all of which are deleted within this method. func (k Keeper) DeleteSyntheticLockup(ctx sdk.Context, lockID uint64, synthdenom string) error { synthLock, err := k.GetSyntheticLockup(ctx, lockID, synthdenom) if err != nil { @@ -185,6 +193,7 @@ func (k Keeper) DeleteSyntheticLockup(ctx sdk.Context, lockID uint64, synthdenom return nil } +// DeleteAllMaturedSyntheticLocks deletes all matured synthetic locks. func (k Keeper) DeleteAllMaturedSyntheticLocks(ctx sdk.Context) { iterator := k.iteratorBeforeTime(ctx, combineKeys(types.KeyPrefixSyntheticLockTimestamp), ctx.BlockTime()) defer iterator.Close() @@ -201,3 +210,33 @@ func (k Keeper) DeleteAllMaturedSyntheticLocks(ctx sdk.Context) { } } } + +func (k Keeper) GetUnderlyingLock(ctx sdk.Context, synthlock types.SyntheticLock) types.PeriodLock { + lock, err := k.GetLockByID(ctx, synthlock.UnderlyingLockId) + if err != nil { + panic(err) // Synthetic lock MUST have underlying lock + } + return *lock +} + +func (k Keeper) setSyntheticLockupObject(ctx sdk.Context, synthLock *types.SyntheticLock) error { + store := ctx.KVStore(k.storeKey) + bz, err := proto.Marshal(synthLock) + if err != nil { + return err + } + store.Set(syntheticLockStoreKey(synthLock.UnderlyingLockId, synthLock.SynthDenom), bz) + if !synthLock.EndTime.Equal(time.Time{}) { + store.Set(syntheticLockTimeStoreKey(synthLock.UnderlyingLockId, synthLock.SynthDenom, synthLock.EndTime), bz) + } + return nil +} + +func (k Keeper) deleteSyntheticLockupObject(ctx sdk.Context, lockID uint64, synthdenom string) { + store := ctx.KVStore(k.storeKey) + synthLock, _ := k.GetSyntheticLockup(ctx, lockID, synthdenom) + if synthLock != nil && !synthLock.EndTime.Equal(time.Time{}) { + store.Delete(syntheticLockTimeStoreKey(lockID, synthdenom, synthLock.EndTime)) + } + store.Delete(syntheticLockStoreKey(lockID, synthdenom)) +} From 5ba829f984db41d8db372a7bc0682c678876b148 Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 30 Jun 2022 23:35:14 -0400 Subject: [PATCH 008/376] e2e: ExecCmd debug log on error (#1924) * e2e: ExecCmd debug log on error * update * update --- tests/e2e/containers/containers.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/tests/e2e/containers/containers.go b/tests/e2e/containers/containers.go index a1703b35f67..477a17837ad 100644 --- a/tests/e2e/containers/containers.go +++ b/tests/e2e/containers/containers.go @@ -5,6 +5,7 @@ import ( "context" "fmt" "os" + "regexp" "strings" "testing" "time" @@ -14,6 +15,8 @@ import ( "github.com/stretchr/testify/require" ) +var errRegex = regexp.MustCompile(`(E|e)rror`) + // Manager is a wrapper around all Docker instances, and the Docker API. // It provides utilities to run and interact with all Docker containers used within e2e testing. type Manager struct { @@ -88,15 +91,29 @@ func (m *Manager) ExecCmd(t *testing.T, chainId string, validatorIndex int, comm return false } + errBufString := errBuf.String() + // Note that this does not match all errors. + // This only works if CLI outpurs "Error" or "error" + // to stderr. + if errRegex.MatchString(errBufString) { + t.Log("Potential error in stderr:") + t.Log(errBufString) + // N.B: We should not be returning false here + // because some applications such as Hermes might log + // "error" to stderr when they function correctly, + // causing test flakiness. This log is needed only for + // debugging purposes. + } + if success != "" { - return strings.Contains(outBuf.String(), success) || strings.Contains(errBuf.String(), success) + return strings.Contains(outBuf.String(), success) || strings.Contains(errBufString, success) } return true }, time.Minute, time.Second, - "tx returned a non-zero code; stdout: %s, stderr: %s", outBuf.String(), errBuf.String(), + "tx returned a non-zero code", ) return outBuf, errBuf, nil From 0f3e8b9a9be76938d55a30fcb92a541cd8f70dba Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Thu, 30 Jun 2022 22:48:01 -0500 Subject: [PATCH 009/376] Delete cmd/testnetify (#1933) --- cmd/osmosisd/cmd/testnetify/README.md | 116 ------- cmd/osmosisd/cmd/testnetify/cmd.go | 66 ---- cmd/osmosisd/cmd/testnetify/find_replace.go | 25 -- cmd/osmosisd/cmd/testnetify/script.sh | 83 ----- .../cmd/testnetify/state_export_to_testnet.go | 123 ------- cmd/osmosisd/cmd/testnetify/testnetify.py | 313 ------------------ 6 files changed, 726 deletions(-) delete mode 100644 cmd/osmosisd/cmd/testnetify/README.md delete mode 100644 cmd/osmosisd/cmd/testnetify/cmd.go delete mode 100644 cmd/osmosisd/cmd/testnetify/find_replace.go delete mode 100644 cmd/osmosisd/cmd/testnetify/script.sh delete mode 100644 cmd/osmosisd/cmd/testnetify/state_export_to_testnet.go delete mode 100644 cmd/osmosisd/cmd/testnetify/testnetify.py diff --git a/cmd/osmosisd/cmd/testnetify/README.md b/cmd/osmosisd/cmd/testnetify/README.md deleted file mode 100644 index 177216d6d8c..00000000000 --- a/cmd/osmosisd/cmd/testnetify/README.md +++ /dev/null @@ -1,116 +0,0 @@ -# Testnetify.py - -This script takes a state export JSON file (under the name -testnet\_genesis.json) and edits multiple values to give the operator -address 1M spendable OSMO, makes your validator file possess over 1M -OSMO, makes the epoch duration 21600s, and sets the voting period to -180s. - -## Instructions - -Start at home directory - -```sh -cd $HOME -``` - -Create state export from a running node (ensure to name it -testnet\_genesis.json for script to work) - -```sh -osmosisd export 2> testnet_genesis.json -``` - -Make a copy of the genesis file, just in case you mess up - -```sh -cp $HOME/testnet_genesis.json $HOME/testnet_genesis_bk.json -``` - -NOTE: There are three values in the python script you can change. - -1. The operator address (op\_address) and its corresponding public key - (op\_pubkey). I provided the mnemonic for the provided address - (osmo12smx2wdlyttvyzvzg54y2vnqwq2qjateuf7thj), but you may change - the address and corresponding pubkey if desired -2. The chain-id (new\_chain\_id) -3. The epoch duration (new\_duration) -4. The voting period (new\_voting\_period) -5. The distribution module account currently must be subtracted by 3 - due to a bug. If the account gets offset further, you must change - dist\_offset\_amt - -Mnemonic for provided address: **bottom loan skill merry east cradle -onion journey palm apology verb edit desert impose absurd oil bubble -sweet glove shallow size build burst effort** - -From the same directory as the testnet\_genesis.json, run testnetify.py - -```sh -python3 testnetify.py -``` - -After it is complete, overwrite the current genesis file with new -testnet genesis - -```sh -cp testnet_genesis.json .osmosisd/config/genesis.json -``` - -Unsafe reset all - -```sh -osmosisd unsafe-reset-all -``` - -Start osmosis daemon (with extra flag first time around) - -```sh -osmosisd start --x-crisis-skip-assert-invariants -``` - -After initializing, you will get a "couldn't connect to any seeds" -error. Leave the node as it is. - -Set up a second node with the same genesis.json file that was created -using the first node. - -On the first node, retrieve its public IP and also run this command to -get your node ID - -```sh -osmosisd tendermint show-node-id -``` - -On the second node, open the config.toml - -```sh -nano $HOME/.osmosisd/config/config.toml -``` - -Under persistent\_peers and seeds, add the first nodes information like -so: node-id\@IP:26656 - -Example: 665ebb897edc41d691c70b15916086a9c7761dc4\@199.43.113.117:26656 - -On the second node, ensure the genesis file is replaced with the genesis -created on the first node and start the osmosis daemon - -```sh -osmosisd start --x-crisis-skip-assert-invariants -``` - -Once the second peer initializes, the chain will no longer be halted -(this is necessary due to a tendermint bug). The second peer can then be -shut off if desired. If the first peer ever shuts down, the second peer -must be started in order to kickstart the chain again. - -As a last note, sometimes getting testnet nodes spun up for the first -time can be finicky. If you are stuck getting the second node to connect -to the first node, sometimes doing a `unsafe-reset-all` on both nodes -fixes the issue. Also, try adding the second node as a persistent peer -to the first node. These two methods have fixed nodes that do not want -to cooperate. Lastly, if your node keeps killing the daemon, please -ensure you have a swap file set up. - -Enjoy your state exported testnet! diff --git a/cmd/osmosisd/cmd/testnetify/cmd.go b/cmd/osmosisd/cmd/testnetify/cmd.go deleted file mode 100644 index 97990c49a9a..00000000000 --- a/cmd/osmosisd/cmd/testnetify/cmd.go +++ /dev/null @@ -1,66 +0,0 @@ -package testnetify - -import ( - "encoding/json" - "io/ioutil" - "os" - - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/spf13/cobra" -) - -// get cmd to convert any bech32 address to an osmo prefix. -func StateExportToTestnetGenesis() *cobra.Command { - cmd := &cobra.Command{ - Use: "testnetify [state_export_path] -p [testnet_params]", - Short: "Convert state export to be a testnet", - Long: `Fill this out plz - `, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - testnetParams, err := loadTestnetParams(cmd) - if err != nil { - return err - } - - state_export_path := args[0] - file, err := ioutil.ReadFile(state_export_path) - if err != nil { - // failed to read file - return err - } - var genesis app.GenesisState - err = json.Unmarshal(file, &genesis) - if err != nil { - return err - } - - replaceValidatorDetails(genesis, testnetParams) - updateChainId(genesis) - clearIBC(genesis) - - cmd.Println("Writing new genesis to: ", testnetParams.OutputExportFilepath) - err = writeGenesis(genesis, testnetParams.OutputExportFilepath) - if err != nil { - // failed to read file - return err - } - return nil - }, - } - - cmd.Flags().StringP(flagTestnetParams, "p", "params", "Testnet params json") - - return cmd -} - -func writeGenesis(genesis app.GenesisState, path string) error { - file, err := os.OpenFile(path, os.O_CREATE, os.ModePerm) - if err != nil { - // failed to read file - return err - } - defer file.Close() - encoder := json.NewEncoder(file) - return encoder.Encode(genesis) -} diff --git a/cmd/osmosisd/cmd/testnetify/find_replace.go b/cmd/osmosisd/cmd/testnetify/find_replace.go deleted file mode 100644 index 69f413dd5b4..00000000000 --- a/cmd/osmosisd/cmd/testnetify/find_replace.go +++ /dev/null @@ -1,25 +0,0 @@ -package testnetify - -import ( - "bytes" - - "github.com/osmosis-labs/osmosis/v7/app" -) - -func replaceConsAddrHex(genesis app.GenesisState, fromAddr string, replaceAddr string) { - // TODO: When optimizing, do single in-place mutation - replaceAllInGenesis(genesis, fromAddr, replaceAddr) -} - -// TODO: Make it possible to only replace all in certain genesis keys -// no reason to pay for iterating over bank every time :). -func replaceAllInGenesis(genesis app.GenesisState, find string, replace string) { - // To help in debugging - findBz := []byte(find) - replaceBz := []byte(replace) - for k := range genesis { - value := genesis[k] - value = bytes.ReplaceAll(value, findBz, replaceBz) - genesis[k] = value - } -} diff --git a/cmd/osmosisd/cmd/testnetify/script.sh b/cmd/osmosisd/cmd/testnetify/script.sh deleted file mode 100644 index 26aaa8ba3c8..00000000000 --- a/cmd/osmosisd/cmd/testnetify/script.sh +++ /dev/null @@ -1,83 +0,0 @@ -# run sed - -export EXPORTED_GENESIS=testnet_genesis.json - -# Replace Sentinel addrs/pubkeys - -# priv_validator_key.json file for what we replace to -# { -# "address": "8B78E478777427CC3906B8234CB72BCEA2C78E83", -# "pub_key": { -# "type": "tendermint/PubKeyEd25519", -# "value": "2OpBuqaXvXQ+lSxAoT1S7Jfyr56KiakTzvuFiuJK+X4=" -# }, -# "priv_key": { -# "type": "tendermint/PrivKeyEd25519", -# "value": "3OLLoEfdT+ZrLqpRCvytpXrhgKfeEBBoeaoXe1p3/mjY6kG6ppe9dD6VLEChPVLsl/KvnoqJqRPO+4WK4kr5fg==" -# } -# } - -# replace validator cons pubkey -sed -i '' 's%b77zCh/VsRgVvfGXuW4dB+Dhg4PrMWWBC5G2K/qFgiU=%2OpBuqaXvXQ+lSxAoT1S7Jfyr56KiakTzvuFiuJK+X4=%g' $EXPORTED_GENESIS -# This is a PITA to get: -# take pubkey, do osmosisd debug pubkey {base64} -# take address out of it, feed into osmosisd debug addr {addr} -# pass that into osmosisd debug bech32-convert -p osmovalcons -sed -i '' 's%osmovalcons1z6skn9g6s7py0klztr7acutr3anqd52k9x5p70%osmovalcons13duwg7rhwsnucwgxhq35edete63v0r5rqp90es%g' $EXPORTED_GENESIS -# replace validator hex addr -sed -i '' 's%16A169951A878247DBE258FDDC71638F6606D156%8B78E478777427CC3906B8234CB72BCEA2C78E83%g' $EXPORTED_GENESIS -# replace operator address -# mnemonic: kitchen comic flower drip sick prize account cheese truth income weekend nominee segment punch call satisfy captain earth ethics wasp clump tunnel orchard advance -sed -i '' 's%osmovaloper1cyw4vw20el8e7ez8080md0r8psg25n0cq98a9n%osmovaloper1qye772qje88p7ggtzrvl9nxvty6dkuusvpqhac%g' $EXPORTED_GENESIS -# replace the actual account -sed -i '' 's%osmo1cyw4vw20el8e7ez8080md0r8psg25n0c6j07j5%osmo1qye772qje88p7ggtzrvl9nxvty6dkuuskkg52l%g' $EXPORTED_GENESIS -# replace that accounts pubkey, obtained via auth. New pubkey obtained via new debug command -sed -i '' 's%AqlNb1FM8veQrT4/apR5B3hww8VApc0LTtZnXhq7FqG0%A9zC0Sa0VCK/lVLi1Kv0C1c0MQp47d+yjFqb6dAUza0a%g' $EXPORTED_GENESIS - -# now time to replace the delegation share amounts for the self-bond -# before: 5000000000.000000000000000000 (5000 osmo) -# after: 1000005000000000.000000000000000000 (1 BN + 5k osmo = 1,000,005,000) -# There are two spots for this, one is the delegator shares of the pool -# in app_state[staking][delegations]{ -# entry with delegator_address = osmo1qye772qje88p7ggtzrvl9nxvty6dkuuskkg52lm, and validator addr = osmovaloper1qye772qje88p7ggtzrvl9nxvty6dkuusvpqhac} -DELEGATOR_INDEX=$(jq '.app_state["staking"]["delegations"] | map (.delegator_address=="osmo1qye772qje88p7ggtzrvl9nxvty6dkuuskkg52l") | index(true)' $EXPORTED_GENESIS) -cat $EXPORTED_GENESIS | jq '.app_state["staking"]["delegations"]['"$DELEGATOR_INDEX"']["shares"]="1000005000000000.000000000000000000"' > tmp_genesis.json && mv tmp_genesis.json $EXPORTED_GENESIS -# and in app_state.distribution.delegator_starting_infos -DISTRIBUTION_START_INFO_INDEX=$(jq '.app_state.distribution.delegator_starting_infos | map (.delegator_address=="osmo1qye772qje88p7ggtzrvl9nxvty6dkuuskkg52l") | index(true)' $EXPORTED_GENESIS) -cat $EXPORTED_GENESIS | jq '.app_state.distribution.delegator_starting_infos['"$DISTRIBUTION_START_INFO_INDEX"'].starting_info.stake="1000005000000000.000000000000000000"' > tmp_genesis.json && mv tmp_genesis.json $EXPORTED_GENESIS - -# Then correspondingly up the total tokens bonded to the validator -# "tokens": "5743672759222", (add 1BN to this) -sed -i '' 's%5743672759222%1005743672759222%g' $EXPORTED_GENESIS -sed -i '' 's%"power": "5743672"%"power": "1005743672"%g' $EXPORTED_GENESIS -# Update last_total_power (which is last total bonded across validators) -sed -i '' 's%65600898%1065600898%g' $EXPORTED_GENESIS - -# edit operator address, old: 2125267 (2.1 osmo), new: 1000000002125267 (1BN + 2.1) -sed -i '' 's%"2125267"%"1000000002125267"%g' $EXPORTED_GENESIS - -# Update total osmo supply, old 429793936956313, new 2Billion + 429793936956313 -sed -i '' 's%429793936956313%2429793936956313%g' $EXPORTED_GENESIS - -# Fix bonded_tokens_pool balance, old 65600951578831 -sed -i '' 's%65600951578831%1065600951578831%g' $EXPORTED_GENESIS - -### Fix gov params - -# deposit -sed -i '' 's%"voting_period": "259200s"%"voting_period": "40s"%g' $EXPORTED_GENESIS - -# epoch length - # "epochs": [ - # { - # "current_epoch": "77", - # "current_epoch_ended": false, - # "current_epoch_start_time": "2021-12-03T17:02:07.229632445Z", - # "duration": "86400s", - # "epoch_counting_started": true, - # "identifier": "day", - # "start_time": "2021-06-18T17:00:00Z" - # }, -# replace that duration with jq -cat $EXPORTED_GENESIS | jq '.app_state["epochs"]["epochs"][0]["duration"]="3600s"' > tmp_genesis.json && mv tmp_genesis.json $EXPORTED_GENESIS -cat $EXPORTED_GENESIS | jq '.app_state["epochs"]["epochs"][0]["current_epoch_start_time"]="2021-12-08T17:02:07.229632445Z"' > tmp_genesis.json && mv tmp_genesis.json $EXPORTED_GENESIS diff --git a/cmd/osmosisd/cmd/testnetify/state_export_to_testnet.go b/cmd/osmosisd/cmd/testnetify/state_export_to_testnet.go deleted file mode 100644 index be694c629a1..00000000000 --- a/cmd/osmosisd/cmd/testnetify/state_export_to_testnet.go +++ /dev/null @@ -1,123 +0,0 @@ -package testnetify - -import ( - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/spf13/cobra" -) - -var ( - flagTestnetParams = "empty" - valConsBech32 = "osmovalcons" -) - -// TODO: Add params for min num validators for consensus. -type TestnetParams struct { - ValidatorConsensusPubkeys []string - ValidatorOperatorPubkeys []string - OutputExportFilepath string -} - -type ValidatorDetails struct { - // e.g. 16A169951A878247DBE258FDDC71638F6606D156 - // Only appears once - ConsAddressHex string - // e.g. b77zCh/VsRgVvfGXuW4dB+Dhg4PrMWWBC5G2K/qFgiU= - ConsPubkeyRaw string - // e.g. osmovaloper1cyw4vw20el8e7ez8080md0r8psg25n0cq98a9n - OperatorAddress string -} - -//nolint:ineffassign -func defaultTestnetParams() TestnetParams { - /* priv_validator_key.json file - { - "address": "8B78E478777427CC3906B8234CB72BCEA2C78E83", - "pub_key": { - "type": "tendermint/PubKeyEd25519", - "value": "2OpBuqaXvXQ+lSxAoT1S7Jfyr56KiakTzvuFiuJK+X4=" - }, - "priv_key": { - "type": "tendermint/PrivKeyEd25519", - "value": "3OLLoEfdT+ZrLqpRCvytpXrhgKfeEBBoeaoXe1p3/mjY6kG6ppe9dD6VLEChPVLsl/KvnoqJqRPO+4WK4kr5fg==" - } - } - */ - consensusPubkey := "2OpBuqaXvXQ+lSxAoT1S7Jfyr56KiakTzvuFiuJK+X4=" - // mnemonic kitchen comic flower drip sick prize account cheese truth income weekend nominee segment punch call satisfy captain earth ethics wasp clump tunnel orchard advance - operatorPubkey := "osmopub1addwnpepq0wv95fxk32z90u42t3df2l5pdtngvg20rkalv5vt2d7n5q5ekk35d8hh20" - operatorValOper := "osmovaloper1qye772qje88p7ggtzrvl9nxvty6dkuusvpqhac" - operatorValOper += "" - return TestnetParams{ - ValidatorConsensusPubkeys: []string{consensusPubkey}, - ValidatorOperatorPubkeys: []string{operatorPubkey}, - OutputExportFilepath: "new_testnet_genesis.json", - } -} - -func (params TestnetParams) NewValidatorDetails() []ValidatorDetails { - numValidators := len(params.ValidatorConsensusPubkeys) - outputDeets := make([]ValidatorDetails, 0, numValidators) - for i := 0; i < numValidators; i++ { - deets := ValidatorDetails{ - ConsPubkeyRaw: params.ValidatorConsensusPubkeys[i], - OperatorAddress: params.ValidatorConsensusPubkeys[i], - } - outputDeets = append(outputDeets, deets) - } - return outputDeets -} - -func replaceValidatorDetails(genesis app.GenesisState, params TestnetParams) { - oldValidatorDetails := getValidatorDetailsToReplace(genesis, params) - newValidatorDetails := params.NewValidatorDetails() - numValidators := len(oldValidatorDetails) - for i := 0; i < numValidators; i++ { - oldDeets := oldValidatorDetails[i] - newDeets := newValidatorDetails[i] - - // TODO: Use more module-focused find replaces - replaceConsAddrHex(genesis, oldDeets.ConsAddressHex, newDeets.ConsAddressHex) - replaceAllInGenesis(genesis, oldDeets.ConsPubkeyRaw, newDeets.ConsPubkeyRaw) - replaceAllInGenesis(genesis, oldDeets.OperatorAddress, newDeets.OperatorAddress) - } -} - -func getValidatorDetailsToReplace(genesis app.GenesisState, params TestnetParams) []ValidatorDetails { - // TODO: Don't hardcode to sentinel, instead all validators from chain - // and get top N validators - // consAddr only has 1 instance - validatorConsAddr := "16A169951A878247DBE258FDDC71638F6606D156" - // Only has 2 instances - validatorConsPubkey := "b77zCh/VsRgVvfGXuW4dB+Dhg4PrMWWBC5G2K/qFgiU=" - // Sometimes appears in slashing - // validatorConsBech32Addr := "osmosvalcons1z6skn9g6s7py0klztr7acutr3anqd52kuhdukh" - validatorOperBech32Addr := "osmovaloper1cyw4vw20el8e7ez8080md0r8psg25n0cq98a9n" - - SentinelValidatorDetails := ValidatorDetails{ - ConsAddressHex: validatorConsAddr, - ConsPubkeyRaw: validatorConsPubkey, - OperatorAddress: validatorOperBech32Addr, - } - return []ValidatorDetails{ - SentinelValidatorDetails, - } -} - -func updateChainId(genesis app.GenesisState) { - // TODO: Implement -} - -func clearIBC(genesis app.GenesisState) { - // TODO: Implement -} - -func loadTestnetParams(cmd *cobra.Command) (TestnetParams, error) { - testnetParamPath, err := cmd.Flags().GetString(flagTestnetParams) - if err != nil { - return TestnetParams{}, err - } - if testnetParamPath == "empty" { - return defaultTestnetParams(), nil - } - panic("TODO: Go read testnet params from a file") -} diff --git a/cmd/osmosisd/cmd/testnetify/testnetify.py b/cmd/osmosisd/cmd/testnetify/testnetify.py deleted file mode 100644 index 1f94fe2cc97..00000000000 --- a/cmd/osmosisd/cmd/testnetify/testnetify.py +++ /dev/null @@ -1,313 +0,0 @@ -import json -import subprocess -import re, shutil, tempfile -from datetime import datetime - - -#get values from your priv_validator_key.json to later switch with high power validator - -daemon_name = "osmosisd" - -#get bas64 -result = subprocess.run([daemon_name,"tendermint","show-validator"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) -base64 = result.stdout.strip() -##base64 = '{"@type":"/cosmos.crypto.ed25519.PubKey","key":"3QVAkiUIkKR3B6kkbd+QqzWDdcExoggbZV5fwH4jKDs="}' - -#get validator cons pubkey -val_pubkey = base64[base64.find('key":') +6 :-2] -##val_pubkey = "3QVAkiUIkKR3B6kkbd+QqzWDdcExoggbZV5fwH4jKDs=" - -#osmosisd debug pubkey {base64} to get address -debug_pubkey = subprocess.run([daemon_name,"debug", "pubkey", base64], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) - -#address -address = debug_pubkey.stderr[9: debug_pubkey.stderr.find("\n")] -##based on show-valdiator -##address = "214D831D6F49A75F9104BDC3F2E12A6CC1FC5669" - -#feed address into osmosisd debug addr {address} to get bech32 validator address (osmovaloper) -bech32 = subprocess.run([daemon_name,"debug", "addr", address], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) -#osmovaloper -bech32_val = bech32.stderr[bech32.stderr.find("Val: ") + 5: -1] -##operator address -##bech32_val = "osmovaloper1y9xcx8t0fxn4lygyhhpl9cf2dnqlc4nf4pymm4" - -#pass osmovaloper address into osmosisd debug bech32-convert -p osmovalcons -bech32_convert = subprocess.run([daemon_name,"debug", "bech32-convert", bech32_val, "-p", "osmovalcons"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) -#osmovalcons -final_address = bech32_convert.stderr[:bech32_convert.stderr.find("\n")] -##osmovalcons is taken from show-validator -##final_address = "osmovalcons1y9xcx8t0fxn4lygyhhpl9cf2dnqlc4nfpjh8h5" - -#own opp address -#exchange the op_address and op_pubkey with own address and pubkey or use above mnemonic for following address -#bottom loan skill merry east cradle onion journey palm apology verb edit desert impose absurd oil bubble sweet glove shallow size build burst effort -#CAN MODIFY -op_address = "osmo12smx2wdlyttvyzvzg54y2vnqwq2qjateuf7thj" - -#own pub key -#op_base64_pre = subprocess.run(["osmosisd","query", "auth", "account", op_address], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) -#op_pubkey = op_base64_pre.stdout[op_base64_pre.stdout.find("key: ")+5:op_base64_pre.stdout.find("sequence")-1] -#CAN MODIFY -op_pubkey = "A2MR6q+pOpLtdxh0tHHe2JrEY2KOcvRogtLxHDHzJvOh" - -#feed address into osmosisd debug addr {address} to get bech32 validator op address (osmovaloper) -# bech32_op = subprocess.run([daemon_name,"debug", "addr", op_address], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) -#osmovaloper -# bech32_valoper = bech32_op.stderr[bech32_op.stderr.find("Val: ") + 5: -1] -# osmovaloper12smx2wdlyttvyzvzg54y2vnqwq2qjatex7kgq4 - -def sed_inplace(filename, pattern, repl): - ''' - Perform the pure-Python equivalent of in-place `sed` substitution: e.g., - `sed -i -e 's/'${pattern}'/'${repl}' "${filename}"`. - ''' - # For efficiency, precompile the passed regular expression. - pattern_compiled = re.compile(pattern) - - # For portability, NamedTemporaryFile() defaults to mode "w+b" (i.e., binary - # writing with updating) - with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file: - with open(filename) as src_file: - for line in src_file: - tmp_file.write(pattern_compiled.sub(repl, line)) - - # Overwrite the original file with the munged temporary file in a - # manner preserving file attributes (e.g., permissions). - shutil.copystat(filename, tmp_file.name) - shutil.move(tmp_file.name, filename) - - -#validator cons pubkey: val_pubkey -#osmovalcons: final_address -#validator hex address: address -#osmovaloper: bech32_valoper -#actual account: op_address -#accounts pubkey: op_pubkey - - - -#replace validator cons pubkey (this did not work well due to random forward slashes, did other way later) -#sed_inplace("testnet_genesis.json", "b77zCh/VsRgVvfGXuW4dB+Dhg4PrMWWBC5G2K/qFgiU=", val_pubkey) - -#replace validator osmovalcons -print("Replacing osmovalcons1z6skn9g6s7py0klztr7acutr3anqd52k9x5p70 with " + final_address) -sed_inplace("testnet_genesis.json", "osmovalcons1z6skn9g6s7py0klztr7acutr3anqd52k9x5p70", final_address) - -#replace validator hex address -print("Replacing 16A169951A878247DBE258FDDC71638F6606D156 with " + address) -sed_inplace("testnet_genesis.json", "16A169951A878247DBE258FDDC71638F6606D156", address) - -#replace validator osmovaloper -#print("Replacing osmovaloper1cyw4vw20el8e7ez8080md0r8psg25n0cq98a9n with " + bech32_valoper) -#sed_inplace("testnet_genesis.json", "osmovaloper1cyw4vw20el8e7ez8080md0r8psg25n0cq98a9n", bech32_valoper) - -#replace actual account -print("Replacing osmo1cyw4vw20el8e7ez8080md0r8psg25n0c6j07j5 with " + op_address) -sed_inplace("testnet_genesis.json", "osmo1cyw4vw20el8e7ez8080md0r8psg25n0c6j07j5", op_address) - -#replace actual account pubkey -print("Replacing AqlNb1FM8veQrT4/apR5B3hww8VApc0LTtZnXhq7FqG0 with " + op_pubkey) -sed_inplace("testnet_genesis.json", "AqlNb1FM8veQrT4/apR5B3hww8VApc0LTtZnXhq7FqG0", op_pubkey) - - - -#open genesis json file with read write priv, load json -test_gen = open("testnet_genesis.json", "r+") -read_test_gen = json.loads(test_gen.read()) -#print(read_test_gen.keys()) - - -#change chain-id -print("Current chain-id is " + read_test_gen['chain_id']) -#CAN MODIFY -new_chain_id = "osmo-test-2" -read_test_gen['chain_id'] = new_chain_id -print("New chain-id is " + read_test_gen['chain_id']) - - -#validator pubkey must be replaced from b77zCh/VsRgVvfGXuW4dB+Dhg4PrMWWBC5G2K/qFgiU= in two locations -#first under read_test_gen['app_state']['staking']['validators'] -#second under read_test_gen['validators'] -#i tried to do this using sed_inplace above but the multiple slashes broke it so did this instead - -#first val list index -app_state_val_list = read_test_gen['app_state']['staking']['validators'] -val_index = [i for i, elem in enumerate(app_state_val_list) if 'Sentinel' in elem['description']['moniker']][0] -#first val list update key -#based on val -app_state_val_list[val_index]['consensus_pubkey']['key'] = val_pubkey -#also update delegator shares and tokens -current_del_share = str(app_state_val_list[val_index]['delegator_shares']) -print("Current delegator shares is " + current_del_share) -app_state_val_list[val_index]['delegator_shares'] = str(int(float(app_state_val_list[val_index]['delegator_shares']) + 1000000000000000)) + ".000000000000000000" -print("New delegator shares is " + app_state_val_list[val_index]['delegator_shares']) -print("Current delegator tokens is " + app_state_val_list[val_index]['tokens']) -app_state_val_list[val_index]['tokens'] = str(int(app_state_val_list[val_index]['tokens']) + 1000000000000000) -print("New delegator tokens is " + app_state_val_list[val_index]['tokens']) - -#second val list index -val_list_2 = read_test_gen['validators'] -val_list_2_index = [i for i, elem in enumerate(val_list_2) if 'Sentinel' in elem['name']][0] -#second val list update key -#based on val -val_list_2[val_list_2_index]['pub_key']['value'] = val_pubkey - - -#distribution module fix -dist_address = "osmo1jv65s3grqf6v6jl3dp4t6c9t9rk99cd80yhvld" -app_state_balances_list = read_test_gen['app_state']['bank']['balances'] -dist_index = [i for i, elem in enumerate(app_state_balances_list) if dist_address in elem['address']][0] -dist_all = app_state_balances_list[dist_index]['coins'] -osmo_index = [i for i, elem in enumerate(dist_all) if 'uosmo' in elem['denom']][0] -current_dist_osmo_bal = dist_all[osmo_index]['amount'] -dist_offset_amt = 2 -print("Current distribution account uosmo balance is " + current_dist_osmo_bal) -new_dist_osmo_bal = str(int(current_dist_osmo_bal) - dist_offset_amt) -print("New distribution account uosmo balance is " + new_dist_osmo_bal) -dist_all[osmo_index]['amount'] = new_dist_osmo_bal - - -#change self delegation amount on operator address - -#first location -app_state_del_list = read_test_gen['app_state']['staking']['delegations'] -del_index = [i for i, elem in enumerate(app_state_del_list) if op_address in elem['delegator_address']][0] -#first val list update share (add 1 BN) -current_share = app_state_del_list[del_index]['shares'] -print("Current self delegation is " + str(current_share)) -new_share = str(int(float(current_share)) + 1000000000000000)+".000000000000000000" -print("New self delegation is " + new_share) -app_state_del_list[del_index]['shares'] = new_share - -#second location -app_state_dist_list = read_test_gen['app_state']['distribution']['delegator_starting_infos'] -dist_index = [i for i, elem in enumerate(app_state_dist_list) if op_address in elem['delegator_address']][0] -#second val list update stake (add 1 BN) -current_stake = app_state_dist_list[dist_index]['starting_info']['stake'] -print("Current stake is " + str(current_stake)) -new_stake = str(int(float(current_stake)) + 1000000000000000)+".000000000000000000" -print("New stake is " + new_stake) -app_state_dist_list[dist_index]['starting_info']['stake'] = new_stake - - -#get index of val power -val_power_list = read_test_gen['validators'] -val_power_index = [i for i, elem in enumerate(val_power_list) if 'Sentinel' in elem['name']][0] -#change val power (add 1 BN) -current_power = int(val_power_list[val_power_index]['power']) -print("Current validator power is " + str(current_power)) -new_power = str(current_power + 1000000000) -print("New validator power is " + new_power) -val_power_list[val_power_index]['power'] = new_power -#get index of val power in app state (osmovaloper) (bech32_valoper) -last_val_power_list = read_test_gen['app_state']['staking']['last_validator_powers'] -#last_val_power_index = [i for i, elem in enumerate(last_val_power_list) if bech32_valoper in elem['address']][0] -last_val_power_index = [i for i, elem in enumerate(last_val_power_list) if 'osmovaloper1cyw4vw20el8e7ez8080md0r8psg25n0cq98a9n' in elem['address']][0] -val_power = int(read_test_gen['app_state']['staking']['last_validator_powers'][last_val_power_index]['power']) -print("Current validator power in second location is " + str(val_power)) -new_val_power = str(val_power + 1000000000) -print("New validator power in second location is " + new_val_power) -read_test_gen['app_state']['staking']['last_validator_powers'][last_val_power_index]['power'] = new_val_power - - -#update last_total_power (last total bonded across all validators, add 1BN) -last_total_power = int(read_test_gen['app_state']['staking']['last_total_power']) -print("Current last total power is " + str(last_total_power)) -new_last_total_power = str(last_total_power + 1000000000) -print("New last total power is " + new_last_total_power) -read_test_gen['app_state']['staking']['last_total_power'] = new_last_total_power - - -#update operator address amount (add 1 BN) -#find wallet index in bank balance -bank_balance_list = read_test_gen['app_state']['bank']['balances'] -op_amount_index = [i for i, elem in enumerate(bank_balance_list) if op_address in elem['address']][0] -#get uosmo index from wallet -op_wallet = read_test_gen['app_state']['bank']['balances'][op_amount_index]['coins'] -op_uosmo_index = [i for i, elem in enumerate(op_wallet) if 'uosmo' in elem['denom']][0] -#update uosmo amount -op_uosmo = int(op_wallet[op_uosmo_index]['amount']) -print("Current operator address uosmo balance is " + str(op_uosmo)) -new_op_uosmo = str(op_uosmo + 1000000000000000) -print("New operator address uosmo balance is " + new_op_uosmo) -op_wallet[op_uosmo_index]['amount'] = new_op_uosmo - - -#update total OSMO supply (add 2 BN) -#supply list (ibc, ion, osmo) -supply = read_test_gen['app_state']['bank']['supply'] - -#get index of osmo supply -osmo_index = [i for i, elem in enumerate(supply) if 'uosmo' in elem['denom']][0] - -#get osmo supply value -osmo_supply = supply[osmo_index]['amount'] -print("Current OSMO supply is " + osmo_supply) - -#update osmo supply to new total osmo value (add 2 Billion OSMO) -#subtract by however much module account is subtracted by -osmo_supply_new = int(osmo_supply) + 2000000000000000 - dist_offset_amt -print("New OSMO supply is " + str(osmo_supply_new)) -supply[osmo_index]['amount'] = str(osmo_supply_new) - - -#update bonded_tokens_pool module balance osmo1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3aq6l09 (add 1BN) -#get list of bank balances -bank_bal_list = read_test_gen['app_state']['bank']['balances'] -#get index of module account -module_acct_index = [i for i, elem in enumerate(bank_bal_list) if 'osmo1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3aq6l09' in elem['address']][0] -#get current value -module_denom_list = bank_bal_list[module_acct_index]['coins'] -osmo_bal_index = [i for i, elem in enumerate(module_denom_list) if 'uosmo' in elem['denom']][0] -osmo_bal = bank_bal_list[module_acct_index]['coins'][osmo_bal_index]['amount'] -print("Current bonded tokens pool module account balance is " + osmo_bal) -#increase by 1BN -new_osmo_bal = int(osmo_bal) + 1000000000000000 -print("New bonded tokens pool module account balance is " + str(new_osmo_bal)) -bank_bal_list[module_acct_index]['coins'][osmo_bal_index]['amount'] = str(new_osmo_bal) - - -#edit epoch params -#change epoch duration to 21600s -epochs_list = read_test_gen['app_state']['epochs']['epochs'][0] -duration_current = epochs_list['duration'] -print("Current epoch duration is " + duration_current) -#21600s for 6 hour epoch -#CAN MODIFY -new_duration = '21600s' -print("New epoch duration is " + new_duration) -epochs_list['duration'] = new_duration - -#change current_epoch_start_time -start_time_current = epochs_list['current_epoch_start_time'] -print("Current epoch start time is " + start_time_current) -#today = date.today() -now = datetime.now() -#date_format = now.strftime("%Y-%m-%d") -date_format = now.strftime("%Y-%m-%d"+"T"+"%H:%M:") -start_time_current_list = list(start_time_current) -start_time_current_list[:17] = date_format -start_time_new = ''.join(start_time_current_list) -epochs_list['current_epoch_start_time'] = start_time_new -print("New epoch start time is " + start_time_new) - - -#edit gov params -#change VotingPeriod -current_voting_period = read_test_gen['app_state']['gov']['voting_params']['voting_period'] -print("Current voting period is " + current_voting_period) -#180s for 3 minute voting period -#CAN MODIFY -new_voting_period = "180s" -print("New voting period is " + new_voting_period) -read_test_gen['app_state']['gov']['voting_params']['voting_period'] = new_voting_period - - -print("Please wait while file writes over itself, this may take 60 seconds or more") -#go back to begining of file, write over with new values -test_gen.seek(0) -json.dump(read_test_gen, test_gen) - -#delete remainder in case new data is shorter than old -test_gen.truncate() From 01dee57c4abc6cf7116156cd22bb5c04afe235a1 Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Thu, 30 Jun 2022 22:57:53 -0500 Subject: [PATCH 010/376] x/gamm: Add check to ensure JoinPoolNoSwap cannot be called with arbitrary denoms (#1930) * add denom equivalence check for input vs. expected * add test for new logic * refactor new logic and add more relevant error messages * update changelog * Revert "update changelog" This reverts commit fa33bf7733f9cac6ab8a2511af1f29d0f91d3e14. * Update changelog --- CHANGELOG.md | 2 ++ x/gamm/keeper/pool_service.go | 3 +++ x/gamm/keeper/pool_service_test.go | 12 ++++++++++++ 3 files changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 405f64acb73..318d638e2d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,6 +64,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#1539] Superfluid: Combine superfluid and staking query on querying delegation by delegator ### Bug Fixes + +* [1930](https://github.com/osmosis-labs/osmosis/pull/1930) Ensure you can't `JoinPoolNoSwap` tokens that are not in the pool * [1700](https://github.com/osmosis-labs/osmosis/pull/1700) Upgrade sdk fork with missing snapshot manager fix. * [1716](https://github.com/osmosis-labs/osmosis/pull/1716) Fix secondary over-LP shares bug with uneven swap amounts in `CalcJoinPoolShares`. * [1759](https://github.com/osmosis-labs/osmosis/pull/1759) Fix pagination filter in incentives query. diff --git a/x/gamm/keeper/pool_service.go b/x/gamm/keeper/pool_service.go index d8e82c3bc55..094eea0f4a5 100644 --- a/x/gamm/keeper/pool_service.go +++ b/x/gamm/keeper/pool_service.go @@ -203,6 +203,9 @@ func (k Keeper) JoinPoolNoSwap( if !(neededLpLiquidity.DenomsSubsetOf(tokenInMaxs) && tokenInMaxs.IsAllGTE(neededLpLiquidity)) { return sdkerrors.Wrapf(types.ErrLimitMaxAmount, "TokenInMaxs is less than the needed LP liquidity to this JoinPoolNoSwap,"+ " upperbound: %v, needed %v", tokenInMaxs, neededLpLiquidity) + } else if !(tokenInMaxs.DenomsSubsetOf(neededLpLiquidity)) { + return sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, "TokenInMaxs includes tokens that are not part of the target pool,"+ + " input tokens: %v, pool tokens %v", tokenInMaxs, neededLpLiquidity) } } diff --git a/x/gamm/keeper/pool_service_test.go b/x/gamm/keeper/pool_service_test.go index e556754314f..850faa886aa 100644 --- a/x/gamm/keeper/pool_service_test.go +++ b/x/gamm/keeper/pool_service_test.go @@ -316,6 +316,18 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { suite.Require().Equal("15000bar,15000foo", liquidity.String()) }, }, + { + fn: func(poolId uint64) { + keeper := suite.App.GAMMKeeper + // Test the "tokenInMaxs" with an additional invalid denom + // In this case, to get the 50 * OneShare amount of share token, the foo, bar token are expected to be provided as 5000 amounts. + // The test input has the correct amount for each, but also includes an incorrect denom that should cause an error + err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ + sdk.NewCoin("bar", sdk.NewInt(5000)), sdk.NewCoin("foo", sdk.NewInt(5000)), sdk.NewCoin("baz", sdk.NewInt(5000)), + }) + suite.Require().Error(err) + }, + }, } for _, test := range tests { From c0573d1e45ee18c0b5c1233823b3411ece8fbbec Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 1 Jul 2022 00:24:56 -0500 Subject: [PATCH 011/376] Add deadcode linter (#1934) --- .golangci.yml | 2 +- osmomath/math.go | 1 + tests/e2e/containers/config.go | 1 + x/gamm/pool-models/balancer/pool.go | 1 + x/gamm/pool-models/stableswap/amm.go | 5 +++++ x/lockup/keeper/export_test.go | 4 ---- x/lockup/keeper/utils.go | 8 -------- x/mint/simulation/genesis.go | 8 +------- x/tokenfactory/keeper/keeper.go | 10 ---------- x/tokenfactory/types/codec.go | 1 - 10 files changed, 10 insertions(+), 31 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 6f13fdeebb5..bbcae8a8715 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,7 +13,7 @@ linters: # - bodyclose <- needs go 1.18 support # - contextcheck <- needs go 1.18 support # - cyclop - # - deadcode <- re-enable in another pr + - deadcode - depguard # - dogsled <- disabled because we would like to participate in the iditerod # - dupl <- really just catches cli stub text diff --git a/osmomath/math.go b/osmomath/math.go index 87a65c3d1b3..390b84eece1 100644 --- a/osmomath/math.go +++ b/osmomath/math.go @@ -11,6 +11,7 @@ import ( var powPrecision, _ = sdk.NewDecFromStr("0.00000001") // Singletons. +//nolint:deadcode var zero sdk.Dec = sdk.ZeroDec() var ( diff --git a/tests/e2e/containers/config.go b/tests/e2e/containers/config.go index e25d765cce5..9b6fe0d4d2b 100644 --- a/tests/e2e/containers/config.go +++ b/tests/e2e/containers/config.go @@ -13,6 +13,7 @@ type ImageConfig struct { RelayerTag string } +//nolint:deadcode const ( // Current Git branch osmosis repo/version. It is meant to be built locally. // It is used when skipping upgrade by setting OSMOSIS_E2E_SKIP_UPGRADE to true). diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index a1da2389e1b..3fd277e7a8c 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -15,6 +15,7 @@ import ( "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) +//nolint:deadcode const ( errMsgFormatSharesAmountNotPositive = "shares amount must be positive, was %d" errMsgFormatTokenAmountNotPositive = "token amount must be positive, was %d" diff --git a/x/gamm/pool-models/stableswap/amm.go b/x/gamm/pool-models/stableswap/amm.go index 6193444faa6..ae79bd77bcf 100644 --- a/x/gamm/pool-models/stableswap/amm.go +++ b/x/gamm/pool-models/stableswap/amm.go @@ -15,6 +15,7 @@ var ( ) // solidly CFMM is xy(x^2 + y^2) = k +// nolint:deadcode func cfmmConstant(xReserve, yReserve sdk.Dec) sdk.Dec { xy := xReserve.Mul(yReserve) x2 := xReserve.Mul(xReserve) @@ -27,6 +28,7 @@ func cfmmConstant(xReserve, yReserve sdk.Dec) sdk.Dec { // outside of x and y (e.g. u = wz), and v is the sum // of their squares (e.g. v = w^2 + z^2). // When u = 1 and v = 0, this is equivalent to solidly's CFMM +// nolint:deadcode func cfmmConstantMulti(xReserve, yReserve, uReserve, vSumSquares sdk.Dec) sdk.Dec { xyu := xReserve.Mul(yReserve.Mul(uReserve)) x2 := xReserve.Mul(xReserve) @@ -159,6 +161,7 @@ func solveCfmm(xReserve, yReserve, yIn sdk.Dec) sdk.Dec { // how many units `a` of x do we get out. // So we solve the following expression for `a` // xyz(x^2 + y^2 + w) = (x - a)(y + b)z((x - a)^2 + (y + b)^2 + w) +// nolint:deadcode func solveCfmmMulti(xReserve, yReserve, wSumSquares, yIn sdk.Dec) sdk.Dec { if !yReserve.Add(yIn).IsPositive() { panic("invalid yReserve, yIn combo") @@ -271,6 +274,7 @@ var ( // solveCFMMBinarySearch searches the correct dx using binary search over constant K. // added for future extension +// nolint:deadcode func solveCFMMBinarySearch(constantFunction func(sdk.Dec, sdk.Dec) sdk.Dec) func(sdk.Dec, sdk.Dec, sdk.Dec) sdk.Dec { return func(xReserve, yReserve, yIn sdk.Dec) sdk.Dec { k := constantFunction(xReserve, yReserve) @@ -294,6 +298,7 @@ func solveCFMMBinarySearch(constantFunction func(sdk.Dec, sdk.Dec) sdk.Dec) func // solveCFMMBinarySearch searches the correct dx using binary search over constant K. // added for future extension +// nolint:deadcode func solveCFMMBinarySearchMulti(constantFunction func(sdk.Dec, sdk.Dec, sdk.Dec, sdk.Dec) sdk.Dec) func(sdk.Dec, sdk.Dec, sdk.Dec, sdk.Dec, sdk.Dec) sdk.Dec { return func(xReserve, yReserve, uReserve, wSumSquares, yIn sdk.Dec) sdk.Dec { k := constantFunction(xReserve, yReserve, uReserve, wSumSquares) diff --git a/x/lockup/keeper/export_test.go b/x/lockup/keeper/export_test.go index 97dfe9579cf..8c235e3381a 100644 --- a/x/lockup/keeper/export_test.go +++ b/x/lockup/keeper/export_test.go @@ -18,10 +18,6 @@ func (k Keeper) GetLockRefs(ctx sdk.Context, key []byte) []uint64 { return k.getLockRefs(ctx, key) } -func (k Keeper) SyntheticCoins(coins sdk.Coins, suffix string) sdk.Coins { - return syntheticCoins(coins, suffix) -} - func (k Keeper) GetCoinsFromLocks(locks []types.PeriodLock) sdk.Coins { return k.getCoinsFromLocks(locks) } diff --git a/x/lockup/keeper/utils.go b/x/lockup/keeper/utils.go index de294c9c312..e3ec5037d77 100644 --- a/x/lockup/keeper/utils.go +++ b/x/lockup/keeper/utils.go @@ -107,14 +107,6 @@ func syntheticLockRefKeys(lock types.PeriodLock, synthLock types.SyntheticLock) return refKeys, nil } -func syntheticCoins(coins sdk.Coins, suffix string) sdk.Coins { - syntheticCoins := sdk.Coins{} - for _, coin := range coins { - syntheticCoins = syntheticCoins.Add(sdk.NewCoin(coin.Denom+suffix, coin.Amount)) - } - return syntheticCoins -} - func combineLocks(pl1 []types.PeriodLock, pl2 []types.PeriodLock) []types.PeriodLock { return append(pl1, pl2...) } diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index f11118c7943..94dd75c1f70 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -16,16 +16,10 @@ import ( // Simulation parameter constants. const ( epochProvisionsKey = "genesis_epoch_provisions" - epochIdentifierKey = "epoch_identifier" reductionFactorKey = "reduction_factor" reductionPeriodInEpochsKey = "reduction_period_in_epochs" - stakingDistributionProportionKey = "staking_distribution_proportion" - poolIncentivesDistributionProportionKey = "pool_incentives_distribution_proportion" - developerRewardsDistributionProportionKey = "developer_rewards_distribution_proportion" - communityPoolDistributionProportionKey = "community_pool_distribution_proportion" - weightedDevRewardReceiversKey = "weighted_developer_rewards_receivers" - mintingRewardsDistributionStartEpochKey = "minting_rewards_distribution_start_epoch" + mintingRewardsDistributionStartEpochKey = "minting_rewards_distribution_start_epoch" epochIdentifier = "day" maxInt64 = int(^uint(0) >> 1) diff --git a/x/tokenfactory/keeper/keeper.go b/x/tokenfactory/keeper/keeper.go index 7b6d97ffc44..b4798b2d631 100644 --- a/x/tokenfactory/keeper/keeper.go +++ b/x/tokenfactory/keeper/keeper.go @@ -28,16 +28,6 @@ type ( } ) -func permContains(perms []string, perm string) bool { - for _, v := range perms { - if v == perm { - return true - } - } - - return false -} - // NewKeeper returns a new instance of the x/tokenfactory keeper func NewKeeper( cdc codec.Codec, diff --git a/x/tokenfactory/types/codec.go b/x/tokenfactory/types/codec.go index 6308a36fe5b..a4e11fad8ac 100644 --- a/x/tokenfactory/types/codec.go +++ b/x/tokenfactory/types/codec.go @@ -30,6 +30,5 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { } var ( - amino = codec.NewLegacyAmino() ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) ) From 2007babdee01e9bb7743ccadeff097cdab9b7236 Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Fri, 1 Jul 2022 16:09:09 +0900 Subject: [PATCH 012/376] Generalize gamm Inverse relationship test , add Inverse relationship test for stableswap (#1456) * Generalize inverse testing from balancer package to pool-models * Add stableswap inverse testing * fixed failing lint test * Update x/gamm/pool-models/internal/test_helpers/test_helpers.go Co-authored-by: Roman * Add test * Address Bez's review * Fix test * Update x/gamm/pool-models/internal/test_helpers/test_helpers.go Co-authored-by: Aleksandr Bezobchuk Co-authored-by: Xiangan He <76530366+xBalbinus@users.noreply.github.com> Co-authored-by: Xiangan He Co-authored-by: Roman Co-authored-by: Aleksandr Bezobchuk --- app/apptesting/test_suite.go | 13 +++ x/gamm/pool-models/balancer/amm_test.go | 5 + x/gamm/pool-models/balancer/pool_test.go | 21 +--- .../internal/cfmm_common/lp_test.go | 2 - .../internal/test_helpers/test_helpers.go | 63 ++++++++++ x/gamm/pool-models/stableswap/amm_test.go | 109 +++++++++++++++++- x/gamm/pool-models/stableswap/msgs.go | 2 +- .../pool-models/stableswap/stableswap_pool.go | 4 +- x/gamm/pool-models/stableswap/util_test.go | 21 ++++ 9 files changed, 215 insertions(+), 25 deletions(-) create mode 100644 x/gamm/pool-models/internal/test_helpers/test_helpers.go create mode 100644 x/gamm/pool-models/stableswap/util_test.go diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index 8ed0543459d..a10e4d62039 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/store/rootmulti" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" @@ -18,7 +19,10 @@ import ( "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" + dbm "github.com/tendermint/tm-db" "github.com/osmosis-labs/osmosis/v7/app" "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" @@ -47,6 +51,15 @@ func (s *KeeperTestHelper) Setup() { s.TestAccs = CreateRandomAccounts(3) } +func (s *KeeperTestHelper) CreateTestContext() sdk.Context { + db := dbm.NewMemDB() + logger := log.NewNopLogger() + + ms := rootmulti.NewStore(db, logger) + + return sdk.NewContext(ms, tmtypes.Header{}, false, logger) +} + func (s *KeeperTestHelper) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) { err := simapp.FundAccount(s.App.BankKeeper, s.Ctx, acc, amounts) s.Require().NoError(err) diff --git a/x/gamm/pool-models/balancer/amm_test.go b/x/gamm/pool-models/balancer/amm_test.go index ad26cc556f8..707da15924a 100644 --- a/x/gamm/pool-models/balancer/amm_test.go +++ b/x/gamm/pool-models/balancer/amm_test.go @@ -7,8 +7,13 @@ import ( "github.com/stretchr/testify/require" "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/test_helpers" ) +type BalancerTestSuite struct { + test_helpers.CfmmCommonTestSuite +} + func TestBalancerPoolParams(t *testing.T) { // Tests that creating a pool with the given pair of swapfee and exit fee // errors or succeeds as intended. Furthermore, it checks that diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go index 677c63dbe69..d4b3133672f 100644 --- a/x/gamm/pool-models/balancer/pool_test.go +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -504,7 +504,7 @@ func TestGetPoolAssetsByDenom(t *testing.T) { // TestCalculateAmountOutAndIn_InverseRelationship tests that the same amount of token is guaranteed upon // sequential operation of CalcInAmtGivenOut and CalcOutAmtGivenIn. -func TestCalculateAmountOutAndIn_InverseRelationship(t *testing.T) { +func (suite *BalancerTestSuite) TestBalancerCalculateAmountOutAndIn_InverseRelationship(t *testing.T) { type testcase struct { denomOut string initialPoolOut int64 @@ -584,7 +584,7 @@ func TestCalculateAmountOutAndIn_InverseRelationship(t *testing.T) { for _, tc := range testcases { for _, swapFee := range swapFeeCases { t.Run(getTestCaseName(tc, swapFee), func(t *testing.T) { - ctx := createTestContext(t) + ctx := suite.CreateTestContext() poolAssetOut := balancer.PoolAsset{ Token: sdk.NewInt64Coin(tc.denomOut, tc.initialPoolOut), @@ -605,24 +605,9 @@ func TestCalculateAmountOutAndIn_InverseRelationship(t *testing.T) { pool := createTestPool(t, swapFeeDec, exitFeeDec, poolAssetOut, poolAssetIn) require.NotNil(t, pool) - initialOut := sdk.NewInt64Coin(poolAssetOut.Token.Denom, tc.initialCalcOut) - initialOutCoins := sdk.NewCoins(initialOut) - sut := func() { - actualTokenIn, err := pool.CalcInAmtGivenOut(ctx, initialOutCoins, poolAssetIn.Token.Denom, swapFeeDec) - require.NoError(t, err) - - inverseTokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(actualTokenIn), poolAssetOut.Token.Denom, swapFeeDec) - require.NoError(t, err) - - require.Equal(t, initialOut.Denom, inverseTokenOut.Denom) - - expected := initialOut.Amount.ToDec() - actual := inverseTokenOut.Amount.ToDec() + suite.TestCalculateAmountOutAndIn_InverseRelationship(ctx, pool, poolAssetIn.Token.Denom, poolAssetOut.Token.Denom, tc.initialCalcOut, swapFeeDec) - // allow a rounding error of up to 1 for this relation - tol := sdk.NewDec(1) - require.True(osmoutils.DecApproxEq(t, expected, actual, tol)) } balancerPool, ok := pool.(*balancer.Pool) diff --git a/x/gamm/pool-models/internal/cfmm_common/lp_test.go b/x/gamm/pool-models/internal/cfmm_common/lp_test.go index be9cd2ed3ae..abb62f267c8 100644 --- a/x/gamm/pool-models/internal/cfmm_common/lp_test.go +++ b/x/gamm/pool-models/internal/cfmm_common/lp_test.go @@ -46,7 +46,6 @@ func TestCalcExitPool(t *testing.T) { stableswap.PoolParams{ExitFee: sdk.ZeroDec()}, twoStablePoolAssets, "", - time.Now(), ) require.NoError(t, err) @@ -64,7 +63,6 @@ func TestCalcExitPool(t *testing.T) { stableswap.PoolParams{ExitFee: sdk.MustNewDecFromStr("0.0001")}, twoStablePoolAssets, "", - time.Now(), ) require.NoError(t, err) diff --git a/x/gamm/pool-models/internal/test_helpers/test_helpers.go b/x/gamm/pool-models/internal/test_helpers/test_helpers.go new file mode 100644 index 00000000000..ba1f7dad435 --- /dev/null +++ b/x/gamm/pool-models/internal/test_helpers/test_helpers.go @@ -0,0 +1,63 @@ +package test_helpers + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/store/rootmulti" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" + "github.com/tendermint/tendermint/libs/log" + tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" + dbm "github.com/tendermint/tm-db" + + "github.com/osmosis-labs/osmosis/v7/osmoutils" + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +// CfmmCommonTestSuite is the common test suite struct of Constant Function Market Maker, +// that pool-models can inherit from. +type CfmmCommonTestSuite struct { + suite.Suite +} + +func (suite *CfmmCommonTestSuite) CreateTestContext() sdk.Context { + db := dbm.NewMemDB() + logger := log.NewNopLogger() + + ms := rootmulti.NewStore(db, logger) + + return sdk.NewContext(ms, tmtypes.Header{}, false, logger) +} + +func (suite *CfmmCommonTestSuite) TestCalculateAmountOutAndIn_InverseRelationship( + ctx sdk.Context, + pool types.PoolI, + assetInDenom string, + assetOutDenom string, + initialCalcOut int64, + swapFee sdk.Dec, +) { + initialOut := sdk.NewInt64Coin(assetOutDenom, initialCalcOut) + initialOutCoins := sdk.NewCoins(initialOut) + + actualTokenIn, err := pool.CalcInAmtGivenOut(ctx, initialOutCoins, assetInDenom, swapFee) + suite.Require().NoError(err) + + inverseTokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(actualTokenIn), assetOutDenom, swapFee) + suite.Require().NoError(err) + + suite.Require().Equal(initialOut.Denom, inverseTokenOut.Denom) + + expected := initialOut.Amount.ToDec() + actual := inverseTokenOut.Amount.ToDec() + + // allow a rounding error of up to 1 for this relation + tol := sdk.NewDec(1) + _, approxEqual, _, _, _ := osmoutils.DecApproxEq(suite.T(), expected, actual, tol) + suite.Require().True(approxEqual) +} + +func TestCfmmCommonTestSuite(t *testing.T) { + t.Parallel() + suite.Run(t, new(CfmmCommonTestSuite)) +} diff --git a/x/gamm/pool-models/stableswap/amm_test.go b/x/gamm/pool-models/stableswap/amm_test.go index 2283f4117ad..881de9fcc41 100644 --- a/x/gamm/pool-models/stableswap/amm_test.go +++ b/x/gamm/pool-models/stableswap/amm_test.go @@ -6,8 +6,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/test_helpers" ) +type StableSwapTestSuite struct { + test_helpers.CfmmCommonTestSuite +} + // Replace with https://github.com/cosmos/cosmos-sdk/blob/master/types/decimal.go#L892-L895 // once our SDK branch is up to date with it func decApproxEq(t *testing.T, exp sdk.Dec, actual sdk.Dec, errTolerance sdk.Dec) { @@ -45,7 +51,7 @@ func TestCFMMInvariantTwoAssets(t *testing.T) { // using two-asset cfmm k0 := cfmmConstant(test.xReserve, test.yReserve) xOut := solveCfmm(test.xReserve, test.yReserve, test.yIn) - fmt.Println("xOut", xOut) + k1 := cfmmConstant(test.xReserve.Sub(xOut), test.yReserve.Add(test.yIn)) decApproxEq(t, k0, k1, kErrTolerance) @@ -100,3 +106,104 @@ func TestCFMMInvariantMultiAssets(t *testing.T) { decApproxEq(t, k2, k3, kErrTolerance) } } + +func (suite *StableSwapTestSuite) Test_StableSwap_CalculateAmountOutAndIn_InverseRelationship(t *testing.T) { + type testcase struct { + denomOut string + initialPoolOut int64 + initialWeightOut int64 + initialCalcOut int64 + + denomIn string + initialPoolIn int64 + initialWeightIn int64 + } + + // For every test case in testcases, apply a swap fee in swapFeeCases. + testcases := []testcase{ + { + denomOut: "uosmo", + initialPoolOut: 1_000_000_000_000, + initialWeightOut: 100, + initialCalcOut: 100, + + denomIn: "ion", + initialPoolIn: 1_000_000_000_000, + initialWeightIn: 100, + }, + { + denomOut: "uosmo", + initialPoolOut: 1_000, + initialWeightOut: 100, + initialCalcOut: 100, + + denomIn: "ion", + initialPoolIn: 1_000_000, + initialWeightIn: 100, + }, + { + denomOut: "uosmo", + initialPoolOut: 1_000, + initialWeightOut: 100, + initialCalcOut: 100, + + denomIn: "ion", + initialPoolIn: 1_000_000, + initialWeightIn: 100, + }, + { + denomOut: "uosmo", + initialPoolOut: 1_000, + initialWeightOut: 200, + initialCalcOut: 100, + + denomIn: "ion", + initialPoolIn: 1_000_000, + initialWeightIn: 50, + }, + { + denomOut: "uosmo", + initialPoolOut: 1_000_000, + initialWeightOut: 200, + initialCalcOut: 100000, + + denomIn: "ion", + initialPoolIn: 1_000_000_000, + initialWeightIn: 50, + }, + } + + swapFeeCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} + + getTestCaseName := func(tc testcase, swapFeeCase string) string { + return fmt.Sprintf("tokenOutInitial: %d, tokenInInitial: %d, initialOut: %d, swapFee: %s", + tc.initialPoolOut, + tc.initialPoolIn, + tc.initialCalcOut, + swapFeeCase, + ) + } + + for _, tc := range testcases { + for _, swapFee := range swapFeeCases { + t.Run(getTestCaseName(tc, swapFee), func(t *testing.T) { + ctx := suite.CreateTestContext() + + poolLiquidityIn := sdk.NewInt64Coin(tc.denomOut, tc.initialPoolOut) + poolLiquidityOut := sdk.NewInt64Coin(tc.denomIn, tc.initialPoolIn) + poolLiquidity := sdk.NewCoins(poolLiquidityIn, poolLiquidityOut) + + swapFeeDec, err := sdk.NewDecFromStr(swapFee) + require.NoError(t, err) + + exitFeeDec, err := sdk.NewDecFromStr("0") + require.NoError(t, err) + + pool := createTestPool(t, poolLiquidity, swapFeeDec, exitFeeDec) + require.NotNil(t, pool) + + suite.TestCalculateAmountOutAndIn_InverseRelationship(ctx, pool, poolLiquidityIn.Denom, poolLiquidityOut.Denom, tc.initialCalcOut, swapFeeDec) + }) + } + } +} diff --git a/x/gamm/pool-models/stableswap/msgs.go b/x/gamm/pool-models/stableswap/msgs.go index 20c25466d79..4661693164d 100644 --- a/x/gamm/pool-models/stableswap/msgs.go +++ b/x/gamm/pool-models/stableswap/msgs.go @@ -91,7 +91,7 @@ func (msg MsgCreateStableswapPool) InitialLiquidity() sdk.Coins { } func (msg MsgCreateStableswapPool) CreatePool(ctx sdk.Context, poolId uint64) (types.PoolI, error) { - stableswapPool, err := NewStableswapPool(poolId, *msg.PoolParams, msg.InitialPoolLiquidity, msg.FuturePoolGovernor, ctx.BlockTime()) + stableswapPool, err := NewStableswapPool(poolId, *msg.PoolParams, msg.InitialPoolLiquidity, msg.FuturePoolGovernor) if err != nil { return nil, err } diff --git a/x/gamm/pool-models/stableswap/stableswap_pool.go b/x/gamm/pool-models/stableswap/stableswap_pool.go index 238e7a03f1b..d7c6f31adf6 100644 --- a/x/gamm/pool-models/stableswap/stableswap_pool.go +++ b/x/gamm/pool-models/stableswap/stableswap_pool.go @@ -1,8 +1,6 @@ package stableswap import ( - "time" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/osmosis-labs/osmosis/v7/x/gamm/types" @@ -15,7 +13,7 @@ var _ types.PoolI = &Pool{} // * len(initialLiquidity) = 2 // * FutureGovernor is valid // * poolID doesn't already exist -func NewStableswapPool(poolId uint64, stableswapPoolParams PoolParams, initialLiquidity sdk.Coins, futureGovernor string, blockTime time.Time) (Pool, error) { +func NewStableswapPool(poolId uint64, stableswapPoolParams PoolParams, initialLiquidity sdk.Coins, futureGovernor string) (Pool, error) { pool := Pool{ Address: types.NewPoolAddress(poolId).String(), Id: poolId, diff --git a/x/gamm/pool-models/stableswap/util_test.go b/x/gamm/pool-models/stableswap/util_test.go new file mode 100644 index 00000000000..d1dbaa82702 --- /dev/null +++ b/x/gamm/pool-models/stableswap/util_test.go @@ -0,0 +1,21 @@ +package stableswap + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +func createTestPool(t *testing.T, poolLiquidity sdk.Coins, swapFee, exitFee sdk.Dec) types.PoolI { + pool, err := NewStableswapPool(1, PoolParams{ + SwapFee: swapFee, + ExitFee: exitFee, + }, poolLiquidity, "") + + require.NoError(t, err) + + return &pool +} From fc11147cae413504c23fa378561c81007e5995f6 Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Fri, 1 Jul 2022 15:05:15 -0500 Subject: [PATCH 013/376] x/gamm: Delete the height < v10forkheight { use broken code } check (#1941) * remove height gating from JoinPool * remove corresponding broken functions --- x/gamm/pool-models/balancer/pool.go | 58 ------------------- x/gamm/pool-models/internal/cfmm_common/lp.go | 41 ------------- 2 files changed, 99 deletions(-) diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index 3fd277e7a8c..449213fe3b5 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -661,61 +661,6 @@ func (p *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (n return numShares, nil } -func (p *Pool) calcJoinPoolSharesBroken(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) { - poolAssets := p.GetAllPoolAssets() - poolAssetsByDenom := make(map[string]PoolAsset) - for _, poolAsset := range poolAssets { - poolAssetsByDenom[poolAsset.Token.Denom] = poolAsset - } - - totalShares := p.GetTotalShares() - - if tokensIn.Len() == 1 { - numShares, err = p.calcSingleAssetJoin(tokensIn[0], swapFee, poolAssetsByDenom[tokensIn[0].Denom], totalShares) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - - newLiquidity = tokensIn - - return numShares, newLiquidity, nil - } else if tokensIn.Len() != p.NumAssets() { - return sdk.ZeroInt(), sdk.NewCoins(), errors.New("balancer pool only supports LP'ing with one asset or all assets in pool") - } - - // Add all exact coins we can (no swap). ctx arg doesn't matter for Balancer. - numShares, remCoins, err := cfmm_common.MaximalExactRatioJoinBroken(p, sdk.Context{}, tokensIn) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - - // update liquidity for accurate calcSingleAssetJoin calculation - newLiquidity = tokensIn.Sub(remCoins) - for _, coin := range newLiquidity { - poolAsset := poolAssetsByDenom[coin.Denom] - poolAsset.Token.Amount = poolAssetsByDenom[coin.Denom].Token.Amount.Add(coin.Amount) - poolAssetsByDenom[coin.Denom] = poolAsset - } - - totalShares = totalShares.Add(numShares) - - // If there are coins that couldn't be perfectly joined, do single asset joins - // for each of them. - if !remCoins.Empty() { - for _, coin := range remCoins { - newShares, err := p.calcSingleAssetJoin(coin, swapFee, poolAssetsByDenom[coin.Denom], totalShares) - if err != nil { - return sdk.ZeroInt(), sdk.NewCoins(), err - } - - newLiquidity = newLiquidity.Add(coin) - numShares = numShares.Add(newShares) - } - } - - return numShares, newLiquidity, nil -} - // CalcJoinPoolShares calculates the number of shares created to join pool with the provided amount of `tokenIn`. // The input tokens must either be: // - a single token @@ -724,9 +669,6 @@ func (p *Pool) calcJoinPoolSharesBroken(ctx sdk.Context, tokensIn sdk.Coins, swa // It returns the number of shares created, the amount of coins actually joined into the pool // (in case of not being able to fully join), or an error. func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { - if ctx.BlockHeight() < v10Fork { - return p.calcJoinPoolSharesBroken(ctx, tokensIn, swapFee) - } // 1) Get pool current liquidity + and token weights // 2) If single token provided, do single asset join and exit. // 3) If multi-asset join, first do as much of a join as we can with no swaps. diff --git a/x/gamm/pool-models/internal/cfmm_common/lp.go b/x/gamm/pool-models/internal/cfmm_common/lp.go index e4e67267cf2..ffcd9559f5e 100644 --- a/x/gamm/pool-models/internal/cfmm_common/lp.go +++ b/x/gamm/pool-models/internal/cfmm_common/lp.go @@ -50,47 +50,6 @@ func CalcExitPool(ctx sdk.Context, pool types.PoolI, exitingShares sdk.Int, exit return exitedCoins, nil } -func MaximalExactRatioJoinBroken(p types.PoolI, ctx sdk.Context, tokensIn sdk.Coins) (numShares sdk.Int, remCoins sdk.Coins, err error) { - coinShareRatios := make([]sdk.Dec, len(tokensIn)) - minShareRatio := sdk.MaxSortableDec - maxShareRatio := sdk.ZeroDec() - poolLiquidity := p.GetTotalPoolLiquidity(ctx) - totalShares := p.GetTotalShares() - for i, coin := range tokensIn { - shareRatio := coin.Amount.ToDec().QuoInt(poolLiquidity.AmountOfNoDenomValidation(coin.Denom)) - if shareRatio.LT(minShareRatio) { - minShareRatio = shareRatio - } - if shareRatio.GT(maxShareRatio) { - maxShareRatio = shareRatio - } - coinShareRatios[i] = shareRatio - } - if minShareRatio.Equal(sdk.MaxSortableDec) { - return numShares, remCoins, errors.New("unexpected error in MaximalExactRatioJoin") - } - remCoins = sdk.Coins{} - numShares = minShareRatio.MulInt(totalShares).TruncateInt() - // if we have multiple share values, calculate remainingCoins - if !minShareRatio.Equal(maxShareRatio) { - // we have to calculate remCoins - for i, coin := range tokensIn { - // if coinShareRatios[i] == minShareRatio, no remainder - if coinShareRatios[i].Equal(minShareRatio) { - continue - } - - usedAmount := minShareRatio.MulInt(coin.Amount).Ceil().TruncateInt() - newAmt := coin.Amount.Sub(usedAmount) - // if newAmt is non-zero, add to RemCoins. (It could be zero due to rounding) - if !newAmt.IsZero() { - remCoins = remCoins.Add(sdk.Coin{Denom: coin.Denom, Amount: newAmt}) - } - } - } - return numShares, remCoins, nil -} - // MaximalExactRatioJoin calculates the maximal amount of tokens that can be joined whilst maintaining pool asset's ratio // returning the number of shares that'd be and how many coins would be left over. // e.g) suppose we have a pool of 10 foo tokens and 10 bar tokens, with the total amount of 100 shares. From 99304f2b607f0323f9c7b025d2a4613473392d45 Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Sat, 2 Jul 2022 05:11:11 +0900 Subject: [PATCH 014/376] x/lock: Fix `ExtendLockup` API (#1937) * Fix extendlock api * Apply suggestions from code review * Add changelog Co-authored-by: Dev Ojha Co-authored-by: Dev Ojha --- CHANGELOG.md | 1 + x/lockup/keeper/lock.go | 33 +++++++++++++++++++++------------ x/lockup/keeper/lock_test.go | 6 +++--- x/lockup/keeper/msg_server.go | 13 +++++++------ 4 files changed, 32 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 318d638e2d6..5af33dbbffe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 #### Golang API breaks +* [#1937](https://github.com/osmosis-labs/osmosis/pull/1937) Change `lockupKeeper.ExtendLock` to take in lockID instead of the direct lock struct. * [#1893](https://github.com/osmosis-labs/osmosis/pull/1893) Change `EpochsKeeper.SetEpochInfo` to `AddEpochInfo`, which has more safety checks with it. (Makes it suitable to be called within upgrades) * [#1671](https://github.com/osmosis-labs/osmosis/pull/1671) Remove methods that constitute AppModuleSimulation APIs for several modules' AppModules, which implemented no-ops * [#1671](https://github.com/osmosis-labs/osmosis/pull/1671) Add hourly epochs to `x/epochs` DefaultGenesis. diff --git a/x/lockup/keeper/lock.go b/x/lockup/keeper/lock.go index 052a09e8905..0331912dea8 100644 --- a/x/lockup/keeper/lock.go +++ b/x/lockup/keeper/lock.go @@ -374,7 +374,16 @@ func (k Keeper) unlockMaturedLockInternalLogic(ctx sdk.Context, lock types.Perio // 2. Locks that are unlokcing are not allowed to change duration. // 3. Locks that have synthetic lockup are not allowed to change. // 4. Provided duration should be greater than the original duration. -func (k Keeper) ExtendLockup(ctx sdk.Context, lock types.PeriodLock, newDuration time.Duration) error { +func (k Keeper) ExtendLockup(ctx sdk.Context, lockID uint64, owner sdk.AccAddress, newDuration time.Duration) error { + lock, err := k.GetLockByID(ctx, lockID) + if err != nil { + return err + } + + if lock.GetOwner() != owner.String() { + return types.ErrNotLockOwner + } + if lock.IsUnlocking() { return fmt.Errorf("cannot edit unlocking lockup for lock %d", lock.ID) } @@ -384,10 +393,15 @@ func (k Keeper) ExtendLockup(ctx sdk.Context, lock types.PeriodLock, newDuration return fmt.Errorf("cannot edit lockup with synthetic lock %d", lock.ID) } - oldLock := lock + // completely delete existing lock refs + err = k.deleteLockRefs(ctx, unlockingPrefix(lock.IsUnlocking()), *lock) + if err != nil { + return err + } + oldDuration := lock.GetDuration() if newDuration != 0 { - if newDuration <= lock.Duration { + if newDuration <= oldDuration { return fmt.Errorf("new duration should be greater than the original") } @@ -400,25 +414,20 @@ func (k Keeper) ExtendLockup(ctx sdk.Context, lock types.PeriodLock, newDuration lock.Duration = newDuration } - // update lockup - err := k.deleteLockRefs(ctx, unlockingPrefix(oldLock.IsUnlocking()), oldLock) - if err != nil { - return err - } - - err = k.addLockRefs(ctx, lock) + // add lock refs with the new duration + err = k.addLockRefs(ctx, *lock) if err != nil { return err } - err = k.setLock(ctx, lock) + err = k.setLock(ctx, *lock) if err != nil { return err } k.hooks.OnLockupExtend(ctx, lock.GetID(), - oldLock.GetDuration(), + oldDuration, lock.GetDuration(), ) diff --git a/x/lockup/keeper/lock_test.go b/x/lockup/keeper/lock_test.go index 5afecbd678e..5dde289529e 100644 --- a/x/lockup/keeper/lock_test.go +++ b/x/lockup/keeper/lock_test.go @@ -666,14 +666,14 @@ func (suite *KeeperTestSuite) TestEditLockup() { lock, _ := suite.App.LockupKeeper.GetLockByID(suite.Ctx, 1) // duration decrease should fail - err = suite.App.LockupKeeper.ExtendLockup(suite.Ctx, *lock, time.Second/2) + err = suite.App.LockupKeeper.ExtendLockup(suite.Ctx, lock.ID, addr, time.Second/2) suite.Require().Error(err) // extending lock with same duration should fail - err = suite.App.LockupKeeper.ExtendLockup(suite.Ctx, *lock, time.Second) + err = suite.App.LockupKeeper.ExtendLockup(suite.Ctx, lock.ID, addr, time.Second) suite.Require().Error(err) // duration increase should success - err = suite.App.LockupKeeper.ExtendLockup(suite.Ctx, *lock, time.Second*2) + err = suite.App.LockupKeeper.ExtendLockup(suite.Ctx, lock.ID, addr, time.Second*2) suite.Require().NoError(err) // check queries diff --git a/x/lockup/keeper/msg_server.go b/x/lockup/keeper/msg_server.go index 725570bad6c..ce123cff367 100644 --- a/x/lockup/keeper/msg_server.go +++ b/x/lockup/keeper/msg_server.go @@ -156,18 +156,19 @@ func createBeginUnlockEvent(lock *types.PeriodLock) sdk.Event { func (server msgServer) ExtendLockup(goCtx context.Context, msg *types.MsgExtendLockup) (*types.MsgExtendLockupResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - lock, err := server.keeper.GetLockByID(ctx, msg.ID) + owner, err := sdk.AccAddressFromBech32(msg.Owner) if err != nil { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, err.Error()) + return nil, err } - if msg.Owner != lock.Owner { - return nil, sdkerrors.Wrapf(types.ErrNotLockOwner, fmt.Sprintf("msg sender (%s) and lock owner (%s) does not match", msg.Owner, lock.Owner)) + err = server.keeper.ExtendLockup(ctx, msg.ID, owner, msg.Duration) + if err != nil { + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, err.Error()) } - err = server.keeper.ExtendLockup(ctx, *lock, msg.Duration) + lock, err := server.keeper.GetLockByID(ctx, msg.ID) if err != nil { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, err.Error()) + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) } ctx.EventManager().EmitEvents(sdk.Events{ From b33920abbd1cd152b08114117f7b45a471969888 Mon Sep 17 00:00:00 2001 From: Roman Date: Fri, 1 Jul 2022 16:34:41 -0400 Subject: [PATCH 015/376] chore: x/mint genesis - audit, clean up and tests (#1872) * chore: audit, clean up and tests for mint genesis * remove unused integration_test.go * restore check for account existence in InitGenesis * unit test CreateDeveloperVestingModuleAccount * table-driven tests for SetInitialSupplyOffsetDuringMigration * TestMintInitGenesis * reduce suite verbosity in TestMintInitGenesis * refactor TestSetInitialSupplyOffsetDuringMigration with setupDeveloperAccountTestcase * refactor TestCreateDeveloperVestingModuleAccount with setupDeveloperAccountTestcase * refactor TestMintExportGenesis * clean up * lint errors * remove height gated assertions; move module account creation test to TestMintInitGenesis * Update x/mint/keeper/genesis_test.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update x/mint/keeper/genesis_test.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update x/mint/keeper/keeper.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * address Matt's comment about supply offset * Apply suggestions from code review Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * remove init genesis keepers * GetModuleAccount comment * Update x/mint/keeper/genesis.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> --- app/upgrades/v7/upgrades.go | 5 +- x/mint/keeper/export_test.go | 11 ++ x/mint/keeper/genesis.go | 36 ++++-- x/mint/keeper/genesis_test.go | 187 +++++++++++++++++++++++++++--- x/mint/keeper/hooks_test.go | 8 -- x/mint/keeper/integration_test.go | 21 ---- x/mint/keeper/keeper.go | 46 ++++++-- x/mint/keeper/keeper_test.go | 121 +++++++++++++++++++ x/mint/module.go | 2 +- x/mint/module_test.go | 29 ----- 10 files changed, 374 insertions(+), 92 deletions(-) create mode 100644 x/mint/keeper/export_test.go delete mode 100644 x/mint/keeper/integration_test.go delete mode 100644 x/mint/module_test.go diff --git a/app/upgrades/v7/upgrades.go b/app/upgrades/v7/upgrades.go index 9bf662f1a02..c07ac041470 100644 --- a/app/upgrades/v7/upgrades.go +++ b/app/upgrades/v7/upgrades.go @@ -10,7 +10,6 @@ import ( "github.com/osmosis-labs/osmosis/v7/app/keepers" "github.com/osmosis-labs/osmosis/v7/app/upgrades" lockupkeeper "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - mintkeeper "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" ) @@ -56,7 +55,9 @@ func CreateUpgradeHandler( keepers.SuperfluidKeeper.AddNewSuperfluidAsset(ctx, superfluidAsset) // Set the supply offset from the developer vesting account - mintkeeper.SetInitialSupplyOffsetDuringMigration(ctx, *keepers.MintKeeper) + if err := keepers.MintKeeper.SetInitialSupplyOffsetDuringMigration(ctx); err != nil { + panic(err) + } return newVM, err } diff --git a/x/mint/keeper/export_test.go b/x/mint/keeper/export_test.go new file mode 100644 index 00000000000..728a8bcc249 --- /dev/null +++ b/x/mint/keeper/export_test.go @@ -0,0 +1,11 @@ +package keeper + +const ( + DeveloperVestingAmount = developerVestingAmount +) + +var ( + ErrAmountCannotBeNilOrZero = errAmountCannotBeNilOrZero + ErrDevVestingModuleAccountAlreadyCreated = errDevVestingModuleAccountAlreadyCreated + ErrDevVestingModuleAccountNotCreated = errDevVestingModuleAccountNotCreated +) diff --git a/x/mint/keeper/genesis.go b/x/mint/keeper/genesis.go index b794a64c0fc..5633e9fcadf 100644 --- a/x/mint/keeper/genesis.go +++ b/x/mint/keeper/genesis.go @@ -6,17 +6,32 @@ import ( "github.com/osmosis-labs/osmosis/v7/x/mint/types" ) +const developerVestingAmount = 225_000_000_000_000 + // InitGenesis new mint genesis. -func (k Keeper) InitGenesis(ctx sdk.Context, ak types.AccountKeeper, bk types.BankKeeper, data *types.GenesisState) { +func (k Keeper) InitGenesis(ctx sdk.Context, data *types.GenesisState) { + if data == nil { + panic("nil mint genesis state") + } + data.Minter.EpochProvisions = data.Params.GenesisEpochProvisions k.SetMinter(ctx, data.Minter) k.SetParams(ctx, data.Params) - if !ak.HasAccount(ctx, ak.GetModuleAddress(types.ModuleName)) { - ak.GetModuleAccount(ctx, types.ModuleName) - totalDeveloperVestingCoins := sdk.NewCoin(data.Params.MintDenom, sdk.NewInt(225_000_000_000_000)) - k.CreateDeveloperVestingModuleAccount(ctx, totalDeveloperVestingCoins) - bk.AddSupplyOffset(ctx, data.Params.MintDenom, sdk.NewInt(225_000_000_000_000).Neg()) + // The call to GetModuleAccount creates a module account if it does not exist. + k.accountKeeper.GetModuleAccount(ctx, types.ModuleName) + + // The account should be exported in the ExportGenesis of the + // x/auth SDK module. Therefore, we check for existence here + // to avoid overwriting pre-existing genesis account data. + if !k.accountKeeper.HasAccount(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) { + totalDeveloperVestingCoins := sdk.NewCoin(data.Params.MintDenom, sdk.NewInt(developerVestingAmount)) + + if err := k.CreateDeveloperVestingModuleAccount(ctx, totalDeveloperVestingCoins); err != nil { + panic(err) + } + + k.bankKeeper.AddSupplyOffset(ctx, data.Params.MintDenom, sdk.NewInt(developerVestingAmount).Neg()) } k.SetLastReductionEpochNum(ctx, data.ReductionStartedEpoch) @@ -26,6 +41,11 @@ func (k Keeper) InitGenesis(ctx sdk.Context, ak types.AccountKeeper, bk types.Ba func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { minter := k.GetMinter(ctx) params := k.GetParams(ctx) - lastReductionEpoch := k.GetLastReductionEpochNum(ctx) - return types.NewGenesisState(minter, params, lastReductionEpoch) + + if params.WeightedDeveloperRewardsReceivers == nil { + params.WeightedDeveloperRewardsReceivers = make([]types.WeightedAddress, 0) + } + + lastHalvenEpoch := k.GetLastReductionEpochNum(ctx) + return types.NewGenesisState(minter, params, lastHalvenEpoch) } diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index 44b79563e11..7aa8ddcf01f 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -4,26 +4,183 @@ import ( "testing" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - simapp "github.com/osmosis-labs/osmosis/v7/app" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/stretchr/testify/suite" + "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" "github.com/osmosis-labs/osmosis/v7/x/mint/types" ) -func TestMintInitGenesis(t *testing.T) { - app := simapp.Setup(false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{}) +var customGenesis = types.NewGenesisState( + types.NewMinter(sdk.ZeroDec()), + types.NewParams( + "uosmo", // denom + sdk.NewDec(200), // epoch provisions + "year", // epoch identifier + sdk.NewDecWithPrec(5, 1), // reduction factor + 5, // reduction perion in epochs + types.DistributionProportions{ + Staking: sdk.NewDecWithPrec(25, 2), + PoolIncentives: sdk.NewDecWithPrec(25, 2), + DeveloperRewards: sdk.NewDecWithPrec(25, 2), + CommunityPool: sdk.NewDecWithPrec(25, 2), + }, + []types.WeightedAddress{ + { + Address: "osmo14kjcwdwcqsujkdt8n5qwpd8x8ty2rys5rjrdjj", + Weight: sdk.NewDecWithPrec(6, 1), + }, + { + Address: "osmo1gw445ta0aqn26suz2rg3tkqfpxnq2hs224d7gq", + Weight: sdk.NewDecWithPrec(4, 1), + }, + }, + 2), // minting reward distribution start epoch + 3) // halven started epoch + +func TestMintGenesisTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} + +// TestMintInitGenesis tests that genesis is initialized correctly +// with different parameters and state. +func (suite *KeeperTestSuite) TestMintInitGenesis() { + testCases := map[string]struct { + mintGenesis *types.GenesisState + mintDenom string + ctxHeight int64 + isDeveloperModuleAccountCreated bool + + expectPanic bool + expectedEpochProvisions sdk.Dec + // Deltas represent by how much a certain paramets + // has changed after calling InitGenesis() + expectedSupplyOffsetDelta sdk.Int + expectedSupplyWithOffsetDelta sdk.Int + expectedDeveloperVestingAmountDelta sdk.Int + expectedHalvenStartedEpoch int64 + }{ + "default genesis - developer module account is not created prior to InitGenesis() - created during the call": { + mintGenesis: types.DefaultGenesisState(), + mintDenom: sdk.DefaultBondDenom, + + expectedEpochProvisions: types.DefaultGenesisState().Params.GenesisEpochProvisions, + expectedSupplyOffsetDelta: sdk.NewInt(keeper.DeveloperVestingAmount).Neg(), + expectedSupplyWithOffsetDelta: sdk.ZeroInt(), + expectedDeveloperVestingAmountDelta: sdk.NewInt(keeper.DeveloperVestingAmount), + }, + "default genesis - developer module account is created prior to InitGenesis() - not created during the call": { + mintGenesis: types.DefaultGenesisState(), + mintDenom: sdk.DefaultBondDenom, + isDeveloperModuleAccountCreated: true, + + expectedEpochProvisions: types.DefaultGenesisState().Params.GenesisEpochProvisions, + expectedSupplyOffsetDelta: sdk.ZeroInt(), + expectedSupplyWithOffsetDelta: sdk.ZeroInt(), + expectedDeveloperVestingAmountDelta: sdk.ZeroInt(), + }, + "custom genesis": { + mintGenesis: customGenesis, + mintDenom: "uosmo", + + expectedEpochProvisions: sdk.NewDec(200), + expectedSupplyOffsetDelta: sdk.NewInt(keeper.DeveloperVestingAmount).Neg(), + expectedSupplyWithOffsetDelta: sdk.ZeroInt(), + expectedDeveloperVestingAmountDelta: sdk.NewInt(keeper.DeveloperVestingAmount), + expectedHalvenStartedEpoch: 3, + }, + "nil genesis state - panic": { + mintDenom: sdk.DefaultBondDenom, + expectPanic: true, + }, + } + + for name, tc := range testCases { + suite.Run(name, func() { + // Setup. + suite.setupDeveloperVestingModuleAccountTest(tc.ctxHeight, tc.isDeveloperModuleAccountCreated) + ctx := suite.Ctx + accountKeeper := suite.App.AccountKeeper + bankKeeper := suite.App.BankKeeper + mintKeeper := suite.App.MintKeeper + + developerAccount := accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName) + + originalSupplyOffset := bankKeeper.GetSupplyOffset(ctx, tc.mintDenom) + originalSupplyWithOffset := bankKeeper.GetSupplyWithOffset(ctx, tc.mintDenom) + originalVestingCoins := bankKeeper.GetBalance(ctx, developerAccount, tc.mintDenom) + + // Test. + if tc.expectPanic { + suite.Panics(func() { + mintKeeper.InitGenesis(ctx, tc.mintGenesis) + }) + return + } + + suite.NotPanics(func() { + mintKeeper.InitGenesis(ctx, tc.mintGenesis) + }) + + // Assertions. + + // Module account was created. + acc := accountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName)) + suite.NotNil(acc) + + // Epoch provisions are set to genesis epoch provisions from params. + actualEpochProvisions := mintKeeper.GetMinter(ctx).EpochProvisions + suite.Equal(tc.expectedEpochProvisions, actualEpochProvisions) + + // Supply offset is applied to genesis supply. + actualSupplyOffset := bankKeeper.GetSupplyOffset(ctx, tc.mintDenom) + expectedSupplyOffset := tc.expectedSupplyOffsetDelta.Add(originalSupplyOffset) + suite.Equal(expectedSupplyOffset, actualSupplyOffset) + + // Supply with offset is as expected. + actualSupplyWithOffset := bankKeeper.GetSupplyWithOffset(ctx, tc.mintDenom).Amount + expectedSupplyWithOffset := tc.expectedSupplyWithOffsetDelta.Add(originalSupplyWithOffset.Amount) + suite.Equal(expectedSupplyWithOffset.Int64(), actualSupplyWithOffset.Int64()) + + // Developer vesting account has the desired amount of tokens. + actualVestingCoins := bankKeeper.GetBalance(ctx, developerAccount, tc.mintDenom) + expectedDeveloperVestingAmount := tc.expectedDeveloperVestingAmountDelta.Add(originalVestingCoins.Amount) + suite.Equal(expectedDeveloperVestingAmount.Int64(), actualVestingCoins.Amount.Int64()) + + // Last halven epoch num is set to 0. + suite.Equal(tc.expectedHalvenStartedEpoch, mintKeeper.GetLastReductionEpochNum(ctx)) + }) + } +} + +// TestMintExportGenesis tests that genesis is exported correctly. +// It first initializes genesis to the expected value. Then, attempts +// to export it. Lastly, compares exported to the expected. +func (suite *KeeperTestSuite) TestMintExportGenesis() { + testCases := map[string]struct { + expectedGenesis *types.GenesisState + }{ + "default genesis": { + expectedGenesis: types.DefaultGenesisState(), + }, + "custom genesis": { + expectedGenesis: customGenesis, + }, + } + + for name, tc := range testCases { + suite.Run(name, func() { + // Setup. + app := suite.App + ctx := suite.Ctx - validateGenesis := types.ValidateGenesis(*types.DefaultGenesisState()) - require.NoError(t, validateGenesis) + app.MintKeeper.InitGenesis(ctx, tc.expectedGenesis) - developerAccount := app.AccountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName) - initialVestingCoins := app.BankKeeper.GetBalance(ctx, developerAccount, sdk.DefaultBondDenom) + // Test. + actualGenesis := app.MintKeeper.ExportGenesis(ctx) - expectedVestingCoins, ok := sdk.NewIntFromString("225000000000000") - require.True(t, ok) - require.Equal(t, expectedVestingCoins, initialVestingCoins.Amount) - require.Equal(t, int64(0), app.MintKeeper.GetLastReductionEpochNum(ctx)) + // Assertions. + suite.Equal(tc.expectedGenesis, actualGenesis) + }) + } } diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index fcfd5a67380..dd9b66c3941 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -38,10 +38,6 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { } app.MintKeeper.SetParams(ctx, mintParams) - // setup developer rewards account - app.MintKeeper.CreateDeveloperVestingModuleAccount( - ctx, sdk.NewCoin("stake", sdk.NewInt(156*500000*2))) - height := int64(1) lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) // correct rewards @@ -121,10 +117,6 @@ func TestMintedCoinDistributionWhenDevRewardsAddressEmpty(t *testing.T) { params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) - // setup developer rewards account - app.MintKeeper.CreateDeveloperVestingModuleAccount( - ctx, sdk.NewCoin("stake", sdk.NewInt(156*500000*2))) - height := int64(1) lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) // correct rewards diff --git a/x/mint/keeper/integration_test.go b/x/mint/keeper/integration_test.go deleted file mode 100644 index 258236ab776..00000000000 --- a/x/mint/keeper/integration_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package keeper_test - -import ( - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - simapp "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// returns context and an app with updated mint keeper -func createTestApp(isCheckTx bool) (*simapp.OsmosisApp, sdk.Context) { - app := simapp.Setup(isCheckTx) - - ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{}) - app.MintKeeper.SetParams(ctx, types.DefaultParams()) - app.MintKeeper.SetMinter(ctx, types.DefaultInitialMinter()) - - return app, ctx -} diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index 3ae53908c10..0535942c0d4 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -1,6 +1,9 @@ package keeper import ( + "errors" + "fmt" + "github.com/tendermint/tendermint/libs/log" "github.com/osmosis-labs/osmosis/v7/x/mint/types" @@ -12,6 +15,12 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) +var ( + errAmountCannotBeNilOrZero = errors.New("amount cannot be nil or zero") + errDevVestingModuleAccountAlreadyCreated = fmt.Errorf("%s module account already exists", types.DeveloperVestingModuleAcctName) + errDevVestingModuleAccountNotCreated = fmt.Errorf("%s module account does not exist", types.DeveloperVestingModuleAcctName) +) + // Keeper of the mint store. type Keeper struct { cdc codec.BinaryCodec @@ -54,25 +63,46 @@ func NewKeeper( } // SetInitialSupplyOffsetDuringMigration sets the supply offset based on the balance of the -// Develop rVesting Module Account. It should only be called one time during the initial -// migration to v7. -func SetInitialSupplyOffsetDuringMigration(ctx sdk.Context, k Keeper) { +// developer vesting module account. CreateDeveloperVestingModuleAccount must be called +// prior to calling this method. That is, developer vesting module account must exist when +// SetInitialSupplyOffsetDuringMigration is called. Also, SetInitialSupplyOffsetDuringMigration +// should only be called one time during the initial migration to v7. This is done so because +// we would like to ensure that unvested developer tokens are not returned as part of the supply +// queries. The method returns an error if current height in ctx is greater than the v7 upgrade height. +func (k Keeper) SetInitialSupplyOffsetDuringMigration(ctx sdk.Context) error { + if !k.accountKeeper.HasAccount(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) { + return errDevVestingModuleAccountNotCreated + } + moduleAccBalance := k.bankKeeper.GetBalance(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), k.GetParams(ctx).MintDenom) k.bankKeeper.AddSupplyOffset(ctx, moduleAccBalance.Denom, moduleAccBalance.Amount.Neg()) + return nil } -// CreateDeveloperVestingModuleAccount creates the module account for developer vesting. -// Should only be called in initial genesis creation, never again. -func (k Keeper) CreateDeveloperVestingModuleAccount(ctx sdk.Context, amount sdk.Coin) { +// CreateDeveloperVestingModuleAccount creates the developer vesting module account +// and mints amount of tokens to it. +// Should only be called during the initial genesis creation, never again. Returns nil on success. +// Returns error in the following cases: +// - amount is nil or zero. +// - if ctx has block height greater than 0. +// - developer vesting module account is already created prior to calling this method. +func (k Keeper) CreateDeveloperVestingModuleAccount(ctx sdk.Context, amount sdk.Coin) error { + if amount.IsNil() || amount.Amount.IsZero() { + return errAmountCannotBeNilOrZero + } + if k.accountKeeper.HasAccount(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) { + return errDevVestingModuleAccountAlreadyCreated + } + moduleAcc := authtypes.NewEmptyModuleAccount( types.DeveloperVestingModuleAcctName, authtypes.Minter) - k.accountKeeper.SetModuleAccount(ctx, moduleAcc) err := k.bankKeeper.MintCoins(ctx, types.DeveloperVestingModuleAcctName, sdk.NewCoins(amount)) if err != nil { - panic(err) + return err } + return nil } // _____________________________________________________________________ diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 46278ae6218..802cfd98268 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -11,9 +11,11 @@ import ( "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/osmosis-labs/osmosis/v7/app/apptesting" lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" "github.com/osmosis-labs/osmosis/v7/x/mint/types" poolincentivestypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" ) @@ -26,6 +28,33 @@ func (suite *KeeperTestSuite) SetupTest() { suite.Setup() } +// setupDeveloperVestingModuleAccountTest sets up test cases that utilize developer vesting +// module account logic. It reverts some default logic added by suite.Setup() +// Specifically, it removes the developer vesting module account +// from account keeper if isDeveloperModuleAccountCreated is true. +// Additionally, it initializes suite's Ctx with blockHeight +func (suite *KeeperTestSuite) setupDeveloperVestingModuleAccountTest(blockHeight int64, isDeveloperModuleAccountCreated bool) { + suite.Setup() + // Reset height to the desired value since test suite setup initialized + // it to 1. + suite.Ctx = suite.Ctx.WithBlockHeader(tmproto.Header{Height: blockHeight}) + + if !isDeveloperModuleAccountCreated { + // Remove the developer vesting account since suite setup creates and initializes it. + // This environment w/o the developer vesting account configured is necessary for + // testing edge cases of multiple tests. + developerVestingAccount := suite.App.AccountKeeper.GetAccount(suite.Ctx, suite.App.AccountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) + suite.App.AccountKeeper.RemoveAccount(suite.Ctx, developerVestingAccount) + suite.App.BankKeeper.BurnCoins(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(keeper.DeveloperVestingAmount)))) + + // If developer module account is created, the suite.Setup() also sets the offset, + // therefore, we should reset it to 0 to set up the environment truly w/o the module account. + supplyOffset := suite.App.BankKeeper.GetSupplyOffset(suite.Ctx, sdk.DefaultBondDenom) + suite.App.BankKeeper.AddSupplyOffset(suite.Ctx, sdk.DefaultBondDenom, supplyOffset.Mul(sdk.NewInt(-1))) + suite.Equal(sdk.ZeroInt(), suite.App.BankKeeper.GetSupplyOffset(suite.Ctx, sdk.DefaultBondDenom)) + } +} + func TestKeeperTestSuite(t *testing.T) { suite.Run(t, new(KeeperTestSuite)) } @@ -179,3 +208,95 @@ func (suite *KeeperTestSuite) TestDistrAssetToCommunityPoolWhenNoDeveloperReward mintCoins[0].Amount.ToDec().Mul(proportionToCommunity).Mul(sdk.NewDec(2)), feePool.CommunityPool.AmountOf("stake")) } + +func (suite *KeeperTestSuite) TestCreateDeveloperVestingModuleAccount() { + testcases := map[string]struct { + blockHeight int64 + amount sdk.Coin + isDeveloperModuleAccountCreated bool + + expectedError error + }{ + "valid call": { + blockHeight: 0, + amount: sdk.NewCoin("stake", sdk.NewInt(keeper.DeveloperVestingAmount)), + }, + "nil amount": { + blockHeight: 0, + expectedError: keeper.ErrAmountCannotBeNilOrZero, + }, + "zero amount": { + blockHeight: 0, + amount: sdk.NewCoin("stake", sdk.NewInt(0)), + expectedError: keeper.ErrAmountCannotBeNilOrZero, + }, + "module account is already created": { + blockHeight: 0, + amount: sdk.NewCoin("stake", sdk.NewInt(keeper.DeveloperVestingAmount)), + isDeveloperModuleAccountCreated: true, + expectedError: keeper.ErrDevVestingModuleAccountAlreadyCreated, + }, + } + + for name, tc := range testcases { + suite.Run(name, func() { + suite.setupDeveloperVestingModuleAccountTest(tc.blockHeight, tc.isDeveloperModuleAccountCreated) + mintKeeper := suite.App.MintKeeper + + // Test + actualError := mintKeeper.CreateDeveloperVestingModuleAccount(suite.Ctx, tc.amount) + + if tc.expectedError != nil { + suite.Error(actualError) + suite.Equal(actualError, tc.expectedError) + return + } + suite.NoError(actualError) + }) + } +} + +func (suite *KeeperTestSuite) TestSetInitialSupplyOffsetDuringMigration() { + testcases := map[string]struct { + blockHeight int64 + isDeveloperModuleAccountCreated bool + + expectedError error + }{ + "valid call": { + blockHeight: 1, + isDeveloperModuleAccountCreated: true, + }, + "dev vesting module account does not exist": { + blockHeight: 1, + expectedError: keeper.ErrDevVestingModuleAccountNotCreated, + }, + } + + for name, tc := range testcases { + suite.Run(name, func() { + suite.setupDeveloperVestingModuleAccountTest(tc.blockHeight, tc.isDeveloperModuleAccountCreated) + ctx := suite.Ctx + bankKeeper := suite.App.BankKeeper + mintKeeper := suite.App.MintKeeper + + supplyWithOffsetBefore := bankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom) + supplyOffsetBefore := bankKeeper.GetSupplyOffset(ctx, sdk.DefaultBondDenom) + + // Test + actualError := mintKeeper.SetInitialSupplyOffsetDuringMigration(ctx) + + if tc.expectedError != nil { + suite.Error(actualError) + suite.Equal(actualError, tc.expectedError) + + suite.Equal(supplyWithOffsetBefore.Amount, bankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount) + suite.Equal(supplyOffsetBefore, bankKeeper.GetSupplyOffset(ctx, sdk.DefaultBondDenom)) + return + } + suite.NoError(actualError) + suite.Equal(supplyWithOffsetBefore.Amount.Sub(sdk.NewInt(keeper.DeveloperVestingAmount)), bankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount) + suite.Equal(supplyOffsetBefore.Sub(sdk.NewInt(keeper.DeveloperVestingAmount)), bankKeeper.GetSupplyOffset(ctx, sdk.DefaultBondDenom)) + }) + } +} diff --git a/x/mint/module.go b/x/mint/module.go index 54a123ec844..89eeb0ecb1e 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -141,7 +141,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json. var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) - am.keeper.InitGenesis(ctx, am.authKeeper, am.bankKeeper, &genesisState) + am.keeper.InitGenesis(ctx, &genesisState) return []abci.ValidatorUpdate{} } diff --git a/x/mint/module_test.go b/x/mint/module_test.go deleted file mode 100644 index 0be8567e544..00000000000 --- a/x/mint/module_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package mint_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - abcitypes "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - simapp "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" - - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { - app := simapp.Setup(false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - - app.InitChain( - abcitypes.RequestInitChain{ - AppStateBytes: []byte("{}"), - ChainId: "test-chain-id", - }, - ) - - acc := app.AccountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName)) - require.NotNil(t, acc) -} From 197a9b1255ce152a9bf055ff8fa0b1e20bb2f4e8 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sat, 2 Jul 2022 20:04:30 -0500 Subject: [PATCH 016/376] Re-use code in superfluid TotalDelegationByDelegator (#1938) --- .golangci.yml | 2 +- x/superfluid/keeper/grpc_query.go | 49 ++++++------------------------- 2 files changed, 10 insertions(+), 41 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index bbcae8a8715..aa2c9cb1e0f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -47,7 +47,7 @@ linters: # - gosec <- triggers too much for this round and should be re-enabled later # - gosimple <- later - govet - # - ifshort <- seems to be of questionable value + # - ifshort <- questionable value, unclear if globally helping readability. - importas - ineffassign # - ireturn <- disabled because we want to return interfaces diff --git a/x/superfluid/keeper/grpc_query.go b/x/superfluid/keeper/grpc_query.go index 8d8e475ab71..ad74c932500 100644 --- a/x/superfluid/keeper/grpc_query.go +++ b/x/superfluid/keeper/grpc_query.go @@ -439,48 +439,17 @@ func (q Querier) TotalDelegationByDelegator(goCtx context.Context, req *types.Qu return nil, err } - res := types.QueryTotalDelegationByDelegatorResponse{ - SuperfluidDelegationRecords: []types.SuperfluidDelegationRecord{}, - DelegationResponse: []stakingtypes.DelegationResponse{}, - TotalDelegatedCoins: sdk.NewCoins(), - TotalEquivalentStakedAmount: sdk.NewCoin(appparams.BaseCoinUnit, sdk.ZeroInt()), + superfluidDelegationResp, err := q.SuperfluidDelegationsByDelegator(goCtx, &types.SuperfluidDelegationsByDelegatorRequest{ + DelegatorAddress: req.DelegatorAddress}) + if err != nil { + return nil, err } - syntheticLocks := q.Keeper.lk.GetAllSyntheticLockupsByAddr(ctx, delAddr) - - for _, syntheticLock := range syntheticLocks { - // don't include unbonding delegations - if strings.Contains(syntheticLock.SynthDenom, "superunbonding") { - continue - } - - periodLock, err := q.Keeper.lk.GetLockByID(ctx, syntheticLock.UnderlyingLockId) - if err != nil { - return nil, err - } - - baseDenom := periodLock.Coins.GetDenomByIndex(0) - lockedCoins := sdk.NewCoin(baseDenom, periodLock.GetCoins().AmountOf(baseDenom)) - valAddr, err := ValidatorAddressFromSyntheticDenom(syntheticLock.SynthDenom) - - // Find how many osmo tokens this delegation is worth at superfluids current risk adjustment - // and twap of the denom. - equivalentAmount := q.Keeper.GetSuperfluidOSMOTokens(ctx, baseDenom, lockedCoins.Amount) - coin := sdk.NewCoin(appparams.BaseCoinUnit, equivalentAmount) - - if err != nil { - return nil, err - } - res.SuperfluidDelegationRecords = append(res.SuperfluidDelegationRecords, - types.SuperfluidDelegationRecord{ - DelegatorAddress: req.DelegatorAddress, - ValidatorAddress: valAddr, - DelegationAmount: lockedCoins, - EquivalentStakedAmount: &coin, - }, - ) - res.TotalDelegatedCoins = res.TotalDelegatedCoins.Add(lockedCoins) - res.TotalEquivalentStakedAmount = res.TotalEquivalentStakedAmount.Add(coin) + res := types.QueryTotalDelegationByDelegatorResponse{ + SuperfluidDelegationRecords: superfluidDelegationResp.SuperfluidDelegationRecords, + DelegationResponse: []stakingtypes.DelegationResponse{}, + TotalDelegatedCoins: superfluidDelegationResp.TotalDelegatedCoins, + TotalEquivalentStakedAmount: superfluidDelegationResp.TotalEquivalentStakedAmount, } //this is for getting normal staking From 8f018a6c638b64912c1b22c7df04f84abe667ba0 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 3 Jul 2022 08:04:48 +0700 Subject: [PATCH 017/376] gofumpt matienance (#1948) --- tests/e2e/e2e_setup_test.go | 2 -- x/epochs/keeper/epoch_test.go | 3 ++- x/gamm/pool-models/balancer/pool_test.go | 1 - x/mint/keeper/hooks_test.go | 6 ++---- x/mint/keeper/keeper_test.go | 2 +- x/mint/simulation/genesis.go | 2 +- x/mint/types/minter_test.go | 1 - x/pool-incentives/keeper/hooks.go | 6 ++++-- x/superfluid/client/cli/query.go | 1 - x/superfluid/keeper/grpc_query.go | 2 +- x/tokenfactory/types/codec.go | 4 +--- 11 files changed, 12 insertions(+), 18 deletions(-) diff --git a/tests/e2e/e2e_setup_test.go b/tests/e2e/e2e_setup_test.go index 0ce8235868c..1a1eb1a1cfd 100644 --- a/tests/e2e/e2e_setup_test.go +++ b/tests/e2e/e2e_setup_test.go @@ -502,9 +502,7 @@ func (s *IntegrationTestSuite) upgrade() { } func (s *IntegrationTestSuite) upgradeFork() { - for _, chainConfig := range s.chainConfigs { - for i := range chainConfig.validators { validatorResource, exists := s.containerManager.GetValidatorResource(chainConfig.meta.Id, i) require.True(s.T(), exists) diff --git a/x/epochs/keeper/epoch_test.go b/x/epochs/keeper/epoch_test.go index 922f3b0dba8..dea59d69830 100644 --- a/x/epochs/keeper/epoch_test.go +++ b/x/epochs/keeper/epoch_test.go @@ -35,7 +35,8 @@ func (suite *KeeperTestSuite) TestAddEpochInfo() { CurrentEpochStartHeight: startBlockHeight, CurrentEpochStartTime: time.Time{}, EpochCountingStarted: false, - }}, + }, + }, "zero_duration": { addedEpochInfo: types.EpochInfo{ Identifier: defaultIdentifier, diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go index d4b3133672f..466a93fc17d 100644 --- a/x/gamm/pool-models/balancer/pool_test.go +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -607,7 +607,6 @@ func (suite *BalancerTestSuite) TestBalancerCalculateAmountOutAndIn_InverseRelat sut := func() { suite.TestCalculateAmountOutAndIn_InverseRelationship(ctx, pool, poolAssetIn.Token.Denom, poolAssetOut.Token.Denom, tc.initialCalcOut, swapFeeDec) - } balancerPool, ok := pool.(*balancer.Pool) diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index dd9b66c3941..f6fa8e6f877 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -236,9 +236,7 @@ func TestAfterEpochEnd_FirstYearThirdening_RealParameters(t *testing.T) { developerAccountBalance = 225_000_000_000_000 ) - var ( - reductionFactor = sdk.NewDec(2).Quo(sdk.NewDec(3)) - ) + reductionFactor := sdk.NewDec(2).Quo(sdk.NewDec(3)) app := osmoapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) @@ -256,7 +254,7 @@ func TestAfterEpochEnd_FirstYearThirdening_RealParameters(t *testing.T) { Staking: sdk.NewDecWithPrec(25, 2), PoolIncentives: sdk.NewDecWithPrec(45, 2), DeveloperRewards: sdk.NewDecWithPrec(25, 2), - CommunityPool: sdk.NewDecWithPrec(05, 2), + CommunityPool: sdk.NewDecWithPrec(0o5, 2), }, WeightedDeveloperRewardsReceivers: []types.WeightedAddress{ { diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 802cfd98268..a7c65186a10 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -268,7 +268,7 @@ func (suite *KeeperTestSuite) TestSetInitialSupplyOffsetDuringMigration() { isDeveloperModuleAccountCreated: true, }, "dev vesting module account does not exist": { - blockHeight: 1, + blockHeight: 1, expectedError: keeper.ErrDevVestingModuleAccountNotCreated, }, } diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index 94dd75c1f70..bb121e631aa 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -31,7 +31,7 @@ var ( Staking: sdk.NewDecWithPrec(25, 2), PoolIncentives: sdk.NewDecWithPrec(45, 2), DeveloperRewards: sdk.NewDecWithPrec(25, 2), - CommunityPool: sdk.NewDecWithPrec(05, 2), + CommunityPool: sdk.NewDecWithPrec(0o5, 2), } weightedDevRewardReceivers = []types.WeightedAddress{ { diff --git a/x/mint/types/minter_test.go b/x/mint/types/minter_test.go index cb841155a9f..4df3dc8e31e 100644 --- a/x/mint/types/minter_test.go +++ b/x/mint/types/minter_test.go @@ -45,7 +45,6 @@ func BenchmarkNextEpochProvisions(b *testing.B) { } func TestMinterValidate(t *testing.T) { - testcases := []struct { name string minter types.Minter diff --git a/x/pool-incentives/keeper/hooks.go b/x/pool-incentives/keeper/hooks.go index af099cbc535..60fd8e97254 100644 --- a/x/pool-incentives/keeper/hooks.go +++ b/x/pool-incentives/keeper/hooks.go @@ -11,8 +11,10 @@ type Hooks struct { k Keeper } -var _ gammtypes.GammHooks = Hooks{} -var _ minttypes.MintHooks = Hooks{} +var ( + _ gammtypes.GammHooks = Hooks{} + _ minttypes.MintHooks = Hooks{} +) // Create new pool incentives hooks. func (k Keeper) Hooks() Hooks { return Hooks{k} } diff --git a/x/superfluid/client/cli/query.go b/x/superfluid/client/cli/query.go index 22e9bddc4c8..e120cb6bf59 100644 --- a/x/superfluid/client/cli/query.go +++ b/x/superfluid/client/cli/query.go @@ -366,7 +366,6 @@ func GetCmdTotalDelegationByDelegator() *cobra.Command { res, err := queryClient.TotalDelegationByDelegator(cmd.Context(), &types.QueryTotalDelegationByDelegatorRequest{ DelegatorAddress: args[0], }) - if err != nil { return err } diff --git a/x/superfluid/keeper/grpc_query.go b/x/superfluid/keeper/grpc_query.go index ad74c932500..593b5d8074c 100644 --- a/x/superfluid/keeper/grpc_query.go +++ b/x/superfluid/keeper/grpc_query.go @@ -452,7 +452,7 @@ func (q Querier) TotalDelegationByDelegator(goCtx context.Context, req *types.Qu TotalEquivalentStakedAmount: superfluidDelegationResp.TotalEquivalentStakedAmount, } - //this is for getting normal staking + // this is for getting normal staking q.sk.IterateDelegations(ctx, delAddr, func(_ int64, del stakingtypes.DelegationI) bool { val, found := q.sk.GetValidator(ctx, del.GetValidatorAddr()) if !found { diff --git a/x/tokenfactory/types/codec.go b/x/tokenfactory/types/codec.go index a4e11fad8ac..7b1c1413b37 100644 --- a/x/tokenfactory/types/codec.go +++ b/x/tokenfactory/types/codec.go @@ -29,6 +29,4 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } -var ( - ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) -) +var ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) From aca83eb1213b3cf3446c0b00fda717ea14e6872e Mon Sep 17 00:00:00 2001 From: Roman Date: Mon, 4 Jul 2022 09:32:24 -0400 Subject: [PATCH 018/376] lint: enable unused in golangci-lint (#1939) --- .golangci.yml | 9 ++++++++- osmomath/math.go | 2 +- store/node.go | 5 ----- tests/e2e/containers/config.go | 5 ----- tests/e2e/initialization/chain.go | 27 --------------------------- tests/e2e/initialization/validator.go | 21 ++++++++------------- x/gamm/keeper/keeper.go | 3 +++ x/gamm/module.go | 4 ---- x/gamm/pool-models/stableswap/amm.go | 6 ------ x/incentives/keeper/gauge.go | 4 ---- x/lockup/keeper/store.go | 1 + x/tokenfactory/keeper/bankactions.go | 1 + 12 files changed, 22 insertions(+), 66 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index aa2c9cb1e0f..b4af32571b7 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -79,7 +79,7 @@ linters: - typecheck - unconvert # - unparam <- looks for unused parameters (enable later) -# - unused <- looks for unused variables (enable later) + - unused # looks for unused variables, subset of staticcheck binary. # - varcheck <- later # - varnamelen <- disabled because defies idiom # - wastedassign @@ -95,5 +95,12 @@ issues: - path: client/docs linters: - all + - path: x/gamm/pool-models/stableswap + linters: + # Stableswap is in development. + # We should re-enable deadcode and unused linting + # across its files, once stableswap is fully complete. + - unused + - deadcode max-issues-per-linter: 10000 max-same-issues: 10000 diff --git a/osmomath/math.go b/osmomath/math.go index 390b84eece1..def0f501446 100644 --- a/osmomath/math.go +++ b/osmomath/math.go @@ -11,7 +11,7 @@ import ( var powPrecision, _ = sdk.NewDecFromStr("0.00000001") // Singletons. -//nolint:deadcode +// nolint: deadcode, unused var zero sdk.Dec = sdk.ZeroDec() var ( diff --git a/store/node.go b/store/node.go index 79862a6d69a..47aa4336904 100644 --- a/store/node.go +++ b/store/node.go @@ -233,11 +233,6 @@ func (node Node) find(key []byte) (idx int, match bool) { return len(node.Children), false } -func (node *Node) set(idx int, child *Child) *Node { - node.Children[idx] = child - return node -} - func (node *Node) setAcc(idx int, acc sdk.Int) *Node { node.Children[idx] = &Child{node.Children[idx].Index, acc} return node diff --git a/tests/e2e/containers/config.go b/tests/e2e/containers/config.go index 9b6fe0d4d2b..da5bb1a0254 100644 --- a/tests/e2e/containers/config.go +++ b/tests/e2e/containers/config.go @@ -20,11 +20,6 @@ const ( // This image should be pre-built with `make docker-build-debug` either in CI or locally. CurrentBranchOsmoRepository = "osmosis" CurrentBranchOsmoTag = "debug" - /// Current Git branch repo/version for osmosis initialization. It is meant to be built locally. - // It is used when skipping upgrade by setting OSMOSIS_E2E_SKIP_UPGRADE to true). - // This image should be pre-built with `make docker-build-e2e-chain-init` either in CI or locally. - currentBranchInitRepository = "osmosis-e2e-chain-init" - currentBranchInitTag = "debug" // Pre-upgrade osmosis repo/tag to pull. // It should be uploaded to Docker Hub. OSMOSIS_E2E_SKIP_UPGRADE should be unset // for this functionality to be used. diff --git a/tests/e2e/initialization/chain.go b/tests/e2e/initialization/chain.go index ba3c46f8b50..818d05afb6b 100644 --- a/tests/e2e/initialization/chain.go +++ b/tests/e2e/initialization/chain.go @@ -52,33 +52,6 @@ func (c *internalChain) createAndInitValidators(count int) error { return nil } -func (c *internalChain) createAndInitValidatorsWithMnemonics(count int, mnemonics []string) error { - for i := 0; i < count; i++ { - // create node - node := c.createValidator(i) - - // generate genesis files - if err := node.init(); err != nil { - return err - } - - c.validators = append(c.validators, node) - - // create keys - if err := node.createKeyFromMnemonic("val", mnemonics[i]); err != nil { - return err - } - if err := node.createNodeKey(); err != nil { - return err - } - if err := node.createConsensusKey(); err != nil { - return err - } - } - - return nil -} - func (c *internalChain) createValidator(index int) *internalValidator { return &internalValidator{ chain: c, diff --git a/tests/e2e/initialization/validator.go b/tests/e2e/initialization/validator.go index 03c5e80faf8..16e302f52d9 100644 --- a/tests/e2e/initialization/validator.go +++ b/tests/e2e/initialization/validator.go @@ -31,15 +31,14 @@ import ( ) type internalValidator struct { - chain *internalChain - index int - moniker string - mnemonic string - keyInfo keyring.Info - privateKey cryptotypes.PrivKey - consensusKey privval.FilePVKey - consensusPrivKey cryptotypes.PrivKey - nodeKey p2p.NodeKey + chain *internalChain + index int + moniker string + mnemonic string + keyInfo keyring.Info + privateKey cryptotypes.PrivKey + consensusKey privval.FilePVKey + nodeKey p2p.NodeKey } func (v *internalValidator) instanceName() string { @@ -58,10 +57,6 @@ func (v *internalValidator) getMoniker() string { return v.moniker } -func (v *internalValidator) getMnemonic() string { - return v.mnemonic -} - func (v *internalValidator) buildCreateValidatorMsg(amount sdk.Coin) (sdk.Msg, error) { description := stakingtypes.NewDescription(v.moniker, "", "", "", "") commissionRates := stakingtypes.CommissionRates{ diff --git a/x/gamm/keeper/keeper.go b/x/gamm/keeper/keeper.go index 183bdf1c878..97d937d0703 100644 --- a/x/gamm/keeper/keeper.go +++ b/x/gamm/keeper/keeper.go @@ -61,6 +61,7 @@ func NewKeeper(cdc codec.BinaryCodec, storeKey sdk.StoreKey, paramSpace paramtyp } } +// nolint: unused func (k *Keeper) createSwapEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) { ctx.EventManager().EmitEvents(sdk.Events{ sdk.NewEvent( @@ -74,6 +75,7 @@ func (k *Keeper) createSwapEvent(ctx sdk.Context, sender sdk.AccAddress, poolId }) } +// nolint: unused func (k *Keeper) createAddLiquidityEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) { ctx.EventManager().EmitEvents(sdk.Events{ sdk.NewEvent( @@ -86,6 +88,7 @@ func (k *Keeper) createAddLiquidityEvent(ctx sdk.Context, sender sdk.AccAddress, }) } +// nolint: unused func (k *Keeper) createRemoveLiquidityEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) { ctx.EventManager().EmitEvents(sdk.Events{ sdk.NewEvent( diff --git a/x/gamm/module.go b/x/gamm/module.go index f09fac85d30..b9a73752e36 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -15,7 +15,6 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/osmosis-labs/osmosis/v7/x/gamm/client/cli" "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" @@ -87,9 +86,6 @@ type AppModule struct { ak types.AccountKeeper bk types.BankKeeper keeper keeper.Keeper - - accountKeeper stakingtypes.AccountKeeper - bankKeeper stakingtypes.BankKeeper } func (am AppModule) RegisterServices(cfg module.Configurator) { diff --git a/x/gamm/pool-models/stableswap/amm.go b/x/gamm/pool-models/stableswap/amm.go index ae79bd77bcf..cf65894f9af 100644 --- a/x/gamm/pool-models/stableswap/amm.go +++ b/x/gamm/pool-models/stableswap/amm.go @@ -15,7 +15,6 @@ var ( ) // solidly CFMM is xy(x^2 + y^2) = k -// nolint:deadcode func cfmmConstant(xReserve, yReserve sdk.Dec) sdk.Dec { xy := xReserve.Mul(yReserve) x2 := xReserve.Mul(xReserve) @@ -28,7 +27,6 @@ func cfmmConstant(xReserve, yReserve sdk.Dec) sdk.Dec { // outside of x and y (e.g. u = wz), and v is the sum // of their squares (e.g. v = w^2 + z^2). // When u = 1 and v = 0, this is equivalent to solidly's CFMM -// nolint:deadcode func cfmmConstantMulti(xReserve, yReserve, uReserve, vSumSquares sdk.Dec) sdk.Dec { xyu := xReserve.Mul(yReserve.Mul(uReserve)) x2 := xReserve.Mul(xReserve) @@ -161,7 +159,6 @@ func solveCfmm(xReserve, yReserve, yIn sdk.Dec) sdk.Dec { // how many units `a` of x do we get out. // So we solve the following expression for `a` // xyz(x^2 + y^2 + w) = (x - a)(y + b)z((x - a)^2 + (y + b)^2 + w) -// nolint:deadcode func solveCfmmMulti(xReserve, yReserve, wSumSquares, yIn sdk.Dec) sdk.Dec { if !yReserve.Add(yIn).IsPositive() { panic("invalid yReserve, yIn combo") @@ -274,7 +271,6 @@ var ( // solveCFMMBinarySearch searches the correct dx using binary search over constant K. // added for future extension -// nolint:deadcode func solveCFMMBinarySearch(constantFunction func(sdk.Dec, sdk.Dec) sdk.Dec) func(sdk.Dec, sdk.Dec, sdk.Dec) sdk.Dec { return func(xReserve, yReserve, yIn sdk.Dec) sdk.Dec { k := constantFunction(xReserve, yReserve) @@ -298,7 +294,6 @@ func solveCFMMBinarySearch(constantFunction func(sdk.Dec, sdk.Dec) sdk.Dec) func // solveCFMMBinarySearch searches the correct dx using binary search over constant K. // added for future extension -// nolint:deadcode func solveCFMMBinarySearchMulti(constantFunction func(sdk.Dec, sdk.Dec, sdk.Dec, sdk.Dec) sdk.Dec) func(sdk.Dec, sdk.Dec, sdk.Dec, sdk.Dec, sdk.Dec) sdk.Dec { return func(xReserve, yReserve, uReserve, wSumSquares, yIn sdk.Dec) sdk.Dec { k := constantFunction(xReserve, yReserve, uReserve, wSumSquares) @@ -320,7 +315,6 @@ func solveCFMMBinarySearchMulti(constantFunction func(sdk.Dec, sdk.Dec, sdk.Dec, } } -//nolint:unused func spotPrice(baseReserve, quoteReserve sdk.Dec) sdk.Dec { // y = baseAsset, x = quoteAsset // Define f_{y -> x}(a) as the function that outputs the amount of tokens X you'd get by diff --git a/x/incentives/keeper/gauge.go b/x/incentives/keeper/gauge.go index eac459b4fb4..cda28bfb133 100644 --- a/x/incentives/keeper/gauge.go +++ b/x/incentives/keeper/gauge.go @@ -46,10 +46,6 @@ func (k Keeper) getCoinsFromGauges(gauges []types.Gauge) sdk.Coins { return coins } -func (k Keeper) getCoinsFromIterator(ctx sdk.Context, iterator db.Iterator) sdk.Coins { - return k.getCoinsFromGauges(k.getGaugesFromIterator(ctx, iterator)) -} - // setGauge set the gauge inside store. func (k Keeper) setGauge(ctx sdk.Context, gauge *types.Gauge) error { store := ctx.KVStore(k.storeKey) diff --git a/x/lockup/keeper/store.go b/x/lockup/keeper/store.go index b8ac7173628..31285c841bb 100644 --- a/x/lockup/keeper/store.go +++ b/x/lockup/keeper/store.go @@ -52,6 +52,7 @@ func syntheticLockTimeStoreKey(lockID uint64, synthDenom string, endTime time.Ti } // getLockRefs get lock IDs specified on the prefix and timestamp key. +// nolint: unused func (k Keeper) getLockRefs(ctx sdk.Context, key []byte) []uint64 { store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, key) diff --git a/x/tokenfactory/keeper/bankactions.go b/x/tokenfactory/keeper/bankactions.go index ab5debb0221..bf23d1c273b 100644 --- a/x/tokenfactory/keeper/bankactions.go +++ b/x/tokenfactory/keeper/bankactions.go @@ -51,6 +51,7 @@ func (k Keeper) burnFrom(ctx sdk.Context, amount sdk.Coin, burnFrom string) erro return k.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(amount)) } +// nolint: unused func (k Keeper) forceTransfer(ctx sdk.Context, amount sdk.Coin, fromAddr string, toAddr string) error { // verify that denom is an x/tokenfactory denom _, _, err := types.DeconstructDenom(amount.Denom) From 0956d893dc798d1c5b7d992b73afa5597636d1b3 Mon Sep 17 00:00:00 2001 From: Xiangan He <76530366+xBalbinus@users.noreply.github.com> Date: Mon, 4 Jul 2022 09:40:58 -0400 Subject: [PATCH 019/376] Making CI for testing generated proto correctness (#1892) --- .github/workflows/check-generated.yml | 29 +++++++++++++++++++++++++++ chain.schema.json | 2 +- contrib/scripts/check-generated.sh | 15 ++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/check-generated.yml create mode 100755 contrib/scripts/check-generated.sh diff --git a/.github/workflows/check-generated.yml b/.github/workflows/check-generated.yml new file mode 100644 index 00000000000..4f2407ad666 --- /dev/null +++ b/.github/workflows/check-generated.yml @@ -0,0 +1,29 @@ +# Verify that generated code is up-to-date. +# +# Note that we run these checks regardless whether the input files have +# changed, because generated code can change in response to toolchain updates +# even if no files in the repository are modified. +name: Check generated code +on: + workflow_dispatch: + pull_request: + branches: + - '*' + +permissions: + contents: read + +jobs: + check-proto: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v3 + with: + go-version: '1.18' + + - uses: actions/checkout@v3 + with: + fetch-depth: 1 # we need a .git directory to run git diff + + - name: "Check protobuf generated code" + run: contrib/scripts/check-generated.sh diff --git a/chain.schema.json b/chain.schema.json index 2cd48336f3f..71a75536ef3 100644 --- a/chain.schema.json +++ b/chain.schema.json @@ -9,4 +9,4 @@ "linux/arm64": "https://github.com/osmosis-labs/osmosis/releases/download/v10.0.0/osmosis-10.0.0-linux-arm64" } } -} +} \ No newline at end of file diff --git a/contrib/scripts/check-generated.sh b/contrib/scripts/check-generated.sh new file mode 100755 index 00000000000..dbdcdf7c8f4 --- /dev/null +++ b/contrib/scripts/check-generated.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +set -euo pipefail + +make proto-gen + +#Specificially ignore all differences in go.mod / go.sum. +if ! git diff --stat --exit-code . ':(exclude)*.mod' ':(exclude)*.sum'; then + echo ">> ERROR:" + echo ">>" + echo ">> Protobuf generated code requires update (either tools or .proto files may have changed)." + echo ">> Ensure your tools are up-to-date, re-run 'make proto-all' and update this PR." + echo ">>" + exit 1 +fi From 5be82920fa67a97c2c2dff1c06edd10e0ab66319 Mon Sep 17 00:00:00 2001 From: Roman Date: Mon, 4 Jul 2022 10:30:05 -0400 Subject: [PATCH 020/376] lint: remove unused v10 fork height not caught during merge (#1953) --- x/gamm/pool-models/balancer/pool.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index 449213fe3b5..c7c9e4496e5 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -24,8 +24,6 @@ const ( errMsgFormatFailedInterimLiquidityUpdate = "failed to update interim liquidity - pool asset %s does not exist" errMsgFormatRepeatingPoolAssetsNotAllowed = "repeating pool assets not allowed, found %s" errMsgFormatNoPoolAssetFound = "can't find the PoolAsset (%s)" - - v10Fork = 4713065 ) var ( From 1517e651c8af8417009f6a2392833265106b7d64 Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Tue, 5 Jul 2022 01:46:45 +0900 Subject: [PATCH 021/376] refactor ref method (#1951) --- x/lockup/keeper/bench_test.go | 7 ++++--- x/lockup/keeper/genesis.go | 4 ++-- x/lockup/keeper/genesis_test.go | 10 ++++++---- x/lockup/keeper/lock.go | 12 ++++++------ x/lockup/keeper/synthetic_lock_test.go | 2 +- 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/x/lockup/keeper/bench_test.go b/x/lockup/keeper/bench_test.go index 4630b3e4c67..6eb99b14b54 100644 --- a/x/lockup/keeper/bench_test.go +++ b/x/lockup/keeper/bench_test.go @@ -6,11 +6,12 @@ import ( "testing" "time" - "github.com/osmosis-labs/osmosis/v7/app" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" "github.com/tendermint/tendermint/crypto/secp256k1" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "github.com/osmosis-labs/osmosis/v7/app" + lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -74,7 +75,7 @@ func benchmarkResetLogic(numLockups int, b *testing.B) { b.StartTimer() b.ReportAllocs() // distribute coins from gauges to lockup owners - _ = app.LockupKeeper.ResetAllLocks(ctx, locks) + _ = app.LockupKeeper.InitializeAllLocks(ctx, locks) } func BenchmarkResetLogicMedium(b *testing.B) { diff --git a/x/lockup/keeper/genesis.go b/x/lockup/keeper/genesis.go index dce6109cae8..43367c17223 100644 --- a/x/lockup/keeper/genesis.go +++ b/x/lockup/keeper/genesis.go @@ -10,10 +10,10 @@ import ( // state. func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { k.SetLastLockID(ctx, genState.LastLockId) - if err := k.ResetAllLocks(ctx, genState.Locks); err != nil { + if err := k.InitializeAllLocks(ctx, genState.Locks); err != nil { return } - if err := k.ResetAllSyntheticLocks(ctx, genState.SyntheticLocks); err != nil { + if err := k.InitializeAllSyntheticLocks(ctx, genState.SyntheticLocks); err != nil { return } } diff --git a/x/lockup/keeper/genesis_test.go b/x/lockup/keeper/genesis_test.go index a4c96840dd0..6048046befb 100644 --- a/x/lockup/keeper/genesis_test.go +++ b/x/lockup/keeper/genesis_test.go @@ -61,12 +61,14 @@ func TestInitGenesis(t *testing.T) { coins = app.LockupKeeper.GetAccountLockedCoins(ctx, acc2) require.Equal(t, coins.String(), sdk.NewInt64Coin("foo", 5000000).String()) - // TODO: module account balance is kept by bank keeper and no need to check here - // coins = app.LockupKeeper.GetModuleBalance(ctx) - // require.Equal(t, coins.String(), sdk.NewInt64Coin("foo", 30000000).String()) - lastLockId := app.LockupKeeper.GetLastLockID(ctx) require.Equal(t, lastLockId, uint64(10)) + + acc := app.LockupKeeper.GetPeriodLocksAccumulation(ctx, types.QueryCondition{ + Denom: "foo", + Duration: time.Second, + }) + require.Equal(t, sdk.NewInt(30000000), acc) } func TestExportGenesis(t *testing.T) { diff --git a/x/lockup/keeper/lock.go b/x/lockup/keeper/lock.go index 0331912dea8..b29b5e22391 100644 --- a/x/lockup/keeper/lock.go +++ b/x/lockup/keeper/lock.go @@ -434,10 +434,10 @@ func (k Keeper) ExtendLockup(ctx sdk.Context, lockID uint64, owner sdk.AccAddres return nil } -// ResetAllLocks takes a set of locks, and initializes state to be storing +// InitializeAllLocks takes a set of locks, and initializes state to be storing // them all correctly. This utilizes batch optimizations to improve efficiency, // as this becomes a bottleneck at chain initialization & upgrades. -func (k Keeper) ResetAllLocks(ctx sdk.Context, locks []types.PeriodLock) error { +func (k Keeper) InitializeAllLocks(ctx sdk.Context, locks []types.PeriodLock) error { // index by coin.Denom, them duration -> amt // We accumulate the accumulation store entries separately, // to avoid hitting the myriad of slowdowns in the SDK iterator creation process. @@ -449,7 +449,7 @@ func (k Keeper) ResetAllLocks(ctx sdk.Context, locks []types.PeriodLock) error { msg := fmt.Sprintf("Reset %d lock refs, cur lock ID %d", i, lock.ID) ctx.Logger().Info(msg) } - err := k.setLockAndResetLockRefs(ctx, lock) + err := k.setLockAndAddLockRefs(ctx, lock) if err != nil { return err } @@ -497,7 +497,7 @@ func (k Keeper) ResetAllLocks(ctx sdk.Context, locks []types.PeriodLock) error { return nil } -func (k Keeper) ResetAllSyntheticLocks(ctx sdk.Context, syntheticLocks []types.SyntheticLock) error { +func (k Keeper) InitializeAllSyntheticLocks(ctx sdk.Context, syntheticLocks []types.SyntheticLock) error { // index by coin.Denom, them duration -> amt // We accumulate the accumulation store entries separately, // to avoid hitting the myriad of slowdowns in the SDK iterator creation process. @@ -633,9 +633,9 @@ func (k Keeper) setLock(ctx sdk.Context, lock types.PeriodLock) error { return nil } -// setLockAndResetLockRefs sets the lock, and resets all of its lock references +// setLockAndAddLockRefs sets the lock, and resets all of its lock references // This puts the lock into a 'clean' state, aside from the AccumulationStore. -func (k Keeper) setLockAndResetLockRefs(ctx sdk.Context, lock types.PeriodLock) error { +func (k Keeper) setLockAndAddLockRefs(ctx sdk.Context, lock types.PeriodLock) error { err := k.setLock(ctx, lock) if err != nil { return err diff --git a/x/lockup/keeper/synthetic_lock_test.go b/x/lockup/keeper/synthetic_lock_test.go index 09fd5b37377..09a296a7a98 100644 --- a/x/lockup/keeper/synthetic_lock_test.go +++ b/x/lockup/keeper/synthetic_lock_test.go @@ -276,7 +276,7 @@ func (suite *KeeperTestSuite) TestResetAllSyntheticLocks() { suite.Require().Len(locks, 1) suite.Require().Equal(locks[0].Coins, coins) - suite.App.LockupKeeper.ResetAllSyntheticLocks(suite.Ctx, []types.SyntheticLock{ + suite.App.LockupKeeper.InitializeAllSyntheticLocks(suite.Ctx, []types.SyntheticLock{ { UnderlyingLockId: 1, SynthDenom: "synthstakestakedtovalidator1", From cc82980bde6ff2964a4b6b5c0d90e29351049156 Mon Sep 17 00:00:00 2001 From: Roman Date: Mon, 4 Jul 2022 14:00:36 -0400 Subject: [PATCH 022/376] lint: enable gosimple (#1957) --- .golangci.yml | 2 +- tests/e2e/containers/containers.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b4af32571b7..eae40af7d2e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -45,7 +45,7 @@ linters: - gomodguard - goprintffuncname # - gosec <- triggers too much for this round and should be re-enabled later -# - gosimple <- later + - gosimple # specializes in simplifying code, subset of staticcheck binary. - govet # - ifshort <- questionable value, unclear if globally helping readability. - importas diff --git a/tests/e2e/containers/containers.go b/tests/e2e/containers/containers.go index 477a17837ad..bd60d2a253a 100644 --- a/tests/e2e/containers/containers.go +++ b/tests/e2e/containers/containers.go @@ -212,7 +212,7 @@ func (m *Manager) RunChainInitResource(chainId string, chainVotingPeriod int, va initResource, err := m.pool.RunWithOptions( &dockertest.RunOptions{ - Name: fmt.Sprintf("%s", chainId), + Name: chainId, Repository: m.ImageConfig.InitRepository, Tag: m.ImageConfig.InitTag, NetworkID: m.network.Network.ID, From c1155937b4b07d4db16edf29d5222410e291734f Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Tue, 5 Jul 2022 16:29:09 +0900 Subject: [PATCH 023/376] Refactor `lock` method (#1936) * Add lock method refactor * Delete duplciated testing * Update x/lockup/keeper/lock.go Co-authored-by: Aleksandr Bezobchuk * Add tests implement feedback from code review * Add test cases Co-authored-by: Aleksandr Bezobchuk --- x/lockup/keeper/admin_keeper_test.go | 8 +- x/lockup/keeper/export_test.go | 4 + x/lockup/keeper/lock.go | 77 ++++++--------- x/lockup/keeper/lock_test.go | 137 +++++++++++++++++++++------ 4 files changed, 141 insertions(+), 85 deletions(-) diff --git a/x/lockup/keeper/admin_keeper_test.go b/x/lockup/keeper/admin_keeper_test.go index 9829c31635c..9d4d6a083bf 100644 --- a/x/lockup/keeper/admin_keeper_test.go +++ b/x/lockup/keeper/admin_keeper_test.go @@ -4,7 +4,6 @@ import ( "time" "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -14,11 +13,10 @@ func (suite *KeeperTestSuite) TestRelock() { addr1 := sdk.AccAddress([]byte("addr1---------------")) coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} - lock := types.NewPeriodLock(1, addr1, time.Second, suite.Ctx.BlockTime().Add(time.Second), coins) // lock with balance suite.FundAcc(addr1, coins) - err := suite.App.LockupKeeper.Lock(suite.Ctx, lock) + lock, err := suite.App.LockupKeeper.CreateLock(suite.Ctx, addr1, coins, time.Second) suite.Require().NoError(err) // lock with balance with same id @@ -38,12 +36,12 @@ func (suite *KeeperTestSuite) BreakLock() { addr1 := sdk.AccAddress([]byte("addr1---------------")) coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} - lock := types.NewPeriodLock(1, addr1, time.Second, suite.Ctx.BlockTime().Add(time.Second), coins) // lock with balance suite.FundAcc(addr1, coins) - err := suite.App.LockupKeeper.Lock(suite.Ctx, lock) + lock, err := suite.App.LockupKeeper.CreateLock(suite.Ctx, addr1, coins, time.Second) + suite.Require().NoError(err) // break lock diff --git a/x/lockup/keeper/export_test.go b/x/lockup/keeper/export_test.go index 8c235e3381a..9b31939f4f4 100644 --- a/x/lockup/keeper/export_test.go +++ b/x/lockup/keeper/export_test.go @@ -21,3 +21,7 @@ func (k Keeper) GetLockRefs(ctx sdk.Context, key []byte) []uint64 { func (k Keeper) GetCoinsFromLocks(locks []types.PeriodLock) sdk.Coins { return k.getCoinsFromLocks(locks) } + +func (k Keeper) Lock(ctx sdk.Context, lock types.PeriodLock, tokensToLock sdk.Coins) error { + return k.lock(ctx, lock, tokensToLock) +} diff --git a/x/lockup/keeper/lock.go b/x/lockup/keeper/lock.go index b29b5e22391..4181b316e94 100644 --- a/x/lockup/keeper/lock.go +++ b/x/lockup/keeper/lock.go @@ -66,100 +66,79 @@ func (k Keeper) AddToExistingLock(ctx sdk.Context, owner sdk.AccAddress, coin sd // Tokens locked are sent and kept in the module account. // This method alters the lock state in store, thus we do a sanity check to ensure // lock owner matches the given owner. -func (k Keeper) AddTokensToLockByID(ctx sdk.Context, lockID uint64, owner sdk.AccAddress, coin sdk.Coin) (*types.PeriodLock, error) { +func (k Keeper) AddTokensToLockByID(ctx sdk.Context, lockID uint64, owner sdk.AccAddress, tokensToAdd sdk.Coin) (*types.PeriodLock, error) { lock, err := k.GetLockByID(ctx, lockID) + if err != nil { + return nil, err + } if lock.GetOwner() != owner.String() { return nil, types.ErrNotLockOwner } + lock.Coins = lock.Coins.Add(tokensToAdd) + err = k.lock(ctx, *lock, sdk.NewCoins(tokensToAdd)) if err != nil { return nil, err } - if err := k.bk.SendCoinsFromAccountToModule(ctx, lock.OwnerAddress(), types.ModuleName, sdk.NewCoins(coin)); err != nil { - return nil, err - } - err = k.addTokenToLock(ctx, lock, coin) - if err != nil { - return nil, err + for _, synthlock := range k.GetAllSyntheticLockupsByLockup(ctx, lock.ID) { + k.accumulationStore(ctx, synthlock.SynthDenom).Increase(accumulationKey(synthlock.Duration), tokensToAdd.Amount) } if k.hooks == nil { return lock, nil } - k.hooks.OnTokenLocked(ctx, lock.OwnerAddress(), lock.ID, sdk.Coins{coin}, lock.Duration, lock.EndTime) - return lock, nil -} - -// addTokenToLock adds token to lock and modifies the state of the lock and the accumulation store. -func (k Keeper) addTokenToLock(ctx sdk.Context, lock *types.PeriodLock, coin sdk.Coin) error { - lock.Coins = lock.Coins.Add(coin) - - err := k.setLock(ctx, *lock) - if err != nil { - return err - } - - // modifications to accumulation store - k.accumulationStore(ctx, coin.Denom).Increase(accumulationKey(lock.Duration), coin.Amount) - - // CONTRACT: lock will have synthetic lock only if it has a single coin - // accumulation store for its synthetic denom is increased if exists. - lockedCoin, err := lock.SingleCoin() - if err == nil { - for _, synthlock := range k.GetAllSyntheticLockupsByLockup(ctx, lock.ID) { - k.accumulationStore(ctx, synthlock.SynthDenom).Increase(accumulationKey(synthlock.Duration), sdk.NewCoins(coin).AmountOf(lockedCoin.Denom)) - } - } - - k.hooks.AfterAddTokensToLock(ctx, lock.OwnerAddress(), lock.GetID(), sdk.NewCoins(coin)) + k.hooks.AfterAddTokensToLock(ctx, lock.OwnerAddress(), lock.GetID(), sdk.NewCoins(tokensToAdd)) - return nil + return lock, nil } // CreateLock creates a new lock with the specified duration for the owner. +// Returns an error in the following conditions: +// - account does not have enough balance func (k Keeper) CreateLock(ctx sdk.Context, owner sdk.AccAddress, coins sdk.Coins, duration time.Duration) (types.PeriodLock, error) { ID := k.GetLastLockID(ctx) + 1 // unlock time is initially set without a value, gets set as unlock start time + duration // when unlocking starts. lock := types.NewPeriodLock(ID, owner, duration, time.Time{}, coins) - err := k.Lock(ctx, lock) + err := k.lock(ctx, lock, lock.Coins) + if err != nil { + return lock, err + } + + // add lock refs into not unlocking queue + err = k.addLockRefs(ctx, lock) if err != nil { return lock, err } + k.SetLastLockID(ctx, lock.ID) return lock, nil } -// Lock is a utility method to lock tokens into the module account. This method includes setting the -// lock within the state machine and increasing the value of accumulation store. -func (k Keeper) Lock(ctx sdk.Context, lock types.PeriodLock) error { +// lock is an internal utility to lock coins and set corresponding states. +// This is only called by either of the two possible entry points to lock tokens. +// 1. CreateLock +// 2. AddTokensToLockByID +func (k Keeper) lock(ctx sdk.Context, lock types.PeriodLock, tokensToLock sdk.Coins) error { owner, err := sdk.AccAddressFromBech32(lock.Owner) if err != nil { return err } - if err := k.bk.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, lock.Coins); err != nil { + if err := k.bk.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, tokensToLock); err != nil { return err } // store lock object into the store - store := ctx.KVStore(k.storeKey) - bz, err := proto.Marshal(&lock) - if err != nil { - return err - } - store.Set(lockStoreKey(lock.ID), bz) - - // add lock refs into not unlocking queue - err = k.addLockRefs(ctx, lock) + err = k.setLock(ctx, lock) if err != nil { return err } // add to accumulation store - for _, coin := range lock.Coins { + for _, coin := range tokensToLock { k.accumulationStore(ctx, coin.Denom).Increase(accumulationKey(lock.Duration), coin.Amount) } diff --git a/x/lockup/keeper/lock_test.go b/x/lockup/keeper/lock_test.go index 5dde289529e..834a72f8de2 100644 --- a/x/lockup/keeper/lock_test.go +++ b/x/lockup/keeper/lock_test.go @@ -144,35 +144,6 @@ func (suite *KeeperTestSuite) TestUnlockPeriodLockByID() { suite.Require().Len(locks, 0) } -func (suite *KeeperTestSuite) TestLock() { - // test for coin locking - suite.SetupTest() - - addr1 := sdk.AccAddress([]byte("addr1---------------")) - coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} - lock := types.NewPeriodLock(1, addr1, time.Second, suite.Ctx.BlockTime().Add(time.Second), coins) - - // try lock without balance - err := suite.App.LockupKeeper.Lock(suite.Ctx, lock) - suite.Require().Error(err) - - // lock with balance - suite.FundAcc(addr1, coins) - err = suite.App.LockupKeeper.Lock(suite.Ctx, lock) - suite.Require().NoError(err) - - // lock with balance with same id - suite.FundAcc(addr1, coins) - err = suite.App.LockupKeeper.Lock(suite.Ctx, lock) - suite.Require().Error(err) - - // lock with balance with different id - lock = types.NewPeriodLock(2, addr1, time.Second, suite.Ctx.BlockTime().Add(time.Second), coins) - suite.FundAcc(addr1, coins) - err = suite.App.LockupKeeper.Lock(suite.Ctx, lock) - suite.Require().NoError(err) -} - func (suite *KeeperTestSuite) TestUnlock() { // test for coin unlocking suite.SetupTest() @@ -180,11 +151,10 @@ func (suite *KeeperTestSuite) TestUnlock() { addr1 := sdk.AccAddress([]byte("addr1---------------")) coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} - lock := types.NewPeriodLock(1, addr1, time.Second, time.Time{}, coins) // lock with balance suite.FundAcc(addr1, coins) - err := suite.App.LockupKeeper.Lock(suite.Ctx, lock) + lock, err := suite.App.LockupKeeper.CreateLock(suite.Ctx, addr1, coins, time.Second) suite.Require().NoError(err) // begin unlock with lock object @@ -320,6 +290,65 @@ func (suite *KeeperTestSuite) TestLocksLongerThanDurationDenom() { suite.Require().Len(locks, 1) } +func (suite *KeeperTestSuite) TestCreateLock() { + suite.SetupTest() + + addr1 := sdk.AccAddress([]byte("addr1---------------")) + coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} + + // test locking without balance + _, err := suite.App.LockupKeeper.CreateLock(suite.Ctx, addr1, coins, time.Second) + suite.Require().Error(err) + + suite.FundAcc(addr1, coins) + + lock, err := suite.App.LockupKeeper.CreateLock(suite.Ctx, addr1, coins, time.Second) + suite.Require().NoError(err) + + // check new lock + suite.Require().Equal(coins, lock.Coins) + suite.Require().Equal(time.Second, lock.Duration) + suite.Require().Equal(time.Time{}, lock.EndTime) + suite.Require().Equal(uint64(1), lock.ID) + + lockID := suite.App.LockupKeeper.GetLastLockID(suite.Ctx) + suite.Require().Equal(uint64(1), lockID) + + // check accumulation store + accum := suite.App.LockupKeeper.GetPeriodLocksAccumulation(suite.Ctx, types.QueryCondition{ + LockQueryType: types.ByDuration, + Denom: "stake", + Duration: time.Second, + }) + suite.Require().Equal(accum.String(), "10") + + // create new lock + coins = sdk.Coins{sdk.NewInt64Coin("stake", 20)} + suite.FundAcc(addr1, coins) + + lock, err = suite.App.LockupKeeper.CreateLock(suite.Ctx, addr1, coins, time.Second) + suite.Require().NoError(err) + + lockID = suite.App.LockupKeeper.GetLastLockID(suite.Ctx) + suite.Require().Equal(uint64(2), lockID) + + // check accumulation store + accum = suite.App.LockupKeeper.GetPeriodLocksAccumulation(suite.Ctx, types.QueryCondition{ + LockQueryType: types.ByDuration, + Denom: "stake", + Duration: time.Second, + }) + suite.Require().Equal(accum.String(), "30") + + // check balance + balance := suite.App.BankKeeper.GetBalance(suite.Ctx, addr1, "stake") + suite.Require().Equal(sdk.ZeroInt(), balance.Amount) + + acc := suite.App.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) + balance = suite.App.BankKeeper.GetBalance(suite.Ctx, acc.GetAddress(), "stake") + suite.Require().Equal(sdk.NewInt(30), balance.Amount) +} + func (suite *KeeperTestSuite) TestAddTokensToLock() { suite.SetupTest() @@ -381,6 +410,52 @@ func (suite *KeeperTestSuite) TestAddTokensToLock() { suite.Require().Error(err) } +func (suite *KeeperTestSuite) TestLock() { + suite.SetupTest() + + addr1 := sdk.AccAddress([]byte("addr1---------------")) + coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} + + lock := types.PeriodLock{ + ID: 1, + Owner: addr1.String(), + Duration: time.Second, + EndTime: time.Time{}, + Coins: coins, + } + + // test locking without balance + err := suite.App.LockupKeeper.Lock(suite.Ctx, lock, coins) + suite.Require().Error(err) + + // check accumulation store + accum := suite.App.LockupKeeper.GetPeriodLocksAccumulation(suite.Ctx, types.QueryCondition{ + LockQueryType: types.ByDuration, + Denom: "stake", + Duration: time.Second, + }) + suite.Require().Equal(accum.String(), "0") + + suite.FundAcc(addr1, coins) + err = suite.App.LockupKeeper.Lock(suite.Ctx, lock, coins) + suite.Require().NoError(err) + + // check accumulation store + accum = suite.App.LockupKeeper.GetPeriodLocksAccumulation(suite.Ctx, types.QueryCondition{ + LockQueryType: types.ByDuration, + Denom: "stake", + Duration: time.Second, + }) + suite.Require().Equal(accum.String(), "10") + + balance := suite.App.BankKeeper.GetBalance(suite.Ctx, addr1, "stake") + suite.Require().Equal(sdk.ZeroInt(), balance.Amount) + + acc := suite.App.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) + balance = suite.App.BankKeeper.GetBalance(suite.Ctx, acc.GetAddress(), "stake") + suite.Require().Equal(sdk.NewInt(10), balance.Amount) +} + func (suite *KeeperTestSuite) AddTokensToLockForSynth() { suite.SetupTest() From 14ca3fdca41f52247c5638bb60836e5b9fc6a778 Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Tue, 5 Jul 2022 12:51:32 -0500 Subject: [PATCH 024/376] x/gamm: Rename CalcExitPoolShares to CalcExitPoolCoinsFromShares #1970 --- x/gamm/pool-models/balancer/pool.go | 4 ++-- x/gamm/pool-models/stableswap/pool.go | 4 ++-- x/gamm/types/pool.go | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index c7c9e4496e5..cad53d6f54d 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -762,7 +762,7 @@ func (p *Pool) calcJoinSingleAssetTokensIn(tokensIn sdk.Coins, totalShares sdk.I } func (p *Pool) ExitPool(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { - exitingCoins, err = p.CalcExitPoolShares(ctx, exitingShares, exitFee) + exitingCoins, err = p.CalcExitPoolCoinsFromShares(ctx, exitingShares, exitFee) if err != nil { return sdk.Coins{}, err } @@ -788,7 +788,7 @@ func (p *Pool) exitPool(ctx sdk.Context, exitingCoins sdk.Coins, exitingShares s return nil } -func (p *Pool) CalcExitPoolShares(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) { +func (p *Pool) CalcExitPoolCoinsFromShares(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) { return cfmm_common.CalcExitPool(ctx, p, exitingShares, exitFee) } diff --git a/x/gamm/pool-models/stableswap/pool.go b/x/gamm/pool-models/stableswap/pool.go index e94b1ebb3f3..d1e8f1499cf 100644 --- a/x/gamm/pool-models/stableswap/pool.go +++ b/x/gamm/pool-models/stableswap/pool.go @@ -235,7 +235,7 @@ func (pa *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) ( } func (pa *Pool) ExitPool(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { - exitingCoins, err = pa.CalcExitPoolShares(ctx, exitingShares, exitFee) + exitingCoins, err = pa.CalcExitPoolCoinsFromShares(ctx, exitingShares, exitFee) if err != nil { return sdk.Coins{}, err } @@ -246,7 +246,7 @@ func (pa *Pool) ExitPool(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec return exitingCoins, nil } -func (pa Pool) CalcExitPoolShares(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { +func (pa Pool) CalcExitPoolCoinsFromShares(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { return cfmm_common.CalcExitPool(ctx, &pa, exitingShares, exitFee) } diff --git a/x/gamm/types/pool.go b/x/gamm/types/pool.go index a44f39e712b..00b586dfadf 100644 --- a/x/gamm/types/pool.go +++ b/x/gamm/types/pool.go @@ -67,9 +67,9 @@ type PoolI interface { // and returns the number of coins that are being returned. // This mutates the pool and state. ExitPool(ctx sdk.Context, numShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) - // CalcExitPoolShares returns how many coins ExitPool would return on these arguments. + // CalcExitPoolCoinsFromShares returns how many coins ExitPool would return on these arguments. // This does not mutate the pool, or state. - CalcExitPoolShares(ctx sdk.Context, numShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) + CalcExitPoolCoinsFromShares(ctx sdk.Context, numShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) // PokePool determines if a pool's weights need to be updated and updates // them if so. From c35d886727e9138ae849c4c3c9af3fcedaab97a9 Mon Sep 17 00:00:00 2001 From: Hieu Vu <72878483+hieuvubk@users.noreply.github.com> Date: Wed, 6 Jul 2022 01:06:05 +0700 Subject: [PATCH 025/376] Clean up pool asset (#1967) --- x/gamm/pool-models/balancer/msgs.go | 2 +- x/gamm/pool-models/balancer/pool.go | 14 +++---- x/gamm/pool-models/balancer/pool_asset.go | 47 +++++++++------------- x/gamm/pool-models/balancer/pool_params.go | 4 +- 4 files changed, 28 insertions(+), 39 deletions(-) diff --git a/x/gamm/pool-models/balancer/msgs.go b/x/gamm/pool-models/balancer/msgs.go index f5012b34ed5..400fa26f93a 100644 --- a/x/gamm/pool-models/balancer/msgs.go +++ b/x/gamm/pool-models/balancer/msgs.go @@ -38,7 +38,7 @@ func (msg MsgCreateBalancerPool) ValidateBasic() error { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) } - err = ValidateUserSpecifiedPoolAssets(msg.PoolAssets) + err = validateUserSpecifiedPoolAssets(msg.PoolAssets) if err != nil { return err } diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index cad53d6f54d..45764549043 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -90,7 +90,7 @@ func (pa Pool) GetSwapFee(_ sdk.Context) sdk.Dec { } func (pa Pool) GetTotalPoolLiquidity(_ sdk.Context) sdk.Coins { - return PoolAssetsCoins(pa.PoolAssets) + return poolAssetsCoins(pa.PoolAssets) } func (pa Pool) GetExitFee(_ sdk.Context) sdk.Dec { @@ -140,7 +140,7 @@ func (pa *Pool) SetInitialPoolAssets(PoolAssets []PoolAsset) error { return fmt.Errorf("can't add the zero or negative balance of token") } - err := asset.ValidateWeight() + err := asset.validateWeight() if err != nil { return err } @@ -160,7 +160,7 @@ func (pa *Pool) SetInitialPoolAssets(PoolAssets []PoolAsset) error { // Furthermore, consider changing the underlying data type to allow in-place modification if the // number of PoolAssets is expected to be large. pa.PoolAssets = append(pa.PoolAssets, scaledPoolAssets...) - SortPoolAssetsByDenom(pa.PoolAssets) + sortPoolAssetsByDenom(pa.PoolAssets) pa.TotalWeight = newTotalWeight @@ -183,7 +183,7 @@ func (pa *Pool) setInitialPoolParams(params PoolParams, sortedAssets []PoolAsset // sort target weights by denom targetPoolWeights := params.SmoothWeightChangeParams.TargetPoolWeights - SortPoolAssetsByDenom(targetPoolWeights) + sortPoolAssetsByDenom(targetPoolWeights) // scale target pool weights by GuaranteedWeightPrecision for i, v := range targetPoolWeights { @@ -246,8 +246,8 @@ func (pa Pool) getPoolAssetAndIndex(denom string) (int, PoolAsset, error) { func (p Pool) parsePoolAssetsByDenoms(tokenADenom, tokenBDenom string) ( Aasset PoolAsset, Basset PoolAsset, err error, ) { - Aasset, found1 := GetPoolAssetByDenom(p.PoolAssets, tokenADenom) - Basset, found2 := GetPoolAssetByDenom(p.PoolAssets, tokenBDenom) + Aasset, found1 := getPoolAssetByDenom(p.PoolAssets, tokenADenom) + Basset, found2 := getPoolAssetByDenom(p.PoolAssets, tokenBDenom) if !(found1 && found2) { return Aasset, Basset, errors.New("one of the provided pool denoms does not exist in pool") } @@ -375,7 +375,7 @@ func (pa *Pool) updateAllWeights(newWeights []PoolAsset) { "expected new weights' %vth asset to be %v, got %v", i, asset.Token.Denom, newWeights[i].Token.Denom)) } - err := newWeights[i].ValidateWeight() + err := newWeights[i].validateWeight() if err != nil { panic("updateAllWeights: Tried to set an invalid weight") } diff --git a/x/gamm/pool-models/balancer/pool_asset.go b/x/gamm/pool-models/balancer/pool_asset.go index 43729f9d409..a15fdd9bb52 100644 --- a/x/gamm/pool-models/balancer/pool_asset.go +++ b/x/gamm/pool-models/balancer/pool_asset.go @@ -12,25 +12,23 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// Validates a pool asset, to check if it has a valid weight. -func (asset PoolAsset) ValidateWeight() error { +type poolAssetPretty struct { + Token sdk.Coin `json:"token" yaml:"token"` + Weight sdk.Dec `json:"weight" yaml:"weight"` +} + +// validates a pool asset, to check if it has a valid weight. +func (asset PoolAsset) validateWeight() error { if asset.Weight.LTE(sdk.ZeroInt()) { return fmt.Errorf("a token's weight in the pool must be greater than 0") } - // TODO: Choose a value that is too large for weights - // if asset.Weight >= (1 << 32) { - // return fmt.Errorf("a token's weight in the pool must be less than 2^32") - // } + // TODO: add validation for asset weight overflow: + // https://github.com/osmosis-labs/osmosis/issues/1958 return nil } -type poolAssetPretty struct { - Token sdk.Coin `json:"token" yaml:"token"` - Weight sdk.Dec `json:"weight" yaml:"weight"` -} - func (asset PoolAsset) prettify() poolAssetPretty { return poolAssetPretty{ Weight: sdk.NewDecFromInt(asset.Weight).QuoInt64(GuaranteedWeightPrecision), @@ -38,14 +36,6 @@ func (asset PoolAsset) prettify() poolAssetPretty { } } -// D: at name -// func (asset poolAssetPretty) uglify() PoolAsset { -// return PoolAsset{ -// Weight: asset.Weight.MulInt64(GuaranteedWeightPrecision).RoundInt(), -// Token: asset.Token, -// } -// } - // MarshalYAML returns the YAML representation of a PoolAsset. // This is assumed to not be called on a stand-alone instance, so it removes the first marshalled line. func (pa PoolAsset) MarshalYAML() (interface{}, error) { @@ -57,18 +47,18 @@ func (pa PoolAsset) MarshalYAML() (interface{}, error) { return s, nil } -// SortPoolAssetsOutOfPlaceByDenom sorts pool assets in place, by weight +// sortPoolAssetsOutOfPlaceByDenom sorts pool assets in place, by weight // Doesn't deep copy the underlying weights, but it does place the assets // into a new slice. -func SortPoolAssetsOutOfPlaceByDenom(assets []PoolAsset) []PoolAsset { +func sortPoolAssetsOutOfPlaceByDenom(assets []PoolAsset) []PoolAsset { assets_copy := make([]PoolAsset, len(assets)) copy(assets_copy, assets) - SortPoolAssetsByDenom(assets_copy) + sortPoolAssetsByDenom(assets_copy) return assets_copy } -// SortPoolAssetsByDenom sorts pool assets in place, by weight. -func SortPoolAssetsByDenom(assets []PoolAsset) { +// sortPoolAssetsByDenom sorts pool assets in place, by weight. +func sortPoolAssetsByDenom(assets []PoolAsset) { sort.Slice(assets, func(i, j int) bool { PoolAssetA := assets[i] PoolAssetB := assets[j] @@ -77,13 +67,12 @@ func SortPoolAssetsByDenom(assets []PoolAsset) { }) } -func ValidateUserSpecifiedPoolAssets(assets []PoolAsset) error { +func validateUserSpecifiedPoolAssets(assets []PoolAsset) error { // The pool must be swapping between at least two assets if len(assets) < 2 { return types.ErrTooFewPoolAssets } - // TODO: Add the limit of binding token to the pool params? if len(assets) > 8 { return sdkerrors.Wrapf(types.ErrTooManyPoolAssets, "%d", len(assets)) } @@ -106,8 +95,8 @@ func ValidateUserSpecifiedPoolAssets(assets []PoolAsset) error { return nil } -// PoolAssetsCoins returns all the coins corresponding to a slice of pool assets. -func PoolAssetsCoins(assets []PoolAsset) sdk.Coins { +// poolAssetsCoins returns all the coins corresponding to a slice of pool assets. +func poolAssetsCoins(assets []PoolAsset) sdk.Coins { coins := sdk.Coins{} for _, asset := range assets { coins = coins.Add(asset.Token) @@ -115,7 +104,7 @@ func PoolAssetsCoins(assets []PoolAsset) sdk.Coins { return coins } -func GetPoolAssetByDenom(assets []PoolAsset, denom string) (PoolAsset, bool) { +func getPoolAssetByDenom(assets []PoolAsset, denom string) (PoolAsset, bool) { for _, asset := range assets { if asset.Token.Denom == denom { return asset, true diff --git a/x/gamm/pool-models/balancer/pool_params.go b/x/gamm/pool-models/balancer/pool_params.go index 58c5bd82336..1d25fe33402 100644 --- a/x/gamm/pool-models/balancer/pool_params.go +++ b/x/gamm/pool-models/balancer/pool_params.go @@ -47,8 +47,8 @@ func (params PoolParams) Validate(poolWeights []PoolAsset) error { } } // Ensure that all the target weight denoms are same as pool asset weights - sortedTargetPoolWeights := SortPoolAssetsOutOfPlaceByDenom(targetWeights) - sortedPoolWeights := SortPoolAssetsOutOfPlaceByDenom(poolWeights) + sortedTargetPoolWeights := sortPoolAssetsOutOfPlaceByDenom(targetWeights) + sortedPoolWeights := sortPoolAssetsOutOfPlaceByDenom(poolWeights) for i, v := range sortedPoolWeights { if sortedTargetPoolWeights[i].Token.Denom != v.Token.Denom { return types.ErrPoolParamsInvalidDenom From 49d632f7717408fd4fe18795fbd3c07103e041df Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Tue, 5 Jul 2022 13:07:05 -0500 Subject: [PATCH 026/376] x/gamm: Add check for correct input asset denoms to CalcJoinPoolShares (#1931) --- CHANGELOG.md | 1 + x/gamm/pool-models/balancer/amm.go | 2 +- x/gamm/pool-models/balancer/pool.go | 9 +++++++++ x/superfluid/keeper/grpc_query.go | 3 ++- 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5af33dbbffe..b8b3207a9a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,6 +71,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [1716](https://github.com/osmosis-labs/osmosis/pull/1716) Fix secondary over-LP shares bug with uneven swap amounts in `CalcJoinPoolShares`. * [1759](https://github.com/osmosis-labs/osmosis/pull/1759) Fix pagination filter in incentives query. * [1698](https://github.com/osmosis-labs/osmosis/pull/1698) Register wasm snapshotter extension. +* [1931](https://github.com/osmosis-labs/osmosis/pull/1931) Add explicit check for input denoms to `CalcJoinPoolShares` ## [v9.0.0 - Nitrogen](https://github.com/osmosis-labs/osmosis/releases/tag/v9.0.0) diff --git a/x/gamm/pool-models/balancer/amm.go b/x/gamm/pool-models/balancer/amm.go index cd05a5c3ef6..a574cef411d 100644 --- a/x/gamm/pool-models/balancer/amm.go +++ b/x/gamm/pool-models/balancer/amm.go @@ -161,7 +161,7 @@ func getPoolAssetsByDenom(poolAssets []PoolAsset) (map[string]PoolAsset, error) // updateIntermediaryPoolAssetsLiquidity updates poolAssetsByDenom with liquidity. // -// all liqidity coins must exist in poolAssetsByDenom. Returns error, if not. +// all liquidity coins must exist in poolAssetsByDenom. Returns error, if not. // // This is a helper function that is useful for updating the pool asset amounts // as an intermediary step in a multi-join methods such as CalcJoinPoolShares. diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index 45764549043..16c33bccb36 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -24,6 +24,7 @@ const ( errMsgFormatFailedInterimLiquidityUpdate = "failed to update interim liquidity - pool asset %s does not exist" errMsgFormatRepeatingPoolAssetsNotAllowed = "repeating pool assets not allowed, found %s" errMsgFormatNoPoolAssetFound = "can't find the PoolAsset (%s)" + errMsgFormatInvalidInputDenoms = "input denoms must already exist in the pool (%s)" ) var ( @@ -685,6 +686,14 @@ func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee s return sdk.ZeroInt(), sdk.NewCoins(), err } + // check to make sure the input denoms exist in the pool + for _, coin := range tokensIn { + _, ok := poolAssetsByDenom[coin.Denom] + if !ok { + return sdk.ZeroInt(), sdk.NewCoins(), fmt.Errorf(errMsgFormatInvalidInputDenoms, coin.Denom) + } + } + totalShares := p.GetTotalShares() if tokensIn.Len() == 1 { // 2) Single token provided, so do single asset join and exit. diff --git a/x/superfluid/keeper/grpc_query.go b/x/superfluid/keeper/grpc_query.go index 593b5d8074c..117b3741441 100644 --- a/x/superfluid/keeper/grpc_query.go +++ b/x/superfluid/keeper/grpc_query.go @@ -440,7 +440,8 @@ func (q Querier) TotalDelegationByDelegator(goCtx context.Context, req *types.Qu } superfluidDelegationResp, err := q.SuperfluidDelegationsByDelegator(goCtx, &types.SuperfluidDelegationsByDelegatorRequest{ - DelegatorAddress: req.DelegatorAddress}) + DelegatorAddress: req.DelegatorAddress, + }) if err != nil { return nil, err } From 298d7cf5e4c7257a49de2fba0d504d519503e3b9 Mon Sep 17 00:00:00 2001 From: Sishir Giri Date: Tue, 5 Jul 2022 12:18:20 -0700 Subject: [PATCH 027/376] test/devux: helper function for assertions conditional on panics (#1964) * test: helper function for assertions conditional on panics * added devs comments * matts comment --- osmoutils/test_helpers.go | 18 ++++++++++++++++++ x/gamm/pool-models/balancer/pool_suite_test.go | 3 ++- x/gamm/pool-models/balancer/pool_test.go | 2 +- x/gamm/pool-models/balancer/util_test.go | 10 ---------- x/mint/keeper/genesis_test.go | 9 ++------- 5 files changed, 23 insertions(+), 19 deletions(-) create mode 100644 osmoutils/test_helpers.go diff --git a/osmoutils/test_helpers.go b/osmoutils/test_helpers.go new file mode 100644 index 00000000000..a331ce00c3a --- /dev/null +++ b/osmoutils/test_helpers.go @@ -0,0 +1,18 @@ +package osmoutils + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// ConditionalPanic checks if expectPanic is true, asserts that sut (system under test) +// panics. If expectPanic is false, asserts that sut does not panic. +// returns true if sut panics and false it it does not +func ConditionalPanic(t *testing.T, expectPanic bool, sut func()) { + if expectPanic { + require.Panics(t, sut) + return + } + require.NotPanics(t, sut) +} diff --git a/x/gamm/pool-models/balancer/pool_suite_test.go b/x/gamm/pool-models/balancer/pool_suite_test.go index afd071d0acb..851aa185f0e 100644 --- a/x/gamm/pool-models/balancer/pool_suite_test.go +++ b/x/gamm/pool-models/balancer/pool_suite_test.go @@ -13,6 +13,7 @@ import ( "github.com/osmosis-labs/osmosis/v7/app/apptesting" v10 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v10" + "github.com/osmosis-labs/osmosis/v7/osmoutils" "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) @@ -720,7 +721,7 @@ func (suite *KeeperTestSuite) TestCalcJoinPoolShares() { require.True(t, ok) assertPoolStateNotModified(t, balancerPool, func() { - assertPanic(t, tc.expectPanic, sut) + osmoutils.ConditionalPanic(t, tc.expectPanic, sut) }) }) } diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go index 466a93fc17d..1bafc576d39 100644 --- a/x/gamm/pool-models/balancer/pool_test.go +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -202,7 +202,7 @@ func TestCalcSingleAssetJoin(t *testing.T) { } assertPoolStateNotModified(t, balancerPool, func() { - assertPanic(t, tc.expectPanic, sut) + osmoutils.ConditionalPanic(t, tc.expectPanic, sut) }) }) } diff --git a/x/gamm/pool-models/balancer/util_test.go b/x/gamm/pool-models/balancer/util_test.go index 8a6f7f0afb2..c5e8405b696 100644 --- a/x/gamm/pool-models/balancer/util_test.go +++ b/x/gamm/pool-models/balancer/util_test.go @@ -76,13 +76,3 @@ func assertPoolStateNotModified(t *testing.T, pool *balancer.Pool, sut func()) { require.Equal(t, oldLiquidity, newLiquidity) require.Equal(t, oldShares, newShares) } - -// assertPanic if expectPanic is true, asserts that sut (system under test) -// panics. If expectPanic is false, asserts that sut does not panic. -func assertPanic(t *testing.T, expectPanic bool, sut func()) { - if expectPanic { - require.Panics(t, sut) - } else { - require.NotPanics(t, sut) - } -} diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index 7aa8ddcf01f..72a29ba8b9c 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -7,6 +7,7 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/suite" + "github.com/osmosis-labs/osmosis/v7/osmoutils" "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" "github.com/osmosis-labs/osmosis/v7/x/mint/types" ) @@ -111,17 +112,11 @@ func (suite *KeeperTestSuite) TestMintInitGenesis() { originalVestingCoins := bankKeeper.GetBalance(ctx, developerAccount, tc.mintDenom) // Test. + osmoutils.ConditionalPanic(suite.T(), tc.expectPanic, func() { mintKeeper.InitGenesis(ctx, tc.mintGenesis) }) if tc.expectPanic { - suite.Panics(func() { - mintKeeper.InitGenesis(ctx, tc.mintGenesis) - }) return } - suite.NotPanics(func() { - mintKeeper.InitGenesis(ctx, tc.mintGenesis) - }) - // Assertions. // Module account was created. From e398235773d838f07018a95d99ee7ed8f791c820 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 5 Jul 2022 15:31:20 -0400 Subject: [PATCH 028/376] lint: enable stylecheck (#1960) * lint: stylecheck * merge conflict * pool asset lint --- .golangci.yml | 5 +- app/apptesting/gamm.go | 52 +++---- app/apptesting/test_suite.go | 11 +- store/node.go | 4 +- x/gamm/pool-models/balancer/marshal.go | 36 ++--- x/gamm/pool-models/balancer/pool.go | 146 ++++++++++---------- x/gamm/pool-models/balancer/pool_asset.go | 10 +- x/gamm/pool-models/stableswap/amm.go | 32 ++--- x/gamm/pool-models/stableswap/pool.go | 124 ++++++++--------- x/incentives/client/cli/tx.go | 5 +- x/pool-incentives/types/expected_keepers.go | 3 +- x/tokenfactory/keeper/createdenom.go | 4 +- x/txfees/keeper/feedecorator.go | 2 +- x/txfees/types/options.go | 3 +- 14 files changed, 220 insertions(+), 217 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index eae40af7d2e..771ce0d3685 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -70,7 +70,7 @@ linters: # - sqlclosecheck <- needs go 1.18 support # - staticcheck <- later # - structcheck <- later -# - stylecheck <- enable later, atriggers on underscores in variable names and on poolId + - stylecheck # replacement of golint, subset of staticcheck binary. # - tagliatelle <- disabled for defying cosmos idiom - tenv - testpackage @@ -102,5 +102,8 @@ issues: # across its files, once stableswap is fully complete. - unused - deadcode + - linters: + - stylecheck + text: "ST1003:" # requires identifiers with "id" to be "ID". max-issues-per-linter: 10000 max-same-issues: 10000 diff --git a/app/apptesting/gamm.go b/app/apptesting/gamm.go index d431e70399d..556efb75358 100644 --- a/app/apptesting/gamm.go +++ b/app/apptesting/gamm.go @@ -15,8 +15,8 @@ var DefaultAcctFunds sdk.Coins = sdk.NewCoins( ) // Returns a Univ2 pool with the initial liquidity being the provided balances -func (suite *KeeperTestHelper) PrepareUni2PoolWithAssets(asset1, asset2 sdk.Coin) uint64 { - return suite.PrepareBalancerPoolWithPoolAsset( +func (s *KeeperTestHelper) PrepareUni2PoolWithAssets(asset1, asset2 sdk.Coin) uint64 { + return s.PrepareBalancerPoolWithPoolAsset( []balancer.PoolAsset{ { Weight: sdk.NewInt(1), @@ -30,30 +30,30 @@ func (suite *KeeperTestHelper) PrepareUni2PoolWithAssets(asset1, asset2 sdk.Coin ) } -func (suite *KeeperTestHelper) PrepareBalancerPool() uint64 { - poolId := suite.PrepareBalancerPoolWithPoolParams(balancer.PoolParams{ +func (s *KeeperTestHelper) PrepareBalancerPool() uint64 { + poolId := s.PrepareBalancerPoolWithPoolParams(balancer.PoolParams{ SwapFee: sdk.NewDec(0), ExitFee: sdk.NewDec(0), }) - spotPrice, err := suite.App.GAMMKeeper.CalculateSpotPrice(suite.Ctx, poolId, "foo", "bar") - suite.NoError(err) - suite.Equal(sdk.NewDec(2).String(), spotPrice.String()) - spotPrice, err = suite.App.GAMMKeeper.CalculateSpotPrice(suite.Ctx, poolId, "bar", "baz") - suite.NoError(err) - suite.Equal(sdk.NewDecWithPrec(15, 1).String(), spotPrice.String()) - spotPrice, err = suite.App.GAMMKeeper.CalculateSpotPrice(suite.Ctx, poolId, "baz", "foo") - suite.NoError(err) - s := sdk.NewDec(1).Quo(sdk.NewDec(3)) - sp := s.MulInt(gammtypes.SigFigs).RoundInt().ToDec().QuoInt(gammtypes.SigFigs) - suite.Equal(sp.String(), spotPrice.String()) + spotPrice, err := s.App.GAMMKeeper.CalculateSpotPrice(s.Ctx, poolId, "foo", "bar") + s.NoError(err) + s.Equal(sdk.NewDec(2).String(), spotPrice.String()) + spotPrice, err = s.App.GAMMKeeper.CalculateSpotPrice(s.Ctx, poolId, "bar", "baz") + s.NoError(err) + s.Equal(sdk.NewDecWithPrec(15, 1).String(), spotPrice.String()) + spotPrice, err = s.App.GAMMKeeper.CalculateSpotPrice(s.Ctx, poolId, "baz", "foo") + s.NoError(err) + oneThird := sdk.NewDec(1).Quo(sdk.NewDec(3)) + sp := oneThird.MulInt(gammtypes.SigFigs).RoundInt().ToDec().QuoInt(gammtypes.SigFigs) + s.Equal(sp.String(), spotPrice.String()) return poolId } -func (suite *KeeperTestHelper) PrepareBalancerPoolWithPoolParams(poolParams balancer.PoolParams) uint64 { +func (s *KeeperTestHelper) PrepareBalancerPoolWithPoolParams(poolParams balancer.PoolParams) uint64 { // Mint some assets to the account. - suite.FundAcc(suite.TestAccs[0], DefaultAcctFunds) + s.FundAcc(s.TestAccs[0], DefaultAcctFunds) poolAssets := []balancer.PoolAsset{ { @@ -69,27 +69,27 @@ func (suite *KeeperTestHelper) PrepareBalancerPoolWithPoolParams(poolParams bala Token: sdk.NewCoin("baz", sdk.NewInt(5000000)), }, } - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], poolParams, poolAssets, "") - poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, msg) - suite.NoError(err) + msg := balancer.NewMsgCreateBalancerPool(s.TestAccs[0], poolParams, poolAssets, "") + poolId, err := s.App.GAMMKeeper.CreatePool(s.Ctx, msg) + s.NoError(err) return poolId } -func (suite *KeeperTestHelper) PrepareBalancerPoolWithPoolAsset(assets []balancer.PoolAsset) uint64 { - suite.Require().Len(assets, 2) +func (s *KeeperTestHelper) PrepareBalancerPoolWithPoolAsset(assets []balancer.PoolAsset) uint64 { + s.Require().Len(assets, 2) // Add coins for pool creation fee + coins needed to mint balances fundCoins := sdk.Coins{sdk.NewCoin("uosmo", sdk.NewInt(10000000000))} for _, a := range assets { fundCoins = fundCoins.Add(a.Token) } - suite.FundAcc(suite.TestAccs[0], fundCoins) + s.FundAcc(s.TestAccs[0], fundCoins) - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + msg := balancer.NewMsgCreateBalancerPool(s.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.ZeroDec(), ExitFee: sdk.ZeroDec(), }, assets, "") - poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, msg) - suite.NoError(err) + poolId, err := s.App.GAMMKeeper.CreatePool(s.Ctx, msg) + s.NoError(err) return poolId } diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index a10e4d62039..a73be4ece5e 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -20,7 +20,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" @@ -42,7 +41,7 @@ type KeeperTestHelper struct { func (s *KeeperTestHelper) Setup() { s.App = app.Setup(false) - s.Ctx = s.App.BaseApp.NewContext(false, tmproto.Header{Height: 1, ChainID: "osmosis-1", Time: time.Now().UTC()}) + s.Ctx = s.App.BaseApp.NewContext(false, tmtypes.Header{Height: 1, ChainID: "osmosis-1", Time: time.Now().UTC()}) s.QueryHelper = &baseapp.QueryServiceTestHelper{ GRPCQueryRouter: s.App.GRPCQueryRouter(), Ctx: s.Ctx, @@ -138,7 +137,7 @@ func (s *KeeperTestHelper) BeginNewBlockWithProposer(executeNextEpoch bool, prop newBlockTime = endEpochTime.Add(time.Second) } - header := tmproto.Header{Height: s.Ctx.BlockHeight() + 1, Time: newBlockTime} + header := tmtypes.Header{Height: s.Ctx.BlockHeight() + 1, Time: newBlockTime} newCtx := s.Ctx.WithBlockTime(newBlockTime).WithBlockHeight(s.Ctx.BlockHeight() + 1) s.Ctx = newCtx lastCommitInfo := abci.LastCommitInfo{ @@ -200,16 +199,16 @@ func (s *KeeperTestHelper) SetupGammPoolsWithBondDenomMultiplier(multipliers []s defaultFutureGovernor = "" // pool assets - defaultFooAsset balancer.PoolAsset = balancer.PoolAsset{ + defaultFooAsset = balancer.PoolAsset{ Weight: sdk.NewInt(100), Token: sdk.NewCoin(bondDenom, uosmoAmount), } - defaultBarAsset balancer.PoolAsset = balancer.PoolAsset{ + defaultBarAsset = balancer.PoolAsset{ Weight: sdk.NewInt(100), Token: sdk.NewCoin(token, sdk.NewInt(10000)), } - poolAssets []balancer.PoolAsset = []balancer.PoolAsset{defaultFooAsset, defaultBarAsset} + poolAssets = []balancer.PoolAsset{defaultFooAsset, defaultBarAsset} ) poolParams := balancer.PoolParams{ diff --git a/store/node.go b/store/node.go index 47aa4336904..9be825c5b0f 100644 --- a/store/node.go +++ b/store/node.go @@ -238,8 +238,8 @@ func (node *Node) setAcc(idx int, acc sdk.Int) *Node { return node } -func (cs *Node) insert(idx int, c *Child) *Node { - arr := append(cs.Children[:idx], append([]*Child{c}, cs.Children[idx:]...)...) +func (node *Node) insert(idx int, c *Child) *Node { + arr := append(node.Children[:idx], append([]*Child{c}, node.Children[idx:]...)...) return NewNode(arr...) } diff --git a/x/gamm/pool-models/balancer/marshal.go b/x/gamm/pool-models/balancer/marshal.go index e967ef1ffec..c847affedbf 100644 --- a/x/gamm/pool-models/balancer/marshal.go +++ b/x/gamm/pool-models/balancer/marshal.go @@ -16,8 +16,8 @@ type balancerPoolPretty struct { PoolAssets []PoolAsset `json:"pool_assets" yaml:"pool_assets"` } -func (pa Pool) String() string { - out, err := pa.MarshalJSON() +func (p Pool) String() string { + out, err := p.MarshalJSON() if err != nil { panic(err) } @@ -25,39 +25,39 @@ func (pa Pool) String() string { } // MarshalJSON returns the JSON representation of a Pool. -func (pa Pool) MarshalJSON() ([]byte, error) { - accAddr, err := sdk.AccAddressFromBech32(pa.Address) +func (p Pool) MarshalJSON() ([]byte, error) { + accAddr, err := sdk.AccAddressFromBech32(p.Address) if err != nil { return nil, err } - decTotalWeight := sdk.NewDecFromInt(pa.TotalWeight) + decTotalWeight := sdk.NewDecFromInt(p.TotalWeight) return json.Marshal(balancerPoolPretty{ Address: accAddr, - Id: pa.Id, - PoolParams: pa.PoolParams, - FuturePoolGovernor: pa.FuturePoolGovernor, + Id: p.Id, + PoolParams: p.PoolParams, + FuturePoolGovernor: p.FuturePoolGovernor, TotalWeight: decTotalWeight, - TotalShares: pa.TotalShares, - PoolAssets: pa.PoolAssets, + TotalShares: p.TotalShares, + PoolAssets: p.PoolAssets, }) } // UnmarshalJSON unmarshals raw JSON bytes into a Pool. -func (pa *Pool) UnmarshalJSON(bz []byte) error { +func (p *Pool) UnmarshalJSON(bz []byte) error { var alias balancerPoolPretty if err := json.Unmarshal(bz, &alias); err != nil { return err } - pa.Address = alias.Address.String() - pa.Id = alias.Id - pa.PoolParams = alias.PoolParams - pa.FuturePoolGovernor = alias.FuturePoolGovernor - pa.TotalWeight = alias.TotalWeight.RoundInt() - pa.TotalShares = alias.TotalShares - pa.PoolAssets = alias.PoolAssets + p.Address = alias.Address.String() + p.Id = alias.Id + p.PoolParams = alias.PoolParams + p.FuturePoolGovernor = alias.FuturePoolGovernor + p.TotalWeight = alias.TotalWeight.RoundInt() + p.TotalShares = alias.TotalShares + p.PoolAssets = alias.PoolAssets return nil } diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index 16c33bccb36..2a34b982b48 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -74,48 +74,48 @@ func NewBalancerPool(poolId uint64, balancerPoolParams PoolParams, assets []Pool // GetAddress returns the address of a pool. // If the pool address is not bech32 valid, it returns an empty address. -func (pa Pool) GetAddress() sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(pa.Address) +func (p Pool) GetAddress() sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(p.Address) if err != nil { - panic(fmt.Sprintf("could not bech32 decode address of pool with id: %d", pa.GetId())) + panic(fmt.Sprintf("could not bech32 decode address of pool with id: %d", p.GetId())) } return addr } -func (pa Pool) GetId() uint64 { - return pa.Id +func (p Pool) GetId() uint64 { + return p.Id } -func (pa Pool) GetSwapFee(_ sdk.Context) sdk.Dec { - return pa.PoolParams.SwapFee +func (p Pool) GetSwapFee(_ sdk.Context) sdk.Dec { + return p.PoolParams.SwapFee } -func (pa Pool) GetTotalPoolLiquidity(_ sdk.Context) sdk.Coins { - return poolAssetsCoins(pa.PoolAssets) +func (p Pool) GetTotalPoolLiquidity(_ sdk.Context) sdk.Coins { + return poolAssetsCoins(p.PoolAssets) } -func (pa Pool) GetExitFee(_ sdk.Context) sdk.Dec { - return pa.PoolParams.ExitFee +func (p Pool) GetExitFee(_ sdk.Context) sdk.Dec { + return p.PoolParams.ExitFee } -func (pa Pool) GetPoolParams() PoolParams { - return pa.PoolParams +func (p Pool) GetPoolParams() PoolParams { + return p.PoolParams } -func (pa Pool) GetTotalWeight() sdk.Int { - return pa.TotalWeight +func (p Pool) GetTotalWeight() sdk.Int { + return p.TotalWeight } -func (pa Pool) GetTotalShares() sdk.Int { - return pa.TotalShares.Amount +func (p Pool) GetTotalShares() sdk.Int { + return p.TotalShares.Amount } -func (pa *Pool) AddTotalShares(amt sdk.Int) { - pa.TotalShares.Amount = pa.TotalShares.Amount.Add(amt) +func (p *Pool) AddTotalShares(amt sdk.Int) { + p.TotalShares.Amount = p.TotalShares.Amount.Add(amt) } -func (pa *Pool) SubTotalShares(amt sdk.Int) { - pa.TotalShares.Amount = pa.TotalShares.Amount.Sub(amt) +func (p *Pool) SubTotalShares(amt sdk.Int) { + p.TotalShares.Amount = p.TotalShares.Amount.Sub(amt) } // SetInitialPoolAssets sets the PoolAssets in the pool. It is only designed to @@ -126,13 +126,13 @@ func (pa *Pool) SubTotalShares(amt sdk.Int) { // for a PoolAsset by denomination. // TODO: Unify story for validation of []PoolAsset, some is here, some is in // CreatePool.ValidateBasic() -func (pa *Pool) SetInitialPoolAssets(PoolAssets []PoolAsset) error { +func (p *Pool) SetInitialPoolAssets(PoolAssets []PoolAsset) error { exists := make(map[string]bool) - for _, asset := range pa.PoolAssets { + for _, asset := range p.PoolAssets { exists[asset.Token.Denom] = true } - newTotalWeight := pa.TotalWeight + newTotalWeight := p.TotalWeight scaledPoolAssets := make([]PoolAsset, 0, len(PoolAssets)) // TODO: Refactor this into PoolAsset.validate() @@ -160,17 +160,17 @@ func (pa *Pool) SetInitialPoolAssets(PoolAssets []PoolAsset) error { // TODO: Change this to a more efficient sorted insert algorithm. // Furthermore, consider changing the underlying data type to allow in-place modification if the // number of PoolAssets is expected to be large. - pa.PoolAssets = append(pa.PoolAssets, scaledPoolAssets...) - sortPoolAssetsByDenom(pa.PoolAssets) + p.PoolAssets = append(p.PoolAssets, scaledPoolAssets...) + sortPoolAssetsByDenom(p.PoolAssets) - pa.TotalWeight = newTotalWeight + p.TotalWeight = newTotalWeight return nil } // setInitialPoolParams -func (pa *Pool) setInitialPoolParams(params PoolParams, sortedAssets []PoolAsset, curBlockTime time.Time) error { - pa.PoolParams = params +func (p *Pool) setInitialPoolParams(params PoolParams, sortedAssets []PoolAsset, curBlockTime time.Time) error { + p.PoolParams = params if params.SmoothWeightChangeParams != nil { // set initial assets initialWeights := make([]PoolAsset, len(sortedAssets)) @@ -192,7 +192,7 @@ func (pa *Pool) setInitialPoolParams(params PoolParams, sortedAssets []PoolAsset if err != nil { return err } - pa.PoolParams.SmoothWeightChangeParams.TargetPoolWeights[i] = PoolAsset{ + p.PoolParams.SmoothWeightChangeParams.TargetPoolWeights[i] = PoolAsset{ Weight: v.Weight.MulRaw(GuaranteedWeightPrecision), Token: v.Token, } @@ -211,37 +211,37 @@ func (pa *Pool) setInitialPoolParams(params PoolParams, sortedAssets []PoolAsset // GetPoolAssets returns the denom's PoolAsset, If the PoolAsset doesn't exist, will return error. // As above, it will search the denom's PoolAsset by using binary search. // So, it is important to make sure that the PoolAssets are sorted. -func (pa Pool) GetPoolAsset(denom string) (PoolAsset, error) { - _, asset, err := pa.getPoolAssetAndIndex(denom) +func (p Pool) GetPoolAsset(denom string) (PoolAsset, error) { + _, asset, err := p.getPoolAssetAndIndex(denom) return asset, err } // Returns a pool asset, and its index. If err != nil, then the index will be valid. -func (pa Pool) getPoolAssetAndIndex(denom string) (int, PoolAsset, error) { +func (p Pool) getPoolAssetAndIndex(denom string) (int, PoolAsset, error) { if denom == "" { return -1, PoolAsset{}, fmt.Errorf("you tried to find the PoolAsset with empty denom") } - if len(pa.PoolAssets) == 0 { + if len(p.PoolAssets) == 0 { return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) } - i := sort.Search(len(pa.PoolAssets), func(i int) bool { - PoolAssetA := pa.PoolAssets[i] + i := sort.Search(len(p.PoolAssets), func(i int) bool { + PoolAssetA := p.PoolAssets[i] compare := strings.Compare(PoolAssetA.Token.Denom, denom) return compare >= 0 }) - if i < 0 || i >= len(pa.PoolAssets) { + if i < 0 || i >= len(p.PoolAssets) { return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) } - if pa.PoolAssets[i].Token.Denom != denom { + if p.PoolAssets[i].Token.Denom != denom { return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) } - return i, pa.PoolAssets[i], nil + return i, p.PoolAssets[i], nil } func (p Pool) parsePoolAssetsByDenoms(tokenADenom, tokenBDenom string) ( @@ -283,9 +283,9 @@ func (p *Pool) IncreaseLiquidity(sharesOut sdk.Int, coinsIn sdk.Coins) { p.AddTotalShares(sharesOut) } -func (pa *Pool) UpdatePoolAssetBalance(coin sdk.Coin) error { +func (p *Pool) UpdatePoolAssetBalance(coin sdk.Coin) error { // Check that PoolAsset exists. - assetIndex, existingAsset, err := pa.getPoolAssetAndIndex(coin.Denom) + assetIndex, existingAsset, err := p.getPoolAssetAndIndex(coin.Denom) if err != nil { return err } @@ -296,11 +296,11 @@ func (pa *Pool) UpdatePoolAssetBalance(coin sdk.Coin) error { // Update the supply of the asset existingAsset.Token = coin - pa.PoolAssets[assetIndex] = existingAsset + p.PoolAssets[assetIndex] = existingAsset return nil } -func (pa *Pool) UpdatePoolAssetBalances(coins sdk.Coins) error { +func (p *Pool) UpdatePoolAssetBalances(coins sdk.Coins) error { // Ensures that there are no duplicate denoms, all denom's are valid, // and amount is > 0 err := coins.Validate() @@ -312,7 +312,7 @@ func (pa *Pool) UpdatePoolAssetBalances(coins sdk.Coins) error { // TODO: We may be able to make this log(|coins|) faster in how it // looks up denom -> Coin by doing a multi-search, // but as we don't anticipate |coins| to be large, we omit this. - err = pa.UpdatePoolAssetBalance(coin) + err = p.UpdatePoolAssetBalance(coin) if err != nil { return err } @@ -321,23 +321,23 @@ func (pa *Pool) UpdatePoolAssetBalances(coins sdk.Coins) error { return nil } -func (pa *Pool) addToPoolAssetBalances(coins sdk.Coins) error { +func (p *Pool) addToPoolAssetBalances(coins sdk.Coins) error { for _, coin := range coins { - i, poolAsset, err := pa.getPoolAssetAndIndex(coin.Denom) + i, poolAsset, err := p.getPoolAssetAndIndex(coin.Denom) if err != nil { return err } poolAsset.Token.Amount = poolAsset.Token.Amount.Add(coin.Amount) - pa.PoolAssets[i] = poolAsset + p.PoolAssets[i] = poolAsset } return nil } -func (pa Pool) GetPoolAssets(denoms ...string) ([]PoolAsset, error) { +func (p Pool) GetPoolAssets(denoms ...string) ([]PoolAsset, error) { result := make([]PoolAsset, 0, len(denoms)) for _, denom := range denoms { - PoolAsset, err := pa.GetPoolAsset(denom) + PoolAsset, err := p.GetPoolAsset(denom) if err != nil { return nil, err } @@ -348,9 +348,9 @@ func (pa Pool) GetPoolAssets(denoms ...string) ([]PoolAsset, error) { return result, nil } -func (pa Pool) GetAllPoolAssets() []PoolAsset { - copyslice := make([]PoolAsset, len(pa.PoolAssets)) - copy(copyslice, pa.PoolAssets) +func (p Pool) GetAllPoolAssets() []PoolAsset { + copyslice := make([]PoolAsset, len(p.PoolAssets)) + copy(copyslice, p.PoolAssets) return copyslice } @@ -365,12 +365,12 @@ func (pa Pool) GetAllPoolAssets() []PoolAsset { // TODO: (post-launch) If newWeights excludes an existing denomination, // remove the weight from the pool, and figure out something to do // with any remaining coin. -func (pa *Pool) updateAllWeights(newWeights []PoolAsset) { - if len(pa.PoolAssets) != len(newWeights) { +func (p *Pool) updateAllWeights(newWeights []PoolAsset) { + if len(p.PoolAssets) != len(newWeights) { panic("updateAllWeights called with invalid input, len(newWeights) != len(existingWeights)") } totalWeight := sdk.ZeroInt() - for i, asset := range pa.PoolAssets { + for i, asset := range p.PoolAssets { if asset.Token.Denom != newWeights[i].Token.Denom { panic(fmt.Sprintf("updateAllWeights called with invalid input, "+ "expected new weights' %vth asset to be %v, got %v", @@ -380,22 +380,22 @@ func (pa *Pool) updateAllWeights(newWeights []PoolAsset) { if err != nil { panic("updateAllWeights: Tried to set an invalid weight") } - pa.PoolAssets[i].Weight = newWeights[i].Weight - totalWeight = totalWeight.Add(pa.PoolAssets[i].Weight) + p.PoolAssets[i].Weight = newWeights[i].Weight + totalWeight = totalWeight.Add(p.PoolAssets[i].Weight) } - pa.TotalWeight = totalWeight + p.TotalWeight = totalWeight } // PokePool checks to see if the pool's token weights need to be updated, and // if so, does so. Currently doesn't do anything outside out LBPs. -func (pa *Pool) PokePool(blockTime time.Time) { +func (p *Pool) PokePool(blockTime time.Time) { // check if pool weights didn't change - poolWeightsChanging := pa.PoolParams.SmoothWeightChangeParams != nil + poolWeightsChanging := p.PoolParams.SmoothWeightChangeParams != nil if !poolWeightsChanging { return } - params := *pa.PoolParams.SmoothWeightChangeParams + params := *p.PoolParams.SmoothWeightChangeParams // The weights w(t) for the pool at time `t` is defined in one of three // possible ways: @@ -419,10 +419,10 @@ func (pa *Pool) PokePool(blockTime time.Time) { // // TODO: When we add support for adding new assets via this method, ensure // the new asset has some token sent with it. - pa.updateAllWeights(params.TargetPoolWeights) + p.updateAllWeights(params.TargetPoolWeights) // we've finished updating the weights, so reset the following fields - pa.PoolParams.SmoothWeightChangeParams = nil + p.PoolParams.SmoothWeightChangeParams = nil return default: @@ -434,7 +434,7 @@ func (pa *Pool) PokePool(blockTime time.Time) { // If the duration elapsed is equal to the total time, or a rounding error // makes it seem like it is, just set to target weight. if percentDurationElapsed.GTE(sdk.OneDec()) { - pa.updateAllWeights(params.TargetPoolWeights) + p.updateAllWeights(params.TargetPoolWeights) return } @@ -443,12 +443,12 @@ func (pa *Pool) PokePool(blockTime time.Time) { scaledDiff := poolAssetsMulDec(totalWeightsDiff, percentDurationElapsed) updatedWeights := addPoolAssetWeights(params.InitialPoolWeights, scaledDiff) - pa.updateAllWeights(updatedWeights) + p.updateAllWeights(updatedWeights) } } -func (pa Pool) GetTokenWeight(denom string) (sdk.Int, error) { - PoolAsset, err := pa.GetPoolAsset(denom) +func (p Pool) GetTokenWeight(denom string) (sdk.Int, error) { + PoolAsset, err := p.GetPoolAsset(denom) if err != nil { return sdk.Int{}, err } @@ -456,8 +456,8 @@ func (pa Pool) GetTokenWeight(denom string) (sdk.Int, error) { return PoolAsset.Weight, nil } -func (pa Pool) GetTokenBalance(denom string) (sdk.Int, error) { - PoolAsset, err := pa.GetPoolAsset(denom) +func (p Pool) GetTokenBalance(denom string) (sdk.Int, error) { + PoolAsset, err := p.GetPoolAsset(denom) if err != nil { return sdk.Int{}, err } @@ -465,11 +465,11 @@ func (pa Pool) GetTokenBalance(denom string) (sdk.Int, error) { return PoolAsset.Token.Amount, nil } -func (pa Pool) NumAssets() int { - return len(pa.PoolAssets) +func (p Pool) NumAssets() int { + return len(p.PoolAssets) } -func (pa Pool) IsActive(ctx sdk.Context) bool { +func (p Pool) IsActive(ctx sdk.Context) bool { return true } @@ -741,7 +741,7 @@ func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee s tokensJoined = tokensJoined.Add(newLiquidityFromRemaining...) if tokensJoined.IsAnyGT(tokensIn) { - return sdk.ZeroInt(), sdk.NewCoins(), errors.New("An error has occurred, more coins joined than token In") + return sdk.ZeroInt(), sdk.NewCoins(), errors.New("an error has occurred, more coins joined than token In") } return numShares, tokensJoined, nil diff --git a/x/gamm/pool-models/balancer/pool_asset.go b/x/gamm/pool-models/balancer/pool_asset.go index a15fdd9bb52..ecfc06411cc 100644 --- a/x/gamm/pool-models/balancer/pool_asset.go +++ b/x/gamm/pool-models/balancer/pool_asset.go @@ -18,8 +18,8 @@ type poolAssetPretty struct { } // validates a pool asset, to check if it has a valid weight. -func (asset PoolAsset) validateWeight() error { - if asset.Weight.LTE(sdk.ZeroInt()) { +func (pa PoolAsset) validateWeight() error { + if pa.Weight.LTE(sdk.ZeroInt()) { return fmt.Errorf("a token's weight in the pool must be greater than 0") } @@ -29,10 +29,10 @@ func (asset PoolAsset) validateWeight() error { return nil } -func (asset PoolAsset) prettify() poolAssetPretty { +func (pa PoolAsset) prettify() poolAssetPretty { return poolAssetPretty{ - Weight: sdk.NewDecFromInt(asset.Weight).QuoInt64(GuaranteedWeightPrecision), - Token: asset.Token, + Weight: sdk.NewDecFromInt(pa.Weight).QuoInt64(GuaranteedWeightPrecision), + Token: pa.Token, } } diff --git a/x/gamm/pool-models/stableswap/amm.go b/x/gamm/pool-models/stableswap/amm.go index cf65894f9af..7872d5d02fe 100644 --- a/x/gamm/pool-models/stableswap/amm.go +++ b/x/gamm/pool-models/stableswap/amm.go @@ -336,21 +336,21 @@ func spotPrice(baseReserve, quoteReserve sdk.Dec) sdk.Dec { } // returns outAmt as a decimal -func (pa *Pool) calcOutAmtGivenIn(tokenIn sdk.Coin, tokenOutDenom string, swapFee sdk.Dec) (sdk.Dec, error) { - reserves, err := pa.getScaledPoolAmts(tokenIn.Denom, tokenOutDenom) +func (p *Pool) calcOutAmtGivenIn(tokenIn sdk.Coin, tokenOutDenom string, swapFee sdk.Dec) (sdk.Dec, error) { + reserves, err := p.getScaledPoolAmts(tokenIn.Denom, tokenOutDenom) if err != nil { return sdk.Dec{}, err } tokenInSupply, tokenOutSupply := reserves[0], reserves[1] // We are solving for the amount of token out, hence x = tokenOutSupply, y = tokenInSupply cfmmOut := solveCfmm(tokenOutSupply, tokenInSupply, tokenIn.Amount.ToDec()) - outAmt := pa.getDescaledPoolAmt(tokenOutDenom, cfmmOut) + outAmt := p.getDescaledPoolAmt(tokenOutDenom, cfmmOut) return outAmt, nil } // returns inAmt as a decimal -func (pa *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, swapFee sdk.Dec) (sdk.Dec, error) { - reserves, err := pa.getScaledPoolAmts(tokenInDenom, tokenOut.Denom) +func (p *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, swapFee sdk.Dec) (sdk.Dec, error) { + reserves, err := p.getScaledPoolAmts(tokenInDenom, tokenOut.Denom) if err != nil { return sdk.Dec{}, err } @@ -358,46 +358,46 @@ func (pa *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, swapFe // We are solving for the amount of token in, cfmm(x,y) = cfmm(x + x_in, y - y_out) // x = tokenInSupply, y = tokenOutSupply, yIn = -tokenOutAmount cfmmIn := solveCfmm(tokenInSupply, tokenOutSupply, tokenOut.Amount.ToDec().Neg()) - inAmt := pa.getDescaledPoolAmt(tokenInDenom, cfmmIn.NegMut()) + inAmt := p.getDescaledPoolAmt(tokenInDenom, cfmmIn.NegMut()) return inAmt, nil } -func (pa *Pool) calcSingleAssetJoinShares(tokenIn sdk.Coin, swapFee sdk.Dec) (sdk.Int, error) { +func (p *Pool) calcSingleAssetJoinShares(tokenIn sdk.Coin, swapFee sdk.Dec) (sdk.Int, error) { poolWithAddedLiquidityAndShares := func(newLiquidity sdk.Coin, newShares sdk.Int) types.PoolI { - paCopy := pa.Copy() + paCopy := p.Copy() paCopy.updatePoolForJoin(sdk.NewCoins(tokenIn), newShares) return &paCopy } // TODO: Correctly handle swap fee - return cfmm_common.BinarySearchSingleAssetJoin(pa, tokenIn, poolWithAddedLiquidityAndShares) + return cfmm_common.BinarySearchSingleAssetJoin(p, tokenIn, poolWithAddedLiquidityAndShares) } // We can mutate pa here // TODO: some day switch this to a COW wrapped pa, for better perf -func (pa *Pool) joinPoolSharesInternal(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) { +func (p *Pool) joinPoolSharesInternal(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) { if len(tokensIn) == 1 { - numShares, err = pa.calcSingleAssetJoinShares(tokensIn[0], swapFee) + numShares, err = p.calcSingleAssetJoinShares(tokensIn[0], swapFee) newLiquidity = tokensIn return numShares, newLiquidity, err - } else if len(tokensIn) != pa.NumAssets() { + } else if len(tokensIn) != p.NumAssets() { return sdk.ZeroInt(), sdk.NewCoins(), errors.New( "stableswap pool only supports LP'ing with one asset, or all assets in pool") } // Add all exact coins we can (no swap). ctx arg doesn't matter for Stableswap - numShares, remCoins, err := cfmm_common.MaximalExactRatioJoin(pa, sdk.Context{}, tokensIn) + numShares, remCoins, err := cfmm_common.MaximalExactRatioJoin(p, sdk.Context{}, tokensIn) if err != nil { return sdk.ZeroInt(), sdk.NewCoins(), err } - pa.updatePoolForJoin(tokensIn.Sub(remCoins), numShares) + p.updatePoolForJoin(tokensIn.Sub(remCoins), numShares) for _, coin := range remCoins { // TODO: Perhaps add a method to skip if this is too small. - newShare, err := pa.calcSingleAssetJoinShares(coin, swapFee) + newShare, err := p.calcSingleAssetJoinShares(coin, swapFee) if err != nil { return sdk.ZeroInt(), sdk.NewCoins(), err } - pa.updatePoolForJoin(sdk.NewCoins(coin), newShare) + p.updatePoolForJoin(sdk.NewCoins(coin), newShare) numShares = numShares.Add(newShare) } diff --git a/x/gamm/pool-models/stableswap/pool.go b/x/gamm/pool-models/stableswap/pool.go index d1e8f1499cf..21959fce7e3 100644 --- a/x/gamm/pool-models/stableswap/pool.go +++ b/x/gamm/pool-models/stableswap/pool.go @@ -15,64 +15,64 @@ import ( var _ types.PoolI = &Pool{} -func (pa Pool) GetAddress() sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(pa.Address) +func (p Pool) GetAddress() sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(p.Address) if err != nil { - panic(fmt.Sprintf("could not bech32 decode address of pool with id: %d", pa.GetId())) + panic(fmt.Sprintf("could not bech32 decode address of pool with id: %d", p.GetId())) } return addr } -func (pa Pool) String() string { - out, err := json.Marshal(pa) +func (p Pool) String() string { + out, err := json.Marshal(p) if err != nil { panic(err) } return string(out) } -func (pa Pool) GetId() uint64 { - return pa.Id +func (p Pool) GetId() uint64 { + return p.Id } -func (pa Pool) GetSwapFee(ctx sdk.Context) sdk.Dec { - return pa.PoolParams.SwapFee +func (p Pool) GetSwapFee(ctx sdk.Context) sdk.Dec { + return p.PoolParams.SwapFee } -func (pa Pool) GetExitFee(ctx sdk.Context) sdk.Dec { - return pa.PoolParams.ExitFee +func (p Pool) GetExitFee(ctx sdk.Context) sdk.Dec { + return p.PoolParams.ExitFee } -func (pa Pool) IsActive(ctx sdk.Context) bool { +func (p Pool) IsActive(ctx sdk.Context) bool { return true } // Returns the coins in the pool owned by all LP shareholders -func (pa Pool) GetTotalPoolLiquidity(ctx sdk.Context) sdk.Coins { - return pa.PoolLiquidity +func (p Pool) GetTotalPoolLiquidity(ctx sdk.Context) sdk.Coins { + return p.PoolLiquidity } -func (pa Pool) GetTotalShares() sdk.Int { - return pa.TotalShares.Amount +func (p Pool) GetTotalShares() sdk.Int { + return p.TotalShares.Amount } -func (pa Pool) GetScalingFactors() []uint64 { - return pa.ScalingFactor +func (p Pool) GetScalingFactors() []uint64 { + return p.ScalingFactor } // CONTRACT: scaling factors follow the same index with pool liquidity denoms -func (pa Pool) GetScalingFactorByLiquidityIndex(liquidityIndex int) uint64 { - return pa.ScalingFactor[liquidityIndex] +func (p Pool) GetScalingFactorByLiquidityIndex(liquidityIndex int) uint64 { + return p.ScalingFactor[liquidityIndex] } -func (pa Pool) NumAssets() int { - return len(pa.PoolLiquidity) +func (p Pool) NumAssets() int { + return len(p.PoolLiquidity) } // returns pool liquidity of the provided denoms, in the same order the denoms were provided in -func (pa Pool) getPoolAmts(denoms ...string) ([]sdk.Int, error) { +func (p Pool) getPoolAmts(denoms ...string) ([]sdk.Int, error) { result := make([]sdk.Int, len(denoms)) - poolLiquidity := pa.PoolLiquidity + poolLiquidity := p.PoolLiquidity for i, d := range denoms { amt := poolLiquidity.AmountOf(d) if amt.IsZero() { @@ -84,10 +84,10 @@ func (pa Pool) getPoolAmts(denoms ...string) ([]sdk.Int, error) { } // getScaledPoolAmts returns scaled amount of pool liquidity based on each asset's precisions -func (pa Pool) getScaledPoolAmts(denoms ...string) ([]sdk.Dec, error) { +func (p Pool) getScaledPoolAmts(denoms ...string) ([]sdk.Dec, error) { result := make([]sdk.Dec, len(denoms)) - poolLiquidity := pa.PoolLiquidity - liquidityIndexes := pa.getLiquidityIndexMap() + poolLiquidity := p.PoolLiquidity + liquidityIndexes := p.getLiquidityIndexMap() for i, denom := range denoms { liquidityIndex := liquidityIndexes[denom] @@ -96,24 +96,24 @@ func (pa Pool) getScaledPoolAmts(denoms ...string) ([]sdk.Dec, error) { if amt.IsZero() { return []sdk.Dec{}, fmt.Errorf("denom %s does not exist in pool", denom) } - scalingFactor := pa.GetScalingFactorByLiquidityIndex(liquidityIndex) + scalingFactor := p.GetScalingFactorByLiquidityIndex(liquidityIndex) result[i] = amt.ToDec().QuoInt64Mut(int64(scalingFactor)) } return result, nil } // getDescaledPoolAmts gets descaled amount of given denom and amount -func (pa Pool) getDescaledPoolAmt(denom string, amount sdk.Dec) sdk.Dec { - liquidityIndexes := pa.getLiquidityIndexMap() +func (p Pool) getDescaledPoolAmt(denom string, amount sdk.Dec) sdk.Dec { + liquidityIndexes := p.getLiquidityIndexMap() liquidityIndex := liquidityIndexes[denom] - scalingFactor := pa.GetScalingFactorByLiquidityIndex(liquidityIndex) + scalingFactor := p.GetScalingFactorByLiquidityIndex(liquidityIndex) return amount.MulInt64(int64(scalingFactor)) } // getLiquidityIndexMap creates a map of denoms to its index in pool liquidity -func (pa Pool) getLiquidityIndexMap() map[string]int { - poolLiquidity := pa.PoolLiquidity +func (p Pool) getLiquidityIndexMap() map[string]int { + poolLiquidity := p.PoolLiquidity liquidityIndexMap := make(map[string]int, poolLiquidity.Len()) for i, coin := range poolLiquidity { liquidityIndexMap[coin.Denom] = i @@ -148,11 +148,11 @@ func (p *Pool) updatePoolForJoin(tokensIn sdk.Coins, newShares sdk.Int) { } // TODO: These should all get moved to amm.go -func (pa Pool) CalcOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (tokenOut sdk.Coin, err error) { +func (p Pool) CalcOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (tokenOut sdk.Coin, err error) { if tokenIn.Len() != 1 { return sdk.Coin{}, errors.New("stableswap CalcOutAmtGivenIn: tokenIn is of wrong length") } - outAmtDec, err := pa.calcOutAmtGivenIn(tokenIn[0], tokenOutDenom, swapFee) + outAmtDec, err := p.calcOutAmtGivenIn(tokenIn[0], tokenOutDenom, swapFee) if err != nil { return sdk.Coin{}, err } @@ -165,23 +165,23 @@ func (pa Pool) CalcOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDen return sdk.NewCoin(tokenOutDenom, tokenOutAmt), nil } -func (pa *Pool) SwapOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (tokenOut sdk.Coin, err error) { - tokenOut, err = pa.CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee) +func (p *Pool) SwapOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (tokenOut sdk.Coin, err error) { + tokenOut, err = p.CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee) if err != nil { return sdk.Coin{}, err } - pa.updatePoolLiquidityForSwap(tokenIn, sdk.NewCoins(tokenOut)) + p.updatePoolLiquidityForSwap(tokenIn, sdk.NewCoins(tokenOut)) return tokenOut, nil } -func (pa Pool) CalcInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) { +func (p Pool) CalcInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) { if tokenOut.Len() != 1 { return sdk.Coin{}, errors.New("stableswap CalcInAmtGivenOut: tokenOut is of wrong length") } // TODO: Refactor this later to handle scaling factors - amt, err := pa.calcInAmtGivenOut(tokenOut[0], tokenInDenom, swapFee) + amt, err := p.calcInAmtGivenOut(tokenOut[0], tokenInDenom, swapFee) if err != nil { return sdk.Coin{}, err } @@ -196,59 +196,59 @@ func (pa Pool) CalcInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDen return sdk.NewCoin(tokenInDenom, tokenInAmt), nil } -func (pa *Pool) SwapInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) { - tokenIn, err = pa.CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee) +func (p *Pool) SwapInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) { + tokenIn, err = p.CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee) if err != nil { return sdk.Coin{}, err } - pa.updatePoolLiquidityForSwap(sdk.NewCoins(tokenIn), tokenOut) + p.updatePoolLiquidityForSwap(sdk.NewCoins(tokenIn), tokenOut) return tokenIn, nil } -func (pa Pool) SpotPrice(ctx sdk.Context, baseAssetDenom string, quoteAssetDenom string) (sdk.Dec, error) { - reserves, err := pa.getScaledPoolAmts(baseAssetDenom, quoteAssetDenom) +func (p Pool) SpotPrice(ctx sdk.Context, baseAssetDenom string, quoteAssetDenom string) (sdk.Dec, error) { + reserves, err := p.getScaledPoolAmts(baseAssetDenom, quoteAssetDenom) if err != nil { return sdk.Dec{}, err } scaledSpotPrice := spotPrice(reserves[0], reserves[1]) - spotPrice := pa.getDescaledPoolAmt(baseAssetDenom, scaledSpotPrice) + spotPrice := p.getDescaledPoolAmt(baseAssetDenom, scaledSpotPrice) return spotPrice, nil } -func (pa Pool) Copy() Pool { - pa2 := pa - pa2.PoolLiquidity = sdk.NewCoins(pa.PoolLiquidity...) - return pa2 +func (p Pool) Copy() Pool { + p2 := p + p2.PoolLiquidity = sdk.NewCoins(p.PoolLiquidity...) + return p2 } -func (pa *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) { - paCopy := pa.Copy() - return paCopy.joinPoolSharesInternal(ctx, tokensIn, swapFee) +func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) { + pCopy := p.Copy() + return pCopy.joinPoolSharesInternal(ctx, tokensIn, swapFee) } -func (pa *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) { - numShares, _, err = pa.joinPoolSharesInternal(ctx, tokensIn, swapFee) +func (p *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) { + numShares, _, err = p.joinPoolSharesInternal(ctx, tokensIn, swapFee) return numShares, err } -func (pa *Pool) ExitPool(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { - exitingCoins, err = pa.CalcExitPoolCoinsFromShares(ctx, exitingShares, exitFee) +func (p *Pool) ExitPool(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { + exitingCoins, err = p.CalcExitPoolCoinsFromShares(ctx, exitingShares, exitFee) if err != nil { return sdk.Coins{}, err } - pa.TotalShares.Amount = pa.TotalShares.Amount.Sub(exitingShares) - pa.updatePoolLiquidityForExit(exitingCoins) + p.TotalShares.Amount = p.TotalShares.Amount.Sub(exitingShares) + p.updatePoolLiquidityForExit(exitingCoins) return exitingCoins, nil } -func (pa Pool) CalcExitPoolCoinsFromShares(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { - return cfmm_common.CalcExitPool(ctx, &pa, exitingShares, exitFee) +func (p Pool) CalcExitPoolCoinsFromShares(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) { + return cfmm_common.CalcExitPool(ctx, &p, exitingShares, exitFee) } // no-op for stableswap -func (pa *Pool) PokePool(blockTime time.Time) {} +func (p *Pool) PokePool(blockTime time.Time) {} diff --git a/x/incentives/client/cli/tx.go b/x/incentives/client/cli/tx.go index 1dfad7072dd..c2cfb9e4084 100644 --- a/x/incentives/client/cli/tx.go +++ b/x/incentives/client/cli/tx.go @@ -6,9 +6,10 @@ import ( "strconv" "time" + "github.com/spf13/cobra" + "github.com/osmosis-labs/osmosis/v7/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -66,7 +67,7 @@ func NewCreateGaugeCmd() *cobra.Command { } else if timeRFC, err := time.Parse(time.RFC3339, timeStr); err == nil { // RFC time startTime = timeRFC } else { // invalid input - return errors.New("Invalid start time format") + return errors.New("invalid start time format") } epochs, err := cmd.Flags().GetUint64(FlagEpochs) diff --git a/x/pool-incentives/types/expected_keepers.go b/x/pool-incentives/types/expected_keepers.go index bd6cf746ab4..ffdf807a0bc 100644 --- a/x/pool-incentives/types/expected_keepers.go +++ b/x/pool-incentives/types/expected_keepers.go @@ -9,7 +9,6 @@ import ( gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - types "github.com/osmosis-labs/osmosis/v7/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" ) @@ -33,7 +32,7 @@ type GAMMKeeper interface { type IncentivesKeeper interface { CreateGauge(ctx sdk.Context, isPerpetual bool, owner sdk.AccAddress, coins sdk.Coins, distrTo lockuptypes.QueryCondition, startTime time.Time, numEpochsPaidOver uint64) (uint64, error) GetGaugeByID(ctx sdk.Context, gaugeID uint64) (*incentivestypes.Gauge, error) - GetGauges(ctx sdk.Context) []types.Gauge + GetGauges(ctx sdk.Context) []incentivestypes.Gauge AddToGaugeRewards(ctx sdk.Context, owner sdk.AccAddress, coins sdk.Coins, gaugeID uint64) error } diff --git a/x/tokenfactory/keeper/createdenom.go b/x/tokenfactory/keeper/createdenom.go index 66e0374608c..f09181d4572 100644 --- a/x/tokenfactory/keeper/createdenom.go +++ b/x/tokenfactory/keeper/createdenom.go @@ -13,8 +13,8 @@ import ( func (k Keeper) CreateDenom(ctx sdk.Context, creatorAddr string, subdenom string) (newTokenDenom string, err error) { // Temporary check until IBC bug is sorted out if k.bankKeeper.HasSupply(ctx, subdenom) { - return "", fmt.Errorf("Temporary error until IBC bug is sorted out, " + - "can't create subdenoms that are the same as a native denom.") + return "", fmt.Errorf("temporary error until IBC bug is sorted out, " + + "can't create subdenoms that are the same as a native denom") } // Send creation fee to community pool diff --git a/x/txfees/keeper/feedecorator.go b/x/txfees/keeper/feedecorator.go index 950f224f47c..afb4b555f90 100644 --- a/x/txfees/keeper/feedecorator.go +++ b/x/txfees/keeper/feedecorator.go @@ -155,7 +155,7 @@ func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bo // checks to make sure the module account has been set to collect fees in base token if addr := dfd.ak.GetModuleAddress(types.FeeCollectorName); addr == nil { - return ctx, fmt.Errorf("Fee collector module account (%s) has not been set", types.FeeCollectorName) + return ctx, fmt.Errorf("fee collector module account (%s) has not been set", types.FeeCollectorName) } // checks to make sure a separate module account has been set to collect fees not in base token diff --git a/x/txfees/types/options.go b/x/txfees/types/options.go index f4e9f5c7c62..8527fb2cd1d 100644 --- a/x/txfees/types/options.go +++ b/x/txfees/types/options.go @@ -12,7 +12,8 @@ import ( // If Options are not set in a config somewhere, // use defaults to preserve functionality with old node software -// TODO: Bump after next minor version. (in 6.2+). +// DefaultMinGasPriceForArbitrageTx represents minimum gas price +// for arbitrage transactions. var DefaultMinGasPriceForArbitrageTx = sdk.ZeroDec() var ( From 1da14b8b7946b4f4aec011f1585c37d75078e777 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 5 Jul 2022 15:45:21 -0400 Subject: [PATCH 029/376] e2e: refactor initialization with single node logic (#1963) * e2e: refactor initialization with single node logic * lint and remove redundant getters from node * restore accidental change * rename init to InitChain * persistentPeers typo --- Makefile | 3 + tests/e2e/e2e_setup_test.go | 36 ++- tests/e2e/e2e_test.go | 9 +- tests/e2e/e2e_util_test.go | 4 +- tests/e2e/initialization/chain.go | 52 +---- tests/e2e/initialization/chain/main.go | 4 +- tests/e2e/initialization/config.go | 163 +++++--------- tests/e2e/initialization/export.go | 9 +- tests/e2e/initialization/init.go | 75 +++++++ tests/e2e/initialization/init_test.go | 143 ++++++++++++ tests/e2e/initialization/main.go | 20 -- .../initialization/{validator.go => node.go} | 206 ++++++++++++------ tests/e2e/initialization/node/main.go | 66 ++++++ 13 files changed, 531 insertions(+), 259 deletions(-) create mode 100644 tests/e2e/initialization/init.go create mode 100644 tests/e2e/initialization/init_test.go delete mode 100644 tests/e2e/initialization/main.go rename tests/e2e/initialization/{validator.go => node.go} (54%) create mode 100644 tests/e2e/initialization/node/main.go diff --git a/Makefile b/Makefile index 5c759929f7b..44f86d8786f 100644 --- a/Makefile +++ b/Makefile @@ -250,6 +250,9 @@ docker-build-debug: docker-build-e2e-init-chain: @docker build -t osmosis-e2e-init-chain:debug --build-arg E2E_SCRIPT_NAME=chain -f tests/e2e/initialization/init.Dockerfile . +docker-build-e2e-init-node: + @docker build -t osmosis-e2e-init-node:debug --build-arg E2E_SCRIPT_NAME=node -f tests/e2e/initialization/init.Dockerfile . + ############################################################################### ### Linting ### ############################################################################### diff --git a/tests/e2e/e2e_setup_test.go b/tests/e2e/e2e_setup_test.go index 1a1eb1a1cfd..6d3a7f1dd1f 100644 --- a/tests/e2e/e2e_setup_test.go +++ b/tests/e2e/e2e_setup_test.go @@ -33,7 +33,7 @@ type syncInfo struct { } type validatorConfig struct { - validator initialization.Validator + validator initialization.Node operatorAddress string } @@ -76,57 +76,71 @@ const ( var ( // whatever number of validator configs get posted here are how many validators that will spawn on chain A and B respectively - validatorConfigsChainA = []*initialization.ValidatorConfig{ + validatorConfigsChainA = []*initialization.NodeConfig{ { + Name: "prune-default-snapshot", Pruning: "default", PruningKeepRecent: "0", PruningInterval: "0", SnapshotInterval: 1500, SnapshotKeepRecent: 2, + IsValidator: true, }, { + Name: "prune-nothing-snapshot", Pruning: "nothing", PruningKeepRecent: "0", PruningInterval: "0", SnapshotInterval: 1500, SnapshotKeepRecent: 2, + IsValidator: true, }, { + Name: "prune-custom-10000-13-snapshot", Pruning: "custom", PruningKeepRecent: "10000", PruningInterval: "13", SnapshotInterval: 1500, SnapshotKeepRecent: 2, + IsValidator: true, }, { + Name: "prune-everything-no-snapshot", Pruning: "everything", PruningKeepRecent: "0", PruningInterval: "0", SnapshotInterval: 0, SnapshotKeepRecent: 0, + IsValidator: true, }, } - validatorConfigsChainB = []*initialization.ValidatorConfig{ + validatorConfigsChainB = []*initialization.NodeConfig{ { + Name: "prune-default-snapshot", Pruning: "default", PruningKeepRecent: "0", PruningInterval: "0", SnapshotInterval: 1500, SnapshotKeepRecent: 2, + IsValidator: true, }, { + Name: "prune-nothing-snapshot", Pruning: "nothing", PruningKeepRecent: "0", PruningInterval: "0", SnapshotInterval: 1500, SnapshotKeepRecent: 2, + IsValidator: true, }, { + Name: "prune-custom-snapshot", Pruning: "custom", PruningKeepRecent: "10000", PruningInterval: "13", SnapshotInterval: 1500, SnapshotKeepRecent: 2, + IsValidator: true, }, } ) @@ -363,7 +377,7 @@ func (s *IntegrationTestSuite) runIBCRelayer(chainA *chainConfig, chainB *chainC s.connectIBCChains(chainA, chainB) } -func (s *IntegrationTestSuite) configureChain(chainId string, validatorConfigs []*initialization.ValidatorConfig, skipValidatorIndexes map[int]struct{}) { +func (s *IntegrationTestSuite) configureChain(chainId string, validatorConfigs []*initialization.NodeConfig, skipValidatorIndexes map[int]struct{}) { s.T().Logf("starting e2e infrastructure for chain-id: %s", chainId) tmpDir, err := os.MkdirTemp("", "osmosis-e2e-testnet-") @@ -384,7 +398,7 @@ func (s *IntegrationTestSuite) configureChain(chainId string, validatorConfigs [ // via Docker. if s.skipUpgrade { - initializedChain, err := initialization.Init(chainId, tmpDir, validatorConfigs, time.Duration(newChainConfig.votingPeriod), s.forkHeight) + initializedChain, err := initialization.InitChain(chainId, tmpDir, validatorConfigs, time.Duration(newChainConfig.votingPeriod), s.forkHeight) s.Require().NoError(err) s.initializeChainConfig(&newChainConfig, initializedChain) return @@ -428,8 +442,8 @@ func (s *IntegrationTestSuite) initializeChainConfig(chainConfig *chainConfig, i chainConfig.meta.DataDir = initializedChain.ChainMeta.DataDir chainConfig.meta.Id = initializedChain.ChainMeta.Id - chainConfig.validators = make([]*validatorConfig, 0, len(initializedChain.Validators)) - for _, val := range initializedChain.Validators { + chainConfig.validators = make([]*validatorConfig, 0, len(initializedChain.Nodes)) + for _, val := range initializedChain.Nodes { chainConfig.validators = append(chainConfig.validators, &validatorConfig{validator: *val}) } @@ -569,8 +583,8 @@ func (s *IntegrationTestSuite) createPreUpgradeState() { s.sendIBC(chainB, chainA, chainA.validators[0].validator.PublicAddress, initialization.OsmoToken) s.sendIBC(chainA, chainB, chainB.validators[0].validator.PublicAddress, initialization.StakeToken) s.sendIBC(chainB, chainA, chainA.validators[0].validator.PublicAddress, initialization.StakeToken) - s.createPool(chainA, "pool1A.json") - s.createPool(chainB, "pool1B.json") + s.createPool(chainA, "pool1A.json", initialization.ValidatorWalletName) + s.createPool(chainB, "pool1B.json", initialization.ValidatorWalletName) } func (s *IntegrationTestSuite) runPostUpgradeTests() { @@ -585,6 +599,6 @@ func (s *IntegrationTestSuite) runPostUpgradeTests() { s.sendIBC(chainB, chainA, chainA.validators[0].validator.PublicAddress, initialization.OsmoToken) s.sendIBC(chainA, chainB, chainB.validators[0].validator.PublicAddress, initialization.StakeToken) s.sendIBC(chainB, chainA, chainA.validators[0].validator.PublicAddress, initialization.StakeToken) - s.createPool(chainA, "pool2A.json") - s.createPool(chainB, "pool2B.json") + s.createPool(chainA, "pool2A.json", initialization.ValidatorWalletName) + s.createPool(chainB, "pool2B.json", initialization.ValidatorWalletName) } diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index 864f611cc94..82d5fe1a26e 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -25,24 +25,25 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { // TODO: https://github.com/osmosis-labs/osmosis/issues/1843 s.T().Skip("Superfluid tests are broken when upgrade is skipped. To be fixed in #1843") } + const walletName = "superfluid-wallet" chainA := s.chainConfigs[0] s.submitSuperfluidProposal(chainA, "gamm/pool/1") s.depositProposal(chainA) s.voteProposal(chainA) - walletAddr := s.createWallet(chainA, 0, "wallet") + walletAddr := s.createWallet(chainA, 0, walletName) // send gamm tokens to validator's other wallet (non self-delegation wallet) s.sendTx(chainA, 0, "100000000000000000000gamm/pool/1", chainA.validators[0].validator.PublicAddress, walletAddr) // lock tokens from validator 0 on chain A - s.lockTokens(chainA, 0, "100000000000000000000gamm/pool/1", "240s", "wallet") + s.lockTokens(chainA, 0, "100000000000000000000gamm/pool/1", "240s", walletName) // superfluid delegate from validator 0 non self-delegation wallet to validator 1 on chain A - s.superfluidDelegate(chainA, chainA.validators[1].operatorAddress, "wallet") + s.superfluidDelegate(chainA, chainA.validators[1].operatorAddress, walletName) // create a text prop, deposit and vote yes s.submitTextProposal(chainA, "superfluid vote overwrite test") s.depositProposal(chainA) s.voteProposal(chainA) // set delegator vote to no - s.voteNoProposal(chainA, 0, "wallet") + s.voteNoProposal(chainA, 0, walletName) hostPort, err := s.containerManager.GetValidatorHostPort(chainA.meta.Id, 0, "1317/tcp") s.Require().NoError(err) diff --git a/tests/e2e/e2e_util_test.go b/tests/e2e/e2e_util_test.go index 4ee3f927a23..40b9ca1b52e 100644 --- a/tests/e2e/e2e_util_test.go +++ b/tests/e2e/e2e_util_test.go @@ -220,9 +220,9 @@ func (s *IntegrationTestSuite) queryPropTally(endpoint, addr string) (sdk.Int, s return noTotal, yesTotal, noWithVetoTotal, abstainTotal, nil } -func (s *IntegrationTestSuite) createPool(c *chainConfig, poolFile string) { +func (s *IntegrationTestSuite) createPool(c *chainConfig, poolFile string, from string) { s.T().Logf("creating pool for chain-id: %s", c.meta.Id) - cmd := []string{"osmosisd", "tx", "gamm", "create-pool", fmt.Sprintf("--pool-file=/osmosis/%s", poolFile), fmt.Sprintf("--chain-id=%s", c.meta.Id), "--from=val", "-b=block", "--yes", "--keyring-backend=test"} + cmd := []string{"osmosisd", "tx", "gamm", "create-pool", fmt.Sprintf("--pool-file=/osmosis/%s", poolFile), fmt.Sprintf("--chain-id=%s", c.meta.Id), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, 0, cmd, "code: 0") s.Require().NoError(err) validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, 0) diff --git a/tests/e2e/initialization/chain.go b/tests/e2e/initialization/chain.go index 818d05afb6b..690503b78a5 100644 --- a/tests/e2e/initialization/chain.go +++ b/tests/e2e/initialization/chain.go @@ -1,9 +1,5 @@ package initialization -import ( - "fmt" -) - const ( keyringPassphrase = "testpassphrase" keyringAppName = "testnet" @@ -12,8 +8,8 @@ const ( // internalChain contains the same info as chain, but with the validator structs instead using the internal validator // representation, with more derived data type internalChain struct { - chainMeta ChainMeta - validators []*internalValidator + chainMeta ChainMeta + nodes []*internalNode } func new(id, dataDir string) (*internalChain, error) { @@ -26,48 +22,14 @@ func new(id, dataDir string) (*internalChain, error) { }, nil } -func (c *internalChain) createAndInitValidators(count int) error { - for i := 0; i < count; i++ { - node := c.createValidator(i) - - // generate genesis files - if err := node.init(); err != nil { - return err - } - - c.validators = append(c.validators, node) - - // create keys - if err := node.createKey("val"); err != nil { - return err - } - if err := node.createNodeKey(); err != nil { - return err - } - if err := node.createConsensusKey(); err != nil { - return err - } - } - - return nil -} - -func (c *internalChain) createValidator(index int) *internalValidator { - return &internalValidator{ - chain: c, - index: index, - moniker: fmt.Sprintf("%s-osmosis-%d", c.chainMeta.Id, index), - } -} - func (c *internalChain) export() *Chain { - exportValidators := make([]*Validator, 0, len(c.validators)) - for _, v := range c.validators { - exportValidators = append(exportValidators, v.export()) + exportNodes := make([]*Node, 0, len(c.nodes)) + for _, v := range c.nodes { + exportNodes = append(exportNodes, v.export()) } return &Chain{ - ChainMeta: c.chainMeta, - Validators: exportValidators, + ChainMeta: c.chainMeta, + Nodes: exportNodes, } } diff --git a/tests/e2e/initialization/chain/main.go b/tests/e2e/initialization/chain/main.go index bdcbd12970a..3c12471224f 100644 --- a/tests/e2e/initialization/chain/main.go +++ b/tests/e2e/initialization/chain/main.go @@ -12,7 +12,7 @@ import ( func main() { var ( - valConfig []*initialization.ValidatorConfig + valConfig []*initialization.NodeConfig dataDir string chainId string config string @@ -41,7 +41,7 @@ func main() { panic(err) } - createdChain, err := initialization.Init(chainId, dataDir, valConfig, votingPeriod, forkHeight) + createdChain, err := initialization.InitChain(chainId, dataDir, valConfig, votingPeriod, forkHeight) if err != nil { panic(err) } diff --git a/tests/e2e/initialization/config.go b/tests/e2e/initialization/config.go index 330b07ac279..66644e3482a 100644 --- a/tests/e2e/initialization/config.go +++ b/tests/e2e/initialization/config.go @@ -4,11 +4,9 @@ import ( "encoding/json" "fmt" "path/filepath" - "strings" "time" "github.com/cosmos/cosmos-sdk/server" - srvconfig "github.com/cosmos/cosmos-sdk/server/config" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -18,8 +16,6 @@ import ( govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" staketypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/gogo/protobuf/proto" - "github.com/spf13/viper" - tmconfig "github.com/tendermint/tendermint/config" tmjson "github.com/tendermint/tendermint/libs/json" epochtypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" @@ -32,22 +28,29 @@ import ( "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" ) -type ValidatorConfig struct { +// NodeConfig is a confiuration for the node supplied from the test runner +// to initialization scripts. It should be backwards compatible with earlier +// versions. If this struct is updated, the change must be backported to earlier +// branches that might be used for upgrade testing. +type NodeConfig struct { + Name string // name of the config that will also be assigned to Docke container. Pruning string // default, nothing, everything, or custom PruningKeepRecent string // keep all of the last N states (only used with custom pruning) PruningInterval string // delete old states from every Nth block (only used with custom pruning) SnapshotInterval uint64 // statesync snapshot every Nth block (0 to disable) SnapshotKeepRecent uint32 // number of recent snapshots to keep and serve (0 to keep all) + IsValidator bool // flag indicating whether a node should be a validator } const ( // common - OsmoDenom = "uosmo" - StakeDenom = "stake" - OsmoIBCDenom = "ibc/ED07A3391A112B175915CD8FAF43A2DA8E4790EDE12566649D0C2F97716B8518" - StakeIBCDenom = "ibc/C053D637CCA2A2BA030E2C5EE1B28A16F71CCB0E45E8BE52766DC1B241B7787" - MinGasPrice = "0.000" - IbcSendAmount = 3300000000 + OsmoDenom = "uosmo" + StakeDenom = "stake" + OsmoIBCDenom = "ibc/ED07A3391A112B175915CD8FAF43A2DA8E4790EDE12566649D0C2F97716B8518" + StakeIBCDenom = "ibc/C053D637CCA2A2BA030E2C5EE1B28A16F71CCB0E45E8BE52766DC1B241B7787" + MinGasPrice = "0.000" + IbcSendAmount = 3300000000 + ValidatorWalletName = "val" // chainA ChainAID = "osmo-test-a" OsmoBalanceA = 200000000000 @@ -163,12 +166,37 @@ func updateModuleGenesis[V proto.Message](appGenState map[string]json.RawMessage return nil } -func initGenesis(c *internalChain, votingPeriod time.Duration) error { +func initGenesis(chain *internalChain, votingPeriod time.Duration, forkHeight int) error { + // initialize a genesis file + configDir := chain.nodes[0].configDir() + for _, val := range chain.nodes { + if chain.chainMeta.Id == ChainAID { + if err := addAccount(configDir, "", InitBalanceStrA, val.keyInfo.GetAddress(), forkHeight); err != nil { + return err + } + } else if chain.chainMeta.Id == ChainBID { + if err := addAccount(configDir, "", InitBalanceStrB, val.keyInfo.GetAddress(), forkHeight); err != nil { + return err + } + } + } + + // copy the genesis file to the remaining validators + for _, val := range chain.nodes[1:] { + _, err := util.CopyFile( + filepath.Join(configDir, "config", "genesis.json"), + filepath.Join(val.configDir(), "config", "genesis.json"), + ) + if err != nil { + return err + } + } + serverCtx := server.NewDefaultContext() config := serverCtx.Config - config.SetRoot(c.validators[0].configDir()) - config.Moniker = c.validators[0].getMoniker() + config.SetRoot(chain.nodes[0].configDir()) + config.Moniker = chain.nodes[0].moniker genFilePath := config.GenesisFile() appGenState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFilePath) @@ -186,7 +214,6 @@ func initGenesis(c *internalChain, votingPeriod time.Duration) error { return err } - // pool incentives err = updateModuleGenesis(appGenState, poolitypes.ModuleName, &poolitypes.GenesisState{}, updatePoolIncentiveGenesis) if err != nil { return err @@ -227,7 +254,7 @@ func initGenesis(c *internalChain, votingPeriod time.Duration) error { return err } - err = updateModuleGenesis(appGenState, genutiltypes.ModuleName, &genutiltypes.GenesisState{}, updateGenUtilGenesis(c)) + err = updateModuleGenesis(appGenState, genutiltypes.ModuleName, &genutiltypes.GenesisState{}, updateGenUtilGenesis(chain)) if err != nil { return err } @@ -245,7 +272,7 @@ func initGenesis(c *internalChain, votingPeriod time.Duration) error { } // write the updated genesis file to each validator - for _, val := range c.validators { + for _, val := range chain.nodes { if err := util.WriteFile(filepath.Join(val.configDir(), "config", "genesis.json"), genesisJson); err != nil { return err } @@ -343,18 +370,22 @@ func updateGovGenesis(votingPeriod time.Duration) func(*govtypes.GenesisState) { func updateGenUtilGenesis(c *internalChain) func(*genutiltypes.GenesisState) { return func(genUtilGenState *genutiltypes.GenesisState) { // generate genesis txs - genTxs := make([]json.RawMessage, len(c.validators)) - for i, val := range c.validators { + genTxs := make([]json.RawMessage, 0, len(c.nodes)) + for _, node := range c.nodes { + if !node.isValidator { + continue + } + stakeAmountCoin := StakeAmountCoinA if c.chainMeta.Id != ChainAID { stakeAmountCoin = StakeAmountCoinB } - createValmsg, err := val.buildCreateValidatorMsg(stakeAmountCoin) + createValmsg, err := node.buildCreateValidatorMsg(stakeAmountCoin) if err != nil { panic("genutil genesis setup failed: " + err.Error()) } - signedTx, err := val.signMsg(createValmsg) + signedTx, err := node.signMsg(createValmsg) if err != nil { panic("genutil genesis setup failed: " + err.Error()) } @@ -363,96 +394,8 @@ func updateGenUtilGenesis(c *internalChain) func(*genutiltypes.GenesisState) { if err != nil { panic("genutil genesis setup failed: " + err.Error()) } - genTxs[i] = txRaw + genTxs = append(genTxs, txRaw) } genUtilGenState.GenTxs = genTxs } } - -func initNodes(c *internalChain, numVal, forkHeight int) error { - if err := c.createAndInitValidators(numVal); err != nil { - return err - } - - // initialize a genesis file for the first validator - val0ConfigDir := c.validators[0].configDir() - for _, val := range c.validators { - if c.chainMeta.Id == ChainAID { - if err := addAccount(val0ConfigDir, "", InitBalanceStrA, val.getKeyInfo().GetAddress(), forkHeight); err != nil { - return err - } - } else if c.chainMeta.Id == ChainBID { - if err := addAccount(val0ConfigDir, "", InitBalanceStrB, val.getKeyInfo().GetAddress(), forkHeight); err != nil { - return err - } - } - } - - // copy the genesis file to the remaining validators - for _, val := range c.validators[1:] { - _, err := util.CopyFile( - filepath.Join(val0ConfigDir, "config", "genesis.json"), - filepath.Join(val.configDir(), "config", "genesis.json"), - ) - if err != nil { - return err - } - } - return nil -} - -func initValidatorConfigs(c *internalChain, validatorConfigs []*ValidatorConfig) error { - for i, val := range c.validators { - tmCfgPath := filepath.Join(val.configDir(), "config", "config.toml") - - vpr := viper.New() - vpr.SetConfigFile(tmCfgPath) - if err := vpr.ReadInConfig(); err != nil { - return err - } - - valConfig := &tmconfig.Config{} - if err := vpr.Unmarshal(valConfig); err != nil { - return err - } - - valConfig.P2P.ListenAddress = "tcp://0.0.0.0:26656" - valConfig.P2P.AddrBookStrict = false - valConfig.P2P.ExternalAddress = fmt.Sprintf("%s:%d", val.instanceName(), 26656) - valConfig.RPC.ListenAddress = "tcp://0.0.0.0:26657" - valConfig.StateSync.Enable = false - valConfig.LogLevel = "info" - - var peers []string - - for j := 0; j < len(c.validators); j++ { - // skip adding a peer to yourself - if i == j { - continue - } - - peer := c.validators[j] - peerID := fmt.Sprintf("%s@%s%d:26656", peer.getNodeKey().ID(), peer.getMoniker(), j) - peers = append(peers, peerID) - } - - valConfig.P2P.PersistentPeers = strings.Join(peers, ",") - - tmconfig.WriteConfigFile(tmCfgPath, valConfig) - - // set application configuration - appCfgPath := filepath.Join(val.configDir(), "config", "app.toml") - - appConfig := srvconfig.DefaultConfig() - appConfig.BaseConfig.Pruning = validatorConfigs[i].Pruning - appConfig.BaseConfig.PruningKeepRecent = validatorConfigs[i].PruningKeepRecent - appConfig.BaseConfig.PruningInterval = validatorConfigs[i].PruningInterval - appConfig.API.Enable = true - appConfig.MinGasPrices = fmt.Sprintf("%s%s", MinGasPrice, OsmoDenom) - appConfig.StateSync.SnapshotInterval = validatorConfigs[i].SnapshotInterval - appConfig.StateSync.SnapshotKeepRecent = validatorConfigs[i].SnapshotKeepRecent - - srvconfig.WriteConfigFile(appCfgPath, appConfig) - } - return nil -} diff --git a/tests/e2e/initialization/export.go b/tests/e2e/initialization/export.go index c63bc82c1e1..8e42241644b 100644 --- a/tests/e2e/initialization/export.go +++ b/tests/e2e/initialization/export.go @@ -7,18 +7,19 @@ type ChainMeta struct { Id string `json:"id"` } -type Validator struct { +type Node struct { Name string `json:"name"` ConfigDir string `json:"configDir"` - Index int `json:"index"` Mnemonic string `json:"mnemonic"` PublicAddress string `json:"publicAddress"` PublicKey string `json:"publicKey"` + PeerId string `json:"peerId"` + IsValidator bool `json:"isValidator"` } type Chain struct { - ChainMeta ChainMeta `json:"chainMeta"` - Validators []*Validator `json:"validators"` + ChainMeta ChainMeta `json:"chainMeta"` + Nodes []*Node `json:"validators"` } func (c *ChainMeta) configDir() string { diff --git a/tests/e2e/initialization/init.go b/tests/e2e/initialization/init.go new file mode 100644 index 00000000000..df03c842731 --- /dev/null +++ b/tests/e2e/initialization/init.go @@ -0,0 +1,75 @@ +package initialization + +import ( + "errors" + "fmt" + "path/filepath" + "time" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" +) + +func InitChain(id, dataDir string, nodeConfigs []*NodeConfig, votingPeriod time.Duration, forkHeight int) (*Chain, error) { + chain, err := new(id, dataDir) + if err != nil { + return nil, err + } + + for _, nodeConfig := range nodeConfigs { + newNode, err := newNode(chain, nodeConfig) + if err != nil { + return nil, err + } + chain.nodes = append(chain.nodes, newNode) + } + + if err := initGenesis(chain, votingPeriod, forkHeight); err != nil { + return nil, err + } + + var peers []string + for _, peer := range chain.nodes { + peerID := fmt.Sprintf("%s@%s:26656", peer.getNodeKey().ID(), peer.moniker) + peer.peerId = peerID + peers = append(peers, peerID) + } + + for _, node := range chain.nodes { + if node.isValidator { + if err := node.initValidatorConfigs(chain, peers); err != nil { + return nil, err + } + } + } + return chain.export(), nil +} + +func InitSingleNode(chainId, dataDir string, existingGenesisDir string, nodeConfig *NodeConfig, votingPeriod time.Duration, trustHeight int64, trustHash string, stateSyncRPCServers []string) (*Node, error) { + if nodeConfig.IsValidator { + return nil, errors.New("creating individual validator nodes after starting up chain is not currently supported") + } + + chain, err := new(chainId, dataDir) + if err != nil { + return nil, err + } + + newNode, err := newNode(chain, nodeConfig) + if err != nil { + return nil, err + } + + _, err = util.CopyFile( + existingGenesisDir, + filepath.Join(newNode.configDir(), "config", "genesis.json"), + ) + if err != nil { + return nil, err + } + + if err := newNode.initStateSyncConfig(trustHeight, trustHash, stateSyncRPCServers); err != nil { + return nil, err + } + + return newNode.export(), nil +} diff --git a/tests/e2e/initialization/init_test.go b/tests/e2e/initialization/init_test.go new file mode 100644 index 00000000000..fff036b42c4 --- /dev/null +++ b/tests/e2e/initialization/init_test.go @@ -0,0 +1,143 @@ +package initialization_test + +import ( + "fmt" + "io/ioutil" + "os" + "path" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +) + +const forkHeight = 10 + +var ( + expectedConfigFiles = []string{ + "app.toml", "config.toml", "genesis.json", "node_key.json", "priv_validator_key.json", + } +) + +// TestChainInit tests that chain initialization correctly initializes a full chain +// and produces the desired output with genesis, chain and validator configs. +func TestChainInit(t *testing.T) { + const id = initialization.ChainAID + + var ( + nodeConfigs = []*initialization.NodeConfig{ + { + Name: "0", + Pruning: "default", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 1500, + SnapshotKeepRecent: 2, + IsValidator: true, + }, + { + Name: "1", + Pruning: "nothing", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 100, + SnapshotKeepRecent: 1, + IsValidator: false, + }, + } + dataDir, err = ioutil.TempDir("", "osmosis-e2e-testnet-test") + ) + + chain, err := initialization.InitChain(id, dataDir, nodeConfigs, time.Second*3, forkHeight) + require.NoError(t, err) + + require.Equal(t, chain.ChainMeta.DataDir, dataDir) + require.Equal(t, chain.ChainMeta.Id, id) + + require.Equal(t, len(nodeConfigs), len(chain.Nodes)) + + actualNodes := chain.Nodes + + for i, expectedConfig := range nodeConfigs { + actualNode := actualNodes[i] + + validateNode(t, id, dataDir, expectedConfig, actualNode) + } +} + +// TestSingleNodeInit tests that node initialization correctly initializes a single node +// and produces the desired output with genesis, chain and validator config. +func TestSingleNodeInit(t *testing.T) { + const ( + id = initialization.ChainAID + ) + + var ( + existingChainNodeConfigs = []*initialization.NodeConfig{ + { + Name: "0", + Pruning: "default", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 1500, + SnapshotKeepRecent: 2, + IsValidator: true, + }, + { + Name: "1", + Pruning: "nothing", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 100, + SnapshotKeepRecent: 1, + IsValidator: true, + }, + } + expectedConfig = &initialization.NodeConfig{ + Name: "2", + Pruning: "everything", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 100, + SnapshotKeepRecent: 1, + IsValidator: false, + } + dataDir, err = ioutil.TempDir("", "osmosis-e2e-testnet-test") + ) + + // Setup + existingChain, err := initialization.InitChain(id, dataDir, existingChainNodeConfigs, time.Second*3, forkHeight) + require.NoError(t, err) + + actualNode, err := initialization.InitSingleNode(existingChain.ChainMeta.Id, dataDir, filepath.Join(existingChain.Nodes[0].ConfigDir, "config", "genesis.json"), expectedConfig, time.Second*3, 3, "testHash", []string{"some server"}) + require.NoError(t, err) + + validateNode(t, id, dataDir, expectedConfig, actualNode) +} + +func validateNode(t *testing.T, chainId string, dataDir string, expectedConfig *initialization.NodeConfig, actualNode *initialization.Node) { + require.Equal(t, fmt.Sprintf("%s-node-%s", chainId, expectedConfig.Name), actualNode.Name) + require.Equal(t, expectedConfig.IsValidator, actualNode.IsValidator) + + expectedPath := fmt.Sprintf("%s/%s/%s-node-%s", dataDir, chainId, chainId, expectedConfig.Name) + + require.Equal(t, expectedPath, actualNode.ConfigDir) + + require.NotEmpty(t, actualNode.Mnemonic) + require.NotEmpty(t, actualNode.PublicAddress) + + if expectedConfig.IsValidator { + require.NotEmpty(t, actualNode.PeerId) + } + + for _, expectedFileName := range expectedConfigFiles { + expectedFilePath := path.Join(expectedPath, "config", expectedFileName) + _, err := os.Stat(expectedFilePath) + require.NoError(t, err) + } + _, err := os.Stat(path.Join(expectedPath, "keyring-test")) + require.NoError(t, err) +} diff --git a/tests/e2e/initialization/main.go b/tests/e2e/initialization/main.go deleted file mode 100644 index 3979ea692ec..00000000000 --- a/tests/e2e/initialization/main.go +++ /dev/null @@ -1,20 +0,0 @@ -package initialization - -import "time" - -func Init(id, dataDir string, validatorConfigs []*ValidatorConfig, votingPeriod time.Duration, forkHeight int) (*Chain, error) { - chain, err := new(id, dataDir) - if err != nil { - return nil, err - } - if err := initNodes(chain, len(validatorConfigs), forkHeight); err != nil { - return nil, err - } - if err := initGenesis(chain, votingPeriod); err != nil { - return nil, err - } - if err := initValidatorConfigs(chain, validatorConfigs); err != nil { - return nil, err - } - return chain.export(), nil -} diff --git a/tests/e2e/initialization/validator.go b/tests/e2e/initialization/node.go similarity index 54% rename from tests/e2e/initialization/validator.go rename to tests/e2e/initialization/node.go index 16e302f52d9..5513d270aae 100644 --- a/tests/e2e/initialization/validator.go +++ b/tests/e2e/initialization/node.go @@ -6,6 +6,7 @@ import ( "os" "path" "path/filepath" + "strings" sdkcrypto "github.com/cosmos/cosmos-sdk/crypto" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" @@ -13,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/server" + srvconfig "github.com/cosmos/cosmos-sdk/server/config" sdk "github.com/cosmos/cosmos-sdk/types" sdktx "github.com/cosmos/cosmos-sdk/types/tx" txsigning "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -20,7 +22,9 @@ import ( "github.com/cosmos/cosmos-sdk/x/genutil" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/go-bip39" + "github.com/spf13/viper" tmcfg "github.com/tendermint/tendermint/config" + tmconfig "github.com/tendermint/tendermint/config" tmos "github.com/tendermint/tendermint/libs/os" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/privval" @@ -30,35 +34,48 @@ import ( "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" ) -type internalValidator struct { +type internalNode struct { chain *internalChain - index int moniker string mnemonic string keyInfo keyring.Info privateKey cryptotypes.PrivKey consensusKey privval.FilePVKey nodeKey p2p.NodeKey + peerId string + isValidator bool } -func (v *internalValidator) instanceName() string { - return fmt.Sprintf("%s%d", v.moniker, v.index) -} - -func (v *internalValidator) configDir() string { - return fmt.Sprintf("%s/%s", v.chain.chainMeta.configDir(), v.instanceName()) -} - -func (v *internalValidator) getKeyInfo() keyring.Info { - return v.keyInfo +func newNode(chain *internalChain, nodeConfig *NodeConfig) (*internalNode, error) { + node := &internalNode{ + chain: chain, + moniker: fmt.Sprintf("%s-node-%s", chain.chainMeta.Id, nodeConfig.Name), + isValidator: nodeConfig.IsValidator, + } + // generate genesis files + if err := node.init(); err != nil { + return nil, err + } + // create keys + if err := node.createKey(ValidatorWalletName); err != nil { + return nil, err + } + if err := node.createNodeKey(); err != nil { + return nil, err + } + if err := node.createConsensusKey(); err != nil { + return nil, err + } + node.createAppConfig(nodeConfig) + return node, nil } -func (v *internalValidator) getMoniker() string { - return v.moniker +func (n *internalNode) configDir() string { + return fmt.Sprintf("%s/%s", n.chain.chainMeta.configDir(), n.moniker) } -func (v *internalValidator) buildCreateValidatorMsg(amount sdk.Coin) (sdk.Msg, error) { - description := stakingtypes.NewDescription(v.moniker, "", "", "", "") +func (n *internalNode) buildCreateValidatorMsg(amount sdk.Coin) (sdk.Msg, error) { + description := stakingtypes.NewDescription(n.moniker, "", "", "", "") commissionRates := stakingtypes.CommissionRates{ Rate: sdk.MustNewDecFromStr("0.1"), MaxRate: sdk.MustNewDecFromStr("0.2"), @@ -68,13 +85,13 @@ func (v *internalValidator) buildCreateValidatorMsg(amount sdk.Coin) (sdk.Msg, e // get the initial validator min self delegation minSelfDelegation, _ := sdk.NewIntFromString("1") - valPubKey, err := cryptocodec.FromTmPubKeyInterface(v.consensusKey.PubKey) + valPubKey, err := cryptocodec.FromTmPubKeyInterface(n.consensusKey.PubKey) if err != nil { return nil, err } return stakingtypes.NewMsgCreateValidator( - sdk.ValAddress(v.keyInfo.GetAddress()), + sdk.ValAddress(n.keyInfo.GetAddress()), valPubKey, amount, description, @@ -83,33 +100,49 @@ func (v *internalValidator) buildCreateValidatorMsg(amount sdk.Coin) (sdk.Msg, e ) } -func (v *internalValidator) createConfig() error { - p := path.Join(v.configDir(), "config") +func (n *internalNode) createConfig() error { + p := path.Join(n.configDir(), "config") return os.MkdirAll(p, 0o755) } -func (v *internalValidator) createNodeKey() error { +func (n *internalNode) createAppConfig(nodeConfig *NodeConfig) { + // set application configuration + appCfgPath := filepath.Join(n.configDir(), "config", "app.toml") + + appConfig := srvconfig.DefaultConfig() + appConfig.BaseConfig.Pruning = nodeConfig.Pruning + appConfig.BaseConfig.PruningKeepRecent = nodeConfig.PruningKeepRecent + appConfig.BaseConfig.PruningInterval = nodeConfig.PruningInterval + appConfig.API.Enable = true + appConfig.MinGasPrices = fmt.Sprintf("%s%s", MinGasPrice, OsmoDenom) + appConfig.StateSync.SnapshotInterval = nodeConfig.SnapshotInterval + appConfig.StateSync.SnapshotKeepRecent = nodeConfig.SnapshotKeepRecent + + srvconfig.WriteConfigFile(appCfgPath, appConfig) +} + +func (n *internalNode) createNodeKey() error { serverCtx := server.NewDefaultContext() config := serverCtx.Config - config.SetRoot(v.configDir()) - config.Moniker = v.moniker + config.SetRoot(n.configDir()) + config.Moniker = n.moniker nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile()) if err != nil { return err } - v.nodeKey = *nodeKey + n.nodeKey = *nodeKey return nil } -func (v *internalValidator) createConsensusKey() error { +func (n *internalNode) createConsensusKey() error { serverCtx := server.NewDefaultContext() config := serverCtx.Config - config.SetRoot(v.configDir()) - config.Moniker = v.moniker + config.SetRoot(n.configDir()) + config.Moniker = n.moniker pvKeyFile := config.PrivValidatorKeyFile() if err := tmos.EnsureDir(filepath.Dir(pvKeyFile), 0o777); err != nil { @@ -122,13 +155,13 @@ func (v *internalValidator) createConsensusKey() error { } filePV := privval.LoadOrGenFilePV(pvKeyFile, pvStateFile) - v.consensusKey = filePV.Key + n.consensusKey = filePV.Key return nil } -func (v *internalValidator) createKeyFromMnemonic(name, mnemonic string) error { - kb, err := keyring.New(keyringAppName, keyring.BackendTest, v.configDir(), nil) +func (n *internalNode) createKeyFromMnemonic(name, mnemonic string) error { + kb, err := keyring.New(keyringAppName, keyring.BackendTest, n.configDir(), nil) if err != nil { return err } @@ -154,41 +187,42 @@ func (v *internalValidator) createKeyFromMnemonic(name, mnemonic string) error { return err } - v.keyInfo = info - v.mnemonic = mnemonic - v.privateKey = privKey + n.keyInfo = info + n.mnemonic = mnemonic + n.privateKey = privKey return nil } -func (v *internalValidator) createKey(name string) error { - mnemonic, err := createMnemonic() +func (n *internalNode) createKey(name string) error { + mnemonic, err := n.createMnemonic() if err != nil { return err } - return v.createKeyFromMnemonic(name, mnemonic) + return n.createKeyFromMnemonic(name, mnemonic) } -func (v *internalValidator) export() *Validator { - return &Validator{ - Name: v.instanceName(), - ConfigDir: v.configDir(), - Index: v.index, - Mnemonic: v.mnemonic, - PublicAddress: v.keyInfo.GetAddress().String(), - PublicKey: v.keyInfo.GetPubKey().Address().String(), +func (n *internalNode) export() *Node { + return &Node{ + Name: n.moniker, + ConfigDir: n.configDir(), + Mnemonic: n.mnemonic, + PublicAddress: n.keyInfo.GetAddress().String(), + PublicKey: n.keyInfo.GetPubKey().Address().String(), + PeerId: n.peerId, + IsValidator: n.isValidator, } } -func (v *internalValidator) getNodeKey() *p2p.NodeKey { - return &v.nodeKey +func (n *internalNode) getNodeKey() *p2p.NodeKey { + return &n.nodeKey } -func (v *internalValidator) getGenesisDoc() (*tmtypes.GenesisDoc, error) { +func (n *internalNode) getGenesisDoc() (*tmtypes.GenesisDoc, error) { serverCtx := server.NewDefaultContext() config := serverCtx.Config - config.SetRoot(v.configDir()) + config.SetRoot(n.configDir()) genFile := config.GenesisFile() doc := &tmtypes.GenesisDoc{} @@ -209,18 +243,18 @@ func (v *internalValidator) getGenesisDoc() (*tmtypes.GenesisDoc, error) { return doc, nil } -func (v *internalValidator) init() error { - if err := v.createConfig(); err != nil { +func (n *internalNode) init() error { + if err := n.createConfig(); err != nil { return err } serverCtx := server.NewDefaultContext() config := serverCtx.Config - config.SetRoot(v.configDir()) - config.Moniker = v.moniker + config.SetRoot(n.configDir()) + config.Moniker = n.moniker - genDoc, err := v.getGenesisDoc() + genDoc, err := n.getGenesisDoc() if err != nil { return err } @@ -230,7 +264,7 @@ func (v *internalValidator) init() error { return fmt.Errorf("failed to JSON encode app genesis state: %w", err) } - genDoc.ChainID = v.chain.chainMeta.Id + genDoc.ChainID = n.chain.chainMeta.Id genDoc.Validators = nil genDoc.AppState = appState @@ -242,7 +276,7 @@ func (v *internalValidator) init() error { return nil } -func createMnemonic() (string, error) { +func (n *internalNode) createMnemonic() (string, error) { entropySeed, err := bip39.NewEntropy(256) if err != nil { return "", err @@ -256,22 +290,72 @@ func createMnemonic() (string, error) { return mnemonic, nil } +func (n *internalNode) initValidatorConfigs(c *internalChain, persistentPeers []string) error { + tmCfgPath := filepath.Join(n.configDir(), "config", "config.toml") + + vpr := viper.New() + vpr.SetConfigFile(tmCfgPath) + if err := vpr.ReadInConfig(); err != nil { + return err + } + + valConfig := &tmconfig.Config{} + if err := vpr.Unmarshal(valConfig); err != nil { + return err + } + + valConfig.P2P.ListenAddress = "tcp://0.0.0.0:26656" + valConfig.P2P.AddrBookStrict = false + valConfig.P2P.ExternalAddress = fmt.Sprintf("%s:%d", n.moniker, 26656) + valConfig.RPC.ListenAddress = "tcp://0.0.0.0:26657" + valConfig.StateSync.Enable = false + valConfig.LogLevel = "info" + valConfig.P2P.PersistentPeers = strings.Join(persistentPeers, ",") + + tmconfig.WriteConfigFile(tmCfgPath, valConfig) + return nil +} + +func (n *internalNode) initStateSyncConfig(trustHeight int64, trustHash string, stateSyncRPCServers []string) error { + tmCfgPath := filepath.Join(n.configDir(), "config", "config.toml") + + vpr := viper.New() + vpr.SetConfigFile(tmCfgPath) + if err := vpr.ReadInConfig(); err != nil { + return err + } + + valConfig := &tmconfig.Config{} + if err := vpr.Unmarshal(valConfig); err != nil { + return err + } + + valConfig.StateSync = tmcfg.DefaultStateSyncConfig() + valConfig.StateSync.Enable = true + valConfig.StateSync.TrustHeight = trustHeight + valConfig.StateSync.TrustHash = trustHash + valConfig.StateSync.RPCServers = stateSyncRPCServers + + tmconfig.WriteConfigFile(tmCfgPath, valConfig) + return nil +} + // signMsg returns a signed tx of the provided messages, // signed by the validator, using 0 fees, a high gas limit, and a common memo. -func (v *internalValidator) signMsg(msgs ...sdk.Msg) (*sdktx.Tx, error) { +func (n *internalNode) signMsg(msgs ...sdk.Msg) (*sdktx.Tx, error) { txBuilder := util.EncodingConfig.TxConfig.NewTxBuilder() if err := txBuilder.SetMsgs(msgs...); err != nil { return nil, err } - txBuilder.SetMemo(fmt.Sprintf("%s@%s:26656", v.nodeKey.ID(), v.instanceName())) + txBuilder.SetMemo(fmt.Sprintf("%s@%s:26656", n.nodeKey.ID(), n.moniker)) txBuilder.SetFeeAmount(sdk.NewCoins()) txBuilder.SetGasLimit(uint64(200000 * len(msgs))) // TODO: Find a better way to sign this tx with less code. signerData := authsigning.SignerData{ - ChainID: v.chain.chainMeta.Id, + ChainID: n.chain.chainMeta.Id, AccountNumber: 0, Sequence: 0, } @@ -285,7 +369,7 @@ func (v *internalValidator) signMsg(msgs ...sdk.Msg) (*sdktx.Tx, error) { // also doesn't affect its generated sign bytes, so for code's simplicity // sake, we put it here. sig := txsigning.SignatureV2{ - PubKey: v.keyInfo.GetPubKey(), + PubKey: n.keyInfo.GetPubKey(), Data: &txsigning.SingleSignatureData{ SignMode: txsigning.SignMode_SIGN_MODE_DIRECT, Signature: nil, @@ -306,13 +390,13 @@ func (v *internalValidator) signMsg(msgs ...sdk.Msg) (*sdktx.Tx, error) { return nil, err } - sigBytes, err := v.privateKey.Sign(bytesToSign) + sigBytes, err := n.privateKey.Sign(bytesToSign) if err != nil { return nil, err } sig = txsigning.SignatureV2{ - PubKey: v.keyInfo.GetPubKey(), + PubKey: n.keyInfo.GetPubKey(), Data: &txsigning.SingleSignatureData{ SignMode: txsigning.SignMode_SIGN_MODE_DIRECT, Signature: sigBytes, diff --git a/tests/e2e/initialization/node/main.go b/tests/e2e/initialization/node/main.go new file mode 100644 index 00000000000..b8130c3d118 --- /dev/null +++ b/tests/e2e/initialization/node/main.go @@ -0,0 +1,66 @@ +package main + +import ( + "encoding/json" + "flag" + "os" + "strings" + "time" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +) + +func main() { + var ( + nodeConfigStr string + + dataDir string + + existingGenesisDir string + + chainId string + + votingPeriod time.Duration + + stateSyncRPCServersStr string + + trustHeight int64 + + trustHash string + ) + + flag.StringVar(&dataDir, "data-dir", "", "chain data directory") + flag.StringVar(&existingGenesisDir, "genesis-dir", "", "pre-existing genesis location") + flag.StringVar(&chainId, "chain-id", "", "chain ID") + flag.StringVar(&nodeConfigStr, "node-config", "", "serialized node config") + flag.DurationVar(&votingPeriod, "voting-period", 30000000000, "voting period") + flag.StringVar(&stateSyncRPCServersStr, "rpc-servers", "", "state sync RPC servers") + flag.Int64Var(&trustHeight, "trust-height", 0, "trust Height") + flag.StringVar(&trustHash, "trust-hash", "", "trust hash") + + flag.Parse() + + if len(dataDir) == 0 { + panic("data-dir is required") + } + + var nodeConfig initialization.NodeConfig + err := json.Unmarshal([]byte(nodeConfigStr), &nodeConfig) + if err != nil { + panic(err) + } + + stateSyncRPCServers := strings.Split(stateSyncRPCServersStr, ",") + if len(stateSyncRPCServers) == 0 { + panic("rpc-servers is required, separated by commas") + } + + if err := os.MkdirAll(dataDir, 0o755); err != nil { + panic(err) + } + + _, err = initialization.InitSingleNode(chainId, dataDir, existingGenesisDir, &nodeConfig, votingPeriod, trustHeight, trustHash, stateSyncRPCServers) + if err != nil { + panic(err) + } +} From 1a67b02121cdbb5da603792cfe3d0e638bf7073b Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 5 Jul 2022 16:16:34 -0400 Subject: [PATCH 030/376] lint: fix issue from parallel e2e pull request (#1974) --- tests/e2e/initialization/node.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/e2e/initialization/node.go b/tests/e2e/initialization/node.go index 5513d270aae..1f4733896b3 100644 --- a/tests/e2e/initialization/node.go +++ b/tests/e2e/initialization/node.go @@ -23,7 +23,6 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/go-bip39" "github.com/spf13/viper" - tmcfg "github.com/tendermint/tendermint/config" tmconfig "github.com/tendermint/tendermint/config" tmos "github.com/tendermint/tendermint/libs/os" "github.com/tendermint/tendermint/p2p" @@ -272,7 +271,7 @@ func (n *internalNode) init() error { return fmt.Errorf("failed to export app genesis state: %w", err) } - tmcfg.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config) + tmconfig.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config) return nil } @@ -330,7 +329,7 @@ func (n *internalNode) initStateSyncConfig(trustHeight int64, trustHash string, return err } - valConfig.StateSync = tmcfg.DefaultStateSyncConfig() + valConfig.StateSync = tmconfig.DefaultStateSyncConfig() valConfig.StateSync.Enable = true valConfig.StateSync.TrustHeight = trustHeight valConfig.StateSync.TrustHash = trustHash From 133e139ac2fa2fb5be3ffe972f3f27a973734021 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 5 Jul 2022 16:45:06 -0400 Subject: [PATCH 031/376] chore: x/tokenfactory audit (#1962) * updates * updates * updates * updates * Update x/tokenfactory/README.md Co-authored-by: Roman * Update x/tokenfactory/module.go Co-authored-by: Roman * updates * updates Co-authored-by: Roman --- .../tokenfactory/v1beta1/genesis.proto | 5 +- .../osmosis/tokenfactory/v1beta1/params.proto | 2 +- .../osmosis/tokenfactory/v1beta1/query.proto | 17 +++- proto/osmosis/tokenfactory/v1beta1/tx.proto | 44 +++++---- x/tokenfactory/README.md | 99 ++++++++++++------- x/tokenfactory/module.go | 50 +++++----- x/tokenfactory/types/genesis.pb.go | 3 + x/tokenfactory/types/params.pb.go | 2 +- x/tokenfactory/types/query.pb.go | 22 ++++- x/tokenfactory/types/tx.pb.go | 24 +++-- 10 files changed, 170 insertions(+), 98 deletions(-) diff --git a/proto/osmosis/tokenfactory/v1beta1/genesis.proto b/proto/osmosis/tokenfactory/v1beta1/genesis.proto index 6901a494d5d..67f94646700 100644 --- a/proto/osmosis/tokenfactory/v1beta1/genesis.proto +++ b/proto/osmosis/tokenfactory/v1beta1/genesis.proto @@ -18,6 +18,9 @@ message GenesisState { ]; } +// GenesisDenom defines a tokenfactory denom that is defined within genesis +// state. The structure contains DenomAuthorityMetadata which defines the +// denom's admin. message GenesisDenom { option (gogoproto.equal) = true; @@ -26,4 +29,4 @@ message GenesisDenom { (gogoproto.moretags) = "yaml:\"authority_metadata\"", (gogoproto.nullable) = false ]; -} \ No newline at end of file +} diff --git a/proto/osmosis/tokenfactory/v1beta1/params.proto b/proto/osmosis/tokenfactory/v1beta1/params.proto index 6cbe6090fa5..0aafb65ecf4 100644 --- a/proto/osmosis/tokenfactory/v1beta1/params.proto +++ b/proto/osmosis/tokenfactory/v1beta1/params.proto @@ -8,7 +8,7 @@ import "cosmos/base/v1beta1/coin.proto"; option go_package = "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types"; -// Params holds parameters for the tokenfactory module +// Params defines the parameters for the tokenfactory module. message Params { repeated cosmos.base.v1beta1.Coin denom_creation_fee = 1 [ (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", diff --git a/proto/osmosis/tokenfactory/v1beta1/query.proto b/proto/osmosis/tokenfactory/v1beta1/query.proto index c1e3b3717dd..d4811ad9f08 100644 --- a/proto/osmosis/tokenfactory/v1beta1/query.proto +++ b/proto/osmosis/tokenfactory/v1beta1/query.proto @@ -11,17 +11,22 @@ option go_package = "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types"; // Query defines the gRPC querier service. service Query { - // Params returns the total set of minting parameters. + // Params defines a gRPC query method that returns the tokenfactory module's + // parameters. rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { option (google.api.http).get = "/osmosis/tokenfactory/v1beta1/params"; } + // DenomAuthorityMetadata defines a gRPC query method for fetching + // DenomAuthorityMetadata for a particular denom. rpc DenomAuthorityMetadata(QueryDenomAuthorityMetadataRequest) returns (QueryDenomAuthorityMetadataResponse) { option (google.api.http).get = "/osmosis/tokenfactory/v1beta1/denoms/{denom}/authority_metadata"; } + // DenomsFromCreator defines a gRPC query method for fetching all + // denominations created by a specific admin/creator. rpc DenomsFromCreator(QueryDenomsFromCreatorRequest) returns (QueryDenomsFromCreatorResponse) { option (google.api.http).get = @@ -38,9 +43,14 @@ message QueryParamsResponse { Params params = 1 [ (gogoproto.nullable) = false ]; } +// QueryDenomAuthorityMetadataRequest defines the request structure for the +// DenomAuthorityMetadata gRPC query. message QueryDenomAuthorityMetadataRequest { string denom = 1 [ (gogoproto.moretags) = "yaml:\"denom\"" ]; } + +// QueryDenomAuthorityMetadataResponse defines the response structure for the +// DenomAuthorityMetadata gRPC query. message QueryDenomAuthorityMetadataResponse { DenomAuthorityMetadata authority_metadata = 1 [ (gogoproto.moretags) = "yaml:\"authority_metadata\"", @@ -48,9 +58,14 @@ message QueryDenomAuthorityMetadataResponse { ]; } +// QueryDenomsFromCreatorRequest defines the request structure for the +// DenomsFromCreator gRPC query. message QueryDenomsFromCreatorRequest { string creator = 1 [ (gogoproto.moretags) = "yaml:\"creator\"" ]; } + +// QueryDenomsFromCreatorRequest defines the response structure for the +// DenomsFromCreator gRPC query. message QueryDenomsFromCreatorResponse { repeated string denoms = 1 [ (gogoproto.moretags) = "yaml:\"denoms\"" ]; } diff --git a/proto/osmosis/tokenfactory/v1beta1/tx.proto b/proto/osmosis/tokenfactory/v1beta1/tx.proto index 8d358394592..7391d4dd295 100644 --- a/proto/osmosis/tokenfactory/v1beta1/tx.proto +++ b/proto/osmosis/tokenfactory/v1beta1/tx.proto @@ -6,24 +6,27 @@ import "cosmos/base/v1beta1/coin.proto"; option go_package = "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types"; -// Msg defines the Msg service. +// Msg defines the tokefactory module's gRPC message service. service Msg { rpc CreateDenom(MsgCreateDenom) returns (MsgCreateDenomResponse); rpc Mint(MsgMint) returns (MsgMintResponse); rpc Burn(MsgBurn) returns (MsgBurnResponse); + rpc ChangeAdmin(MsgChangeAdmin) returns (MsgChangeAdminResponse); + // ForceTransfer is deactivated for now because we need to think through edge // cases rpc ForceTransfer(MsgForceTransfer) returns // (MsgForceTransferResponse); - rpc ChangeAdmin(MsgChangeAdmin) returns (MsgChangeAdminResponse); } -// MsgCreateDenom is the sdk.Msg type for allowing an account to create -// a new denom. It requires a sender address and a subdenomination. -// The (sender_address, sub_denomination) pair must be unique and cannot be -// re-used. The resulting denom created is `factory/{creator -// address}/{subdenom}`. The resultant denom's admin is originally set to be the -// creator, but this can be changed later. The token denom does not indicate the -// current admin. +// MsgCreateDenom defines the message structure for the CreateDenom gRPC service +// method. It allows an account to create a new denom. It requires a sender +// address and a sub denomination. The (sender_address, sub_denomination) tuple +// must be unique and cannot be re-used. +// +// The resulting denom created is defined as +// . The resulting denom's admin is +// originally set to be the creator, but this can be changed later. The token +// denom does not indicate the current admin. message MsgCreateDenom { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; // subdenom can be up to 44 "alphanumeric" characters long. @@ -61,7 +64,18 @@ message MsgBurn { message MsgBurnResponse {} -// // ===================== MsgForceTransfer +// MsgChangeAdmin is the sdk.Msg type for allowing an admin account to reassign +// adminship of a denom to a new account +message MsgChangeAdmin { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + string denom = 2 [ (gogoproto.moretags) = "yaml:\"denom\"" ]; + string new_admin = 3 [ (gogoproto.moretags) = "yaml:\"new_admin\"" ]; +} + +// MsgChangeAdminResponse defines the response structure for an executed +// MsgChangeAdmin message. +message MsgChangeAdminResponse {} + // message MsgForceTransfer { // string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; // cosmos.base.v1beta1.Coin amount = 2 [ @@ -75,13 +89,3 @@ message MsgBurnResponse {} // } // message MsgForceTransferResponse {} - -// MsgChangeAdmin is the sdk.Msg type for allowing an admin account to reassign -// adminship of a denom to a new account -message MsgChangeAdmin { - string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; - string denom = 2 [ (gogoproto.moretags) = "yaml:\"denom\"" ]; - string new_admin = 3 [ (gogoproto.moretags) = "yaml:\"new_admin\"" ]; -} - -message MsgChangeAdminResponse {} \ No newline at end of file diff --git a/x/tokenfactory/README.md b/x/tokenfactory/README.md index c976498431e..4f1f4fea2c4 100644 --- a/x/tokenfactory/README.md +++ b/x/tokenfactory/README.md @@ -11,18 +11,20 @@ created denom. Once a denom is created, the original creator is given - Mint their denom to any account - Burn their denom from any account - Create a transfer of their denom between any two accounts -- Change the admin In the future, more admin capabilities may be - added. Admins can choose to share admin privileges with other - accounts using the authz module. The `ChangeAdmin` functionality, - allows changing the master admin account, or even setting it to - `""`, meaning no account has admin privileges of the asset. - +- Change the admin. In the future, more admin capabilities may be added. Admins + can choose to share admin privileges with other accounts using the authz + module. The `ChangeAdmin` functionality, allows changing the master admin + account, or even setting it to `""`, meaning no account has admin privileges + of the asset. ## Messages ### CreateDenom -- Creates a denom of `factory/{creator address}/{subdenom}` given the denom creator address and the subdenom. Subdenoms can contain `[a-zA-Z0-9./]`. -``` {.go} + +Creates a denom of `factory/{creator address}/{subdenom}` given the denom creator +address and the subdenom. Subdenoms can contain `[a-zA-Z0-9./]`. + +```go message MsgCreateDenom { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; string subdenom = 2 [ (gogoproto.moretags) = "yaml:\"subdenom\"" ]; @@ -30,14 +32,22 @@ message MsgCreateDenom { ``` **State Modifications:** -- Fund community pool with the denom creation fee from the creator address, set in `Params` -- Set `DenomMetaData` via bank keeper -- Set `AuthorityMetadata` for the given denom to store the admin for the created denom `factory/{creator address}/{subdenom}`. Admin is automatically set as the Msg sender -- Add denom to the `CreatorPrefixStore`, where a state of denoms created per creator is kept + +- Fund community pool with the denom creation fee from the creator address, set + in `Params`. +- Set `DenomMetaData` via bank keeper. +- Set `AuthorityMetadata` for the given denom to store the admin for the created + denom `factory/{creator address}/{subdenom}`. Admin is automatically set as the + Msg sender. +- Add denom to the `CreatorPrefixStore`, where a state of denoms created per + creator is kept. ### Mint -- Minting of a specific denom is only allowed for the creator of the denom registered during `CreateDenom` -``` {.go} + +Minting of a specific denom is only allowed for the creator of the denom +registered during `CreateDenom`. + +```go message MsgMint { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; cosmos.base.v1beta1.Coin amount = 2 [ @@ -48,16 +58,18 @@ message MsgMint { ``` **State Modifications:** + - Safety check the following - Check that the denom minting is created via `tokenfactory` module - Check that the sender of the message is the admin of the denom - Mint designated amount of tokens for the denom via `bank` module +### Burn +Burning of a specific denom is only allowed for the creator of the denom +registered during `CreateDenom`. -### Burn -- Burning of a specific denom is only allowed for the creator of the denom registered during `CreateDenom` -``` {.go} +```go message MsgBurn { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; cosmos.base.v1beta1.Coin amount = 2 [ @@ -68,15 +80,18 @@ message MsgBurn { ``` **State Modifications:** + - Saftey check the following - Check that the denom minting is created via `tokenfactory` module - Check that the sender of the message is the admin of the denom - Burn designated amount of tokens for the denom via `bank` module - ### ChangeAdmin -- Burning of a specific denom is only allowed for the creator of the denom registered during `CreateDenom` -``` {.go} + +Burning of a specific denom is only allowed for the creator of the denom +registered during `CreateDenom`. + +```go message MsgChangeAdmin { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; string denom = 2 [ (gogoproto.moretags) = "yaml:\"denom\"" ]; @@ -85,6 +100,7 @@ message MsgChangeAdmin { ``` **State Modifications:** + - Check that sender of the message is the admin of denom - Modify `AuthorityMetadata` state entry to change the admin of the denom @@ -92,26 +108,37 @@ message MsgChangeAdmin { The chain's bech32 prefix for addresses can be at most 16 characters long. -This comes from denoms having a 128 byte maximum length, enforced from the SDK, and us setting longest_subdenom to be 44 bytes. -A token factory token's denom is: -`factory/{creator address}/{subdenom}` +This comes from denoms having a 128 byte maximum length, enforced from the SDK, +and us setting longest_subdenom to be 44 bytes. + +A token factory token's denom is: `factory/{creator address}/{subdenom}` + Splitting up into sub-components, this has: -* `len(factory) = 7` -* `2 * len("/") = 2` -* `len(longest_subdenom)` -* `len(creator_address) = len(bech32(longest_addr_length, chain_addr_prefix))`. -Longest addr length at the moment is `32 bytes`. -Due to SDK error correction settings, this means `len(bech32(32, chain_addr_prefix)) = len(chain_addr_prefix) + 1 + 58`. + +- `len(factory) = 7` +- `2 * len("/") = 2` +- `len(longest_subdenom)` +- `len(creator_address) = len(bech32(longest_addr_length, chain_addr_prefix))`. + +Longest addr length at the moment is `32 bytes`. Due to SDK error correction +settings, this means `len(bech32(32, chain_addr_prefix)) = len(chain_addr_prefix) + 1 + 58`. Adding this all, we have a total length constraint of `128 = 7 + 2 + len(longest_subdenom) + len(longest_chain_addr_prefix) + 1 + 58`. Therefore `len(longest_subdenom) + len(longest_chain_addr_prefix) = 128 - (7 + 2 + 1 + 58) = 60`. -The choice between how we standardized the split these 60 bytes between maxes from longest_subdenom and longest_chain_addr_prefix is somewhat arbitrary. Considerations going into this: -* Per [BIP-0173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32) the technically longest HRP for a 32 byte address ('data field') is 31 bytes. (Comes from encode(data) = 59 bytes, and max length = 90 bytes) -* subdenom should be at least 32 bytes so hashes can go into it -* longer subdenoms are very helpful for creating human readable denoms -* chain addresses should prefer being smaller. The longest HRP in cosmos to date is 11 bytes. (`persistence`) +The choice between how we standardized the split these 60 bytes between maxes +from longest_subdenom and longest_chain_addr_prefix is somewhat arbitrary. +Considerations going into this: + +- Per [BIP-0173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32) + the technically longest HRP for a 32 byte address ('data field') is 31 bytes. + (Comes from encode(data) = 59 bytes, and max length = 90 bytes) +- subdenom should be at least 32 bytes so hashes can go into it +- longer subdenoms are very helpful for creating human readable denoms +- chain addresses should prefer being smaller. The longest HRP in cosmos to date is 11 bytes. (`persistence`) For explicitness, its currently set to `len(longest_subdenom) = 44` and `len(longest_chain_addr_prefix) = 16`. -Please note, if the SDK increases the maximum length of a denom from 128 bytes, these caps should increase. -So please don't make code rely on these max lengths for parsing. \ No newline at end of file +Please note, if the SDK increases the maximum length of a denom from 128 bytes, +these caps should increase. + +So please don't make code rely on these max lengths for parsing. diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index c2b7d691e33..68a0207310e 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -5,17 +5,15 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/client/cli" "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/keeper" @@ -40,7 +38,7 @@ func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { return AppModuleBasic{cdc: cdc} } -// Name returns the capability module's name. +// Name returns the x/tokenfactory module's name. func (AppModuleBasic) Name() string { return types.ModuleName } @@ -54,17 +52,18 @@ func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { types.RegisterInterfaces(reg) } -// DefaultGenesis returns the capability module's default genesis state. +// DefaultGenesis returns the x/tokenfactory module's default genesis state. func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesis()) } -// ValidateGenesis performs genesis state validation for the capability module. +// ValidateGenesis performs genesis state validation for the x/tokenfactory module. func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var genState types.GenesisState if err := cdc.UnmarshalJSON(bz, &genState); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } + return genState.Validate() } @@ -77,12 +76,12 @@ func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *r types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) //nolint:errcheck } -// GetTxCmd returns the tokenfactory module's root tx command. +// GetTxCmd returns the x/tokenfactory module's root tx command. func (a AppModuleBasic) GetTxCmd() *cobra.Command { return cli.GetTxCmd() } -// GetQueryCmd returns the tokenfactory module's root query command. +// GetQueryCmd returns the x/tokenfactory module's root query command. func (AppModuleBasic) GetQueryCmd() *cobra.Command { return cli.GetQueryCmd() } @@ -100,30 +99,34 @@ type AppModule struct { bankKeeper types.BankKeeper } -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper) AppModule { +func NewAppModule( + cdc codec.Codec, + keeper keeper.Keeper, + accountKeeper types.AccountKeeper, + bankKeeper types.BankKeeper, +) AppModule { return AppModule{ AppModuleBasic: NewAppModuleBasic(cdc), keeper: keeper, - - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, } } -// Name returns the capability module's name. +// Name returns the x/tokenfactory module's name. func (am AppModule) Name() string { return am.AppModuleBasic.Name() } -// Route returns the capability module's message routing key. +// Route returns the x/tokenfactory module's message routing key. func (am AppModule) Route() sdk.Route { return sdk.Route{} } -// QuerierRoute returns the capability module's query routing key. +// QuerierRoute returns the x/tokenfactory module's query routing key. func (AppModule) QuerierRoute() string { return types.QuerierRoute } -// LegacyQuerierHandler returns the capability module's Querier. +// LegacyQuerierHandler returns the x/tokenfactory module's Querier. func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return nil } @@ -135,11 +138,11 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterQueryServer(cfg.QueryServer(), am.keeper) } -// RegisterInvariants registers the tokenfactory module's invariants. +// RegisterInvariants registers the x/tokenfactory module's invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// InitGenesis performs the tokenfactory module's genesis initialization It returns -// no validator updates. +// InitGenesis performs the x/tokenfactory module's genesis initialization. It +// returns no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { var genState types.GenesisState cdc.MustUnmarshalJSON(gs, &genState) @@ -149,7 +152,8 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.Ra return []abci.ValidatorUpdate{} } -// ExportGenesis returns the capability module's exported genesis state as raw JSON bytes. +// ExportGenesis returns the x/tokenfactory module's exported genesis state as raw +// JSON bytes. func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { genState := am.keeper.ExportGenesis(ctx) return cdc.MustMarshalJSON(genState) diff --git a/x/tokenfactory/types/genesis.pb.go b/x/tokenfactory/types/genesis.pb.go index 666c0d495bd..9e7458096ba 100644 --- a/x/tokenfactory/types/genesis.pb.go +++ b/x/tokenfactory/types/genesis.pb.go @@ -77,6 +77,9 @@ func (m *GenesisState) GetFactoryDenoms() []GenesisDenom { return nil } +// GenesisDenom defines a tokenfactory denom that is defined within genesis +// state. The structure contains DenomAuthorityMetadata which defines the +// denom's admin. type GenesisDenom struct { Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty" yaml:"denom"` AuthorityMetadata DenomAuthorityMetadata `protobuf:"bytes,2,opt,name=authority_metadata,json=authorityMetadata,proto3" json:"authority_metadata" yaml:"authority_metadata"` diff --git a/x/tokenfactory/types/params.pb.go b/x/tokenfactory/types/params.pb.go index b8f90a9b98c..6755f175e5e 100644 --- a/x/tokenfactory/types/params.pb.go +++ b/x/tokenfactory/types/params.pb.go @@ -26,7 +26,7 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// Params holds parameters for the tokenfactory module +// Params defines the parameters for the tokenfactory module. type Params struct { DenomCreationFee github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=denom_creation_fee,json=denomCreationFee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"denom_creation_fee" yaml:"denom_creation_fee"` } diff --git a/x/tokenfactory/types/query.pb.go b/x/tokenfactory/types/query.pb.go index c71398eb8f4..a8eb09754b1 100644 --- a/x/tokenfactory/types/query.pb.go +++ b/x/tokenfactory/types/query.pb.go @@ -113,6 +113,8 @@ func (m *QueryParamsResponse) GetParams() Params { return Params{} } +// QueryDenomAuthorityMetadataRequest defines the request structure for the +// DenomAuthorityMetadata gRPC query. type QueryDenomAuthorityMetadataRequest struct { Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty" yaml:"denom"` } @@ -157,6 +159,8 @@ func (m *QueryDenomAuthorityMetadataRequest) GetDenom() string { return "" } +// QueryDenomAuthorityMetadataResponse defines the response structure for the +// DenomAuthorityMetadata gRPC query. type QueryDenomAuthorityMetadataResponse struct { AuthorityMetadata DenomAuthorityMetadata `protobuf:"bytes,1,opt,name=authority_metadata,json=authorityMetadata,proto3" json:"authority_metadata" yaml:"authority_metadata"` } @@ -201,6 +205,8 @@ func (m *QueryDenomAuthorityMetadataResponse) GetAuthorityMetadata() DenomAuthor return DenomAuthorityMetadata{} } +// QueryDenomsFromCreatorRequest defines the request structure for the +// DenomsFromCreator gRPC query. type QueryDenomsFromCreatorRequest struct { Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty" yaml:"creator"` } @@ -245,6 +251,8 @@ func (m *QueryDenomsFromCreatorRequest) GetCreator() string { return "" } +// QueryDenomsFromCreatorRequest defines the response structure for the +// DenomsFromCreator gRPC query. type QueryDenomsFromCreatorResponse struct { Denoms []string `protobuf:"bytes,1,rep,name=denoms,proto3" json:"denoms,omitempty" yaml:"denoms"` } @@ -354,9 +362,14 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { - // Params returns the total set of minting parameters. + // Params defines a gRPC query method that returns the tokenfactory module's + // parameters. Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + // DenomAuthorityMetadata defines a gRPC query method for fetching + // DenomAuthorityMetadata for a particular denom. DenomAuthorityMetadata(ctx context.Context, in *QueryDenomAuthorityMetadataRequest, opts ...grpc.CallOption) (*QueryDenomAuthorityMetadataResponse, error) + // DenomsFromCreator defines a gRPC query method for fetching all + // denominations created by a specific admin/creator. DenomsFromCreator(ctx context.Context, in *QueryDenomsFromCreatorRequest, opts ...grpc.CallOption) (*QueryDenomsFromCreatorResponse, error) } @@ -397,9 +410,14 @@ func (c *queryClient) DenomsFromCreator(ctx context.Context, in *QueryDenomsFrom // QueryServer is the server API for Query service. type QueryServer interface { - // Params returns the total set of minting parameters. + // Params defines a gRPC query method that returns the tokenfactory module's + // parameters. Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + // DenomAuthorityMetadata defines a gRPC query method for fetching + // DenomAuthorityMetadata for a particular denom. DenomAuthorityMetadata(context.Context, *QueryDenomAuthorityMetadataRequest) (*QueryDenomAuthorityMetadataResponse, error) + // DenomsFromCreator defines a gRPC query method for fetching all + // denominations created by a specific admin/creator. DenomsFromCreator(context.Context, *QueryDenomsFromCreatorRequest) (*QueryDenomsFromCreatorResponse, error) } diff --git a/x/tokenfactory/types/tx.pb.go b/x/tokenfactory/types/tx.pb.go index ead34210afa..e3088cd3959 100644 --- a/x/tokenfactory/types/tx.pb.go +++ b/x/tokenfactory/types/tx.pb.go @@ -29,13 +29,15 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// MsgCreateDenom is the sdk.Msg type for allowing an account to create -// a new denom. It requires a sender address and a subdenomination. -// The (sender_address, sub_denomination) pair must be unique and cannot be -// re-used. The resulting denom created is `factory/{creator -// address}/{subdenom}`. The resultant denom's admin is originally set to be the -// creator, but this can be changed later. The token denom does not indicate the -// current admin. +// MsgCreateDenom defines the message structure for the CreateDenom gRPC service +// method. It allows an account to create a new denom. It requires a sender +// address and a sub denomination. The (sender_address, sub_denomination) tuple +// must be unique and cannot be re-used. +// +// The resulting denom created is defined as +// . The resulting denom's admin is +// originally set to be the creator, but this can be changed later. The token +// denom does not indicate the current admin. type MsgCreateDenom struct { Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` // subdenom can be up to 44 "alphanumeric" characters long. @@ -377,6 +379,8 @@ func (m *MsgChangeAdmin) GetNewAdmin() string { return "" } +// MsgChangeAdminResponse defines the response structure for an executed +// MsgChangeAdmin message. type MsgChangeAdminResponse struct { } @@ -480,9 +484,6 @@ type MsgClient interface { CreateDenom(ctx context.Context, in *MsgCreateDenom, opts ...grpc.CallOption) (*MsgCreateDenomResponse, error) Mint(ctx context.Context, in *MsgMint, opts ...grpc.CallOption) (*MsgMintResponse, error) Burn(ctx context.Context, in *MsgBurn, opts ...grpc.CallOption) (*MsgBurnResponse, error) - // ForceTransfer is deactivated for now because we need to think through edge - // cases rpc ForceTransfer(MsgForceTransfer) returns - // (MsgForceTransferResponse); ChangeAdmin(ctx context.Context, in *MsgChangeAdmin, opts ...grpc.CallOption) (*MsgChangeAdminResponse, error) } @@ -535,9 +536,6 @@ type MsgServer interface { CreateDenom(context.Context, *MsgCreateDenom) (*MsgCreateDenomResponse, error) Mint(context.Context, *MsgMint) (*MsgMintResponse, error) Burn(context.Context, *MsgBurn) (*MsgBurnResponse, error) - // ForceTransfer is deactivated for now because we need to think through edge - // cases rpc ForceTransfer(MsgForceTransfer) returns - // (MsgForceTransferResponse); ChangeAdmin(context.Context, *MsgChangeAdmin) (*MsgChangeAdminResponse, error) } From f0270d04bd77cc5e1c23f7913118b3c2ba737e97 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 5 Jul 2022 18:24:46 -0400 Subject: [PATCH 032/376] chore(e2e): update initialization image (#1976) --- tests/e2e/containers/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/containers/config.go b/tests/e2e/containers/config.go index da5bb1a0254..03c51ec9fce 100644 --- a/tests/e2e/containers/config.go +++ b/tests/e2e/containers/config.go @@ -27,7 +27,7 @@ const ( previousVersionOsmoTag = "v10.0.0-debug" // Pre-upgrade repo/tag for osmosis initialization (this should be one version below upgradeVersion) previousVersionInitRepository = "osmolabs/osmosis-e2e-init-chain" - previousVersionInitTag = "v10.0.0-e2e-v1" + previousVersionInitTag = "v10.0.0-e2e-v2" // Hermes repo/version for relayer relayerRepository = "osmolabs/hermes" relayerTag = "0.13.0" From 198a4dead643cad8a379b062b711d4f9c3c30975 Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Thu, 7 Jul 2022 01:01:27 +0900 Subject: [PATCH 033/376] chore: refactor unlock test (#1968) * Unlocking tests * Add test cases * Update x/lockup/keeper/lock_test.go Co-authored-by: Roman * Apply suggestions from code review Co-authored-by: Roman * cleanup Co-authored-by: Roman --- x/lockup/keeper/lock_test.go | 285 ++++++++++++++++------------------- 1 file changed, 134 insertions(+), 151 deletions(-) diff --git a/x/lockup/keeper/lock_test.go b/x/lockup/keeper/lock_test.go index 834a72f8de2..109031a7c10 100644 --- a/x/lockup/keeper/lock_test.go +++ b/x/lockup/keeper/lock_test.go @@ -46,37 +46,6 @@ func (suite *KeeperTestSuite) TestBeginUnlocking() { // test for all unlockable suite.Require().NotEqual(locks[0].IsUnlocking(), false) } -func (suite *KeeperTestSuite) TestBeginUnlockPeriodLock() { - suite.SetupTest() - - // initial check - locks, err := suite.App.LockupKeeper.GetPeriodLocks(suite.Ctx) - suite.Require().NoError(err) - suite.Require().Len(locks, 0) - - // lock coins - addr1 := sdk.AccAddress([]byte("addr1---------------")) - coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} - suite.LockTokens(addr1, coins, time.Second) - - // check locks - locks, err = suite.App.LockupKeeper.GetPeriodLocks(suite.Ctx) - suite.Require().NoError(err) - suite.Require().Len(locks, 1) - suite.Require().Equal(locks[0].EndTime, time.Time{}) - suite.Require().Equal(locks[0].IsUnlocking(), false) - - // begin unlock - err = suite.App.LockupKeeper.BeginUnlock(suite.Ctx, locks[0].ID, nil) - suite.Require().NoError(err) - - // check locks - locks, err = suite.App.LockupKeeper.GetPeriodLocks(suite.Ctx) - suite.Require().NoError(err) - suite.Require().NotEqual(locks[0].EndTime, time.Time{}) - suite.Require().NotEqual(locks[0].IsUnlocking(), false) -} - func (suite *KeeperTestSuite) TestGetPeriodLocks() { suite.SetupTest() @@ -96,143 +65,157 @@ func (suite *KeeperTestSuite) TestGetPeriodLocks() { suite.Require().Len(locks, 1) } -func (suite *KeeperTestSuite) TestUnlockPeriodLockByID() { - suite.SetupTest() - now := suite.Ctx.BlockTime() - lockKeeper := suite.App.LockupKeeper - - // initial check - locks, err := lockKeeper.GetPeriodLocks(suite.Ctx) - suite.Require().NoError(err) - suite.Require().Len(locks, 0) - - // lock coins - addr1 := sdk.AccAddress([]byte("addr1---------------")) - coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} - suite.LockTokens(addr1, coins, time.Second) - - // unlock lock just now - lock, err := lockKeeper.GetLockByID(suite.Ctx, 1) - suite.Require().NoError(err) - err = lockKeeper.UnlockMaturedLock(suite.Ctx, lock.ID) - suite.Require().Error(err) - - // move start time to 1 second in the future. - suite.Ctx = suite.Ctx.WithBlockTime(now.Add(time.Second)) - - // Try to finish unlocking a lock, before starting unlock. - lock, err = lockKeeper.GetLockByID(suite.Ctx, 1) - suite.Require().NoError(err) - err = lockKeeper.UnlockMaturedLock(suite.Ctx, lock.ID) - suite.Require().Error(err) - - // begin unlock - lock, err = lockKeeper.GetLockByID(suite.Ctx, 1) - suite.Require().NoError(err) - err = lockKeeper.BeginUnlock(suite.Ctx, lock.ID, nil) - suite.Require().NoError(err) - - // unlock 1s after begin unlock - lock, err = lockKeeper.GetLockByID(suite.Ctx, 1) - suite.Require().NoError(err) - err = lockKeeper.UnlockMaturedLock(suite.Ctx.WithBlockTime(now.Add(time.Second*2)), lock.ID) - suite.Require().NoError(err) - - // check locks - locks, err = lockKeeper.GetPeriodLocks(suite.Ctx) - suite.Require().NoError(err) - suite.Require().Len(locks, 0) -} - func (suite *KeeperTestSuite) TestUnlock() { - // test for coin unlocking suite.SetupTest() - now := suite.Ctx.BlockTime() - - addr1 := sdk.AccAddress([]byte("addr1---------------")) - coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} - - // lock with balance - suite.FundAcc(addr1, coins) - lock, err := suite.App.LockupKeeper.CreateLock(suite.Ctx, addr1, coins, time.Second) - suite.Require().NoError(err) - - // begin unlock with lock object - err = suite.App.LockupKeeper.BeginUnlock(suite.Ctx, lock.ID, nil) - suite.Require().NoError(err) - - lockPtr, err := suite.App.LockupKeeper.GetLockByID(suite.Ctx, lock.ID) - suite.Require().NoError(err) + initialLockCoins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} + + testCases := []struct { + name string + unlockingCoins sdk.Coins + expectedBeginUnlockPass bool + passedTime time.Duration + expectedUnlockMaturedLockPass bool + balanceAfterUnlock sdk.Coins + }{ + { + name: "normal unlocking case", + unlockingCoins: initialLockCoins, + expectedBeginUnlockPass: true, + passedTime: time.Second, + expectedUnlockMaturedLockPass: true, + balanceAfterUnlock: initialLockCoins, + }, + { + name: "begin unlocking with nil as unlocking coins", + unlockingCoins: nil, + expectedBeginUnlockPass: true, + passedTime: time.Second, + expectedUnlockMaturedLockPass: true, + balanceAfterUnlock: initialLockCoins, + }, + { + name: "unlocking coins exceed what's in lock", + unlockingCoins: sdk.Coins{sdk.NewInt64Coin("stake", 20)}, + passedTime: time.Second, + expectedUnlockMaturedLockPass: false, + balanceAfterUnlock: sdk.Coins{}, + }, + { + name: "unlocking unknown tokens", + unlockingCoins: sdk.Coins{sdk.NewInt64Coin("unknown", 10)}, + passedTime: time.Second, + expectedUnlockMaturedLockPass: false, + balanceAfterUnlock: sdk.Coins{}, + }, + { + name: "partial unlocking", + unlockingCoins: sdk.Coins{sdk.NewInt64Coin("stake", 5)}, + expectedBeginUnlockPass: true, + passedTime: time.Second, + expectedUnlockMaturedLockPass: true, + balanceAfterUnlock: sdk.Coins{sdk.NewInt64Coin("stake", 5)}, + }, + { + name: "partial unlocking unknown tokens", + unlockingCoins: sdk.Coins{sdk.NewInt64Coin("unknown", 5)}, + passedTime: time.Second, + expectedUnlockMaturedLockPass: false, + balanceAfterUnlock: sdk.Coins{}, + }, + { + name: "unlocking should not finish yet", + unlockingCoins: initialLockCoins, + expectedBeginUnlockPass: true, + passedTime: time.Millisecond, + expectedUnlockMaturedLockPass: false, + balanceAfterUnlock: sdk.Coins{}, + }, + } - // unlock with lock object - err = suite.App.LockupKeeper.UnlockMaturedLock(suite.Ctx.WithBlockTime(now.Add(time.Second)), lockPtr.ID) - suite.Require().NoError(err) -} + for _, tc := range testCases { + suite.SetupTest() + lockupKeeper := suite.App.LockupKeeper + bankKeeper := suite.App.BankKeeper + ctx := suite.Ctx -func (suite *KeeperTestSuite) TestPartialUnlock() { - suite.SetupTest() - now := suite.Ctx.BlockTime() + addr1 := sdk.AccAddress([]byte("addr1---------------")) + lock := types.NewPeriodLock(1, addr1, time.Second, time.Time{}, initialLockCoins) - addr1 := sdk.AccAddress([]byte("addr1---------------")) - coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} + // lock with balance + suite.FundAcc(addr1, initialLockCoins) + lock, err := lockupKeeper.CreateLock(ctx, addr1, initialLockCoins, time.Second) + suite.Require().NoError(err) - // lock with balance - suite.FundAcc(addr1, coins) - lock, err := suite.App.LockupKeeper.CreateLock(suite.Ctx, addr1, coins, time.Second) - suite.Require().NoError(err) + // store in variable if we're testing partial unlocking for future use + partialUnlocking := tc.unlockingCoins.IsAllLT(initialLockCoins) && tc.unlockingCoins != nil - // check unlocking coins - unlockings := suite.App.LockupKeeper.GetAccountUnlockingCoins(suite.Ctx, addr1) - suite.Require().Equal(len(unlockings), 0) + // begin unlocking + err = lockupKeeper.BeginUnlock(ctx, lock.ID, tc.unlockingCoins) - // check locked coins - locked := suite.App.LockupKeeper.GetAccountLockedCoins(suite.Ctx, addr1) - suite.Require().Equal(len(locked), 1) - suite.Require().Equal(locked[0].Amount.Int64(), int64(10)) + if tc.expectedBeginUnlockPass { + suite.Require().NoError(err) - // test exceeding coins - exceedingCoins := sdk.Coins{sdk.NewInt64Coin("stake", 15)} - err = suite.App.LockupKeeper.BeginUnlock(suite.Ctx, lock.ID, exceedingCoins) - suite.Require().Error(err) + // check unlocking coins. When a lock is a partial lock + // (i.e. tc.unlockingCoins is not nit and less than initialLockCoins), + // we only unlock the partial amount of tc.unlockingCoins + expectedUnlockingCoins := tc.unlockingCoins + if expectedUnlockingCoins == nil { + expectedUnlockingCoins = initialLockCoins + } + actualUnlockingCoins := suite.App.LockupKeeper.GetAccountUnlockingCoins(suite.Ctx, addr1) + suite.Require().Equal(len(actualUnlockingCoins), 1) + suite.Require().Equal(expectedUnlockingCoins[0].Amount, actualUnlockingCoins[0].Amount) - // test invalid coins - invalidCoins := sdk.Coins{sdk.NewInt64Coin("unknown", 1)} - err = suite.App.LockupKeeper.BeginUnlock(suite.Ctx, lock.ID, invalidCoins) - suite.Require().Error(err) + lock = lockupKeeper.GetAccountPeriodLocks(ctx, addr1)[0] - // begin unlock partial amount - partialCoins := sdk.Coins{sdk.NewInt64Coin("stake", 1)} - err = suite.App.LockupKeeper.BeginUnlock(suite.Ctx, lock.ID, partialCoins) - suite.Require().NoError(err) + // if it is partial unlocking, get the new partial lock id + if partialUnlocking { + lock = lockupKeeper.GetAccountPeriodLocks(ctx, addr1)[1] + } - // check unlocking coins - unlockings = suite.App.LockupKeeper.GetAccountUnlockingCoins(suite.Ctx, addr1) - suite.Require().Equal(len(unlockings), 1) - suite.Require().Equal(unlockings[0].Amount.Int64(), int64(1)) + // check lock state + suite.Require().Equal(ctx.BlockTime().Add(lock.Duration), lock.EndTime) + suite.Require().Equal(true, lock.IsUnlocking()) - // check locked coins - locked = suite.App.LockupKeeper.GetAccountLockedCoins(suite.Ctx, addr1) - suite.Require().Equal(len(locked), 1) - suite.Require().Equal(locked[0].Amount.Int64(), int64(10)) + } else { + suite.Require().Error(err) - // check locked coins after the unlocking period - locked = suite.App.LockupKeeper.GetAccountLockedCoins(suite.Ctx.WithBlockTime(now.Add(time.Second)), addr1) - suite.Require().Equal(len(locked), 1) - suite.Require().Equal(locked[0].Amount.Int64(), int64(9)) + // check unlocking coins, should not be unlocking any coins + unlockingCoins := suite.App.LockupKeeper.GetAccountUnlockingCoins(suite.Ctx, addr1) + suite.Require().Equal(len(unlockingCoins), 0) - // Finish unlocking partial unlock - partialUnlock := suite.App.LockupKeeper.GetAccountPeriodLocks(suite.Ctx, addr1)[1] - err = suite.App.LockupKeeper.UnlockMaturedLock(suite.Ctx.WithBlockTime(now.Add(time.Second)), partialUnlock.ID) - suite.Require().NoError(err) + lockedCoins := suite.App.LockupKeeper.GetAccountLockedCoins(suite.Ctx, addr1) + suite.Require().Equal(len(lockedCoins), 1) + suite.Require().Equal(initialLockCoins[0], lockedCoins[0]) + } - // check unlocking coins - unlockings = suite.App.LockupKeeper.GetAccountUnlockingCoins(suite.Ctx, addr1) - suite.Require().Equal(len(unlockings), 0) + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(tc.passedTime)) + + err = lockupKeeper.UnlockMaturedLock(ctx, lock.ID) + if tc.expectedUnlockMaturedLockPass { + suite.Require().NoError(err) + + unlockings := lockupKeeper.GetAccountUnlockingCoins(ctx, addr1) + suite.Require().Equal(len(unlockings), 0) + } else { + suite.Require().Error(err) + // things to test if unlocking has started + if tc.expectedBeginUnlockPass { + // should still be unlocking if `UnlockMaturedLock` failed + actualUnlockingCoins := suite.App.LockupKeeper.GetAccountUnlockingCoins(suite.Ctx, addr1) + suite.Require().Equal(len(actualUnlockingCoins), 1) + + expectedUnlockingCoins := tc.unlockingCoins + if tc.unlockingCoins == nil { + actualUnlockingCoins = initialLockCoins + } + suite.Require().Equal(expectedUnlockingCoins, actualUnlockingCoins) + } + } - // check locked coins - locked = suite.App.LockupKeeper.GetAccountLockedCoins(suite.Ctx, addr1) - suite.Require().Equal(len(locked), 1) - suite.Require().Equal(locked[0].Amount.Int64(), int64(9)) + balance := bankKeeper.GetAllBalances(ctx, addr1) + suite.Require().Equal(tc.balanceAfterUnlock, balance) + } } func (suite *KeeperTestSuite) TestModuleLockedCoins() { From 4fb906fece7d78c22226dda27eb951738c78ad82 Mon Sep 17 00:00:00 2001 From: Richard Liu Date: Wed, 6 Jul 2022 09:02:44 -0700 Subject: [PATCH 034/376] rename params.go to pool_params.go, consolidate pool functions to pool.go (#1978) --- x/gamm/pool-models/stableswap/pool.go | 18 +++++++++++++ .../stableswap/{params.go => pool_params.go} | 0 .../pool-models/stableswap/stableswap_pool.go | 27 ------------------- 3 files changed, 18 insertions(+), 27 deletions(-) rename x/gamm/pool-models/stableswap/{params.go => pool_params.go} (100%) delete mode 100644 x/gamm/pool-models/stableswap/stableswap_pool.go diff --git a/x/gamm/pool-models/stableswap/pool.go b/x/gamm/pool-models/stableswap/pool.go index 21959fce7e3..8ab7e1f962a 100644 --- a/x/gamm/pool-models/stableswap/pool.go +++ b/x/gamm/pool-models/stableswap/pool.go @@ -15,6 +15,24 @@ import ( var _ types.PoolI = &Pool{} +// NewStableswapPool returns a stableswap pool +// Invariants that are assumed to be satisfied and not checked: +// * len(initialLiquidity) = 2 +// * FutureGovernor is valid +// * poolID doesn't already exist +func NewStableswapPool(poolId uint64, stableswapPoolParams PoolParams, initialLiquidity sdk.Coins, futureGovernor string) (Pool, error) { + pool := Pool{ + Address: types.NewPoolAddress(poolId).String(), + Id: poolId, + PoolParams: stableswapPoolParams, + TotalShares: sdk.NewCoin(types.GetPoolShareDenom(poolId), types.InitPoolSharesSupply), + PoolLiquidity: initialLiquidity, + FuturePoolGovernor: futureGovernor, + } + + return pool, nil +} + func (p Pool) GetAddress() sdk.AccAddress { addr, err := sdk.AccAddressFromBech32(p.Address) if err != nil { diff --git a/x/gamm/pool-models/stableswap/params.go b/x/gamm/pool-models/stableswap/pool_params.go similarity index 100% rename from x/gamm/pool-models/stableswap/params.go rename to x/gamm/pool-models/stableswap/pool_params.go diff --git a/x/gamm/pool-models/stableswap/stableswap_pool.go b/x/gamm/pool-models/stableswap/stableswap_pool.go deleted file mode 100644 index d7c6f31adf6..00000000000 --- a/x/gamm/pool-models/stableswap/stableswap_pool.go +++ /dev/null @@ -1,27 +0,0 @@ -package stableswap - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" -) - -var _ types.PoolI = &Pool{} - -// NewStableswapPool returns a stableswap pool -// Invariants that are assumed to be satisfied and not checked: -// * len(initialLiquidity) = 2 -// * FutureGovernor is valid -// * poolID doesn't already exist -func NewStableswapPool(poolId uint64, stableswapPoolParams PoolParams, initialLiquidity sdk.Coins, futureGovernor string) (Pool, error) { - pool := Pool{ - Address: types.NewPoolAddress(poolId).String(), - Id: poolId, - PoolParams: stableswapPoolParams, - TotalShares: sdk.NewCoin(types.GetPoolShareDenom(poolId), types.InitPoolSharesSupply), - PoolLiquidity: initialLiquidity, - FuturePoolGovernor: futureGovernor, - } - - return pool, nil -} From 28417c0b065c56d0afe6ef75511761c5d0f119d0 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Wed, 6 Jul 2022 17:52:25 -0500 Subject: [PATCH 035/376] Remove the EndBlock ordering constraints, that didn't matter before (#1981) * Remove the EndBlock ordering constraints, that didn't matter before * Remove unused superfluid end block logic --- app/modules.go | 7 +------ x/superfluid/abci.go | 7 ------- x/superfluid/module.go | 1 - 3 files changed, 1 insertion(+), 14 deletions(-) diff --git a/app/modules.go b/app/modules.go index add97dcd9cf..a78d320139a 100644 --- a/app/modules.go +++ b/app/modules.go @@ -183,13 +183,8 @@ func orderBeginBlockers() []string { func OrderEndBlockers(allModuleNames []string) []string { ord := partialord.NewPartialOrdering(allModuleNames) - // Epochs must run after all other end blocks - ord.LastElements(epochstypes.ModuleName) - // txfees auto-swap code should occur before any potential gamm end block code. - ord.Before(txfeestypes.ModuleName, gammtypes.ModuleName) - // only remaining modules that aren;t no-ops are: crisis & govtypes + // only Osmosis modules with endblock code are: crisis, govtypes, staking // we don't care about the relative ordering between them. - return ord.TotalOrdering() } diff --git a/x/superfluid/abci.go b/x/superfluid/abci.go index cf27e4b7ada..04e246c7eb8 100644 --- a/x/superfluid/abci.go +++ b/x/superfluid/abci.go @@ -1,8 +1,6 @@ package superfluid import ( - abci "github.com/tendermint/tendermint/abci/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" @@ -19,8 +17,3 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper, ek types.EpochKeeper) { k.AfterEpochStartBeginBlock(ctx) } } - -// Called every block to automatically unlock matured locks. -func EndBlocker(ctx sdk.Context, k keeper.Keeper) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/superfluid/module.go b/x/superfluid/module.go index 0c841e5a6da..1002cba8859 100644 --- a/x/superfluid/module.go +++ b/x/superfluid/module.go @@ -187,7 +187,6 @@ func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { // EndBlock executes all ABCI EndBlock logic respective to the capability module. It // returns no validator updates. func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - EndBlocker(ctx, am.keeper) return []abci.ValidatorUpdate{} } From a364494a3ac7f9d369b88ac0c3c29cb0f3542a16 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Wed, 6 Jul 2022 20:36:31 -0500 Subject: [PATCH 036/376] Add TWAP stub package (#1982) * Add TWAP stub package * Fix unused lint --- x/gamm/twap/README.md | 9 +++ x/gamm/twap/abci.go | 13 ++++ x/gamm/twap/hook_listener.go | 31 ++++++++ x/gamm/twap/keeper.go | 8 ++ x/gamm/twap/module.go | 137 +++++++++++++++++++++++++++++++++++ x/gamm/twap/store.go | 30 ++++++++ x/gamm/twap/types/keys.go | 15 ++++ 7 files changed, 243 insertions(+) create mode 100644 x/gamm/twap/README.md create mode 100644 x/gamm/twap/abci.go create mode 100644 x/gamm/twap/hook_listener.go create mode 100644 x/gamm/twap/keeper.go create mode 100644 x/gamm/twap/module.go create mode 100644 x/gamm/twap/store.go create mode 100644 x/gamm/twap/types/keys.go diff --git a/x/gamm/twap/README.md b/x/gamm/twap/README.md new file mode 100644 index 00000000000..6afca121295 --- /dev/null +++ b/x/gamm/twap/README.md @@ -0,0 +1,9 @@ +# TWAP + +We maintain TWAP entries for every gamm pool. + +NOTE: Not yet integrated into state machine, this package is a stub. + +## Basic architecture notes + +We maintain the list of pools altered within in a block \ No newline at end of file diff --git a/x/gamm/twap/abci.go b/x/gamm/twap/abci.go new file mode 100644 index 00000000000..060da2b2525 --- /dev/null +++ b/x/gamm/twap/abci.go @@ -0,0 +1,13 @@ +package twap + +import sdk "github.com/cosmos/cosmos-sdk/types" + +func (k twapkeeper) endBlockLogic(ctx sdk.Context) { + // TODO: Update TWAP entries + // step 1: Get all altered pool ids + changedPoolIds := k.getChangedPools(ctx) + if len(changedPoolIds) == 0 { + return + } + // 'altered pool ids' should be automatically cleared +} diff --git a/x/gamm/twap/hook_listener.go b/x/gamm/twap/hook_listener.go new file mode 100644 index 00000000000..4b84676b3d4 --- /dev/null +++ b/x/gamm/twap/hook_listener.go @@ -0,0 +1,31 @@ +package twap + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +var _ types.GammHooks = &gammhook{} + +type gammhook struct { + k twapkeeper +} + +// AfterPoolCreated is called after CreatePool +func (hook *gammhook) AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, poolId uint64) { + // TODO: Log pool creation to begin creating TWAPs for it +} + +func (hook *gammhook) AfterSwap(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) { + // Log that this pool had a potential spot price change + hook.k.trackChangedPool(ctx, poolId) +} + +func (hook *gammhook) AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, enterCoins sdk.Coins, shareOutAmount sdk.Int) { + // Log that this pool had a potential spot price change + hook.k.trackChangedPool(ctx, poolId) +} + +func (hook *gammhook) AfterExitPool(_ sdk.Context, _ sdk.AccAddress, _ uint64, _ sdk.Int, _ sdk.Coins) { +} diff --git a/x/gamm/twap/keeper.go b/x/gamm/twap/keeper.go new file mode 100644 index 00000000000..b3a189b2701 --- /dev/null +++ b/x/gamm/twap/keeper.go @@ -0,0 +1,8 @@ +package twap + +import sdk "github.com/cosmos/cosmos-sdk/types" + +type twapkeeper struct { + // storeKey sdk.StoreKey + transientKey sdk.TransientStoreKey +} diff --git a/x/gamm/twap/module.go b/x/gamm/twap/module.go new file mode 100644 index 00000000000..1601969b775 --- /dev/null +++ b/x/gamm/twap/module.go @@ -0,0 +1,137 @@ +package twap + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + + "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" + twaptypes "github.com/osmosis-labs/osmosis/v7/x/gamm/twap/types" + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +type AppModuleBasic struct { + cdc codec.Codec +} + +func (AppModuleBasic) Name() string { return twaptypes.ModuleName } + +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +} + +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return json.RawMessage{} + // return cdc.MustMarshalJSON(types.DefaultGenesis()) +} + +// ValidateGenesis performs genesis state validation for the gamm module. +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + // var genState types.GenesisState + // if err := cdc.UnmarshalJSON(bz, &genState); err != nil { + // return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + // } + // return genState.Validate() + return nil +} + +//--------------------------------------- +// Interfaces. +func (b AppModuleBasic) RegisterRESTRoutes(ctx client.Context, r *mux.Router) { +} +func (b AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) //nolint:errcheck +} + +func (b AppModuleBasic) GetTxCmd() *cobra.Command { + return nil + // return cli.NewTxCmd() +} +func (b AppModuleBasic) GetQueryCmd() *cobra.Command { + return nil + // return cli.GetQueryCmd() +} + +// RegisterInterfaces registers interfaces and implementations of the gamm module. +func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +} + +type AppModule struct { + AppModuleBasic + + ak types.AccountKeeper + bk types.BankKeeper + gk keeper.Keeper + tk twapkeeper +} + +func (am AppModule) RegisterServices(cfg module.Configurator) { +} + +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, + accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, +) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{cdc: cdc}, + gk: keeper, + ak: accountKeeper, + bk: bankKeeper, + } +} + +func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { +} + +func (am AppModule) Route() sdk.Route { + return sdk.Route{} +} + +// QuerierRoute returns the gamm module's querier route name. +func (AppModule) QuerierRoute() string { return types.RouterKey } + +// LegacyQuerierHandler returns the x/gamm module's sdk.Querier. +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return func(sdk.Context, []string, abci.RequestQuery) ([]byte, error) { + return nil, fmt.Errorf("legacy querier not supported for the x/%s module", types.ModuleName) + } +} + +// InitGenesis performs genesis initialization for the gamm module. It returns +// no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the exported genesis state as raw bytes for the gamm +// module. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + return json.RawMessage{} +} + +// BeginBlock performs a no-op. +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} + +// EndBlock returns the end blocker for the gamm module. It returns no validator +// updates. +func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + am.tk.endBlockLogic(ctx) + return []abci.ValidatorUpdate{} +} + +// ConsensusVersion implements AppModule/ConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return 1 } diff --git a/x/gamm/twap/store.go b/x/gamm/twap/store.go new file mode 100644 index 00000000000..171a678f897 --- /dev/null +++ b/x/gamm/twap/store.go @@ -0,0 +1,30 @@ +package twap + +import ( + "encoding/binary" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (k twapkeeper) trackChangedPool(ctx sdk.Context, poolId uint64) { + store := ctx.TransientStore(&k.transientKey) + poolIdBz := make([]byte, 8) + binary.LittleEndian.PutUint64(poolIdBz, poolId) + // just has to not be empty, for store to work / not register as a delete. + sentinelExistsValue := []byte{1} + store.Set(poolIdBz, sentinelExistsValue) +} + +func (k twapkeeper) getChangedPools(ctx sdk.Context) []uint64 { + store := ctx.TransientStore(&k.transientKey) + iter := store.Iterator(nil, nil) + defer iter.Close() + + alteredPoolIds := []uint64{} + for ; iter.Key() != nil; iter.Next() { + k := iter.Key() + poolId := binary.LittleEndian.Uint64(k) + alteredPoolIds = append(alteredPoolIds, poolId) + } + return alteredPoolIds +} diff --git a/x/gamm/twap/types/keys.go b/x/gamm/twap/types/keys.go new file mode 100644 index 00000000000..c20ffdd8abf --- /dev/null +++ b/x/gamm/twap/types/keys.go @@ -0,0 +1,15 @@ +package types + +const ( + ModuleName = "twap" + + StoreKey = ModuleName + TransientStoreKey = "transient_" + ModuleName // this is silly we have to do this + RouterKey = ModuleName + + QuerierRoute = ModuleName +) + +var ( + AlteredPoolIdsPrefix = []byte{0} +) From 73a585303d350fd9c66fb22ac5a8b20a9659ad7a Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Wed, 6 Jul 2022 21:49:37 -0500 Subject: [PATCH 037/376] x/incentives: protobuf updates (#1984) * proto updates * Update proto/osmosis/incentives/gauge.proto Co-authored-by: Dev Ojha * Update proto/osmosis/incentives/gauge.proto Co-authored-by: Dev Ojha * proto linter * address Roman comments (proto standards) Co-authored-by: Dev Ojha --- proto/osmosis/incentives/gauge.proto | 39 +++++----- proto/osmosis/incentives/genesis.proto | 10 ++- proto/osmosis/incentives/params.proto | 3 +- proto/osmosis/incentives/query.proto | 73 ++++++++++++------ proto/osmosis/incentives/tx.proto | 24 ++++-- x/incentives/types/gauge.pb.go | 39 +++++----- x/incentives/types/genesis.pb.go | 16 ++-- x/incentives/types/params.pb.go | 3 +- x/incentives/types/query.pb.go | 102 ++++++++++++++++--------- x/incentives/types/tx.pb.go | 31 +++++--- 10 files changed, 215 insertions(+), 125 deletions(-) diff --git a/proto/osmosis/incentives/gauge.proto b/proto/osmosis/incentives/gauge.proto index 5f9cbd0741e..1f5fd02a0dd 100644 --- a/proto/osmosis/incentives/gauge.proto +++ b/proto/osmosis/incentives/gauge.proto @@ -9,41 +9,41 @@ import "osmosis/lockup/lock.proto"; option go_package = "github.com/osmosis-labs/osmosis/v7/x/incentives/types"; -// Gauge is a struct that works as a single unit for each distribution of -// incentives defined by x/incentives module. +// Gauge is an object that stores and distributes yields to recipients who +// satisfy certain conditions. Currently gauges support conditions around the +// duration for which a given denom is locked. message Gauge { - // ID is the unique id of the gauge. - // The ID of the gauge is decided upon gauge creation, incrementing by 1 for - // every gauge. + // id is the unique ID of a Gauge uint64 id = 1; - // IsPerpetual defines whether the gauge is perpetual or not. - // A non-perpetual gauge distributes the incentive tokens equally per epoch - // while the gauge is in an active period. - // A perpetual gauge distributes all tokens at a single distribution, mainly - // used to distribute minted osmo to lp token stakers. + // is_perpetual is a flag to show if it's a perpetual or non-perpetual gauge + // Non-perpetual gauges distribute their tokens equally per epoch while the + // gauge is in the active period. Perpetual gauges distribute all their tokens + // at a single time and only distribute their tokens again once the gauge is + // refilled, Intended for use with incentives that get refilled daily. bool is_perpetual = 2; - // DistributeTo is the lock query condition that the gauge reward are to be - // distributed to. + // distribute_to is where the gauge rewards are distributed to. + // This is queried via lock duration or by timestamp osmosis.lockup.QueryCondition distribute_to = 3 [ (gogoproto.nullable) = false ]; - // Coins is the total amount of tokens in the gauge. - // Multiple coins can be distributed. + // coins is the total amount of coins that have been in the gauge + // Can distribute multiple coin denoms repeated cosmos.base.v1beta1.Coin coins = 4 [ (gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" ]; - // StartTime is the distribution start time for the gauge. + // start_time is the distribution start time google.protobuf.Timestamp start_time = 5 [ (gogoproto.stdtime) = true, (gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"start_time\"" ]; - // NumEpochsPaidOver is the number of epochs it takes for the distribution to - // be done. + // num_epochs_paid_over is the number of total epochs distribution will be + // completed over uint64 num_epochs_paid_over = 6; - // FilledEpoch is the number of epochs distributed already. + // filled_epochs is the number of epochs distribution has been completed on + // already uint64 filled_epochs = 7; - // DistributedCoins are the coins already distributed from the gauge. + // distributed_coins are coins that have been distributed already repeated cosmos.base.v1beta1.Coin distributed_coins = 8 [ (gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" @@ -51,6 +51,7 @@ message Gauge { } message LockableDurationsInfo { + // List of incentivised durations that gauges will pay out to repeated google.protobuf.Duration lockable_durations = 1 [ (gogoproto.nullable) = false, (gogoproto.stdduration) = true, diff --git a/proto/osmosis/incentives/genesis.proto b/proto/osmosis/incentives/genesis.proto index b1abf386a64..6010b968c58 100644 --- a/proto/osmosis/incentives/genesis.proto +++ b/proto/osmosis/incentives/genesis.proto @@ -8,15 +8,21 @@ import "osmosis/incentives/gauge.proto"; option go_package = "github.com/osmosis-labs/osmosis/v7/x/incentives/types"; -// GenesisState defines the incentives module's genesis state. +// GenesisState defines the incentives module's various parameters when first +// initialized message GenesisState { - // params defines all the parameters of the module + // params are all the parameters of the module Params params = 1 [ (gogoproto.nullable) = false ]; + // gauges are all gauges that should exist at genesis repeated Gauge gauges = 2 [ (gogoproto.nullable) = false ]; + // lockable_durations are all lockup durations that gauges can be locked for + // in order to recieve incentives repeated google.protobuf.Duration lockable_durations = 3 [ (gogoproto.nullable) = false, (gogoproto.stdduration) = true, (gogoproto.moretags) = "yaml:\"lockable_durations\"" ]; + // last_gauge_id is what the gauge number will increment from when creating + // the next gauge after genesis uint64 last_gauge_id = 4; } diff --git a/proto/osmosis/incentives/params.proto b/proto/osmosis/incentives/params.proto index 47709619aab..9cfa281bb58 100644 --- a/proto/osmosis/incentives/params.proto +++ b/proto/osmosis/incentives/params.proto @@ -7,7 +7,8 @@ option go_package = "github.com/osmosis-labs/osmosis/v7/x/incentives/types"; // Params holds parameters for the incentives module message Params { - // distribution epoch identifier + // distr_epoch_identifier is what epoch type distribution will be triggered by + // (day, week, etc.) string distr_epoch_identifier = 1 [ (gogoproto.moretags) = "yaml:\"distr_epoch_identifier\"" ]; } diff --git a/proto/osmosis/incentives/query.proto b/proto/osmosis/incentives/query.proto index de04142e060..5e66273f917 100644 --- a/proto/osmosis/incentives/query.proto +++ b/proto/osmosis/incentives/query.proto @@ -11,60 +11,63 @@ import "osmosis/lockup/lock.proto"; option go_package = "github.com/osmosis-labs/osmosis/v7/x/incentives/types"; -// Query defines the gRPC querier service. +// Query defines the gRPC querier service service Query { - // returns coins that is going to be distributed + // ModuleToDistributeCoins returns coins that are going to be distributed rpc ModuleToDistributeCoins(ModuleToDistributeCoinsRequest) returns (ModuleToDistributeCoinsResponse) { option (google.api.http).get = "/osmosis/incentives/v1beta1/module_to_distribute_coins"; } - // returns coins that are distributed by module so far + // ModuleDistributedCoins returns coins that are distributed by the module so + // far rpc ModuleDistributedCoins(ModuleDistributedCoinsRequest) returns (ModuleDistributedCoinsResponse) { option (google.api.http).get = "/osmosis/incentives/v1beta1/module_distributed_coins"; } - // returns Gauge by id + // GaugeByID returns gauges by their respective ID rpc GaugeByID(GaugeByIDRequest) returns (GaugeByIDResponse) { option (google.api.http).get = "/osmosis/incentives/v1beta1/gauge_by_id/{id}"; } - // returns gauges both upcoming and active + // Gauges returns both upcoming and active gauges rpc Gauges(GaugesRequest) returns (GaugesResponse) { option (google.api.http).get = "/osmosis/incentives/v1beta1/gauges"; } - // returns active gauges + // ActiveGauges returns active gauges rpc ActiveGauges(ActiveGaugesRequest) returns (ActiveGaugesResponse) { option (google.api.http).get = "/osmosis/incentives/v1beta1/active_gauges"; } - // returns active gauges per denom + // ActiveGaugesPerDenom returns active gauges by denom rpc ActiveGaugesPerDenom(ActiveGaugesPerDenomRequest) returns (ActiveGaugesPerDenomResponse) { option (google.api.http).get = "/osmosis/incentives/v1beta1/active_gauges_per_denom"; } - // returns scheduled gauges + // Returns scheduled gauges that have not yet occured rpc UpcomingGauges(UpcomingGaugesRequest) returns (UpcomingGaugesResponse) { option (google.api.http).get = "/osmosis/incentives/v1beta1/upcoming_gauges"; } - // returns scheduled gauges per denom + // UpcomingGaugesPerDenom returns scheduled gauges that have not yet occured + // by denom rpc UpcomingGaugesPerDenom(UpcomingGaugesPerDenomRequest) returns (UpcomingGaugesPerDenomResponse) { option (google.api.http).get = "/osmosis/incentives/v1beta1/upcoming_gauges_per_denom"; } - // RewardsEst returns an estimate of the rewards at a future specific time. - // The querier either provides an address or a set of locks - // for which they want to find the associated rewards. + // RewardsEst returns an estimate of the rewards from now until a specified + // time in the future The querier either provides an address or a set of locks + // for which they want to find the associated rewards rpc RewardsEst(RewardsEstRequest) returns (RewardsEstResponse) { option (google.api.http).get = "/osmosis/incentives/v1beta1/rewards_est/{owner}"; } - // returns lockable durations that are valid to give incentives + // LockableDurations returns lockable durations that are valid to distribute + // incentives for rpc LockableDurations(QueryLockableDurationsRequest) returns (QueryLockableDurationsResponse) { option (google.api.http).get = @@ -74,6 +77,7 @@ service Query { message ModuleToDistributeCoinsRequest {} message ModuleToDistributeCoinsResponse { + // Coins that have yet to be distributed repeated cosmos.base.v1beta1.Coin coins = 1 [ (gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" @@ -82,72 +86,94 @@ message ModuleToDistributeCoinsResponse { message ModuleDistributedCoinsRequest {} message ModuleDistributedCoinsResponse { + // Coins that have been distributed already repeated cosmos.base.v1beta1.Coin coins = 1 [ (gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" ]; } -message GaugeByIDRequest { uint64 id = 1; } -message GaugeByIDResponse { Gauge gauge = 1; } +message GaugeByIDRequest { + // Gague ID being queried + uint64 id = 1; +} +message GaugeByIDResponse { + // Gauge that corresponds to provided gague ID + Gauge gauge = 1; +} message GaugesRequest { - // pagination defines an pagination for the request. + // Pagination defines pagination for the request cosmos.base.query.v1beta1.PageRequest pagination = 1; } message GaugesResponse { + // Upcoming and active gauges repeated Gauge data = 1 [ (gogoproto.nullable) = false ]; - // pagination defines an pagination for the response. + // Pagination defines pagination for the response cosmos.base.query.v1beta1.PageResponse pagination = 2; } message ActiveGaugesRequest { - // pagination defines an pagination for the request. + // Pagination defines pagination for the request cosmos.base.query.v1beta1.PageRequest pagination = 1; } message ActiveGaugesResponse { + // Active gagues only repeated Gauge data = 1 [ (gogoproto.nullable) = false ]; - // pagination defines an pagination for the response. + // Pagination defines pagination for the response cosmos.base.query.v1beta1.PageResponse pagination = 2; } message ActiveGaugesPerDenomRequest { + // Desired denom when querying active gagues string denom = 1; - // pagination defines an pagination for the request. + // Pagination defines pagination for the request cosmos.base.query.v1beta1.PageRequest pagination = 2; } message ActiveGaugesPerDenomResponse { + // Active gagues that match denom in query repeated Gauge data = 1 [ (gogoproto.nullable) = false ]; - // pagination defines an pagination for the response. + // Pagination defines pagination for the response cosmos.base.query.v1beta1.PageResponse pagination = 2; } message UpcomingGaugesRequest { - // pagination defines an pagination for the request. + // Pagination defines pagination for the request cosmos.base.query.v1beta1.PageRequest pagination = 1; } message UpcomingGaugesResponse { + // Gauges whose distribution is upcoming repeated Gauge data = 1 [ (gogoproto.nullable) = false ]; - // pagination defines an pagination for the response. + // Pagination defines pagination for the response cosmos.base.query.v1beta1.PageResponse pagination = 2; } message UpcomingGaugesPerDenomRequest { + // Filter for upcoming gagues that match specific denom string denom = 1; + // Pagination defines pagination for the request cosmos.base.query.v1beta1.PageRequest pagination = 2; } message UpcomingGaugesPerDenomResponse { + // Upcoming gagues that match denom in query repeated Gauge upcoming_gauges = 1 [ (gogoproto.nullable) = false ]; + // Pagination defines pagination for the response cosmos.base.query.v1beta1.PageResponse pagination = 2; } message RewardsEstRequest { + // Address that is being queried for future estimated rewards string owner = 1 [ (gogoproto.moretags) = "yaml:\"owner\"" ]; + // Lock IDs included in future reward estimation repeated uint64 lock_ids = 2; + // Upper time limit of reward estimation + // Lower limit is current epoch int64 end_epoch = 3; } message RewardsEstResponse { + // Estimated coin rewards that will be recieved at provided address + // from specified locks between current time and end epoch repeated cosmos.base.v1beta1.Coin coins = 1 [ (gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" @@ -156,6 +182,7 @@ message RewardsEstResponse { message QueryLockableDurationsRequest {} message QueryLockableDurationsResponse { + // Time durations that users can lock coins for in order to recieve rewards repeated google.protobuf.Duration lockable_durations = 1 [ (gogoproto.nullable) = false, (gogoproto.stdduration) = true, diff --git a/proto/osmosis/incentives/tx.proto b/proto/osmosis/incentives/tx.proto index 06c76fc9420..f9f2bfd18c4 100644 --- a/proto/osmosis/incentives/tx.proto +++ b/proto/osmosis/incentives/tx.proto @@ -14,34 +14,44 @@ service Msg { rpc AddToGauge(MsgAddToGauge) returns (MsgAddToGaugeResponse); } +// MsgCreateGauge creates a gague to distribute rewards to users message MsgCreateGauge { - // flag to show if it's perpetual or multi-epoch - // distribution incentives by third party + // is_perpetual shows if it's a perpetual or non-perpetual gauge + // Non-perpetual gauges distribute their tokens equally per epoch while the + // gauge is in the active period. Perpetual gauges distribute all their tokens + // at a single time and only distribute their tokens again once the gauge is + // refilled bool is_perpetual = 1; - + // owner is the address of gauge creator string owner = 2 [ (gogoproto.moretags) = "yaml:\"owner\"" ]; - // distribute condition of a lock which meet one of these conditions + // distribute_to show which lock the gauge should distribute to by time + // duration or by timestamp osmosis.lockup.QueryCondition distribute_to = 3 [ (gogoproto.nullable) = false ]; - // can distribute multiple coins + // coins are coin(s) to be distributed by the gauge repeated cosmos.base.v1beta1.Coin coins = 4 [ (gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" ]; - // distribution start time + // start_time is the distribution start time google.protobuf.Timestamp start_time = 5 [ (gogoproto.stdtime) = true, (gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"timestamp\"" ]; - // number of epochs distribution will be done + // num_epochs_paid_over is the number of epochs distribution will be completed + // over uint64 num_epochs_paid_over = 6; } message MsgCreateGaugeResponse {} +// MsgAddToGauge adds coins to a previously created gauge message MsgAddToGauge { + // owner is the gauge owner's address string owner = 1 [ (gogoproto.moretags) = "yaml:\"owner\"" ]; + // gauge_id is the ID of gauge that rewards are getting added to uint64 gauge_id = 2; + // rewards are the coin(s) to add to gauge repeated cosmos.base.v1beta1.Coin rewards = 3 [ (gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" diff --git a/x/incentives/types/gauge.pb.go b/x/incentives/types/gauge.pb.go index 66a5aecc629..36e74c0af84 100644 --- a/x/incentives/types/gauge.pb.go +++ b/x/incentives/types/gauge.pb.go @@ -30,33 +30,33 @@ var _ = time.Kitchen // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// Gauge is a struct that works as a single unit for each distribution of -// incentives defined by x/incentives module. +// Gauge is an object that stores and distributes yields to recipients who +// satisfy certain conditions. Currently gauges support conditions around the +// duration for which a given denom is locked. type Gauge struct { - // ID is the unique id of the gauge. - // The ID of the gauge is decided upon gauge creation, incrementing by 1 for - // every gauge. + // id is the unique ID of a Gauge Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - // IsPerpetual defines whether the gauge is perpetual or not. - // A non-perpetual gauge distributes the incentive tokens equally per epoch - // while the gauge is in an active period. - // A perpetual gauge distributes all tokens at a single distribution, mainly - // used to distribute minted osmo to lp token stakers. + // is_perpetual is a flag to show if it's a perpetual or non-perpetual gauge + // Non-perpetual gauges distribute their tokens equally per epoch while the + // gauge is in the active period. Perpetual gauges distribute all their tokens + // at a single time and only distribute their tokens again once the gauge is + // refilled, Intended for use with incentives that get refilled daily. IsPerpetual bool `protobuf:"varint,2,opt,name=is_perpetual,json=isPerpetual,proto3" json:"is_perpetual,omitempty"` - // DistributeTo is the lock query condition that the gauge reward are to be - // distributed to. + // distribute_to is where the gauge rewards are distributed to. + // This is queried via lock duration or by timestamp DistributeTo types.QueryCondition `protobuf:"bytes,3,opt,name=distribute_to,json=distributeTo,proto3" json:"distribute_to"` - // Coins is the total amount of tokens in the gauge. - // Multiple coins can be distributed. + // coins is the total amount of coins that have been in the gauge + // Can distribute multiple coin denoms Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` - // StartTime is the distribution start time for the gauge. + // start_time is the distribution start time StartTime time.Time `protobuf:"bytes,5,opt,name=start_time,json=startTime,proto3,stdtime" json:"start_time" yaml:"start_time"` - // NumEpochsPaidOver is the number of epochs it takes for the distribution to - // be done. + // num_epochs_paid_over is the number of total epochs distribution will be + // completed over NumEpochsPaidOver uint64 `protobuf:"varint,6,opt,name=num_epochs_paid_over,json=numEpochsPaidOver,proto3" json:"num_epochs_paid_over,omitempty"` - // FilledEpoch is the number of epochs distributed already. + // filled_epochs is the number of epochs distribution has been completed on + // already FilledEpochs uint64 `protobuf:"varint,7,opt,name=filled_epochs,json=filledEpochs,proto3" json:"filled_epochs,omitempty"` - // DistributedCoins are the coins already distributed from the gauge. + // distributed_coins are coins that have been distributed already DistributedCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,8,rep,name=distributed_coins,json=distributedCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"distributed_coins"` } @@ -150,6 +150,7 @@ func (m *Gauge) GetDistributedCoins() github_com_cosmos_cosmos_sdk_types.Coins { } type LockableDurationsInfo struct { + // List of incentivised durations that gauges will pay out to LockableDurations []time.Duration `protobuf:"bytes,1,rep,name=lockable_durations,json=lockableDurations,proto3,stdduration" json:"lockable_durations" yaml:"lockable_durations"` } diff --git a/x/incentives/types/genesis.pb.go b/x/incentives/types/genesis.pb.go index 11ab4018453..0661e2378f7 100644 --- a/x/incentives/types/genesis.pb.go +++ b/x/incentives/types/genesis.pb.go @@ -27,13 +27,19 @@ var _ = time.Kitchen // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// GenesisState defines the incentives module's genesis state. +// GenesisState defines the incentives module's various parameters when first +// initialized type GenesisState struct { - // params defines all the parameters of the module - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - Gauges []Gauge `protobuf:"bytes,2,rep,name=gauges,proto3" json:"gauges"` + // params are all the parameters of the module + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + // gauges are all gauges that should exist at genesis + Gauges []Gauge `protobuf:"bytes,2,rep,name=gauges,proto3" json:"gauges"` + // lockable_durations are all lockup durations that gauges can be locked for + // in order to recieve incentives LockableDurations []time.Duration `protobuf:"bytes,3,rep,name=lockable_durations,json=lockableDurations,proto3,stdduration" json:"lockable_durations" yaml:"lockable_durations"` - LastGaugeId uint64 `protobuf:"varint,4,opt,name=last_gauge_id,json=lastGaugeId,proto3" json:"last_gauge_id,omitempty"` + // last_gauge_id is what the gauge number will increment from when creating + // the next gauge after genesis + LastGaugeId uint64 `protobuf:"varint,4,opt,name=last_gauge_id,json=lastGaugeId,proto3" json:"last_gauge_id,omitempty"` } func (m *GenesisState) Reset() { *m = GenesisState{} } diff --git a/x/incentives/types/params.pb.go b/x/incentives/types/params.pb.go index 1883a77f073..ba4e8aed481 100644 --- a/x/incentives/types/params.pb.go +++ b/x/incentives/types/params.pb.go @@ -25,7 +25,8 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Params holds parameters for the incentives module type Params struct { - // distribution epoch identifier + // distr_epoch_identifier is what epoch type distribution will be triggered by + // (day, week, etc.) DistrEpochIdentifier string `protobuf:"bytes,1,opt,name=distr_epoch_identifier,json=distrEpochIdentifier,proto3" json:"distr_epoch_identifier,omitempty" yaml:"distr_epoch_identifier"` } diff --git a/x/incentives/types/query.pb.go b/x/incentives/types/query.pb.go index 3e188c0cc66..846c7f939a3 100644 --- a/x/incentives/types/query.pb.go +++ b/x/incentives/types/query.pb.go @@ -74,6 +74,7 @@ func (m *ModuleToDistributeCoinsRequest) XXX_DiscardUnknown() { var xxx_messageInfo_ModuleToDistributeCoinsRequest proto.InternalMessageInfo type ModuleToDistributeCoinsResponse struct { + // Coins that have yet to be distributed Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` } @@ -154,6 +155,7 @@ func (m *ModuleDistributedCoinsRequest) XXX_DiscardUnknown() { var xxx_messageInfo_ModuleDistributedCoinsRequest proto.InternalMessageInfo type ModuleDistributedCoinsResponse struct { + // Coins that have been distributed already Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` } @@ -198,6 +200,7 @@ func (m *ModuleDistributedCoinsResponse) GetCoins() github_com_cosmos_cosmos_sdk } type GaugeByIDRequest struct { + // Gague ID being queried Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` } @@ -242,6 +245,7 @@ func (m *GaugeByIDRequest) GetId() uint64 { } type GaugeByIDResponse struct { + // Gauge that corresponds to provided gague ID Gauge *Gauge `protobuf:"bytes,1,opt,name=gauge,proto3" json:"gauge,omitempty"` } @@ -286,7 +290,7 @@ func (m *GaugeByIDResponse) GetGauge() *Gauge { } type GaugesRequest struct { - // pagination defines an pagination for the request. + // Pagination defines pagination for the request Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` } @@ -331,8 +335,9 @@ func (m *GaugesRequest) GetPagination() *query.PageRequest { } type GaugesResponse struct { + // Upcoming and active gauges Data []Gauge `protobuf:"bytes,1,rep,name=data,proto3" json:"data"` - // pagination defines an pagination for the response. + // Pagination defines pagination for the response Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } @@ -384,7 +389,7 @@ func (m *GaugesResponse) GetPagination() *query.PageResponse { } type ActiveGaugesRequest struct { - // pagination defines an pagination for the request. + // Pagination defines pagination for the request Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` } @@ -429,8 +434,9 @@ func (m *ActiveGaugesRequest) GetPagination() *query.PageRequest { } type ActiveGaugesResponse struct { + // Active gagues only Data []Gauge `protobuf:"bytes,1,rep,name=data,proto3" json:"data"` - // pagination defines an pagination for the response. + // Pagination defines pagination for the response Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } @@ -482,8 +488,9 @@ func (m *ActiveGaugesResponse) GetPagination() *query.PageResponse { } type ActiveGaugesPerDenomRequest struct { + // Desired denom when querying active gagues Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // pagination defines an pagination for the request. + // Pagination defines pagination for the request Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } @@ -535,8 +542,9 @@ func (m *ActiveGaugesPerDenomRequest) GetPagination() *query.PageRequest { } type ActiveGaugesPerDenomResponse struct { + // Active gagues that match denom in query Data []Gauge `protobuf:"bytes,1,rep,name=data,proto3" json:"data"` - // pagination defines an pagination for the response. + // Pagination defines pagination for the response Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } @@ -588,7 +596,7 @@ func (m *ActiveGaugesPerDenomResponse) GetPagination() *query.PageResponse { } type UpcomingGaugesRequest struct { - // pagination defines an pagination for the request. + // Pagination defines pagination for the request Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` } @@ -633,8 +641,9 @@ func (m *UpcomingGaugesRequest) GetPagination() *query.PageRequest { } type UpcomingGaugesResponse struct { + // Gauges whose distribution is upcoming Data []Gauge `protobuf:"bytes,1,rep,name=data,proto3" json:"data"` - // pagination defines an pagination for the response. + // Pagination defines pagination for the response Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } @@ -686,7 +695,9 @@ func (m *UpcomingGaugesResponse) GetPagination() *query.PageResponse { } type UpcomingGaugesPerDenomRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` + // Filter for upcoming gagues that match specific denom + Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` + // Pagination defines pagination for the request Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } @@ -738,8 +749,10 @@ func (m *UpcomingGaugesPerDenomRequest) GetPagination() *query.PageRequest { } type UpcomingGaugesPerDenomResponse struct { - UpcomingGauges []Gauge `protobuf:"bytes,1,rep,name=upcoming_gauges,json=upcomingGauges,proto3" json:"upcoming_gauges"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` + // Upcoming gagues that match denom in query + UpcomingGauges []Gauge `protobuf:"bytes,1,rep,name=upcoming_gauges,json=upcomingGauges,proto3" json:"upcoming_gauges"` + // Pagination defines pagination for the response + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } func (m *UpcomingGaugesPerDenomResponse) Reset() { *m = UpcomingGaugesPerDenomResponse{} } @@ -790,9 +803,13 @@ func (m *UpcomingGaugesPerDenomResponse) GetPagination() *query.PageResponse { } type RewardsEstRequest struct { - Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty" yaml:"owner"` - LockIds []uint64 `protobuf:"varint,2,rep,packed,name=lock_ids,json=lockIds,proto3" json:"lock_ids,omitempty"` - EndEpoch int64 `protobuf:"varint,3,opt,name=end_epoch,json=endEpoch,proto3" json:"end_epoch,omitempty"` + // Address that is being queried for future estimated rewards + Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty" yaml:"owner"` + // Lock IDs included in future reward estimation + LockIds []uint64 `protobuf:"varint,2,rep,packed,name=lock_ids,json=lockIds,proto3" json:"lock_ids,omitempty"` + // Upper time limit of reward estimation + // Lower limit is current epoch + EndEpoch int64 `protobuf:"varint,3,opt,name=end_epoch,json=endEpoch,proto3" json:"end_epoch,omitempty"` } func (m *RewardsEstRequest) Reset() { *m = RewardsEstRequest{} } @@ -850,6 +867,8 @@ func (m *RewardsEstRequest) GetEndEpoch() int64 { } type RewardsEstResponse struct { + // Estimated coin rewards that will be recieved at provided address + // from specified locks between current time and end epoch Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` } @@ -930,6 +949,7 @@ func (m *QueryLockableDurationsRequest) XXX_DiscardUnknown() { var xxx_messageInfo_QueryLockableDurationsRequest proto.InternalMessageInfo type QueryLockableDurationsResponse struct { + // Time durations that users can lock coins for in order to recieve rewards LockableDurations []time.Duration `protobuf:"bytes,1,rep,name=lockable_durations,json=lockableDurations,proto3,stdduration" json:"lockable_durations" yaml:"lockable_durations"` } @@ -1083,27 +1103,30 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { - // returns coins that is going to be distributed + // ModuleToDistributeCoins returns coins that are going to be distributed ModuleToDistributeCoins(ctx context.Context, in *ModuleToDistributeCoinsRequest, opts ...grpc.CallOption) (*ModuleToDistributeCoinsResponse, error) - // returns coins that are distributed by module so far + // ModuleDistributedCoins returns coins that are distributed by the module so + // far ModuleDistributedCoins(ctx context.Context, in *ModuleDistributedCoinsRequest, opts ...grpc.CallOption) (*ModuleDistributedCoinsResponse, error) - // returns Gauge by id + // GaugeByID returns gauges by their respective ID GaugeByID(ctx context.Context, in *GaugeByIDRequest, opts ...grpc.CallOption) (*GaugeByIDResponse, error) - // returns gauges both upcoming and active + // Gauges returns both upcoming and active gauges Gauges(ctx context.Context, in *GaugesRequest, opts ...grpc.CallOption) (*GaugesResponse, error) - // returns active gauges + // ActiveGauges returns active gauges ActiveGauges(ctx context.Context, in *ActiveGaugesRequest, opts ...grpc.CallOption) (*ActiveGaugesResponse, error) - // returns active gauges per denom + // ActiveGaugesPerDenom returns active gauges by denom ActiveGaugesPerDenom(ctx context.Context, in *ActiveGaugesPerDenomRequest, opts ...grpc.CallOption) (*ActiveGaugesPerDenomResponse, error) - // returns scheduled gauges + // Returns scheduled gauges that have not yet occured UpcomingGauges(ctx context.Context, in *UpcomingGaugesRequest, opts ...grpc.CallOption) (*UpcomingGaugesResponse, error) - // returns scheduled gauges per denom + // UpcomingGaugesPerDenom returns scheduled gauges that have not yet occured + // by denom UpcomingGaugesPerDenom(ctx context.Context, in *UpcomingGaugesPerDenomRequest, opts ...grpc.CallOption) (*UpcomingGaugesPerDenomResponse, error) - // RewardsEst returns an estimate of the rewards at a future specific time. - // The querier either provides an address or a set of locks - // for which they want to find the associated rewards. + // RewardsEst returns an estimate of the rewards from now until a specified + // time in the future The querier either provides an address or a set of locks + // for which they want to find the associated rewards RewardsEst(ctx context.Context, in *RewardsEstRequest, opts ...grpc.CallOption) (*RewardsEstResponse, error) - // returns lockable durations that are valid to give incentives + // LockableDurations returns lockable durations that are valid to distribute + // incentives for LockableDurations(ctx context.Context, in *QueryLockableDurationsRequest, opts ...grpc.CallOption) (*QueryLockableDurationsResponse, error) } @@ -1207,27 +1230,30 @@ func (c *queryClient) LockableDurations(ctx context.Context, in *QueryLockableDu // QueryServer is the server API for Query service. type QueryServer interface { - // returns coins that is going to be distributed + // ModuleToDistributeCoins returns coins that are going to be distributed ModuleToDistributeCoins(context.Context, *ModuleToDistributeCoinsRequest) (*ModuleToDistributeCoinsResponse, error) - // returns coins that are distributed by module so far + // ModuleDistributedCoins returns coins that are distributed by the module so + // far ModuleDistributedCoins(context.Context, *ModuleDistributedCoinsRequest) (*ModuleDistributedCoinsResponse, error) - // returns Gauge by id + // GaugeByID returns gauges by their respective ID GaugeByID(context.Context, *GaugeByIDRequest) (*GaugeByIDResponse, error) - // returns gauges both upcoming and active + // Gauges returns both upcoming and active gauges Gauges(context.Context, *GaugesRequest) (*GaugesResponse, error) - // returns active gauges + // ActiveGauges returns active gauges ActiveGauges(context.Context, *ActiveGaugesRequest) (*ActiveGaugesResponse, error) - // returns active gauges per denom + // ActiveGaugesPerDenom returns active gauges by denom ActiveGaugesPerDenom(context.Context, *ActiveGaugesPerDenomRequest) (*ActiveGaugesPerDenomResponse, error) - // returns scheduled gauges + // Returns scheduled gauges that have not yet occured UpcomingGauges(context.Context, *UpcomingGaugesRequest) (*UpcomingGaugesResponse, error) - // returns scheduled gauges per denom + // UpcomingGaugesPerDenom returns scheduled gauges that have not yet occured + // by denom UpcomingGaugesPerDenom(context.Context, *UpcomingGaugesPerDenomRequest) (*UpcomingGaugesPerDenomResponse, error) - // RewardsEst returns an estimate of the rewards at a future specific time. - // The querier either provides an address or a set of locks - // for which they want to find the associated rewards. + // RewardsEst returns an estimate of the rewards from now until a specified + // time in the future The querier either provides an address or a set of locks + // for which they want to find the associated rewards RewardsEst(context.Context, *RewardsEstRequest) (*RewardsEstResponse, error) - // returns lockable durations that are valid to give incentives + // LockableDurations returns lockable durations that are valid to distribute + // incentives for LockableDurations(context.Context, *QueryLockableDurationsRequest) (*QueryLockableDurationsResponse, error) } diff --git a/x/incentives/types/tx.pb.go b/x/incentives/types/tx.pb.go index e704c65346e..740c33d7bb7 100644 --- a/x/incentives/types/tx.pb.go +++ b/x/incentives/types/tx.pb.go @@ -35,18 +35,25 @@ var _ = time.Kitchen // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// MsgCreateGauge creates a gague to distribute rewards to users type MsgCreateGauge struct { - // flag to show if it's perpetual or multi-epoch - // distribution incentives by third party - IsPerpetual bool `protobuf:"varint,1,opt,name=is_perpetual,json=isPerpetual,proto3" json:"is_perpetual,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty" yaml:"owner"` - // distribute condition of a lock which meet one of these conditions + // is_perpetual shows if it's a perpetual or non-perpetual gauge + // Non-perpetual gauges distribute their tokens equally per epoch while the + // gauge is in the active period. Perpetual gauges distribute all their tokens + // at a single time and only distribute their tokens again once the gauge is + // refilled + IsPerpetual bool `protobuf:"varint,1,opt,name=is_perpetual,json=isPerpetual,proto3" json:"is_perpetual,omitempty"` + // owner is the address of gauge creator + Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty" yaml:"owner"` + // distribute_to show which lock the gauge should distribute to by time + // duration or by timestamp DistributeTo types.QueryCondition `protobuf:"bytes,3,opt,name=distribute_to,json=distributeTo,proto3" json:"distribute_to"` - // can distribute multiple coins + // coins are coin(s) to be distributed by the gauge Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` - // distribution start time + // start_time is the distribution start time StartTime time.Time `protobuf:"bytes,5,opt,name=start_time,json=startTime,proto3,stdtime" json:"start_time" yaml:"timestamp"` - // number of epochs distribution will be done + // num_epochs_paid_over is the number of epochs distribution will be completed + // over NumEpochsPaidOver uint64 `protobuf:"varint,6,opt,name=num_epochs_paid_over,json=numEpochsPaidOver,proto3" json:"num_epochs_paid_over,omitempty"` } @@ -161,9 +168,13 @@ func (m *MsgCreateGaugeResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgCreateGaugeResponse proto.InternalMessageInfo +// MsgAddToGauge adds coins to a previously created gauge type MsgAddToGauge struct { - Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty" yaml:"owner"` - GaugeId uint64 `protobuf:"varint,2,opt,name=gauge_id,json=gaugeId,proto3" json:"gauge_id,omitempty"` + // owner is the gauge owner's address + Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty" yaml:"owner"` + // gauge_id is the ID of gauge that rewards are getting added to + GaugeId uint64 `protobuf:"varint,2,opt,name=gauge_id,json=gaugeId,proto3" json:"gauge_id,omitempty"` + // rewards are the coin(s) to add to gauge Rewards github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=rewards,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"rewards"` } From fbc91b7984a6fdbf20ad98822704b23db7409315 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Thu, 7 Jul 2022 08:09:15 -0500 Subject: [PATCH 038/376] x/gamm : Fix public/private on GetNextPoolNumber API (#1987) * Fix public/private on GetNextPoolNumber API * Add changelog * Drive by changelog improvement --- CHANGELOG.md | 3 ++- x/gamm/keeper/genesis.go | 4 ++-- x/gamm/keeper/grpc_query.go | 2 +- x/gamm/keeper/pool.go | 22 ++++++++++++++-------- x/gamm/keeper/pool_service.go | 2 +- 5 files changed, 20 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b8b3207a9a0..f349aafd634 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,13 +49,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 #### Golang API breaks +* [#1987](https://github.com/osmosis-labs/osmosis/pull/1987) Remove `GammKeeper.GetNextPoolNumberAndIncrement` in favor of the non-mutative `GammKeeper.GetNextPoolNumber`. * [#1937](https://github.com/osmosis-labs/osmosis/pull/1937) Change `lockupKeeper.ExtendLock` to take in lockID instead of the direct lock struct. * [#1893](https://github.com/osmosis-labs/osmosis/pull/1893) Change `EpochsKeeper.SetEpochInfo` to `AddEpochInfo`, which has more safety checks with it. (Makes it suitable to be called within upgrades) * [#1671](https://github.com/osmosis-labs/osmosis/pull/1671) Remove methods that constitute AppModuleSimulation APIs for several modules' AppModules, which implemented no-ops * [#1671](https://github.com/osmosis-labs/osmosis/pull/1671) Add hourly epochs to `x/epochs` DefaultGenesis. * [#1665](https://github.com/osmosis-labs/osmosis/pull/1665) Delete app/App interface, instead use simapp.App * [#1630](https://github.com/osmosis-labs/osmosis/pull/1630) Delete the v043_temp module, now that we're on an updated SDK version. -* [#1667](https://github.com/osmosis-labs/osmosis/pull/1673) Move wasm-bindings code out of app . +* [#1667](https://github.com/osmosis-labs/osmosis/pull/1673) Move wasm-bindings code out of app package into its own root level package. ### Features diff --git a/x/gamm/keeper/genesis.go b/x/gamm/keeper/genesis.go index bdccb8a4921..e299d4f80f0 100644 --- a/x/gamm/keeper/genesis.go +++ b/x/gamm/keeper/genesis.go @@ -11,7 +11,7 @@ import ( // state, which includes the current live pools, global pool parameters (e.g. pool creation fee), next pool number etc. func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState, unpacker codectypes.AnyUnpacker) { k.SetParams(ctx, genState.Params) - k.SetNextPoolNumber(ctx, genState.NextPoolNumber) + k.setNextPoolNumber(ctx, genState.NextPoolNumber) // Sums up the liquidity in all genesis state pools to find the total liquidity across all pools. // Also adds each genesis state pool to the x/gamm module's state @@ -51,7 +51,7 @@ func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { poolAnys = append(poolAnys, any) } return &types.GenesisState{ - NextPoolNumber: k.GetNextPoolNumberAndIncrement(ctx), + NextPoolNumber: k.GetNextPoolNumber(ctx), Pools: poolAnys, Params: k.GetParams(ctx), } diff --git a/x/gamm/keeper/grpc_query.go b/x/gamm/keeper/grpc_query.go index f95f037c324..5bc9c77c6b2 100644 --- a/x/gamm/keeper/grpc_query.go +++ b/x/gamm/keeper/grpc_query.go @@ -120,7 +120,7 @@ func (q Querier) NumPools(ctx context.Context, _ *types.QueryNumPoolsRequest) (* sdkCtx := sdk.UnwrapSDKContext(ctx) return &types.QueryNumPoolsResponse{ - NumPools: q.Keeper.GetNextPoolNumberAndIncrement(sdkCtx) - 1, + NumPools: q.Keeper.GetNextPoolNumber(sdkCtx) - 1, }, nil } diff --git a/x/gamm/keeper/pool.go b/x/gamm/keeper/pool.go index 357d96a293c..e3639c2d85e 100644 --- a/x/gamm/keeper/pool.go +++ b/x/gamm/keeper/pool.go @@ -196,16 +196,17 @@ func (k Keeper) DeletePool(ctx sdk.Context, poolId uint64) error { // return nil // } -// SetNextPoolNumber sets next pool number. -func (k Keeper) SetNextPoolNumber(ctx sdk.Context, poolNumber uint64) { +// setNextPoolNumber sets next pool number. +func (k Keeper) setNextPoolNumber(ctx sdk.Context, poolNumber uint64) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshal(&gogotypes.UInt64Value{Value: poolNumber}) store.Set(types.KeyNextGlobalPoolNumber, bz) } -// GetNextPoolNumberAndIncrement returns the next pool number, and increments the corresponding state entry. -func (k Keeper) GetNextPoolNumberAndIncrement(ctx sdk.Context) uint64 { - var poolNumber uint64 +// GetNextPoolNumber returns the next pool number. +// TODO: Rename NextPoolNumber to NextPoolId +func (k Keeper) GetNextPoolNumber(ctx sdk.Context) uint64 { + var nextPoolId uint64 store := ctx.KVStore(k.storeKey) bz := store.Get(types.KeyNextGlobalPoolNumber) @@ -219,11 +220,16 @@ func (k Keeper) GetNextPoolNumberAndIncrement(ctx sdk.Context) uint64 { panic(err) } - poolNumber = val.GetValue() + nextPoolId = val.GetValue() } + return nextPoolId +} - k.SetNextPoolNumber(ctx, poolNumber+1) - return poolNumber +// getNextPoolNumberAndIncrement returns the next pool number, and increments the corresponding state entry. +func (k Keeper) getNextPoolNumberAndIncrement(ctx sdk.Context) uint64 { + nextPoolId := k.GetNextPoolNumber(ctx) + k.setNextPoolNumber(ctx, nextPoolId+1) + return nextPoolId } // set ScalingFactors in stable stableswap pools diff --git a/x/gamm/keeper/pool_service.go b/x/gamm/keeper/pool_service.go index 094eea0f4a5..38b6b08d4c2 100644 --- a/x/gamm/keeper/pool_service.go +++ b/x/gamm/keeper/pool_service.go @@ -105,7 +105,7 @@ func (k Keeper) CreatePool(ctx sdk.Context, msg types.CreatePoolMsg) (uint64, er return 0, err } - poolId := k.GetNextPoolNumberAndIncrement(ctx) + poolId := k.getNextPoolNumberAndIncrement(ctx) pool, err := msg.CreatePool(ctx, poolId) if err != nil { return 0, err From b23a4fd2b5dc17efe33be8cca2100a82ec991664 Mon Sep 17 00:00:00 2001 From: Ehsan-saradar Date: Thu, 7 Jul 2022 18:12:31 +0430 Subject: [PATCH 039/376] Feature/add details to join exit pool reponse (#1886) * Add ShareOutAmount and TokenIn fields to MsgJoinPoolResponse * Fix yaml tags * Fix yaml tags of MsgExitPoolResponse * Set TokenOut as exitCoins * Fix tests * Add Changelog * Add requested test updates Co-authored-by: Dev Ojha --- CHANGELOG.md | 4 + go.mod | 2 +- go.sum | 3 +- proto/osmosis/gamm/v1beta1/tx.proto | 19 +- x/gamm/keeper/gas_test.go | 6 +- x/gamm/keeper/msg_server.go | 13 +- x/gamm/keeper/pool_service.go | 16 +- x/gamm/keeper/pool_service_test.go | 31 ++- x/gamm/types/tx.pb.go | 313 +++++++++++++++++++++------- x/superfluid/keeper/unpool_test.go | 2 +- 10 files changed, 307 insertions(+), 102 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f349aafd634..48f18265b6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking Changes + +* [#1889](https://github.com/osmosis-labs/osmosis/pull/1825) Add proto responses to gamm LP messages: + * MsgJoinPoolResponse: share_out_amount and token_in fields + * MsgExitPoolResponse: token_out field * [#1825](https://github.com/osmosis-labs/osmosis/pull/1825) Fixes Interchain Accounts (host side) by adding it to AppModuleBasics * [#1699](https://github.com/osmosis-labs/osmosis/pull/1699) Fixes bug in sig fig rounding on spot price queries for small values diff --git a/go.mod b/go.mod index c2c941e6294..99b414416d5 100644 --- a/go.mod +++ b/go.mod @@ -112,7 +112,7 @@ require ( github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gofrs/flock v0.8.1 // indirect github.com/gogo/gateway v1.1.0 // indirect - github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect + github.com/golang/glog v1.0.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/snappy v0.0.3 // indirect github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2 // indirect diff --git a/go.sum b/go.sum index 931eaad556d..4f0b4409505 100644 --- a/go.sum +++ b/go.sum @@ -487,8 +487,9 @@ github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzw github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= +github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= diff --git a/proto/osmosis/gamm/v1beta1/tx.proto b/proto/osmosis/gamm/v1beta1/tx.proto index 069b0d9d0ff..950357b920f 100644 --- a/proto/osmosis/gamm/v1beta1/tx.proto +++ b/proto/osmosis/gamm/v1beta1/tx.proto @@ -39,7 +39,17 @@ message MsgJoinPool { ]; } -message MsgJoinPoolResponse {} +message MsgJoinPoolResponse { + string share_out_amount = 1 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.moretags) = "yaml:\"share_out_amount\"", + (gogoproto.nullable) = false + ]; + repeated cosmos.base.v1beta1.Coin token_in = 2 [ + (gogoproto.moretags) = "yaml:\"token_in\"", + (gogoproto.nullable) = false + ]; +} // ===================== MsgExitPool message MsgExitPool { @@ -57,7 +67,12 @@ message MsgExitPool { ]; } -message MsgExitPoolResponse {} +message MsgExitPoolResponse { + repeated cosmos.base.v1beta1.Coin token_out = 1 [ + (gogoproto.moretags) = "yaml:\"token_out\"", + (gogoproto.nullable) = false + ]; +} // ===================== MsgSwapExactAmountIn message SwapAmountInRoute { diff --git a/x/gamm/keeper/gas_test.go b/x/gamm/keeper/gas_test.go index 6e6c11fd585..b5dd575306f 100644 --- a/x/gamm/keeper/gas_test.go +++ b/x/gamm/keeper/gas_test.go @@ -23,7 +23,7 @@ func (suite *KeeperTestSuite) measureJoinPoolGas( shareOutAmountMax sdk.Int, maxCoins sdk.Coins, ) uint64 { alreadySpent := suite.Ctx.GasMeter().GasConsumed() - err := suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, addr, poolID, shareOutAmountMax, maxCoins) + _, _, err := suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, addr, poolID, shareOutAmountMax, maxCoins) suite.Require().NoError(err) newSpent := suite.Ctx.GasMeter().GasConsumed() spentNow := newSpent - alreadySpent @@ -76,7 +76,7 @@ func (suite *KeeperTestSuite) TestJoinPoolGas() { suite.Assert().LessOrEqual(int(firstJoinGas), 100000) for i := 1; i < startAveragingAt; i++ { - err := suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, defaultAddr, poolId, minShareOutAmount, sdk.Coins{}) + _, _, err := suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, defaultAddr, poolId, minShareOutAmount, sdk.Coins{}) suite.Require().NoError(err) } @@ -133,7 +133,7 @@ func (suite *KeeperTestSuite) TestRepeatedJoinPoolDistinctDenom() { firstJoinGas := suite.measureJoinPoolGas(defaultAddr, initialPoolId, minShareOutAmount, defaultCoins) for i := 2; i < denomNumber; i++ { - err := suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, defaultAddr, uint64(i), minShareOutAmount, sdk.Coins{}) + _, _, err := suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, defaultAddr, uint64(i), minShareOutAmount, sdk.Coins{}) suite.Require().NoError(err) } diff --git a/x/gamm/keeper/msg_server.go b/x/gamm/keeper/msg_server.go index 3a856ee8e32..357a4da60aa 100644 --- a/x/gamm/keeper/msg_server.go +++ b/x/gamm/keeper/msg_server.go @@ -108,7 +108,7 @@ func (server msgServer) JoinPool(goCtx context.Context, msg *types.MsgJoinPool) return nil, err } - err = server.keeper.JoinPoolNoSwap(ctx, sender, msg.PoolId, msg.ShareOutAmount, msg.TokenInMaxs) + neededLp, sharesOut, err := server.keeper.JoinPoolNoSwap(ctx, sender, msg.PoolId, msg.ShareOutAmount, msg.TokenInMaxs) if err != nil { return nil, err } @@ -125,7 +125,10 @@ func (server msgServer) JoinPool(goCtx context.Context, msg *types.MsgJoinPool) ), }) - return &types.MsgJoinPoolResponse{}, nil + return &types.MsgJoinPoolResponse{ + ShareOutAmount: sharesOut, + TokenIn: neededLp, + }, nil } func (server msgServer) ExitPool(goCtx context.Context, msg *types.MsgExitPool) (*types.MsgExitPoolResponse, error) { @@ -136,7 +139,7 @@ func (server msgServer) ExitPool(goCtx context.Context, msg *types.MsgExitPool) return nil, err } - _, err = server.keeper.ExitPool(ctx, sender, msg.PoolId, msg.ShareInAmount, msg.TokenOutMins) + exitCoins, err := server.keeper.ExitPool(ctx, sender, msg.PoolId, msg.ShareInAmount, msg.TokenOutMins) if err != nil { return nil, err } @@ -153,7 +156,9 @@ func (server msgServer) ExitPool(goCtx context.Context, msg *types.MsgExitPool) ), }) - return &types.MsgExitPoolResponse{}, nil + return &types.MsgExitPoolResponse{ + TokenOut: exitCoins, + }, nil } func (server msgServer) SwapExactAmountIn(goCtx context.Context, msg *types.MsgSwapExactAmountIn) (*types.MsgSwapExactAmountInResponse, error) { diff --git a/x/gamm/keeper/pool_service.go b/x/gamm/keeper/pool_service.go index 38b6b08d4c2..47fe5f03ebe 100644 --- a/x/gamm/keeper/pool_service.go +++ b/x/gamm/keeper/pool_service.go @@ -183,35 +183,35 @@ func (k Keeper) JoinPoolNoSwap( poolId uint64, shareOutAmount sdk.Int, tokenInMaxs sdk.Coins, -) (err error) { +) (tokenIn sdk.Coins, sharesOut sdk.Int, err error) { // all pools handled within this method are pointer references, `JoinPool` directly updates the pools pool, err := k.GetPoolAndPoke(ctx, poolId) if err != nil { - return err + return nil, sdk.ZeroInt(), err } // we do an abstract calculation on the lp liquidity coins needed to have // the designated amount of given shares of the pool without performing swap neededLpLiquidity, err := getMaximalNoSwapLPAmount(ctx, pool, shareOutAmount) if err != nil { - return err + return nil, sdk.ZeroInt(), err } // check that needed lp liquidity does not exceed the given `tokenInMaxs` parameter. Return error if so. // if tokenInMaxs == 0, don't do this check. if tokenInMaxs.Len() != 0 { if !(neededLpLiquidity.DenomsSubsetOf(tokenInMaxs) && tokenInMaxs.IsAllGTE(neededLpLiquidity)) { - return sdkerrors.Wrapf(types.ErrLimitMaxAmount, "TokenInMaxs is less than the needed LP liquidity to this JoinPoolNoSwap,"+ + return nil, sdk.ZeroInt(), sdkerrors.Wrapf(types.ErrLimitMaxAmount, "TokenInMaxs is less than the needed LP liquidity to this JoinPoolNoSwap,"+ " upperbound: %v, needed %v", tokenInMaxs, neededLpLiquidity) } else if !(tokenInMaxs.DenomsSubsetOf(neededLpLiquidity)) { - return sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, "TokenInMaxs includes tokens that are not part of the target pool,"+ + return nil, sdk.ZeroInt(), sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, "TokenInMaxs includes tokens that are not part of the target pool,"+ " input tokens: %v, pool tokens %v", tokenInMaxs, neededLpLiquidity) } } - sharesOut, err := pool.JoinPool(ctx, neededLpLiquidity, pool.GetSwapFee(ctx)) + sharesOut, err = pool.JoinPool(ctx, neededLpLiquidity, pool.GetSwapFee(ctx)) if err != nil { - return err + return nil, sdk.ZeroInt(), err } // sanity check, don't return error as not worth halting the LP. We know its not too much. if sharesOut.LT(shareOutAmount) { @@ -220,7 +220,7 @@ func (k Keeper) JoinPoolNoSwap( } err = k.applyJoinPoolStateChange(ctx, pool, sender, sharesOut, neededLpLiquidity) - return err + return neededLpLiquidity, sharesOut, err } // getMaximalNoSwapLPAmount returns the coins(lp liquidity) needed to get the specified amount of shares in the pool. diff --git a/x/gamm/keeper/pool_service_test.go b/x/gamm/keeper/pool_service_test.go index 850faa886aa..e3929d9c43d 100644 --- a/x/gamm/keeper/pool_service_test.go +++ b/x/gamm/keeper/pool_service_test.go @@ -255,6 +255,7 @@ func (suite *KeeperTestSuite) TestCreateBalancerPool() { // TODO: Add more edge cases around TokenInMaxs not containing every token in pool. func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { + fiveKFooAndBar := sdk.NewCoins(sdk.NewCoin("bar", sdk.NewInt(5000)), sdk.NewCoin("foo", sdk.NewInt(5000))) tests := []struct { fn func(poolId uint64) }{ @@ -262,14 +263,16 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { fn: func(poolId uint64) { keeper := suite.App.GAMMKeeper balancesBefore := suite.App.BankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[1]) - err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{}) + neededLp, sharesOut, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{}) suite.Require().NoError(err) + suite.Require().Equal(types.OneShare.MulRaw(50).String(), sharesOut.String()) suite.Require().Equal(types.OneShare.MulRaw(50).String(), suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], "gamm/pool/1").Amount.String()) balancesAfter := suite.App.BankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[1]) deltaBalances, _ := balancesBefore.SafeSub(balancesAfter) // The pool was created with the 10000foo, 10000bar, and the pool share was minted as 100000000gamm/pool/1. // Thus, to get the 50*OneShare gamm/pool/1, (10000foo, 10000bar) * (1 / 2) balances should be provided. + suite.Require().Equal(deltaBalances.FilterDenoms([]string{"foo", "bar"}).Sort().String(), neededLp.Sort().String()) suite.Require().Equal("5000", deltaBalances.AmountOf("foo").String()) suite.Require().Equal("5000", deltaBalances.AmountOf("bar").String()) @@ -280,14 +283,14 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { { fn: func(poolId uint64) { keeper := suite.App.GAMMKeeper - err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, sdk.NewInt(0), sdk.Coins{}) + _, _, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, sdk.NewInt(0), sdk.Coins{}) suite.Require().Error(err, "can't join the pool with requesting 0 share amount") }, }, { fn: func(poolId uint64) { keeper := suite.App.GAMMKeeper - err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, sdk.NewInt(-1), sdk.Coins{}) + _, _, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, sdk.NewInt(-1), sdk.Coins{}) suite.Require().Error(err, "can't join the pool with requesting negative share amount") }, }, @@ -296,7 +299,7 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { keeper := suite.App.GAMMKeeper // Test the "tokenInMaxs" // In this case, to get the 50 * OneShare amount of share token, the foo, bar token are expected to be provided as 5000 amounts. - err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ + _, _, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ sdk.NewCoin("bar", sdk.NewInt(4999)), sdk.NewCoin("foo", sdk.NewInt(4999)), }) suite.Require().Error(err) @@ -307,13 +310,17 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { keeper := suite.App.GAMMKeeper // Test the "tokenInMaxs" // In this case, to get the 50 * OneShare amount of share token, the foo, bar token are expected to be provided as 5000 amounts. - err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ - sdk.NewCoin("bar", sdk.NewInt(5000)), sdk.NewCoin("foo", sdk.NewInt(5000)), - }) + actualTokenIn, actualSharesOut, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ + fiveKFooAndBar[0], fiveKFooAndBar[1]}) suite.Require().NoError(err) liquidity := suite.App.GAMMKeeper.GetTotalLiquidity(suite.Ctx) suite.Require().Equal("15000bar,15000foo", liquidity.String()) + // TODO: Add these tests to more cases, as part of improving this test structure. + // 100% add, so actualTokenIn = max provided + suite.Require().Equal(fiveKFooAndBar, actualTokenIn) + // shares out was estimated perfectly + suite.Require().Equal(types.OneShare.MulRaw(50), actualSharesOut) }, }, { @@ -322,7 +329,7 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { // Test the "tokenInMaxs" with an additional invalid denom // In this case, to get the 50 * OneShare amount of share token, the foo, bar token are expected to be provided as 5000 amounts. // The test input has the correct amount for each, but also includes an incorrect denom that should cause an error - err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ + _, _, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ sdk.NewCoin("bar", sdk.NewInt(5000)), sdk.NewCoin("foo", sdk.NewInt(5000)), sdk.NewCoin("baz", sdk.NewInt(5000)), }) suite.Require().Error(err) @@ -351,6 +358,7 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { } func (suite *KeeperTestSuite) TestExitPool() { + fiveKFooAndBar := sdk.NewCoins(sdk.NewCoin("bar", sdk.NewInt(5000)), sdk.NewCoin("foo", sdk.NewInt(5000))) tests := []struct { fn func(poolId uint64) }{ @@ -414,10 +422,11 @@ func (suite *KeeperTestSuite) TestExitPool() { // Test the "tokenOutMins" // In this case, to refund the 50000000 amount of share token, the foo, bar token are expected to be refunded as 5000 amounts. - _, err := keeper.ExitPool(suite.Ctx, suite.TestAccs[0], poolId, types.OneShare.MulRaw(50), sdk.Coins{ + exitedCoins, err := keeper.ExitPool(suite.Ctx, suite.TestAccs[0], poolId, types.OneShare.MulRaw(50), sdk.Coins{ sdk.NewCoin("foo", sdk.NewInt(5000)), }) suite.Require().NoError(err) + suite.Require().Equal(fiveKFooAndBar, exitedCoins) }, }, } @@ -505,7 +514,7 @@ func (suite *KeeperTestSuite) TestJoinPoolExitPool_InverseRelationship() { balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) fmt.Println(balanceBeforeJoin.String()) - err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) + _, _, err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) suite.Require().NoError(err) _, err = suite.App.GAMMKeeper.ExitPool(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) @@ -547,7 +556,7 @@ func (suite *KeeperTestSuite) TestActiveBalancerPool() { suite.Ctx = suite.Ctx.WithBlockTime(tc.blockTime) // uneffected by start time - err := suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[0], poolId, types.OneShare.MulRaw(50), sdk.Coins{}) + _, _, err := suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[0], poolId, types.OneShare.MulRaw(50), sdk.Coins{}) suite.Require().NoError(err) _, err = suite.App.GAMMKeeper.ExitPool(suite.Ctx, suite.TestAccs[0], poolId, types.InitPoolSharesSupply.QuoRaw(2), sdk.Coins{}) suite.Require().NoError(err) diff --git a/x/gamm/types/tx.pb.go b/x/gamm/types/tx.pb.go index d2391a299b5..75e649d559d 100644 --- a/x/gamm/types/tx.pb.go +++ b/x/gamm/types/tx.pb.go @@ -94,6 +94,8 @@ func (m *MsgJoinPool) GetTokenInMaxs() []types.Coin { } type MsgJoinPoolResponse struct { + ShareOutAmount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,1,opt,name=share_out_amount,json=shareOutAmount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"share_out_amount" yaml:"share_out_amount"` + TokenIn []types.Coin `protobuf:"bytes,2,rep,name=token_in,json=tokenIn,proto3" json:"token_in" yaml:"token_in"` } func (m *MsgJoinPoolResponse) Reset() { *m = MsgJoinPoolResponse{} } @@ -129,6 +131,13 @@ func (m *MsgJoinPoolResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgJoinPoolResponse proto.InternalMessageInfo +func (m *MsgJoinPoolResponse) GetTokenIn() []types.Coin { + if m != nil { + return m.TokenIn + } + return nil +} + // ===================== MsgExitPool type MsgExitPool struct { Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` @@ -192,6 +201,7 @@ func (m *MsgExitPool) GetTokenOutMins() []types.Coin { } type MsgExitPoolResponse struct { + TokenOut []types.Coin `protobuf:"bytes,1,rep,name=token_out,json=tokenOut,proto3" json:"token_out" yaml:"token_out"` } func (m *MsgExitPoolResponse) Reset() { *m = MsgExitPoolResponse{} } @@ -227,6 +237,13 @@ func (m *MsgExitPoolResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgExitPoolResponse proto.InternalMessageInfo +func (m *MsgExitPoolResponse) GetTokenOut() []types.Coin { + if m != nil { + return m.TokenOut + } + return nil +} + // ===================== MsgSwapExactAmountIn type SwapAmountInRoute struct { PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty" yaml:"pool_id"` @@ -952,77 +969,77 @@ func init() { func init() { proto.RegisterFile("osmosis/gamm/v1beta1/tx.proto", fileDescriptor_cfc8fd3ac7df3247) } var fileDescriptor_cfc8fd3ac7df3247 = []byte{ - // 1108 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x58, 0x4d, 0x6f, 0x1b, 0x45, - 0x18, 0xce, 0xd8, 0x6e, 0x3e, 0x26, 0x4d, 0xe2, 0x6c, 0x93, 0xc6, 0xd9, 0xb6, 0x76, 0x3a, 0x20, - 0x48, 0xa9, 0xba, 0x4b, 0x53, 0x89, 0x22, 0x2e, 0x80, 0x21, 0x08, 0x23, 0x2c, 0x57, 0xdb, 0x4b, - 0xc5, 0xc5, 0x5a, 0xc7, 0x2b, 0x77, 0xd5, 0x78, 0xc6, 0xf2, 0xcc, 0x06, 0x57, 0x48, 0x20, 0xf1, - 0x71, 0x07, 0x21, 0x3e, 0x7e, 0x01, 0xe2, 0x2f, 0x70, 0x80, 0x03, 0x5c, 0x7a, 0xec, 0x8d, 0x8f, - 0x83, 0x85, 0x92, 0x7f, 0xe0, 0x5f, 0x50, 0xed, 0xce, 0xcc, 0xee, 0x7a, 0xbd, 0x6b, 0x7b, 0x93, - 0xb8, 0x3d, 0xd9, 0xde, 0x79, 0xe7, 0x9d, 0x67, 0x9f, 0xf7, 0x99, 0x67, 0xde, 0x31, 0xbc, 0x46, - 0x68, 0x9b, 0x50, 0x9b, 0xea, 0x2d, 0xb3, 0xdd, 0xd6, 0x8f, 0x6e, 0x37, 0x2c, 0x66, 0xde, 0xd6, - 0x59, 0x4f, 0xeb, 0x74, 0x09, 0x23, 0xca, 0x86, 0x18, 0xd6, 0xdc, 0x61, 0x4d, 0x0c, 0xab, 0x1b, - 0x2d, 0xd2, 0x22, 0x5e, 0x80, 0xee, 0x7e, 0xe3, 0xb1, 0x6a, 0xf1, 0xc0, 0x0b, 0xd6, 0x1b, 0x26, - 0xb5, 0xfc,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, 0xb8, 0x28, 0x65, 0xea, - 0x95, 0x7e, 0x6c, 0x25, 0xb6, 0x44, 0x25, 0xd6, 0x86, 0xf5, 0x8d, 0x8c, 0x05, 0xa1, 0x69, 0xe5, - 0x73, 0xb8, 0x11, 0x57, 0x9f, 0x42, 0xce, 0x7b, 0x9d, 0x6a, 0x6a, 0x55, 0x5d, 0x49, 0xae, 0x39, - 0x32, 0xd6, 0x43, 0x25, 0xe7, 0xef, 0x88, 0xbe, 0x07, 0xf0, 0x6a, 0x1c, 0xb3, 0x52, 0x01, 0x0a, - 0x85, 0xf9, 0x20, 0x99, 0x00, 0xc7, 0xb9, 0xae, 0xa4, 0x06, 0xb7, 0x15, 0x05, 0x27, 0x81, 0xad, - 0x4a, 0x60, 0x02, 0xd5, 0x57, 0x00, 0x2a, 0x41, 0x21, 0x6a, 0x0e, 0x3b, 0x85, 0xee, 0xde, 0x91, - 0x1b, 0xc7, 0xc6, 0x53, 0xcb, 0xee, 0xa2, 0x28, 0x0b, 0x57, 0xdd, 0xbf, 0x19, 0xb8, 0x39, 0xca, - 0x4d, 0xcd, 0x61, 0x69, 0x64, 0xf7, 0x41, 0x44, 0x76, 0xbb, 0x93, 0x64, 0x27, 0xdf, 0x36, 0xa2, - 0xbb, 0xcf, 0xe0, 0xa5, 0x18, 0x7b, 0x14, 0xee, 0xf3, 0x71, 0xea, 0x52, 0xa8, 0x89, 0x8e, 0x8b, - 0x8c, 0x7c, 0x60, 0xb8, 0xc2, 0x84, 0xee, 0xc1, 0x25, 0x9f, 0x2b, 0x4f, 0x9a, 0x63, 0x55, 0x5f, - 0x10, 0xaa, 0xcf, 0x47, 0x58, 0x46, 0xc6, 0xa2, 0xac, 0x33, 0xfa, 0x0e, 0xc0, 0x6b, 0xb1, 0xdc, - 0xfa, 0xc2, 0xeb, 0x48, 0xdf, 0x08, 0x36, 0x05, 0x38, 0x9b, 0xd5, 0x46, 0xd2, 0x49, 0x97, 0x91, - 0x56, 0x8b, 0xfe, 0xcc, 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x09, 0x91, - 0xfb, 0xd6, 0xa1, 0xd9, 0xa0, 0xf2, 0x87, 0x7e, 0x74, 0x57, 0xef, 0xf1, 0xbf, 0x0f, 0x3d, 0xcf, - 0x68, 0xcc, 0x7b, 0x7f, 0xf7, 0xdd, 0x79, 0x16, 0x00, 0x00, 0xff, 0xff, 0x5d, 0xdb, 0x47, 0x35, - 0x5b, 0x14, 0x00, 0x00, + // 1119 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x58, 0x4b, 0x6f, 0x1b, 0x45, + 0x1c, 0xcf, 0xd8, 0x6e, 0x1e, 0x93, 0xe6, 0xb5, 0x4d, 0x1a, 0x67, 0xdb, 0xda, 0xe9, 0x80, 0x20, + 0xa5, 0xea, 0x2e, 0x4d, 0x25, 0x8a, 0xb8, 0x00, 0x86, 0x20, 0x8c, 0xb0, 0x5c, 0x6d, 0x2f, 0x15, + 0x17, 0x6b, 0x1d, 0xaf, 0xdc, 0x55, 0xb3, 0x33, 0x96, 0x67, 0x36, 0xb8, 0x42, 0x02, 0x89, 0xc7, + 0x1d, 0x84, 0x78, 0x7c, 0x02, 0xc4, 0x57, 0xe0, 0x00, 0x07, 0xb8, 0xf4, 0xd8, 0x1b, 0x94, 0x83, + 0x85, 0x92, 0x6f, 0xe0, 0x4f, 0x80, 0x76, 0x67, 0xf6, 0xe9, 0xdd, 0xd8, 0x9b, 0xd8, 0xc9, 0x29, + 0xf1, 0xce, 0xff, 0xfd, 0xff, 0xcd, 0xef, 0xff, 0xdf, 0x85, 0x37, 0x08, 0xb5, 0x08, 0x35, 0xa9, + 0xda, 0xd6, 0x2d, 0x4b, 0x3d, 0xbc, 0xdb, 0x34, 0x98, 0x7e, 0x57, 0x65, 0x3d, 0xa5, 0xd3, 0x25, + 0x8c, 0x48, 0xeb, 0xe2, 0x58, 0x71, 0x8e, 0x15, 0x71, 0x2c, 0xaf, 0xb7, 0x49,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, 0xaa, 0x58, 0x23, 0x36, 0x33, 0xc2, 0x4d, 0x00, 0x23, 0x9b, 0x50, + 0x81, 0x2b, 0x41, 0x4e, 0x2d, 0x03, 0x13, 0xcb, 0xed, 0xdc, 0x42, 0x45, 0x0e, 0xca, 0x1a, 0x13, + 0x40, 0xda, 0x92, 0x17, 0xc1, 0xfb, 0xee, 0xef, 0xbf, 0x73, 0x70, 0xbd, 0x46, 0xdb, 0x4e, 0x24, + 0x7b, 0x3d, 0x7d, 0x9f, 0x79, 0xe1, 0x64, 0x41, 0xce, 0x1e, 0x9c, 0xed, 0x3a, 0xd1, 0x53, 0x81, + 0xe0, 0x57, 0x95, 0x24, 0xb6, 0x53, 0x86, 0xb2, 0xad, 0x14, 0x9c, 0x3a, 0x69, 0x42, 0x39, 0x72, + 0x15, 0x1c, 0x30, 0x9d, 0xed, 0x2a, 0x48, 0x9f, 0xc3, 0xf5, 0xa4, 0x8e, 0x17, 0x0b, 0x6e, 0x3a, + 0xb5, 0xcc, 0x38, 0xbd, 0x96, 0x8e, 0x22, 0xa4, 0xad, 0x85, 0x40, 0xc4, 0x73, 0x44, 0xdf, 0x03, + 0x78, 0x3d, 0xa9, 0xb2, 0x61, 0xbe, 0x09, 0x8c, 0x4d, 0x86, 0x6f, 0xe2, 0xf6, 0x90, 0xb6, 0xec, + 0x05, 0x26, 0xa2, 0xfa, 0x0a, 0x40, 0x29, 0x68, 0x44, 0xdd, 0x66, 0xa7, 0xc0, 0xdd, 0x3b, 0xde, + 0x55, 0x34, 0xf1, 0xd8, 0xb0, 0xbb, 0x2c, 0xda, 0xc2, 0x51, 0xf7, 0x22, 0x07, 0x37, 0x86, 0x6b, + 0x53, 0xb7, 0x59, 0x16, 0xd8, 0x7d, 0x10, 0x83, 0xdd, 0xce, 0x28, 0xd8, 0x79, 0xd9, 0xc6, 0x70, + 0xf7, 0x19, 0xbc, 0x92, 0x30, 0x35, 0x04, 0x9f, 0x7d, 0x9c, 0xb9, 0x15, 0x72, 0xea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0x95, 0xea, 0xb3, 0xa3, + 0x12, 0x78, 0x7e, 0x54, 0x02, 0xff, 0x1d, 0x95, 0xc0, 0xb7, 0xc7, 0xa5, 0x99, 0xe7, 0xc7, 0xa5, + 0x99, 0x7f, 0x8e, 0x4b, 0x33, 0x9f, 0xa8, 0x21, 0x9a, 0x10, 0xb6, 0xef, 0x1c, 0xe8, 0x4d, 0xea, + 0xfd, 0x50, 0x0f, 0xef, 0xab, 0x3d, 0xfe, 0x55, 0xd5, 0xe5, 0x8c, 0xe6, 0xac, 0xfb, 0x15, 0xf4, + 0xde, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff, 0x67, 0xe6, 0x5e, 0x56, 0x72, 0x15, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -1436,6 +1453,30 @@ func (m *MsgJoinPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.TokenIn) > 0 { + for iNdEx := len(m.TokenIn) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.TokenIn[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size := m.ShareOutAmount.Size() + i -= size + if _, err := m.ShareOutAmount.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa return len(dAtA) - i, nil } @@ -1518,6 +1559,20 @@ func (m *MsgExitPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.TokenOut) > 0 { + for iNdEx := len(m.TokenOut) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.TokenOut[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } return len(dAtA) - i, nil } @@ -2192,6 +2247,14 @@ func (m *MsgJoinPoolResponse) Size() (n int) { } var l int _ = l + l = m.ShareOutAmount.Size() + n += 1 + l + sovTx(uint64(l)) + if len(m.TokenIn) > 0 { + for _, e := range m.TokenIn { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } return n } @@ -2225,6 +2288,12 @@ func (m *MsgExitPoolResponse) Size() (n int) { } var l int _ = l + if len(m.TokenOut) > 0 { + for _, e := range m.TokenOut { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } return n } @@ -2664,6 +2733,74 @@ func (m *MsgJoinPoolResponse) Unmarshal(dAtA []byte) error { return fmt.Errorf("proto: MsgJoinPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ShareOutAmount", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + 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 ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ShareOutAmount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TokenIn", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TokenIn = append(m.TokenIn, types.Coin{}) + if err := m.TokenIn[len(m.TokenIn)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -2883,6 +3020,40 @@ func (m *MsgExitPoolResponse) Unmarshal(dAtA []byte) error { return fmt.Errorf("proto: MsgExitPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TokenOut", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TokenOut = append(m.TokenOut, types.Coin{}) + if err := m.TokenOut[len(m.TokenOut)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) diff --git a/x/superfluid/keeper/unpool_test.go b/x/superfluid/keeper/unpool_test.go index 0a247960f97..a919f5bc52b 100644 --- a/x/superfluid/keeper/unpool_test.go +++ b/x/superfluid/keeper/unpool_test.go @@ -115,7 +115,7 @@ func (suite *KeeperTestSuite) TestUnpool() { // join pool balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, poolJoinAcc) - err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, poolJoinAcc, poolId, gammtypes.OneShare.MulRaw(50), sdk.Coins{}) + _, _, err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, poolJoinAcc, poolId, gammtypes.OneShare.MulRaw(50), sdk.Coins{}) suite.Require().NoError(err) balanceAfterJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, poolJoinAcc) From f94b4739c55924a39876a80fc9585e8916a460bb Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Thu, 7 Jul 2022 10:15:34 -0400 Subject: [PATCH 040/376] chore: add stalebot to CI (#1992) --- .github/workflows/stalebot.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/stalebot.yml diff --git a/.github/workflows/stalebot.yml b/.github/workflows/stalebot.yml new file mode 100644 index 00000000000..5202e47f86a --- /dev/null +++ b/.github/workflows/stalebot.yml @@ -0,0 +1,27 @@ +name: "Close stale pull requests" +on: + schedule: + - cron: "0 0 * * *" + +permissions: + contents: read + +jobs: + stale: + permissions: + issues: write # for actions/stale to close stale issues + pull-requests: write # for actions/stale to close stale PRs + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v5 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-pr-message: > + This pull request has been automatically marked as stale because it + has not had any recent activity. It will be closed if no further + activity occurs. Thank you! + days-before-stale: -1 + days-before-close: -1 + days-before-pr-stale: 14 + days-before-pr-close: 6 + exempt-pr-labels: "security, proposal, blocked" From 5c49af33d7a6eeff8917b321b8f44d819ce42825 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Thu, 7 Jul 2022 13:18:27 -0400 Subject: [PATCH 041/376] chore: remove legacy msg handlers (#1996) --- x/epochs/handler.go | 24 ---------------- x/epochs/module.go | 2 +- x/gamm/handler.go | 61 ----------------------------------------- x/gamm/module.go | 2 +- x/incentives/handler.go | 31 --------------------- x/incentives/module.go | 2 +- x/lockup/handler.go | 34 ----------------------- x/lockup/module.go | 2 +- x/superfluid/handler.go | 43 ----------------------------- x/superfluid/module.go | 2 +- 10 files changed, 5 insertions(+), 198 deletions(-) delete mode 100644 x/epochs/handler.go delete mode 100644 x/gamm/handler.go delete mode 100644 x/incentives/handler.go delete mode 100644 x/lockup/handler.go delete mode 100644 x/superfluid/handler.go diff --git a/x/epochs/handler.go b/x/epochs/handler.go deleted file mode 100644 index d0c49e4e9be..00000000000 --- a/x/epochs/handler.go +++ /dev/null @@ -1,24 +0,0 @@ -package epochs - -import ( - "fmt" - - "github.com/osmosis-labs/osmosis/v7/x/epochs/keeper" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewHandler returns a handler for epochs module messages. -func NewHandler(k keeper.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - - switch msg := msg.(type) { - default: - errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) - } - } -} diff --git a/x/epochs/module.go b/x/epochs/module.go index b039f640211..ac1201ae189 100644 --- a/x/epochs/module.go +++ b/x/epochs/module.go @@ -109,7 +109,7 @@ func (am AppModule) Name() string { // Route returns the capability module's message routing key. func (am AppModule) Route() sdk.Route { - return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper)) + return sdk.Route{} } // QuerierRoute returns the capability module's query routing key. diff --git a/x/gamm/handler.go b/x/gamm/handler.go deleted file mode 100644 index d9385638a7a..00000000000 --- a/x/gamm/handler.go +++ /dev/null @@ -1,61 +0,0 @@ -package gamm - -import ( - "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewHandler returns a handler for "gamm" type messages. -func NewHandler(k *keeper.Keeper) sdk.Handler { - msgServer := keeper.NewMsgServerImpl(k) - msgBalancerServer := keeper.NewBalancerMsgServerImpl(k) - - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - - switch msg := msg.(type) { - case *types.MsgJoinPool: - res, err := msgServer.JoinPool(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgExitPool: - res, err := msgServer.ExitPool(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *balancer.MsgCreateBalancerPool: - res, err := msgBalancerServer.CreateBalancerPool(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgSwapExactAmountIn: - res, err := msgServer.SwapExactAmountIn(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgSwapExactAmountOut: - res, err := msgServer.SwapExactAmountOut(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgJoinSwapExternAmountIn: - res, err := msgServer.JoinSwapExternAmountIn(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgJoinSwapShareAmountOut: - res, err := msgServer.JoinSwapShareAmountOut(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgExitSwapExternAmountOut: - res, err := msgServer.ExitSwapExternAmountOut(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgExitSwapShareAmountIn: - res, err := msgServer.ExitSwapShareAmountIn(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s message type: %T", types.ModuleName, msg) - } - } -} diff --git a/x/gamm/module.go b/x/gamm/module.go index b9a73752e36..596e57830ce 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -113,7 +113,7 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { // Route returns the message routing key for the gamm module. func (am AppModule) Route() sdk.Route { - return sdk.NewRoute(types.RouterKey, NewHandler(&am.keeper)) + return sdk.Route{} } // QuerierRoute returns the gamm module's querier route name. diff --git a/x/incentives/handler.go b/x/incentives/handler.go deleted file mode 100644 index 06a8d7630a0..00000000000 --- a/x/incentives/handler.go +++ /dev/null @@ -1,31 +0,0 @@ -package incentives - -import ( - "fmt" - - "github.com/osmosis-labs/osmosis/v7/x/incentives/keeper" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewHandler returns msg handler for this module. -func NewHandler(k *keeper.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - msgServer := keeper.NewMsgServerImpl(k) - - switch msg := msg.(type) { - case *types.MsgCreateGauge: - res, err := msgServer.CreateGauge(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - case *types.MsgAddToGauge: - res, err := msgServer.AddToGauge(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - default: - errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) - } - } -} diff --git a/x/incentives/module.go b/x/incentives/module.go index e2ca494c5e8..33d03c93a53 100644 --- a/x/incentives/module.go +++ b/x/incentives/module.go @@ -129,7 +129,7 @@ func (am AppModule) Name() string { // Route returns the capability module's message routing key. func (am AppModule) Route() sdk.Route { - return sdk.NewRoute(types.RouterKey, NewHandler(&am.keeper)) + return sdk.Route{} } // QuerierRoute returns the capability module's query routing key. diff --git a/x/lockup/handler.go b/x/lockup/handler.go deleted file mode 100644 index 3419731de0a..00000000000 --- a/x/lockup/handler.go +++ /dev/null @@ -1,34 +0,0 @@ -package lockup - -import ( - "fmt" - - "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewHandler returns a handler for "lockup" type messages. -func NewHandler(k keeper.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - msgServer := keeper.NewMsgServerImpl(&k) - - switch msg := msg.(type) { - case *types.MsgLockTokens: - res, err := msgServer.LockTokens(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - case *types.MsgBeginUnlocking: - res, err := msgServer.BeginUnlocking(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - case *types.MsgBeginUnlockingAll: - res, err := msgServer.BeginUnlockingAll(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - default: - errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) - } - } -} diff --git a/x/lockup/module.go b/x/lockup/module.go index 9a67eac04d6..1157559f32e 100644 --- a/x/lockup/module.go +++ b/x/lockup/module.go @@ -126,7 +126,7 @@ func (am AppModule) Name() string { // Route returns the capability module's message routing key. func (am AppModule) Route() sdk.Route { - return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper)) + return sdk.Route{} } // QuerierRoute returns the capability module's query routing key. diff --git a/x/superfluid/handler.go b/x/superfluid/handler.go deleted file mode 100644 index 9a26e00d132..00000000000 --- a/x/superfluid/handler.go +++ /dev/null @@ -1,43 +0,0 @@ -package superfluid - -import ( - "fmt" - - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewHandler returns a handler for "superfluid" type messages. -func NewHandler(k *keeper.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - msgServer := keeper.NewMsgServerImpl(k) - - switch msg := msg.(type) { - case *types.MsgSuperfluidDelegate: - res, err := msgServer.SuperfluidDelegate(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - case *types.MsgSuperfluidUndelegate: - res, err := msgServer.SuperfluidUndelegate(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - case *types.MsgSuperfluidUnbondLock: - res, err := msgServer.SuperfluidUnbondLock(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - case *types.MsgLockAndSuperfluidDelegate: - res, err := msgServer.LockAndSuperfluidDelegate(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - case *types.MsgUnPoolWhitelistedPool: - res, err := msgServer.UnPoolWhitelistedPool(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - // case *types.MsgSuperfluidRedelegate: - // res, err := msgServer.SuperfluidRedelegate(sdk.WrapSDKContext(ctx), msg) - // return sdk.WrapServiceResult(ctx, res, err) - default: - errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) - } - } -} diff --git a/x/superfluid/module.go b/x/superfluid/module.go index 1002cba8859..54ae2b9373c 100644 --- a/x/superfluid/module.go +++ b/x/superfluid/module.go @@ -137,7 +137,7 @@ func (am AppModule) Name() string { // Route returns the capability module's message routing key. func (am AppModule) Route() sdk.Route { - return sdk.NewRoute(types.RouterKey, NewHandler(&am.keeper)) + return sdk.Route{} } // QuerierRoute returns the capability module's query routing key. From ed55aebc519cb7d38e4cb5d70c875d2c35021f29 Mon Sep 17 00:00:00 2001 From: vuong <56973102+vuong177@users.noreply.github.com> Date: Fri, 8 Jul 2022 06:44:13 +0700 Subject: [PATCH 042/376] Refactor keeper tests in x/mint (#1952) * TestMintCoinsToFeeCollectorAndGetProportions refactor * TestDistrAssetToDeveloperRewardsAddrWhenNotEmpty refactor * add feePool and feeCollector check * comment * use hasPreExistingSupply and better readable mintKeeper * Update x/mint/keeper/keeper_test.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update x/mint/keeper/keeper_test.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * add testcase when nil dev reward address * use shorter keeper name for better readability Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> --- x/mint/keeper/keeper_test.go | 256 +++++++++++++++++++++-------------- 1 file changed, 154 insertions(+), 102 deletions(-) diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index a7c65186a10..9bc63372497 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -37,21 +37,24 @@ func (suite *KeeperTestSuite) setupDeveloperVestingModuleAccountTest(blockHeight suite.Setup() // Reset height to the desired value since test suite setup initialized // it to 1. + bankKeeper := suite.App.BankKeeper + accountKeeper := suite.App.AccountKeeper + suite.Ctx = suite.Ctx.WithBlockHeader(tmproto.Header{Height: blockHeight}) if !isDeveloperModuleAccountCreated { // Remove the developer vesting account since suite setup creates and initializes it. // This environment w/o the developer vesting account configured is necessary for // testing edge cases of multiple tests. - developerVestingAccount := suite.App.AccountKeeper.GetAccount(suite.Ctx, suite.App.AccountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) - suite.App.AccountKeeper.RemoveAccount(suite.Ctx, developerVestingAccount) - suite.App.BankKeeper.BurnCoins(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(keeper.DeveloperVestingAmount)))) + developerVestingAccount := accountKeeper.GetAccount(suite.Ctx, accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) + accountKeeper.RemoveAccount(suite.Ctx, developerVestingAccount) + bankKeeper.BurnCoins(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(keeper.DeveloperVestingAmount)))) // If developer module account is created, the suite.Setup() also sets the offset, // therefore, we should reset it to 0 to set up the environment truly w/o the module account. - supplyOffset := suite.App.BankKeeper.GetSupplyOffset(suite.Ctx, sdk.DefaultBondDenom) - suite.App.BankKeeper.AddSupplyOffset(suite.Ctx, sdk.DefaultBondDenom, supplyOffset.Mul(sdk.NewInt(-1))) - suite.Equal(sdk.ZeroInt(), suite.App.BankKeeper.GetSupplyOffset(suite.Ctx, sdk.DefaultBondDenom)) + supplyOffset := bankKeeper.GetSupplyOffset(suite.Ctx, sdk.DefaultBondDenom) + bankKeeper.AddSupplyOffset(suite.Ctx, sdk.DefaultBondDenom, supplyOffset.Mul(sdk.NewInt(-1))) + suite.Equal(sdk.ZeroInt(), bankKeeper.GetSupplyOffset(suite.Ctx, sdk.DefaultBondDenom)) } } @@ -60,113 +63,162 @@ func TestKeeperTestSuite(t *testing.T) { } func (suite *KeeperTestSuite) TestMintCoinsToFeeCollectorAndGetProportions() { - mintKeeper := suite.App.MintKeeper - - // When coin is minted to the fee collector - fee := sdk.NewCoin("stake", sdk.NewInt(0)) - fees := sdk.NewCoins(fee) - coin := mintKeeper.GetProportions(suite.Ctx, fee, sdk.NewDecWithPrec(2, 1)) - suite.Equal("0stake", coin.String()) - - // When mint the 100K stake coin to the fee collector - fee = sdk.NewCoin("stake", sdk.NewInt(100000)) - fees = sdk.NewCoins(fee) - - err := simapp.FundModuleAccount(suite.App.BankKeeper, - suite.Ctx, - authtypes.FeeCollectorName, - fees) - suite.NoError(err) - - // check proportion for 20% - coin = mintKeeper.GetProportions(suite.Ctx, fee, sdk.NewDecWithPrec(2, 1)) - suite.Equal(fees[0].Amount.Quo(sdk.NewInt(5)), coin.Amount) -} - -func (suite *KeeperTestSuite) TestDistrAssetToDeveloperRewardsAddrWhenNotEmpty() { - mintKeeper := suite.App.MintKeeper - params := suite.App.MintKeeper.GetParams(suite.Ctx) - devRewardsReceiver := sdk.AccAddress([]byte("addr1---------------")) - gaugeCreator := sdk.AccAddress([]byte("addr2---------------")) - devRewardsReceiver2 := sdk.AccAddress([]byte("addr3---------------")) - devRewardsReceiver3 := sdk.AccAddress([]byte("addr4---------------")) - params.WeightedDeveloperRewardsReceivers = []types.WeightedAddress{ + tests := []struct { + name string + ratio sdk.Dec + hasPreExistingSupply bool + expectedCoin sdk.Coin + fee sdk.Coin + }{ { - Address: devRewardsReceiver.String(), - Weight: sdk.NewDec(1), + name: "coin is minted to the fee collector", + fee: sdk.NewCoin("stake", sdk.NewInt(0)), + ratio: sdk.NewDecWithPrec(2, 1), + hasPreExistingSupply: false, + expectedCoin: sdk.NewCoin("stake", sdk.NewInt(0)), + }, { + name: "mint the 100K stake coin to the fee collector", + fee: sdk.NewCoin("stake", sdk.NewInt(100000)), + ratio: sdk.NewDecWithPrec(2, 1), + hasPreExistingSupply: true, + expectedCoin: sdk.NewCoin("stake", sdk.NewInt(100000).Quo(sdk.NewInt(5))), }, } - suite.App.MintKeeper.SetParams(suite.Ctx, params) - - // Create record - coins := sdk.Coins{sdk.NewInt64Coin("stake", 10000)} - suite.FundAcc(gaugeCreator, coins) - distrTo := lockuptypes.QueryCondition{ - LockQueryType: lockuptypes.ByDuration, - Denom: "lptoken", - Duration: time.Second, - } - - // mints coins so supply exists on chain - mintLPtokens := sdk.Coins{sdk.NewInt64Coin(distrTo.Denom, 200)} - suite.FundAcc(gaugeCreator, mintLPtokens) - gaugeId, err := suite.App.IncentivesKeeper.CreateGauge(suite.Ctx, true, gaugeCreator, coins, distrTo, time.Now(), 1) - suite.NoError(err) - err = suite.App.PoolIncentivesKeeper.UpdateDistrRecords(suite.Ctx, poolincentivestypes.DistrRecord{ - GaugeId: gaugeId, - Weight: sdk.NewInt(100), - }) - suite.NoError(err) + for _, tc := range tests { + suite.Run(tc.name, func() { + bankKeeper := suite.App.BankKeeper + mintKeeper := suite.App.MintKeeper - // At this time, there is no distr record, so the asset should be allocated to the community pool. - mintCoin := sdk.NewCoin("stake", sdk.NewInt(100000)) - mintCoins := sdk.Coins{mintCoin} - err = mintKeeper.MintCoins(suite.Ctx, mintCoins) - suite.NoError(err) - err = mintKeeper.DistributeMintedCoin(suite.Ctx, mintCoin) - suite.NoError(err) + if tc.hasPreExistingSupply { + fee := sdk.NewCoin("stake", sdk.NewInt(100000)) + fees := sdk.NewCoins(fee) + err := simapp.FundModuleAccount(bankKeeper, + suite.Ctx, + authtypes.FeeCollectorName, + fees) + suite.NoError(err) + } - feePool := suite.App.DistrKeeper.GetFeePool(suite.Ctx) - feeCollector := suite.App.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName) - suite.Equal( - mintCoin.Amount.ToDec().Mul(params.DistributionProportions.Staking).TruncateInt(), - suite.App.BankKeeper.GetAllBalances(suite.Ctx, feeCollector).AmountOf("stake")) - suite.Equal( - mintCoin.Amount.ToDec().Mul(params.DistributionProportions.CommunityPool), - feePool.CommunityPool.AmountOf("stake")) - suite.Equal( - mintCoin.Amount.ToDec().Mul(params.DistributionProportions.DeveloperRewards).TruncateInt(), - suite.App.BankKeeper.GetBalance(suite.Ctx, devRewardsReceiver, "stake").Amount) + coin := mintKeeper.GetProportions(suite.Ctx, tc.fee, tc.ratio) + suite.Equal(tc.expectedCoin, coin) + }) + } +} - // Test for multiple dev reward addresses - params.WeightedDeveloperRewardsReceivers = []types.WeightedAddress{ +func (suite *KeeperTestSuite) TestDistrAssetToDeveloperRewardsAddr() { + var ( + distrTo = lockuptypes.QueryCondition{ + LockQueryType: lockuptypes.ByDuration, + Denom: "lptoken", + Duration: time.Second, + } + params = suite.App.MintKeeper.GetParams(suite.Ctx) + gaugeCoins = sdk.Coins{sdk.NewInt64Coin("stake", 10000)} + gaugeCreator = sdk.AccAddress([]byte("addr2---------------")) + mintLPtokens = sdk.Coins{sdk.NewInt64Coin(distrTo.Denom, 200)} + ) + + tests := []struct { + name string + weightedAddresses []types.WeightedAddress + mintCoin sdk.Coin + }{ + { + name: "one dev reward address", + weightedAddresses: []types.WeightedAddress{ + { + Address: sdk.AccAddress([]byte("addr1---------------")).String(), + Weight: sdk.NewDec(1), + }}, + mintCoin: sdk.NewCoin("stake", sdk.NewInt(10000)), + }, { - Address: devRewardsReceiver2.String(), - Weight: sdk.NewDecWithPrec(6, 1), + name: "multiple dev reward addresses", + weightedAddresses: []types.WeightedAddress{ + { + Address: sdk.AccAddress([]byte("addr3---------------")).String(), + Weight: sdk.NewDecWithPrec(6, 1), + }, + { + Address: sdk.AccAddress([]byte("addr4---------------")).String(), + Weight: sdk.NewDecWithPrec(4, 1), + }}, + mintCoin: sdk.NewCoin("stake", sdk.NewInt(100000)), }, { - Address: devRewardsReceiver3.String(), - Weight: sdk.NewDecWithPrec(4, 1), + name: "nil dev reward address", + weightedAddresses: nil, + mintCoin: sdk.NewCoin("stake", sdk.NewInt(100000)), }, } - suite.App.MintKeeper.SetParams(suite.Ctx, params) + for _, tc := range tests { + suite.Run(tc.name, func() { + suite.Setup() - err = mintKeeper.MintCoins(suite.Ctx, mintCoins) - suite.NoError(err) - err = mintKeeper.DistributeMintedCoin(suite.Ctx, mintCoin) - suite.NoError(err) + mintKeeper := suite.App.MintKeeper + bankKeeper := suite.App.BankKeeper + intencentivesKeeper := suite.App.IncentivesKeeper + poolincentivesKeeper := suite.App.PoolIncentivesKeeper + distrKeeper := suite.App.DistrKeeper + accountKeeper := suite.App.AccountKeeper + + // set WeightedDeveloperRewardsReceivers + params.WeightedDeveloperRewardsReceivers = tc.weightedAddresses + mintKeeper.SetParams(suite.Ctx, params) + + // mints coins so supply exists on chain + suite.FundAcc(gaugeCreator, gaugeCoins) + suite.FundAcc(gaugeCreator, mintLPtokens) + + gaugeId, err := intencentivesKeeper.CreateGauge(suite.Ctx, true, gaugeCreator, gaugeCoins, distrTo, time.Now(), 1) + suite.NoError(err) + err = poolincentivesKeeper.UpdateDistrRecords(suite.Ctx, poolincentivestypes.DistrRecord{ + GaugeId: gaugeId, + Weight: sdk.NewInt(100), + }) + suite.NoError(err) + + err = mintKeeper.MintCoins(suite.Ctx, sdk.NewCoins(tc.mintCoin)) + suite.NoError(err) + + err = mintKeeper.DistributeMintedCoin(suite.Ctx, tc.mintCoin) + suite.NoError(err) + + // check feePool + feePool := distrKeeper.GetFeePool(suite.Ctx) + feeCollector := accountKeeper.GetModuleAddress(authtypes.FeeCollectorName) + suite.Equal( + tc.mintCoin.Amount.ToDec().Mul(params.DistributionProportions.Staking).TruncateInt(), + bankKeeper.GetAllBalances(suite.Ctx, feeCollector).AmountOf("stake")) + + if tc.weightedAddresses != nil { + suite.Equal( + tc.mintCoin.Amount.ToDec().Mul(params.DistributionProportions.CommunityPool), + feePool.CommunityPool.AmountOf("stake")) + } else { + suite.Equal( + //distribution go to community pool because nil dev reward addresses. + tc.mintCoin.Amount.ToDec().Mul((params.DistributionProportions.DeveloperRewards).Add(params.DistributionProportions.CommunityPool)), + feePool.CommunityPool.AmountOf("stake")) + } - suite.Equal( - mintCoins[0].Amount.ToDec().Mul(params.DistributionProportions.DeveloperRewards).Mul(params.WeightedDeveloperRewardsReceivers[0].Weight).TruncateInt(), - suite.App.BankKeeper.GetBalance(suite.Ctx, devRewardsReceiver2, "stake").Amount) - suite.Equal( - mintCoins[0].Amount.ToDec().Mul(params.DistributionProportions.DeveloperRewards).Mul(params.WeightedDeveloperRewardsReceivers[1].Weight).TruncateInt(), - suite.App.BankKeeper.GetBalance(suite.Ctx, devRewardsReceiver3, "stake").Amount) + // check devAddress balances + for i, weightedAddress := range tc.weightedAddresses { + devRewardsReceiver, _ := sdk.AccAddressFromBech32(weightedAddress.GetAddress()) + suite.Equal( + tc.mintCoin.Amount.ToDec().Mul(params.DistributionProportions.DeveloperRewards).Mul(params.WeightedDeveloperRewardsReceivers[i].Weight).TruncateInt(), + bankKeeper.GetBalance(suite.Ctx, devRewardsReceiver, "stake").Amount) + } + }) + } } func (suite *KeeperTestSuite) TestDistrAssetToCommunityPoolWhenNoDeveloperRewardsAddr() { mintKeeper := suite.App.MintKeeper + bankKeeper := suite.App.BankKeeper + distrKeeper := suite.App.DistrKeeper + accountKeeper := suite.App.AccountKeeper params := suite.App.MintKeeper.GetParams(suite.Ctx) // At this time, there is no distr record, so the asset should be allocated to the community pool. @@ -177,17 +229,17 @@ func (suite *KeeperTestSuite) TestDistrAssetToCommunityPoolWhenNoDeveloperReward err = mintKeeper.DistributeMintedCoin(suite.Ctx, mintCoin) suite.NoError(err) - distribution.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{}, *suite.App.DistrKeeper) + distribution.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{}, *distrKeeper) - feePool := suite.App.DistrKeeper.GetFeePool(suite.Ctx) - feeCollector := suite.App.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName) + feePool := distrKeeper.GetFeePool(suite.Ctx) + feeCollector := accountKeeper.GetModuleAddress(authtypes.FeeCollectorName) // PoolIncentives + DeveloperRewards + CommunityPool => CommunityPool proportionToCommunity := params.DistributionProportions.PoolIncentives. Add(params.DistributionProportions.DeveloperRewards). Add(params.DistributionProportions.CommunityPool) suite.Equal( mintCoins[0].Amount.ToDec().Mul(params.DistributionProportions.Staking).TruncateInt(), - suite.App.BankKeeper.GetBalance(suite.Ctx, feeCollector, "stake").Amount) + bankKeeper.GetBalance(suite.Ctx, feeCollector, "stake").Amount) suite.Equal( mintCoins[0].Amount.ToDec().Mul(proportionToCommunity), feePool.CommunityPool.AmountOf("stake")) @@ -198,12 +250,12 @@ func (suite *KeeperTestSuite) TestDistrAssetToCommunityPoolWhenNoDeveloperReward err = mintKeeper.DistributeMintedCoin(suite.Ctx, mintCoin) suite.NoError(err) - distribution.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{}, *suite.App.DistrKeeper) + distribution.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{}, *distrKeeper) - feePool = suite.App.DistrKeeper.GetFeePool(suite.Ctx) + feePool = distrKeeper.GetFeePool(suite.Ctx) suite.Equal( mintCoins[0].Amount.ToDec().Mul(params.DistributionProportions.Staking).TruncateInt().Mul(sdk.NewInt(2)), - suite.App.BankKeeper.GetBalance(suite.Ctx, feeCollector, "stake").Amount) + bankKeeper.GetBalance(suite.Ctx, feeCollector, "stake").Amount) suite.Equal( mintCoins[0].Amount.ToDec().Mul(proportionToCommunity).Mul(sdk.NewDec(2)), feePool.CommunityPool.AmountOf("stake")) From c79f28be2be3e58d09badfe0a896ecb2bb97f753 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 7 Jul 2022 19:57:56 -0400 Subject: [PATCH 043/376] remove bech32 ibc (#1994) * remove bech32 ibc * comment out in v5 upgrade code * CHANGELOG --- CHANGELOG.md | 1 + app/keepers/keepers.go | 24 ------------------------ app/keepers/modules.go | 2 -- app/modules.go | 9 ++------- app/upgrades/v5/upgrades.go | 4 ++-- go.mod | 1 - go.sum | 4 +--- osmoutils/partialord/partialord_test.go | 5 ++--- 8 files changed, 8 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48f18265b6a..23ae5527ddb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * MsgExitPoolResponse: token_out field * [#1825](https://github.com/osmosis-labs/osmosis/pull/1825) Fixes Interchain Accounts (host side) by adding it to AppModuleBasics * [#1699](https://github.com/osmosis-labs/osmosis/pull/1699) Fixes bug in sig fig rounding on spot price queries for small values +* [#1994](https://github.com/osmosis-labs/osmosis/pull/1994) Removed bech32ibc module #### Golang API breaks diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index f563ae5ec6c..180fc6d2baf 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -46,10 +46,6 @@ import ( // IBC Transfer: Defines the "transfer" IBC port transfer "github.com/cosmos/ibc-go/v3/modules/apps/transfer" - "github.com/osmosis-labs/bech32-ibc/x/bech32ibc" - bech32ibckeeper "github.com/osmosis-labs/bech32-ibc/x/bech32ibc/keeper" - bech32ibctypes "github.com/osmosis-labs/bech32-ibc/x/bech32ibc/types" - bech32ics20keeper "github.com/osmosis-labs/bech32-ibc/x/bech32ics20/keeper" _ "github.com/osmosis-labs/osmosis/v7/client/docs/statik" owasm "github.com/osmosis-labs/osmosis/v7/wasmbinding" @@ -100,8 +96,6 @@ type AppKeepers struct { IBCKeeper *ibckeeper.Keeper ICAHostKeeper *icahostkeeper.Keeper TransferKeeper *ibctransferkeeper.Keeper - Bech32IBCKeeper *bech32ibckeeper.Keeper - Bech32ICS20Keeper *bech32ics20keeper.Keeper EvidenceKeeper *evidencekeeper.Keeper GAMMKeeper *gammkeeper.Keeper LockupKeeper *lockupkeeper.Keeper @@ -231,22 +225,6 @@ func (appKeepers *AppKeepers) InitNormalKeepers( AddRoute(ibctransfertypes.ModuleName, transferIBCModule) // Note: the sealing is done after creating wasmd and wiring that up - appKeepers.Bech32IBCKeeper = bech32ibckeeper.NewKeeper( - appKeepers.IBCKeeper.ChannelKeeper, appCodec, appKeepers.keys[bech32ibctypes.StoreKey], - appKeepers.TransferKeeper, - ) - - // TODO: Should we be passing this instead of bank in many places? - // Where do we want send coins to be cross-chain? - appKeepers.Bech32ICS20Keeper = bech32ics20keeper.NewKeeper( - appKeepers.IBCKeeper.ChannelKeeper, - appKeepers.BankKeeper, - appKeepers.TransferKeeper, - appKeepers.Bech32IBCKeeper, - appKeepers.TransferKeeper, - appCodec, - ) - // create evidence keeper with router // If evidence needs to be handled for the app, set routes in router here and seal appKeepers.EvidenceKeeper = evidencekeeper.NewKeeper( @@ -374,7 +352,6 @@ func (appKeepers *AppKeepers) InitNormalKeepers( AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(*appKeepers.UpgradeKeeper)). AddRoute(ibchost.RouterKey, ibcclient.NewClientProposalHandler(appKeepers.IBCKeeper.ClientKeeper)). AddRoute(poolincentivestypes.RouterKey, poolincentives.NewPoolIncentivesProposalHandler(*appKeepers.PoolIncentivesKeeper)). - AddRoute(bech32ibctypes.RouterKey, bech32ibc.NewBech32IBCProposalHandler(*appKeepers.Bech32IBCKeeper)). AddRoute(txfeestypes.RouterKey, txfees.NewUpdateFeeTokenProposalHandler(*appKeepers.TxFeesKeeper)). AddRoute(superfluidtypes.RouterKey, superfluid.NewSuperfluidProposalHandler(*appKeepers.SuperfluidKeeper, *appKeepers.EpochsKeeper)) @@ -539,7 +516,6 @@ func KVStoreKeys() []string { authzkeeper.StoreKey, txfeestypes.StoreKey, superfluidtypes.StoreKey, - bech32ibctypes.StoreKey, wasm.StoreKey, tokenfactorytypes.StoreKey, } diff --git a/app/keepers/modules.go b/app/keepers/modules.go index b0766bf1b6b..83af806ebdf 100644 --- a/app/keepers/modules.go +++ b/app/keepers/modules.go @@ -6,7 +6,6 @@ import ( transfer "github.com/cosmos/ibc-go/v3/modules/apps/transfer" ibc "github.com/cosmos/ibc-go/v3/modules/core" ibcclientclient "github.com/cosmos/ibc-go/v3/modules/core/02-client/client" - "github.com/osmosis-labs/bech32-ibc/x/bech32ibc" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" @@ -82,7 +81,6 @@ var AppModuleBasics = []module.AppModuleBasic{ epochs.AppModuleBasic{}, superfluid.AppModuleBasic{}, tokenfactory.AppModuleBasic{}, - bech32ibc.AppModuleBasic{}, wasm.AppModuleBasic{}, ica.AppModuleBasic{}, } diff --git a/app/modules.go b/app/modules.go index a78d320139a..a8d0900258f 100644 --- a/app/modules.go +++ b/app/modules.go @@ -8,9 +8,6 @@ import ( ica "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts" icatypes "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts/types" - "github.com/osmosis-labs/bech32-ibc/x/bech32ibc" - bech32ibctypes "github.com/osmosis-labs/bech32-ibc/x/bech32ibc/types" - "github.com/osmosis-labs/bech32-ibc/x/bech32ics20" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" @@ -20,6 +17,7 @@ import ( vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module" + "github.com/cosmos/cosmos-sdk/x/bank" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/capability" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" @@ -105,7 +103,7 @@ func appModules( ), auth.NewAppModule(appCodec, *app.AccountKeeper, nil), vesting.NewAppModule(*app.AccountKeeper, app.BankKeeper), - bech32ics20.NewAppModule(appCodec, *app.Bech32ICS20Keeper), + bank.NewAppModule(appCodec, *app.BankKeeper, app.AccountKeeper), capability.NewAppModule(appCodec, *app.CapabilityKeeper), crisis.NewAppModule(app.CrisisKeeper, skipGenesisInvariants), gov.NewAppModule(appCodec, *app.GovKeeper, app.AccountKeeper, app.BankKeeper), @@ -138,7 +136,6 @@ func appModules( app.EpochsKeeper, ), tokenfactory.NewAppModule(appCodec, *app.TokenFactoryKeeper, app.AccountKeeper, app.BankKeeper), - bech32ibc.NewAppModule(appCodec, *app.Bech32IBCKeeper), } } @@ -175,7 +172,6 @@ func orderBeginBlockers() []string { tokenfactorytypes.ModuleName, // superfluid must come after distribution and epochs superfluidtypes.ModuleName, - bech32ibctypes.ModuleName, txfeestypes.ModuleName, wasm.ModuleName, } @@ -210,7 +206,6 @@ func OrderInitGenesis(allModuleNames []string) []string { upgradetypes.ModuleName, vestingtypes.ModuleName, ibctransfertypes.ModuleName, - bech32ibctypes.ModuleName, // comes after ibctransfertypes poolincentivestypes.ModuleName, superfluidtypes.ModuleName, tokenfactorytypes.ModuleName, diff --git a/app/upgrades/v5/upgrades.go b/app/upgrades/v5/upgrades.go index 851f9b0ba92..efb21a5c1f8 100644 --- a/app/upgrades/v5/upgrades.go +++ b/app/upgrades/v5/upgrades.go @@ -2,7 +2,7 @@ package v5 import ( ibcconnectiontypes "github.com/cosmos/ibc-go/v3/modules/core/03-connection/types" - bech32ibctypes "github.com/osmosis-labs/bech32-ibc/x/bech32ibc/types" + // bech32ibctypes "github.com/osmosis-labs/bech32-ibc/x/bech32ibc/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -46,7 +46,7 @@ func CreateUpgradeHandler( // Override versions for authz & bech32ibctypes module as to not skip their // InitGenesis for txfees module, we will override txfees ourselves. delete(fromVM, authz.ModuleName) - delete(fromVM, bech32ibctypes.ModuleName) + // delete(fromVM, bech32ibctypes.ModuleName) newVM, err := mm.RunMigrations(ctx, configurator, fromVM) if err != nil { diff --git a/go.mod b/go.mod index 99b414416d5..2f7557701a7 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,6 @@ require ( github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/ory/dockertest/v3 v3.9.1 - github.com/osmosis-labs/bech32-ibc v0.3.0-rc1 github.com/pkg/errors v0.9.1 github.com/rakyll/statik v0.1.7 github.com/spf13/cast v1.5.0 diff --git a/go.sum b/go.sum index 4f0b4409505..2b6732e6289 100644 --- a/go.sum +++ b/go.sum @@ -437,8 +437,8 @@ github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8c github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= -github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= github.com/go-redis/redis v6.15.8+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-sourcemap/sourcemap v2.1.2+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= @@ -1040,8 +1040,6 @@ github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4 github.com/ory/dockertest v3.3.5+incompatible/go.mod h1:1vX4m9wsvi00u5bseYwXaSnhNrne+V0E6LAcBILJdPs= github.com/ory/dockertest/v3 v3.9.1 h1:v4dkG+dlu76goxMiTT2j8zV7s4oPPEppKT8K8p2f1kY= github.com/ory/dockertest/v3 v3.9.1/go.mod h1:42Ir9hmvaAPm0Mgibk6mBPi7SFvTXxEcnztDYOJ//uM= -github.com/osmosis-labs/bech32-ibc v0.3.0-rc1 h1:frHKHEdPfzoK2iMF2GeWKudLLzUXz+6GJcdZ/TMcs2k= -github.com/osmosis-labs/bech32-ibc v0.3.0-rc1/go.mod h1:X5/FZHMPL+B3ufuVyY2/koxVjd4hIwyTLjYP1DZwppQ= github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220620200611-3e46ff7501a1 h1:DGOm5SJcKVmgUVN8of2u4jj3vxEhAYs/+e+XqsxcrnQ= github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220620200611-3e46ff7501a1/go.mod h1:pMiEr6WR7drhXAXK1FOdAKPazWCi7b+WOyWOF4O0OXY= github.com/osmosis-labs/iavl v0.17.3-osmo-v7 h1:6KcADC/WhL7yDmNQxUIJt2XmzNt4FfRmq9gRke45w74= diff --git a/osmoutils/partialord/partialord_test.go b/osmoutils/partialord/partialord_test.go index 6de9edcd92d..1f8afd4e0c9 100644 --- a/osmoutils/partialord/partialord_test.go +++ b/osmoutils/partialord/partialord_test.go @@ -14,12 +14,11 @@ func TestAPI(t *testing.T) { moduleNames := []string{ "auth", "authz", "bank", "capabilities", "staking", "distribution", "epochs", "mint", "upgrades", "wasm", "ibc", - "ibctransfers", "bech32ibc", + "ibctransfers", } beginBlockOrd := partialord.NewPartialOrdering(moduleNames) beginBlockOrd.FirstElements("upgrades", "epochs", "capabilities") beginBlockOrd.After("ibctransfers", "ibc") - beginBlockOrd.After("bech32ibc", "ibctransfers") beginBlockOrd.Before("mint", "distribution") // This is purely just to test last functionality, doesn't make sense in context beginBlockOrd.LastElements("auth", "authz", "wasm") @@ -27,7 +26,7 @@ func TestAPI(t *testing.T) { totalOrd := beginBlockOrd.TotalOrdering() expTotalOrd := []string{ "upgrades", "epochs", "capabilities", - "bank", "staking", "mint", "ibc", "distribution", "ibctransfers", "bech32ibc", + "bank", "staking", "mint", "ibc", "distribution", "ibctransfers", "auth", "authz", "wasm", } require.Equal(t, expTotalOrd, totalOrd) From 1b5a1d3b034e222d069f05c928d6383a1534ce82 Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 7 Jul 2022 20:46:58 -0400 Subject: [PATCH 044/376] lint: enable staticcheck (#1956) * lint: enable staticcheck * remove more dead code from balances from state export command * named return for error in forceprune * remove nolint --- .golangci.yml | 5 ++++- cmd/osmosisd/cmd/balances_from_state_export.go | 10 ---------- cmd/osmosisd/cmd/forceprune.go | 17 +++++++++++++++-- cmd/osmosisd/cmd/genesis.go | 3 +++ cmd/osmosisd/cmd/testnet.go | 5 ++++- x/incentives/types/genesis.go | 3 --- x/lockup/types/genesis.go | 5 ----- 7 files changed, 26 insertions(+), 22 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 771ce0d3685..88baa9a2a63 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -68,7 +68,7 @@ linters: # - revive <- temporarily disabled while jacob figures out how to make poolId not trigger it. # - rowserrcheck <- needs go 1.18 support # - sqlclosecheck <- needs go 1.18 support -# - staticcheck <- later + - staticcheck # set of rules from staticcheck, subset of staticcheck binary. # - structcheck <- later - stylecheck # replacement of golint, subset of staticcheck binary. # - tagliatelle <- disabled for defying cosmos idiom @@ -102,6 +102,9 @@ issues: # across its files, once stableswap is fully complete. - unused - deadcode + - linters: + - staticcheck + text: "SA1024: cutset contains duplicate characters" # proved to not provide much value, only false positives. - linters: - stylecheck text: "ST1003:" # requires identifiers with "id" to be "ID". diff --git a/cmd/osmosisd/cmd/balances_from_state_export.go b/cmd/osmosisd/cmd/balances_from_state_export.go index 9c3ff42af77..558f4a791ce 100644 --- a/cmd/osmosisd/cmd/balances_from_state_export.go +++ b/cmd/osmosisd/cmd/balances_from_state_export.go @@ -19,7 +19,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -141,7 +140,6 @@ func getGenStateFromPath(genesisFilePath string) (map[string]json.RawMessage, er } // ExportAirdropSnapshotCmd generates a snapshot.json from a provided exported genesis.json. -//nolint:ineffassign // because of accounts = authtypes.SanitizeGenesisAccounts(accounts) func ExportDeriveBalancesCmd() *cobra.Command { cmd := &cobra.Command{ Use: "export-derive-balances [input-genesis-file] [output-snapshot-json]", @@ -177,14 +175,6 @@ Example: } } - authGenesis := authtypes.GenesisState{} - clientCtx.Codec.MustUnmarshalJSON(genState["auth"], &authGenesis) - accounts, err := authtypes.UnpackAccounts(authGenesis.Accounts) - if err != nil { - panic(err) - } - accounts = authtypes.SanitizeGenesisAccounts(accounts) - // Produce the map of address to total atom balance, both staked and UnbondingStake snapshotAccs := make(map[string]DerivedAccount) diff --git a/cmd/osmosisd/cmd/forceprune.go b/cmd/osmosisd/cmd/forceprune.go index 0add006e94e..0ac1424180c 100644 --- a/cmd/osmosisd/cmd/forceprune.go +++ b/cmd/osmosisd/cmd/forceprune.go @@ -105,6 +105,8 @@ func pruneBlockStoreAndGetHeights(dbPath string, fullHeight int64) ( if err != nil { return 0, 0, err } + + // nolint: staticcheck defer db_bs.Close() bs := tmstore.NewBlockStore(db_bs) @@ -117,10 +119,19 @@ func pruneBlockStoreAndGetHeights(dbPath string, fullHeight int64) ( return 0, 0, err } fmt.Println("Pruned Block Store ...", prunedBlocks) + + // N.B: We duplicate the call to db_bs.Close() on top of + // the call in defer statement above to make sure that the resources + // are properly released and any potential error from Close() + // is handled. Close() should be idempotent so this is acceptable. + if err := db_bs.Close(); err != nil { + return 0, 0, err + } + return startHeight, currentHeight, nil } -func compactBlockStore(dbPath string) error { +func compactBlockStore(dbPath string) (err error) { compactOpts := opt.Options{ DisableSeeksCompaction: true, } @@ -128,7 +139,9 @@ func compactBlockStore(dbPath string) error { fmt.Println("Compacting Block Store ...") db, err := leveldb.OpenFile(dbPath+"/blockstore.db", &compactOpts) - defer db.Close() + defer func() { + err = db.Close() + }() if err != nil { return err } diff --git a/cmd/osmosisd/cmd/genesis.go b/cmd/osmosisd/cmd/genesis.go index 6ee8988b7f2..ba03b5e1ded 100644 --- a/cmd/osmosisd/cmd/genesis.go +++ b/cmd/osmosisd/cmd/genesis.go @@ -78,6 +78,9 @@ Example: // run Prepare Genesis appState, genDoc, err = PrepareGenesis(clientCtx, appState, genDoc, genesisParams, chainID) + if err != nil { + return err + } // validate genesis state if err = mbm.ValidateGenesis(cdc, clientCtx.TxConfig, appState); err != nil { diff --git a/cmd/osmosisd/cmd/testnet.go b/cmd/osmosisd/cmd/testnet.go index 11ee553cccc..78b8b805ec0 100644 --- a/cmd/osmosisd/cmd/testnet.go +++ b/cmd/osmosisd/cmd/testnet.go @@ -25,6 +25,7 @@ import ( cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/server" srvconfig "github.com/cosmos/cosmos-sdk/server/config" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -40,6 +41,8 @@ var ( flagOutputDir = "output-dir" flagNodeDaemonHome = "node-daemon-home" flagStartingIPAddress = "starting-ip-address" + + emptyMnemonic = "" ) // get cmd to initialize all files for tendermint testnet and application. @@ -180,7 +183,7 @@ func InitTestnet( return err } - addr, secret, err := server.GenerateSaveCoinKey(kb, nodeDirName, true, algo) + addr, secret, err := testutil.GenerateSaveCoinKey(kb, nodeDirName, emptyMnemonic, true, algo) if err != nil { _ = os.RemoveAll(outputDir) return err diff --git a/x/incentives/types/genesis.go b/x/incentives/types/genesis.go index 9bf67d0d12a..afa224997ac 100644 --- a/x/incentives/types/genesis.go +++ b/x/incentives/types/genesis.go @@ -45,8 +45,5 @@ func (gs GenesisState) Validate() error { if gs.Params.DistrEpochIdentifier == "" { return errors.New("epoch identifier should NOT be empty") } - if gs.LastGaugeId < 0 { - return errors.New("lock gauge lock id should be non-negative") - } return nil } diff --git a/x/lockup/types/genesis.go b/x/lockup/types/genesis.go index 6e5b5828511..e883ff8d4af 100644 --- a/x/lockup/types/genesis.go +++ b/x/lockup/types/genesis.go @@ -1,7 +1,5 @@ package types -import "errors" - // DefaultIndex is the default capability global index. const DefaultIndex uint64 = 1 @@ -13,8 +11,5 @@ func DefaultGenesis() *GenesisState { // Validate performs basic genesis state validation returning an error upon any // failure. func (gs GenesisState) Validate() error { - if gs.LastLockId < 0 { - return errors.New("lock last lock id should be non-negative") - } return nil } From 05375f8603e4d2e294281df267ee891405a32b7c Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 7 Jul 2022 23:55:49 -0400 Subject: [PATCH 045/376] refactor(e2e): modular test runner (#1999) * use should_run_go_test to skip e2e * attempt to disable upgrade * remporary remove get data from build cache * go setup * bring back cache * log for upgrade * invert the disable condition * comment * add more logic regarding skipping some e2e components * fix markdown lint * change branch to main * refactor to be able to run local version without building Docker image in CI * remove if on building local image * TestCreatePool runs only post-upgrade * lint * TestCreatePoolPostUpgrade * Document * restore git diff * Update tests/e2e/README.md Co-authored-by: Dev Ojha * README updates * rename files; move validator configs, factory and constants to separate files * avoid exporting base configurer * all reference to "local" are replaced to" current branch" * fix formatting * move all docker logic to containers package * move hermes resource to container manager * move val resources to container manager * clear docker resources in manager * unexport hermes resource * configurer chain package * pass chain config to RunHermesResource * rename configurer chain to chain config consistently * unexport validator resources * unexport network * define commands and queries on chain config struct * lint * format * remove unused noRestart function * remove more redundant structs * refactor(e2e): modular test runner * restore test.yml * fix e2e_setup_test.go * space * readme * fix sf test * restore initialization * ibc skip * minimize diff and lint * Update tests/e2e/README.md Co-authored-by: Adam Tucker * factory design pattern * Adam's suggestions Co-authored-by: Dev Ojha Co-authored-by: Adam Tucker --- tests/e2e/README.md | 90 +++- tests/e2e/configurer/base.go | 218 +++++++++ tests/e2e/configurer/chain/chain.go | 43 ++ tests/e2e/configurer/chain/commands.go | 190 ++++++++ tests/e2e/configurer/chain/queries.go | 150 +++++++ tests/e2e/configurer/chain/validator.go | 9 + tests/e2e/configurer/config/constants.go | 16 + tests/e2e/configurer/current.go | 57 +++ tests/e2e/configurer/factory.go | 148 ++++++ tests/e2e/configurer/setup.go | 49 ++ tests/e2e/configurer/upgrade.go | 259 +++++++++++ tests/e2e/e2e_setup_test.go | 547 +---------------------- tests/e2e/e2e_test.go | 60 +-- tests/e2e/e2e_util_test.go | 304 ------------- tests/e2e/initialization/README.md | 2 +- tests/e2e/initialization/init_test.go | 5 +- 16 files changed, 1286 insertions(+), 861 deletions(-) create mode 100644 tests/e2e/configurer/base.go create mode 100644 tests/e2e/configurer/chain/chain.go create mode 100644 tests/e2e/configurer/chain/commands.go create mode 100644 tests/e2e/configurer/chain/queries.go create mode 100644 tests/e2e/configurer/chain/validator.go create mode 100644 tests/e2e/configurer/config/constants.go create mode 100644 tests/e2e/configurer/current.go create mode 100644 tests/e2e/configurer/factory.go create mode 100644 tests/e2e/configurer/setup.go create mode 100644 tests/e2e/configurer/upgrade.go delete mode 100644 tests/e2e/e2e_util_test.go diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 2de01da1888..efe054035fa 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -24,11 +24,93 @@ core bootstrapping logic that creates a testing environment via Docker containers. A testing network is created dynamically with 2 test validators. -The file e2e\_test.go contains the actual end-to-end integration tests +The file `e2e_test.go` contains the actual end-to-end integration tests that utilize the testing suite. -Currently, there is a single test in `e2e_test.go` to query the balances -of a validator. +Currently, there is a single IBC test in `e2e_test.go`. + +Additionally, there is an ability to disable certain components +of the e2e suite. This can be done by setting the environment +variables. See "Environment variables" section below for more details. + +## How It Works + +Conceptually, we can split the e2e setup into 2 parts: + +1. Chain Initialization + + The chain can either be initailized off of the current branch, or off the prior mainnet release and then upgraded to the current branch. + + If current, we run chain initialization off of the current Git branch + by calling `chain.Init(...)` method in the `configurer/current.go`. + + If with the upgrade, the same `chain.Init(...)` function is run inside a Docker container + of the previous Osmosis version, inside `configurer/upgrade.go`. This is + needed to initialize chain configs and the genesis of the previous version that + we are upgrading from. + + The decision of what configuration type to use is decided by the `Configurer`. + This is an interface that has `CurrentBranchConfigurer` and `UpgradeConfigurer` implementations. + There is also a `BaseConfigurer` which is shared by the concrete implementations. However, + the user of the `configurer` package does not need to know about this detail. + + When the desired configurer is created, the caller may + configure the chain in the desired way as follows: + + ```go + conf, _ := configurer.New(..., < isIBCEnabled bool >, < isUpgradeEnabled bool >) + + conf.ConfigureChains() + ``` + + The caller (e2e setup logic), does not need to be concerned about what type of + configurations is hapenning in the background. The appropriate logic is selected + depending on what the values of the arguments to `configurer.New(...)` are. + + The configurer constructor is using a factory design pattern + to decide on what kind of configurer to return. Factory design + pattern is used to decouple the client from the initialization + details of the configurer. More on this can be found + [here](https://www.tutorialspoint.com/design_pattern/factory_pattern.htm) + + The rules for deciding on the configurer type + are as follows: + + - If only `isIBCEnabled`, we want to have 2 chains initialized at the + current branch version of Osmosis codebase + + - If only `isUpgradeEnabled`, that's invalid (we can decouple upgrade + testing from IBC in a future PR) + + - If both `isIBCEnabled` and `isUpgradeEnabled`, we want 2 chain + with IBC initialized at the previous Osmosis version + + - If none are true, we only need one chain at the current branch version + of the Osmosis code + +2. Setting up e2e components + + Currently, there exist the following components: + + - Base logic + - This is the most basic type of setup where a single chain is created + - It simply spins up the desired number of validators on a chain. + - IBC testing + - 2 chains are created connected by Hermes relayer + - Upgrade Testing + - 2 chains of the older Osmosis version are created, and + connected by Hermes relayer + - Upgrade testing + - CLI commands are run to create an upgrade proposal and approve it + - Old version containers are stopped and the upgrade binary is added + - Current branch Osmosis version is spun up to continue with testing + - State Sync Testing (WIP) + - An additional full node is created after a chain has started. + - This node is meant to state sync with the rest of the system. + + This is done in `configurer/setup_runner.go` via function decorator design pattern + where we chain the desired setup components during configurer creation. + [Example](https://github.com/osmosis-labs/osmosis/blob/c5d5c9f0c6b5c7fdf9688057eb78ec793f6dd580/tests/e2e/configurer/configurer.go#L166) ## `initialization` Package @@ -56,7 +138,7 @@ Docker containers. Currently, validator containers are created with a name of the corresponding validator struct that is initialized in the `chain` package. -## Running Locally +## Running From Current Branch ### To build chain initialization image diff --git a/tests/e2e/configurer/base.go b/tests/e2e/configurer/base.go new file mode 100644 index 00000000000..e18ddb457d7 --- /dev/null +++ b/tests/e2e/configurer/base.go @@ -0,0 +1,218 @@ +package configurer + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" + rpchttp "github.com/tendermint/tendermint/rpc/client/http" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" +) + +// baseConfigurer is the base implementation for the +// other 2 types of configurers. It is not meant to be used +// on its own. Instead, it is meant to be embedded +// by composition into more concrete configurers. +type baseConfigurer struct { + chainConfigs []*chain.Config + containerManager *containers.Manager + setupTests setupFn + syncUntilHeight int64 // the height until which to wait for validators to sync when first started. + t *testing.T +} + +// defaultSyncUntilHeight arbitrary small height to make sure the chain is making progress. +const defaultSyncUntilHeight = 3 + +func (bc *baseConfigurer) ClearResources() error { + bc.t.Log("tearing down e2e integration test suite...") + + if err := bc.containerManager.ClearResources(); err != nil { + return err + } + + for _, chainConfig := range bc.chainConfigs { + os.RemoveAll(chainConfig.DataDir) + } + return nil +} + +func (bc *baseConfigurer) GetChainConfig(chainIndex int) *chain.Config { + return bc.chainConfigs[chainIndex] +} + +func (bc *baseConfigurer) RunValidators() error { + for _, chainConfig := range bc.chainConfigs { + if err := bc.runValidators(chainConfig); err != nil { + return err + } + } + return nil +} + +func (bc *baseConfigurer) runValidators(chainConfig *chain.Config) error { + bc.t.Logf("starting %s validator containers...", chainConfig.Id) + + for _, val := range chainConfig.NodeConfigs { + resource, err := bc.containerManager.RunValidatorResource(chainConfig.Id, val.Name, val.ConfigDir) + if err != nil { + return err + } + bc.t.Logf("started %s validator container: %s", resource.Container.Name[1:], resource.Container.ID) + } + + validatorHostPort, err := bc.containerManager.GetValidatorHostPort(chainConfig.Id, 0, "26657/tcp") + if err != nil { + return err + } + + rpcClient, err := rpchttp.New(fmt.Sprintf("tcp://%s", validatorHostPort), "/websocket") + if err != nil { + return err + } + + require.Eventually( + bc.t, + func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + + status, err := rpcClient.Status(ctx) + if err != nil { + return false + } + + // let the node produce a few blocks + if status.SyncInfo.CatchingUp && status.SyncInfo.LatestBlockHeight < bc.syncUntilHeight { + return false + } + + return true + }, + 5*time.Minute, + time.Second, + "Osmosis node failed to produce blocks", + ) + chainConfig.ExtractValidatorOperatorAddresses() + return nil +} + +func (bc *baseConfigurer) RunIBC() error { + // Run a relayer between every possible pair of chains. + for i := 0; i < len(bc.chainConfigs); i++ { + for j := i + 1; j < len(bc.chainConfigs); j++ { + if err := bc.runIBCRelayer(bc.chainConfigs[i], bc.chainConfigs[j]); err != nil { + return err + } + } + } + return nil +} + +func (bc *baseConfigurer) runIBCRelayer(chainConfigA *chain.Config, chainConfigB *chain.Config) error { + bc.t.Log("starting Hermes relayer container...") + + tmpDir, err := os.MkdirTemp("", "osmosis-e2e-testnet-hermes-") + if err != nil { + return err + } + + hermesCfgPath := path.Join(tmpDir, "hermes") + + if err := os.MkdirAll(hermesCfgPath, 0o755); err != nil { + return err + } + + _, err = util.CopyFile( + filepath.Join("./scripts/", "hermes_bootstrap.sh"), + filepath.Join(hermesCfgPath, "hermes_bootstrap.sh"), + ) + if err != nil { + return err + } + + hermesResource, err := bc.containerManager.RunHermesResource( + chainConfigA.Id, + chainConfigA.NodeConfigs[0].Mnemonic, + chainConfigB.Id, chainConfigB.NodeConfigs[0].Mnemonic, + hermesCfgPath) + if err != nil { + return err + } + + endpoint := fmt.Sprintf("http://%s/state", hermesResource.GetHostPort("3031/tcp")) + + require.Eventually(bc.t, func() bool { + resp, err := http.Get(endpoint) + if err != nil { + return false + } + + defer resp.Body.Close() + + bz, err := io.ReadAll(resp.Body) + if err != nil { + return false + } + + var respBody map[string]interface{} + if err := json.Unmarshal(bz, &respBody); err != nil { + return false + } + + status, ok := respBody["status"].(string) + require.True(bc.t, ok) + result, ok := respBody["result"].(map[string]interface{}) + require.True(bc.t, ok) + + chains, ok := result["chains"].([]interface{}) + require.True(bc.t, ok) + + return status == "success" && len(chains) == 2 + }, + 5*time.Minute, + time.Second, + "hermes relayer not healthy") + + bc.t.Logf("started Hermes relayer container: %s", bc.containerManager.GetHermesContainerID()) + + // XXX: Give time to both networks to start, otherwise we might see gRPC + // transport errors. + time.Sleep(10 * time.Second) + + // create the client, connection and channel between the two Osmosis chains + return bc.connectIBCChains(chainConfigA, chainConfigB) +} + +func (bc *baseConfigurer) connectIBCChains(chainA *chain.Config, chainB *chain.Config) error { + bc.t.Logf("connecting %s and %s chains via IBC", chainA.ChainMeta.Id, chainB.ChainMeta.Id) + cmd := []string{"hermes", "create", "channel", chainA.ChainMeta.Id, chainB.ChainMeta.Id, "--port-a=transfer", "--port-b=transfer"} + _, _, err := bc.containerManager.ExecCmd(bc.t, "", 0, cmd, "successfully opened init channel") + if err != nil { + return err + } + bc.t.Logf("connected %s and %s chains via IBC", chainA.ChainMeta.Id, chainB.ChainMeta.Id) + return nil +} + +func (bc *baseConfigurer) initializeChainConfigFromInitChain(initializedChain *initialization.Chain, chainConfig *chain.Config) { + chainConfig.ChainMeta = initializedChain.ChainMeta + chainConfig.NodeConfigs = make([]*chain.ValidatorConfig, 0, len(initializedChain.Nodes)) + for _, validator := range initializedChain.Nodes { + chainConfig.NodeConfigs = append(chainConfig.NodeConfigs, &chain.ValidatorConfig{ + Node: *validator, + }) + } +} diff --git a/tests/e2e/configurer/chain/chain.go b/tests/e2e/configurer/chain/chain.go new file mode 100644 index 00000000000..7d008db2ecf --- /dev/null +++ b/tests/e2e/configurer/chain/chain.go @@ -0,0 +1,43 @@ +package chain + +import ( + "testing" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +) + +type Config struct { + initialization.ChainMeta + + ValidatorInitConfigs []*initialization.NodeConfig + // voting period is number of blocks it takes to deposit, 1.2 seconds per validator to vote on the prop, and a buffer. + VotingPeriod float32 + // upgrade proposal height for chain. + PropHeight int + LatestProposalNumber int + LatestLockNumber int + NodeConfigs []*ValidatorConfig + + t *testing.T + containerManager *containers.Manager +} + +type status struct { + LatestHeight string `json:"latest_block_height"` +} + +type syncInfo struct { + SyncInfo status `json:"SyncInfo"` +} + +func New(t *testing.T, containerManager *containers.Manager, id string, initValidatorConfigs []*initialization.NodeConfig) *Config { + return &Config{ + ChainMeta: initialization.ChainMeta{ + Id: id, + }, + ValidatorInitConfigs: initValidatorConfigs, + t: t, + containerManager: containerManager, + } +} diff --git a/tests/e2e/configurer/chain/commands.go b/tests/e2e/configurer/chain/commands.go new file mode 100644 index 00000000000..fffc2fa1f8b --- /dev/null +++ b/tests/e2e/configurer/chain/commands.go @@ -0,0 +1,190 @@ +package chain + +import ( + "fmt" + "regexp" + "strconv" + "strings" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +) + +func (c *Config) CreatePool(poolFile, from string) { + c.t.Logf("creating pool for chain-id: %s", c.Id) + cmd := []string{"osmosisd", "tx", "gamm", "create-pool", fmt.Sprintf("--pool-file=/osmosis/%s", poolFile), fmt.Sprintf("--chain-id=%s", c.Id), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + require.NoError(c.t, err) + + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) + require.True(c.t, exists) + c.t.Logf("successfully created pool from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) +} + +func (c *Config) SubmitUpgradeProposal(upgradeVersion string) { + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) + require.True(c.t, exists) + + upgradeHeightStr := strconv.Itoa(c.PropHeight) + c.t.Logf("submitting upgrade proposal on %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%s", upgradeHeightStr), "--upgrade-info=\"\"", fmt.Sprintf("--chain-id=%s", c.Id), "--from=val", "-b=block", "--yes", "--keyring-backend=test", "--log_format=json"} + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + require.NoError(c.t, err) + c.t.Log("successfully submitted upgrade proposal") + c.LatestProposalNumber = c.LatestProposalNumber + 1 +} + +func (c *Config) SubmitSuperfluidProposal(asset string) { + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) + require.True(c.t, exists) + + c.t.Logf("submitting superfluid proposal for asset %s on %s container: %s", asset, validatorResource.Container.Name[1:], validatorResource.Container.ID) + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "set-superfluid-assets-proposal", fmt.Sprintf("--superfluid-assets=%s", asset), fmt.Sprintf("--title=\"%s superfluid asset\"", asset), fmt.Sprintf("--description=\"%s superfluid asset\"", asset), "--from=val", "-b=block", "--yes", "--keyring-backend=test", "--log_format=json", fmt.Sprintf("--chain-id=%s", c.Id)} + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + require.NoError(c.t, err) + c.t.Log("successfully submitted superfluid proposal") + c.LatestProposalNumber = c.LatestProposalNumber + 1 +} + +func (c *Config) SubmitTextProposal(text string) { + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) + require.True(c.t, exists) + + c.t.Logf("submitting text proposal on %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "--type=text", fmt.Sprintf("--title=\"%s\"", text), "--description=\"test text proposal\"", "--from=val", "-b=block", "--yes", "--keyring-backend=test", "--log_format=json", fmt.Sprintf("--chain-id=%s", c.Id)} + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + c.t.Log("successfully submitted text proposal") + require.NoError(c.t, err) + c.LatestProposalNumber = c.LatestProposalNumber + 1 +} + +func (c *Config) DepositProposal() { + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) + require.True(c.t, exists) + + propStr := strconv.Itoa(c.LatestProposalNumber) + c.t.Logf("depositing to proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) + cmd := []string{"osmosisd", "tx", "gov", "deposit", propStr, "500000000uosmo", "--from=val", fmt.Sprintf("--chain-id=%s", c.Id), "-b=block", "--yes", "--keyring-backend=test"} + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + require.NoError(c.t, err) + c.t.Log("successfully deposited to proposal") +} + +func (c *Config) VoteYesProposal() { + propStr := strconv.Itoa(c.LatestProposalNumber) + c.t.Logf("voting yes on proposal for chain-id: %s", c.Id) + cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "yes", "--from=val", fmt.Sprintf("--chain-id=%s", c.Id), "-b=block", "--yes", "--keyring-backend=test"} + for i := range c.NodeConfigs { + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, i, cmd, "code: 0") + require.NoError(c.t, err) + + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, i) + require.True(c.t, exists) + c.t.Logf("successfully voted yes on proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) + } +} + +func (c *Config) VoteNoProposal(validatorIdx int, from string) { + propStr := strconv.Itoa(c.LatestProposalNumber) + c.t.Logf("voting no on proposal for chain-id: %s", c.Id) + cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "no", fmt.Sprintf("--from=%s", from), fmt.Sprintf("--chain-id=%s", c.Id), "-b=block", "--yes", "--keyring-backend=test"} + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIdx, cmd, "code: 0") + require.NoError(c.t, err) + + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, validatorIdx) + require.True(c.t, exists) + c.t.Logf("successfully voted no for proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) +} + +func (c *Config) LockTokens(validatorIdx int, tokens string, duration string, from string) { + c.t.Logf("locking %s for %s on chain-id: %s", tokens, duration, c.Id) + cmd := []string{"osmosisd", "tx", "lockup", "lock-tokens", tokens, fmt.Sprintf("--chain-id=%s", c.Id), fmt.Sprintf("--duration=%s", duration), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIdx, cmd, "code: 0") + require.NoError(c.t, err) + + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, validatorIdx) + require.True(c.t, exists) + c.t.Logf("successfully created lock %v from %s container: %s", c.LatestLockNumber, validatorResource.Container.Name[1:], validatorResource.Container.ID) + c.LatestLockNumber = c.LatestLockNumber + 1 +} + +func (c *Config) SuperfluidDelegate(valAddress string, from string) { + lockStr := strconv.Itoa(c.LatestLockNumber) + c.t.Logf("superfluid delegating lock %s to %s on chain-id: %s", lockStr, valAddress, c.Id) + cmd := []string{"osmosisd", "tx", "superfluid", "delegate", lockStr, valAddress, fmt.Sprintf("--chain-id=%s", c.Id), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + require.NoError(c.t, err) + + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) + require.True(c.t, exists) + c.t.Logf("successfully superfluid delegated from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) +} + +func (c *Config) BankSend(validatorIndex int, amount string, sendAddress string, receiveAddress string) { + c.t.Logf("sending %s from %s to %s on chain-id: %s", amount, sendAddress, receiveAddress, c.Id) + cmd := []string{"osmosisd", "tx", "bank", "send", sendAddress, receiveAddress, amount, fmt.Sprintf("--chain-id=%s", c.Id), "--from=val", "-b=block", "--yes", "--keyring-backend=test"} + _, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIndex, cmd, "code: 0") + require.NoError(c.t, err) + + validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) + require.True(c.t, exists) + c.t.Logf("successfully sent tx from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) +} + +func (c *Config) CreateWallet(validatorIndex int, walletName string) string { + cmd := []string{"osmosisd", "keys", "add", walletName, "--keyring-backend=test"} + outBuf, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIndex, cmd, "") + require.NoError(c.t, err) + re := regexp.MustCompile("osmo1(.{38})") + walletAddr := fmt.Sprintf("%s\n", re.FindString(outBuf.String())) + walletAddr = strings.TrimSuffix(walletAddr, "\n") + return walletAddr +} + +func (c *Config) SendIBC(dstChain *Config, recipient string, token sdk.Coin) { + c.t.Logf("sending %s from %s to %s (%s)", token, c.Id, dstChain.Id, recipient) + balancesBPre, err := dstChain.QueryBalances(0, recipient) + require.NoError(c.t, err) + + cmd := []string{"hermes", "tx", "raw", "ft-transfer", dstChain.Id, c.Id, "transfer", "channel-0", token.Amount.String(), fmt.Sprintf("--denom=%s", token.Denom), fmt.Sprintf("--receiver=%s", recipient), "--timeout-height-offset=1000"} + _, _, err = c.containerManager.ExecCmd(c.t, "", 0, cmd, "Success") + require.NoError(c.t, err) + + require.Eventually( + c.t, + func() bool { + balancesBPost, err := dstChain.QueryBalances(0, recipient) + require.NoError(c.t, err) + ibcCoin := balancesBPost.Sub(balancesBPre) + if ibcCoin.Len() == 1 { + tokenPre := balancesBPre.AmountOfNoDenomValidation(ibcCoin[0].Denom) + tokenPost := balancesBPost.AmountOfNoDenomValidation(ibcCoin[0].Denom) + resPre := initialization.OsmoToken.Amount + resPost := tokenPost.Sub(tokenPre) + return resPost.Uint64() == resPre.Uint64() + } else { + return false + } + }, + 5*time.Minute, + time.Second, + "tx not received on destination chain", + ) + + c.t.Log("successfully sent IBC tokens") +} + +func (c *Config) ExtractValidatorOperatorAddresses() { + for i, val := range c.NodeConfigs { + cmd := []string{"osmosisd", "debug", "addr", val.PublicKey} + c.t.Logf("extracting validator operator addresses for chain-id: %s", c.Id) + _, errBuf, err := c.containerManager.ExecCmd(c.t, c.Id, i, cmd, "") + require.NoError(c.t, err) + re := regexp.MustCompile("osmovaloper(.{39})") + operAddr := fmt.Sprintf("%s\n", re.FindString(errBuf.String())) + c.NodeConfigs[i].OperatorAddress = strings.TrimSuffix(operAddr, "\n") + } +} diff --git a/tests/e2e/configurer/chain/queries.go b/tests/e2e/configurer/chain/queries.go new file mode 100644 index 00000000000..58219ee2c4f --- /dev/null +++ b/tests/e2e/configurer/chain/queries.go @@ -0,0 +1,150 @@ +package chain + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" + "strconv" + "strings" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/stretchr/testify/require" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" + superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" +) + +func (c *Config) QueryRPC(path string) ([]byte, error) { + var err error + var resp *http.Response + retriesLeft := 5 + for { + resp, err = http.Get(path) + + if resp.StatusCode == http.StatusServiceUnavailable { + retriesLeft-- + if retriesLeft == 0 { + return nil, err + } + time.Sleep(10 * time.Second) + } else { + break + } + } + + if err != nil { + return nil, fmt.Errorf("failed to execute HTTP request: %w", err) + } + + defer resp.Body.Close() + + bz, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return bz, nil +} + +func (c *Config) QueryChainStatus(validatorIdx int) []byte { + cmd := []string{"osmosisd", "status"} + _, errBuf, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIdx, cmd, "NodeInfo") + require.NoError(c.t, err) + return errBuf.Bytes() +} + +func (c *Config) QueryCurrentChainHeightFromValidator(validatorIdx int) int { + var block syncInfo + require.Eventually( + c.t, + func() bool { + out := c.QueryChainStatus(validatorIdx) + err := json.Unmarshal(out, &block) + return err == nil + }, + 1*time.Minute, + time.Second, + "Osmosis node failed to retrieve height info", + ) + currentHeight, err := strconv.Atoi(block.SyncInfo.LatestHeight) + require.NoError(c.t, err) + return currentHeight +} + +func (c *Config) QueryBalances(validatorIndex int, addr string) (sdk.Coins, error) { + cmd := []string{"osmosisd", "query", "bank", "balances", addr, "--output=json"} + outBuf, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIndex, cmd, "balances") + require.NoError(c.t, err) + + var balancesResp banktypes.QueryAllBalancesResponse + err = util.Cdc.UnmarshalJSON(outBuf.Bytes(), &balancesResp) + require.NoError(c.t, err) + + return balancesResp.GetBalances(), nil +} + +func (c *Config) QueryPropTally(validatorIdx int, addr string) (sdk.Int, sdk.Int, sdk.Int, sdk.Int, error) { + hostPort, err := c.containerManager.GetValidatorHostPort(c.Id, validatorIdx, "1317/tcp") + require.NoError(c.t, err) + + endpoint := fmt.Sprintf("http://%s", hostPort) + + path := fmt.Sprintf( + "%s/cosmos/gov/v1beta1/proposals/%s/tally", + endpoint, addr, + ) + bz, err := c.QueryRPC(path) + require.NoError(c.t, err) + + var balancesResp govtypes.QueryTallyResultResponse + if err := util.Cdc.UnmarshalJSON(bz, &balancesResp); err != nil { + return sdk.ZeroInt(), sdk.ZeroInt(), sdk.ZeroInt(), sdk.ZeroInt(), err + } + noTotal := balancesResp.Tally.No + yesTotal := balancesResp.Tally.Yes + noWithVetoTotal := balancesResp.Tally.NoWithVeto + abstainTotal := balancesResp.Tally.Abstain + + return noTotal, yesTotal, noWithVetoTotal, abstainTotal, nil +} + +func (c *Config) QueryValidatorOperatorAddresses() { + for i, val := range c.NodeConfigs { + cmd := []string{"osmosisd", "debug", "addr", val.PublicKey} + c.t.Logf("extracting validator operator addresses for chain-id: %s", c.Id) + _, errBuf, err := c.containerManager.ExecCmd(c.t, c.Id, i, cmd, "") + require.NoError(c.t, err) + re := regexp.MustCompile("osmovaloper(.{39})") + operAddr := fmt.Sprintf("%s\n", re.FindString(errBuf.String())) + c.NodeConfigs[i].OperatorAddress = strings.TrimSuffix(operAddr, "\n") + } +} + +func (c *Config) QueryIntermediaryAccount(validatorIdx int, denom string, valAddr string) (int, error) { + hostPort, err := c.containerManager.GetValidatorHostPort(c.Id, validatorIdx, "1317/tcp") + require.NoError(c.t, err) + + endpoint := fmt.Sprintf("http://%s", hostPort) + + intAccount := superfluidtypes.GetSuperfluidIntermediaryAccountAddr(denom, valAddr) + path := fmt.Sprintf( + "%s/cosmos/staking/v1beta1/validators/%s/delegations/%s", + endpoint, valAddr, intAccount, + ) + bz, err := c.QueryRPC(path) + require.NoError(c.t, err) + + var stakingResp stakingtypes.QueryDelegationResponse + err = util.Cdc.UnmarshalJSON(bz, &stakingResp) + require.NoError(c.t, err) + + intAccBalance := stakingResp.DelegationResponse.Balance.Amount.String() + intAccountBalance, err := strconv.Atoi(intAccBalance) + require.NoError(c.t, err) + return intAccountBalance, err +} diff --git a/tests/e2e/configurer/chain/validator.go b/tests/e2e/configurer/chain/validator.go new file mode 100644 index 00000000000..c973d1378d2 --- /dev/null +++ b/tests/e2e/configurer/chain/validator.go @@ -0,0 +1,9 @@ +package chain + +import "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + +type ValidatorConfig struct { + initialization.Node + + OperatorAddress string +} diff --git a/tests/e2e/configurer/config/constants.go b/tests/e2e/configurer/config/constants.go new file mode 100644 index 00000000000..3e2518261fd --- /dev/null +++ b/tests/e2e/configurer/config/constants.go @@ -0,0 +1,16 @@ +package config + +const ( + // if not skipping upgrade, how many blocks we allow for fork to run pre upgrade state creation + ForkHeightPreUpgradeOffset int64 = 60 + // estimated number of blocks it takes to submit for a proposal + PropSubmitBlocks float32 = 10 + // estimated number of blocks it takes to deposit for a proposal + PropDepositBlocks float32 = 10 + // number of blocks it takes to vote for a single validator to vote for a proposal + PropVoteBlocks float32 = 1.2 + // number of blocks used as a calculation buffer + PropBufferBlocks float32 = 5 + // max retries for json unmarshalling + MaxRetries = 60 +) diff --git a/tests/e2e/configurer/current.go b/tests/e2e/configurer/current.go new file mode 100644 index 00000000000..8e058e2fcd4 --- /dev/null +++ b/tests/e2e/configurer/current.go @@ -0,0 +1,57 @@ +package configurer + +import ( + "os" + "testing" + "time" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +) + +type CurrentBranchConfigurer struct { + baseConfigurer +} + +var _ Configurer = (*CurrentBranchConfigurer)(nil) + +func NewCurrentBranchConfigurer(t *testing.T, chainConfigs []*chain.Config, setupTests setupFn, containerManager *containers.Manager) Configurer { + return &CurrentBranchConfigurer{ + baseConfigurer: baseConfigurer{ + chainConfigs: chainConfigs, + containerManager: containerManager, + setupTests: setupTests, + syncUntilHeight: defaultSyncUntilHeight, + t: t, + }, + } +} + +func (cb *CurrentBranchConfigurer) ConfigureChains() error { + for _, chainConfig := range cb.chainConfigs { + if err := cb.ConfigureChain(chainConfig); err != nil { + return err + } + } + return nil +} + +func (cb *CurrentBranchConfigurer) ConfigureChain(chainConfig *chain.Config) error { + cb.t.Logf("starting e2e infrastructure from current branch for chain-id: %s", chainConfig.Id) + tmpDir, err := os.MkdirTemp("", "osmosis-e2e-testnet-") + if err != nil { + return err + } + cb.t.Logf("temp directory for chain-id %v: %v", chainConfig.Id, tmpDir) + initializedChain, err := initialization.InitChain(chainConfig.Id, tmpDir, chainConfig.ValidatorInitConfigs, time.Duration(chainConfig.VotingPeriod), 0) + if err != nil { + return err + } + cb.initializeChainConfigFromInitChain(initializedChain, chainConfig) + return nil +} + +func (cb *CurrentBranchConfigurer) RunSetup() error { + return cb.setupTests(cb) +} diff --git a/tests/e2e/configurer/factory.go b/tests/e2e/configurer/factory.go new file mode 100644 index 00000000000..f25db50c14c --- /dev/null +++ b/tests/e2e/configurer/factory.go @@ -0,0 +1,148 @@ +package configurer + +import ( + "errors" + "testing" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +) + +type Configurer interface { + ConfigureChains() error + + ClearResources() error + + GetChainConfig(chainIndex int) *chain.Config + + RunSetup() error + + RunValidators() error + + RunIBC() error +} + +var ( + // whatever number of validator configs get posted here are how many validators that will spawn on chain A and B respectively + validatorConfigsChainA = []*initialization.NodeConfig{ + { + Name: "prune-default-snapshot", + Pruning: "default", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 1500, + SnapshotKeepRecent: 2, + IsValidator: true, + }, + { + Name: "prune-nothing-snapshot", + Pruning: "nothing", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 1500, + SnapshotKeepRecent: 2, + IsValidator: true, + }, + { + Name: "prune-custom-10000-13-snapshot", + Pruning: "custom", + PruningKeepRecent: "10000", + PruningInterval: "13", + SnapshotInterval: 1500, + SnapshotKeepRecent: 2, + IsValidator: true, + }, + { + Name: "prune-everything-no-snapshot", + Pruning: "everything", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 0, + SnapshotKeepRecent: 0, + IsValidator: true, + }, + } + validatorConfigsChainB = []*initialization.NodeConfig{ + { + Name: "prune-default-snapshot", + Pruning: "default", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 1500, + SnapshotKeepRecent: 2, + IsValidator: true, + }, + { + Name: "prune-nothing-snapshot", + Pruning: "nothing", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 1500, + SnapshotKeepRecent: 2, + IsValidator: true, + }, + { + Name: "prune-custom-snapshot", + Pruning: "custom", + PruningKeepRecent: "10000", + PruningInterval: "13", + SnapshotInterval: 1500, + SnapshotKeepRecent: 2, + IsValidator: true, + }, + } +) + +// New returns a new Configurer depending on the values of its parameters. +// - If only isIBCEnabled, we want to have 2 chains initialized at the current +// Git branch version of Osmosis codebase. +// - If only isUpgradeEnabled, that is invalid and an error is returned. +// - If both isIBCEnabled and isUpgradeEnabled, we want 2 chains with IBC initialized +// at the previous Osmosis version. +// - If !isIBCEnabled and !isUpgradeEnabled, we only need one chain at the current +// Git branch version of the Osmosis code. +func New(t *testing.T, isIBCEnabled bool, upgradeSettings UpgradeSettings) (Configurer, error) { + containerManager, err := containers.NewManager(upgradeSettings.IsEnabled, upgradeSettings.ForkHeight > 0) + if err != nil { + return nil, err + } + + if isIBCEnabled && upgradeSettings.IsEnabled { + // skip none - configure two chains via Docker + // to utilize the older version of osmosis to upgrade from + return NewUpgradeConfigurer(t, + []*chain.Config{ + chain.New(t, containerManager, initialization.ChainAID, validatorConfigsChainA), + chain.New(t, containerManager, initialization.ChainBID, validatorConfigsChainB), + }, + withUpgrade(withIBC(baseSetup)), // base set up with IBC and upgrade + containerManager, + upgradeSettings.Version, + upgradeSettings.ForkHeight, + ), nil + } else if isIBCEnabled { + // configure two chains from current Git branch + return NewCurrentBranchConfigurer(t, + []*chain.Config{ + chain.New(t, containerManager, initialization.ChainAID, validatorConfigsChainA), + chain.New(t, containerManager, initialization.ChainBID, validatorConfigsChainB), + }, + withIBC(baseSetup), // base set up with IBC + containerManager, + ), nil + } else if upgradeSettings.IsEnabled { + // invalid - IBC tests must be enabled for upgrade + // to function + return nil, errors.New("IBC tests must be enabled for upgrade to work") + } else { + // configure one chain from current Git branch + return NewCurrentBranchConfigurer(t, + []*chain.Config{ + chain.New(t, containerManager, initialization.ChainAID, validatorConfigsChainA), + }, + baseSetup, // base set up only + containerManager, + ), nil + } +} diff --git a/tests/e2e/configurer/setup.go b/tests/e2e/configurer/setup.go new file mode 100644 index 00000000000..d12944fdb32 --- /dev/null +++ b/tests/e2e/configurer/setup.go @@ -0,0 +1,49 @@ +package configurer + +import ( + "fmt" +) + +type setupFn func(configurer Configurer) error + +func baseSetup(configurer Configurer) error { + if err := configurer.RunValidators(); err != nil { + return err + } + return nil +} + +func withIBC(setupHandler setupFn) setupFn { + return func(configurer Configurer) error { + if err := setupHandler(configurer); err != nil { + return err + } + + if err := configurer.RunIBC(); err != nil { + return err + } + + return nil + } +} + +func withUpgrade(setupHandler setupFn) setupFn { + return func(configurer Configurer) error { + if err := setupHandler(configurer); err != nil { + return err + } + + upgradeConfigurer, ok := configurer.(*UpgradeConfigurer) + if !ok { + return fmt.Errorf("to run with upgrade, %v must be set during initialization", &UpgradeConfigurer{}) + } + + upgradeConfigurer.CreatePreUpgradeState() + + if err := upgradeConfigurer.RunUpgrade(); err != nil { + return err + } + + return nil + } +} diff --git a/tests/e2e/configurer/upgrade.go b/tests/e2e/configurer/upgrade.go new file mode 100644 index 00000000000..364f2ea464c --- /dev/null +++ b/tests/e2e/configurer/upgrade.go @@ -0,0 +1,259 @@ +package configurer + +import ( + "encoding/json" + "fmt" + "os" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/config" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +) + +type UpgradeSettings struct { + IsEnabled bool + Version string + ForkHeight int64 // non-zero height implies that this is a fork upgrade. +} + +type UpgradeConfigurer struct { + baseConfigurer + upgradeVersion string + forkHeight int64 // forkHeight > 0 implies that this is a fork upgrade. Otherwise, proposal upgrade. +} + +var _ Configurer = (*UpgradeConfigurer)(nil) + +func NewUpgradeConfigurer(t *testing.T, chainConfigs []*chain.Config, setupTests setupFn, containerManager *containers.Manager, upgradeVersion string, forkHeight int64) Configurer { + return &UpgradeConfigurer{ + baseConfigurer: baseConfigurer{ + chainConfigs: chainConfigs, + containerManager: containerManager, + setupTests: setupTests, + syncUntilHeight: forkHeight + defaultSyncUntilHeight, + t: t, + }, + forkHeight: forkHeight, + upgradeVersion: upgradeVersion, + } +} + +func (uc *UpgradeConfigurer) ConfigureChains() error { + for _, chainConfig := range uc.chainConfigs { + if err := uc.ConfigureChain(chainConfig); err != nil { + return err + } + } + return nil +} + +func (uc *UpgradeConfigurer) ConfigureChain(chainConfig *chain.Config) error { + uc.t.Logf("starting upgrade e2e infrastructure for chain-id: %s", chainConfig.Id) + tmpDir, err := os.MkdirTemp("", "osmosis-e2e-testnet-") + if err != nil { + return err + } + + numVal := float32(len(chainConfig.ValidatorInitConfigs)) + chainConfig.VotingPeriod = config.PropDepositBlocks + numVal*config.PropVoteBlocks + config.PropBufferBlocks + + validatorConfigBytes, err := json.Marshal(chainConfig.ValidatorInitConfigs) + if err != nil { + return err + } + + forkHeight := uc.forkHeight + if forkHeight > 0 { + forkHeight = forkHeight - config.ForkHeightPreUpgradeOffset + } + + chainInitResource, err := uc.containerManager.RunChainInitResource(chainConfig.Id, int(chainConfig.VotingPeriod), validatorConfigBytes, tmpDir, int(forkHeight)) + + if err != nil { + return err + } + + fileName := fmt.Sprintf("%v/%v-encode", tmpDir, chainConfig.Id) + uc.t.Logf("serialized init file for chain-id %v: %v", chainConfig.Id, fileName) + + // loop through the reading and unmarshaling of the init file a total of maxRetries or until error is nil + // without this, test attempts to unmarshal file before docker container is finished writing + var initializedChain initialization.Chain + for i := 0; i < config.MaxRetries; i++ { + initializedChainBytes, _ := os.ReadFile(fileName) + err = json.Unmarshal(initializedChainBytes, &initializedChain) + if err == nil { + break + } + + if i == config.MaxRetries-1 { + if err != nil { + return err + } + } + + if i > 0 { + time.Sleep(1 * time.Second) + } + } + if err := uc.containerManager.PurgeResource(chainInitResource); err != nil { + return err + } + uc.initializeChainConfigFromInitChain(&initializedChain, chainConfig) + return nil +} + +func (uc *UpgradeConfigurer) CreatePreUpgradeState() { + chainA := uc.chainConfigs[0] + chainB := uc.chainConfigs[1] + + chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, initialization.OsmoToken) + chainB.SendIBC(chainA, chainA.NodeConfigs[0].PublicAddress, initialization.OsmoToken) + chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, initialization.StakeToken) + chainB.SendIBC(chainA, chainA.NodeConfigs[0].PublicAddress, initialization.StakeToken) + + chainA.CreatePool("pool1A.json", initialization.ValidatorWalletName) + chainB.CreatePool("pool1B.json", initialization.ValidatorWalletName) +} + +func (uc *UpgradeConfigurer) RunSetup() error { + return uc.setupTests(uc) +} + +func (uc *UpgradeConfigurer) RunUpgrade() error { + if uc.forkHeight > 0 { + return uc.runForkUpgrade() + } + return uc.runProposalUpgrade() +} + +func (uc *UpgradeConfigurer) runProposalUpgrade() error { + // submit, deposit, and vote for upgrade proposal + // prop height = current height + voting period + time it takes to submit proposal + small buffer + for _, chainConfig := range uc.chainConfigs { + currentHeight := chainConfig.QueryCurrentChainHeightFromValidator(0) + chainConfig.PropHeight = currentHeight + int(chainConfig.VotingPeriod) + int(config.PropSubmitBlocks) + int(config.PropBufferBlocks) + + chainConfig.SubmitUpgradeProposal(uc.upgradeVersion) + chainConfig.DepositProposal() + chainConfig.VoteYesProposal() + } + + // wait till all chains halt at upgrade height + for _, chainConfig := range uc.chainConfigs { + for validatorIndex := range chainConfig.NodeConfigs { + validatorResource, exists := uc.containerManager.GetValidatorResource(chainConfig.Id, validatorIndex) + require.True(uc.t, exists, "validator container not found: chain id %s, valIdx %d ", chainConfig.Id, validatorIndex) + containerId := validatorResource.Container.ID + containerName := validatorResource.Container.Name[1:] + + // use counter to ensure no new blocks are being created + counter := 0 + uc.t.Logf("waiting to reach upgrade height on %s validator container: %s", containerName, containerId) + require.Eventually( + uc.t, + func() bool { + currentHeight := chainConfig.QueryCurrentChainHeightFromValidator(validatorIndex) + if currentHeight != chainConfig.PropHeight { + uc.t.Logf("current block height on %s is %v, waiting for block %v container: %s", containerName, currentHeight, chainConfig.PropHeight, containerId) + } + if currentHeight > chainConfig.PropHeight { + panic("chain did not halt at upgrade height") + } + if currentHeight == chainConfig.PropHeight { + counter++ + } + return counter == 3 + }, + 5*time.Minute, + time.Second, + ) + uc.t.Logf("reached upgrade height on %s container: %s", containerName, containerId) + } + } + + // remove all containers so we can upgrade them to the new version + for _, chainConfig := range uc.chainConfigs { + for _, validatorConfig := range chainConfig.NodeConfigs { + err := uc.containerManager.RemoveValidatorResource(chainConfig.Id, validatorConfig.Name) + if err != nil { + return err + } + } + } + + // remove all containers so we can upgrade them to the new version + for _, chainConfig := range uc.chainConfigs { + uc.upgradeContainers(chainConfig, chainConfig.PropHeight) + } + return nil +} + +func (uc *UpgradeConfigurer) runForkUpgrade() error { + for _, chainConfig := range uc.chainConfigs { + for i := range chainConfig.NodeConfigs { + validatorResource, exists := uc.containerManager.GetValidatorResource(chainConfig.Id, i) + if !exists { + return fmt.Errorf("validator container not found: chain id %s, valIdx %d ", chainConfig.Id, i) + } + containerId := validatorResource.Container.ID + containerName := validatorResource.Container.Name[1:] + + uc.t.Logf("waiting to reach fork height on %s validator container: %s", containerName, containerId) + require.Eventually( + uc.t, + func() bool { + currentHeight := chainConfig.QueryCurrentChainHeightFromValidator(i) + if int64(currentHeight) < uc.forkHeight { + uc.t.Logf("current block height on %s is %v, waiting for block %v container: %s", containerName, currentHeight, uc.forkHeight, containerId) + return false + } + return true + }, + 5*time.Minute, + time.Second, + ) + uc.t.Logf("successfully got past fork height on %s container: %s", containerName, containerId) + } + } + return nil +} + +func (uc *UpgradeConfigurer) upgradeContainers(chainConfig *chain.Config, propHeight int) { + // upgrade containers to the locally compiled daemon + uc.t.Logf("starting upgrade for chain-id: %s...", chainConfig.Id) + uc.containerManager.OsmosisRepository = containers.CurrentBranchOsmoRepository + uc.containerManager.OsmosisTag = containers.CurrentBranchOsmoTag + for _, val := range chainConfig.NodeConfigs { + validatorResource, err := uc.containerManager.RunValidatorResource(chainConfig.Id, val.Name, val.ConfigDir) + require.NoError(uc.t, err) + uc.t.Logf("started %s validator container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) + } + + // check that we are creating blocks again + for validatorIndex := range chainConfig.NodeConfigs { + validatorResource, exists := uc.containerManager.GetValidatorResource(chainConfig.Id, validatorIndex) + require.True(uc.t, exists, "validator container not found: chain id %s, valIdx %d ", chainConfig.Id, validatorIndex) + containerId := validatorResource.Container.ID + containerName := validatorResource.Container.Name[1:] + + require.Eventually( + uc.t, + func() bool { + currentHeight := chainConfig.QueryCurrentChainHeightFromValidator(validatorIndex) + if currentHeight <= propHeight { + uc.t.Logf("current block height on %s is %v, waiting to create blocks container: %s", containerName, currentHeight, containerId) + } + return currentHeight > propHeight + }, + 5*time.Minute, + time.Second, + ) + uc.t.Logf("upgrade successful on %s validator container: %s", containerName, containerId) + } +} diff --git a/tests/e2e/e2e_setup_test.go b/tests/e2e/e2e_setup_test.go index 6d3a7f1dd1f..acd8940ce06 100644 --- a/tests/e2e/e2e_setup_test.go +++ b/tests/e2e/e2e_setup_test.go @@ -1,54 +1,16 @@ package e2e import ( - "context" - "encoding/json" "fmt" - "io" - "net/http" "os" - "path" - "path/filepath" "strconv" "testing" - "time" - "github.com/ory/dockertest/v3/docker" - "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" - - "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" + configurer "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer" ) -type status struct { - LatestHeight string `json:"latest_block_height"` -} - -type syncInfo struct { - SyncInfo status `json:"SyncInfo"` -} - -type validatorConfig struct { - validator initialization.Node - operatorAddress string -} - -type chainConfig struct { - // voting period is number of blocks it takes to deposit, 1.2 seconds per validator to vote on the prop, and a buffer. - votingPeriod float32 - // upgrade proposal height for chain. - propHeight int - forkHeight int - latestProposalNumber int - latestLockNumber int - meta initialization.ChainMeta - validators []*validatorConfig -} - const ( // Environment variable name to skip the upgrade tests skipUpgradeEnv = "OSMOSIS_E2E_SKIP_UPGRADE" @@ -60,102 +22,15 @@ const ( skipCleanupEnv = "OSMOSIS_E2E_SKIP_CLEANUP" // Environment variable name to determine what version we are upgrading to upgradeVersionEnv = "OSMOSIS_E2E_UPGRADE_VERSION" - // if not skipping upgrade, how many blocks we allow for fork to run pre upgrade state creation - forkHeightPreUpgradeOffset int = 60 - // estimated number of blocks it takes to submit for a proposal - propSubmitBlocks float32 = 10 - // estimated number of blocks it takes to deposit for a proposal - propDepositBlocks float32 = 10 - // number of blocks it takes to vote for a single validator to vote for a proposal - propVoteBlocks float32 = 1.2 - // number of blocks used as a calculation buffer - propBufferBlocks float32 = 5 - // max retries for json unmarshalling - maxRetries = 60 -) - -var ( - // whatever number of validator configs get posted here are how many validators that will spawn on chain A and B respectively - validatorConfigsChainA = []*initialization.NodeConfig{ - { - Name: "prune-default-snapshot", - Pruning: "default", - PruningKeepRecent: "0", - PruningInterval: "0", - SnapshotInterval: 1500, - SnapshotKeepRecent: 2, - IsValidator: true, - }, - { - Name: "prune-nothing-snapshot", - Pruning: "nothing", - PruningKeepRecent: "0", - PruningInterval: "0", - SnapshotInterval: 1500, - SnapshotKeepRecent: 2, - IsValidator: true, - }, - { - Name: "prune-custom-10000-13-snapshot", - Pruning: "custom", - PruningKeepRecent: "10000", - PruningInterval: "13", - SnapshotInterval: 1500, - SnapshotKeepRecent: 2, - IsValidator: true, - }, - { - Name: "prune-everything-no-snapshot", - Pruning: "everything", - PruningKeepRecent: "0", - PruningInterval: "0", - SnapshotInterval: 0, - SnapshotKeepRecent: 0, - IsValidator: true, - }, - } - validatorConfigsChainB = []*initialization.NodeConfig{ - { - Name: "prune-default-snapshot", - Pruning: "default", - PruningKeepRecent: "0", - PruningInterval: "0", - SnapshotInterval: 1500, - SnapshotKeepRecent: 2, - IsValidator: true, - }, - { - Name: "prune-nothing-snapshot", - Pruning: "nothing", - PruningKeepRecent: "0", - PruningInterval: "0", - SnapshotInterval: 1500, - SnapshotKeepRecent: 2, - IsValidator: true, - }, - { - Name: "prune-custom-snapshot", - Pruning: "custom", - PruningKeepRecent: "10000", - PruningInterval: "13", - SnapshotInterval: 1500, - SnapshotKeepRecent: 2, - IsValidator: true, - }, - } ) type IntegrationTestSuite struct { suite.Suite - tmpDirs []string - chainConfigs []*chainConfig - containerManager *containers.Manager - skipUpgrade bool - skipIBC bool - isFork bool - forkHeight int - upgradeVersion string + configurer configurer.Configurer + skipUpgrade bool + skipIBC bool + forkHeight int } func TestIntegrationTestSuite(t *testing.T) { @@ -164,10 +39,10 @@ func TestIntegrationTestSuite(t *testing.T) { func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up e2e integration test suite...") - var forkHeight64 int64 - var err error - - s.chainConfigs = make([]*chainConfig, 0, 2) + var ( + err error + upgradeSettings configurer.UpgradeSettings + ) // The e2e test flow is as follows: // @@ -177,81 +52,39 @@ func (s *IntegrationTestSuite) SetupSuite() { // 2. Start both networks. // 3. Run IBC relayer betweeen the two chains. // 4. Execute various e2e tests, including IBC. - if str := os.Getenv(skipUpgradeEnv); len(str) > 0 { s.skipUpgrade, err = strconv.ParseBool(str) s.Require().NoError(err) - - if s.skipUpgrade { - s.T().Log(fmt.Sprintf("%s was true, skipping upgrade tests", skipIBCEnv)) - } + s.T().Log(fmt.Sprintf("%s was true, skipping upgrade tests", skipIBCEnv)) } + upgradeSettings.IsEnabled = !s.skipUpgrade if str := os.Getenv(forkHeightEnv); len(str) > 0 { - forkHeight64, err = strconv.ParseInt(str, 0, 64) + upgradeSettings.ForkHeight, err = strconv.ParseInt(str, 0, 64) s.Require().NoError(err) - s.forkHeight = int(forkHeight64) - s.isFork = true - s.T().Log(fmt.Sprintf("fork upgrade is enabled, %s was set to height %v", forkHeightEnv, s.forkHeight)) + s.T().Log(fmt.Sprintf("fork upgrade is enabled, %s was set to height %d", forkHeightEnv, upgradeSettings.ForkHeight)) } if str := os.Getenv(skipIBCEnv); len(str) > 0 { s.skipIBC, err = strconv.ParseBool(str) s.Require().NoError(err) - - if s.skipIBC { - s.T().Log(fmt.Sprintf("%s was true, skipping IBC tests", skipIBCEnv)) - - if !s.skipUpgrade { - s.T().Fatal("If upgrade is enabled, IBC must be enabled as well.") - } - } + s.T().Log(fmt.Sprintf("%s was true, skipping IBC tests", skipIBCEnv)) } if str := os.Getenv(upgradeVersionEnv); len(str) > 0 { - s.upgradeVersion = str - - s.T().Log(fmt.Sprintf("upgrade version set to %s", s.upgradeVersion)) + upgradeSettings.Version = str + s.T().Log(fmt.Sprintf("upgrade version set to %s", upgradeSettings.Version)) } - s.containerManager, err = containers.NewManager(!s.skipUpgrade, s.isFork) - require.NoError(s.T(), err) - - s.configureChain(initialization.ChainAID, validatorConfigsChainA, map[int]struct{}{ - 3: {}, // skip validator at index 3 - }) - - // We don't need a second chain if IBC is disabled - if !s.skipIBC { - s.configureChain(initialization.ChainBID, validatorConfigsChainB, map[int]struct{}{}) - } - - for i, chainConfig := range s.chainConfigs { - s.runValidators(chainConfig, i*10) - s.extractValidatorOperatorAddresses(chainConfig) - } - - if !s.skipIBC { - // Run a relayer between every possible pair of chains. - for i := 0; i < len(s.chainConfigs); i++ { - for j := i + 1; j < len(s.chainConfigs); j++ { - s.runIBCRelayer(s.chainConfigs[i], s.chainConfigs[j]) - } - } - } - - if !s.skipUpgrade { - s.createPreUpgradeState() + s.configurer, err = configurer.New(s.T(), !s.skipIBC, upgradeSettings) + s.Require().NoError(err) - if s.isFork { - s.upgradeFork() - } else { - s.upgrade() - } - } + err = s.configurer.ConfigureChains() + s.Require().NoError(err) - s.runPostUpgradeTests() + err = s.configurer.RunSetup() + s.Require().NoError(err) } func (s *IntegrationTestSuite) TearDownSuite() { @@ -265,340 +98,6 @@ func (s *IntegrationTestSuite) TearDownSuite() { } } - s.T().Log("tearing down e2e integration test suite...") - - err := s.containerManager.ClearResources() - s.Require().NoError(err) - - for _, chainConfig := range s.chainConfigs { - os.RemoveAll(chainConfig.meta.DataDir) - } - - for _, td := range s.tmpDirs { - os.RemoveAll(td) - } -} - -func (s *IntegrationTestSuite) runValidators(chainConfig *chainConfig, portOffset int) { - s.T().Logf("starting %s validator containers...", chainConfig.meta.Id) - for _, val := range chainConfig.validators { - validatorResource, err := s.containerManager.RunValidatorResource(chainConfig.meta.Id, val.validator.Name, val.validator.ConfigDir) - require.NoError(s.T(), err) - s.T().Logf("started %s validator container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - } - - validatorHostPort, err := s.containerManager.GetValidatorHostPort(chainConfig.meta.Id, 0, "26657/tcp") - require.NoError(s.T(), err) - - rpcClient, err := rpchttp.New(fmt.Sprintf("tcp://%s", validatorHostPort), "/websocket") - s.Require().NoError(err) - - s.Require().Eventually( - func() bool { - ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) - defer cancel() - - status, err := rpcClient.Status(ctx) - if err != nil { - return false - } - - // let the node produce a few blocks - if status.SyncInfo.CatchingUp || status.SyncInfo.LatestBlockHeight < 3 { - return false - } - - return true - }, - 5*time.Minute, - time.Second, - "Osmosis node failed to produce blocks", - ) -} - -func (s *IntegrationTestSuite) runIBCRelayer(chainA *chainConfig, chainB *chainConfig) { - s.T().Log("starting Hermes relayer container...") - - tmpDir, err := os.MkdirTemp("", "osmosis-e2e-testnet-hermes-") - s.Require().NoError(err) - s.tmpDirs = append(s.tmpDirs, tmpDir) - - osmoAVal := chainA.validators[0].validator - osmoBVal := chainB.validators[0].validator - hermesCfgPath := path.Join(tmpDir, "hermes") - - s.Require().NoError(os.MkdirAll(hermesCfgPath, 0o755)) - _, err = util.CopyFile( - filepath.Join("./scripts/", "hermes_bootstrap.sh"), - filepath.Join(hermesCfgPath, "hermes_bootstrap.sh"), - ) - s.Require().NoError(err) - - hermesResource, err := s.containerManager.RunHermesResource(chainA.meta.Id, osmoAVal.Mnemonic, chainB.meta.Id, osmoBVal.Mnemonic, hermesCfgPath) - require.NoError(s.T(), err) - - endpoint := fmt.Sprintf("http://%s/state", hermesResource.GetHostPort("3031/tcp")) - s.Require().Eventually( - func() bool { - resp, err := http.Get(endpoint) - if err != nil { - return false - } - - defer resp.Body.Close() - - bz, err := io.ReadAll(resp.Body) - if err != nil { - return false - } - - var respBody map[string]interface{} - if err := json.Unmarshal(bz, &respBody); err != nil { - return false - } - - status := respBody["status"].(string) - result := respBody["result"].(map[string]interface{}) - - return status == "success" && len(result["chains"].([]interface{})) == 2 - }, - 5*time.Minute, - time.Second, - "hermes relayer not healthy", - ) - - s.T().Logf("started Hermes relayer container: %s", hermesResource.Container.ID) - - // XXX: Give time to both networks to start, otherwise we might see gRPC - // transport errors. - time.Sleep(10 * time.Second) - - // create the client, connection and channel between the two Osmosis chains - s.connectIBCChains(chainA, chainB) -} - -func (s *IntegrationTestSuite) configureChain(chainId string, validatorConfigs []*initialization.NodeConfig, skipValidatorIndexes map[int]struct{}) { - s.T().Logf("starting e2e infrastructure for chain-id: %s", chainId) - tmpDir, err := os.MkdirTemp("", "osmosis-e2e-testnet-") - - s.T().Logf("temp directory for chain-id %v: %v", chainId, tmpDir) - s.Require().NoError(err) - - validatorConfigBytes, err := json.Marshal(validatorConfigs) - s.Require().NoError(err) - - numVal := float32(len(validatorConfigs)) - - newChainConfig := chainConfig{ - votingPeriod: propDepositBlocks + numVal*propVoteBlocks + propBufferBlocks, - } - - // If upgrade is skipped, we can use the chain initialization logic from - // current branch directly. As a result, there is no need to run this - // via Docker. - - if s.skipUpgrade { - initializedChain, err := initialization.InitChain(chainId, tmpDir, validatorConfigs, time.Duration(newChainConfig.votingPeriod), s.forkHeight) - s.Require().NoError(err) - s.initializeChainConfig(&newChainConfig, initializedChain) - return - } - - if s.isFork { - s.forkHeight = s.forkHeight - forkHeightPreUpgradeOffset - } - - initResource, err := s.containerManager.RunChainInitResource(chainId, int(newChainConfig.votingPeriod), validatorConfigBytes, tmpDir, s.forkHeight) + err := s.configurer.ClearResources() s.Require().NoError(err) - - fileName := fmt.Sprintf("%v/%v-encode", tmpDir, chainId) - s.T().Logf("serialized init file for chain-id %v: %v", chainId, fileName) - var initializedChain initialization.Chain - // loop through the reading and unmarshaling of the init file a total of maxRetries or until error is nil - // without this, test attempts to unmarshal file before docker container is finished writing - for i := 0; i < maxRetries; i++ { - encJson, _ := os.ReadFile(fileName) - // err = json.Unmarshal(encJson, &newChainConfig.validators) - err = json.Unmarshal(encJson, &initializedChain) - if err == nil { - break - } - - if i == maxRetries-1 { - s.Require().NoError(err) - } - - if i > 0 { - time.Sleep(1 * time.Second) - } - } - - s.Require().NoError(s.containerManager.PurgeResource(initResource)) - - s.initializeChainConfig(&newChainConfig, &initializedChain) -} - -func (s *IntegrationTestSuite) initializeChainConfig(chainConfig *chainConfig, initializedChain *initialization.Chain) { - chainConfig.meta.DataDir = initializedChain.ChainMeta.DataDir - chainConfig.meta.Id = initializedChain.ChainMeta.Id - - chainConfig.validators = make([]*validatorConfig, 0, len(initializedChain.Nodes)) - for _, val := range initializedChain.Nodes { - chainConfig.validators = append(chainConfig.validators, &validatorConfig{validator: *val}) - } - - s.chainConfigs = append(s.chainConfigs, chainConfig) -} - -func noRestart(config *docker.HostConfig) { - // in this case we don't want the nodes to restart on failure - config.RestartPolicy = docker.RestartPolicy{ - Name: "no", - } -} - -func (s *IntegrationTestSuite) upgrade() { - // submit, deposit, and vote for upgrade proposal - // prop height = current height + voting period + time it takes to submit proposal + small buffer - for _, chainConfig := range s.chainConfigs { - currentHeight := s.getCurrentChainHeight(chainConfig, 0) - chainConfig.propHeight = currentHeight + int(chainConfig.votingPeriod) + int(propSubmitBlocks) + int(propBufferBlocks) - s.submitUpgradeProposal(chainConfig) - s.depositProposal(chainConfig) - s.voteProposal(chainConfig) - } - - // wait till all chains halt at upgrade height - for _, chainConfig := range s.chainConfigs { - for i := range chainConfig.validators { - validatorResource, exists := s.containerManager.GetValidatorResource(chainConfig.meta.Id, i) - require.True(s.T(), exists) - containerId := validatorResource.Container.ID - containerName := validatorResource.Container.Name[1:] - - // use counter to ensure no new blocks are being created - counter := 0 - s.T().Logf("waiting to reach upgrade height on %s validator container: %s", containerName, containerId) - s.Require().Eventually( - func() bool { - currentHeight := s.getCurrentChainHeight(chainConfig, i) - if currentHeight != chainConfig.propHeight { - s.T().Logf("current block height on %s is %v, waiting for block %v container: %s", containerName, currentHeight, chainConfig.propHeight, containerId) - } - if currentHeight > chainConfig.propHeight { - panic("chain did not halt at upgrade height") - } - if currentHeight == chainConfig.propHeight { - counter++ - } - return counter == 3 - }, - 5*time.Minute, - time.Second, - ) - s.T().Logf("reached upgrade height on %s container: %s", containerName, containerId) - } - } - - // remove all containers so we can upgrade them to the new version - for _, chainConfig := range s.chainConfigs { - for _, val := range chainConfig.validators { - containerName := val.validator.Name - err := s.containerManager.RemoveValidatorResource(chainConfig.meta.Id, containerName) - s.Require().NoError(err) - s.T().Logf("removed container: %s", containerName) - } - } - - for _, chainConfig := range s.chainConfigs { - s.upgradeContainers(chainConfig, chainConfig.propHeight) - } -} - -func (s *IntegrationTestSuite) upgradeFork() { - for _, chainConfig := range s.chainConfigs { - for i := range chainConfig.validators { - validatorResource, exists := s.containerManager.GetValidatorResource(chainConfig.meta.Id, i) - require.True(s.T(), exists) - containerId := validatorResource.Container.ID - containerName := validatorResource.Container.Name[1:] - - s.T().Logf("waiting to reach fork height on %s validator container: %s", containerName, containerId) - s.Require().Eventually( - func() bool { - currentHeight := s.getCurrentChainHeight(chainConfig, i) - if currentHeight < s.forkHeight { - s.T().Logf("current block height on %s is %v, waiting for block %v container: %s", containerName, currentHeight, s.forkHeight, containerId) - return false - } - return true - }, - 5*time.Minute, - time.Second, - ) - s.T().Logf("successfully got past fork height on %s container: %s", containerName, containerId) - } - } -} - -func (s *IntegrationTestSuite) upgradeContainers(chainConfig *chainConfig, propHeight int) { - // upgrade containers to the locally compiled daemon - chain := chainConfig - s.T().Logf("starting upgrade for chain-id: %s...", chain.meta.Id) - - s.containerManager.OsmosisRepository = containers.CurrentBranchOsmoRepository - s.containerManager.OsmosisTag = containers.CurrentBranchOsmoTag - - for _, val := range chain.validators { - validatorResource, err := s.containerManager.RunValidatorResource(chainConfig.meta.Id, val.validator.Name, val.validator.ConfigDir) - require.NoError(s.T(), err) - s.T().Logf("started %s validator container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - } - - // check that we are creating blocks again - for i := range chain.validators { - validatorResource, exists := s.containerManager.GetValidatorResource(chainConfig.meta.Id, i) - require.True(s.T(), exists) - - s.Require().Eventually( - func() bool { - currentHeight := s.getCurrentChainHeight(chainConfig, i) - if currentHeight <= propHeight { - s.T().Logf("current block height on %s is %v, waiting to create blocks container: %s", validatorResource.Container.Name[1:], currentHeight, validatorResource.Container.ID) - } - return currentHeight > propHeight - }, - 5*time.Minute, - time.Second, - ) - s.T().Logf("upgrade successful on %s validator container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - } -} - -func (s *IntegrationTestSuite) createPreUpgradeState() { - chainA := s.chainConfigs[0] - chainB := s.chainConfigs[1] - - s.sendIBC(chainA, chainB, chainB.validators[0].validator.PublicAddress, initialization.OsmoToken) - s.sendIBC(chainB, chainA, chainA.validators[0].validator.PublicAddress, initialization.OsmoToken) - s.sendIBC(chainA, chainB, chainB.validators[0].validator.PublicAddress, initialization.StakeToken) - s.sendIBC(chainB, chainA, chainA.validators[0].validator.PublicAddress, initialization.StakeToken) - s.createPool(chainA, "pool1A.json", initialization.ValidatorWalletName) - s.createPool(chainB, "pool1B.json", initialization.ValidatorWalletName) -} - -func (s *IntegrationTestSuite) runPostUpgradeTests() { - if s.skipIBC { - return - } - - chainA := s.chainConfigs[0] - chainB := s.chainConfigs[1] - - s.sendIBC(chainA, chainB, chainB.validators[0].validator.PublicAddress, initialization.OsmoToken) - s.sendIBC(chainB, chainA, chainA.validators[0].validator.PublicAddress, initialization.OsmoToken) - s.sendIBC(chainA, chainB, chainB.validators[0].validator.PublicAddress, initialization.StakeToken) - s.sendIBC(chainB, chainA, chainA.validators[0].validator.PublicAddress, initialization.StakeToken) - s.createPool(chainA, "pool2A.json", initialization.ValidatorWalletName) - s.createPool(chainB, "pool2B.json", initialization.ValidatorWalletName) } diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index 82d5fe1a26e..48e0a0020ac 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -8,16 +8,28 @@ import ( "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" ) +func (s *IntegrationTestSuite) TestCreatePoolPostUpgrade() { + if s.skipUpgrade { + s.T().Skip("pool creation tests are broken when upgrade is skipped. To be fixed in #1843") + } + + chainA := s.configurer.GetChainConfig(0) + chainA.CreatePool("pool2A.json", initialization.ValidatorWalletName) + chainA.CreatePool("pool2B.json", initialization.ValidatorWalletName) +} + func (s *IntegrationTestSuite) TestIBCTokenTransfer() { if s.skipIBC { s.T().Skip("Skipping IBC tests") } - chainA := s.chainConfigs[0] - chainB := s.chainConfigs[1] - // compare coins of receiver pre and post IBC send - // diff should only be the amount sent - s.sendIBC(chainA, chainB, chainB.validators[0].validator.PublicAddress, initialization.OsmoToken) + chainA := s.configurer.GetChainConfig(0) + chainB := s.configurer.GetChainConfig(1) + + chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, initialization.OsmoToken) + chainB.SendIBC(chainA, chainA.NodeConfigs[0].PublicAddress, initialization.OsmoToken) + chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, initialization.StakeToken) + chainB.SendIBC(chainA, chainA.NodeConfigs[0].PublicAddress, initialization.StakeToken) } func (s *IntegrationTestSuite) TestSuperfluidVoting() { @@ -27,32 +39,30 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { } const walletName = "superfluid-wallet" - chainA := s.chainConfigs[0] - s.submitSuperfluidProposal(chainA, "gamm/pool/1") - s.depositProposal(chainA) - s.voteProposal(chainA) - walletAddr := s.createWallet(chainA, 0, walletName) + chainA := s.configurer.GetChainConfig(0) + + chainA.SubmitSuperfluidProposal("gamm/pool/1") + + chainA.DepositProposal() + chainA.VoteYesProposal() + walletAddr := chainA.CreateWallet(0, walletName) // send gamm tokens to validator's other wallet (non self-delegation wallet) - s.sendTx(chainA, 0, "100000000000000000000gamm/pool/1", chainA.validators[0].validator.PublicAddress, walletAddr) + chainA.BankSend(0, "100000000000000000000gamm/pool/1", chainA.NodeConfigs[0].PublicAddress, walletAddr) // lock tokens from validator 0 on chain A - s.lockTokens(chainA, 0, "100000000000000000000gamm/pool/1", "240s", walletName) + chainA.LockTokens(0, "100000000000000000000gamm/pool/1", "240s", walletName) // superfluid delegate from validator 0 non self-delegation wallet to validator 1 on chain A - s.superfluidDelegate(chainA, chainA.validators[1].operatorAddress, walletName) + chainA.SuperfluidDelegate(chainA.NodeConfigs[1].OperatorAddress, walletName) // create a text prop, deposit and vote yes - s.submitTextProposal(chainA, "superfluid vote overwrite test") - s.depositProposal(chainA) - s.voteProposal(chainA) + chainA.SubmitTextProposal("superfluid vote overwrite test") + chainA.DepositProposal() + chainA.VoteYesProposal() // set delegator vote to no - s.voteNoProposal(chainA, 0, walletName) - - hostPort, err := s.containerManager.GetValidatorHostPort(chainA.meta.Id, 0, "1317/tcp") - s.Require().NoError(err) + chainA.VoteNoProposal(0, walletName) - chainAAPIEndpoint := fmt.Sprintf("http://%s", hostPort) - sfProposalNumber := strconv.Itoa(chainA.latestProposalNumber) + sfProposalNumber := strconv.Itoa(chainA.LatestProposalNumber) s.Require().Eventually( func() bool { - noTotal, yesTotal, noWithVetoTotal, abstainTotal, err := s.queryPropTally(chainAAPIEndpoint, sfProposalNumber) + noTotal, yesTotal, noWithVetoTotal, abstainTotal, err := chainA.QueryPropTally(0, sfProposalNumber) if err != nil { return false } @@ -65,13 +75,13 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { time.Second, "Osmosis node failed to retrieve prop tally", ) - noTotal, _, _, _, _ := s.queryPropTally(chainAAPIEndpoint, sfProposalNumber) + noTotal, _, _, _, _ := chainA.QueryPropTally(0, sfProposalNumber) noTotalFinal, err := strconv.Atoi(noTotal.String()) s.Require().NoError(err) s.Require().Eventually( func() bool { - intAccountBalance, err := s.queryIntermediaryAccount(chainA, chainAAPIEndpoint, "gamm/pool/1", chainA.validators[1].operatorAddress) + intAccountBalance, err := chainA.QueryIntermediaryAccount(0, "gamm/pool/1", chainA.NodeConfigs[1].OperatorAddress) s.Require().NoError(err) if err != nil { return false diff --git a/tests/e2e/e2e_util_test.go b/tests/e2e/e2e_util_test.go deleted file mode 100644 index 40b9ca1b52e..00000000000 --- a/tests/e2e/e2e_util_test.go +++ /dev/null @@ -1,304 +0,0 @@ -package e2e - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "regexp" - "strconv" - "strings" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" - - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" -) - -func (s *IntegrationTestSuite) ExecQueryRPC(path string) ([]byte, error) { - var err error - var resp *http.Response - retriesLeft := 5 - for { - resp, err = http.Get(path) - - if resp.StatusCode == http.StatusServiceUnavailable { - retriesLeft-- - if retriesLeft == 0 { - return nil, err - } - time.Sleep(10 * time.Second) - } else { - break - } - } - - if err != nil { - return nil, fmt.Errorf("failed to execute HTTP request: %w", err) - } - - defer resp.Body.Close() - - bz, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - return bz, nil -} - -func (s *IntegrationTestSuite) connectIBCChains(chainA *chainConfig, chainB *chainConfig) { - s.T().Logf("connecting %s and %s chains via IBC", chainA.meta.Id, chainB.meta.Id) - cmd := []string{"hermes", "create", "channel", chainA.meta.Id, chainB.meta.Id, "--port-a=transfer", "--port-b=transfer"} - _, _, err := s.containerManager.ExecCmd(s.T(), "", 0, cmd, "successfully opened init channel") - s.Require().NoError(err) - s.T().Logf("connected %s and %s chains via IBC", chainA.meta.Id, chainB.meta.Id) -} - -func (s *IntegrationTestSuite) sendIBC(srcChain *chainConfig, dstChain *chainConfig, recipient string, token sdk.Coin) { - cmd := []string{"hermes", "tx", "raw", "ft-transfer", dstChain.meta.Id, srcChain.meta.Id, "transfer", "channel-0", token.Amount.String(), fmt.Sprintf("--denom=%s", token.Denom), fmt.Sprintf("--receiver=%s", recipient), "--timeout-height-offset=1000"} - _, _, err := s.containerManager.ExecCmd(s.T(), "", 0, cmd, "Success") - s.Require().NoError(err) - - s.T().Logf("sending %s from %s to %s (%s)", token, srcChain.meta.Id, dstChain.meta.Id, recipient) - balancesBPre, err := s.queryBalances(dstChain, 0, recipient) - s.Require().NoError(err) - - s.Require().Eventually( - func() bool { - balancesBPost, err := s.queryBalances(dstChain, 0, recipient) - s.Require().NoError(err) - ibcCoin := balancesBPost.Sub(balancesBPre) - if ibcCoin.Len() == 1 { - tokenPre := balancesBPre.AmountOfNoDenomValidation(ibcCoin[0].Denom) - tokenPost := balancesBPost.AmountOfNoDenomValidation(ibcCoin[0].Denom) - resPre := initialization.OsmoToken.Amount - resPost := tokenPost.Sub(tokenPre) - return resPost.Uint64() == resPre.Uint64() - } else { - return false - } - }, - 5*time.Minute, - time.Second, - "tx not received on destination chain", - ) - - s.T().Log("successfully sent IBC tokens") -} - -func (s *IntegrationTestSuite) submitUpgradeProposal(c *chainConfig) { - upgradeHeightStr := strconv.Itoa(c.propHeight) - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, 0) - s.Require().True(exists) - s.T().Logf("submitting upgrade proposal on %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", s.upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", s.upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%s", upgradeHeightStr), "--upgrade-info=\"\"", fmt.Sprintf("--chain-id=%s", c.meta.Id), "--from=val", "-b=block", "--yes", "--keyring-backend=test", "--log_format=json"} - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, 0, cmd, "code: 0") - s.Require().NoError(err) - s.T().Log("successfully submitted upgrade proposal") - c.latestProposalNumber = c.latestProposalNumber + 1 -} - -func (s *IntegrationTestSuite) submitSuperfluidProposal(c *chainConfig, asset string) { - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, 0) - s.Require().True(exists) - s.T().Logf("submitting superfluid proposal for asset %s on %s container: %s", asset, validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "set-superfluid-assets-proposal", fmt.Sprintf("--superfluid-assets=%s", asset), fmt.Sprintf("--title=\"%s superfluid asset\"", asset), fmt.Sprintf("--description=\"%s superfluid asset\"", asset), "--from=val", "-b=block", "--yes", "--keyring-backend=test", "--log_format=json", fmt.Sprintf("--chain-id=%s", c.meta.Id)} - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, 0, cmd, "code: 0") - s.Require().NoError(err) - s.T().Log("successfully submitted superfluid proposal") - c.latestProposalNumber = c.latestProposalNumber + 1 -} - -func (s *IntegrationTestSuite) submitTextProposal(c *chainConfig, text string) { - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, 0) - s.Require().True(exists) - s.T().Logf("submitting text proposal on %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "--type=text", fmt.Sprintf("--title=\"%s\"", text), "--description=\"test text proposal\"", "--from=val", "-b=block", "--yes", "--keyring-backend=test", "--log_format=json", fmt.Sprintf("--chain-id=%s", c.meta.Id)} - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, 0, cmd, "code: 0") - s.Require().NoError(err) - s.T().Log("successfully submitted text proposal") - c.latestProposalNumber = c.latestProposalNumber + 1 -} - -func (s *IntegrationTestSuite) depositProposal(c *chainConfig) { - propStr := strconv.Itoa(c.latestProposalNumber) - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, 0) - s.Require().True(exists) - s.T().Logf("depositing to proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "deposit", propStr, "500000000uosmo", "--from=val", fmt.Sprintf("--chain-id=%s", c.meta.Id), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, 0, cmd, "code: 0") - s.Require().NoError(err) - s.T().Log("successfully deposited to proposal") -} - -func (s *IntegrationTestSuite) voteProposal(c *chainConfig) { - propStr := strconv.Itoa(c.latestProposalNumber) - s.T().Logf("voting yes on proposal for chain-id: %s", c.meta.Id) - cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "yes", "--from=val", fmt.Sprintf("--chain-id=%s", c.meta.Id), "-b=block", "--yes", "--keyring-backend=test"} - for i := range c.validators { - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, i, cmd, "code: 0") - s.Require().NoError(err) - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, i) - s.Require().True(exists) - s.T().Logf("successfully voted yes on proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - } -} - -func (s *IntegrationTestSuite) voteNoProposal(c *chainConfig, validatorIndex int, from string) { - propStr := strconv.Itoa(c.latestProposalNumber) - s.T().Logf("voting no on proposal for chain-id: %s", c.meta.Id) - cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "no", fmt.Sprintf("--from=%s", from), fmt.Sprintf("--chain-id=%s", c.meta.Id), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, validatorIndex, cmd, "code: 0") - s.Require().NoError(err) - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, validatorIndex) - s.Require().True(exists) - s.T().Logf("successfully voted no for proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) -} - -func (s *IntegrationTestSuite) chainStatus(c *chainConfig, i int) []byte { - cmd := []string{"osmosisd", "status"} - _, errBuf, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, i, cmd, "") - s.Require().NoError(err) - return errBuf.Bytes() -} - -func (s *IntegrationTestSuite) getCurrentChainHeight(c *chainConfig, i int) int { - var block syncInfo - s.Require().Eventually( - func() bool { - out := s.chainStatus(c, i) - err := json.Unmarshal(out, &block) - if err != nil { - return false - } - return true - }, - 1*time.Minute, - time.Second, - "Osmosis node failed to retrieve height info", - ) - currentHeight, err := strconv.Atoi(block.SyncInfo.LatestHeight) - s.Require().NoError(err) - return currentHeight -} - -func (s *IntegrationTestSuite) queryBalances(c *chainConfig, i int, addr string) (sdk.Coins, error) { - cmd := []string{"osmosisd", "query", "bank", "balances", addr, "--output=json"} - outBuf, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, i, cmd, "") - s.Require().NoError(err) - - var balancesResp banktypes.QueryAllBalancesResponse - err = util.Cdc.UnmarshalJSON(outBuf.Bytes(), &balancesResp) - s.Require().NoError(err) - - return balancesResp.GetBalances(), nil -} - -func (s *IntegrationTestSuite) queryPropTally(endpoint, addr string) (sdk.Int, sdk.Int, sdk.Int, sdk.Int, error) { - path := fmt.Sprintf( - "%s/cosmos/gov/v1beta1/proposals/%s/tally", - endpoint, addr, - ) - bz, err := s.ExecQueryRPC(path) - s.Require().NoError(err) - - var balancesResp govtypes.QueryTallyResultResponse - if err := util.Cdc.UnmarshalJSON(bz, &balancesResp); err != nil { - return sdk.ZeroInt(), sdk.ZeroInt(), sdk.ZeroInt(), sdk.ZeroInt(), err - } - noTotal := balancesResp.Tally.No - yesTotal := balancesResp.Tally.Yes - noWithVetoTotal := balancesResp.Tally.NoWithVeto - abstainTotal := balancesResp.Tally.Abstain - - return noTotal, yesTotal, noWithVetoTotal, abstainTotal, nil -} - -func (s *IntegrationTestSuite) createPool(c *chainConfig, poolFile string, from string) { - s.T().Logf("creating pool for chain-id: %s", c.meta.Id) - cmd := []string{"osmosisd", "tx", "gamm", "create-pool", fmt.Sprintf("--pool-file=/osmosis/%s", poolFile), fmt.Sprintf("--chain-id=%s", c.meta.Id), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, 0, cmd, "code: 0") - s.Require().NoError(err) - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, 0) - s.Require().True(exists) - s.T().Logf("successfully created pool from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) -} - -func (s *IntegrationTestSuite) lockTokens(c *chainConfig, validatorIndex int, tokens string, duration string, from string) { - s.T().Logf("locking %s for %s on chain-id: %s", tokens, duration, c.meta.Id) - cmd := []string{"osmosisd", "tx", "lockup", "lock-tokens", tokens, fmt.Sprintf("--chain-id=%s", c.meta.Id), fmt.Sprintf("--duration=%s", duration), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, validatorIndex, cmd, "code: 0") - s.Require().NoError(err) - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, validatorIndex) - s.Require().True(exists) - s.T().Logf("successfully created lock %v from %s container: %s", c.latestLockNumber, validatorResource.Container.Name[1:], validatorResource.Container.ID) - c.latestLockNumber = c.latestLockNumber + 1 -} - -func (s *IntegrationTestSuite) superfluidDelegate(c *chainConfig, valAddress string, from string) { - lockStr := strconv.Itoa(c.latestLockNumber) - s.T().Logf("superfluid delegating lock %s to %s on chain-id: %s", lockStr, valAddress, c.meta.Id) - cmd := []string{"osmosisd", "tx", "superfluid", "delegate", lockStr, valAddress, fmt.Sprintf("--chain-id=%s", c.meta.Id), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, 0, cmd, "code: 0") - s.Require().NoError(err) - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, 0) - s.Require().True(exists) - s.T().Logf("successfully superfluid delegated from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) -} - -func (s *IntegrationTestSuite) sendTx(c *chainConfig, validatorIndex int, amount string, sendAddress string, receiveAddress string) { - s.T().Logf("sending %s from %s to %s on chain-id: %s", amount, sendAddress, receiveAddress, c.meta.Id) - cmd := []string{"osmosisd", "tx", "bank", "send", sendAddress, receiveAddress, amount, fmt.Sprintf("--chain-id=%s", c.meta.Id), "--from=val", "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, validatorIndex, cmd, "code: 0") - s.Require().NoError(err) - validatorResource, exists := s.containerManager.GetValidatorResource(c.meta.Id, validatorIndex) - s.Require().True(exists) - s.T().Logf("successfully sent tx from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) -} - -func (s *IntegrationTestSuite) extractValidatorOperatorAddresses(config *chainConfig) { - for i, val := range config.validators { - cmd := []string{"osmosisd", "debug", "addr", val.validator.PublicKey} - s.T().Logf("extracting validator operator addresses for chain-id: %s", config.meta.Id) - _, errBuf, err := s.containerManager.ExecCmd(s.T(), config.meta.Id, i, cmd, "") - s.Require().NoError(err) - re := regexp.MustCompile("osmovaloper(.{39})") - operAddr := fmt.Sprintf("%s\n", re.FindString(errBuf.String())) - config.validators[i].operatorAddress = strings.TrimSuffix(operAddr, "\n") - } -} - -func (s *IntegrationTestSuite) queryIntermediaryAccount(c *chainConfig, endpoint string, denom string, valAddr string) (int, error) { - intAccount := superfluidtypes.GetSuperfluidIntermediaryAccountAddr(denom, valAddr) - path := fmt.Sprintf( - "%s/cosmos/staking/v1beta1/validators/%s/delegations/%s", - endpoint, valAddr, intAccount, - ) - bz, err := s.ExecQueryRPC(path) - s.Require().NoError(err) - - var stakingResp stakingtypes.QueryDelegationResponse - err = util.Cdc.UnmarshalJSON(bz, &stakingResp) - s.Require().NoError(err) - - intAccBalance := stakingResp.DelegationResponse.Balance.Amount.String() - intAccountBalance, err := strconv.Atoi(intAccBalance) - s.Require().NoError(err) - return intAccountBalance, err -} - -func (s *IntegrationTestSuite) createWallet(c *chainConfig, index int, walletName string) string { - cmd := []string{"osmosisd", "keys", "add", walletName, "--keyring-backend=test"} - outBuf, _, err := s.containerManager.ExecCmd(s.T(), c.meta.Id, index, cmd, "") - s.Require().NoError(err) - re := regexp.MustCompile("osmo1(.{38})") - walletAddr := fmt.Sprintf("%s\n", re.FindString(outBuf.String())) - walletAddr = strings.TrimSuffix(walletAddr, "\n") - return walletAddr -} diff --git a/tests/e2e/initialization/README.md b/tests/e2e/initialization/README.md index bd315658bf5..0e2c5b0274d 100644 --- a/tests/e2e/initialization/README.md +++ b/tests/e2e/initialization/README.md @@ -63,7 +63,7 @@ Additionally, it takes the following arguments: - The configurable voting period duration for the chain ```go - tmpDir, _ := ioutil.TempDir("", "osmosis-e2e-testnet-") + tmpDir, _ := os.MkdirTemp("", "osmosis-e2e-testnet-") initResource, _ = s.dkrPool.RunWithOptions( &dockertest.RunOptions{ diff --git a/tests/e2e/initialization/init_test.go b/tests/e2e/initialization/init_test.go index fff036b42c4..aaa67283a55 100644 --- a/tests/e2e/initialization/init_test.go +++ b/tests/e2e/initialization/init_test.go @@ -2,7 +2,6 @@ package initialization_test import ( "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -48,7 +47,7 @@ func TestChainInit(t *testing.T) { IsValidator: false, }, } - dataDir, err = ioutil.TempDir("", "osmosis-e2e-testnet-test") + dataDir, err = os.MkdirTemp("", "osmosis-e2e-testnet-test") ) chain, err := initialization.InitChain(id, dataDir, nodeConfigs, time.Second*3, forkHeight) @@ -105,7 +104,7 @@ func TestSingleNodeInit(t *testing.T) { SnapshotKeepRecent: 1, IsValidator: false, } - dataDir, err = ioutil.TempDir("", "osmosis-e2e-testnet-test") + dataDir, err = os.MkdirTemp("", "osmosis-e2e-testnet-test") ) // Setup From 00e17c6dd78a41a0b4fc2a8324d0cf2518bd4f45 Mon Sep 17 00:00:00 2001 From: Sishir Giri Date: Fri, 8 Jul 2022 19:52:43 -0700 Subject: [PATCH 046/376] x/mint: make all fixtures in keeper package use KeeperTestSuite (#2001) * only one test suite in mint module * Romans comments * roman comments v2 * romansv3 comments --- x/mint/keeper/grpc_query_test.go | 17 ++------ x/mint/keeper/hooks_test.go | 70 ++++++++++++++++---------------- x/mint/keeper/keeper_test.go | 3 ++ 3 files changed, 41 insertions(+), 49 deletions(-) diff --git a/x/mint/keeper/grpc_query_test.go b/x/mint/keeper/grpc_query_test.go index 90ad7ed5de1..9f0d8d080ca 100644 --- a/x/mint/keeper/grpc_query_test.go +++ b/x/mint/keeper/grpc_query_test.go @@ -6,21 +6,14 @@ import ( "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" "github.com/osmosis-labs/osmosis/v7/x/mint/types" ) -type MintTestSuite struct { - apptesting.KeeperTestHelper - queryClient types.QueryClient +func TestMintGRPCQueryTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) } -func (suite *MintTestSuite) SetupTest() { - suite.Setup() - suite.queryClient = types.NewQueryClient(suite.QueryHelper) -} - -func (suite *MintTestSuite) TestGRPCParams() { +func (suite *KeeperTestSuite) TestGRPCParams() { _, _, queryClient := suite.App, suite.Ctx, suite.queryClient _, err := queryClient.Params(gocontext.Background(), &types.QueryParamsRequest{}) @@ -29,7 +22,3 @@ func (suite *MintTestSuite) TestGRPCParams() { _, err = queryClient.EpochProvisions(gocontext.Background(), &types.QueryEpochProvisionsRequest{}) suite.Require().NoError(err) } - -func TestMintTestSuite(t *testing.T) { - suite.Run(t, new(MintTestSuite)) -} diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index f6fa8e6f877..800e579b9b7 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -16,14 +16,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func TestEndOfEpochMintedCoinDistribution(t *testing.T) { +func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { app := osmoapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - setupGaugeForLPIncentives(t, app, ctx) + setupGaugeForLPIncentives(suite.T(), app, ctx) params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) @@ -62,24 +62,24 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { // ensure post-epoch supply with offset changed by less than the minted coins amount (because of developer vesting account) postsupply := app.BankKeeper.GetSupply(ctx, mintParams.MintDenom) postsupplyWithOffset := app.BankKeeper.GetSupplyWithOffset(ctx, mintParams.MintDenom) - require.False(t, postsupply.IsEqual(presupply.Add(mintedCoin))) - require.True(t, postsupplyWithOffset.IsEqual(presupplyWithOffset.Add(mintedCoin))) + suite.False(postsupply.IsEqual(presupply.Add(mintedCoin))) + suite.True(postsupplyWithOffset.IsEqual(presupplyWithOffset.Add(mintedCoin))) // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) - require.Equal(t, feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) + suite.Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) expectedDevRewards := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - require.Equal(t, devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) + suite.Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) } app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) lastReductionPeriod = app.MintKeeper.GetLastReductionEpochNum(ctx) - require.Equal(t, lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) + suite.Equal(lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) @@ -96,23 +96,23 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) - require.Equal(t, feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) + suite.Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) // test that the balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) expectedDevRewards := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - require.Equal(t, devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) + suite.Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) } } -func TestMintedCoinDistributionWhenDevRewardsAddressEmpty(t *testing.T) { +func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmpty() { app := osmoapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - setupGaugeForLPIncentives(t, app, ctx) + setupGaugeForLPIncentives(suite.T(), app, ctx) params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) @@ -134,19 +134,19 @@ func TestMintedCoinDistributionWhenDevRewardsAddressEmpty(t *testing.T) { // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) - require.Equal(t, feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) + suite.Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) expectedDevRewards := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - require.Equal(t, devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) + suite.Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) } app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) lastReductionPeriod = app.MintKeeper.GetLastReductionEpochNum(ctx) - require.Equal(t, lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) + suite.Equal(lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) @@ -163,16 +163,16 @@ func TestMintedCoinDistributionWhenDevRewardsAddressEmpty(t *testing.T) { // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) - require.Equal(t, feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, expectedRewards.String()) + suite.Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, expectedRewards.String()) // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) expectedDevRewards := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - require.Equal(t, devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) + suite.Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) } } -func TestEndOfEpochNoDistributionWhenIsNotYetStartTime(t *testing.T) { +func (suite *KeeperTestSuite) TestEndOfEpochNoDistributionWhenIsNotYetStartTime() { app := osmoapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) @@ -183,7 +183,7 @@ func TestEndOfEpochNoDistributionWhenIsNotYetStartTime(t *testing.T) { header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - setupGaugeForLPIncentives(t, app, ctx) + setupGaugeForLPIncentives(suite.T(), app, ctx) params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) @@ -198,18 +198,18 @@ func TestEndOfEpochNoDistributionWhenIsNotYetStartTime(t *testing.T) { // check community pool balance not increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) - require.Equal(t, feePoolOrigin.CommunityPool, feePoolNew.CommunityPool, "height = %v", height) + suite.Equal(feePoolOrigin.CommunityPool, feePoolNew.CommunityPool, "height = %v", height) } // Run through epochs mintParams.MintingRewardsDistributionStartEpoch // ensure tokens distributed app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - require.NotEqual(t, sdk.DecCoins{}, app.DistrKeeper.GetFeePool(ctx).CommunityPool, + suite.Require().NotEqual(sdk.DecCoins{}, app.DistrKeeper.GetFeePool(ctx).CommunityPool, "Tokens to community pool at start distribution epoch") // reduction period should be set to mintParams.MintingRewardsDistributionStartEpoch lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) - require.Equal(t, lastReductionPeriod, mintParams.MintingRewardsDistributionStartEpoch) + suite.Equal(lastReductionPeriod, mintParams.MintingRewardsDistributionStartEpoch) } // TODO: Remove after rounding errors are addressed and resolved. @@ -217,7 +217,7 @@ func TestEndOfEpochNoDistributionWhenIsNotYetStartTime(t *testing.T) { // supply for correctness. // // Ref: https://github.com/osmosis-labs/osmosis/issues/1917 -func TestAfterEpochEnd_FirstYearThirdening_RealParameters(t *testing.T) { +func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParameters() { // Most values in this test are taken from mainnet genesis to mimic real-world behavior: // https://github.com/osmosis-labs/networks/raw/main/osmosis-1/genesis.json const ( @@ -242,7 +242,7 @@ func TestAfterEpochEnd_FirstYearThirdening_RealParameters(t *testing.T) { ctx := app.BaseApp.NewContext(false, tmproto.Header{}) genesisEpochProvisionsDec, err := sdk.NewDecFromStr(genesisEpochProvisions) - require.NoError(t, err) + suite.Require().NoError(err) mintParams := types.Params{ MintDenom: mintDenom, @@ -326,7 +326,7 @@ func TestAfterEpochEnd_FirstYearThirdening_RealParameters(t *testing.T) { for _, w := range mintParams.WeightedDeveloperRewardsReceivers { sumOfWeights = sumOfWeights.Add(w.Weight) } - require.Equal(t, sdk.OneDec(), sumOfWeights) + suite.Equal(sdk.OneDec(), sumOfWeights) // Test setup parameters are not identical with mainnet. // Therfore, we set them here to the desired mainnet values. @@ -340,10 +340,10 @@ func TestAfterEpochEnd_FirstYearThirdening_RealParameters(t *testing.T) { expectedSupply := sdk.NewDec(developerAccountBalance) supplyWithOffset := app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom) - require.Equal(t, expectedSupplyWithOffset.TruncateInt64(), supplyWithOffset.Amount.Int64()) + suite.Equal(expectedSupplyWithOffset.TruncateInt64(), supplyWithOffset.Amount.Int64()) supply := app.BankKeeper.GetSupply(ctx, mintDenom) - require.Equal(t, expectedSupply.TruncateInt64(), supply.Amount.Int64()) + suite.Equal(expectedSupply.TruncateInt64(), supply.Amount.Int64()) devRewardsDelta := sdk.ZeroDec() epochProvisionsDelta := genesisEpochProvisionsDec.Sub(genesisEpochProvisionsDec.TruncateInt().ToDec()).Mul(sdk.NewDec(reductionPeriodInEpochs)) @@ -381,20 +381,20 @@ func TestAfterEpochEnd_FirstYearThirdening_RealParameters(t *testing.T) { actualDeveloperAccountBalanceAfterHook := developerAccountBalance.Amount.ToDec() // This is supposed to be equal but is failing due to the rounding errors from devRewards. - require.NotEqual(t, expectedDeveloperAccountBalanceAfterHook, actualDeveloperAccountBalanceAfterHook) + suite.Require().NotEqual(expectedDeveloperAccountBalanceAfterHook, actualDeveloperAccountBalanceAfterHook) devRewardsDelta = devRewardsDelta.Add(actualDeveloperAccountBalanceAfterHook.Sub(expectedDeveloperAccountBalanceAfterHook)) } expectedSupply = expectedSupply.Add(truncatedEpochProvisions).Sub(devRewards) - require.Equal(t, expectedSupply.RoundInt(), app.BankKeeper.GetSupply(ctx, mintDenom).Amount) + suite.Equal(expectedSupply.RoundInt(), app.BankKeeper.GetSupply(ctx, mintDenom).Amount) expectedSupplyWithOffset = expectedSupply.Sub(developerAccountBalance.Amount.ToDec()) - require.Equal(t, expectedSupplyWithOffset.RoundInt(), app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount) + suite.Equal(expectedSupplyWithOffset.RoundInt(), app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount) // Validate that the epoch provisions have not been reduced. - require.Equal(t, mintingRewardsDistributionStartEpoch, app.MintKeeper.GetLastReductionEpochNum(ctx)) - require.Equal(t, genesisEpochProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions.String()) + suite.Equal(mintingRewardsDistributionStartEpoch, app.MintKeeper.GetLastReductionEpochNum(ctx)) + suite.Equal(genesisEpochProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions.String()) } // Validate total supply. @@ -410,18 +410,18 @@ func TestAfterEpochEnd_FirstYearThirdening_RealParameters(t *testing.T) { actualTotalProvisionedSupply := app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount.ToDec() // 299_999_999_999_999.999999999999999705 == 299_999_999_997_380 + 2555 + 64.999999999999999705 - require.Equal(t, expectedTotalProvisionedSupply, actualTotalProvisionedSupply.Add(devRewardsDelta).Add(epochProvisionsDelta)) + suite.Equal(expectedTotalProvisionedSupply, actualTotalProvisionedSupply.Add(devRewardsDelta).Add(epochProvisionsDelta)) // This end of epoch should trigger thirdening. It will utilize the updated // (reduced) provisions. app.MintKeeper.AfterEpochEnd(ctx, epochIdentifier, thirdeningEpochNum) - require.Equal(t, thirdeningEpochNum, app.MintKeeper.GetLastReductionEpochNum(ctx)) + suite.Equal(thirdeningEpochNum, app.MintKeeper.GetLastReductionEpochNum(ctx)) expectedThirdenedProvisions := mintParams.ReductionFactor.Mul(genesisEpochProvisionsDec) // Sanity check with the actual value on mainnet. - require.Equal(t, mainnetThirdenedProvisions, expectedThirdenedProvisions.String()) - require.Equal(t, expectedThirdenedProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions) + suite.Equal(mainnetThirdenedProvisions, expectedThirdenedProvisions.String()) + suite.Equal(expectedThirdenedProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions) } func setupGaugeForLPIncentives(t *testing.T, app *osmoapp.OsmosisApp, ctx sdk.Context) { diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 9bc63372497..91740653599 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -22,10 +22,13 @@ import ( type KeeperTestSuite struct { apptesting.KeeperTestHelper + queryClient types.QueryClient } func (suite *KeeperTestSuite) SetupTest() { suite.Setup() + + suite.queryClient = types.NewQueryClient(suite.QueryHelper) } // setupDeveloperVestingModuleAccountTest sets up test cases that utilize developer vesting From 079bdd496aefea6ad386263b349f2b60f0358738 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Sat, 9 Jul 2022 19:02:03 -0500 Subject: [PATCH 047/376] x/incentives: cli updates (#1985) * incentives cli updates * linter fix * Update x/incentives/client/cli/query.go Co-authored-by: Roman * Update x/incentives/client/cli/query.go Co-authored-by: Roman * make Roman suggestions * make review suggestions * revert suggestion * address roman comment error verbiage * linter * address review comments * get est rewards fix * fix comment Co-authored-by: Roman --- x/incentives/client/cli/cli_test.go | 171 +++++++++++++++++++--------- x/incentives/client/cli/flags.go | 5 +- x/incentives/client/cli/query.go | 96 ++++++++++++---- x/incentives/client/cli/tx.go | 4 +- x/incentives/keeper/distribute.go | 12 +- x/incentives/keeper/gauge.go | 6 +- x/incentives/keeper/grpc_query.go | 14 ++- 7 files changed, 214 insertions(+), 94 deletions(-) diff --git a/x/incentives/client/cli/cli_test.go b/x/incentives/client/cli/cli_test.go index 4ee07b0a737..fce100e1225 100644 --- a/x/incentives/client/cli/cli_test.go +++ b/x/incentives/client/cli/cli_test.go @@ -2,13 +2,22 @@ package cli_test import ( "fmt" + "testing" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" + tmcli "github.com/tendermint/tendermint/libs/cli" + + gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/osmosis-labs/osmosis/v7/app" + gammtestutil "github.com/osmosis-labs/osmosis/v7/x/gamm/client/testutil" "github.com/osmosis-labs/osmosis/v7/x/incentives/client/cli" "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + lockuptestutil "github.com/osmosis-labs/osmosis/v7/x/lockup/client/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" @@ -26,10 +35,50 @@ func (s *IntegrationTestSuite) SetupSuite() { s.cfg = app.DefaultConfig() + // modification to pay pool creation fee with test bond denom "stake" + // marshal result into genesis json + genesisState := app.ModuleBasics.DefaultGenesis(s.cfg.Codec) + gammGen := gammtypes.DefaultGenesis() + gammGen.Params.PoolCreationFee = sdk.Coins{sdk.NewInt64Coin(s.cfg.BondDenom, 1000000)} + gammGenJson := s.cfg.Codec.MustMarshalJSON(gammGen) + genesisState[gammtypes.ModuleName] = gammGenJson + s.cfg.GenesisState = genesisState + + // create a network with a validator s.network = network.New(s.T(), s.cfg) + val := s.network.Validators[0] + + // create a pool to receive gamm tokens + _, err := gammtestutil.MsgCreatePool(s.T(), val.ClientCtx, val.Address, "5stake,5node0token", "100stake,100node0token", "0.01", "0.01", "") + s.Require().NoError(err) + + _, err = s.network.WaitForHeight(1) + s.Require().NoError(err) + + lockAmt, err := sdk.ParseCoinNormalized(fmt.Sprint("100000gamm/pool/1")) + s.Require().NoError(err) + + _, err = s.network.WaitForHeight(1) + s.Require().NoError(err) + + // lock gamm pool tokens to create lock ID 1 + lockuptestutil.MsgLockTokens(val.ClientCtx, val.Address, lockAmt, "24h") + + _, err = s.network.WaitForHeight(1) + s.Require().NoError(err) + + secondLockAmt, err := sdk.ParseCoinNormalized(fmt.Sprint("100000gamm/pool/1")) + s.Require().NoError(err) - _, err := s.network.WaitForHeight(1) + _, err = s.network.WaitForHeight(1) s.Require().NoError(err) + + // lock gamm pool tokens to create lock ID 2 + lockuptestutil.MsgLockTokens(val.ClientCtx, val.Address, secondLockAmt, "168h") + + _, err = s.network.WaitForHeight(1) + s.Require().NoError(err) + } func (s *IntegrationTestSuite) TearDownSuite() { @@ -43,11 +92,14 @@ func (s *IntegrationTestSuite) TestGetCmdGauges() { testCases := []struct { name string expectErr bool + args []string respType proto.Message }{ { "query gauges", - false, &types.GaugesResponse{}, + false, + []string{fmt.Sprintf("--%s=json", tmcli.OutputFlag)}, + &types.GaugesResponse{}, }, } @@ -58,9 +110,7 @@ func (s *IntegrationTestSuite) TestGetCmdGauges() { cmd := cli.GetCmdGauges() clientCtx := val.ClientCtx - args := []string{} - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { @@ -76,12 +126,15 @@ func (s *IntegrationTestSuite) TestGetCmdToDistributeCoins() { testCases := []struct { name string + args []string expectErr bool respType proto.Message }{ { "query to distribute coins", - false, &types.ModuleToDistributeCoinsResponse{}, + []string{fmt.Sprintf("--%s=json", tmcli.OutputFlag)}, + false, + &types.ModuleToDistributeCoinsResponse{}, }, } @@ -92,9 +145,7 @@ func (s *IntegrationTestSuite) TestGetCmdToDistributeCoins() { cmd := cli.GetCmdToDistributeCoins() clientCtx := val.ClientCtx - args := []string{} - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { @@ -110,12 +161,15 @@ func (s *IntegrationTestSuite) TestGetCmdDistributedCoins() { testCases := []struct { name string + args []string expectErr bool respType proto.Message }{ { "query to distribute coins", - false, &types.ModuleDistributedCoinsResponse{}, + []string{fmt.Sprintf("--%s=json", tmcli.OutputFlag)}, + false, + &types.ModuleDistributedCoinsResponse{}, }, } @@ -126,9 +180,7 @@ func (s *IntegrationTestSuite) TestGetCmdDistributedCoins() { cmd := cli.GetCmdDistributedCoins() clientCtx := val.ClientCtx - args := []string{} - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { @@ -144,12 +196,15 @@ func (s *IntegrationTestSuite) TestGetCmdGaugeByID() { testCases := []struct { name string + args []string expectErr bool respType proto.Message }{ { "query gauge by id", - false, &types.GaugeByIDResponse{}, + []string{"1", fmt.Sprintf("--%s=json", tmcli.OutputFlag)}, + false, + &types.GaugeByIDResponse{}, }, } @@ -160,9 +215,7 @@ func (s *IntegrationTestSuite) TestGetCmdGaugeByID() { cmd := cli.GetCmdGaugeByID() clientCtx := val.ClientCtx - args := []string{"1"} - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { @@ -178,12 +231,15 @@ func (s *IntegrationTestSuite) TestGetCmdActiveGauges() { testCases := []struct { name string + args []string expectErr bool respType proto.Message }{ { "query active gauges", - false, &types.ActiveGaugesResponse{}, + []string{fmt.Sprintf("--%s=json", tmcli.OutputFlag)}, + false, + &types.ActiveGaugesResponse{}, }, } @@ -194,9 +250,7 @@ func (s *IntegrationTestSuite) TestGetCmdActiveGauges() { cmd := cli.GetCmdActiveGauges() clientCtx := val.ClientCtx - args := []string{} - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { @@ -212,12 +266,15 @@ func (s *IntegrationTestSuite) TestGetCmdActiveGaugesPerDenom() { testCases := []struct { name string + args []string expectErr bool respType proto.Message }{ { "query active gauges per denom", - false, &types.ActiveGaugesPerDenomResponse{}, + []string{s.cfg.BondDenom, fmt.Sprintf("--%s=json", tmcli.OutputFlag)}, + false, + &types.ActiveGaugesPerDenomResponse{}, }, } @@ -228,9 +285,7 @@ func (s *IntegrationTestSuite) TestGetCmdActiveGaugesPerDenom() { cmd := cli.GetCmdActiveGaugesPerDenom() clientCtx := val.ClientCtx - args := []string{s.cfg.BondDenom} - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { @@ -246,12 +301,15 @@ func (s *IntegrationTestSuite) TestGetCmdUpcomingGauges() { testCases := []struct { name string + args []string expectErr bool respType proto.Message }{ { "query upcoming gauges", - false, &types.UpcomingGaugesResponse{}, + []string{fmt.Sprintf("--%s=json", tmcli.OutputFlag)}, + false, + &types.UpcomingGaugesResponse{}, }, } @@ -262,9 +320,7 @@ func (s *IntegrationTestSuite) TestGetCmdUpcomingGauges() { cmd := cli.GetCmdUpcomingGauges() clientCtx := val.ClientCtx - args := []string{} - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { @@ -280,12 +336,15 @@ func (s *IntegrationTestSuite) TestGetCmdUpcomingGaugesPerDenom() { testCases := []struct { name string + args []string expectErr bool respType proto.Message }{ { "query upcoming gauges per denom", - false, &types.UpcomingGaugesPerDenomResponse{}, + []string{s.cfg.BondDenom, fmt.Sprintf("--%s=json", tmcli.OutputFlag)}, + false, + &types.UpcomingGaugesPerDenomResponse{}, }, } @@ -296,9 +355,7 @@ func (s *IntegrationTestSuite) TestGetCmdUpcomingGaugesPerDenom() { cmd := cli.GetCmdUpcomingGaugesPerDenom() clientCtx := val.ClientCtx - args := []string{s.cfg.BondDenom} - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { @@ -314,32 +371,38 @@ func (s *IntegrationTestSuite) TestGetCmdRewardsEst() { testCases := []struct { name string - owner string - lockIds string - endEpoch int64 + args []string expectErr bool respType proto.Message }{ { "query rewards estimation by owner", - val.Address.String(), - "", - 100, - false, &types.RewardsEstResponse{}, + []string{ + fmt.Sprintf("--%s=%s", cli.FlagOwner, val.Address.String()), + fmt.Sprintf("--%s=100", cli.FlagEndEpoch), + fmt.Sprintf("--%s=json", tmcli.OutputFlag), + }, + false, + &types.RewardsEstResponse{}, }, { "query rewards estimation by lock id", - "", - "1,2", - 100, - false, &types.RewardsEstResponse{}, + []string{ + fmt.Sprintf("--%s=1,2", cli.FlagLockIds), + fmt.Sprintf("--%s=100", cli.FlagEndEpoch), + fmt.Sprintf("--%s=json", tmcli.OutputFlag), + }, + false, + &types.RewardsEstResponse{}, }, { "query rewards estimation with empty end epoch", - "", - "1,2", - 0, - false, &types.RewardsEstResponse{}, + []string{ + fmt.Sprintf("--%s=1,2", cli.FlagLockIds), + fmt.Sprintf("--%s=json", tmcli.OutputFlag), + }, + false, + &types.RewardsEstResponse{}, }, } @@ -350,13 +413,7 @@ func (s *IntegrationTestSuite) TestGetCmdRewardsEst() { cmd := cli.GetCmdRewardsEst() clientCtx := val.ClientCtx - args := []string{ - fmt.Sprintf("--%s=%s", cli.FlagOwner, tc.owner), - fmt.Sprintf("--%s=%s", cli.FlagLockIds, tc.lockIds), - fmt.Sprintf("--%s=%d", cli.FlagEndEpoch, tc.endEpoch), - } - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { @@ -366,3 +423,7 @@ func (s *IntegrationTestSuite) TestGetCmdRewardsEst() { }) } } + +func TestIntegrationTestSuite(t *testing.T) { + suite.Run(t, new(IntegrationTestSuite)) +} diff --git a/x/incentives/client/cli/flags.go b/x/incentives/client/cli/flags.go index 11801813f28..4f8ad1585e1 100644 --- a/x/incentives/client/cli/flags.go +++ b/x/incentives/client/cli/flags.go @@ -6,20 +6,19 @@ import ( flag "github.com/spf13/pflag" ) -// flags for lockup module tx commands. +// Flags for incentives module tx commands. const ( FlagDuration = "duration" FlagStartTime = "start-time" FlagEpochs = "epochs" FlagPerpetual = "perpetual" - FlagTimestamp = "timestamp" FlagOwner = "owner" FlagLockIds = "lock-ids" FlagEndEpoch = "end-epoch" ) -// FlagSetCreateGauge returns flags for creating gauge. +// FlagSetCreateGauge returns flags for creating gauges. func FlagSetCreateGauge() *flag.FlagSet { fs := flag.NewFlagSet("", flag.ContinueOnError) diff --git a/x/incentives/client/cli/query.go b/x/incentives/client/cli/query.go index 4257668dbab..27a0afa89c8 100644 --- a/x/incentives/client/cli/query.go +++ b/x/incentives/client/cli/query.go @@ -4,19 +4,21 @@ import ( "fmt" "strconv" "strings" + "time" "github.com/spf13/cobra" "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/version" ) -// GetQueryCmd returns the cli query commands for this module. +// GetQueryCmd returns the query commands for this module. func GetQueryCmd() *cobra.Command { - // Group incentives queries under a subcommand + // group incentives queries under a subcommand cmd := &cobra.Command{ Use: types.ModuleName, Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), @@ -40,7 +42,7 @@ func GetQueryCmd() *cobra.Command { return cmd } -// GetCmdGauges returns full available gauges. +// GetCmdGauges returns all available gauges. func GetCmdGauges() *cobra.Command { cmd := &cobra.Command{ Use: "gauges", @@ -84,7 +86,7 @@ $ %s query incentives gauges return cmd } -// GetCmdToDistributeCoins returns coins that is going to be distributed. +// GetCmdToDistributeCoins returns coins that are going to be distributed. func GetCmdToDistributeCoins() *cobra.Command { cmd := &cobra.Command{ Use: "to-distribute-coins", @@ -120,7 +122,7 @@ $ %s query incentives to-distribute-coins return cmd } -// GetCmdDistributedCoins returns coins that are distributed so far. +// GetCmdDistributedCoins returns coins that have been distributed so far. func GetCmdDistributedCoins() *cobra.Command { cmd := &cobra.Command{ Use: "distributed-coins", @@ -156,7 +158,7 @@ $ %s query incentives distributed-coins return cmd } -// GetCmdGaugeByID returns Gauge by id. +// GetCmdGaugeByID returns a gauge by ID. func GetCmdGaugeByID() *cobra.Command { cmd := &cobra.Command{ Use: "gauge-by-id [id]", @@ -238,7 +240,7 @@ $ %s query incentives active-gauges return cmd } -// GetCmdActiveGaugesPerDenom returns active gauges for specified denom. +// GetCmdActiveGaugesPerDenom returns active gauges for a specified denom. func GetCmdActiveGaugesPerDenom() *cobra.Command { cmd := &cobra.Command{ Use: "active-gauges-per-denom [denom]", @@ -320,7 +322,7 @@ $ %s query incentives upcoming-gauges return cmd } -// GetCmdActiveGaugesPerDenom returns active gauges for specified denom. +// GetCmdUpcomingGaugesPerDenom returns active gauges for specified denom. func GetCmdUpcomingGaugesPerDenom() *cobra.Command { cmd := &cobra.Command{ Use: "upcoming-gauges-per-denom [denom]", @@ -361,45 +363,83 @@ func GetCmdRewardsEst() *cobra.Command { fmt.Sprintf(`Query rewards estimation. Example: -$ %s query incentives rewards-estimation +$ %s query incentives rewards-estimation `, version.AppName, ), ), Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) + var res *lockuptypes.AccountLockedLongerDurationResponse + ownerLocks := []uint64{} + lockIds := []uint64{} + + owner, err := cmd.Flags().GetString(FlagOwner) if err != nil { return err } - queryClient := types.NewQueryClient(clientCtx) - owner, err := cmd.Flags().GetString(FlagOwner) + lockIdsCombined, err := cmd.Flags().GetString(FlagLockIds) if err != nil { return err } + lockIdStrs := strings.Split(lockIdsCombined, ",") - lockIdsCombined, err := cmd.Flags().GetString(FlagLockIds) + endEpoch, err := cmd.Flags().GetInt64(FlagEndEpoch) if err != nil { return err } - lockIdStrs := strings.Split(lockIdsCombined, ",") - lockIds := []uint64{} - for _, lockIdStr := range lockIdStrs { - lockId, err := strconv.ParseUint(lockIdStr, 10, 64) - if err != nil { - return err + // if user doesn't provide at least one of the lock ids or owner, we don't have enough information to proceed. + if lockIdsCombined == "" && owner == "" { + return fmt.Errorf("either one of owner flag or lock IDs must be provided") + + // if user provides lockIDs, use these lockIDs in our rewards estimation + } else if owner == "" { + for _, lockIdStr := range lockIdStrs { + lockId, err := strconv.ParseUint(lockIdStr, 10, 64) + if err != nil { + return err + } + lockIds = append(lockIds, lockId) } - lockIds = append(lockIds, lockId) + + // if no lockIDs are provided but an owner is provided, we query the rewards for all of the locks the owner has + } else if lockIdsCombined == "" { + lockIds = append(lockIds, ownerLocks...) } - endEpoch, err := cmd.Flags().GetInt64(FlagEndEpoch) + // if lockIDs are provided and an owner is provided, only query the lockIDs that are provided + // if a lockID was provided and it doesn't belong to the owner, return an error + if len(lockIds) != 0 && owner != "" { + for _, lockId := range lockIds { + validInputLockId := contains(ownerLocks, lockId) + if !validInputLockId { + return fmt.Errorf("lock-id %v does not belong to %v", lockId, owner) + } + } + } + + clientCtx, err := client.GetClientQueryContext(cmd) if err != nil { return err } + queryClient := types.NewQueryClient(clientCtx) + + if owner != "" { + queryClientLockup := lockuptypes.NewQueryClient(clientCtx) + + res, err = queryClientLockup.AccountLockedLongerDuration(cmd.Context(), &lockuptypes.AccountLockedLongerDurationRequest{Owner: owner, Duration: time.Millisecond}) + if err != nil { + return err + } + for _, lockId := range res.Locks { + ownerLocks = append(ownerLocks, lockId.ID) + } + } - res, err := queryClient.RewardsEst(cmd.Context(), &types.RewardsEstRequest{ + // TODO: Fix accumulation store bug. For now, we return a graceful error when attempting to query bugged gauges + rewardsEstimateResult, err := queryClient.RewardsEst(cmd.Context(), &types.RewardsEstRequest{ Owner: owner, // owner is used only when lockIds are empty LockIds: lockIds, EndEpoch: endEpoch, @@ -408,7 +448,7 @@ $ %s query incentives rewards-estimation return err } - return clientCtx.PrintProto(res) + return clientCtx.PrintProto(rewardsEstimateResult) }, } @@ -419,3 +459,13 @@ $ %s query incentives rewards-estimation return cmd } + +func contains(s []uint64, value uint64) bool { + for _, v := range s { + if v == value { + return true + } + } + + return false +} diff --git a/x/incentives/client/cli/tx.go b/x/incentives/client/cli/tx.go index c2cfb9e4084..9d8b52a2094 100644 --- a/x/incentives/client/cli/tx.go +++ b/x/incentives/client/cli/tx.go @@ -35,7 +35,7 @@ func GetTxCmd() *cobra.Command { return cmd } -// NewCreateGaugeCmd broadcast MsgCreateGauge. +// NewCreateGaugeCmd broadcasts a CreateGauge message. func NewCreateGaugeCmd() *cobra.Command { cmd := &cobra.Command{ Use: "create-gauge [lockup_denom] [reward] [flags]", @@ -114,7 +114,7 @@ func NewCreateGaugeCmd() *cobra.Command { return cmd } -// NewAddToGaugeCmd broadcast MsgAddToGauge. +// NewAddToGaugeCmd broadcasts a AddToGauge message. func NewAddToGaugeCmd() *cobra.Command { cmd := &cobra.Command{ Use: "add-to-gauge [gauge_id] [rewards] [flags]", diff --git a/x/incentives/keeper/distribute.go b/x/incentives/keeper/distribute.go index 06c3c01ac52..2442bfc4687 100644 --- a/x/incentives/keeper/distribute.go +++ b/x/incentives/keeper/distribute.go @@ -105,10 +105,13 @@ func (k Keeper) getLocksToDistributionWithMaxDuration(ctx sdk.Context, distrTo l // filteredLocks are all locks that are valid for gauge // It also applies an update for the gauge, handling the sending of the rewards. // (Note this update is in-memory, it does not change state.) -func (k Keeper) FilteredLocksDistributionEst(ctx sdk.Context, gauge types.Gauge, filteredLocks []lockuptypes.PeriodLock) (types.Gauge, sdk.Coins, error) { +func (k Keeper) FilteredLocksDistributionEst(ctx sdk.Context, gauge types.Gauge, filteredLocks []lockuptypes.PeriodLock) (types.Gauge, sdk.Coins, bool, error) { TotalAmtLocked := k.lk.GetPeriodLocksAccumulation(ctx, gauge.DistributeTo) if TotalAmtLocked.IsZero() { - return types.Gauge{}, nil, nil + return types.Gauge{}, nil, false, nil + } + if TotalAmtLocked.IsNegative() { + return types.Gauge{}, nil, true, nil } remainCoins := gauge.Coins.Sub(gauge.DistributedCoins) @@ -119,9 +122,8 @@ func (k Keeper) FilteredLocksDistributionEst(ctx sdk.Context, gauge types.Gauge, if !gauge.IsPerpetual { remainEpochs = gauge.NumEpochsPaidOver - gauge.FilledEpochs } - // TODO: Should this return err if remainEpochs == 0 { - return gauge, sdk.Coins{}, nil + return gauge, sdk.Coins{}, false, nil } remainCoinsPerEpoch := sdk.Coins{} @@ -154,7 +156,7 @@ func (k Keeper) FilteredLocksDistributionEst(ctx sdk.Context, gauge types.Gauge, gauge.FilledEpochs += 1 gauge.DistributedCoins = gauge.DistributedCoins.Add(remainCoinsPerEpoch...) - return gauge, filteredDistrCoins, nil + return gauge, filteredDistrCoins, false, nil } // distributionInfo stores all of the information for pent up sends for rewards distributions. diff --git a/x/incentives/keeper/gauge.go b/x/incentives/keeper/gauge.go index cda28bfb133..59bc7436dc2 100644 --- a/x/incentives/keeper/gauge.go +++ b/x/incentives/keeper/gauge.go @@ -3,6 +3,7 @@ package keeper import ( "encoding/json" "fmt" + "strconv" "strings" "time" @@ -261,10 +262,13 @@ func (k Keeper) GetRewardsEst(ctx sdk.Context, addr sdk.AccAddress, locks []lock } for epoch := distrBeginEpoch; epoch <= endEpoch; epoch++ { - newGauge, distrCoins, err := k.FilteredLocksDistributionEst(cacheCtx, gauge, locks) + newGauge, distrCoins, isBuggedGauge, err := k.FilteredLocksDistributionEst(cacheCtx, gauge, locks) if err != nil { continue } + if isBuggedGauge { + ctx.Logger().Error("Reward estimation does not include gauge " + strconv.Itoa(int(gauge.Id)) + " due to accumulation store bug") + } estimatedRewards = estimatedRewards.Add(distrCoins...) gauge = newGauge } diff --git a/x/incentives/keeper/grpc_query.go b/x/incentives/keeper/grpc_query.go index 5fe8e7b45fc..6395910873e 100644 --- a/x/incentives/keeper/grpc_query.go +++ b/x/incentives/keeper/grpc_query.go @@ -138,10 +138,11 @@ func (q Querier) UpcomingGaugesPerDenom(goCtx context.Context, req *types.Upcomi // RewardsEst returns rewards estimation at a future specific time. func (q Querier) RewardsEst(goCtx context.Context, req *types.RewardsEstRequest) (*types.RewardsEstResponse, error) { + var ownerAddress sdk.AccAddress if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - if len(req.Owner) == 0 { + if len(req.Owner) == 0 && len(req.LockIds) == 0 { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "empty owner") } @@ -151,9 +152,12 @@ func (q Querier) RewardsEst(goCtx context.Context, req *types.RewardsEstRequest) return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "end epoch out of ranges") } - owner, err := sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, err + if len(req.Owner) != 0 { + owner, err := sdk.AccAddressFromBech32(req.Owner) + if err != nil { + return nil, err + } + ownerAddress = owner } locks := make([]lockuptypes.PeriodLock, 0, len(req.LockIds)) @@ -165,7 +169,7 @@ func (q Querier) RewardsEst(goCtx context.Context, req *types.RewardsEstRequest) locks = append(locks, *lock) } - return &types.RewardsEstResponse{Coins: q.Keeper.GetRewardsEst(ctx, owner, locks, req.EndEpoch)}, nil + return &types.RewardsEstResponse{Coins: q.Keeper.GetRewardsEst(ctx, ownerAddress, locks, req.EndEpoch)}, nil } func (q Querier) LockableDurations(ctx context.Context, _ *types.QueryLockableDurationsRequest) (*types.QueryLockableDurationsResponse, error) { From 808f12968832cce6b3a54100048fbb015574cc45 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Sat, 9 Jul 2022 22:38:17 -0500 Subject: [PATCH 048/376] x/incentives: test improvements (#1986) * add test changes * remove root folder readme * remove distribut_test.go TODOs for table driven tests * Update x/incentives/keeper/suite_test.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update x/incentives/keeper/suite_test.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update x/incentives/keeper/grpc_query_test.go Co-authored-by: Roman * move var to top * more var to top * Update x/incentives/keeper/suite_test.go Co-authored-by: Roman * remove todo for deleting usage of SetupNewGauge Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> Co-authored-by: Roman --- x/incentives/README.md | 84 ------------ x/incentives/keeper/bench_test.go | 30 ++++- x/incentives/keeper/distribute_test.go | 180 +++++++++++++++++++------ x/incentives/keeper/export_test.go | 6 + x/incentives/keeper/gauge_test.go | 14 +- x/incentives/keeper/genesis_test.go | 25 +++- x/incentives/keeper/grpc_query_test.go | 133 ++++++++++++------ x/incentives/keeper/keeper_test.go | 3 +- x/incentives/keeper/store_test.go | 11 ++ x/incentives/keeper/suite_test.go | 72 ++++++++-- x/incentives/keeper/utils_test.go | 20 ++- 11 files changed, 376 insertions(+), 202 deletions(-) delete mode 100644 x/incentives/README.md diff --git a/x/incentives/README.md b/x/incentives/README.md deleted file mode 100644 index f1bdd3bf3a6..00000000000 --- a/x/incentives/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# Incentives Module - -The incentives module provides users the functionality to create gauges, -which distributes reward tokens to the qualified lockups. Each lockup -has designated lockup duration that indicates how much time that the -user have to wait until the token release after they request to unlock -the tokens. - -## Creating Gauges - -To initialize a gauge, the creator should decide the following -parameters: - -- Distribution condition: denom to incentivize and minimum lockup - duration. -- Rewards: tokens to be distributed to the lockup owners. -- Start time: time when the distribution will begin. -- Total epochs: number of epochs to distribute over. (Osmosis epochs - are 1 day each, ending at 5PM UTC everyday) - -Making transaction is done in the following format: - -``` {.bash} -osmosisd tx incentives create-gauge [denom] [reward] - --duration [minimum duration for lockups, nullable] - --start-time [start time in RFC3339 or unix format, nullable] - # one of --perpetual or --epochs - --epochs [total distribution epoch] - --perpetual -``` - -### Examples - -#### Case 1 - -I want to make incentives for LP tokens of pool X, namely LPToken, that -have been locked up for at least 1 day. I want to reward 1000 Mytoken to -this pool over 2 days (2 epochs). (500 rewarded on each day) I want the -rewards to start disbursing at 2022 Jan 01. - -MsgCreateGauge: - -- Distribution condition: denom "LPToken", 1 day. -- Rewards: 1000 MyToken -- Start time: 1624000706 (in unix time format) -- Total epochs: 2 (days) - -``` {.bash} -osmosisd tx incentives create-gauge LPToken 1000MyToken \ - --duration 24h \ - --start-time 2022-01-01T00:00:00Z \ - --epochs 2 -``` - -#### Case 2 - -I want to make incentives for atoms that have been locked up for at -least 1 month. I want to reward 1000 MyToken to atom holders -perpetually. (Meaning I add more tokens to this gauge myself every -epoch) I want the reward to start disbursing immedietly. - -MsgCreateGauge: - -- Distribution condition: denom "atom", 720 hours. -- Rewards: 1000 MyTokens -- Start time: empty(immedietly) -- Total epochs: 1 (perpetual) - -``` {.bash} -osmosisd tx incentives create-gauge atom 1000MyToken - --perpetual \ - --duration 168h -``` - -I want to refill the gauge with 500 MyToken after the distribution. - -MsgAddToGauge: - -- Gauge ID: (id of the created gauge) -- Rewards: 500 MyTokens - -``` {.bash} -osmosisd tx incentives add-to-gauge $GAUGE_ID 500MyToken -``` diff --git a/x/incentives/keeper/bench_test.go b/x/incentives/keeper/bench_test.go index c342a74ef11..2ff1bc2c9a2 100644 --- a/x/incentives/keeper/bench_test.go +++ b/x/incentives/keeper/bench_test.go @@ -33,6 +33,7 @@ func Max(x, y int) int { return y } +// genRewardCoins takes coins and returns a randomized coin struct used as rewards for the distribution benchmark. func genRewardCoins(r *rand.Rand, coins sdk.Coins) (res sdk.Coins) { numCoins := 1 + r.Intn(Min(coins.Len(), 1)) denomIndices := r.Perm(numCoins) @@ -45,17 +46,18 @@ func genRewardCoins(r *rand.Rand, coins sdk.Coins) (res sdk.Coins) { return } +// genQueryCondition takes coins and durations and returns a QueryConditon struct. func genQueryCondition( r *rand.Rand, blocktime time.Time, coins sdk.Coins, durationOptions []time.Duration, ) lockuptypes.QueryCondition { - lockQueryType := r.Intn(2) + // only use lockQueryType ByDuration (0) since ByTime (1) is deprecated + lockQueryType := 0 denom := coins[r.Intn(len(coins))].Denom durationOption := r.Intn(len(durationOptions)) duration := durationOptions[durationOption] - // timestampSecs := r.Intn(1 * 60 * 60 * 24 * 7) // range of 1 week timestamp := time.Time{} return lockuptypes.QueryCondition{ @@ -66,8 +68,8 @@ func genQueryCondition( } } +// benchmarkDistributionLogic creates gauges with lockups that get distributed to. Benchmarks the performance of the distribution process. func benchmarkDistributionLogic(numAccts, numDenoms, numGauges, numLockups, numDistrs int, b *testing.B) { - // b.ReportAllocs() b.StopTimer() blockStartTime := time.Now().UTC() @@ -103,7 +105,6 @@ func benchmarkDistributionLogic(numAccts, numDenoms, numGauges, numLockups, numD isPerpetual := true distributeTo := genQueryCondition(r, ctx.BlockTime(), simCoins, durationOptions) rewards := genRewardCoins(r, simCoins) - // startTimeSecs := r.Intn(1 * 60 * 60 * 24 * 7) // range of 1 week startTime := ctx.BlockTime().Add(time.Duration(-1) * time.Second) durationMillisecs := distributeTo.Duration.Milliseconds() numEpochsPaidOver := uint64(1) @@ -169,11 +170,21 @@ func benchmarkDistributionLogic(numAccts, numDenoms, numGauges, numLockups, numD } func BenchmarkDistributionLogicTiny(b *testing.B) { - benchmarkDistributionLogic(1, 1, 1, 1, 1, b) + numAccts := 1 + numDenoms := 1 + numGauges := 1 + numLockups := 1 + numDistrs := 1 + benchmarkDistributionLogic(numAccts, numDenoms, numGauges, numLockups, numDistrs, b) } func BenchmarkDistributionLogicSmall(b *testing.B) { - benchmarkDistributionLogic(10, 1, 10, 1000, 100, b) + numAccts := 10 + numDenoms := 1 + numGauges := 10 + numLockups := 1000 + numDistrs := 100 + benchmarkDistributionLogic(numAccts, numDenoms, numGauges, numLockups, numDistrs, b) } func BenchmarkDistributionLogicMedium(b *testing.B) { @@ -197,5 +208,10 @@ func BenchmarkDistributionLogicLarge(b *testing.B) { } func BenchmarkDistributionLogicHuge(b *testing.B) { - benchmarkDistributionLogic(1000, 100, 1000, 1000, 30000, b) + numAccts := 1000 + numDenoms := 100 + numGauges := 1000 + numLockups := 1000 + numDistrs := 30000 + benchmarkDistributionLogic(numAccts, numDenoms, numGauges, numLockups, numDistrs, b) } diff --git a/x/incentives/keeper/distribute_test.go b/x/incentives/keeper/distribute_test.go index 4a9a948cae2..9699cf05a28 100644 --- a/x/incentives/keeper/distribute_test.go +++ b/x/incentives/keeper/distribute_test.go @@ -1,21 +1,22 @@ package keeper_test import ( + "strings" "time" + "github.com/stretchr/testify/suite" + "github.com/osmosis-labs/osmosis/v7/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) -// TestDistribute tests that when the distribute command is executed on -// a provided gauge, +var _ = suite.TestingSuite(nil) + +// TestDistribute tests that when the distribute command is executed on a provided gauge +// that the correct amount of rewards is sent to the correct lock owners. func (suite *KeeperTestSuite) TestDistribute() { - twoLockupUser := userLocks{ - lockDurations: []time.Duration{defaultLockDuration, 2 * defaultLockDuration}, - lockAmounts: []sdk.Coins{defaultLPTokens, defaultLPTokens}, - } defaultGauge := perpGaugeDesc{ lockDenom: defaultLPDenom, lockDuration: defaultLockDuration, @@ -36,82 +37,174 @@ func (suite *KeeperTestSuite) TestDistribute() { twoKRewardCoins := sdk.Coins{sdk.NewInt64Coin(defaultRewardDenom, 2000)} fiveKRewardCoins := sdk.Coins{sdk.NewInt64Coin(defaultRewardDenom, 5000)} tests := []struct { + name string users []userLocks gauges []perpGaugeDesc expectedRewards []sdk.Coins }{ - // gauge 1 gives 3k coins. Three locks, all eligible. 1k coins per lock - // so 1k to oneLockupUser, 2k to twoLockupUser + // gauge 1 gives 3k coins. three locks, all eligible. 1k coins per lock. + // 1k should go to oneLockupUser and 2k to twoLockupUser. { + name: "One user with one lockup, another user with two lockups, single default gauge", users: []userLocks{oneLockupUser, twoLockupUser}, gauges: []perpGaugeDesc{defaultGauge}, expectedRewards: []sdk.Coins{oneKRewardCoins, twoKRewardCoins}, }, - // gauge 1 gives 3k coins. Three locks, all eligible. - // gauge 2 gives 3k coins to one lock, in twoLockupUser - // so 1k to oneLockupUser, 5k to twoLockupUser + // gauge 1 gives 3k coins. three locks, all eligible. + // gauge 2 gives 3k coins. one lock, to twoLockupUser. + // 1k should to oneLockupUser and 5k to twoLockupUser. { + name: "One user with one lockup (default gauge), another user with two lockups (double length gauge)", users: []userLocks{oneLockupUser, twoLockupUser}, gauges: []perpGaugeDesc{defaultGauge, doubleLengthGauge}, expectedRewards: []sdk.Coins{oneKRewardCoins, fiveKRewardCoins}, }, + // gauge 1 gives zero rewards. + // both oneLockupUser and twoLockupUser should get no rewards. { + name: "One user with one lockup, another user with two lockups, both with no rewards gauge", users: []userLocks{oneLockupUser, twoLockupUser}, gauges: []perpGaugeDesc{noRewardGauge}, expectedRewards: []sdk.Coins{noRewardCoins, noRewardCoins}, }, + // gauge 1 gives no rewards. + // gauge 2 gives 3k coins. three locks, all eligible. 1k coins per lock. + // 1k should to oneLockupUser and 2k to twoLockupUser. { + name: "One user with one lockup and another user with two lockups. No rewards and a default gauge", users: []userLocks{oneLockupUser, twoLockupUser}, gauges: []perpGaugeDesc{noRewardGauge, defaultGauge}, expectedRewards: []sdk.Coins{oneKRewardCoins, twoKRewardCoins}, }, } - for tcIndex, tc := range tests { + for _, tc := range tests { suite.SetupTest() - gauges := suite.SetupGauges(tc.gauges) + // setup gauges and the locks defined in the above tests, then distribute to them + gauges := suite.SetupGauges(tc.gauges, defaultLPDenom) addrs := suite.SetupUserLocks(tc.users) _, err := suite.App.IncentivesKeeper.Distribute(suite.Ctx, gauges) suite.Require().NoError(err) - // Check expected rewards + // check expected rewards against actual rewards received + for i, addr := range addrs { + bal := suite.App.BankKeeper.GetAllBalances(suite.Ctx, addr) + suite.Require().Equal(tc.expectedRewards[i].String(), bal.String(), "test %v, person %d", tc.name, i) + } + } +} + +// TestSyntheticDistribute tests that when the distribute command is executed on a provided gauge +// the correct amount of rewards is sent to the correct synthetic lock owners. +func (suite *KeeperTestSuite) TestSyntheticDistribute() { + defaultGauge := perpGaugeDesc{ + lockDenom: defaultLPSyntheticDenom, + lockDuration: defaultLockDuration, + rewardAmount: sdk.Coins{sdk.NewInt64Coin(defaultRewardDenom, 3000)}, + } + doubleLengthGauge := perpGaugeDesc{ + lockDenom: defaultLPSyntheticDenom, + lockDuration: 2 * defaultLockDuration, + rewardAmount: sdk.Coins{sdk.NewInt64Coin(defaultRewardDenom, 3000)}, + } + noRewardGauge := perpGaugeDesc{ + lockDenom: defaultLPSyntheticDenom, + lockDuration: defaultLockDuration, + rewardAmount: sdk.Coins{}, + } + noRewardCoins := sdk.Coins{} + oneKRewardCoins := sdk.Coins{sdk.NewInt64Coin(defaultRewardDenom, 1000)} + twoKRewardCoins := sdk.Coins{sdk.NewInt64Coin(defaultRewardDenom, 2000)} + fiveKRewardCoins := sdk.Coins{sdk.NewInt64Coin(defaultRewardDenom, 5000)} + tests := []struct { + name string + users []userLocks + gauges []perpGaugeDesc + expectedRewards []sdk.Coins + }{ + // gauge 1 gives 3k coins. three locks, all eligible. 1k coins per lock. + // 1k should go to oneLockupUser and 2k to twoLockupUser. + { + name: "One user with one synthetic lockup, another user with two synthetic lockups, both with default gauge", + users: []userLocks{oneSyntheticLockupUser, twoSyntheticLockupUser}, + gauges: []perpGaugeDesc{defaultGauge}, + expectedRewards: []sdk.Coins{oneKRewardCoins, twoKRewardCoins}, + }, + // gauge 1 gives 3k coins. three locks, all eligible. + // gauge 2 gives 3k coins. one lock, to twoLockupUser. + // 1k should to oneLockupUser and 5k to twoLockupUser. + { + name: "One user with one synthetic lockup (default gauge), another user with two synthetic lockups (double length gauge)", + users: []userLocks{oneSyntheticLockupUser, twoSyntheticLockupUser}, + gauges: []perpGaugeDesc{defaultGauge, doubleLengthGauge}, + expectedRewards: []sdk.Coins{oneKRewardCoins, fiveKRewardCoins}, + }, + // gauge 1 gives zero rewards. + // both oneLockupUser and twoLockupUser should get no rewards. + { + name: "One user with one synthetic lockup, another user with two synthetic lockups, both with no rewards gauge", + users: []userLocks{oneSyntheticLockupUser, twoSyntheticLockupUser}, + gauges: []perpGaugeDesc{noRewardGauge}, + expectedRewards: []sdk.Coins{noRewardCoins, noRewardCoins}, + }, + // gauge 1 gives no rewards. + // gauge 2 gives 3k coins. three locks, all eligible. 1k coins per lock. + // 1k should to oneLockupUser and 2k to twoLockupUser. + { + name: "One user with one synthetic lockup (no rewards gauge), another user with two synthetic lockups (default gauge)", + users: []userLocks{oneSyntheticLockupUser, twoSyntheticLockupUser}, + gauges: []perpGaugeDesc{noRewardGauge, defaultGauge}, + expectedRewards: []sdk.Coins{oneKRewardCoins, twoKRewardCoins}, + }, + } + for _, tc := range tests { + suite.SetupTest() + // setup gauges and the synthetic locks defined in the above tests, then distribute to them + gauges := suite.SetupGauges(tc.gauges, defaultLPSyntheticDenom) + addrs := suite.SetupUserSyntheticLocks(tc.users) + _, err := suite.App.IncentivesKeeper.Distribute(suite.Ctx, gauges) + suite.Require().NoError(err) + // check expected rewards against actual rewards received for i, addr := range addrs { + var rewards string bal := suite.App.BankKeeper.GetAllBalances(suite.Ctx, addr) - suite.Require().Equal(tc.expectedRewards[i].String(), bal.String(), "tcnum %d, person %d", tcIndex, i) + // extract the superbonding tokens from the rewards distribution + // TODO: figure out a less hacky way of doing this + if strings.Contains(bal.String(), "lptoken/superbonding,") { + rewards = strings.Split(bal.String(), "lptoken/superbonding,")[1] + } + suite.Require().Equal(tc.expectedRewards[i].String(), rewards, "test %v, person %d", tc.name, i) } } - // TODO: test distribution for synthetic lockup as well } -// TODO: Make this test table driven, or move whatever it tests into -// the much simpler TestDistribute +// TestGetModuleToDistributeCoins tests the sum of coins yet to be distributed for all of the module is correct. func (suite *KeeperTestSuite) TestGetModuleToDistributeCoins() { - // test for module get gauges suite.SetupTest() - // initial check + // check that the sum of coins yet to be distributed is nil coins := suite.App.IncentivesKeeper.GetModuleToDistributeCoins(suite.Ctx) suite.Require().Equal(coins, sdk.Coins(nil)) - // setup lock and gauge + // setup a non perpetual lock and gauge _, gaugeID, gaugeCoins, startTime := suite.SetupLockAndGauge(false) - // check after gauge creation + // check that the sum of coins yet to be distributed is equal to the newly created gaugeCoins coins = suite.App.IncentivesKeeper.GetModuleToDistributeCoins(suite.Ctx) suite.Require().Equal(coins, gaugeCoins) - // add to gauge and check + // add coins to the previous gauge and check that the sum of coins yet to be distributed includes these new coins addCoins := sdk.Coins{sdk.NewInt64Coin("stake", 200)} suite.AddToGauge(addCoins, gaugeID) coins = suite.App.IncentivesKeeper.GetModuleToDistributeCoins(suite.Ctx) suite.Require().Equal(coins, gaugeCoins.Add(addCoins...)) - // check after creating another gauge from another address + // create a new gauge + // check that the sum of coins yet to be distributed is equal to the gauge1 and gauge2 coins combined _, _, gaugeCoins2, _ := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 1000)}) - coins = suite.App.IncentivesKeeper.GetModuleToDistributeCoins(suite.Ctx) suite.Require().Equal(coins, gaugeCoins.Add(addCoins...).Add(gaugeCoins2...)) - // start distribution + // move all created gauges from upcoming to active suite.Ctx = suite.Ctx.WithBlockTime(startTime) gauge, err := suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) suite.Require().NoError(err) @@ -128,23 +221,22 @@ func (suite *KeeperTestSuite) TestGetModuleToDistributeCoins() { suite.Require().Equal(coins, gaugeCoins.Add(addCoins...).Add(gaugeCoins2...).Sub(distrCoins)) } -// TODO: Make this test table driven, or move whatever it tests into -// the much simpler TestDistribute +// TestGetModuleDistributedCoins tests that the sum of coins that have been distributed so far for all of the module is correct. func (suite *KeeperTestSuite) TestGetModuleDistributedCoins() { suite.SetupTest() - // initial check + // check that the sum of coins yet to be distributed is nil coins := suite.App.IncentivesKeeper.GetModuleDistributedCoins(suite.Ctx) suite.Require().Equal(coins, sdk.Coins(nil)) - // setup lock and gauge + // setup a non perpetual lock and gauge _, gaugeID, _, startTime := suite.SetupLockAndGauge(false) - // check after gauge creation + // check that the sum of coins yet to be distributed is equal to the newly created gaugeCoins coins = suite.App.IncentivesKeeper.GetModuleDistributedCoins(suite.Ctx) suite.Require().Equal(coins, sdk.Coins(nil)) - // start distribution + // move all created gauges from upcoming to active suite.Ctx = suite.Ctx.WithBlockTime(startTime) gauge, err := suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) suite.Require().NoError(err) @@ -156,22 +248,24 @@ func (suite *KeeperTestSuite) TestGetModuleDistributedCoins() { suite.Require().NoError(err) suite.Require().Equal(distrCoins, sdk.Coins{sdk.NewInt64Coin("stake", 5)}) - // check after distribution + // check gauge changes after distribution coins = suite.App.IncentivesKeeper.GetModuleToDistributeCoins(suite.Ctx) suite.Require().Equal(coins, distrCoins) } +// TestNoLockPerpetualGaugeDistribution tests that the creation of a perp gauge that has no locks associated does not distribute any tokens. func (suite *KeeperTestSuite) TestNoLockPerpetualGaugeDistribution() { - // test for module get gauges suite.SetupTest() - // setup no lock perpetual gauge + // setup a perpetual gauge with no associated locks coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} gaugeID, _, _, startTime := suite.SetupNewGauge(true, coins) - // check gauges + // ensure the created gauge has not completed distribution gauges := suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) suite.Require().Len(gauges, 1) + + // ensure the not finished gauge matches the previously created gauge expectedGauge := types.Gauge{ Id: gaugeID, IsPerpetual: true, @@ -188,7 +282,7 @@ func (suite *KeeperTestSuite) TestNoLockPerpetualGaugeDistribution() { } suite.Require().Equal(gauges[0].String(), expectedGauge.String()) - // start distribution + // move the created gauge from upcoming to active suite.Ctx = suite.Ctx.WithBlockTime(startTime) gauge, err := suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) suite.Require().NoError(err) @@ -206,17 +300,19 @@ func (suite *KeeperTestSuite) TestNoLockPerpetualGaugeDistribution() { suite.Require().Equal(gauges[0].String(), expectedGauge.String()) } +// TestNoLockNonPerpetualGaugeDistribution tests that the creation of a non perp gauge that has no locks associated does not distribute any tokens. func (suite *KeeperTestSuite) TestNoLockNonPerpetualGaugeDistribution() { - // test for module get gauges suite.SetupTest() - // setup no lock non-perpetual gauge + // setup non-perpetual gauge with no associated locks coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)} gaugeID, _, _, startTime := suite.SetupNewGauge(false, coins) - // check gauges + // ensure the created gauge has not completed distribution gauges := suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) suite.Require().Len(gauges, 1) + + // ensure the not finished gauge matches the previously created gauge expectedGauge := types.Gauge{ Id: gaugeID, IsPerpetual: false, @@ -233,14 +329,14 @@ func (suite *KeeperTestSuite) TestNoLockNonPerpetualGaugeDistribution() { } suite.Require().Equal(gauges[0].String(), expectedGauge.String()) - // start distribution + // move the created gauge from upcoming to active suite.Ctx = suite.Ctx.WithBlockTime(startTime) gauge, err := suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) suite.Require().NoError(err) err = suite.App.IncentivesKeeper.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) suite.Require().NoError(err) - // distribute coins to stakers, since it's perpetual distribute everything on single distribution + // distribute coins to stakers distrCoins, err := suite.App.IncentivesKeeper.Distribute(suite.Ctx, []types.Gauge{*gauge}) suite.Require().NoError(err) suite.Require().Equal(distrCoins, sdk.Coins(nil)) diff --git a/x/incentives/keeper/export_test.go b/x/incentives/keeper/export_test.go index 7934833b656..124ed6b2948 100644 --- a/x/incentives/keeper/export_test.go +++ b/x/incentives/keeper/export_test.go @@ -6,26 +6,32 @@ import ( "github.com/osmosis-labs/osmosis/v7/x/incentives/types" ) +// AddGaugeRefByKey appends the provided gauge ID into an array associated with the provided key. func (k Keeper) AddGaugeRefByKey(ctx sdk.Context, key []byte, guageID uint64) error { return k.addGaugeRefByKey(ctx, key, guageID) } +// DeleteGaugeRefByKey removes the provided gauge ID from an array associated with the provided key. func (k Keeper) DeleteGaugeRefByKey(ctx sdk.Context, key []byte, guageID uint64) error { return k.deleteGaugeRefByKey(ctx, key, guageID) } +// GetGaugeRefs returns the gauge IDs specified by the provided key. func (k Keeper) GetGaugeRefs(ctx sdk.Context, key []byte) []uint64 { return k.getGaugeRefs(ctx, key) } +// GetAllGaugeIDsByDenom returns all active gauge-IDs associated with lockups of the provided denom. func (k Keeper) GetAllGaugeIDsByDenom(ctx sdk.Context, denom string) []uint64 { return k.getAllGaugeIDsByDenom(ctx, denom) } +// MoveUpcomingGaugeToActiveGauge moves a gauge that has reached it's start time from an upcoming to an active status. func (k Keeper) MoveUpcomingGaugeToActiveGauge(ctx sdk.Context, gauge types.Gauge) error { return k.moveUpcomingGaugeToActiveGauge(ctx, gauge) } +// MoveActiveGaugeToFinishedGauge moves a gauge that has completed its distribution from an active to a finished status. func (k Keeper) MoveActiveGaugeToFinishedGauge(ctx sdk.Context, gauge types.Gauge) error { return k.moveActiveGaugeToFinishedGauge(ctx, gauge) } diff --git a/x/incentives/keeper/gauge_test.go b/x/incentives/keeper/gauge_test.go index 632e1abda7b..825b78cecee 100644 --- a/x/incentives/keeper/gauge_test.go +++ b/x/incentives/keeper/gauge_test.go @@ -3,12 +3,17 @@ package keeper_test import ( "time" + "github.com/stretchr/testify/suite" + "github.com/osmosis-labs/osmosis/v7/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) +var _ = suite.TestingSuite(nil) + +// TestInvalidDurationGaugeCreationValidation tests error handling for creating a gauge with an invalid duration. func (suite *KeeperTestSuite) TestInvalidDurationGaugeCreationValidation() { suite.SetupTest() @@ -26,6 +31,7 @@ func (suite *KeeperTestSuite) TestInvalidDurationGaugeCreationValidation() { suite.Require().NoError(err) } +// TestNonExistentDenomGaugeCreation tests error handling for creating a gauge with an invalid denom. func (suite *KeeperTestSuite) TestNonExistentDenomGaugeCreation() { suite.SetupTest() @@ -43,9 +49,7 @@ func (suite *KeeperTestSuite) TestNonExistentDenomGaugeCreation() { suite.Require().NoError(err) } -// TODO: Make this test table driven -// OR if it needs to be script based, -// remove lots of boilerplate so this can actually be followed +// TestNonPerpetualGaugeOperations tests non perpetual gauge distribution logic. func (suite *KeeperTestSuite) TestNonPerpetualGaugeOperations() { // test for module get gauges suite.SetupTest() @@ -146,6 +150,7 @@ func (suite *KeeperTestSuite) TestNonPerpetualGaugeOperations() { suite.Require().Equal(sdk.Coins{}, rewardsEst) } +// TestPerpetualGaugeOperations tests perpetual gauge distribution logic. func (suite *KeeperTestSuite) TestPerpetualGaugeOperations() { // test for module get gauges suite.SetupTest() @@ -254,9 +259,8 @@ func (suite *KeeperTestSuite) TestPerpetualGaugeOperations() { suite.Require().Equal(sdk.Coins(nil), rewardsEst) } +// TestGaugesByDenom tests gauge distribution using the gauges by denom keeper. func (suite *KeeperTestSuite) TestGaugesByDenom() { - // TODO: This is not a good test. We should refactor it to be table driven, - // specifying a list of gauges to define, and then the expected result of gauges by denom testGaugeByDenom := func(isPerpetual bool) { // test for module get gauges suite.SetupTest() diff --git a/x/incentives/keeper/genesis_test.go b/x/incentives/keeper/genesis_test.go index 18c6eba863e..f48c3ed9fda 100644 --- a/x/incentives/keeper/genesis_test.go +++ b/x/incentives/keeper/genesis_test.go @@ -15,36 +15,45 @@ import ( lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" ) +// TestIncentivesExportGenesis tests export genesis command for the incentives module. func TestIncentivesExportGenesis(t *testing.T) { + // export genesis using default configurations + // ensure resulting genesis params match default params app := osmoapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) genesis := app.IncentivesKeeper.ExportGenesis(ctx) require.Equal(t, genesis.Params.DistrEpochIdentifier, "week") require.Len(t, genesis.Gauges, 0) + // create an address and fund with coins addr := sdk.AccAddress([]byte("addr1---------------")) coins := sdk.Coins{sdk.NewInt64Coin("stake", 10000)} + err := simapp.FundAccount(app.BankKeeper, ctx, addr, coins) + require.NoError(t, err) + + // mints LP tokens and send to address created earlier + // this ensures the supply exists on chain distrTo := lockuptypes.QueryCondition{ LockQueryType: lockuptypes.ByDuration, Denom: "lptoken", Duration: time.Second, } - startTime := time.Now() - err := simapp.FundAccount(app.BankKeeper, ctx, addr, coins) - require.NoError(t, err) - - // mints coins so supply exists on chain mintLPtokens := sdk.Coins{sdk.NewInt64Coin(distrTo.Denom, 200)} err = simapp.FundAccount(app.BankKeeper, ctx, addr, mintLPtokens) require.NoError(t, err) + // create a gauge that distributes coins to earlier created LP token and duration + startTime := time.Now() gaugeID, err := app.IncentivesKeeper.CreateGauge(ctx, true, addr, coins, distrTo, startTime, 1) require.NoError(t, err) + // export genesis using default configurations + // ensure resulting genesis params match default params genesis = app.IncentivesKeeper.ExportGenesis(ctx) require.Equal(t, genesis.Params.DistrEpochIdentifier, "week") require.Len(t, genesis.Gauges, 1) + // ensure the first gauge listed in the exported genesis explicitly matches expectation require.Equal(t, genesis.Gauges[0], types.Gauge{ Id: gaugeID, IsPerpetual: true, @@ -57,13 +66,16 @@ func TestIncentivesExportGenesis(t *testing.T) { }) } +// TestIncentivesInitGenesis takes a genesis state and tests initializing that genesis for the incentives module. func TestIncentivesInitGenesis(t *testing.T) { app := osmoapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + // checks that the default genesis parameters pass validation validateGenesis := types.DefaultGenesis().Params.Validate() require.NoError(t, validateGenesis) + // create coins, lp tokens with lockup durations, and a gauge for this lockup coins := sdk.Coins{sdk.NewInt64Coin("stake", 10000)} startTime := time.Now() distrTo := lockuptypes.QueryCondition{ @@ -81,6 +93,8 @@ func TestIncentivesInitGenesis(t *testing.T) { DistributedCoins: sdk.Coins(nil), StartTime: startTime.UTC(), } + + // initialize genesis with specified parameter, the gauge created earlier, and lockable durations app.IncentivesKeeper.InitGenesis(ctx, types.GenesisState{ Params: types.Params{ DistrEpochIdentifier: "week", @@ -94,6 +108,7 @@ func TestIncentivesInitGenesis(t *testing.T) { }, }) + // check that the gauge created earlier was initialized through initGenesis and still exists on chain gauges := app.IncentivesKeeper.GetGauges(ctx) require.Len(t, gauges, 1) require.Equal(t, gauges[0], gauge) diff --git a/x/incentives/keeper/grpc_query_test.go b/x/incentives/keeper/grpc_query_test.go index 4316321043d..b458329e839 100644 --- a/x/incentives/keeper/grpc_query_test.go +++ b/x/incentives/keeper/grpc_query_test.go @@ -1,29 +1,33 @@ package keeper_test import ( - // "fmt" "time" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" query "github.com/cosmos/cosmos-sdk/types/query" + "github.com/osmosis-labs/osmosis/v7/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" pooltypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" ) +var _ = suite.TestingSuite(nil) + +// TestGRPCGaugeByID tests querying gauges via gRPC returns the correct response. func (suite *KeeperTestSuite) TestGRPCGaugeByID() { suite.SetupTest() // create a gauge gaugeID, _, coins, startTime := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - // Ensure that a querying for a gauge with an ID that doesn't exist returns an error + // ensure that querying for a gauge with an ID that doesn't exist returns an error. res, err := suite.querier.GaugeByID(sdk.WrapSDKContext(suite.Ctx), &types.GaugeByIDRequest{Id: 1000}) suite.Require().Error(err) suite.Require().Equal(res, (*types.GaugeByIDResponse)(nil)) - // Check that querying a gauge with an ID that exists returns the gauge. + // check that querying a gauge with an ID that exists returns the gauge. res, err = suite.querier.GaugeByID(sdk.WrapSDKContext(suite.Ctx), &types.GaugeByIDRequest{Id: gaugeID}) suite.Require().NoError(err) suite.Require().NotEqual(res.Gauge, nil) @@ -44,10 +48,11 @@ func (suite *KeeperTestSuite) TestGRPCGaugeByID() { suite.Require().Equal(res.Gauge.String(), expectedGauge.String()) } +// TestGRPCGauges tests querying upcoming and active gauges via gRPC returns the correct response. func (suite *KeeperTestSuite) TestGRPCGauges() { suite.SetupTest() - // initial check + // ensure initially querying gauges returns no gauges res, err := suite.querier.Gauges(sdk.WrapSDKContext(suite.Ctx), &types.GaugesRequest{}) suite.Require().NoError(err) suite.Require().Len(res.Data, 0) @@ -55,7 +60,7 @@ func (suite *KeeperTestSuite) TestGRPCGauges() { // create a gauge gaugeID, _, coins, startTime := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - // final check + // query gauges again, but this time expect the gauge created earlier in the response res, err = suite.querier.Gauges(sdk.WrapSDKContext(suite.Ctx), &types.GaugesRequest{}) suite.Require().NoError(err) suite.Require().Len(res.Data, 1) @@ -75,32 +80,34 @@ func (suite *KeeperTestSuite) TestGRPCGauges() { } suite.Require().Equal(res.Data[0].String(), expectedGauge.String()) - // filtering check + // create 10 more gauges for i := 0; i < 10; i++ { suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 3)}) suite.Ctx = suite.Ctx.WithBlockTime(startTime.Add(time.Second)) } + // check that setting page request limit to 10 will only return 10 out of the 11 gauges filter := query.PageRequest{Limit: 10} res, err = suite.querier.Gauges(sdk.WrapSDKContext(suite.Ctx), &types.GaugesRequest{Pagination: &filter}) suite.Require().Len(res.Data, 10) } +// TestGRPCActiveGauges tests querying active gauges via gRPC returns the correct response. func (suite *KeeperTestSuite) TestGRPCActiveGauges() { suite.SetupTest() - // initial check + // ensure initially querying active gauges returns no gauges res, err := suite.querier.ActiveGauges(sdk.WrapSDKContext(suite.Ctx), &types.ActiveGaugesRequest{}) suite.Require().NoError(err) suite.Require().Len(res.Data, 0) - // create a gauge + // create a gauge and move it from upcoming to active gaugeID, gauge, coins, startTime := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) suite.Ctx = suite.Ctx.WithBlockTime(startTime.Add(time.Second)) err = suite.querier.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) suite.Require().NoError(err) - // final check + // query active gauges again, but this time expect the gauge created earlier in the response res, err = suite.querier.ActiveGauges(sdk.WrapSDKContext(suite.Ctx), &types.ActiveGaugesRequest{}) suite.Require().NoError(err) suite.Require().Len(res.Data, 1) @@ -120,28 +127,31 @@ func (suite *KeeperTestSuite) TestGRPCActiveGauges() { } suite.Require().Equal(res.Data[0].String(), expectedGauge.String()) - // filtering check + // create 20 more gauges for i := 0; i < 20; i++ { _, gauge, _, _ := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 3)}) suite.Ctx = suite.Ctx.WithBlockTime(startTime.Add(time.Second)) - // set up more 9 active gauges => 10 + // move the first 9 gauges from upcoming to active (now 10 active gauges, 30 total gauges) if i < 9 { suite.querier.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) } } + // set page request limit to 5, expect only 5 active gauge responses res, err = suite.querier.ActiveGauges(sdk.WrapSDKContext(suite.Ctx), &types.ActiveGaugesRequest{Pagination: &query.PageRequest{Limit: 5}}) suite.Require().Len(res.Data, 5) + // set page request limit to 15, expect only 10 active gauge responses res, err = suite.querier.ActiveGauges(sdk.WrapSDKContext(suite.Ctx), &types.ActiveGaugesRequest{Pagination: &query.PageRequest{Limit: 15}}) suite.Require().Len(res.Data, 10) } +// TestGRPCActiveGaugesPerDenom tests querying active gauges by denom via gRPC returns the correct response. func (suite *KeeperTestSuite) TestGRPCActiveGaugesPerDenom() { suite.SetupTest() - // initial check + // ensure initially querying gauges by denom returns no gauges res, err := suite.querier.ActiveGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &types.ActiveGaugesPerDenomRequest{}) suite.Require().NoError(err) suite.Require().Len(res.Data, 0) @@ -150,7 +160,8 @@ func (suite *KeeperTestSuite) TestGRPCActiveGaugesPerDenom() { gaugeID, gauge, coins, startTime := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) suite.Ctx = suite.Ctx.WithBlockTime(startTime.Add(time.Second)) err = suite.App.IncentivesKeeper.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) - // final check + + // query gauges by denom again, but this time expect the gauge created earlier in the response res, err = suite.querier.ActiveGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &types.ActiveGaugesPerDenomRequest{Denom: "lptoken", Pagination: nil}) suite.Require().NoError(err) suite.Require().Len(res.Data, 1) @@ -170,31 +181,35 @@ func (suite *KeeperTestSuite) TestGRPCActiveGaugesPerDenom() { } suite.Require().Equal(res.Data[0].String(), expectedGauge.String()) - // filtering check + // setup 20 more gauges with the pool denom for i := 0; i < 20; i++ { _, gauge, _, _ := suite.SetupNewGaugeWithDenom(false, sdk.Coins{sdk.NewInt64Coin("stake", 3)}, "pool") suite.Ctx = suite.Ctx.WithBlockTime(startTime.Add(time.Second)) - // set up 10 active gauges with "pool" denom + // move the first 10 of 20 gauges to an active status if i < 10 { suite.querier.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) } } + // query active gauges by lptoken denom with a page request of 5 should only return one gauge res, err = suite.querier.ActiveGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &types.ActiveGaugesPerDenomRequest{Denom: "lptoken", Pagination: &query.PageRequest{Limit: 5}}) suite.Require().Len(res.Data, 1) + // query active gauges by pool denom with a page request of 5 should return 5 gauges res, err = suite.querier.ActiveGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &types.ActiveGaugesPerDenomRequest{Denom: "pool", Pagination: &query.PageRequest{Limit: 5}}) suite.Require().Len(res.Data, 5) + // query active gauges by pool denom with a page request of 15 should return 10 gauges res, err = suite.querier.ActiveGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &types.ActiveGaugesPerDenomRequest{Denom: "pool", Pagination: &query.PageRequest{Limit: 15}}) suite.Require().Len(res.Data, 10) } +// TestGRPCUpcomingGauges tests querying upcoming gauges via gRPC returns the correct response. func (suite *KeeperTestSuite) TestGRPCUpcomingGauges() { suite.SetupTest() - // initial check + // ensure initially querying upcoming gauges returns no gauges res, err := suite.querier.UpcomingGauges(sdk.WrapSDKContext(suite.Ctx), &types.UpcomingGaugesRequest{}) suite.Require().NoError(err) suite.Require().Len(res.Data, 0) @@ -202,7 +217,7 @@ func (suite *KeeperTestSuite) TestGRPCUpcomingGauges() { // create a gauge gaugeID, _, coins, startTime := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - // final check + // query upcoming gauges again, but this time expect the gauge created earlier in the response res, err = suite.querier.UpcomingGauges(sdk.WrapSDKContext(suite.Ctx), &types.UpcomingGaugesRequest{}) suite.Require().NoError(err) suite.Require().Len(res.Data, 1) @@ -222,35 +237,41 @@ func (suite *KeeperTestSuite) TestGRPCUpcomingGauges() { } suite.Require().Equal(res.Data[0].String(), expectedGauge.String()) - // filtering check + // setup 20 more upcoming gauges for i := 0; i < 20; i++ { _, gauge, _, _ := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 3)}) suite.Ctx = suite.Ctx.WithBlockTime(startTime.Add(time.Second)) - // set up more 9 active gauges => Upcoming = 1 + (20 -9) = 12 + // move the first 9 created gauges to an active status + // 1 + (20 -9) = 12 upcoming gauges if i < 9 { suite.querier.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) } } + // query upcoming gauges with a page request of 5 should return 5 gauges res, err = suite.querier.UpcomingGauges(sdk.WrapSDKContext(suite.Ctx), &types.UpcomingGaugesRequest{Pagination: &query.PageRequest{Limit: 5}}) suite.Require().Len(res.Data, 5) + // query upcoming gauges with a page request of 15 should return 12 gauges res, err = suite.querier.UpcomingGauges(sdk.WrapSDKContext(suite.Ctx), &types.UpcomingGaugesRequest{Pagination: &query.PageRequest{Limit: 15}}) suite.Require().Len(res.Data, 12) } +// TestGRPCUpcomingGaugesPerDenom tests querying upcoming gauges by denom via gRPC returns the correct response. func (suite *KeeperTestSuite) TestGRPCUpcomingGaugesPerDenom() { suite.SetupTest() + // ensure initially querying upcoming gauges by denom returns no gauges upcomingGaugeRequest := types.UpcomingGaugesPerDenomRequest{Denom: "lptoken", Pagination: nil} - // initial check, no gauges when none exist res, err := suite.querier.UpcomingGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &upcomingGaugeRequest) suite.Require().NoError(err) suite.Require().Len(res.UpcomingGauges, 0) // create a gauge, and check upcoming gauge is working gaugeID, gauge, coins, startTime := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) + + // query upcoming gauges by denom again, but this time expect the gauge created earlier in the response res, err = suite.querier.UpcomingGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &upcomingGaugeRequest) suite.Require().NoError(err) suite.Require().Len(res.UpcomingGauges, 1) @@ -270,38 +291,45 @@ func (suite *KeeperTestSuite) TestGRPCUpcomingGaugesPerDenom() { } suite.Require().Equal(res.UpcomingGauges[0].String(), expectedGauge.String()) - // final check when gauge is moved from upcoming to active + // move gauge from upcoming to active + // ensure the query no longer returns a response suite.Ctx = suite.Ctx.WithBlockTime(startTime.Add(time.Second)) err = suite.App.IncentivesKeeper.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) res, err = suite.querier.UpcomingGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &upcomingGaugeRequest) suite.Require().NoError(err) suite.Require().Len(res.UpcomingGauges, 0) - // filtering check + // setup 20 more upcoming gauges with pool denom for i := 0; i < 20; i++ { _, gauge, _, _ := suite.SetupNewGaugeWithDenom(false, sdk.Coins{sdk.NewInt64Coin("stake", 3)}, "pool") suite.Ctx = suite.Ctx.WithBlockTime(startTime.Add(time.Second)) - // set up 10 active gauges with "pool" denom => 10 upcoming + // move the first 10 created gauges from upcoming to active + // this leaves 10 upcoming gauges if i < 10 { suite.querier.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) } } + // query upcoming gauges by lptoken denom with a page request of 5 should return 0 gauges res, err = suite.querier.UpcomingGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &types.UpcomingGaugesPerDenomRequest{Denom: "lptoken", Pagination: &query.PageRequest{Limit: 5}}) suite.Require().Len(res.UpcomingGauges, 0) + // query upcoming gauges by pool denom with a page request of 5 should return 5 gauges res, err = suite.querier.UpcomingGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &types.UpcomingGaugesPerDenomRequest{Denom: "pool", Pagination: &query.PageRequest{Limit: 5}}) suite.Require().Len(res.UpcomingGauges, 5) + // query upcoming gauges by pool denom with a page request of 15 should return 10 gauges res, err = suite.querier.UpcomingGaugesPerDenom(sdk.WrapSDKContext(suite.Ctx), &types.UpcomingGaugesPerDenomRequest{Denom: "pool", Pagination: &query.PageRequest{Limit: 15}}) suite.Require().Len(res.UpcomingGauges, 10) } +// TestGRPCRewardsEst tests querying rewards estimation at a future specific time (by epoch) via gRPC returns the correct response. func (suite *KeeperTestSuite) TestGRPCRewardsEst() { suite.SetupTest() - // initial check + // create an address with no locks + // ensure rewards estimation returns a nil coins struct lockOwner := sdk.AccAddress([]byte("addr1---------------")) res, err := suite.querier.RewardsEst(sdk.WrapSDKContext(suite.Ctx), &types.RewardsEstRequest{ Owner: lockOwner.String(), @@ -309,9 +337,11 @@ func (suite *KeeperTestSuite) TestGRPCRewardsEst() { suite.Require().NoError(err) suite.Require().Equal(res.Coins, sdk.Coins{}) - // setup lock and gauge + // setup a lock and gauge for a new address lockOwner, _, coins, _ := suite.SetupLockAndGauge(false) + // query the rewards of the new address after 100 epochs + // since it is the only address the gauge is paying out to, the future rewards should equal the entirety of the gauge res, err = suite.querier.RewardsEst(sdk.WrapSDKContext(suite.Ctx), &types.RewardsEstRequest{ Owner: lockOwner.String(), EndEpoch: 100, @@ -320,10 +350,13 @@ func (suite *KeeperTestSuite) TestGRPCRewardsEst() { suite.Require().Equal(res.Coins, coins) } +// TestRewardsEstWithPoolIncentives tests querying rewards estimation at a future specific time (by epoch) via gRPC returns the correct response. +// Also changes distribution records for the pool incentives to distribute to the respective lock owner. func (suite *KeeperTestSuite) TestRewardsEstWithPoolIncentives() { suite.SetupTest() - // initial check + // create an address with no locks + // ensure rewards estimation returns a nil coins struct lockOwner := sdk.AccAddress([]byte("addr1---------------")) res, err := suite.querier.RewardsEst(sdk.WrapSDKContext(suite.Ctx), &types.RewardsEstRequest{ Owner: lockOwner.String(), @@ -331,8 +364,10 @@ func (suite *KeeperTestSuite) TestRewardsEstWithPoolIncentives() { suite.Require().NoError(err) suite.Require().Equal(res.Coins, sdk.Coins{}) - // setup lock and gauge + // setup a lock and gauge for a new address lockOwner, gaugeID, coins, _ := suite.SetupLockAndGauge(true) + + // take newly created gauge and modify its pool incentives distribution weight to 100 distrRecord := pooltypes.DistrRecord{ GaugeId: gaugeID, Weight: sdk.NewInt(100), @@ -340,6 +375,8 @@ func (suite *KeeperTestSuite) TestRewardsEstWithPoolIncentives() { err = suite.App.PoolIncentivesKeeper.ReplaceDistrRecords(suite.Ctx, distrRecord) suite.Require().NoError(err) + // query the rewards of the new address after the 10th epoch + // since it is the only address the gauge is paying out to, the future rewards should equal the entirety of the gauge res, err = suite.querier.RewardsEst(sdk.WrapSDKContext(suite.Ctx), &types.RewardsEstRequest{ Owner: lockOwner.String(), EndEpoch: 10, @@ -347,12 +384,16 @@ func (suite *KeeperTestSuite) TestRewardsEstWithPoolIncentives() { suite.Require().NoError(err) suite.Require().Equal(res.Coins, coins) + // after the current epoch ends, mint more coins that matches the lock coin demon created earlier epochIdentifier := suite.App.MintKeeper.GetParams(suite.Ctx).EpochIdentifier curEpochNumber := suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, epochIdentifier).CurrentEpoch suite.App.EpochsKeeper.AfterEpochEnd(suite.Ctx, epochIdentifier, curEpochNumber) // TODO: Figure out what this number should be + // TODO: Respond to this mintCoins := sdk.NewCoin(coins[0].Denom, sdk.NewInt(1500000)) + // query the rewards of the new address after the 10th epoch + // since it is the only address the gauge is paying out to, the future rewards should equal the entirety of the gauge plus the newly minted coins res, err = suite.querier.RewardsEst(sdk.WrapSDKContext(suite.Ctx), &types.RewardsEstRequest{ Owner: lockOwner.String(), EndEpoch: 10, @@ -361,30 +402,30 @@ func (suite *KeeperTestSuite) TestRewardsEstWithPoolIncentives() { suite.Require().Equal(res.Coins, coins.Add(mintCoins)) } -// TODO: make this test table driven, or simpler -// I have no idea at a glance what its doing. +// TestGRPCToDistributeCoins tests querying coins that are going to be distributed via gRPC returns the correct response. func (suite *KeeperTestSuite) TestGRPCToDistributeCoins() { suite.SetupTest() - // initial check + // ensure initially querying to distribute coins returns no coins res, err := suite.querier.ModuleToDistributeCoins(sdk.WrapSDKContext(suite.Ctx), &types.ModuleToDistributeCoinsRequest{}) suite.Require().NoError(err) suite.Require().Equal(res.Coins, sdk.Coins(nil)) - // create locks + // create two locks with different durations addr1 := sdk.AccAddress([]byte("addr1---------------")) addr2 := sdk.AccAddress([]byte("addr2---------------")) suite.LockTokens(addr1, sdk.Coins{sdk.NewInt64Coin("lptoken", 10)}, time.Second) suite.LockTokens(addr2, sdk.Coins{sdk.NewInt64Coin("lptoken", 10)}, 2*time.Second) - // setup a gauge + // setup a non perpetual gauge gaugeID, _, coins, startTime := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) gauge, err := suite.querier.GetGaugeByID(suite.Ctx, gaugeID) suite.Require().NoError(err) suite.Require().NotNil(gauge) gauges := []types.Gauge{*gauge} - // check after gauge creation + // check to distribute coins after gauge creation + // ensure this equals the coins within the previously created non perpetual gauge res, err = suite.querier.ModuleToDistributeCoins(sdk.WrapSDKContext(suite.Ctx), &types.ModuleToDistributeCoinsRequest{}) suite.Require().NoError(err) suite.Require().Equal(res.Coins, coins) @@ -395,6 +436,8 @@ func (suite *KeeperTestSuite) TestGRPCToDistributeCoins() { suite.Require().Equal(distrCoins, sdk.Coins{sdk.NewInt64Coin("stake", 4)}) // check gauge changes after distribution + // ensure the gauge's filled epochs have been increased by 1 + // ensure we have distributed 4 out of the 10 stake tokens gauge, err = suite.querier.GetGaugeByID(suite.Ctx, gaugeID) suite.Require().NoError(err) suite.Require().NotNil(gauge) @@ -402,12 +445,12 @@ func (suite *KeeperTestSuite) TestGRPCToDistributeCoins() { suite.Require().Equal(gauge.DistributedCoins, sdk.Coins{sdk.NewInt64Coin("stake", 4)}) gauges = []types.Gauge{*gauge} - // start distribution + // move gauge from an upcoming to an active status suite.Ctx = suite.Ctx.WithBlockTime(startTime) err = suite.querier.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) suite.Require().NoError(err) - // check after distribution + // check that the to distribute coins is equal to the initial gauge coin balance minus what has been distributed already (10-4=6) res, err = suite.querier.ModuleToDistributeCoins(sdk.WrapSDKContext(suite.Ctx), &types.ModuleToDistributeCoinsRequest{}) suite.Require().NoError(err) suite.Require().Equal(res.Coins, coins.Sub(distrCoins)) @@ -417,39 +460,41 @@ func (suite *KeeperTestSuite) TestGRPCToDistributeCoins() { suite.Require().NoError(err) suite.Require().Equal(sdk.Coins{sdk.NewInt64Coin("stake", 6)}, distrCoins) - // final check + // now that all coins have been distributed (4 in first found 6 in the second round) + // to distribute coins should be null res, err = suite.querier.ModuleToDistributeCoins(sdk.WrapSDKContext(suite.Ctx), &types.ModuleToDistributeCoinsRequest{}) suite.Require().NoError(err) suite.Require().Equal(res.Coins, sdk.Coins(nil)) } +// TestGRPCDistributedCoins tests querying coins that have been distributed via gRPC returns the correct response. func (suite *KeeperTestSuite) TestGRPCDistributedCoins() { suite.SetupTest() - // initial check + // ensure initially querying distributed coins returns no coins res, err := suite.querier.ModuleDistributedCoins(sdk.WrapSDKContext(suite.Ctx), &types.ModuleDistributedCoinsRequest{}) suite.Require().NoError(err) suite.Require().Equal(res.Coins, sdk.Coins(nil)) - // create locks + // create two locks with different durations addr1 := sdk.AccAddress([]byte("addr1---------------")) addr2 := sdk.AccAddress([]byte("addr2---------------")) suite.LockTokens(addr1, sdk.Coins{sdk.NewInt64Coin("lptoken", 10)}, time.Second) suite.LockTokens(addr2, sdk.Coins{sdk.NewInt64Coin("lptoken", 10)}, 2*time.Second) - // setup a gauge + // setup a non perpetual gauge gaugeID, _, coins, startTime := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) gauge, err := suite.querier.GetGaugeByID(suite.Ctx, gaugeID) suite.Require().NoError(err) suite.Require().NotNil(gauge) gauges := []types.Gauge{*gauge} - // check after gauge creation + // check that after gauge creation distributed coins still returns no coins res, err = suite.querier.ModuleDistributedCoins(sdk.WrapSDKContext(suite.Ctx), &types.ModuleDistributedCoinsRequest{}) suite.Require().NoError(err) suite.Require().Equal(res.Coins, sdk.Coins(nil)) - // start distribution + // move gauge from upcoming to active suite.Ctx = suite.Ctx.WithBlockTime(startTime) err = suite.querier.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) suite.Require().NoError(err) @@ -460,6 +505,8 @@ func (suite *KeeperTestSuite) TestGRPCDistributedCoins() { suite.Require().Equal(distrCoins, sdk.Coins{sdk.NewInt64Coin("stake", 4)}) // check gauge changes after distribution + // ensure the gauge's filled epochs have been increased by 1 + // ensure we have distributed 4 out of the 10 stake tokens gauge, err = suite.querier.GetGaugeByID(suite.Ctx, gaugeID) suite.Require().NoError(err) suite.Require().NotNil(gauge) @@ -467,7 +514,7 @@ func (suite *KeeperTestSuite) TestGRPCDistributedCoins() { suite.Require().Equal(gauge.DistributedCoins, sdk.Coins{sdk.NewInt64Coin("stake", 4)}) gauges = []types.Gauge{*gauge} - // check after distribution + // check after distribution that distributed coins query matches coins that were distributed res, err = suite.querier.ModuleDistributedCoins(sdk.WrapSDKContext(suite.Ctx), &types.ModuleDistributedCoinsRequest{}) suite.Require().NoError(err) suite.Require().Equal(res.Coins, distrCoins) @@ -477,7 +524,7 @@ func (suite *KeeperTestSuite) TestGRPCDistributedCoins() { suite.Require().NoError(err) suite.Require().Equal(sdk.Coins{sdk.NewInt64Coin("stake", 6)}, distrCoins) - // final check + // ensure distributed coins query equals coins balance of gauge now that it has been completed res, err = suite.querier.ModuleDistributedCoins(sdk.WrapSDKContext(suite.Ctx), &types.ModuleDistributedCoinsRequest{}) suite.Require().NoError(err) suite.Require().Equal(res.Coins, coins) diff --git a/x/incentives/keeper/keeper_test.go b/x/incentives/keeper/keeper_test.go index f881a6829e4..3b4d80b81b1 100644 --- a/x/incentives/keeper/keeper_test.go +++ b/x/incentives/keeper/keeper_test.go @@ -16,11 +16,10 @@ type KeeperTestSuite struct { querier keeper.Querier } +// SetupTest sets incentives parameters from the suite's context func (suite *KeeperTestSuite) SetupTest() { suite.Setup() - suite.querier = keeper.NewQuerier(*suite.App.IncentivesKeeper) - lockableDurations := suite.App.IncentivesKeeper.GetLockableDurations(suite.Ctx) lockableDurations = append(lockableDurations, 2*time.Second) suite.App.IncentivesKeeper.SetLockableDurations(suite.Ctx, lockableDurations) diff --git a/x/incentives/keeper/store_test.go b/x/incentives/keeper/store_test.go index 5490755a2ec..2765181a973 100644 --- a/x/incentives/keeper/store_test.go +++ b/x/incentives/keeper/store_test.go @@ -1,24 +1,35 @@ package keeper_test +import "github.com/stretchr/testify/suite" + func (suite *KeeperTestSuite) TestGaugeReferencesManagement() { key1 := []byte{0x11} key2 := []byte{0x12} suite.SetupTest() + + // set two gauge references to key 1 and three gauge references to key 2 _ = suite.App.IncentivesKeeper.AddGaugeRefByKey(suite.Ctx, key1, 1) _ = suite.App.IncentivesKeeper.AddGaugeRefByKey(suite.Ctx, key2, 1) _ = suite.App.IncentivesKeeper.AddGaugeRefByKey(suite.Ctx, key1, 2) _ = suite.App.IncentivesKeeper.AddGaugeRefByKey(suite.Ctx, key2, 2) _ = suite.App.IncentivesKeeper.AddGaugeRefByKey(suite.Ctx, key2, 3) + // ensure key1 only has 2 entires gaugeRefs1 := suite.App.IncentivesKeeper.GetGaugeRefs(suite.Ctx, key1) suite.Require().Equal(len(gaugeRefs1), 2) + + // ensure key2 only has 3 entries gaugeRefs2 := suite.App.IncentivesKeeper.GetGaugeRefs(suite.Ctx, key2) suite.Require().Equal(len(gaugeRefs2), 3) + // remove gauge 1 from key2, resulting in a reduction from 3 to 2 entries err := suite.App.IncentivesKeeper.DeleteGaugeRefByKey(suite.Ctx, key2, 1) suite.Require().NoError(err) + // ensure key2 now only has 2 entires gaugeRefs3 := suite.App.IncentivesKeeper.GetGaugeRefs(suite.Ctx, key2) suite.Require().Equal(len(gaugeRefs3), 2) } + +var _ = suite.TestingSuite(nil) diff --git a/x/incentives/keeper/suite_test.go b/x/incentives/keeper/suite_test.go index 820076ab313..19c56893e75 100644 --- a/x/incentives/keeper/suite_test.go +++ b/x/incentives/keeper/suite_test.go @@ -12,18 +12,33 @@ import ( ) var ( - defaultLPDenom string = "lptoken" - defaultLPTokens sdk.Coins = sdk.Coins{sdk.NewInt64Coin(defaultLPDenom, 10)} - defaultLiquidTokens sdk.Coins = sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} - defaultLockDuration time.Duration = time.Second - oneLockupUser userLocks = userLocks{ + defaultLPDenom string = "lptoken" + defaultLPSyntheticDenom string = "lptoken/superbonding" + defaultLPTokens sdk.Coins = sdk.Coins{sdk.NewInt64Coin(defaultLPDenom, 10)} + defaultLPSyntheticTokens sdk.Coins = sdk.Coins{sdk.NewInt64Coin(defaultLPSyntheticDenom, 10)} + defaultLiquidTokens sdk.Coins = sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} + defaultLockDuration time.Duration = time.Second + oneLockupUser userLocks = userLocks{ lockDurations: []time.Duration{time.Second}, lockAmounts: []sdk.Coins{defaultLPTokens}, } + twoLockupUser userLocks = userLocks{ + lockDurations: []time.Duration{defaultLockDuration, 2 * defaultLockDuration}, + lockAmounts: []sdk.Coins{defaultLPTokens, defaultLPTokens}, + } + oneSyntheticLockupUser userLocks = userLocks{ + lockDurations: []time.Duration{time.Second}, + lockAmounts: []sdk.Coins{defaultLPSyntheticTokens}, + } + twoSyntheticLockupUser userLocks = userLocks{ + lockDurations: []time.Duration{defaultLockDuration, 2 * defaultLockDuration}, + lockAmounts: []sdk.Coins{defaultLPSyntheticTokens, defaultLPSyntheticTokens}, + } defaultRewardDenom string = "rewardDenom" ) // TODO: Switch more code to use userLocks and perpGaugeDesc +// TODO: Create issue for the above. type userLocks struct { lockDurations []time.Duration lockAmounts []sdk.Coins @@ -35,7 +50,8 @@ type perpGaugeDesc struct { rewardAmount sdk.Coins } -// Leave prefix blank if lazy, it'll be replaced with something random +// setupAddr takes a balance, prefix, and address number. Then returns the respective account address byte array. +// If prefix is left blank, it will be replaced with a random prefix. func (suite *KeeperTestSuite) setupAddr(addrNum int, prefix string, balance sdk.Coins) sdk.AccAddress { if prefix == "" { prefixBz := make([]byte, 8) @@ -50,6 +66,7 @@ func (suite *KeeperTestSuite) setupAddr(addrNum int, prefix string, balance sdk. return addr } +// SetupUserLocks takes an array of user locks, creates locks based on this array, then returns the respective array of accounts. func (suite *KeeperTestSuite) SetupUserLocks(users []userLocks) (accs []sdk.AccAddress) { accs = make([]sdk.AccAddress, len(users)) for i, user := range users { @@ -68,16 +85,40 @@ func (suite *KeeperTestSuite) SetupUserLocks(users []userLocks) (accs []sdk.AccA return } -func (suite *KeeperTestSuite) SetupGauges(gaugeDescriptors []perpGaugeDesc) []types.Gauge { +// SetupUserSyntheticLocks takes an array of user locks and creates synthetic locks based on this array, then returns the respective account address byte array. +func (suite *KeeperTestSuite) SetupUserSyntheticLocks(users []userLocks) (accs []sdk.AccAddress) { + accs = make([]sdk.AccAddress, len(users)) + coins := sdk.Coins{sdk.NewInt64Coin("lptoken", 10)} + lockupID := uint64(1) + for i, user := range users { + suite.Assert().Equal(len(user.lockDurations), len(user.lockAmounts)) + totalLockAmt := user.lockAmounts[0] + for j := 1; j < len(user.lockAmounts); j++ { + totalLockAmt = totalLockAmt.Add(user.lockAmounts[j]...) + } + accs[i] = suite.setupAddr(i, "", totalLockAmt) + for j := 0; j < len(user.lockAmounts); j++ { + suite.LockTokens(accs[i], coins, user.lockDurations[j]) + err := suite.App.LockupKeeper.CreateSyntheticLockup(suite.Ctx, lockupID, "lptoken/superbonding", user.lockDurations[j], false) + lockupID++ + suite.Require().NoError(err) + } + } + return +} + +// SetupGauges takes an array of perpGaugeDesc structs. Then returns the corresponding array of Gauge structs. +func (suite *KeeperTestSuite) SetupGauges(gaugeDescriptors []perpGaugeDesc, denom string) []types.Gauge { gauges := make([]types.Gauge, len(gaugeDescriptors)) perpetual := true for i, desc := range gaugeDescriptors { - _, gaugePtr, _, _ := suite.setupNewGaugeWithDuration(perpetual, desc.rewardAmount, desc.lockDuration) + _, gaugePtr, _, _ := suite.setupNewGaugeWithDuration(perpetual, desc.rewardAmount, desc.lockDuration, denom) gauges[i] = *gaugePtr } return gauges } +// CreateGauge creates a gauge struct given the required params. func (suite *KeeperTestSuite) CreateGauge(isPerpetual bool, addr sdk.AccAddress, coins sdk.Coins, distrTo lockuptypes.QueryCondition, startTime time.Time, numEpoch uint64) (uint64, *types.Gauge) { suite.FundAcc(addr, coins) gaugeID, err := suite.App.IncentivesKeeper.CreateGauge(suite.Ctx, isPerpetual, addr, coins, distrTo, startTime, numEpoch) @@ -87,6 +128,7 @@ func (suite *KeeperTestSuite) CreateGauge(isPerpetual bool, addr sdk.AccAddress, return gaugeID, gauge } +// AddToGauge adds coins to the specified gauge. func (suite *KeeperTestSuite) AddToGauge(coins sdk.Coins, gaugeID uint64) uint64 { addr := sdk.AccAddress([]byte("addrx---------------")) suite.FundAcc(addr, coins) @@ -95,20 +137,22 @@ func (suite *KeeperTestSuite) AddToGauge(coins sdk.Coins, gaugeID uint64) uint64 return gaugeID } +// LockTokens locks tokens for the specified duration func (suite *KeeperTestSuite) LockTokens(addr sdk.AccAddress, coins sdk.Coins, duration time.Duration) { suite.FundAcc(addr, coins) _, err := suite.App.LockupKeeper.CreateLock(suite.Ctx, addr, coins, duration) suite.Require().NoError(err) } -func (suite *KeeperTestSuite) setupNewGaugeWithDuration(isPerpetual bool, coins sdk.Coins, duration time.Duration) ( +// setupNewGaugeWithDuration creates a gauge with the specified duration. +func (suite *KeeperTestSuite) setupNewGaugeWithDuration(isPerpetual bool, coins sdk.Coins, duration time.Duration, denom string) ( uint64, *types.Gauge, sdk.Coins, time.Time, ) { addr := sdk.AccAddress([]byte("Gauge_Creation_Addr_")) startTime2 := time.Now() distrTo := lockuptypes.QueryCondition{ LockQueryType: lockuptypes.ByDuration, - Denom: "lptoken", + Denom: denom, Duration: duration, } @@ -124,11 +168,12 @@ func (suite *KeeperTestSuite) setupNewGaugeWithDuration(isPerpetual bool, coins return gaugeID, gauge, coins, startTime2 } -// TODO: Delete all usages of this method +// SetupNewGauge creates a gauge with the default lock duration. func (suite *KeeperTestSuite) SetupNewGauge(isPerpetual bool, coins sdk.Coins) (uint64, *types.Gauge, sdk.Coins, time.Time) { - return suite.setupNewGaugeWithDuration(isPerpetual, coins, defaultLockDuration) + return suite.setupNewGaugeWithDuration(isPerpetual, coins, defaultLockDuration, "lptoken") } +// setupNewGaugeWithDenom creates a gauge with the specified duration and denom. func (suite *KeeperTestSuite) setupNewGaugeWithDenom(isPerpetual bool, coins sdk.Coins, duration time.Duration, denom string) ( uint64, *types.Gauge, sdk.Coins, time.Time, ) { @@ -152,10 +197,12 @@ func (suite *KeeperTestSuite) setupNewGaugeWithDenom(isPerpetual bool, coins sdk return gaugeID, gauge, coins, startTime2 } +// SetupNewGaugeWithDenom creates a gauge with the specified duration and denom. func (suite *KeeperTestSuite) SetupNewGaugeWithDenom(isPerpetual bool, coins sdk.Coins, denom string) (uint64, *types.Gauge, sdk.Coins, time.Time) { return suite.setupNewGaugeWithDenom(isPerpetual, coins, defaultLockDuration, denom) } +// SetupManyLocks creates as many locks as the user defines. func (suite *KeeperTestSuite) SetupManyLocks(numLocks int, liquidBalance sdk.Coins, coinsPerLock sdk.Coins, lockDuration time.Duration, ) []sdk.AccAddress { @@ -173,6 +220,7 @@ func (suite *KeeperTestSuite) SetupManyLocks(numLocks int, liquidBalance sdk.Coi return addrs } +// SetupLockAndGauge creates both a lock and a gauge. func (suite *KeeperTestSuite) SetupLockAndGauge(isPerpetual bool) (sdk.AccAddress, uint64, sdk.Coins, time.Time) { // create a gauge and locks lockOwner := sdk.AccAddress([]byte("addr1---------------")) diff --git a/x/incentives/keeper/utils_test.go b/x/incentives/keeper/utils_test.go index 36f781fa961..c316e73724b 100644 --- a/x/incentives/keeper/utils_test.go +++ b/x/incentives/keeper/utils_test.go @@ -5,18 +5,26 @@ import ( "testing" "time" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" "github.com/stretchr/testify/require" + "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestCombineKeys(t *testing.T) { + // create three keys, each different byte arrays key1 := []byte{0x11} key2 := []byte{0x12} key3 := []byte{0x13} + + // combine the three keys into a single key key := combineKeys(key1, key2, key3) - require.Len(t, key, 3+2) // 2 is separator + + // three keys plus two separators is equal to a length of 5 + require.Len(t, key, 3+2) + + // ensure the newly created key is made up of the three previous keys (and the two key index separators) require.Equal(t, key[0], key1[0]) require.Equal(t, key[1], types.KeyIndexSeparator[0]) require.Equal(t, key[2], key2[0]) @@ -25,7 +33,11 @@ func TestCombineKeys(t *testing.T) { } func TestFindIndex(t *testing.T) { + // create an array of 5 IDs IDs := []uint64{1, 2, 3, 4, 5} + + // use the findIndex function to find the index of the respective IDs + // if it doesn't exist, return -1 require.Equal(t, findIndex(IDs, 1), 0) require.Equal(t, findIndex(IDs, 3), 2) require.Equal(t, findIndex(IDs, 5), 4) @@ -33,7 +45,11 @@ func TestFindIndex(t *testing.T) { } func TestRemoveValue(t *testing.T) { + // create an array of 5 IDs IDs := []uint64{1, 2, 3, 4, 5} + + // remove an ID + // ensure if ID exists, the length is reduced by one and the index of the removed ID is returned IDs, index1 := removeValue(IDs, 5) require.Len(t, IDs, 4) require.Equal(t, index1, 4) From 938f9bdb4ce05e178340b63c25452505ff7c6a3d Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sun, 10 Jul 2022 11:30:00 -0500 Subject: [PATCH 049/376] =?UTF-8?q?Fix=20Initgenesis=20bug=20in=20tokenfac?= =?UTF-8?q?tory,=20when=20the=20denom=20creation=20fee=20para=E2=80=A6=20(?= =?UTF-8?q?#2011)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix Initgenesis bug in tokenfactory, when the denom creation fee param is set * Add more to genesis test that would've caught this * Update changelog * Fix remaining bug adam pointed out * Make test account for this * Update code comment --- .gitignore | 2 + CHANGELOG.md | 2 + x/tokenfactory/keeper/createdenom.go | 64 ++++++++++++++++------- x/tokenfactory/keeper/createdenom_test.go | 2 - x/tokenfactory/keeper/genesis.go | 4 +- x/tokenfactory/keeper/genesis_test.go | 38 ++++++++------ x/tokenfactory/types/errors.go | 2 +- 7 files changed, 74 insertions(+), 40 deletions(-) diff --git a/.gitignore b/.gitignore index 1e05d8c9fa4..445b336984d 100644 --- a/.gitignore +++ b/.gitignore @@ -202,3 +202,5 @@ $RECYCLE.BIN/ /x/incentives/keeper/osmosis_testing/ tools-stamp /tests/localosmosis/.osmosisd/* +*.save +*.save.* diff --git a/CHANGELOG.md b/CHANGELOG.md index 23ae5527ddb..b7e31401dab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,6 +78,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [1759](https://github.com/osmosis-labs/osmosis/pull/1759) Fix pagination filter in incentives query. * [1698](https://github.com/osmosis-labs/osmosis/pull/1698) Register wasm snapshotter extension. * [1931](https://github.com/osmosis-labs/osmosis/pull/1931) Add explicit check for input denoms to `CalcJoinPoolShares` +* [2011](https://github.com/osmosis-labs/osmosis/pull/2011) Fix bug in TokenFactory initGenesis, relating to denom creation fee param. + ## [v9.0.0 - Nitrogen](https://github.com/osmosis-labs/osmosis/releases/tag/v9.0.0) diff --git a/x/tokenfactory/keeper/createdenom.go b/x/tokenfactory/keeper/createdenom.go index f09181d4572..89658322d58 100644 --- a/x/tokenfactory/keeper/createdenom.go +++ b/x/tokenfactory/keeper/createdenom.go @@ -11,34 +11,23 @@ import ( // ConvertToBaseToken converts a fee amount in a whitelisted fee token to the base fee token amount func (k Keeper) CreateDenom(ctx sdk.Context, creatorAddr string, subdenom string) (newTokenDenom string, err error) { - // Temporary check until IBC bug is sorted out - if k.bankKeeper.HasSupply(ctx, subdenom) { - return "", fmt.Errorf("temporary error until IBC bug is sorted out, " + - "can't create subdenoms that are the same as a native denom") - } - - // Send creation fee to community pool - creationFee := k.GetParams(ctx).DenomCreationFee - accAddr, err := sdk.AccAddressFromBech32(creatorAddr) + err = k.chargeForCreateDenom(ctx, creatorAddr, subdenom) if err != nil { return "", err } - if len(creationFee) > 0 { - if err := k.distrKeeper.FundCommunityPool(ctx, creationFee, accAddr); err != nil { - return "", err - } - } - denom, err := types.GetTokenDenom(creatorAddr, subdenom) + denom, err := k.validateCreateDenom(ctx, creatorAddr, subdenom) if err != nil { return "", err } - _, found := k.bankKeeper.GetDenomMetaData(ctx, denom) - if found { - return "", types.ErrDenomExists - } + err = k.createDenomAfterValidation(ctx, creatorAddr, denom) + return denom, err +} +// Runs CreateDenom logic after the charge and all denom validation has been handled. +// Made into a second function for genesis initialization. +func (k Keeper) createDenomAfterValidation(ctx sdk.Context, creatorAddr string, denom string) (err error) { denomMetaData := banktypes.Metadata{ DenomUnits: []*banktypes.DenomUnit{{ Denom: denom, @@ -54,9 +43,44 @@ func (k Keeper) CreateDenom(ctx sdk.Context, creatorAddr string, subdenom string } err = k.setAuthorityMetadata(ctx, denom, authorityMetadata) if err != nil { - return "", err + return err } k.addDenomFromCreator(ctx, creatorAddr, denom) + return nil +} + +func (k Keeper) validateCreateDenom(ctx sdk.Context, creatorAddr string, subdenom string) (newTokenDenom string, err error) { + // Temporary check until IBC bug is sorted out + if k.bankKeeper.HasSupply(ctx, subdenom) { + return "", fmt.Errorf("temporary error until IBC bug is sorted out, " + + "can't create subdenoms that are the same as a native denom") + } + + denom, err := types.GetTokenDenom(creatorAddr, subdenom) + if err != nil { + return "", err + } + + _, found := k.bankKeeper.GetDenomMetaData(ctx, denom) + if found { + return "", types.ErrDenomExists + } + return denom, nil } + +func (k Keeper) chargeForCreateDenom(ctx sdk.Context, creatorAddr string, subdenom string) (err error) { + // Send creation fee to community pool + creationFee := k.GetParams(ctx).DenomCreationFee + accAddr, err := sdk.AccAddressFromBech32(creatorAddr) + if err != nil { + return err + } + if len(creationFee) > 0 { + if err := k.distrKeeper.FundCommunityPool(ctx, creationFee, accAddr); err != nil { + return err + } + } + return nil +} diff --git a/x/tokenfactory/keeper/createdenom_test.go b/x/tokenfactory/keeper/createdenom_test.go index 77696ed7afb..64179a3972b 100644 --- a/x/tokenfactory/keeper/createdenom_test.go +++ b/x/tokenfactory/keeper/createdenom_test.go @@ -5,7 +5,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/keeper" "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" ) @@ -90,7 +89,6 @@ func (suite *KeeperTestSuite) TestCreateDenom() { }, } { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { - suite.msgServer = keeper.NewMsgServerImpl(*suite.App.TokenFactoryKeeper) if tc.setup != nil { tc.setup() } diff --git a/x/tokenfactory/keeper/genesis.go b/x/tokenfactory/keeper/genesis.go index 6dde765c279..c87cfa94743 100644 --- a/x/tokenfactory/keeper/genesis.go +++ b/x/tokenfactory/keeper/genesis.go @@ -17,11 +17,11 @@ func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { k.SetParams(ctx, genState.Params) for _, genDenom := range genState.GetFactoryDenoms() { - creator, subdenom, err := types.DeconstructDenom(genDenom.GetDenom()) + creator, _, err := types.DeconstructDenom(genDenom.GetDenom()) if err != nil { panic(err) } - _, err = k.CreateDenom(ctx, creator, subdenom) + err = k.createDenomAfterValidation(ctx, creator, genDenom.GetDenom()) if err != nil { panic(err) } diff --git a/x/tokenfactory/keeper/genesis_test.go b/x/tokenfactory/keeper/genesis_test.go index 870da69c390..2e99a6c0a11 100644 --- a/x/tokenfactory/keeper/genesis_test.go +++ b/x/tokenfactory/keeper/genesis_test.go @@ -1,20 +1,14 @@ package keeper_test import ( - "testing" - - "github.com/stretchr/testify/require" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - simapp "github.com/osmosis-labs/osmosis/v7/app" - appparams "github.com/osmosis-labs/osmosis/v7/app/params" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" ) -func TestGenesis(t *testing.T) { - appparams.SetAddressPrefixes() - +func (suite *KeeperTestSuite) TestGenesis() { genesisState := types.GenesisState{ FactoryDenoms: []types.GenesisDenom{ { @@ -23,6 +17,12 @@ func TestGenesis(t *testing.T) { Admin: "osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44", }, }, + { + Denom: "factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/diff-admin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "osmo15czt5nhlnvayqq37xun9s9yus0d6y26dw9xnzn", + }, + }, { Denom: "factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/litecoin", AuthorityMetadata: types.DenomAuthorityMetadata{ @@ -31,11 +31,19 @@ func TestGenesis(t *testing.T) { }, }, } - app := simapp.Setup(false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + app := suite.App + suite.Ctx = app.BaseApp.NewContext(false, tmproto.Header{}) + // Test both with bank denom metadata set, and not set. + for i, denom := range genesisState.FactoryDenoms { + // hacky, sets bank metadata to exist if i != 0, to cover both cases. + if i != 0 { + app.BankKeeper.SetDenomMetaData(suite.Ctx, banktypes.Metadata{Base: denom.GetDenom()}) + } + } - app.TokenFactoryKeeper.InitGenesis(ctx, genesisState) - exportedGenesis := app.TokenFactoryKeeper.ExportGenesis(ctx) - require.NotNil(t, exportedGenesis) - require.Equal(t, genesisState, *exportedGenesis) + app.TokenFactoryKeeper.SetParams(suite.Ctx, types.Params{DenomCreationFee: sdk.Coins{sdk.NewInt64Coin("uosmo", 100)}}) + app.TokenFactoryKeeper.InitGenesis(suite.Ctx, genesisState) + exportedGenesis := app.TokenFactoryKeeper.ExportGenesis(suite.Ctx) + suite.Require().NotNil(exportedGenesis) + suite.Require().Equal(genesisState, *exportedGenesis) } diff --git a/x/tokenfactory/types/errors.go b/x/tokenfactory/types/errors.go index db1552e8f2d..06991f19b91 100644 --- a/x/tokenfactory/types/errors.go +++ b/x/tokenfactory/types/errors.go @@ -10,7 +10,7 @@ import ( // x/tokenfactory module sentinel errors var ( - ErrDenomExists = sdkerrors.Register(ModuleName, 2, "denom already exists") + ErrDenomExists = sdkerrors.Register(ModuleName, 2, "attempting to create a denom that already exists (has bank metadata)") ErrUnauthorized = sdkerrors.Register(ModuleName, 3, "unauthorized account") ErrInvalidDenom = sdkerrors.Register(ModuleName, 4, "invalid denom") ErrInvalidCreator = sdkerrors.Register(ModuleName, 5, "invalid creator") From 23dbaddfe9a458c8bec5c10d2a9dfa750c28f285 Mon Sep 17 00:00:00 2001 From: khanh <50263489+catShaark@users.noreply.github.com> Date: Mon, 11 Jul 2022 11:07:26 +0700 Subject: [PATCH 050/376] improve getToDistributedCoinsFromGauges (#2014) * mod getToDistributedCoinsFromGauges * mod getToDistributedCoinsFromGauges * rm unused function --- x/incentives/keeper/distribute.go | 11 ++++++++--- x/incentives/keeper/gauge.go | 9 --------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/x/incentives/keeper/distribute.go b/x/incentives/keeper/distribute.go index 2442bfc4687..1fcfe5215ed 100644 --- a/x/incentives/keeper/distribute.go +++ b/x/incentives/keeper/distribute.go @@ -21,9 +21,14 @@ func (k Keeper) getDistributedCoinsFromGauges(gauges []types.Gauge) sdk.Coins { } func (k Keeper) getToDistributeCoinsFromGauges(gauges []types.Gauge) sdk.Coins { - // TODO: Consider optimizing this in the future to only require one iteration over all gauges. - coins := k.getCoinsFromGauges(gauges) - distributed := k.getDistributedCoinsFromGauges(gauges) + coins := sdk.Coins{} + distributed := sdk.Coins{} + + for _, gauge := range gauges { + coins = coins.Add(gauge.Coins...) + distributed = distributed.Add(gauge.DistributedCoins...) + } + return coins.Sub(distributed) } diff --git a/x/incentives/keeper/gauge.go b/x/incentives/keeper/gauge.go index 59bc7436dc2..8dfe12d1ac7 100644 --- a/x/incentives/keeper/gauge.go +++ b/x/incentives/keeper/gauge.go @@ -38,15 +38,6 @@ func (k Keeper) getGaugesFromIterator(ctx sdk.Context, iterator db.Iterator) []t return gauges } -// Compute the total amount of coins in all the gauges. -func (k Keeper) getCoinsFromGauges(gauges []types.Gauge) sdk.Coins { - coins := sdk.Coins{} - for _, gauge := range gauges { - coins = coins.Add(gauge.Coins...) - } - return coins -} - // setGauge set the gauge inside store. func (k Keeper) setGauge(ctx sdk.Context, gauge *types.Gauge) error { store := ctx.KVStore(k.storeKey) From ff74d62019c5a4e7bf6f84007bf4e8b6be0324c8 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Mon, 11 Jul 2022 09:33:20 -0500 Subject: [PATCH 051/376] x/superfluid: no delegation distribution info (#2010) --- x/superfluid/keeper/epoch.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/x/superfluid/keeper/epoch.go b/x/superfluid/keeper/epoch.go index 77a63e06e1b..a1146131c63 100644 --- a/x/superfluid/keeper/epoch.go +++ b/x/superfluid/keeper/epoch.go @@ -5,6 +5,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" + distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/osmosis-labs/osmosis/v7/osmoutils" gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" @@ -61,6 +63,10 @@ func (k Keeper) MoveSuperfluidDelegationRewardToGauges(ctx sdk.Context) { // we use cacheCtx and apply the changes later _ = osmoutils.ApplyFuncIfNoError(ctx, func(cacheCtx sdk.Context) error { _, err := k.dk.WithdrawDelegationRewards(cacheCtx, addr, valAddr) + if errors.Is(err, distributiontypes.ErrEmptyDelegationDistInfo) { + ctx.Logger().Debug("no swaps occurred in this pool between last epoch and this epoch") + return nil + } return err }) From 522ddf9c3c6e6a3404ae3be00cfe3e028d515d1a Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Mon, 11 Jul 2022 09:59:33 -0700 Subject: [PATCH 052/376] add suite run to many tests (#2012) --- tests/e2e/initialization/init_test.go | 8 +- x/gamm/keeper/multihop_test.go | 218 +++++++++--------- x/gamm/keeper/pool_service_test.go | 40 ++-- .../pool-models/balancer/pool_suite_test.go | 49 ++-- x/gamm/twap/module.go | 2 + x/gamm/twap/types/keys.go | 4 +- x/txfees/keeper/feedecorator_test.go | 107 ++++----- x/txfees/keeper/feetokens_test.go | 109 ++++----- 8 files changed, 273 insertions(+), 264 deletions(-) diff --git a/tests/e2e/initialization/init_test.go b/tests/e2e/initialization/init_test.go index aaa67283a55..926ef9950d8 100644 --- a/tests/e2e/initialization/init_test.go +++ b/tests/e2e/initialization/init_test.go @@ -15,11 +15,9 @@ import ( const forkHeight = 10 -var ( - expectedConfigFiles = []string{ - "app.toml", "config.toml", "genesis.json", "node_key.json", "priv_validator_key.json", - } -) +var expectedConfigFiles = []string{ + "app.toml", "config.toml", "genesis.json", "node_key.json", "priv_validator_key.json", +} // TestChainInit tests that chain initialization correctly initializes a full chain // and produces the desired output with genesis, chain and validator configs. diff --git a/x/gamm/keeper/multihop_test.go b/x/gamm/keeper/multihop_test.go index 17ce0421e42..e92ee724e19 100644 --- a/x/gamm/keeper/multihop_test.go +++ b/x/gamm/keeper/multihop_test.go @@ -44,60 +44,62 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleMultihopSwapExactAmountIn() // Init suite for each test. suite.SetupTest() - // Prepare 2 pools - suite.PrepareBalancerPool() - suite.PrepareBalancerPool() - - keeper := suite.App.GAMMKeeper - - if test.expectPass { - // Calculate the chained spot price. - spotPriceBefore := func() sdk.Dec { - dec := sdk.NewDec(1) - tokenInDenom := test.param.tokenIn.Denom - for i, route := range test.param.routes { - if i != 0 { - tokenInDenom = test.param.routes[i-1].TokenOutDenom + suite.Run(test.name, func() { + // Prepare 2 pools + suite.PrepareBalancerPool() + suite.PrepareBalancerPool() + + keeper := suite.App.GAMMKeeper + + if test.expectPass { + // Calculate the chained spot price. + spotPriceBefore := func() sdk.Dec { + dec := sdk.NewDec(1) + tokenInDenom := test.param.tokenIn.Denom + for i, route := range test.param.routes { + if i != 0 { + tokenInDenom = test.param.routes[i-1].TokenOutDenom + } + pool, err := keeper.GetPoolAndPoke(suite.Ctx, route.PoolId) + suite.NoError(err, "test: %v", test.name) + + sp, err := pool.SpotPrice(suite.Ctx, tokenInDenom, route.TokenOutDenom) + suite.NoError(err, "test: %v", test.name) + dec = dec.Mul(sp) } - pool, err := keeper.GetPoolAndPoke(suite.Ctx, route.PoolId) - suite.NoError(err, "test: %v", test.name) - - sp, err := pool.SpotPrice(suite.Ctx, tokenInDenom, route.TokenOutDenom) - suite.NoError(err, "test: %v", test.name) - dec = dec.Mul(sp) - } - return dec - }() - - tokenOutAmount, err := keeper.MultihopSwapExactAmountIn(suite.Ctx, suite.TestAccs[0], test.param.routes, test.param.tokenIn, test.param.tokenOutMinAmount) - suite.NoError(err, "test: %v", test.name) - - // Calculate the chained spot price. - spotPriceAfter := func() sdk.Dec { - dec := sdk.NewDec(1) - tokenInDenom := test.param.tokenIn.Denom - for i, route := range test.param.routes { - if i != 0 { - tokenInDenom = test.param.routes[i-1].TokenOutDenom + return dec + }() + + tokenOutAmount, err := keeper.MultihopSwapExactAmountIn(suite.Ctx, suite.TestAccs[0], test.param.routes, test.param.tokenIn, test.param.tokenOutMinAmount) + suite.NoError(err, "test: %v", test.name) + + // Calculate the chained spot price. + spotPriceAfter := func() sdk.Dec { + dec := sdk.NewDec(1) + tokenInDenom := test.param.tokenIn.Denom + for i, route := range test.param.routes { + if i != 0 { + tokenInDenom = test.param.routes[i-1].TokenOutDenom + } + + pool, err := keeper.GetPoolAndPoke(suite.Ctx, route.PoolId) + suite.NoError(err, "test: %v", test.name) + + sp, err := pool.SpotPrice(suite.Ctx, tokenInDenom, route.TokenOutDenom) + suite.NoError(err, "test: %v", test.name) + dec = dec.Mul(sp) } - - pool, err := keeper.GetPoolAndPoke(suite.Ctx, route.PoolId) - suite.NoError(err, "test: %v", test.name) - - sp, err := pool.SpotPrice(suite.Ctx, tokenInDenom, route.TokenOutDenom) - suite.NoError(err, "test: %v", test.name) - dec = dec.Mul(sp) - } - return dec - }() - - // Ratio of the token out should be between the before spot price and after spot price. - sp := test.param.tokenIn.Amount.ToDec().Quo(tokenOutAmount.ToDec()) - suite.True(sp.GT(spotPriceBefore) && sp.LT(spotPriceAfter), "test: %v", test.name) - } else { - _, err := keeper.MultihopSwapExactAmountIn(suite.Ctx, suite.TestAccs[0], test.param.routes, test.param.tokenIn, test.param.tokenOutMinAmount) - suite.Error(err, "test: %v", test.name) - } + return dec + }() + + // Ratio of the token out should be between the before spot price and after spot price. + sp := test.param.tokenIn.Amount.ToDec().Quo(tokenOutAmount.ToDec()) + suite.True(sp.GT(spotPriceBefore) && sp.LT(spotPriceAfter), "test: %v", test.name) + } else { + _, err := keeper.MultihopSwapExactAmountIn(suite.Ctx, suite.TestAccs[0], test.param.routes, test.param.tokenIn, test.param.tokenOutMinAmount) + suite.Error(err, "test: %v", test.name) + } + }) } } @@ -137,62 +139,64 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleMultihopSwapExactAmountOut() // Init suite for each test. suite.SetupTest() - // Prepare 2 pools - suite.PrepareBalancerPool() - suite.PrepareBalancerPool() - - keeper := suite.App.GAMMKeeper - - if test.expectPass { - // Calculate the chained spot price. - spotPriceBefore := func() sdk.Dec { - dec := sdk.NewDec(1) - for i, route := range test.param.routes { - tokenOutDenom := test.param.tokenOut.Denom - if i != len(test.param.routes)-1 { - tokenOutDenom = test.param.routes[i+1].TokenInDenom + suite.Run(test.name, func() { + // Prepare 2 pools + suite.PrepareBalancerPool() + suite.PrepareBalancerPool() + + keeper := suite.App.GAMMKeeper + + if test.expectPass { + // Calculate the chained spot price. + spotPriceBefore := func() sdk.Dec { + dec := sdk.NewDec(1) + for i, route := range test.param.routes { + tokenOutDenom := test.param.tokenOut.Denom + if i != len(test.param.routes)-1 { + tokenOutDenom = test.param.routes[i+1].TokenInDenom + } + + pool, err := keeper.GetPoolAndPoke(suite.Ctx, route.PoolId) + suite.NoError(err, "test: %v", test.name) + + sp, err := pool.SpotPrice(suite.Ctx, route.TokenInDenom, tokenOutDenom) + suite.NoError(err, "test: %v", test.name) + dec = dec.Mul(sp) } - - pool, err := keeper.GetPoolAndPoke(suite.Ctx, route.PoolId) - suite.NoError(err, "test: %v", test.name) - - sp, err := pool.SpotPrice(suite.Ctx, route.TokenInDenom, tokenOutDenom) - suite.NoError(err, "test: %v", test.name) - dec = dec.Mul(sp) - } - return dec - }() - - tokenInAmount, err := keeper.MultihopSwapExactAmountOut(suite.Ctx, suite.TestAccs[0], test.param.routes, test.param.tokenInMaxAmount, test.param.tokenOut) - suite.Require().NoError(err, "test: %v", test.name) - - // Calculate the chained spot price. - spotPriceAfter := func() sdk.Dec { - dec := sdk.NewDec(1) - for i, route := range test.param.routes { - tokenOutDenom := test.param.tokenOut.Denom - if i != len(test.param.routes)-1 { - tokenOutDenom = test.param.routes[i+1].TokenInDenom + return dec + }() + + tokenInAmount, err := keeper.MultihopSwapExactAmountOut(suite.Ctx, suite.TestAccs[0], test.param.routes, test.param.tokenInMaxAmount, test.param.tokenOut) + suite.Require().NoError(err, "test: %v", test.name) + + // Calculate the chained spot price. + spotPriceAfter := func() sdk.Dec { + dec := sdk.NewDec(1) + for i, route := range test.param.routes { + tokenOutDenom := test.param.tokenOut.Denom + if i != len(test.param.routes)-1 { + tokenOutDenom = test.param.routes[i+1].TokenInDenom + } + + pool, err := keeper.GetPoolAndPoke(suite.Ctx, route.PoolId) + suite.NoError(err, "test: %v", test.name) + + sp, err := pool.SpotPrice(suite.Ctx, route.TokenInDenom, tokenOutDenom) + suite.NoError(err, "test: %v", test.name) + dec = dec.Mul(sp) } - - pool, err := keeper.GetPoolAndPoke(suite.Ctx, route.PoolId) - suite.NoError(err, "test: %v", test.name) - - sp, err := pool.SpotPrice(suite.Ctx, route.TokenInDenom, tokenOutDenom) - suite.NoError(err, "test: %v", test.name) - dec = dec.Mul(sp) - } - return dec - }() - - // Ratio of the token out should be between the before spot price and after spot price. - // This is because the swap increases the spot price - sp := tokenInAmount.ToDec().Quo(test.param.tokenOut.Amount.ToDec()) - fmt.Printf("spBefore %s, spAfter %s, sp actual %s\n", spotPriceBefore, spotPriceAfter, sp) - suite.True(sp.GT(spotPriceBefore) && sp.LT(spotPriceAfter), "multi-hop spot price wrong, test: %v", test.name) - } else { - _, err := keeper.MultihopSwapExactAmountOut(suite.Ctx, suite.TestAccs[0], test.param.routes, test.param.tokenInMaxAmount, test.param.tokenOut) - suite.Error(err, "test: %v", test.name) - } + return dec + }() + + // Ratio of the token out should be between the before spot price and after spot price. + // This is because the swap increases the spot price + sp := tokenInAmount.ToDec().Quo(test.param.tokenOut.Amount.ToDec()) + fmt.Printf("spBefore %s, spAfter %s, sp actual %s\n", spotPriceBefore, spotPriceAfter, sp) + suite.True(sp.GT(spotPriceBefore) && sp.LT(spotPriceAfter), "multi-hop spot price wrong, test: %v", test.name) + } else { + _, err := keeper.MultihopSwapExactAmountOut(suite.Ctx, suite.TestAccs[0], test.param.routes, test.param.tokenInMaxAmount, test.param.tokenOut) + suite.Error(err, "test: %v", test.name) + } + }) } } diff --git a/x/gamm/keeper/pool_service_test.go b/x/gamm/keeper/pool_service_test.go index e3929d9c43d..1bf23d3f4d9 100644 --- a/x/gamm/keeper/pool_service_test.go +++ b/x/gamm/keeper/pool_service_test.go @@ -498,35 +498,37 @@ func (suite *KeeperTestSuite) TestJoinPoolExitPool_InverseRelationship() { for _, tc := range testCases { suite.SetupTest() - for _, acc := range suite.TestAccs { - suite.FundAcc(acc, defaultAcctFunds) - } + suite.Run(tc.name, func() { + for _, acc := range suite.TestAccs { + suite.FundAcc(acc, defaultAcctFunds) + } - createPoolAcc := suite.TestAccs[0] - joinPoolAcc := suite.TestAccs[1] + createPoolAcc := suite.TestAccs[0] + joinPoolAcc := suite.TestAccs[1] - // test account is set on every test case iteration, we need to manually update address for pool creator - tc.pool.Sender = createPoolAcc.String() + // test account is set on every test case iteration, we need to manually update address for pool creator + tc.pool.Sender = createPoolAcc.String() - poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, tc.pool) - suite.Require().NoError(err) + poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, tc.pool) + suite.Require().NoError(err) - balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) - fmt.Println(balanceBeforeJoin.String()) + balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) + fmt.Println(balanceBeforeJoin.String()) _, _, err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) suite.Require().NoError(err) - _, err = suite.App.GAMMKeeper.ExitPool(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) + _, err = suite.App.GAMMKeeper.ExitPool(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) - balanceAfterExit := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) - deltaBalance, _ := balanceBeforeJoin.SafeSub(balanceAfterExit) + balanceAfterExit := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) + deltaBalance, _ := balanceBeforeJoin.SafeSub(balanceAfterExit) - // due to rounding, `balanceBeforeJoin` and `balanceAfterExit` have neglectable difference - // coming from rounding in exitPool.Here we test if the difference is within rounding tolerance range - roundingToleranceCoins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1)), sdk.NewCoin("bar", sdk.NewInt(1))) - suite.Require().True(deltaBalance.AmountOf("foo").LTE(roundingToleranceCoins.AmountOf("foo"))) - suite.Require().True(deltaBalance.AmountOf("bar").LTE(roundingToleranceCoins.AmountOf("bar"))) + // due to rounding, `balanceBeforeJoin` and `balanceAfterExit` have neglectable difference + // coming from rounding in exitPool.Here we test if the difference is within rounding tolerance range + roundingToleranceCoins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1)), sdk.NewCoin("bar", sdk.NewInt(1))) + suite.Require().True(deltaBalance.AmountOf("foo").LTE(roundingToleranceCoins.AmountOf("foo"))) + suite.Require().True(deltaBalance.AmountOf("bar").LTE(roundingToleranceCoins.AmountOf("bar"))) + }) } } diff --git a/x/gamm/pool-models/balancer/pool_suite_test.go b/x/gamm/pool-models/balancer/pool_suite_test.go index 851aa185f0e..20c21e5734a 100644 --- a/x/gamm/pool-models/balancer/pool_suite_test.go +++ b/x/gamm/pool-models/balancer/pool_suite_test.go @@ -500,33 +500,34 @@ func (suite *KeeperTestSuite) TestBalancerSpotPrice() { for _, tc := range tests { suite.SetupTest() + suite.Run(tc.name, func() { + poolId := suite.PrepareUni2PoolWithAssets( + tc.baseDenomPoolInput, + tc.quoteDenomPoolInput, + ) - poolId := suite.PrepareUni2PoolWithAssets( - tc.baseDenomPoolInput, - tc.quoteDenomPoolInput, - ) + pool, err := suite.App.GAMMKeeper.GetPoolAndPoke(suite.Ctx, poolId) + suite.Require().NoError(err, "test: %s", tc.name) + balancerPool, isPool := pool.(*balancer.Pool) + suite.Require().True(isPool, "test: %s", tc.name) + + sut := func() { + spotPrice, err := balancerPool.SpotPrice( + suite.Ctx, + tc.baseDenomPoolInput.Denom, + tc.quoteDenomPoolInput.Denom) - pool, err := suite.App.GAMMKeeper.GetPoolAndPoke(suite.Ctx, poolId) - suite.Require().NoError(err, "test: %s", tc.name) - balancerPool, isPool := pool.(*balancer.Pool) - suite.Require().True(isPool, "test: %s", tc.name) - - sut := func() { - spotPrice, err := balancerPool.SpotPrice( - suite.Ctx, - tc.baseDenomPoolInput.Denom, - tc.quoteDenomPoolInput.Denom) - - if tc.expectError { - suite.Require().Error(err, "test: %s", tc.name) - } else { - suite.Require().NoError(err, "test: %s", tc.name) - suite.Require().True(spotPrice.Equal(tc.expectedOutput), - "test: %s\nSpot price wrong, got %s, expected %s\n", tc.name, - spotPrice, tc.expectedOutput) + if tc.expectError { + suite.Require().Error(err, "test: %s", tc.name) + } else { + suite.Require().NoError(err, "test: %s", tc.name) + suite.Require().True(spotPrice.Equal(tc.expectedOutput), + "test: %s\nSpot price wrong, got %s, expected %s\n", tc.name, + spotPrice, tc.expectedOutput) + } } - } - assertPoolStateNotModified(suite.T(), balancerPool, sut) + assertPoolStateNotModified(suite.T(), balancerPool, sut) + }) } } diff --git a/x/gamm/twap/module.go b/x/gamm/twap/module.go index 1601969b775..9dae3925b85 100644 --- a/x/gamm/twap/module.go +++ b/x/gamm/twap/module.go @@ -54,6 +54,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod // Interfaces. func (b AppModuleBasic) RegisterRESTRoutes(ctx client.Context, r *mux.Router) { } + func (b AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) //nolint:errcheck } @@ -62,6 +63,7 @@ func (b AppModuleBasic) GetTxCmd() *cobra.Command { return nil // return cli.NewTxCmd() } + func (b AppModuleBasic) GetQueryCmd() *cobra.Command { return nil // return cli.GetQueryCmd() diff --git a/x/gamm/twap/types/keys.go b/x/gamm/twap/types/keys.go index c20ffdd8abf..5020db04d7c 100644 --- a/x/gamm/twap/types/keys.go +++ b/x/gamm/twap/types/keys.go @@ -10,6 +10,4 @@ const ( QuerierRoute = ModuleName ) -var ( - AlteredPoolIdsPrefix = []byte{0} -) +var AlteredPoolIdsPrefix = []byte{0} diff --git a/x/txfees/keeper/feedecorator_test.go b/x/txfees/keeper/feedecorator_test.go index 204918a77e4..5faddf95259 100644 --- a/x/txfees/keeper/feedecorator_test.go +++ b/x/txfees/keeper/feedecorator_test.go @@ -181,61 +181,62 @@ func (suite *KeeperTestSuite) TestFeeDecorator() { } for _, tc := range tests { - // reset pool and accounts for each test suite.SetupTest(false) - uionPoolId := suite.PrepareUni2PoolWithAssets( - sdk.NewInt64Coin(sdk.DefaultBondDenom, 500), - sdk.NewInt64Coin(uion, 500), - ) - suite.ExecuteUpgradeFeeTokenProposal(uion, uionPoolId) - - suite.Ctx = suite.Ctx.WithIsCheckTx(tc.isCheckTx).WithMinGasPrices(tc.minGasPrices) - suite.Ctx = suite.Ctx.WithMinGasPrices(tc.minGasPrices) - - // TxBuilder components reset for every test case - txBuilder := suite.clientCtx.TxConfig.NewTxBuilder() - priv0, _, addr0 := testdata.KeyTestPubAddr() - acc1 := suite.App.AccountKeeper.NewAccountWithAddress(suite.Ctx, addr0) - suite.App.AccountKeeper.SetAccount(suite.Ctx, acc1) - msgs := []sdk.Msg{testdata.NewTestMsg(addr0)} - privs, accNums, accSeqs := []cryptotypes.PrivKey{priv0}, []uint64{0}, []uint64{0} - signerData := authsigning.SignerData{ - ChainID: suite.Ctx.ChainID(), - AccountNumber: accNums[0], - Sequence: accSeqs[0], - } - - gasLimit := tc.gasRequested - sigV2, _ := clienttx.SignWithPrivKey( - 1, - signerData, - txBuilder, - privs[0], - suite.clientCtx.TxConfig, - accSeqs[0], - ) - - simapp.FundAccount(suite.App.BankKeeper, suite.Ctx, addr0, tc.txFee) - - tx := suite.BuildTx(txBuilder, msgs, sigV2, "", tc.txFee, gasLimit) - - mfd := keeper.NewMempoolFeeDecorator(*suite.App.TxFeesKeeper, mempoolFeeOpts) - dfd := keeper.NewDeductFeeDecorator(*suite.App.TxFeesKeeper, *suite.App.AccountKeeper, *suite.App.BankKeeper, nil) - antehandlerMFD := sdk.ChainAnteDecorators(mfd, dfd) - _, err := antehandlerMFD(suite.Ctx, tx, false) - - if tc.expectPass { - if tc.baseDenomGas && !tc.txFee.IsZero() { - moduleAddr := suite.App.AccountKeeper.GetModuleAddress(types.FeeCollectorName) - suite.Require().Equal(tc.txFee[0], suite.App.BankKeeper.GetBalance(suite.Ctx, moduleAddr, baseDenom), tc.name) - } else if !tc.txFee.IsZero() { - moduleAddr := suite.App.AccountKeeper.GetModuleAddress(types.NonNativeFeeCollectorName) - suite.Require().Equal(tc.txFee[0], suite.App.BankKeeper.GetBalance(suite.Ctx, moduleAddr, tc.txFee[0].Denom), tc.name) + suite.Run(tc.name, func() { + uionPoolId := suite.PrepareUni2PoolWithAssets( + sdk.NewInt64Coin(sdk.DefaultBondDenom, 500), + sdk.NewInt64Coin(uion, 500), + ) + suite.ExecuteUpgradeFeeTokenProposal(uion, uionPoolId) + + suite.Ctx = suite.Ctx.WithIsCheckTx(tc.isCheckTx).WithMinGasPrices(tc.minGasPrices) + suite.Ctx = suite.Ctx.WithMinGasPrices(tc.minGasPrices) + + // TxBuilder components reset for every test case + txBuilder := suite.clientCtx.TxConfig.NewTxBuilder() + priv0, _, addr0 := testdata.KeyTestPubAddr() + acc1 := suite.App.AccountKeeper.NewAccountWithAddress(suite.Ctx, addr0) + suite.App.AccountKeeper.SetAccount(suite.Ctx, acc1) + msgs := []sdk.Msg{testdata.NewTestMsg(addr0)} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv0}, []uint64{0}, []uint64{0} + signerData := authsigning.SignerData{ + ChainID: suite.Ctx.ChainID(), + AccountNumber: accNums[0], + Sequence: accSeqs[0], + } + + gasLimit := tc.gasRequested + sigV2, _ := clienttx.SignWithPrivKey( + 1, + signerData, + txBuilder, + privs[0], + suite.clientCtx.TxConfig, + accSeqs[0], + ) + + simapp.FundAccount(suite.App.BankKeeper, suite.Ctx, addr0, tc.txFee) + + tx := suite.BuildTx(txBuilder, msgs, sigV2, "", tc.txFee, gasLimit) + + mfd := keeper.NewMempoolFeeDecorator(*suite.App.TxFeesKeeper, mempoolFeeOpts) + dfd := keeper.NewDeductFeeDecorator(*suite.App.TxFeesKeeper, *suite.App.AccountKeeper, *suite.App.BankKeeper, nil) + antehandlerMFD := sdk.ChainAnteDecorators(mfd, dfd) + _, err := antehandlerMFD(suite.Ctx, tx, false) + + if tc.expectPass { + if tc.baseDenomGas && !tc.txFee.IsZero() { + moduleAddr := suite.App.AccountKeeper.GetModuleAddress(types.FeeCollectorName) + suite.Require().Equal(tc.txFee[0], suite.App.BankKeeper.GetBalance(suite.Ctx, moduleAddr, baseDenom), tc.name) + } else if !tc.txFee.IsZero() { + moduleAddr := suite.App.AccountKeeper.GetModuleAddress(types.NonNativeFeeCollectorName) + suite.Require().Equal(tc.txFee[0], suite.App.BankKeeper.GetBalance(suite.Ctx, moduleAddr, tc.txFee[0].Denom), tc.name) + } + suite.Require().NoError(err, "test: %s", tc.name) + } else { + suite.Require().Error(err, "test: %s", tc.name) } - suite.Require().NoError(err, "test: %s", tc.name) - } else { - suite.Require().Error(err, "test: %s", tc.name) - } + }) } } diff --git a/x/txfees/keeper/feetokens_test.go b/x/txfees/keeper/feetokens_test.go index fc001a1089e..1dd945f1c00 100644 --- a/x/txfees/keeper/feetokens_test.go +++ b/x/txfees/keeper/feetokens_test.go @@ -101,54 +101,55 @@ func (suite *KeeperTestSuite) TestUpgradeFeeTokenProposals() { } for _, tc := range tests { + suite.Run(tc.name, func() { + feeTokensBefore := suite.App.TxFeesKeeper.GetFeeTokens(suite.Ctx) - feeTokensBefore := suite.App.TxFeesKeeper.GetFeeTokens(suite.Ctx) + // Add a new whitelisted fee token via a governance proposal + err := suite.ExecuteUpgradeFeeTokenProposal(tc.feeToken, tc.poolId) - // Add a new whitelisted fee token via a governance proposal - err := suite.ExecuteUpgradeFeeTokenProposal(tc.feeToken, tc.poolId) + feeTokensAfter := suite.App.TxFeesKeeper.GetFeeTokens(suite.Ctx) - feeTokensAfter := suite.App.TxFeesKeeper.GetFeeTokens(suite.Ctx) - - if tc.expectPass { - // Make sure no error during setting of proposal - suite.Require().NoError(err, "test: %s", tc.name) - - // For a proposal that adds a feetoken - if tc.poolId != 0 { - // Make sure the length of fee tokens is >= before - suite.Require().GreaterOrEqual(len(feeTokensAfter), len(feeTokensBefore), "test: %s", tc.name) - // Ensure that the fee token is convertable to base token - _, err := suite.App.TxFeesKeeper.ConvertToBaseToken(suite.Ctx, sdk.NewInt64Coin(tc.feeToken, 10)) - suite.Require().NoError(err, "test: %s", tc.name) - // make sure the queried poolId is the same as expected - queriedPoolId, err := suite.queryClient.DenomPoolId(suite.Ctx.Context(), - &types.QueryDenomPoolIdRequest{ - Denom: tc.feeToken, - }, - ) + if tc.expectPass { + // Make sure no error during setting of proposal suite.Require().NoError(err, "test: %s", tc.name) - suite.Require().Equal(tc.poolId, queriedPoolId.GetPoolID(), "test: %s", tc.name) + + // For a proposal that adds a feetoken + if tc.poolId != 0 { + // Make sure the length of fee tokens is >= before + suite.Require().GreaterOrEqual(len(feeTokensAfter), len(feeTokensBefore), "test: %s", tc.name) + // Ensure that the fee token is convertable to base token + _, err := suite.App.TxFeesKeeper.ConvertToBaseToken(suite.Ctx, sdk.NewInt64Coin(tc.feeToken, 10)) + suite.Require().NoError(err, "test: %s", tc.name) + // make sure the queried poolId is the same as expected + queriedPoolId, err := suite.queryClient.DenomPoolId(suite.Ctx.Context(), + &types.QueryDenomPoolIdRequest{ + Denom: tc.feeToken, + }, + ) + suite.Require().NoError(err, "test: %s", tc.name) + suite.Require().Equal(tc.poolId, queriedPoolId.GetPoolID(), "test: %s", tc.name) + } else { + // if this proposal deleted a fee token + // ensure that the length of fee tokens is <= to before + suite.Require().LessOrEqual(len(feeTokensAfter), len(feeTokensBefore), "test: %s", tc.name) + // Ensure that the fee token is not convertable to base token + _, err := suite.App.TxFeesKeeper.ConvertToBaseToken(suite.Ctx, sdk.NewInt64Coin(tc.feeToken, 10)) + suite.Require().Error(err, "test: %s", tc.name) + // make sure the queried poolId errors + _, err = suite.queryClient.DenomPoolId(suite.Ctx.Context(), + &types.QueryDenomPoolIdRequest{ + Denom: tc.feeToken, + }, + ) + suite.Require().Error(err, "test: %s", tc.name) + } } else { - // if this proposal deleted a fee token - // ensure that the length of fee tokens is <= to before - suite.Require().LessOrEqual(len(feeTokensAfter), len(feeTokensBefore), "test: %s", tc.name) - // Ensure that the fee token is not convertable to base token - _, err := suite.App.TxFeesKeeper.ConvertToBaseToken(suite.Ctx, sdk.NewInt64Coin(tc.feeToken, 10)) - suite.Require().Error(err, "test: %s", tc.name) - // make sure the queried poolId errors - _, err = suite.queryClient.DenomPoolId(suite.Ctx.Context(), - &types.QueryDenomPoolIdRequest{ - Denom: tc.feeToken, - }, - ) + // Make sure errors during setting of proposal suite.Require().Error(err, "test: %s", tc.name) + // fee tokens should be the same + suite.Require().Equal(len(feeTokensAfter), len(feeTokensBefore), "test: %s", tc.name) } - } else { - // Make sure errors during setting of proposal - suite.Require().Error(err, "test: %s", tc.name) - // fee tokens should be the same - suite.Require().Equal(len(feeTokensAfter), len(feeTokensBefore), "test: %s", tc.name) - } + }) } } @@ -203,19 +204,21 @@ func (suite *KeeperTestSuite) TestFeeTokenConversions() { for _, tc := range tests { suite.SetupTest(false) - poolId := suite.PrepareUni2PoolWithAssets( - tc.baseDenomPoolInput, - tc.feeTokenPoolInput, - ) + suite.Run(tc.name, func() { + poolId := suite.PrepareUni2PoolWithAssets( + tc.baseDenomPoolInput, + tc.feeTokenPoolInput, + ) - suite.ExecuteUpgradeFeeTokenProposal(tc.feeTokenPoolInput.Denom, poolId) + suite.ExecuteUpgradeFeeTokenProposal(tc.feeTokenPoolInput.Denom, poolId) - converted, err := suite.App.TxFeesKeeper.ConvertToBaseToken(suite.Ctx, tc.inputFee) - if tc.expectedConvertable { - suite.Require().NoError(err, "test: %s", tc.name) - suite.Require().True(converted.IsEqual(tc.expectedOutput), "test: %s", tc.name) - } else { - suite.Require().Error(err, "test: %s", tc.name) - } + converted, err := suite.App.TxFeesKeeper.ConvertToBaseToken(suite.Ctx, tc.inputFee) + if tc.expectedConvertable { + suite.Require().NoError(err, "test: %s", tc.name) + suite.Require().True(converted.IsEqual(tc.expectedOutput), "test: %s", tc.name) + } else { + suite.Require().Error(err, "test: %s", tc.name) + } + }) } } From a232405968e7da00da90b264ba965f1151d62256 Mon Sep 17 00:00:00 2001 From: Roman Date: Mon, 11 Jul 2022 13:01:55 -0400 Subject: [PATCH 053/376] refactor(x/mint): distributeToModule function and tests (#2004) * refactor(x/mint): distributeToModule function and tests * refactor TestGetProportions and add cases * fix emrge conflict * Update x/mint/keeper/keeper_test.go Co-authored-by: Dev Ojha * extract var for complex ratio Co-authored-by: Dev Ojha --- x/mint/keeper/export_test.go | 10 ++ x/mint/keeper/hooks_test.go | 59 ++++++---- x/mint/keeper/keeper.go | 74 ++++++++----- x/mint/keeper/keeper_test.go | 203 +++++++++++++++++++++++++++++------ 4 files changed, 267 insertions(+), 79 deletions(-) diff --git a/x/mint/keeper/export_test.go b/x/mint/keeper/export_test.go index 728a8bcc249..2dfe835160d 100644 --- a/x/mint/keeper/export_test.go +++ b/x/mint/keeper/export_test.go @@ -1,5 +1,9 @@ package keeper +import sdk "github.com/cosmos/cosmos-sdk/types" + +type ErrInvalidRatio = invalidRatioError + const ( DeveloperVestingAmount = developerVestingAmount ) @@ -8,4 +12,10 @@ var ( ErrAmountCannotBeNilOrZero = errAmountCannotBeNilOrZero ErrDevVestingModuleAccountAlreadyCreated = errDevVestingModuleAccountAlreadyCreated ErrDevVestingModuleAccountNotCreated = errDevVestingModuleAccountNotCreated + + GetProportions = getProportions ) + +func (k Keeper) DistributeToModule(ctx sdk.Context, recipientModule string, mintedCoin sdk.Coin, proportion sdk.Dec) (sdk.Coin, error) { + return k.distributeToModule(ctx, recipientModule, mintedCoin, proportion) +} diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index 800e579b9b7..071e0124eb8 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -4,18 +4,23 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" osmoapp "github.com/osmosis-labs/osmosis/v7/app" lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" "github.com/osmosis-labs/osmosis/v7/x/mint/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" ) +func TestMintHooksTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} + func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { app := osmoapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) @@ -23,7 +28,7 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - setupGaugeForLPIncentives(suite.T(), app, ctx) + setupGaugeForLPIncentives(suite, app, ctx) params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) @@ -55,8 +60,9 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { mintParams = app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsAmount := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking).Amount - expectedRewards := sdk.NewDecCoin("stake", expectedRewardsAmount) + expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking) + suite.NoError(err) + expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) // ensure post-epoch supply with offset changed by exactly the minted coins amount // ensure post-epoch supply with offset changed by less than the minted coins amount (because of developer vesting account) @@ -71,7 +77,8 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewards := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) + expectedDevRewards, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) + suite.NoError(err) suite.Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) } @@ -91,8 +98,9 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { mintParams = app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsAmount := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking).Amount - expectedRewards := sdk.NewDecCoin("stake", expectedRewardsAmount) + expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking) + suite.NoError(err) + expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) @@ -100,8 +108,9 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { // test that the balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewards := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) + expectedDevRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) + suite.NoError(err) + suite.Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) } } @@ -112,7 +121,7 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - setupGaugeForLPIncentives(suite.T(), app, ctx) + setupGaugeForLPIncentives(suite, app, ctx) params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) @@ -129,8 +138,9 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp mintParams := app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsAmount := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking.Add(mintParams.DistributionProportions.DeveloperRewards)).Amount - expectedRewards := sdk.NewDecCoin("stake", expectedRewardsAmount) + expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking.Add(mintParams.DistributionProportions.DeveloperRewards)) + suite.NoError(err) + expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) @@ -138,8 +148,9 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewards := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) + expectedDevRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) + suite.NoError(err) + suite.Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) } app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) @@ -158,8 +169,9 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp mintParams := app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsAmount := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking.Add(mintParams.DistributionProportions.DeveloperRewards)).Amount - expectedRewards := sdk.NewDecCoin("stake", expectedRewardsAmount) + expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking.Add(mintParams.DistributionProportions.DeveloperRewards)) + suite.NoError(err) + expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) @@ -167,8 +179,9 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewards := app.MintKeeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) + expectedDevRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) + suite.NoError(err) + suite.Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) } } @@ -183,7 +196,7 @@ func (suite *KeeperTestSuite) TestEndOfEpochNoDistributionWhenIsNotYetStartTime( header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - setupGaugeForLPIncentives(suite.T(), app, ctx) + setupGaugeForLPIncentives(suite, app, ctx) params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) @@ -424,11 +437,11 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete suite.Equal(expectedThirdenedProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions) } -func setupGaugeForLPIncentives(t *testing.T, app *osmoapp.OsmosisApp, ctx sdk.Context) { +func setupGaugeForLPIncentives(suite *KeeperTestSuite, app *osmoapp.OsmosisApp, ctx sdk.Context) { addr := sdk.AccAddress([]byte("addr1---------------")) coins := sdk.Coins{sdk.NewInt64Coin("stake", 10000)} err := simapp.FundAccount(app.BankKeeper, ctx, addr, coins) - require.NoError(t, err) + suite.NoError(err) distrTo := lockuptypes.QueryCondition{ LockQueryType: lockuptypes.ByDuration, Denom: "lptoken", @@ -438,8 +451,8 @@ func setupGaugeForLPIncentives(t *testing.T, app *osmoapp.OsmosisApp, ctx sdk.Co // mints coins so supply exists on chain mintLPtokens := sdk.Coins{sdk.NewInt64Coin(distrTo.Denom, 200)} err = simapp.FundAccount(app.BankKeeper, ctx, addr, mintLPtokens) - require.NoError(t, err) + suite.NoError(err) _, err = app.IncentivesKeeper.CreateGauge(ctx, true, addr, coins, distrTo, time.Now(), 1) - require.NoError(t, err) + suite.NoError(err) } diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index 0535942c0d4..dbca5cdb54e 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -15,12 +15,6 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -var ( - errAmountCannotBeNilOrZero = errors.New("amount cannot be nil or zero") - errDevVestingModuleAccountAlreadyCreated = fmt.Errorf("%s module account already exists", types.DeveloperVestingModuleAcctName) - errDevVestingModuleAccountNotCreated = fmt.Errorf("%s module account does not exist", types.DeveloperVestingModuleAcctName) -) - // Keeper of the mint store. type Keeper struct { cdc codec.BinaryCodec @@ -34,6 +28,20 @@ type Keeper struct { feeCollectorName string } +type invalidRatioError struct { + ActualRatio sdk.Dec +} + +func (e invalidRatioError) Error() string { + return fmt.Sprintf("mint allocation ratio %s is greater than 1", e.ActualRatio) +} + +var ( + errAmountCannotBeNilOrZero = errors.New("amount cannot be nil or zero") + errDevVestingModuleAccountAlreadyCreated = fmt.Errorf("%s module account already exists", types.DeveloperVestingModuleAcctName) + errDevVestingModuleAccountNotCreated = fmt.Errorf("%s module account does not exist", types.DeveloperVestingModuleAcctName) +) + // NewKeeper creates a new mint Keeper instance. func NewKeeper( cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace, @@ -185,36 +193,31 @@ func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error { return k.bankKeeper.MintCoins(ctx, types.ModuleName, newCoins) } -// GetProportions gets the balance of the `MintedDenom` from minted coins and returns coins according to the `AllocationRatio`. -func (k Keeper) GetProportions(ctx sdk.Context, mintedCoin sdk.Coin, ratio sdk.Dec) sdk.Coin { - return sdk.NewCoin(mintedCoin.Denom, mintedCoin.Amount.ToDec().Mul(ratio).TruncateInt()) -} - // DistributeMintedCoins implements distribution of minted coins from mint to external modules. func (k Keeper) DistributeMintedCoin(ctx sdk.Context, mintedCoin sdk.Coin) error { params := k.GetParams(ctx) proportions := params.DistributionProportions // allocate staking incentives into fee collector account to be moved to on next begin blocker by staking module - stakingIncentivesCoins := sdk.NewCoins(k.GetProportions(ctx, mintedCoin, proportions.Staking)) - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, k.feeCollectorName, stakingIncentivesCoins) + stakingIncentivesCoin, err := k.distributeToModule(ctx, k.feeCollectorName, mintedCoin, proportions.Staking) if err != nil { return err } // allocate pool allocation ratio to pool-incentives module account account - poolIncentivesCoins := sdk.NewCoins(k.GetProportions(ctx, mintedCoin, proportions.PoolIncentives)) - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, poolincentivestypes.ModuleName, poolIncentivesCoins) + poolIncentivesCoin, err := k.distributeToModule(ctx, poolincentivestypes.ModuleName, mintedCoin, proportions.PoolIncentives) if err != nil { return err } - devRewardCoin := k.GetProportions(ctx, mintedCoin, proportions.DeveloperRewards) + devRewardCoin, err := getProportions(ctx, mintedCoin, proportions.DeveloperRewards) + if err != nil { + return err + } devRewardCoins := sdk.NewCoins(devRewardCoin) // This is supposed to come from the developer vesting module address, not the mint module address // we over-allocated to the mint module address earlier though, so we burn it right here. - err = k.bankKeeper.BurnCoins(ctx, types.ModuleName, devRewardCoins) - if err != nil { + if err := k.bankKeeper.BurnCoins(ctx, types.ModuleName, devRewardCoins); err != nil { return err } @@ -225,16 +228,19 @@ func (k Keeper) DistributeMintedCoin(ctx sdk.Context, mintedCoin sdk.Coin) error if len(params.WeightedDeveloperRewardsReceivers) == 0 { // fund community pool when rewards address is empty - err = k.distrKeeper.FundCommunityPool(ctx, devRewardCoins, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) - if err != nil { + if err := k.distrKeeper.FundCommunityPool(ctx, devRewardCoins, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)); err != nil { return err } } else { // allocate developer rewards to addresses by weight for _, w := range params.WeightedDeveloperRewardsReceivers { - devRewardPortionCoins := sdk.NewCoins(k.GetProportions(ctx, devRewardCoin, w.Weight)) + devPortionCoin, err := getProportions(ctx, devRewardCoin, w.Weight) + if err != nil { + return err + } + devRewardPortionCoins := sdk.NewCoins(devPortionCoin) if w.Address == "" { - err = k.distrKeeper.FundCommunityPool(ctx, devRewardPortionCoins, + err := k.distrKeeper.FundCommunityPool(ctx, devRewardPortionCoins, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) if err != nil { return err @@ -259,8 +265,8 @@ func (k Keeper) DistributeMintedCoin(ctx sdk.Context, mintedCoin sdk.Coin) error k.bankKeeper.AddSupplyOffset(ctx, mintedCoin.Denom, developerAccountBalance.Amount.Neg()) // subtract from original provision to ensure no coins left over after the allocations - communityPoolCoins := sdk.NewCoins(mintedCoin).Sub(stakingIncentivesCoins).Sub(poolIncentivesCoins).Sub(devRewardCoins) - err = k.distrKeeper.FundCommunityPool(ctx, communityPoolCoins, k.accountKeeper.GetModuleAddress(types.ModuleName)) + communityPoolCoin := mintedCoin.Sub(stakingIncentivesCoin).Sub(poolIncentivesCoin).Sub(devRewardCoin) + err = k.distrKeeper.FundCommunityPool(ctx, sdk.NewCoins(communityPoolCoin), k.accountKeeper.GetModuleAddress(types.ModuleName)) if err != nil { return err } @@ -270,3 +276,23 @@ func (k Keeper) DistributeMintedCoin(ctx sdk.Context, mintedCoin sdk.Coin) error return err } + +func (k Keeper) distributeToModule(ctx sdk.Context, recipientModule string, mintedCoin sdk.Coin, proportion sdk.Dec) (sdk.Coin, error) { + distributionCoin, err := getProportions(ctx, mintedCoin, proportion) + if err != nil { + return sdk.Coin{}, err + } + if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, recipientModule, sdk.NewCoins(distributionCoin)); err != nil { + return sdk.Coin{}, err + } + return distributionCoin, nil +} + +// getProportions gets the balance of the `MintedDenom` from minted coins and returns coins according to the +// allocation ratio. Returns error if ratio is greater than 1. +func getProportions(ctx sdk.Context, mintedCoin sdk.Coin, ratio sdk.Dec) (sdk.Coin, error) { + if ratio.GT(sdk.OneDec()) { + return sdk.Coin{}, invalidRatioError{ratio} + } + return sdk.NewCoin(mintedCoin.Denom, mintedCoin.Amount.ToDec().Mul(ratio).TruncateInt()), nil +} diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 91740653599..c619af24699 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -4,7 +4,6 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/distribution" @@ -14,6 +13,7 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/osmosis-labs/osmosis/v7/app/apptesting" + "github.com/osmosis-labs/osmosis/v7/osmoutils" lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" "github.com/osmosis-labs/osmosis/v7/x/mint/types" @@ -25,6 +25,10 @@ type KeeperTestSuite struct { queryClient types.QueryClient } +func TestKeeperTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} + func (suite *KeeperTestSuite) SetupTest() { suite.Setup() @@ -61,49 +65,69 @@ func (suite *KeeperTestSuite) setupDeveloperVestingModuleAccountTest(blockHeight } } -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} +// TestGetProportions tests that mint allocations are computed as expected. +func (suite *KeeperTestSuite) TestGetProportions() { + complexRatioDec := sdk.NewDecWithPrec(131, 3).Quo(sdk.NewDecWithPrec(273, 3)) -func (suite *KeeperTestSuite) TestMintCoinsToFeeCollectorAndGetProportions() { tests := []struct { - name string - ratio sdk.Dec - hasPreExistingSupply bool - expectedCoin sdk.Coin - fee sdk.Coin + name string + ratio sdk.Dec + expectedCoin sdk.Coin + expectedError error + mintedCoin sdk.Coin }{ { - name: "coin is minted to the fee collector", - fee: sdk.NewCoin("stake", sdk.NewInt(0)), - ratio: sdk.NewDecWithPrec(2, 1), - hasPreExistingSupply: false, - expectedCoin: sdk.NewCoin("stake", sdk.NewInt(0)), - }, { - name: "mint the 100K stake coin to the fee collector", - fee: sdk.NewCoin("stake", sdk.NewInt(100000)), - ratio: sdk.NewDecWithPrec(2, 1), - hasPreExistingSupply: true, - expectedCoin: sdk.NewCoin("stake", sdk.NewInt(100000).Quo(sdk.NewInt(5))), + name: "0 * 0.2 = 0", + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0)), + ratio: sdk.NewDecWithPrec(2, 1), + expectedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0)), + }, + { + name: "100000 * 0.2 = 20000", + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000)), + ratio: sdk.NewDecWithPrec(2, 1), + expectedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000).Quo(sdk.NewInt(5))), + }, + { + name: "123456 * 2/3 = 82304", + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(123456)), + ratio: sdk.NewDecWithPrec(2, 1).Quo(sdk.NewDecWithPrec(3, 1)), + expectedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(82304)), + }, + { + name: "54617981 * .131/.273 approx = 2.62", + mintedCoin: sdk.NewCoin("uosmo", sdk.NewInt(54617981)), + ratio: complexRatioDec, // .131/.273 + // TODO: Should not be truncated. Remove truncation after rounding errors are addressed and resolved. + // Ref: https://github.com/osmosis-labs/osmosis/issues/1917 + expectedCoin: sdk.NewCoin("uosmo", sdk.NewInt(54617981).ToDec().Mul(complexRatioDec).TruncateInt()), + }, + { + name: "1 * 1 = 1", + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1)), + ratio: sdk.NewDec(1), + expectedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1)), + }, + { + name: "1 * 1.01 - error, ratio must be <= 1", + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0)), + ratio: sdk.NewDecWithPrec(101, 2), + + expectedError: keeper.ErrInvalidRatio{ActualRatio: sdk.NewDecWithPrec(101, 2)}, }, } for _, tc := range tests { suite.Run(tc.name, func() { - bankKeeper := suite.App.BankKeeper - mintKeeper := suite.App.MintKeeper + coin, err := keeper.GetProportions(suite.Ctx, tc.mintedCoin, tc.ratio) - if tc.hasPreExistingSupply { - fee := sdk.NewCoin("stake", sdk.NewInt(100000)) - fees := sdk.NewCoins(fee) - err := simapp.FundModuleAccount(bankKeeper, - suite.Ctx, - authtypes.FeeCollectorName, - fees) - suite.NoError(err) + if tc.expectedError != nil { + suite.Require().Equal(tc.expectedError, err) + suite.Equal(sdk.Coin{}, coin) + return } - coin := mintKeeper.GetProportions(suite.Ctx, tc.fee, tc.ratio) + suite.NoError(err) suite.Equal(tc.expectedCoin, coin) }) } @@ -355,3 +379,118 @@ func (suite *KeeperTestSuite) TestSetInitialSupplyOffsetDuringMigration() { }) } } + +// TestDistributeToModule tests that distribution from mint module to another module helper +// function is working as expected. +func (suite *KeeperTestSuite) TestDistributeToModule() { + const ( + denomDoesNotExist = "denomDoesNotExist" + moduleAccountDoesNotExist = "moduleAccountDoesNotExist" + ) + + tests := map[string]struct { + preMintAmount sdk.Coin + + recepientModule string + mintedCoin sdk.Coin + proportion sdk.Dec + + expectedError bool + expectPanic bool + }{ + "pre-mint == distribute - poolincentives module - full amount - success": { + preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + + recepientModule: poolincentivestypes.ModuleName, + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + proportion: sdk.NewDec(1), + }, + "pre-mint > distribute - developer vesting module - two thirds - success": { + preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(101)), + + recepientModule: poolincentivestypes.ModuleName, + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + proportion: sdk.NewDecWithPrec(2, 1).Quo(sdk.NewDecWithPrec(3, 1)), + }, + "pre-mint < distribute (0) - error": { + preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0)), + + recepientModule: poolincentivestypes.ModuleName, + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + proportion: sdk.NewDecWithPrec(2, 1).Quo(sdk.NewDecWithPrec(3, 1)), + + expectedError: true, + }, + "denom does not exist - error": { + preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + + recepientModule: poolincentivestypes.ModuleName, + mintedCoin: sdk.NewCoin(denomDoesNotExist, sdk.NewInt(100)), + proportion: sdk.NewDec(1), + + expectedError: true, + }, + "invalid module account -panic": { + preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + + recepientModule: moduleAccountDoesNotExist, + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + proportion: sdk.NewDec(1), + + expectPanic: true, + }, + "proportion greater than 1 - error": { + preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(300)), + + recepientModule: poolincentivestypes.ModuleName, + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + proportion: sdk.NewDec(2), + + expectedError: true, + }, + } + for name, tc := range tests { + suite.Run(name, func() { + suite.Setup() + osmoutils.ConditionalPanic(suite.T(), tc.expectPanic, func() { + mintKeeper := suite.App.MintKeeper + bankKeeper := suite.App.BankKeeper + accountKeeper := suite.App.AccountKeeper + ctx := suite.Ctx + + // Setup. + suite.NoError(mintKeeper.MintCoins(ctx, sdk.NewCoins(tc.preMintAmount))) + + // TODO: Should not be truncated. Remove truncation after rounding errors are addressed and resolved. + // Ref: https://github.com/osmosis-labs/osmosis/issues/1917 + expectedDistributed := tc.mintedCoin.Amount.ToDec().Mul(tc.proportion).TruncateInt() + oldMintModuleBalance := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.ModuleName), tc.mintedCoin.Denom) + oldRecepientModuleBalance := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(tc.recepientModule), tc.mintedCoin.Denom) + + // Test. + actualDistributed, err := mintKeeper.DistributeToModule(ctx, tc.recepientModule, tc.mintedCoin, tc.proportion) + + // Assertions. + actualMintModuleBalance := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.ModuleName), tc.mintedCoin.Denom) + actualRecepientModuleBalance := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(tc.recepientModule), tc.mintedCoin.Denom) + + if tc.expectedError { + suite.Error(err) + suite.Equal(actualDistributed, sdk.Coin{}) + // Old balances should not change. + suite.Equal(oldMintModuleBalance.Amount.Int64(), actualMintModuleBalance.Amount.Int64()) + suite.Equal(oldRecepientModuleBalance.Amount.Int64(), actualRecepientModuleBalance.Amount.Int64()) + return + } + + suite.NoError(err) + suite.Equal(tc.mintedCoin.Denom, actualDistributed.Denom) + suite.Equal(expectedDistributed, actualDistributed.Amount) + + // Updated balances. + suite.Equal(oldMintModuleBalance.Sub(actualDistributed).Amount.Int64(), actualMintModuleBalance.Amount.Int64()) + suite.Equal(oldRecepientModuleBalance.Add(actualDistributed).Amount.Int64(), actualRecepientModuleBalance.Amount.Int64()) + }) + }) + } +} From 56513df3a50c83a80d2d354a6376f030dffb354a Mon Sep 17 00:00:00 2001 From: khanh <50263489+catShaark@users.noreply.github.com> Date: Tue, 12 Jul 2022 03:09:01 +0700 Subject: [PATCH 054/376] use distributeInternal in distributeSyntheticInternal (#2015) * use distributeInternal in distributeSyntheticInternal * remove commented out code * Update distribute.go --- x/incentives/keeper/distribute.go | 49 ++----------------------------- x/superfluid/keeper/hooks_test.go | 2 +- 2 files changed, 3 insertions(+), 48 deletions(-) diff --git a/x/incentives/keeper/distribute.go b/x/incentives/keeper/distribute.go index 1fcfe5215ed..f2700445e32 100644 --- a/x/incentives/keeper/distribute.go +++ b/x/incentives/keeper/distribute.go @@ -231,11 +231,9 @@ func (k Keeper) doDistributionSends(ctx sdk.Context, distrs *distributionInfo) e // distributeSyntheticInternal runs the distribution logic for a synthetic rewards distribution gauge, and adds the sends to // the distrInfo computed. It also updates the gauge for the distribution. // locks is expected to be the correct set of lock recipients for this gauge. -// TODO: Make this code have way more re-use with distribute internal (post-v7). func (k Keeper) distributeSyntheticInternal( ctx sdk.Context, gauge types.Gauge, locks []lockuptypes.PeriodLock, distrInfo *distributionInfo, ) (sdk.Coins, error) { - totalDistrCoins := sdk.NewCoins() denom := gauge.DistributeTo.Denom qualifiedLocks := make([]lockuptypes.PeriodLock, 0, len(locks)) @@ -249,50 +247,7 @@ func (k Keeper) distributeSyntheticInternal( qualifiedLocks = append(qualifiedLocks, lock) } - lockSum := lockuptypes.SumLocksByDenom(qualifiedLocks, lockuptypes.NativeDenom(denom)) - - if lockSum.IsZero() { - return nil, nil - } - - remainCoins := gauge.Coins.Sub(gauge.DistributedCoins) - remainEpochs := uint64(1) - if !gauge.IsPerpetual { // set remain epochs when it's not perpetual gauge - remainEpochs = gauge.NumEpochsPaidOver - gauge.FilledEpochs - } - - for _, lock := range qualifiedLocks { - distrCoins := sdk.Coins{} - for _, coin := range remainCoins { - lockedCoin, err := lock.SingleCoin() - if err != nil { - k.Logger(ctx).Error(err.Error()) - continue - } - // distribution amount = gauge_size * denom_lock_amount / (total_denom_lock_amount * remain_epochs) - // check if the synthlock is qualified for GetLocksToDistribution - amt := coin.Amount.Mul(lockedCoin.Amount).Quo(lockSum.Mul(sdk.NewIntFromUint64(remainEpochs))) - if amt.IsPositive() { - newlyDistributedCoin := sdk.Coin{Denom: coin.Denom, Amount: amt} - distrCoins = distrCoins.Add(newlyDistributedCoin) - } - } - distrCoins = distrCoins.Sort() - if distrCoins.Empty() { - continue - } - // Update the amount for that address - err := distrInfo.addLockRewards(lock.Owner, distrCoins) - if err != nil { - return nil, err - } - - totalDistrCoins = totalDistrCoins.Add(distrCoins...) - } - - // increase filled epochs after distribution - err := k.updateGaugePostDistribute(ctx, gauge, totalDistrCoins) - return totalDistrCoins, err + return k.distributeInternal(ctx, gauge, qualifiedLocks, distrInfo) } // distributeInternal runs the distribution logic for a gauge, and adds the sends to @@ -302,7 +257,7 @@ func (k Keeper) distributeInternal( ctx sdk.Context, gauge types.Gauge, locks []lockuptypes.PeriodLock, distrInfo *distributionInfo, ) (sdk.Coins, error) { totalDistrCoins := sdk.NewCoins() - denom := gauge.DistributeTo.Denom + denom := lockuptypes.NativeDenom(gauge.DistributeTo.Denom) lockSum := lockuptypes.SumLocksByDenom(locks, denom) if lockSum.IsZero() { diff --git a/x/superfluid/keeper/hooks_test.go b/x/superfluid/keeper/hooks_test.go index 859b2a96b5a..3924c2d0976 100644 --- a/x/superfluid/keeper/hooks_test.go +++ b/x/superfluid/keeper/hooks_test.go @@ -78,7 +78,7 @@ func (suite *KeeperTestSuite) TestSuperfluidAfterEpochEnd() { suite.Require().Equal(gauge.Id, intermediaryAcc.GaugeId) suite.Require().Equal(gauge.IsPerpetual, true) suite.Require().Equal(gauge.Coins, tc.expRewards[index]) - suite.Require().Equal(gauge.DistributedCoins, tc.expRewards[index]) + suite.Require().Equal(gauge.DistributedCoins.String(), tc.expRewards[index].String()) } // check delegation changes From aea5125195e547a96fd959583fd8c6fe0fbd5e22 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Mon, 11 Jul 2022 15:22:23 -0500 Subject: [PATCH 055/376] Fix mergify bot config (#2018) --- .github/{.mergify.yml => mergify.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/{.mergify.yml => mergify.yml} (100%) diff --git a/.github/.mergify.yml b/.github/mergify.yml similarity index 100% rename from .github/.mergify.yml rename to .github/mergify.yml From 8cb94703288c97200100cfb447b4d2ab3e7d3689 Mon Sep 17 00:00:00 2001 From: Sishir Giri Date: Mon, 11 Jul 2022 14:42:53 -0700 Subject: [PATCH 056/376] chore: x/txfees: Internal audit(Keeper methods) and test cleanup (#1901) * val * table driven test * nit * addressed matts comments * addressed alp and bez comments * added alp comments * added suite.Run * matts comments --- x/txfees/keeper/feedecorator.go | 3 + x/txfees/keeper/feetokens.go | 10 ++- x/txfees/keeper/hooks_test.go | 115 +++++++++++++++++++------------- 3 files changed, 81 insertions(+), 47 deletions(-) diff --git a/x/txfees/keeper/feedecorator.go b/x/txfees/keeper/feedecorator.go index afb4b555f90..1f4cb51ee1c 100644 --- a/x/txfees/keeper/feedecorator.go +++ b/x/txfees/keeper/feedecorator.go @@ -78,6 +78,7 @@ func (mfd MempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b if (ctx.IsCheckTx() || ctx.IsReCheckTx()) && !simulate { minBaseGasPrice := mfd.GetMinBaseGasPriceForTx(ctx, baseDenom, feeTx) if !(minBaseGasPrice.IsZero()) { + // You should only be able to pay with one fee token in a single tx if len(feeCoins) != 1 { return ctx, sdkerrors.Wrapf(sdkerrors.ErrInsufficientFee, "no fee attached") } @@ -108,6 +109,7 @@ func (k Keeper) IsSufficientFee(ctx sdk.Context, minBaseGasPrice sdk.Dec, gasReq if err != nil { return err } + // check to ensure that the convertedFee should always be greater than or equal to the requireBaseFee if !(convertedFee.IsGTE(requiredBaseFee)) { return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFee, "insufficient fees; got: %s which converts to %s. required: %s", feeCoin, convertedFee, requiredBaseFee) } @@ -117,6 +119,7 @@ func (k Keeper) IsSufficientFee(ctx sdk.Context, minBaseGasPrice sdk.Dec, gasReq func (mfd MempoolFeeDecorator) GetMinBaseGasPriceForTx(ctx sdk.Context, baseDenom string, tx sdk.FeeTx) sdk.Dec { cfgMinGasPrice := ctx.MinGasPrices().AmountOf(baseDenom) + // the check below prevents tx gas from getting over HighGasTxThreshold which is default to 1_000_000 if tx.GetGas() >= mfd.Opts.HighGasTxThreshold { cfgMinGasPrice = sdk.MaxDec(cfgMinGasPrice, mfd.Opts.MinGasPriceForHighGasTx) } diff --git a/x/txfees/keeper/feetokens.go b/x/txfees/keeper/feetokens.go index af158a83ac8..f1da6a3765f 100644 --- a/x/txfees/keeper/feetokens.go +++ b/x/txfees/keeper/feetokens.go @@ -32,6 +32,10 @@ func (k Keeper) ConvertToBaseToken(ctx sdk.Context, inputFee sdk.Coin) (sdk.Coin return sdk.NewCoin(baseDenom, spotPrice.MulInt(inputFee.Amount).RoundInt()), nil } +// CalcFeeSpotPrice converts the provided tx fees into their equivalent value in the base denomination. +// Spot Price Calculation: spotPrice / (1 - swapFee), +// where spotPrice is defined as: +// (tokenBalanceIn / tokenWeightIn) / (tokenBalanceOut / tokenWeightOut) func (k Keeper) CalcFeeSpotPrice(ctx sdk.Context, inputDenom string) (sdk.Dec, error) { baseDenom, err := k.GetBaseDenom(ctx) if err != nil { @@ -50,7 +54,8 @@ func (k Keeper) CalcFeeSpotPrice(ctx sdk.Context, inputDenom string) (sdk.Dec, e return spotPrice, nil } -// GetFeeToken returns the fee token record for a specific denom +// GetFeeToken returns the fee token record for a specific denom, +// In our case the baseDenom is uosmo. func (k Keeper) GetBaseDenom(ctx sdk.Context) (denom string, err error) { store := ctx.KVStore(k.storeKey) @@ -99,7 +104,7 @@ func (k Keeper) ValidateFeeToken(ctx sdk.Context, feeToken types.FeeToken) error return err } -// GetFeeToken returns the fee token record for a specific denom. +// GetFeeToken returns a unique fee token record for a specific denom. // If the denom doesn't exist, returns an error. func (k Keeper) GetFeeToken(ctx sdk.Context, denom string) (types.FeeToken, error) { prefixStore := k.GetFeeTokensStore(ctx) @@ -118,6 +123,7 @@ func (k Keeper) GetFeeToken(ctx sdk.Context, denom string) (types.FeeToken, erro } // setFeeToken sets a new fee token record for a specific denom. +// PoolID is just the pool to swap rate between alt fee token and native fee token. // If the feeToken pool ID is 0, deletes the fee Token entry. func (k Keeper) setFeeToken(ctx sdk.Context, feeToken types.FeeToken) error { prefixStore := k.GetFeeTokensStore(ctx) diff --git a/x/txfees/keeper/hooks_test.go b/x/txfees/keeper/hooks_test.go index 41e0f5f765b..9995ea275f9 100644 --- a/x/txfees/keeper/hooks_test.go +++ b/x/txfees/keeper/hooks_test.go @@ -37,49 +37,74 @@ func (suite *KeeperTestSuite) TestTxFeesAfterEpochEnd() { ust := "ust" _, ustPool := suite.preparePool(ust) - // todo make this section onwards table driven - coins := sdk.NewCoins(sdk.NewInt64Coin(uion, 10), - sdk.NewInt64Coin(atom, 20), - sdk.NewInt64Coin(ust, 14)) - - swapFee := sdk.NewDec(0) - - expectedOutput1, err := uionPool.CalcOutAmtGivenIn(suite.Ctx, - sdk.Coins{sdk.Coin{Denom: uion, Amount: coins.AmountOf(uion)}}, - baseDenom, - swapFee) - suite.Require().NoError(err) - expectedOutput2, err := atomPool.CalcOutAmtGivenIn(suite.Ctx, - sdk.Coins{sdk.Coin{Denom: atom, Amount: coins.AmountOf(atom)}}, - baseDenom, - swapFee) - suite.Require().NoError(err) - expectedOutput3, err := ustPool.CalcOutAmtGivenIn(suite.Ctx, - sdk.Coins{sdk.Coin{Denom: ust, Amount: coins.AmountOf(ust)}}, - baseDenom, - swapFee) - suite.Require().NoError(err) - - fullExpectedOutput := expectedOutput1.Add(expectedOutput2).Add(expectedOutput3) - - _, _, addr0 := testdata.KeyTestPubAddr() - simapp.FundAccount(suite.App.BankKeeper, suite.Ctx, addr0, coins) - suite.App.BankKeeper.SendCoinsFromAccountToModule(suite.Ctx, addr0, types.NonNativeFeeCollectorName, coins) - - moduleAddrFee := suite.App.AccountKeeper.GetModuleAddress(types.FeeCollectorName) - moduleAddrNonNativeFee := suite.App.AccountKeeper.GetModuleAddress(types.NonNativeFeeCollectorName) - - // make sure module account is funded with test fee tokens - suite.Require().True(suite.App.BankKeeper.HasBalance(suite.Ctx, moduleAddrNonNativeFee, coins[0])) - suite.Require().True(suite.App.BankKeeper.HasBalance(suite.Ctx, moduleAddrNonNativeFee, coins[1])) - suite.Require().True(suite.App.BankKeeper.HasBalance(suite.Ctx, moduleAddrNonNativeFee, coins[2])) - - params := suite.App.IncentivesKeeper.GetParams(suite.Ctx) - futureCtx := suite.Ctx.WithBlockTime(time.Now().Add(time.Minute)) - - suite.App.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, int64(1)) - - moduleBaseDenomBalance := suite.App.BankKeeper.GetBalance(suite.Ctx, moduleAddrFee, baseDenom) - suite.Require().Empty(suite.App.BankKeeper.GetAllBalances(suite.Ctx, moduleAddrNonNativeFee)) - suite.Require().True(moduleBaseDenomBalance.Amount.GTE(fullExpectedOutput.Amount)) + tests := []struct { + name string + coins sdk.Coins + baseDenom string + denoms []string + poolTypes []gammtypes.PoolI + swapFee sdk.Dec + expectPass bool + }{ + { + name: "One non-osmo fee token (uion): TxFees AfterEpochEnd", + coins: sdk.Coins{sdk.NewInt64Coin(uion, 10)}, + baseDenom: baseDenom, + denoms: []string{uion}, + poolTypes: []gammtypes.PoolI{uionPool}, + swapFee: sdk.MustNewDecFromStr("0"), + }, + { + name: "Multiple non-osmo fee token: TxFees AfterEpochEnd", + coins: sdk.Coins{sdk.NewInt64Coin(atom, 20), sdk.NewInt64Coin(ust, 30)}, + baseDenom: baseDenom, + denoms: []string{atom, ust}, + poolTypes: []gammtypes.PoolI{atomPool, ustPool}, + swapFee: sdk.MustNewDecFromStr("0"), + }, + } + + var finalOutputAmount = sdk.NewInt(0) + + for _, tc := range tests { + tc := tc + + suite.Run(tc.name, func() { + for i, coin := range tc.coins { + // Get the output amount in osmo denom + expectedOutput, err := tc.poolTypes[i].CalcOutAmtGivenIn(suite.Ctx, + sdk.Coins{sdk.Coin{Denom: tc.denoms[i], Amount: coin.Amount}}, + tc.baseDenom, + tc.swapFee) + suite.NoError(err) + // sanity check for the expectedAmount + suite.True(coin.Amount.GTE(expectedOutput.Amount)) + + finalOutputAmount = finalOutputAmount.Add(expectedOutput.Amount) + + // Deposit some fee amount (non-native-denom) to the fee module account + _, _, addr0 := testdata.KeyTestPubAddr() + simapp.FundAccount(suite.App.BankKeeper, suite.Ctx, addr0, sdk.Coins{coin}) + suite.App.BankKeeper.SendCoinsFromAccountToModule(suite.Ctx, addr0, types.NonNativeFeeCollectorName, sdk.Coins{coin}) + } + + // checks the balance of the non-native denom in module account + moduleAddrNonNativeFee := suite.App.AccountKeeper.GetModuleAddress(types.NonNativeFeeCollectorName) + suite.Equal(suite.App.BankKeeper.GetAllBalances(suite.Ctx, moduleAddrNonNativeFee), tc.coins) + + // End of epoch, so all the non-osmo fee amount should be swapped to osmo and transfer to fee module account + params := suite.App.IncentivesKeeper.GetParams(suite.Ctx) + futureCtx := suite.Ctx.WithBlockTime(time.Now().Add(time.Minute)) + suite.App.TxFeesKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, int64(1)) + + // check the balance of the native-basedenom in module + moduleAddrFee := suite.App.AccountKeeper.GetModuleAddress(types.FeeCollectorName) + moduleBaseDenomBalance := suite.App.BankKeeper.GetBalance(suite.Ctx, moduleAddrFee, tc.baseDenom) + + // non-osmos module account should be empty as all the funds should be transferred to osmo module + suite.Empty(suite.App.BankKeeper.GetAllBalances(suite.Ctx, moduleAddrNonNativeFee)) + // check that the total osmo amount has been transferred to module account + suite.Equal(moduleBaseDenomBalance.Amount, finalOutputAmount) + }) + } } From 716c6e4e0cb01bc089559bc3914fa17c93f73f8b Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Tue, 12 Jul 2022 01:39:21 -0700 Subject: [PATCH 057/376] x/gamm: refactor all pool_service.go tests to be properly table-driven (#1949) * refactor pool creation tests * clean up and debug tests * fix empty balance tests * remove extraneous prints and fix formatting * refactor JoinPoolNoSwap tests * refactor ExitPool tests * clean up comments * refactor empty sender tests and add more pool creation fee tests * add clarifying comments * rename feePoolBeforeNewPool to feePoolBalBeforeNewPool * minor refactor --- x/gamm/keeper/pool_service_test.go | 624 ++++++++++++++++------------- 1 file changed, 345 insertions(+), 279 deletions(-) diff --git a/x/gamm/keeper/pool_service_test.go b/x/gamm/keeper/pool_service_test.go index 1bf23d3f4d9..343aded9fa6 100644 --- a/x/gamm/keeper/pool_service_test.go +++ b/x/gamm/keeper/pool_service_test.go @@ -41,93 +41,56 @@ var ( func (suite *KeeperTestSuite) TestCreateBalancerPool() { params := suite.App.GAMMKeeper.GetParams(suite.Ctx) + // get raw pool creation fee(s) as DecCoins poolCreationFeeDecCoins := sdk.DecCoins{} for _, coin := range params.PoolCreationFee { poolCreationFeeDecCoins = poolCreationFeeDecCoins.Add(sdk.NewDecCoin(coin.Denom, coin.Amount)) } - func() { - keeper := suite.App.GAMMKeeper - - // Try to create pool without balances. - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], defaultPoolParams, defaultPoolAssets, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().Error(err) - }() - - // TODO: Refactor this to be more sensible. - // The struct should contain a MsgCreateBalancerPool. - // then the scaffolding should test pool creation, and check if it was a success or not. - // (And should be moved to balancer package) - // PoolCreationFee tests should get their own isolated test in this package. + // TODO: should be moved to balancer package tests := []struct { - fn func() - }{{ - fn: func() { - keeper := suite.App.GAMMKeeper - prevFeePool := suite.App.DistrKeeper.GetFeePoolCommunityCoins(suite.Ctx) - prevAcc1Bal := suite.App.BankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0]) - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], defaultPoolParams, defaultPoolAssets, defaultFutureGovernor) - poolId, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().NoError(err) - - pool, err := keeper.GetPoolAndPoke(suite.Ctx, poolId) - suite.Require().NoError(err) - suite.Require().Equal(types.InitPoolSharesSupply.String(), pool.GetTotalShares().String(), - fmt.Sprintf("share token should be minted as %s initially", types.InitPoolSharesSupply.String()), - ) - - // check fee is correctly sent to community pool - feePool := suite.App.DistrKeeper.GetFeePoolCommunityCoins(suite.Ctx) - suite.Require().Equal(feePool, prevFeePool.Add(poolCreationFeeDecCoins...)) - - // check account's balance is correctly reduced - acc1Bal := suite.App.BankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0]) - suite.Require().Equal(acc1Bal.String(), - prevAcc1Bal.Sub(params.PoolCreationFee). - Sub(sdk.Coins{ - sdk.NewCoin("bar", sdk.NewInt(10000)), - sdk.NewCoin("foo", sdk.NewInt(10000)), - }).Add(sdk.NewCoin(types.GetPoolShareDenom(pool.GetId()), types.InitPoolSharesSupply)).String(), - ) - - liquidity := suite.App.GAMMKeeper.GetTotalLiquidity(suite.Ctx) - suite.Require().Equal("10000bar,10000foo", liquidity.String()) - }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + name string + msg balancertypes.MsgCreateBalancerPool + emptySender bool + expectPass bool + }{ + { + name: "create pool with default assets", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], defaultPoolParams, defaultPoolAssets, defaultFutureGovernor), + emptySender: false, + expectPass: true, + }, { + name: "create pool with no assets", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], defaultPoolParams, defaultPoolAssets, defaultFutureGovernor), + emptySender: true, + expectPass: false, + }, { + name: "create a pool with negative swap fee", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(-1, 2), ExitFee: sdk.NewDecWithPrec(1, 2), - }, defaultPoolAssets, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().Error(err, "can't create a pool with negative swap fee") - }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + }, defaultPoolAssets, defaultFutureGovernor), + emptySender: false, + expectPass: false, + }, { + name: "create a pool with negative exit fee", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(1, 2), ExitFee: sdk.NewDecWithPrec(-1, 2), - }, defaultPoolAssets, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().Error(err, "can't create a pool with negative exit fee") - }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + }, defaultPoolAssets, defaultFutureGovernor), + emptySender: false, + expectPass: false, + }, { + name: "create the pool with empty PoolAssets", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(1, 2), ExitFee: sdk.NewDecWithPrec(1, 2), - }, []balancertypes.PoolAsset{}, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().Error(err, "can't create the pool with empty PoolAssets") - }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + }, []balancertypes.PoolAsset{}, defaultFutureGovernor), + emptySender: false, + expectPass: false, + }, { + name: "create the pool with 0 weighted PoolAsset", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(1, 2), ExitFee: sdk.NewDecWithPrec(1, 2), }, []balancertypes.PoolAsset{{ @@ -136,14 +99,12 @@ func (suite *KeeperTestSuite) TestCreateBalancerPool() { }, { Weight: sdk.NewInt(100), Token: sdk.NewCoin("bar", sdk.NewInt(10000)), - }}, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().Error(err, "can't create the pool with 0 weighted PoolAsset") - }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + }}, defaultFutureGovernor), + emptySender: false, + expectPass: false, + }, { + name: "create the pool with negative weighted PoolAsset", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(1, 2), ExitFee: sdk.NewDecWithPrec(1, 2), }, []balancertypes.PoolAsset{{ @@ -152,14 +113,12 @@ func (suite *KeeperTestSuite) TestCreateBalancerPool() { }, { Weight: sdk.NewInt(100), Token: sdk.NewCoin("bar", sdk.NewInt(10000)), - }}, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().Error(err, "can't create the pool with negative weighted PoolAsset") - }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + }}, defaultFutureGovernor), + emptySender: false, + expectPass: false, + }, { + name: "create the pool with 0 balance PoolAsset", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(1, 2), ExitFee: sdk.NewDecWithPrec(1, 2), }, []balancertypes.PoolAsset{{ @@ -168,14 +127,12 @@ func (suite *KeeperTestSuite) TestCreateBalancerPool() { }, { Weight: sdk.NewInt(100), Token: sdk.NewCoin("bar", sdk.NewInt(10000)), - }}, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().Error(err, "can't create the pool with 0 balance PoolAsset") - }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + }}, defaultFutureGovernor), + emptySender: false, + expectPass: false, + }, { + name: "create the pool with negative balance PoolAsset", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(1, 2), ExitFee: sdk.NewDecWithPrec(1, 2), }, []balancertypes.PoolAsset{{ @@ -187,14 +144,12 @@ func (suite *KeeperTestSuite) TestCreateBalancerPool() { }, { Weight: sdk.NewInt(100), Token: sdk.NewCoin("bar", sdk.NewInt(10000)), - }}, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().Error(err, "can't create the pool with negative balance PoolAsset") - }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + }}, defaultFutureGovernor), + emptySender: false, + expectPass: false, + }, { + name: "create the pool with duplicated PoolAssets", + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(1, 2), ExitFee: sdk.NewDecWithPrec(1, 2), }, []balancertypes.PoolAsset{{ @@ -203,53 +158,159 @@ func (suite *KeeperTestSuite) TestCreateBalancerPool() { }, { Weight: sdk.NewInt(100), Token: sdk.NewCoin("foo", sdk.NewInt(10000)), - }}, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().Error(err, "can't create the pool with duplicated PoolAssets") + }}, defaultFutureGovernor), + emptySender: false, + expectPass: false, }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - keeper.SetParams(suite.Ctx, types.Params{ - PoolCreationFee: sdk.Coins{}, - }) - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + } + + for _, test := range tests { + suite.SetupTest() + keeper := suite.App.GAMMKeeper + + // fund sender test account + sender, err := sdk.AccAddressFromBech32(test.msg.Sender) + suite.Require().NoError(err, "test: %v", test.name) + if !test.emptySender { + suite.FundAcc(sender, defaultAcctFunds) + } + + // note starting balances for community fee pool and pool creator account + feePoolBalBeforeNewPool := suite.App.DistrKeeper.GetFeePoolCommunityCoins(suite.Ctx) + senderBalBeforeNewPool := suite.App.BankKeeper.GetAllBalances(suite.Ctx, sender) + + // attempt to create a pool with the given NewMsgCreateBalancerPool message + poolId, err := keeper.CreatePool(suite.Ctx, test.msg) + + if test.expectPass { + suite.Require().NoError(err, "test: %v", test.name) + + // check to make sure new pool exists and has minted the correct number of pool shares + pool, err := keeper.GetPoolAndPoke(suite.Ctx, poolId) + suite.Require().NoError(err, "test: %v", test.name) + suite.Require().Equal(types.InitPoolSharesSupply.String(), pool.GetTotalShares().String(), + fmt.Sprintf("share token should be minted as %s initially", types.InitPoolSharesSupply.String()), + ) + + // make sure pool creation fee is correctly sent to community pool + feePool := suite.App.DistrKeeper.GetFeePoolCommunityCoins(suite.Ctx) + suite.Require().Equal(feePool, feePoolBalBeforeNewPool.Add(poolCreationFeeDecCoins...)) + + // get expected tokens in new pool and corresponding pool shares + expectedPoolTokens := sdk.Coins{} + for _, asset := range test.msg.GetPoolAssets() { + expectedPoolTokens = expectedPoolTokens.Add(asset.Token) + } + expectedPoolShares := sdk.NewCoin(types.GetPoolShareDenom(pool.GetId()), types.InitPoolSharesSupply) + + // make sure sender's balance is updated correctly + senderBal := suite.App.BankKeeper.GetAllBalances(suite.Ctx, sender) + expectedSenderBal := senderBalBeforeNewPool.Sub(params.PoolCreationFee).Sub(expectedPoolTokens).Add(expectedPoolShares) + suite.Require().Equal(senderBal.String(), expectedSenderBal.String()) + + // check pool's liquidity is correctly increased + liquidity := suite.App.GAMMKeeper.GetTotalLiquidity(suite.Ctx) + suite.Require().Equal(expectedPoolTokens.String(), liquidity.String()) + } else { + suite.Require().Error(err, "test: %v", test.name) + } + } +} + +func (suite *KeeperTestSuite) TestPoolCreationFee() { + params := suite.App.GAMMKeeper.GetParams(suite.Ctx) + + // get raw pool creation fee(s) as DecCoins + poolCreationFeeDecCoins := sdk.DecCoins{} + for _, coin := range params.PoolCreationFee { + poolCreationFeeDecCoins = poolCreationFeeDecCoins.Add(sdk.NewDecCoin(coin.Denom, coin.Amount)) + } + + tests := []struct { + name string + poolCreationFee sdk.Coins + msg balancertypes.MsgCreateBalancerPool + expectPass bool + }{ + { + name: "no pool creation fee for default asset pool", + poolCreationFee: sdk.Coins{}, + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(1, 2), ExitFee: sdk.NewDecWithPrec(1, 2), - }, defaultPoolAssets, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().NoError(err) - pools, err := keeper.GetPoolsAndPoke(suite.Ctx) - suite.Require().Len(pools, 1) - suite.Require().NoError(err) - }, - }, { - fn: func() { - keeper := suite.App.GAMMKeeper - keeper.SetParams(suite.Ctx, types.Params{ - PoolCreationFee: nil, - }) - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + }, defaultPoolAssets, defaultFutureGovernor), + expectPass: true, + }, { + name: "nil pool creation fee on basic pool", + poolCreationFee: nil, + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(1, 2), ExitFee: sdk.NewDecWithPrec(1, 2), - }, defaultPoolAssets, defaultFutureGovernor) - _, err := keeper.CreatePool(suite.Ctx, msg) - suite.Require().NoError(err) - pools, err := keeper.GetPoolsAndPoke(suite.Ctx) - suite.Require().Len(pools, 1) - suite.Require().NoError(err) + }, defaultPoolAssets, defaultFutureGovernor), + expectPass: true, + }, { + name: "attempt pool creation without sufficient funds for fees", + poolCreationFee: sdk.Coins{sdk.NewCoin("atom", sdk.NewInt(10000))}, + msg: balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ + SwapFee: sdk.NewDecWithPrec(1, 2), + ExitFee: sdk.NewDecWithPrec(1, 2), + }, defaultPoolAssets, defaultFutureGovernor), + expectPass: false, }, - }} + } for _, test := range tests { suite.SetupTest() + keeper := suite.App.GAMMKeeper - // Mint some assets to the accounts. - for _, acc := range suite.TestAccs { - suite.FundAcc(acc, defaultAcctFunds) - } + // set pool creation fee + keeper.SetParams(suite.Ctx, types.Params{ + PoolCreationFee: test.poolCreationFee, + }) + + // fund sender test account + sender, err := sdk.AccAddressFromBech32(test.msg.Sender) + suite.Require().NoError(err, "test: %v", test.name) + suite.FundAcc(sender, defaultAcctFunds) + + // note starting balances for community fee pool and pool creator account + feePoolBalBeforeNewPool := suite.App.DistrKeeper.GetFeePoolCommunityCoins(suite.Ctx) + senderBalBeforeNewPool := suite.App.BankKeeper.GetAllBalances(suite.Ctx, sender) - test.fn() + // attempt to create a pool with the given NewMsgCreateBalancerPool message + poolId, err := keeper.CreatePool(suite.Ctx, test.msg) + + if test.expectPass { + suite.Require().NoError(err, "test: %v", test.name) + + // check to make sure new pool exists and has minted the correct number of pool shares + pool, err := keeper.GetPoolAndPoke(suite.Ctx, poolId) + suite.Require().NoError(err, "test: %v", test.name) + suite.Require().Equal(types.InitPoolSharesSupply.String(), pool.GetTotalShares().String(), + fmt.Sprintf("share token should be minted as %s initially", types.InitPoolSharesSupply.String()), + ) + + // make sure pool creation fee is correctly sent to community pool + feePool := suite.App.DistrKeeper.GetFeePoolCommunityCoins(suite.Ctx) + suite.Require().Equal(feePool, feePoolBalBeforeNewPool.Add(sdk.NewDecCoinsFromCoins(test.poolCreationFee...)...)) + // get expected tokens in new pool and corresponding pool shares + expectedPoolTokens := sdk.Coins{} + for _, asset := range test.msg.GetPoolAssets() { + expectedPoolTokens = expectedPoolTokens.Add(asset.Token) + } + expectedPoolShares := sdk.NewCoin(types.GetPoolShareDenom(pool.GetId()), types.InitPoolSharesSupply) + + // make sure sender's balance is updated correctly + senderBal := suite.App.BankKeeper.GetAllBalances(suite.Ctx, sender) + expectedSenderBal := senderBalBeforeNewPool.Sub(test.poolCreationFee).Sub(expectedPoolTokens).Add(expectedPoolShares) + suite.Require().Equal(senderBal.String(), expectedSenderBal.String()) + + // check pool's liquidity is correctly increased + liquidity := suite.App.GAMMKeeper.GetTotalLiquidity(suite.Ctx) + suite.Require().Equal(expectedPoolTokens.String(), liquidity.String()) + } else { + suite.Require().Error(err, "test: %v", test.name) + } } } @@ -257,93 +318,69 @@ func (suite *KeeperTestSuite) TestCreateBalancerPool() { func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { fiveKFooAndBar := sdk.NewCoins(sdk.NewCoin("bar", sdk.NewInt(5000)), sdk.NewCoin("foo", sdk.NewInt(5000))) tests := []struct { - fn func(poolId uint64) + name string + txSender sdk.AccAddress + sharesRequested sdk.Int + tokenInMaxs sdk.Coins + expectPass bool }{ { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - balancesBefore := suite.App.BankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[1]) - neededLp, sharesOut, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{}) - suite.Require().NoError(err) - suite.Require().Equal(types.OneShare.MulRaw(50).String(), sharesOut.String()) - suite.Require().Equal(types.OneShare.MulRaw(50).String(), suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], "gamm/pool/1").Amount.String()) - balancesAfter := suite.App.BankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[1]) - - deltaBalances, _ := balancesBefore.SafeSub(balancesAfter) - // The pool was created with the 10000foo, 10000bar, and the pool share was minted as 100000000gamm/pool/1. - // Thus, to get the 50*OneShare gamm/pool/1, (10000foo, 10000bar) * (1 / 2) balances should be provided. - suite.Require().Equal(deltaBalances.FilterDenoms([]string{"foo", "bar"}).Sort().String(), neededLp.Sort().String()) - suite.Require().Equal("5000", deltaBalances.AmountOf("foo").String()) - suite.Require().Equal("5000", deltaBalances.AmountOf("bar").String()) - - liquidity := suite.App.GAMMKeeper.GetTotalLiquidity(suite.Ctx) - suite.Require().Equal("15000bar,15000foo", liquidity.String()) - }, + name: "basic join no swap", + txSender: suite.TestAccs[1], + sharesRequested: types.OneShare.MulRaw(50), + tokenInMaxs: sdk.Coins{}, + expectPass: true, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - _, _, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, sdk.NewInt(0), sdk.Coins{}) - suite.Require().Error(err, "can't join the pool with requesting 0 share amount") - }, + name: "join no swap with zero shares requested", + txSender: suite.TestAccs[1], + sharesRequested: sdk.NewInt(0), + tokenInMaxs: sdk.Coins{}, + expectPass: false, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - _, _, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, sdk.NewInt(-1), sdk.Coins{}) - suite.Require().Error(err, "can't join the pool with requesting negative share amount") - }, + name: "join no swap with negative shares requested", + txSender: suite.TestAccs[1], + sharesRequested: sdk.NewInt(-1), + tokenInMaxs: sdk.Coins{}, + expectPass: false, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - // Test the "tokenInMaxs" - // In this case, to get the 50 * OneShare amount of share token, the foo, bar token are expected to be provided as 5000 amounts. - _, _, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ - sdk.NewCoin("bar", sdk.NewInt(4999)), sdk.NewCoin("foo", sdk.NewInt(4999)), - }) - suite.Require().Error(err) + name: "join no swap with insufficient funds", + txSender: suite.TestAccs[1], + sharesRequested: sdk.NewInt(-1), + tokenInMaxs: sdk.Coins{ + sdk.NewCoin("bar", sdk.NewInt(4999)), sdk.NewCoin("foo", sdk.NewInt(4999)), }, + expectPass: false, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - // Test the "tokenInMaxs" - // In this case, to get the 50 * OneShare amount of share token, the foo, bar token are expected to be provided as 5000 amounts. - actualTokenIn, actualSharesOut, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ - fiveKFooAndBar[0], fiveKFooAndBar[1]}) - suite.Require().NoError(err) - - liquidity := suite.App.GAMMKeeper.GetTotalLiquidity(suite.Ctx) - suite.Require().Equal("15000bar,15000foo", liquidity.String()) - // TODO: Add these tests to more cases, as part of improving this test structure. - // 100% add, so actualTokenIn = max provided - suite.Require().Equal(fiveKFooAndBar, actualTokenIn) - // shares out was estimated perfectly - suite.Require().Equal(types.OneShare.MulRaw(50), actualSharesOut) + name: "join no swap with exact tokenInMaxs", + txSender: suite.TestAccs[1], + sharesRequested: types.OneShare.MulRaw(50), + tokenInMaxs: sdk.Coins{ + fiveKFooAndBar[0], fiveKFooAndBar[1], }, + expectPass: true, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - // Test the "tokenInMaxs" with an additional invalid denom - // In this case, to get the 50 * OneShare amount of share token, the foo, bar token are expected to be provided as 5000 amounts. - // The test input has the correct amount for each, but also includes an incorrect denom that should cause an error - _, _, err := keeper.JoinPoolNoSwap(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{ - sdk.NewCoin("bar", sdk.NewInt(5000)), sdk.NewCoin("foo", sdk.NewInt(5000)), sdk.NewCoin("baz", sdk.NewInt(5000)), - }) - suite.Require().Error(err) + name: "join no swap with arbitrary extra token in tokenInMaxs", + txSender: suite.TestAccs[1], + sharesRequested: types.OneShare.MulRaw(50), + tokenInMaxs: sdk.Coins{ + fiveKFooAndBar[0], fiveKFooAndBar[1], sdk.NewCoin("baz", sdk.NewInt(5000)), }, + expectPass: false, }, } for _, test := range tests { suite.SetupTest() + keeper := suite.App.GAMMKeeper + // Mint some assets to the accounts. - for _, acc := range suite.TestAccs { - suite.FundAcc(acc, defaultAcctFunds) - } + suite.FundAcc(suite.TestAccs[0], defaultAcctFunds) // Create the pool at first msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ @@ -351,102 +388,132 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { ExitFee: sdk.NewDecWithPrec(1, 2), }, defaultPoolAssets, defaultFutureGovernor) poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, msg) - suite.Require().NoError(err) + suite.Require().NoError(err, "test: %v", test.name) - test.fn(poolId) + suite.FundAcc(test.txSender, defaultAcctFunds) + + balancesBefore := suite.App.BankKeeper.GetAllBalances(suite.Ctx, test.txSender) + _, _, err = keeper.JoinPoolNoSwap(suite.Ctx, test.txSender, poolId, test.sharesRequested, test.tokenInMaxs) + + if test.expectPass { + suite.Require().NoError(err, "test: %v", test.name) + suite.Require().Equal(test.sharesRequested.String(), suite.App.BankKeeper.GetBalance(suite.Ctx, test.txSender, "gamm/pool/1").Amount.String()) + balancesAfter := suite.App.BankKeeper.GetAllBalances(suite.Ctx, test.txSender) + deltaBalances, _ := balancesBefore.SafeSub(balancesAfter) + // The pool was created with the 10000foo, 10000bar, and the pool share was minted as 100000000gamm/pool/1. + // Thus, to get the 50*OneShare gamm/pool/1, (10000foo, 10000bar) * (1 / 2) balances should be provided. + suite.Require().Equal("5000", deltaBalances.AmountOf("foo").String()) + suite.Require().Equal("5000", deltaBalances.AmountOf("bar").String()) + + liquidity := suite.App.GAMMKeeper.GetTotalLiquidity(suite.Ctx) + suite.Require().Equal("15000bar,15000foo", liquidity.String()) + } else { + suite.Require().Error(err, "test: %v", test.name) + } } } func (suite *KeeperTestSuite) TestExitPool() { fiveKFooAndBar := sdk.NewCoins(sdk.NewCoin("bar", sdk.NewInt(5000)), sdk.NewCoin("foo", sdk.NewInt(5000))) tests := []struct { - fn func(poolId uint64) + name string + txSender sdk.AccAddress + sharesIn sdk.Int + tokenOutMins sdk.Coins + emptySender bool + expectPass bool }{ { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - // Acc2 has no share token. - _, err := keeper.ExitPool(suite.Ctx, suite.TestAccs[1], poolId, types.OneShare.MulRaw(50), sdk.Coins{}) - suite.Require().Error(err) - }, + name: "attempt exit pool with no pool share balance", + txSender: suite.TestAccs[0], + sharesIn: types.OneShare.MulRaw(50), + tokenOutMins: sdk.Coins{}, + emptySender: true, + expectPass: false, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - - balancesBefore := suite.App.BankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0]) - _, err := keeper.ExitPool(suite.Ctx, suite.TestAccs[0], poolId, types.InitPoolSharesSupply.QuoRaw(2), sdk.Coins{}) - suite.Require().NoError(err) - // (100 - 50) * OneShare should remain. - suite.Require().Equal(types.InitPoolSharesSupply.QuoRaw(2).String(), suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], "gamm/pool/1").Amount.String()) - balancesAfter := suite.App.BankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0]) - - deltaBalances, _ := balancesBefore.SafeSub(balancesAfter) - // The pool was created with the 10000foo, 10000bar, and the pool share was minted as 100*OneShare gamm/pool/1. - // Thus, to refund the 50*OneShare gamm/pool/1, (10000foo, 10000bar) * (1 / 2) balances should be refunded. - suite.Require().Equal("-5000", deltaBalances.AmountOf("foo").String()) - suite.Require().Equal("-5000", deltaBalances.AmountOf("bar").String()) - }, + name: "exit half pool with correct pool share balance", + txSender: suite.TestAccs[0], + sharesIn: types.OneShare.MulRaw(50), + tokenOutMins: sdk.Coins{}, + emptySender: false, + expectPass: true, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - - _, err := keeper.ExitPool(suite.Ctx, suite.TestAccs[0], poolId, sdk.NewInt(0), sdk.Coins{}) - suite.Require().Error(err, "can't join the pool with requesting 0 share amount") - }, + name: "attempt exit pool requesting 0 share amount", + txSender: suite.TestAccs[0], + sharesIn: sdk.NewInt(0), + tokenOutMins: sdk.Coins{}, + emptySender: false, + expectPass: false, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - - _, err := keeper.ExitPool(suite.Ctx, suite.TestAccs[0], poolId, sdk.NewInt(-1), sdk.Coins{}) - suite.Require().Error(err, "can't join the pool with requesting negative share amount") - }, + name: "attempt exit pool requesting negative share amount", + txSender: suite.TestAccs[0], + sharesIn: sdk.NewInt(-1), + tokenOutMins: sdk.Coins{}, + emptySender: false, + expectPass: false, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - - // Test the "tokenOutMins" - // In this case, to refund the 50000000 amount of share token, the foo, bar token are expected to be refunded as 5000 amounts. - _, err := keeper.ExitPool(suite.Ctx, suite.TestAccs[0], poolId, types.OneShare.MulRaw(50), sdk.Coins{ - sdk.NewCoin("foo", sdk.NewInt(5001)), - }) - suite.Require().Error(err) + name: "attempt exit pool with tokenOutMins above actual output", + txSender: suite.TestAccs[0], + sharesIn: types.OneShare.MulRaw(50), + tokenOutMins: sdk.Coins{ + sdk.NewCoin("foo", sdk.NewInt(5001)), }, + emptySender: false, + expectPass: false, }, { - fn: func(poolId uint64) { - keeper := suite.App.GAMMKeeper - - // Test the "tokenOutMins" - // In this case, to refund the 50000000 amount of share token, the foo, bar token are expected to be refunded as 5000 amounts. - exitedCoins, err := keeper.ExitPool(suite.Ctx, suite.TestAccs[0], poolId, types.OneShare.MulRaw(50), sdk.Coins{ - sdk.NewCoin("foo", sdk.NewInt(5000)), - }) - suite.Require().NoError(err) - suite.Require().Equal(fiveKFooAndBar, exitedCoins) + name: "attempt exit pool requesting tokenOutMins at exactly the actual output", + txSender: suite.TestAccs[0], + sharesIn: types.OneShare.MulRaw(50), + tokenOutMins: sdk.Coins{ + fiveKFooAndBar[1], }, + emptySender: false, + expectPass: true, }, } for _, test := range tests { suite.SetupTest() - // Mint some assets to the accounts. - for _, acc := range suite.TestAccs { - suite.FundAcc(acc, defaultAcctFunds) + keeper := suite.App.GAMMKeeper - // Create the pool at first - msg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ - SwapFee: sdk.NewDecWithPrec(1, 2), - ExitFee: sdk.NewDec(0), - }, defaultPoolAssets, defaultFutureGovernor) - poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, msg) - suite.Require().NoError(err) + // Mint assets to the pool creator + suite.FundAcc(test.txSender, defaultAcctFunds) - test.fn(poolId) + // Create the pool at first + msg := balancer.NewMsgCreateBalancerPool(test.txSender, balancer.PoolParams{ + SwapFee: sdk.NewDecWithPrec(1, 2), + ExitFee: sdk.NewDec(0), + }, defaultPoolAssets, defaultFutureGovernor) + poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, msg) + + // If we are testing insufficient pool share balances, switch tx sender from pool creator to empty account + if test.emptySender { + test.txSender = suite.TestAccs[1] + } + + balancesBefore := suite.App.BankKeeper.GetAllBalances(suite.Ctx, test.txSender) + _, err = keeper.ExitPool(suite.Ctx, test.txSender, poolId, test.sharesIn, test.tokenOutMins) + + if test.expectPass { + suite.Require().NoError(err, "test: %v", test.name) + suite.Require().Equal(test.sharesIn.String(), suite.App.BankKeeper.GetBalance(suite.Ctx, test.txSender, "gamm/pool/1").Amount.String()) + balancesAfter := suite.App.BankKeeper.GetAllBalances(suite.Ctx, test.txSender) + deltaBalances, _ := balancesBefore.SafeSub(balancesAfter) + // The pool was created with the 10000foo, 10000bar, and the pool share was minted as 100*OneShare gamm/pool/1. + // Thus, to refund the 50*OneShare gamm/pool/1, (10000foo, 10000bar) * (1 / 2) balances should be refunded. + suite.Require().Equal("-5000", deltaBalances.AmountOf("foo").String()) + suite.Require().Equal("-5000", deltaBalances.AmountOf("bar").String()) + + liquidity := suite.App.GAMMKeeper.GetTotalLiquidity(suite.Ctx) + suite.Require().Equal("5000bar,5000foo", liquidity.String()) + } else { + suite.Require().Error(err, "test: %v", test.name) } } } @@ -512,11 +579,10 @@ func (suite *KeeperTestSuite) TestJoinPoolExitPool_InverseRelationship() { poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, tc.pool) suite.Require().NoError(err) - balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) - fmt.Println(balanceBeforeJoin.String()) + balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) - _, _, err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) - suite.Require().NoError(err) + _, _, err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) + suite.Require().NoError(err) _, err = suite.App.GAMMKeeper.ExitPool(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) From 3be2640a842394e962e323e9ad1885019e4e4229 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Tue, 12 Jul 2022 12:03:57 -0500 Subject: [PATCH 058/376] x/incentives: remaining audit updates (#1997) * remaining updates to incentives * regen protos * remove todo * Delete handler.go * bez fix * address Roman comments * Apply suggestions from code review Co-authored-by: Roman * comment out unused function * remove TODOs and dead code * Update x/incentives/keeper/distribute.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * remove comment Co-authored-by: Roman Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> --- x/incentives/keeper/distribute.go | 78 ++++++++++++-------------- x/incentives/keeper/gauge.go | 38 +++++++------ x/incentives/keeper/genesis.go | 5 +- x/incentives/keeper/grpc_query.go | 30 +++++----- x/incentives/keeper/hooks.go | 10 ++-- x/incentives/keeper/iterator.go | 17 +++--- x/incentives/keeper/keeper.go | 10 +++- x/incentives/keeper/msg_server.go | 7 ++- x/incentives/keeper/params.go | 4 +- x/incentives/keeper/store.go | 19 ++++--- x/incentives/keeper/utils.go | 6 +- x/incentives/module.go | 60 ++++++++++---------- x/incentives/simulation/genesis.go | 5 +- x/incentives/simulation/operations.go | 17 +++--- x/incentives/simulation/params.go | 6 +- x/incentives/types/codec.go | 16 +++--- x/incentives/types/events.go | 2 +- x/incentives/types/expected_keepers.go | 1 + x/incentives/types/gauge.go | 4 ++ x/incentives/types/genesis.go | 10 ++-- x/incentives/types/hooks.go | 3 +- x/incentives/types/msgs.go | 23 ++++++-- x/incentives/types/msgs_test.go | 13 ++++- x/incentives/types/params.go | 11 ++-- 24 files changed, 219 insertions(+), 176 deletions(-) diff --git a/x/incentives/keeper/distribute.go b/x/incentives/keeper/distribute.go index f2700445e32..cad4970aac8 100644 --- a/x/incentives/keeper/distribute.go +++ b/x/incentives/keeper/distribute.go @@ -12,6 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// getDistributedCoinsFromGauges returns coins that have been distributed already from the provided gauges func (k Keeper) getDistributedCoinsFromGauges(gauges []types.Gauge) sdk.Coins { coins := sdk.Coins{} for _, gauge := range gauges { @@ -20,6 +21,7 @@ func (k Keeper) getDistributedCoinsFromGauges(gauges []types.Gauge) sdk.Coins { return coins } +// getToDistributeCoinsFromGauges returns coins that have not been distributed yet from the provided gauges func (k Keeper) getToDistributeCoinsFromGauges(gauges []types.Gauge) sdk.Coins { coins := sdk.Coins{} distributed := sdk.Coins{} @@ -28,19 +30,22 @@ func (k Keeper) getToDistributeCoinsFromGauges(gauges []types.Gauge) sdk.Coins { coins = coins.Add(gauge.Coins...) distributed = distributed.Add(gauge.DistributedCoins...) } - return coins.Sub(distributed) } +// getToDistributeCoinsFromIterator utilizes iterator to return a list of gauges. +// From these gauges, coins that have not yet been distributed are returned func (k Keeper) getToDistributeCoinsFromIterator(ctx sdk.Context, iterator db.Iterator) sdk.Coins { return k.getToDistributeCoinsFromGauges(k.getGaugesFromIterator(ctx, iterator)) } +// getDistributedCoinsFromIterator utilizes iterator to return a list of gauges. +// From these gauges, coins that have already been distributed are returned func (k Keeper) getDistributedCoinsFromIterator(ctx sdk.Context, iterator db.Iterator) sdk.Coins { return k.getDistributedCoinsFromGauges(k.getGaugesFromIterator(ctx, iterator)) } -// moveUpcomingGaugeToActiveGauge is a utility to begin distribution for a specific gauge. +// moveUpcomingGaugeToActiveGauge moves a gauge that has reached it's start time from an upcoming to an active status. func (k Keeper) moveUpcomingGaugeToActiveGauge(ctx sdk.Context, gauge types.Gauge) error { // validation for current time and distribution start time if ctx.BlockTime().Before(gauge.StartTime) { @@ -57,7 +62,7 @@ func (k Keeper) moveUpcomingGaugeToActiveGauge(ctx sdk.Context, gauge types.Gaug return nil } -// moveActiveGaugeToFinishedGauge is a utility to finish distribution for a specific gauge. +// moveActiveGaugeToFinishedGauge moves a gauge that has completed its distribution from an active to a finished status. func (k Keeper) moveActiveGaugeToFinishedGauge(ctx sdk.Context, gauge types.Gauge) error { timeKey := getTimeKey(gauge.StartTime) if err := k.deleteGaugeRefByKey(ctx, combineKeys(types.KeyPrefixActiveGauges, timeKey), gauge.Id); err != nil { @@ -73,41 +78,24 @@ func (k Keeper) moveActiveGaugeToFinishedGauge(ctx sdk.Context, gauge types.Gaug return nil } -// GetLocksToDistribution get locks that are associated to a condition. -func (k Keeper) GetLocksToDistribution(ctx sdk.Context, distrTo lockuptypes.QueryCondition) []lockuptypes.PeriodLock { - switch distrTo.LockQueryType { - case lockuptypes.ByDuration: - return k.lk.GetLocksLongerThanDurationDenom(ctx, distrTo.Denom, distrTo.Duration) - case lockuptypes.ByTime: - return k.lk.GetLocksPastTimeDenom(ctx, distrTo.Denom, distrTo.Timestamp) - default: - } - return []lockuptypes.PeriodLock{} -} - -// getLocksToDistributionWithMaxDuration get locks that are associated to a condition -// and if its by duration, then use the min Duration. +// getLocksToDistributionWithMaxDuration returns locks that match the provided lockuptypes QueryCondition, +// are greater than the provided minDuration, AND have yet to be distributed to. func (k Keeper) getLocksToDistributionWithMaxDuration(ctx sdk.Context, distrTo lockuptypes.QueryCondition, minDuration time.Duration) []lockuptypes.PeriodLock { switch distrTo.LockQueryType { case lockuptypes.ByDuration: - // TODO: FIX ME!!!! - // Confusingly, synthetic lockups aren't indexed by denom as expected. - // Thus you have to do this as a hack denom := lockuptypes.NativeDenom(distrTo.Denom) if distrTo.Duration > minDuration { return k.lk.GetLocksLongerThanDurationDenom(ctx, denom, minDuration) } return k.lk.GetLocksLongerThanDurationDenom(ctx, distrTo.Denom, distrTo.Duration) case lockuptypes.ByTime: - panic("Gauge by time is present!?!? Should have been blocked in ValidateBasic") + panic("Gauge by time is present, however is no longer supported. This should have been blocked in ValidateBasic") default: } return []lockuptypes.PeriodLock{} } -// FilteredLocksDistributionEst estimate distribution amount coins from gauge for fitting conditions -// Expectation: gauge is a valid gauge -// filteredLocks are all locks that are valid for gauge +// FilteredLocksDistributionEst estimates distribution amount of coins from gauge. // It also applies an update for the gauge, handling the sending of the rewards. // (Note this update is in-memory, it does not change state.) func (k Keeper) FilteredLocksDistributionEst(ctx sdk.Context, gauge types.Gauge, filteredLocks []lockuptypes.PeriodLock) (types.Gauge, sdk.Coins, bool, error) { @@ -120,9 +108,9 @@ func (k Keeper) FilteredLocksDistributionEst(ctx sdk.Context, gauge types.Gauge, } remainCoins := gauge.Coins.Sub(gauge.DistributedCoins) - // Remaining epochs is the number of remaining epochs that the gauge will pay out its rewards - // For a perpetual gauge, it will pay out everything in the next epoch, and we don't make - // an assumption for what rate it will get refilled at. + // remainEpochs is the number of remaining epochs that the gauge will pay out its rewards. + // for a perpetual gauge, it will pay out everything in the next epoch, and we don't make + // an assumption of the rate at which it will get refilled at. remainEpochs := uint64(1) if !gauge.IsPerpetual { remainEpochs = gauge.NumEpochsPaidOver - gauge.FilledEpochs @@ -138,10 +126,10 @@ func (k Keeper) FilteredLocksDistributionEst(ctx sdk.Context, gauge types.Gauge, remainCoinsPerEpoch = remainCoinsPerEpoch.Add(sdk.NewCoin(coin.Denom, amt)) } - // Now we compute the filtered coins + // now we compute the filtered coins filteredDistrCoins := sdk.Coins{} if len(filteredLocks) == 0 { - // If were doing no filtering, we want to calculate the total amount to distributed in + // if were doing no filtering, we want to calculate the total amount to distributed in // the next epoch. // distribution in next epoch = gauge_size / (remain_epochs) filteredDistrCoins = remainCoinsPerEpoch @@ -174,6 +162,7 @@ type distributionInfo struct { idToDistrCoins []sdk.Coins } +// newDistributionInfo creates a new distributionInfo struct func newDistributionInfo() distributionInfo { return distributionInfo{ nextID: 0, @@ -184,6 +173,7 @@ func newDistributionInfo() distributionInfo { } } +// addLockRewards adds the provided rewards to the lockID mapped to the provided owner address. func (d *distributionInfo) addLockRewards(owner string, rewards sdk.Coins) error { if id, ok := d.lockOwnerAddrToID[owner]; ok { oldDistrCoins := d.idToDistrCoins[id] @@ -203,6 +193,7 @@ func (d *distributionInfo) addLockRewards(owner string, rewards sdk.Coins) error return nil } +// doDistributionSends utilizes provided distributionInfo to send coins from the module account to various recipients. func (k Keeper) doDistributionSends(ctx sdk.Context, distrs *distributionInfo) error { numIDs := len(distrs.idToDecodedAddr) ctx.Logger().Debug(fmt.Sprintf("Beginning distribution to %d users", numIDs)) @@ -229,7 +220,7 @@ func (k Keeper) doDistributionSends(ctx sdk.Context, distrs *distributionInfo) e } // distributeSyntheticInternal runs the distribution logic for a synthetic rewards distribution gauge, and adds the sends to -// the distrInfo computed. It also updates the gauge for the distribution. +// the distrInfo struct. It also updates the gauge for the distribution. // locks is expected to be the correct set of lock recipients for this gauge. func (k Keeper) distributeSyntheticInternal( ctx sdk.Context, gauge types.Gauge, locks []lockuptypes.PeriodLock, distrInfo *distributionInfo, @@ -238,7 +229,7 @@ func (k Keeper) distributeSyntheticInternal( qualifiedLocks := make([]lockuptypes.PeriodLock, 0, len(locks)) for _, lock := range locks { - // See if this lock has a synthetic lockup. If so, err == nil, and we add to qualifiedLocks + // see if this lock has a synthetic lockup. If so, err == nil, and we add to qualifiedLocks. // otherwise it does not, and we continue. _, err := k.lk.GetSyntheticLockup(ctx, lock.ID, denom) if err != nil { @@ -251,8 +242,8 @@ func (k Keeper) distributeSyntheticInternal( } // distributeInternal runs the distribution logic for a gauge, and adds the sends to -// the distrInfo computed. It also updates the gauge for the distribution. -// locks is expected to be the correct set of lock recipients for this gauge. +// the distrInfo struct. It also updates the gauge for the distribution. +// Locks is expected to be the correct set of lock recipients for this gauge. func (k Keeper) distributeInternal( ctx sdk.Context, gauge types.Gauge, locks []lockuptypes.PeriodLock, distrInfo *distributionInfo, ) (sdk.Coins, error) { @@ -265,8 +256,10 @@ func (k Keeper) distributeInternal( } remainCoins := gauge.Coins.Sub(gauge.DistributedCoins) + // if its a perpetual gauge, we set remaining epochs to 1. + // otherwise is is a non perpetual gauge and we determine how many epoch payouts are left remainEpochs := uint64(1) - if !gauge.IsPerpetual { // set remain epochs when it's not perpetual gauge + if !gauge.IsPerpetual { remainEpochs = gauge.NumEpochsPaidOver - gauge.FilledEpochs } @@ -285,7 +278,7 @@ func (k Keeper) distributeInternal( if distrCoins.Empty() { continue } - // Update the amount for that address + // update the amount for that address err := distrInfo.addLockRewards(lock.Owner, distrCoins) if err != nil { return nil, err @@ -298,8 +291,9 @@ func (k Keeper) distributeInternal( return totalDistrCoins, err } +// updateGaugePostDistribute increments the gauge's filled epochs field. +// Also adds the coins that were just distributed to the gauge's distributed coins field. func (k Keeper) updateGaugePostDistribute(ctx sdk.Context, gauge types.Gauge, newlyDistributedCoins sdk.Coins) error { - // increase filled epochs after distribution gauge.FilledEpochs += 1 gauge.DistributedCoins = gauge.DistributedCoins.Add(newlyDistributedCoins...) if err := k.setGauge(ctx, &gauge); err != nil { @@ -308,12 +302,12 @@ func (k Keeper) updateGaugePostDistribute(ctx sdk.Context, gauge types.Gauge, ne return nil } +// getDistributeToBaseLocks takes a gauge along with cached period locks by denom and returns locks that must be distributed to func (k Keeper) getDistributeToBaseLocks(ctx sdk.Context, gauge types.Gauge, cache map[string][]lockuptypes.PeriodLock) []lockuptypes.PeriodLock { // if gauge is empty, don't get the locks if gauge.Coins.Empty() { return []lockuptypes.PeriodLock{} } - // TODO: FIXME!!! // Confusingly, there is no way to get all synthetic lockups. Thus we use a separate method `distributeSyntheticInternal` to separately get lockSum for synthetic lockups. // All gauges have a precondition of being ByDuration. distributeBaseDenom := lockuptypes.NativeDenom(gauge.DistributeTo.Denom) @@ -327,7 +321,7 @@ func (k Keeper) getDistributeToBaseLocks(ctx sdk.Context, gauge types.Gauge, cac return FilterLocksByMinDuration(allLocks, gauge.DistributeTo.Duration) } -// Distribute coins from gauge according to its conditions. +// Distribute distributes coins from an array of gauges to all eligible locks. func (k Keeper) Distribute(ctx sdk.Context, gauges []types.Gauge) (sdk.Coins, error) { distrInfo := newDistributionInfo() @@ -359,11 +353,11 @@ func (k Keeper) Distribute(ctx sdk.Context, gauges []types.Gauge) (sdk.Coins, er return totalDistributedCoins, nil } +// checkFinishDistribution checks if all non perpetual gauges provided have completed their required distributions. +// If complete, move the gauge from an active to a finished status. func (k Keeper) checkFinishDistribution(ctx sdk.Context, gauges []types.Gauge) { for _, gauge := range gauges { // filled epoch is increased in this step and we compare with +1 - // TODO: Wat? we increment filled epochs earlier, this looks wrong and like - // were not paying out the last epoch of rewards... if !gauge.IsPerpetual && gauge.NumEpochsPaidOver <= gauge.FilledEpochs+1 { if err := k.moveActiveGaugeToFinishedGauge(ctx, gauge); err != nil { panic(err) @@ -372,14 +366,14 @@ func (k Keeper) checkFinishDistribution(ctx sdk.Context, gauges []types.Gauge) { } } -// GetModuleToDistributeCoins returns sum of to distribute coins for all of the module. +// GetModuleToDistributeCoins returns sum of coins yet to be distributed for all of the module. func (k Keeper) GetModuleToDistributeCoins(ctx sdk.Context) sdk.Coins { activeGaugesDistr := k.getToDistributeCoinsFromIterator(ctx, k.ActiveGaugesIterator(ctx)) upcomingGaugesDistr := k.getToDistributeCoinsFromIterator(ctx, k.UpcomingGaugesIteratorAfterTime(ctx, ctx.BlockTime())) return activeGaugesDistr.Add(upcomingGaugesDistr...) } -// GetModuleDistributedCoins returns sum of distributed coins so far. +// GetModuleDistributedCoins returns sum of coins that have been distributed so far for all of the module. func (k Keeper) GetModuleDistributedCoins(ctx sdk.Context) sdk.Coins { activeGaugesDistr := k.getDistributedCoinsFromIterator(ctx, k.ActiveGaugesIterator(ctx)) finishedGaugesDistr := k.getDistributedCoinsFromIterator(ctx, k.FinishedGaugesIterator(ctx)) diff --git a/x/incentives/keeper/gauge.go b/x/incentives/keeper/gauge.go index 8dfe12d1ac7..0f1348d6a11 100644 --- a/x/incentives/keeper/gauge.go +++ b/x/incentives/keeper/gauge.go @@ -17,7 +17,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Iterate over everything in a gauges iterator, until it reaches the end. Return all gauges iterated over. +// getGaugesFromIterator iterates over everything in a gauge's iterator, until it reaches the end. Return all gauges iterated over. func (k Keeper) getGaugesFromIterator(ctx sdk.Context, iterator db.Iterator) []types.Gauge { gauges := []types.Gauge{} defer iterator.Close() @@ -49,7 +49,9 @@ func (k Keeper) setGauge(ctx sdk.Context, gauge *types.Gauge) error { return nil } -// CreateGaugeRefKeys adds gauge references as needed. Used to consolidate codepaths for InitGenesis and CreateGauge. +// CreateGaugeRefKeys takes combinedKey (the keyPrefix for upcoming, active, or finished gauges combined with gauge start time) and adds a reference to the respective gauge ID. +// If gauge is active or upcoming, creates reference between the denom and gauge ID. +// Used to consolidate codepaths for InitGenesis and CreateGauge. func (k Keeper) CreateGaugeRefKeys(ctx sdk.Context, gauge *types.Gauge, combinedKeys []byte, activeOrUpcomingGauge bool) error { if err := k.addGaugeRefByKey(ctx, combinedKeys, gauge.Id); err != nil { return err @@ -62,6 +64,9 @@ func (k Keeper) CreateGaugeRefKeys(ctx sdk.Context, gauge *types.Gauge, combined return nil } +// SetGaugeWithRefKey takes a single gauge and assigns a key. +// Takes combinedKey (the keyPrefix for upcoming, active, or finished gauges combined with gauge start time) and adds a reference to the respective gauge ID. +// If this gauge is active or upcoming, creates reference between the denom and gauge ID. func (k Keeper) SetGaugeWithRefKey(ctx sdk.Context, gauge *types.Gauge) error { err := k.setGauge(ctx, gauge) if err != nil { @@ -84,7 +89,7 @@ func (k Keeper) SetGaugeWithRefKey(ctx sdk.Context, gauge *types.Gauge) error { } } -// CreateGauge create a gauge and send coins to the gauge. +// CreateGauge creates a gauge and sends coins to the gauge. func (k Keeper) CreateGauge(ctx sdk.Context, isPerpetual bool, owner sdk.AccAddress, coins sdk.Coins, distrTo lockuptypes.QueryCondition, startTime time.Time, numEpochsPaidOver uint64) (uint64, error) { // Ensure that this gauge's duration is one of the allowed durations on chain durations := k.GetLockableDurations(ctx) @@ -125,7 +130,6 @@ func (k Keeper) CreateGauge(ctx sdk.Context, isPerpetual bool, owner sdk.AccAddr } k.SetLastGaugeID(ctx, gauge.Id) - // TODO: Do we need to be concerned with case where this should be ActiveGauges? combinedKeys := combineKeys(types.KeyPrefixUpcomingGauges, getTimeKey(gauge.StartTime)) activeOrUpcomingGauge := true @@ -137,7 +141,7 @@ func (k Keeper) CreateGauge(ctx sdk.Context, isPerpetual bool, owner sdk.AccAddr return gauge.Id, nil } -// AddToGauge add coins to gauge. +// AddToGaugeRewards adds coins to gauge. func (k Keeper) AddToGaugeRewards(ctx sdk.Context, owner sdk.AccAddress, coins sdk.Coins, gaugeID uint64) error { gauge, err := k.GetGaugeByID(ctx, gaugeID) if err != nil { @@ -156,7 +160,7 @@ func (k Keeper) AddToGaugeRewards(ctx sdk.Context, owner sdk.AccAddress, coins s return nil } -// GetGaugeByID Returns gauge from gauge ID. +// GetGaugeByID returns gauge from gauge ID. func (k Keeper) GetGaugeByID(ctx sdk.Context, gaugeID uint64) (*types.Gauge, error) { gauge := types.Gauge{} store := ctx.KVStore(k.storeKey) @@ -171,7 +175,7 @@ func (k Keeper) GetGaugeByID(ctx sdk.Context, gaugeID uint64) (*types.Gauge, err return &gauge, nil } -// GetGaugeFromIDs returns gauges from gauge ids reference. +// GetGaugeFromIDs returns multiple gauges from a gaugeIDs array. func (k Keeper) GetGaugeFromIDs(ctx sdk.Context, gaugeIDs []uint64) ([]types.Gauge, error) { gauges := []types.Gauge{} for _, gaugeID := range gaugeIDs { @@ -184,11 +188,12 @@ func (k Keeper) GetGaugeFromIDs(ctx sdk.Context, gaugeIDs []uint64) ([]types.Gau return gauges, nil } -// GetGauges returns gauges both upcoming and active. +// GetGauges returns upcoming, active, and finished gauges. func (k Keeper) GetGauges(ctx sdk.Context) []types.Gauge { return k.getGaugesFromIterator(ctx, k.GaugesIterator(ctx)) } +// GetNotFinishedGauges returns both upcoming and active gauges. func (k Keeper) GetNotFinishedGauges(ctx sdk.Context) []types.Gauge { return append(k.GetActiveGauges(ctx), k.GetUpcomingGauges(ctx)...) } @@ -198,7 +203,7 @@ func (k Keeper) GetActiveGauges(ctx sdk.Context) []types.Gauge { return k.getGaugesFromIterator(ctx, k.ActiveGaugesIterator(ctx)) } -// GetUpcomingGauges returns scheduled gauges. +// GetUpcomingGauges returns upcoming gauges. func (k Keeper) GetUpcomingGauges(ctx sdk.Context) []types.Gauge { return k.getGaugesFromIterator(ctx, k.UpcomingGaugesIterator(ctx)) } @@ -208,16 +213,16 @@ func (k Keeper) GetFinishedGauges(ctx sdk.Context) []types.Gauge { return k.getGaugesFromIterator(ctx, k.FinishedGaugesIterator(ctx)) } -// GetRewardsEst returns rewards estimation at a future specific time +// GetRewardsEst returns rewards estimation at a future specific time (by epoch) // If locks are nil, it returns the rewards between now and the end epoch associated with address. // If locks are not nil, it returns all the rewards for the given locks between now and end epoch. func (k Keeper) GetRewardsEst(ctx sdk.Context, addr sdk.AccAddress, locks []lockuptypes.PeriodLock, endEpoch int64) sdk.Coins { - // If locks are nil, populate with all locks associated with the address + // if locks are nil, populate with all locks associated with the address if len(locks) == 0 { locks = k.lk.GetAccountPeriodLocks(ctx, addr) } - // Get all gauges that reward to these locks - // First get all the denominations being locked up + // get all gauges that reward to these locks + // first get all the denominations being locked up denomSet := map[string]bool{} for _, l := range locks { for _, c := range l.Coins { @@ -228,10 +233,10 @@ func (k Keeper) GetRewardsEst(ctx sdk.Context, addr sdk.AccAddress, locks []lock // initialize gauges to active and upcomings if not set for s := range denomSet { gaugeIDs := k.getAllGaugeIDsByDenom(ctx, s) - // Each gauge only rewards locks to one denom, so no duplicates + // each gauge only rewards locks to one denom, so no duplicates for _, id := range gaugeIDs { gauge, err := k.GetGaugeByID(ctx, id) - // Shouldn't happen + // shouldn't happen if err != nil { return sdk.Coins{} } @@ -243,7 +248,7 @@ func (k Keeper) GetRewardsEst(ctx sdk.Context, addr sdk.AccAddress, locks []lock estimatedRewards := sdk.Coins{} epochInfo := k.GetEpochInfo(ctx) - // no need to change storage while doing estimation and we use cached context + // no need to change storage while doing estimation as we use cached context cacheCtx, _ := ctx.CacheContext() for _, gauge := range gauges { distrBeginEpoch := epochInfo.CurrentEpoch @@ -268,6 +273,7 @@ func (k Keeper) GetRewardsEst(ctx sdk.Context, addr sdk.AccAddress, locks []lock return estimatedRewards } +// GetEpochInfo returns EpochInfo struct given context. func (k Keeper) GetEpochInfo(ctx sdk.Context) epochtypes.EpochInfo { params := k.GetParams(ctx) return k.ek.GetEpochInfo(ctx, params.DistrEpochIdentifier) diff --git a/x/incentives/keeper/genesis.go b/x/incentives/keeper/genesis.go index 1ef5dbd09ab..c38b690955b 100644 --- a/x/incentives/keeper/genesis.go +++ b/x/incentives/keeper/genesis.go @@ -6,8 +6,7 @@ import ( "github.com/osmosis-labs/osmosis/v7/x/incentives/types" ) -// InitGenesis initializes the capability module's state from a provided genesis -// state. +// InitGenesis initializes the incentives module's state from a provided genesis state. func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { k.SetParams(ctx, genState.Params) k.SetLockableDurations(ctx, genState.LockableDurations) @@ -20,7 +19,7 @@ func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { } } -// ExportGenesis returns the capability module's exported genesis. +// ExportGenesis returns the x/incentives module's exported genesis. func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { return &types.GenesisState{ Params: k.GetParams(ctx), diff --git a/x/incentives/keeper/grpc_query.go b/x/incentives/keeper/grpc_query.go index 6395910873e..106152cc0f3 100644 --- a/x/incentives/keeper/grpc_query.go +++ b/x/incentives/keeper/grpc_query.go @@ -18,29 +18,29 @@ import ( var _ types.QueryServer = Querier{} -// Querier defines a wrapper around the x/incentives keeper providing gRPC method -// handlers. +// Querier defines a wrapper around the incentives module keeper providing gRPC method handlers. type Querier struct { Keeper } +// NewQuerier creates a new Querier struct. func NewQuerier(k Keeper) Querier { return Querier{Keeper: k} } -// ModuleToDistributeCoins returns coins that is going to be distributed. +// ModuleToDistributeCoins returns coins that are going to be distributed. func (q Querier) ModuleToDistributeCoins(goCtx context.Context, _ *types.ModuleToDistributeCoinsRequest) (*types.ModuleToDistributeCoinsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) return &types.ModuleToDistributeCoinsResponse{Coins: q.Keeper.GetModuleToDistributeCoins(ctx)}, nil } -// ModuleDistributedCoins returns coins that are distributed by module so far. +// ModuleDistributedCoins returns coins that have been distributed by module already. func (q Querier) ModuleDistributedCoins(goCtx context.Context, _ *types.ModuleDistributedCoinsRequest) (*types.ModuleDistributedCoinsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) return &types.ModuleDistributedCoinsResponse{Coins: q.Keeper.GetModuleDistributedCoins(ctx)}, nil } -// GaugeByID returns Gauge by id. +// GaugeByID takes a gaugeID and returns its respective gauge. func (q Querier) GaugeByID(goCtx context.Context, req *types.GaugeByIDRequest) (*types.GaugeByIDResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -56,7 +56,7 @@ func (q Querier) GaugeByID(goCtx context.Context, req *types.GaugeByIDRequest) ( return &types.GaugeByIDResponse{Gauge: gauge}, nil } -// Gauges returns gauges both upcoming and active. +// Gauges returns all upcoming and active gauges. func (q Querier) Gauges(goCtx context.Context, req *types.GaugesRequest) (*types.GaugesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -71,7 +71,7 @@ func (q Querier) Gauges(goCtx context.Context, req *types.GaugesRequest) (*types return &types.GaugesResponse{Data: gauges, Pagination: pageRes}, nil } -// ActiveGauges returns active gauges. +// ActiveGauges returns all active gauges. func (q Querier) ActiveGauges(goCtx context.Context, req *types.ActiveGaugesRequest) (*types.ActiveGaugesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -87,7 +87,7 @@ func (q Querier) ActiveGauges(goCtx context.Context, req *types.ActiveGaugesRequ return &types.ActiveGaugesResponse{Data: gauges, Pagination: pageRes}, nil } -// ActiveGaugesPerDenom returns active gauges for the specified denom. +// ActiveGaugesPerDenom returns all active gauges for the specified denom. func (q Querier) ActiveGaugesPerDenom(goCtx context.Context, req *types.ActiveGaugesPerDenomRequest) (*types.ActiveGaugesPerDenomResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -102,7 +102,7 @@ func (q Querier) ActiveGaugesPerDenom(goCtx context.Context, req *types.ActiveGa return &types.ActiveGaugesPerDenomResponse{Data: gauges, Pagination: pageRes}, nil } -// UpcomingGauges returns scheduled gauges. +// UpcomingGauges returns all upcoming gauges. func (q Querier) UpcomingGauges(goCtx context.Context, req *types.UpcomingGaugesRequest) (*types.UpcomingGaugesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -118,6 +118,7 @@ func (q Querier) UpcomingGauges(goCtx context.Context, req *types.UpcomingGauges return &types.UpcomingGaugesResponse{Data: gauges, Pagination: pageRes}, nil } +// UpcomingGaugesPerDenom returns all upcoming gauges for the specified denom. func (q Querier) UpcomingGaugesPerDenom(goCtx context.Context, req *types.UpcomingGaugesPerDenomRequest) (*types.UpcomingGaugesPerDenomResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if req == nil { @@ -136,7 +137,7 @@ func (q Querier) UpcomingGaugesPerDenom(goCtx context.Context, req *types.Upcomi return &types.UpcomingGaugesPerDenomResponse{UpcomingGauges: gauges, Pagination: pageRes}, nil } -// RewardsEst returns rewards estimation at a future specific time. +// RewardsEst returns rewards estimation at a future specific time (by epoch). func (q Querier) RewardsEst(goCtx context.Context, req *types.RewardsEstRequest) (*types.RewardsEstResponse, error) { var ownerAddress sdk.AccAddress if req == nil { @@ -172,13 +173,14 @@ func (q Querier) RewardsEst(goCtx context.Context, req *types.RewardsEstRequest) return &types.RewardsEstResponse{Coins: q.Keeper.GetRewardsEst(ctx, ownerAddress, locks, req.EndEpoch)}, nil } +// LockableDurations returns all of the allowed lockable durations on chain. func (q Querier) LockableDurations(ctx context.Context, _ *types.QueryLockableDurationsRequest) (*types.QueryLockableDurationsResponse, error) { sdkCtx := sdk.UnwrapSDKContext(ctx) return &types.QueryLockableDurationsResponse{LockableDurations: q.Keeper.GetLockableDurations(sdkCtx)}, nil } -// getGaugeFromIDJsonBytes returns gauges from gauge id json bytes. +// getGaugeFromIDJsonBytes returns gauges from the json bytes of gaugeIDs. func (q Querier) getGaugeFromIDJsonBytes(ctx sdk.Context, refValue []byte) ([]types.Gauge, error) { gauges := []types.Gauge{} gaugeIDs := []uint64{} @@ -200,15 +202,15 @@ func (q Querier) getGaugeFromIDJsonBytes(ctx sdk.Context, refValue []byte) ([]ty return gauges, nil } -// Filter gauges based on given prefix type and denom +// filterByPrefixAndDenom filters gauges based on a given key prefix and denom func (q Querier) filterByPrefixAndDenom(ctx sdk.Context, prefixType []byte, denom string, pagination *query.PageRequest) (*query.PageResponse, []types.Gauge, error) { gauges := []types.Gauge{} store := ctx.KVStore(q.Keeper.storeKey) valStore := prefix.NewStore(store, prefixType) pageRes, err := query.FilteredPaginate(valStore, pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - // This may return multiple gauges at once if two gauges start at the same time. - // For now this is treated as an edge case that is not of importance + // this may return multiple gauges at once if two gauges start at the same time. + // for now this is treated as an edge case that is not of importance newGauges, err := q.getGaugeFromIDJsonBytes(ctx, value) if err != nil { return false, err diff --git a/x/incentives/keeper/hooks.go b/x/incentives/keeper/hooks.go index d960e1940d4..d51d1447d50 100644 --- a/x/incentives/keeper/hooks.go +++ b/x/incentives/keeper/hooks.go @@ -8,9 +8,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// BeforeEpochStart is the epoch start hook. func (k Keeper) BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) { } +// AfterEpochEnd is the epoch end hook. func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) { params := k.GetParams(ctx) if epochIdentifier == params.DistrEpochIdentifier { @@ -30,7 +32,6 @@ func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumb // only distribute to active gauges that are for native denoms // or non-perpetual and for synthetic denoms. // We distribute to perpetual synthetic denoms elsewhere in superfluid. - // TODO: This method of doing is a bit of hack, should clean this up later. distrGauges := []types.Gauge{} for _, gauge := range gauges { isSynthetic := lockuptypes.IsSyntheticDenom(gauge.DistributeTo.Denom) @@ -47,23 +48,24 @@ func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumb // ___________________________________________________________________________________________________ -// Hooks wrapper struct for incentives keeper. +// Hooks is the wrapper struct for the incentives keeper. type Hooks struct { k Keeper } var _ epochstypes.EpochHooks = Hooks{} -// Return the wrapper struct. +// Hooks returns the hook wrapper struct. func (k Keeper) Hooks() Hooks { return Hooks{k} } -// epochs hooks. +// BeforeEpochStart is the epoch start hook. func (h Hooks) BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) { h.k.BeforeEpochStart(ctx, epochIdentifier, epochNumber) } +// AfterEpochEnd is the epoch end hook. func (h Hooks) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) { h.k.AfterEpochEnd(ctx, epochIdentifier, epochNumber) } diff --git a/x/incentives/keeper/iterator.go b/x/incentives/keeper/iterator.go index 5222a4df7ed..ad95a0f1159 100644 --- a/x/incentives/keeper/iterator.go +++ b/x/incentives/keeper/iterator.go @@ -10,7 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Returns an iterator over all gauges in the {prefix} space of state, that begin distributing rewards after a specific time. +// iteratorAfterTime returns an iterator over all gauges in the {prefix} space of state, that begin distributing rewards after a specific time. func (k Keeper) iteratorAfterTime(ctx sdk.Context, prefix []byte, time time.Time) sdk.Iterator { store := ctx.KVStore(k.storeKey) timeKey := getTimeKey(time) @@ -18,6 +18,7 @@ func (k Keeper) iteratorAfterTime(ctx sdk.Context, prefix []byte, time time.Time return store.Iterator(storetypes.InclusiveEndBytes(key), storetypes.PrefixEndBytes(prefix)) } +// iteratorBeforeTime returns an iterator over all gauges in the {prefix} space of state, that begin distributing rewards before a specific time. func (k Keeper) iteratorBeforeTime(ctx sdk.Context, prefix []byte, time time.Time) sdk.Iterator { store := ctx.KVStore(k.storeKey) timeKey := getTimeKey(time) @@ -25,41 +26,43 @@ func (k Keeper) iteratorBeforeTime(ctx sdk.Context, prefix []byte, time time.Tim return store.Iterator(prefix, storetypes.InclusiveEndBytes(key)) } +// iterator returns an iterator over all gauges in the {prefix} space of state. func (k Keeper) iterator(ctx sdk.Context, prefix []byte) sdk.Iterator { store := ctx.KVStore(k.storeKey) return sdk.KVStorePrefixIterator(store, prefix) } -// UpcomingGaugesIteratorAfterTime returns the iterator to get upcoming gauges that start distribution after specific time. +// UpcomingGaugesIteratorAfterTime returns the iterator to get all upcoming gauges that start distribution after a specific time. func (k Keeper) UpcomingGaugesIteratorAfterTime(ctx sdk.Context, time time.Time) sdk.Iterator { return k.iteratorAfterTime(ctx, types.KeyPrefixUpcomingGauges, time) } -// UpcomingGaugesIteratorBeforeTime returns the iterator to get upcoming gauges that already started distribution before specific time. +// UpcomingGaugesIteratorBeforeTime returns the iterator to get all upcoming gauges that have already started distribution before a specific time. func (k Keeper) UpcomingGaugesIteratorBeforeTime(ctx sdk.Context, time time.Time) sdk.Iterator { return k.iteratorBeforeTime(ctx, types.KeyPrefixUpcomingGauges, time) } -// GaugesIterator returns iterator for all gauges. +// GaugesIterator returns the iterator for all gauges. func (k Keeper) GaugesIterator(ctx sdk.Context) sdk.Iterator { return k.iterator(ctx, types.KeyPrefixGauges) } -// UpcomingGaugesIterator returns iterator for upcoming gauges. +// UpcomingGaugesIterator returns the iterator for all upcoming gauges. func (k Keeper) UpcomingGaugesIterator(ctx sdk.Context) sdk.Iterator { return k.iterator(ctx, types.KeyPrefixUpcomingGauges) } -// ActiveGaugesIterator returns iterator for active gauges. +// ActiveGaugesIterator returns the iterator for all active gauges. func (k Keeper) ActiveGaugesIterator(ctx sdk.Context) sdk.Iterator { return k.iterator(ctx, types.KeyPrefixActiveGauges) } -// FinishedGaugesIterator returns iterator for finished gauges. +// FinishedGaugesIterator returns the iterator for all finished gauges. func (k Keeper) FinishedGaugesIterator(ctx sdk.Context) sdk.Iterator { return k.iterator(ctx, types.KeyPrefixFinishedGauges) } +// FilterLocksByMinDuration returns locks whose lock duration is greater than the provided minimum duration. func FilterLocksByMinDuration(locks []lockuptypes.PeriodLock, minDuration time.Duration) []lockuptypes.PeriodLock { filteredLocks := make([]lockuptypes.PeriodLock, 0, len(locks)/2) for _, lock := range locks { diff --git a/x/incentives/keeper/keeper.go b/x/incentives/keeper/keeper.go index 11f9023a545..439e78f68fd 100644 --- a/x/incentives/keeper/keeper.go +++ b/x/incentives/keeper/keeper.go @@ -4,14 +4,16 @@ import ( "fmt" "time" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" "github.com/tendermint/tendermint/libs/log" + "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) +// Keeper provides a way to manage incentives module storage. type Keeper struct { cdc codec.Codec storeKey sdk.StoreKey @@ -22,6 +24,7 @@ type Keeper struct { ek types.EpochKeeper } +// NewKeeper returns a new instance of the incentive module keeper struct. func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey, paramSpace paramtypes.Subspace, bk types.BankKeeper, lk types.LockupKeeper, ek types.EpochKeeper) *Keeper { if !paramSpace.HasKeyTable() { paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) @@ -37,7 +40,7 @@ func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey, paramSpace paramtypes.Sub } } -// Set the gamm hooks. +// SetHooks sets the incentives hooks. func (k *Keeper) SetHooks(ih types.IncentiveHooks) *Keeper { if k.hooks != nil { panic("cannot set incentive hooks twice") @@ -48,10 +51,12 @@ func (k *Keeper) SetHooks(ih types.IncentiveHooks) *Keeper { return k } +// Logger returns a logger instance for the incentives module. func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } +// SetLockableDurations sets which lockable durations will be incentivized. func (k Keeper) SetLockableDurations(ctx sdk.Context, lockableDurations []time.Duration) { store := ctx.KVStore(k.storeKey) @@ -60,6 +65,7 @@ func (k Keeper) SetLockableDurations(ctx sdk.Context, lockableDurations []time.D store.Set(types.LockableDurationsKey, k.cdc.MustMarshal(&info)) } +// GetLockableDurations returns all incentivized lockable durations. func (k Keeper) GetLockableDurations(ctx sdk.Context) []time.Duration { store := ctx.KVStore(k.storeKey) info := types.LockableDurationsInfo{} diff --git a/x/incentives/keeper/msg_server.go b/x/incentives/keeper/msg_server.go index 05bc7c9a3c7..c83f5418b90 100644 --- a/x/incentives/keeper/msg_server.go +++ b/x/incentives/keeper/msg_server.go @@ -10,11 +10,12 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) +// msgServer provides a way to reference keeper pointer in the message server interface. type msgServer struct { keeper *Keeper } -// NewMsgServerImpl returns an instance of MsgServer. +// NewMsgServerImpl returns an instance of MsgServer for the provided keeper. func NewMsgServerImpl(keeper *Keeper) types.MsgServer { return &msgServer{ keeper: keeper, @@ -23,6 +24,8 @@ func NewMsgServerImpl(keeper *Keeper) types.MsgServer { var _ types.MsgServer = msgServer{} +// CreateGauge creates a gauge and sends coins to the gauge. +// Emits create gauge event and returns the create gauge response. func (server msgServer) CreateGauge(goCtx context.Context, msg *types.MsgCreateGauge) (*types.MsgCreateGaugeResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) owner, err := sdk.AccAddressFromBech32(msg.Owner) @@ -45,6 +48,8 @@ func (server msgServer) CreateGauge(goCtx context.Context, msg *types.MsgCreateG return &types.MsgCreateGaugeResponse{}, nil } +// AddToGauge adds coins to gauge. +// Emits add to gauge event and returns the add to gauge response. func (server msgServer) AddToGauge(goCtx context.Context, msg *types.MsgAddToGauge) (*types.MsgAddToGaugeResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) owner, err := sdk.AccAddressFromBech32(msg.Owner) diff --git a/x/incentives/keeper/params.go b/x/incentives/keeper/params.go index 3ec764771d4..5975d785943 100644 --- a/x/incentives/keeper/params.go +++ b/x/incentives/keeper/params.go @@ -6,13 +6,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// GetParams returns the total set params. +// GetParams returns all of the parameters in the incentive module. func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { k.paramSpace.GetParamSet(ctx, ¶ms) return params } -// SetParams sets the total set of params. +// SetParams sets all of the parameters in the incentive module. func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { k.paramSpace.SetParamSet(ctx, ¶ms) } diff --git a/x/incentives/keeper/store.go b/x/incentives/keeper/store.go index bd752f328c1..c96b074955f 100644 --- a/x/incentives/keeper/store.go +++ b/x/incentives/keeper/store.go @@ -9,7 +9,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// GetLastGaugeID returns ID used last time. +// GetLastGaugeID returns the last used gauge ID. func (k Keeper) GetLastGaugeID(ctx sdk.Context) uint64 { store := ctx.KVStore(k.storeKey) @@ -21,22 +21,23 @@ func (k Keeper) GetLastGaugeID(ctx sdk.Context) uint64 { return sdk.BigEndianToUint64(bz) } -// SetLastGaugeID save ID used by last gauge. +// SetLastGaugeID sets the last used gauge ID to the provided ID. func (k Keeper) SetLastGaugeID(ctx sdk.Context, ID uint64) { store := ctx.KVStore(k.storeKey) store.Set(types.KeyLastGaugeID, sdk.Uint64ToBigEndian(ID)) } -// gaugeStoreKey returns action store key from ID. +// gaugeStoreKey returns the combined byte array (store key) of the provided gauge ID's key prefix and the ID itself. func gaugeStoreKey(ID uint64) []byte { return combineKeys(types.KeyPrefixPeriodGauge, sdk.Uint64ToBigEndian(ID)) } +// gaugeDenomStoreKey returns the combined byte array (store key) of the provided gauge denom key prefix and the denom itself. func gaugeDenomStoreKey(denom string) []byte { return combineKeys(types.KeyPrefixGaugesByDenom, []byte(denom)) } -// getGaugeRefs get gauge IDs specified on the provided key. +// getGaugeRefs returns the gauge IDs specified by the provided key. func (k Keeper) getGaugeRefs(ctx sdk.Context, key []byte) []uint64 { store := ctx.KVStore(k.storeKey) gaugeIDs := []uint64{} @@ -50,7 +51,7 @@ func (k Keeper) getGaugeRefs(ctx sdk.Context, key []byte) []uint64 { return gaugeIDs } -// addGaugeRefByKey append gauge ID into an array associated to provided key. +// addGaugeRefByKey appends the provided gauge ID into an array associated with the provided key. func (k Keeper) addGaugeRefByKey(ctx sdk.Context, key []byte, gaugeID uint64) error { store := ctx.KVStore(k.storeKey) gaugeIDs := k.getGaugeRefs(ctx, key) @@ -66,7 +67,7 @@ func (k Keeper) addGaugeRefByKey(ctx sdk.Context, key []byte, gaugeID uint64) er return nil } -// deleteGaugeRefByKey removes gauge ID from an array associated to provided key. +// deleteGaugeRefByKey removes the provided gauge ID from an array associated with the provided key. func (k Keeper) deleteGaugeRefByKey(ctx sdk.Context, key []byte, gaugeID uint64) error { store := ctx.KVStore(k.storeKey) gaugeIDs := k.getGaugeRefs(ctx, key) @@ -86,17 +87,17 @@ func (k Keeper) deleteGaugeRefByKey(ctx sdk.Context, key []byte, gaugeID uint64) return nil } -// getAllGaugeIDsByDenom returns all active gauge-IDs associated with lockups of denomination `denom`. +// getAllGaugeIDsByDenom returns all active gauge-IDs associated with lockups of the provided denom. func (k Keeper) getAllGaugeIDsByDenom(ctx sdk.Context, denom string) []uint64 { return k.getGaugeRefs(ctx, gaugeDenomStoreKey(denom)) } -// deleteGaugeIDForDenom deletes ID from the list of gauge ID's associated with denomination `denom`. +// deleteGaugeIDForDenom deletes the provided ID from the list of gauge ID's associated with the provided denom. func (k Keeper) deleteGaugeIDForDenom(ctx sdk.Context, ID uint64, denom string) error { return k.deleteGaugeRefByKey(ctx, gaugeDenomStoreKey(denom), ID) } -// addGaugeIDForDenom adds ID to the list of gauge ID's associated with denomination `denom`. +// addGaugeIDForDenom adds the provided ID to the list of gauge ID's associated with the provided denom. func (k Keeper) addGaugeIDForDenom(ctx sdk.Context, ID uint64, denom string) error { return k.addGaugeRefByKey(ctx, gaugeDenomStoreKey(denom), ID) } diff --git a/x/incentives/keeper/utils.go b/x/incentives/keeper/utils.go index 168e7acf72f..79efff15d48 100644 --- a/x/incentives/keeper/utils.go +++ b/x/incentives/keeper/utils.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// findIndex takes an array of IDs. Then return the index of a specific ID. func findIndex(IDs []uint64, ID uint64) int { for index, id := range IDs { if id == ID { @@ -17,6 +18,7 @@ func findIndex(IDs []uint64, ID uint64) int { return -1 } +// removeValue takes an array of IDs. Then finds the index of the IDs and remove those IDs from the array. func removeValue(IDs []uint64, ID uint64) ([]uint64, int) { index := findIndex(IDs, ID) if index < 0 { @@ -26,7 +28,7 @@ func removeValue(IDs []uint64, ID uint64) ([]uint64, int) { return IDs[:len(IDs)-1], index } -// getTimeKey returns the key used for getting a set of gauges. +// getTimeKey returns the time key used when getting a set of gauges. func getTimeKey(timestamp time.Time) []byte { timeBz := sdk.FormatTimeBytes(timestamp) timeBzL := len(timeBz) @@ -45,7 +47,7 @@ func getTimeKey(timestamp time.Time) []byte { return bz } -// combineKeys combine bytes array into a single bytes. +// combineKeys combines the byte arrays of multiple keys into a single byte array. func combineKeys(keys ...[]byte) []byte { combined := []byte{} for i, key := range keys { diff --git a/x/incentives/module.go b/x/incentives/module.go index 33d03c93a53..02824adc959 100644 --- a/x/incentives/module.go +++ b/x/incentives/module.go @@ -35,20 +35,22 @@ var ( // AppModuleBasic // ---------------------------------------------------------------------------- -// AppModuleBasic implements the AppModuleBasic interface for the capability module. +// Implements the AppModuleBasic interface for the module. type AppModuleBasic struct { cdc codec.Codec } +// NewAppModuleBasic creates a new AppModuleBasic struct. func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { return AppModuleBasic{cdc: cdc} } -// Name returns the capability module's name. +// Name returns the module's name. func (AppModuleBasic) Name() string { return types.ModuleName } +// RegisterLegacyAminoCodec registers the module's types on the LegacyAmino codec. func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { types.RegisterCodec(cdc) } @@ -58,12 +60,12 @@ func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { types.RegisterInterfaces(reg) } -// DefaultGenesis returns the capability module's default genesis state. +// DefaultGenesis returns the module's default genesis state. func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesis()) } -// ValidateGenesis performs genesis state validation for the capability module. +// ValidateGenesis performs genesis state validation for the module. func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var genState types.GenesisState if err := cdc.UnmarshalJSON(bz, &genState); err != nil { @@ -72,7 +74,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod return genState.Validate() } -// RegisterRESTRoutes registers the capability module's REST service handlers. +// RegisterRESTRoutes registers the module's REST service handlers. func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { rest.RegisterRoutes(clientCtx, rtr) } @@ -84,12 +86,12 @@ func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *r } } -// GetTxCmd returns the capability module's root tx command. +// GetTxCmd returns the module's root tx command. func (a AppModuleBasic) GetTxCmd() *cobra.Command { return cli.GetTxCmd() } -// GetQueryCmd returns the capability module's root query command. +// GetQueryCmd returns the module's root query command. func (AppModuleBasic) GetQueryCmd() *cobra.Command { return cli.GetQueryCmd() } @@ -98,7 +100,7 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { // AppModule // ---------------------------------------------------------------------------- -// AppModule implements the AppModule interface for the capability module. +// AppModule implements the AppModule interface for the module. type AppModule struct { AppModuleBasic @@ -109,6 +111,7 @@ type AppModule struct { epochKeeper types.EpochKeeper } +// NewAppModule creates a new AppModule struct. func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper stakingtypes.AccountKeeper, bankKeeper stakingtypes.BankKeeper, epochKeeper types.EpochKeeper, @@ -122,40 +125,40 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, } } -// Name returns the capability module's name. +// Name returns the module's name. func (am AppModule) Name() string { return am.AppModuleBasic.Name() } -// Route returns the capability module's message routing key. +// Route returns the module's message routing key. func (am AppModule) Route() sdk.Route { return sdk.Route{} } -// QuerierRoute returns the capability module's query routing key. +// QuerierRoute returns the module's query routing key. func (AppModule) QuerierRoute() string { return types.QuerierRoute } -// LegacyQuerierHandler returns the x/incentives module's Querier. +// LegacyQuerierHandler returns the incentive module's Querier. func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(sdk.Context, []string, abci.RequestQuery) ([]byte, error) { return nil, fmt.Errorf("legacy querier not supported for the x/%s module", types.ModuleName) } } -// RegisterServices registers module services. +// RegisterServices registers the module's services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(&am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQuerier(am.keeper)) } -// RegisterInvariants registers the capability module's invariants. +// RegisterInvariants registers the module's invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// InitGenesis performs the capability module's genesis initialization It returns -// no validator updates. +// InitGenesis performs the module's genesis initialization. +// Returns an empty ValidatorUpdate array. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { var genState types.GenesisState - // Initialize global index to index in genesis state + // initialize global index to index in genesis state. cdc.MustUnmarshalJSON(gs, &genState) am.keeper.InitGenesis(ctx, genState) @@ -163,46 +166,43 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.Ra return []abci.ValidatorUpdate{} } -// ExportGenesis returns the capability module's exported genesis state as raw JSON bytes. +// ExportGenesis returns the module's exported genesis state as raw JSON bytes. func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(am.keeper.ExportGenesis(ctx)) } -// BeginBlock executes all ABCI BeginBlock logic respective to the capability module. +// BeginBlock executes all ABCI BeginBlock logic respective to the module. func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// EndBlock executes all ABCI EndBlock logic respective to the capability module. It -// returns no validator updates. +// EndBlock executes all ABCI EndBlock logic respective to the module. +// Returns a nil validatorUpdate struct array. func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } // AppModuleSimulation functions -// GenerateGenesisState creates a randomized GenState of the pool-incentives -// module. +// GenerateGenesisState creates a randomized GenState of the incentives module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } -// ProposalContents doesn't return any content functions for governance -// proposals. +// ProposalContents returns nil for governance proposals contents. +// Should eventually be deleted in a future update. func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return nil } -// RandomizedParams creates randomized pool-incentives param changes for the -// simulator. +// RandomizedParams returns nil. Should eventually be deleted in a future update. func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return nil } -// RegisterStoreDecoder registers a decoder for supply module's types. +// RegisterStoreDecoder has an unknown purpose. Should eventually be deleted in a future update. func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } -// WeightedOperations returns the all the incentive module operations with their -// respective weights. +// WeightedOperations returns the all the module's operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( simState.AppParams, simState.Cdc, diff --git a/x/incentives/simulation/genesis.go b/x/incentives/simulation/genesis.go index 19284e0f685..a28a185b97d 100644 --- a/x/incentives/simulation/genesis.go +++ b/x/incentives/simulation/genesis.go @@ -18,9 +18,9 @@ const ( ParamsDistrEpochIdentifier = "distr_epoch_identifier" ) -// RandomizedGenState generates a random GenesisState for gov. +// RandomizedGenState generates a random GenesisState for the incentives module. func RandomizedGenState(simState *module.SimulationState) { - // Parameter for how often rewards get distributed + // parameter for how often rewards get distributed var distrEpochIdentifier string simState.AppParams.GetOrGenerate( simState.Cdc, ParamsDistrEpochIdentifier, &distrEpochIdentifier, simState.Rand, @@ -31,7 +31,6 @@ func RandomizedGenState(simState *module.SimulationState) { Params: types.Params{ DistrEpochIdentifier: distrEpochIdentifier, }, - // Gauges: gauges, LockableDurations: []time.Duration{ time.Second, time.Hour, diff --git a/x/incentives/simulation/operations.go b/x/incentives/simulation/operations.go index a74fa014832..22ec9f383d4 100644 --- a/x/incentives/simulation/operations.go +++ b/x/incentives/simulation/operations.go @@ -62,26 +62,25 @@ func WeightedOperations( } } +// genRewardCoins generates a random number of coin denoms with a respective random value for each coin. func genRewardCoins(r *rand.Rand, coins sdk.Coins) (res sdk.Coins) { numCoins := 1 + r.Intn(Min(coins.Len(), 1)) denomIndices := r.Perm(numCoins) for i := 0; i < numCoins; i++ { denom := coins[denomIndices[i]].Denom - amt, _ := simtypes.RandPositiveInt(r, coins[i].Amount) + amt, err := simtypes.RandPositiveInt(r, coins[i].Amount) + if err != nil { + panic(err) + } res = append(res, sdk.Coin{Denom: denom, Amount: amt}) } - return } +// genQueryCondition returns a single lockup QueryCondition, which is generated from a single coin randomly selected from the provided coin array func genQueryCondition(r *rand.Rand, blocktime time.Time, coins sdk.Coins, durations []time.Duration) lockuptypes.QueryCondition { - // TODO: reset to 2 after postlaunch, only allow duration based query type on postlaunch - // lockQueryType := r.Intn(2) lockQueryType := 0 denom := coins[r.Intn(len(coins))].Denom - // TODO: for postlaunch, only specific lock durations are allowed - // durationSecs := r.Intn(1*60*60*24*7) + 1*60*60 // range of 1 week, min 1 hour - // duration := time.Duration(durationSecs) * time.Second durationIndex := r.Intn(len(durations)) duration := durations[durationIndex] timestampSecs := r.Intn(1 * 60 * 60 * 24 * 7) // range of 1 week @@ -109,7 +108,7 @@ func Max(x, y int) int { return y } -// SimulateMsgCreateGauge generates a MsgCreateGauge with random values. +// SimulateMsgCreateGauge generates and executes a MsgCreateGauge with random parameters func SimulateMsgCreateGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankKeeper, ek types.EpochKeeper, k keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -148,6 +147,7 @@ func SimulateMsgCreateGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankK } } +// SimulateMsgAddToGauge generates and executes a MsgAddToGauge with random parameters func SimulateMsgAddToGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -181,6 +181,7 @@ func SimulateMsgAddToGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankKe } } +// RandomGauge takes a context, then returns a random existing gauge. func RandomGauge(ctx sdk.Context, r *rand.Rand, k keeper.Keeper) *types.Gauge { gauges := k.GetGauges(ctx) if len(gauges) == 0 { diff --git a/x/incentives/simulation/params.go b/x/incentives/simulation/params.go index 2a79a62a201..db20ddb6268 100644 --- a/x/incentives/simulation/params.go +++ b/x/incentives/simulation/params.go @@ -15,12 +15,9 @@ const ( keyDistrEpochIdentifier = "DistrEpochIdentifier" ) -// TODO: remove hardcoded params -// refer x/epochs/simulation/genesis.go. var epochIdentifiers = []string{"day", "hour"} -// ParamChanges defines the parameters that can be modified by param change proposals -// on the simulation. +// ParamChanges defines the parameters that can be modified by param change proposals on the simulation. func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keyDistrEpochIdentifier, @@ -31,6 +28,7 @@ func ParamChanges(r *rand.Rand) []simtypes.ParamChange { } } +// GenParamsDistrEpochIdentifier generates a random epoch identifier to be used to distribute incentives on. func GenParamsDistrEpochIdentifier(r *rand.Rand) string { return epochIdentifiers[r.Intn(len(epochIdentifiers))] } diff --git a/x/incentives/types/codec.go b/x/incentives/types/codec.go index 927e7e84ee7..07c7a66698d 100644 --- a/x/incentives/types/codec.go +++ b/x/incentives/types/codec.go @@ -7,14 +7,19 @@ import ( "github.com/cosmos/cosmos-sdk/types/msgservice" ) -// RegisterLegacyAminoCodec registers the necessary x/incentives interfaces and -// concrete types on the provided LegacyAmino codec. These types are used for -// Amino JSON serialization. +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + +// RegisterCodec registers the necessary x/incentives interfaces and concrete types on the provided +// LegacyAmino codec. These types are used for Amino JSON serialization. func RegisterCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(&MsgCreateGauge{}, "osmosis/incentives/create-gauge", nil) cdc.RegisterConcrete(&MsgAddToGauge{}, "osmosis/incentives/add-to-gauge", nil) } +// RegisterInterfaces registers interfaces and implementations of the incentives module. func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { registry.RegisterImplementations( (*sdk.Msg)(nil), @@ -25,11 +30,6 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - func init() { RegisterCodec(amino) amino.Seal() diff --git a/x/incentives/types/events.go b/x/incentives/types/events.go index 9c15cd7baa7..a2b260c738c 100644 --- a/x/incentives/types/events.go +++ b/x/incentives/types/events.go @@ -1,6 +1,6 @@ package types -// event types. +// Incentive module event types. const ( TypeEvtCreateGauge = "create_gauge" TypeEvtAddToGauge = "add_to_gauge" diff --git a/x/incentives/types/expected_keepers.go b/x/incentives/types/expected_keepers.go index 374941306ce..ddc26781e8a 100644 --- a/x/incentives/types/expected_keepers.go +++ b/x/incentives/types/expected_keepers.go @@ -32,6 +32,7 @@ type LockupKeeper interface { GetLockByID(ctx sdk.Context, lockID uint64) (*lockuptypes.PeriodLock, error) } +// EpochKeeper defines the expected interface needed to retrieve epoch info. type EpochKeeper interface { GetEpochInfo(ctx sdk.Context, identifier string) epochstypes.EpochInfo } diff --git a/x/incentives/types/gauge.go b/x/incentives/types/gauge.go index 7da16d81e2f..c1dd1b0193d 100644 --- a/x/incentives/types/gauge.go +++ b/x/incentives/types/gauge.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// NewGauge creates a new gauge struct given the required gauge parameters. func NewGauge(id uint64, isPerpetual bool, distrTo lockuptypes.QueryCondition, coins sdk.Coins, startTime time.Time, numEpochsPaidOver uint64, filledEpochs uint64, distrCoins sdk.Coins) Gauge { return Gauge{ Id: id, @@ -21,10 +22,12 @@ func NewGauge(id uint64, isPerpetual bool, distrTo lockuptypes.QueryCondition, c } } +// IsUpcomingGauge returns true if the gauge's distribution start time is after the provided time. func (gauge Gauge) IsUpcomingGauge(curTime time.Time) bool { return curTime.After(gauge.StartTime) } +// IsActiveGauge returns true if the gauge is in an active state during the provided time. func (gauge Gauge) IsActiveGauge(curTime time.Time) bool { if curTime.Before(gauge.StartTime) && (gauge.IsPerpetual || gauge.FilledEpochs < gauge.NumEpochsPaidOver) { return true @@ -32,6 +35,7 @@ func (gauge Gauge) IsActiveGauge(curTime time.Time) bool { return false } +// IsFinishedGauge returns true if the gauge is in a finished state during the provided time. func (gauge Gauge) IsFinishedGauge(curTime time.Time) bool { return !gauge.IsUpcomingGauge(curTime) && !gauge.IsActiveGauge(curTime) } diff --git a/x/incentives/types/genesis.go b/x/incentives/types/genesis.go index afa224997ac..1c865f6561c 100644 --- a/x/incentives/types/genesis.go +++ b/x/incentives/types/genesis.go @@ -8,10 +8,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -// DefaultIndex is the default capability global index. +// DefaultIndex is the default incentive module's global index. const DefaultIndex uint64 = 1 -// DefaultGenesis returns the default Capability genesis state. +// DefaultGenesis returns the incentive module's default genesis state. func DefaultGenesis() *GenesisState { return &GenesisState{ Params: Params{ @@ -27,8 +27,7 @@ func DefaultGenesis() *GenesisState { } } -// GetGenesisStateFromAppState returns x/incentives GenesisState given raw application -// genesis state. +// GetGenesisStateFromAppState returns an incentive module GenesisState given a raw application genesis state. func GetGenesisStateFromAppState(cdc codec.JSONCodec, appState map[string]json.RawMessage) *GenesisState { var genesisState GenesisState @@ -39,8 +38,7 @@ func GetGenesisStateFromAppState(cdc codec.JSONCodec, appState map[string]json.R return &genesisState } -// Validate performs basic genesis state validation returning an error upon any -// failure. +// Validate performs basic genesis state validation, returning an error upon any failure. func (gs GenesisState) Validate() error { if gs.Params.DistrEpochIdentifier == "" { return errors.New("epoch identifier should NOT be empty") diff --git a/x/incentives/types/hooks.go b/x/incentives/types/hooks.go index 08c81719b4e..af6fd4db736 100644 --- a/x/incentives/types/hooks.go +++ b/x/incentives/types/hooks.go @@ -12,9 +12,10 @@ type IncentiveHooks interface { var _ IncentiveHooks = MultiIncentiveHooks{} -// combine multiple incentive hooks, all hook functions are run in array sequence. +// MultiIncentiveHooks combines multiple incentive hooks. All hook functions are run in array sequence. type MultiIncentiveHooks []IncentiveHooks +// NewMultiIncentiveHooks combines multiple incentive hooks into a single IncentiveHooks array. func NewMultiIncentiveHooks(hooks ...IncentiveHooks) MultiIncentiveHooks { return hooks } diff --git a/x/incentives/types/msgs.go b/x/incentives/types/msgs.go index a3e20b21626..a9b61de5dfd 100644 --- a/x/incentives/types/msgs.go +++ b/x/incentives/types/msgs.go @@ -9,7 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// constants. const ( TypeMsgCreateGauge = "create_gauge" TypeMsgAddToGauge = "add_to_gauge" @@ -17,7 +16,7 @@ const ( var _ sdk.Msg = &MsgCreateGauge{} -// NewMsgCreateGauge creates a message to create a gauge. +// NewMsgCreateGauge creates a message to create a gauge with the provided parameters. func NewMsgCreateGauge(isPerpetual bool, owner sdk.AccAddress, distributeTo lockuptypes.QueryCondition, coins sdk.Coins, startTime time.Time, numEpochsPaidOver uint64) *MsgCreateGauge { return &MsgCreateGauge{ IsPerpetual: isPerpetual, @@ -29,8 +28,13 @@ func NewMsgCreateGauge(isPerpetual bool, owner sdk.AccAddress, distributeTo lock } } +// Route takes a create gauge message, then returns the RouterKey used for slashing. func (m MsgCreateGauge) Route() string { return RouterKey } -func (m MsgCreateGauge) Type() string { return TypeMsgCreateGauge } + +// Type takes a create gauge message, then returns a create gauge message type. +func (m MsgCreateGauge) Type() string { return TypeMsgCreateGauge } + +// ValidateBasic checks that the create gauge message is valid. func (m MsgCreateGauge) ValidateBasic() error { if m.Owner == "" { return errors.New("owner should be set") @@ -58,10 +62,12 @@ func (m MsgCreateGauge) ValidateBasic() error { return nil } +// GetSignBytes takes a create gauge message and turns it into a byte array. func (m MsgCreateGauge) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } +// GetSigners takes a create gauge message and returns the owner in a byte array. func (m MsgCreateGauge) GetSigners() []sdk.AccAddress { owner, _ := sdk.AccAddressFromBech32(m.Owner) return []sdk.AccAddress{owner} @@ -69,7 +75,7 @@ func (m MsgCreateGauge) GetSigners() []sdk.AccAddress { var _ sdk.Msg = &MsgAddToGauge{} -// NewMsgCreateGauge creates a message to create a gauge. +// NewMsgAddToGauge creates a message to add rewards to a specific gauge. func NewMsgAddToGauge(owner sdk.AccAddress, gaugeId uint64, rewards sdk.Coins) *MsgAddToGauge { return &MsgAddToGauge{ Owner: owner.String(), @@ -78,8 +84,13 @@ func NewMsgAddToGauge(owner sdk.AccAddress, gaugeId uint64, rewards sdk.Coins) * } } +// Route takes an add to gauge message, then returns the RouterKey used for slashing. func (m MsgAddToGauge) Route() string { return RouterKey } -func (m MsgAddToGauge) Type() string { return TypeMsgAddToGauge } + +// Type takes an add to gauge message, then returns an add to gauge message type. +func (m MsgAddToGauge) Type() string { return TypeMsgAddToGauge } + +// ValidateBasic checks that the add to gauge message is valid. func (m MsgAddToGauge) ValidateBasic() error { if m.Owner == "" { return errors.New("owner should be set") @@ -91,10 +102,12 @@ func (m MsgAddToGauge) ValidateBasic() error { return nil } +// GetSignBytes takes an add to gauge message and turns it into a byte array. func (m MsgAddToGauge) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } +// GetSigners takes an add to gauge message and returns the owner in a byte array. func (m MsgAddToGauge) GetSigners() []sdk.AccAddress { owner, _ := sdk.AccAddressFromBech32(m.Owner) return []sdk.AccAddress{owner} diff --git a/x/incentives/types/msgs_test.go b/x/incentives/types/msgs_test.go index ca6b34e60e2..4ef99c55b71 100644 --- a/x/incentives/types/msgs_test.go +++ b/x/incentives/types/msgs_test.go @@ -4,17 +4,21 @@ import ( "testing" time "time" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/ed25519" + lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + sdk "github.com/cosmos/cosmos-sdk/types" ) +// TestMsgCreatePool tests if valid/invalid create pool messages are properly validated/invalidated func TestMsgCreatePool(t *testing.T) { + // generate a private/public key pair and get the respective address pk1 := ed25519.GenPrivKey().PubKey() addr1 := sdk.AccAddress(pk1.Address()) + // make a proper createPool message createMsg := func(after func(msg MsgCreateGauge) MsgCreateGauge) MsgCreateGauge { distributeTo := lockuptypes.QueryCondition{ LockQueryType: lockuptypes.ByDuration, @@ -34,10 +38,10 @@ func TestMsgCreatePool(t *testing.T) { return after(properMsg) } + // validate createPool message was created as intended msg := createMsg(func(msg MsgCreateGauge) MsgCreateGauge { return msg }) - require.Equal(t, msg.Route(), RouterKey) require.Equal(t, msg.Type(), "create_gauge") signers := msg.GetSigners() @@ -141,10 +145,13 @@ func TestMsgCreatePool(t *testing.T) { } } +// TestMsgAddToGauge tests if valid/invalid add to gauge messages are properly validated/invalidated func TestMsgAddToGauge(t *testing.T) { + // generate a private/public key pair and get the respective address pk1 := ed25519.GenPrivKey().PubKey() addr1 := sdk.AccAddress(pk1.Address()) + // make a proper addToGauge message createMsg := func(after func(msg MsgAddToGauge) MsgAddToGauge) MsgAddToGauge { properMsg := *NewMsgAddToGauge( addr1, @@ -155,10 +162,10 @@ func TestMsgAddToGauge(t *testing.T) { return after(properMsg) } + // validate addToGauge message was created as intended msg := createMsg(func(msg MsgAddToGauge) MsgAddToGauge { return msg }) - require.Equal(t, msg.Route(), RouterKey) require.Equal(t, msg.Type(), "add_to_gauge") signers := msg.GetSigners() diff --git a/x/incentives/types/params.go b/x/incentives/types/params.go index 37fe1d27b42..b9e5a8fa145 100644 --- a/x/incentives/types/params.go +++ b/x/incentives/types/params.go @@ -6,30 +6,31 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -// Parameter store keys. +// Incentives parameters key store. var ( KeyDistrEpochIdentifier = []byte("DistrEpochIdentifier") ) -// ParamTable for minting module. +// ParamKeyTable returns the key table for the incentive module's parameters. func ParamKeyTable() paramtypes.KeyTable { return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) } +// NewParams takes an epoch distribution identifier, then returns an incentives Params struct. func NewParams(distrEpochIdentifier string) Params { return Params{ DistrEpochIdentifier: distrEpochIdentifier, } } -// default minting module parameters. +// DefaultParams returns the default incentives module parameters. func DefaultParams() Params { return Params{ DistrEpochIdentifier: "week", } } -// validate params. +// Validate checks that the incentives module parameters are valid. func (p Params) Validate() error { if err := epochtypes.ValidateEpochIdentifierInterface(p.DistrEpochIdentifier); err != nil { return err @@ -37,7 +38,7 @@ func (p Params) Validate() error { return nil } -// Implements params.ParamSet. +// ParamSetPairs takes the parameter struct and associates the paramsubspace key and field of the parameters as a KVStore. func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { return paramtypes.ParamSetPairs{ paramtypes.NewParamSetPair(KeyDistrEpochIdentifier, &p.DistrEpochIdentifier, epochtypes.ValidateEpochIdentifierInterface), From 5f17b1941d85e1bf906370327a635733bce2a65f Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Tue, 12 Jul 2022 13:42:37 -0500 Subject: [PATCH 059/376] Add partial ord for begin block (#1980) * wip * Add Sequence method for ensuring a sequence of orders happen * Mark all modules with no begin block logic * Finish adding Partial Ord for begin block * Add back IBChost * Address roman's comment of missed constraint --- app/app.go | 2 +- app/modules.go | 56 +++++++++---------------- osmoutils/partialord/partialord.go | 12 ++++++ osmoutils/partialord/partialord_test.go | 19 +++++++++ 4 files changed, 52 insertions(+), 37 deletions(-) diff --git a/app/app.go b/app/app.go index bdf85a0d5b8..2eb703be2ac 100644 --- a/app/app.go +++ b/app/app.go @@ -226,7 +226,7 @@ func NewOsmosisApp( // NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC) // Tell the app's module manager how to set the order of BeginBlockers, which are run at the beginning of every block. - app.mm.SetOrderBeginBlockers(orderBeginBlockers()...) + app.mm.SetOrderBeginBlockers(orderBeginBlockers(app.mm.ModuleNames())...) // Tell the app's module manager how to set the order of EndBlockers, which are run at the end of every block. app.mm.SetOrderEndBlockers(OrderEndBlockers(app.mm.ModuleNames())...) diff --git a/app/modules.go b/app/modules.go index a8d0900258f..fce87e2a77f 100644 --- a/app/modules.go +++ b/app/modules.go @@ -139,42 +139,26 @@ func appModules( } } -// orderBeginBlockers Tell the app's module manager how to set the order of -// BeginBlockers, which are run at the beginning of every block. -func orderBeginBlockers() []string { - return []string{ - // Upgrades should be run VERY first - upgradetypes.ModuleName, - // Note: epochs' begin should be "real" start of epochs, we keep epochs beginblock at the beginning - epochstypes.ModuleName, - capabilitytypes.ModuleName, - minttypes.ModuleName, - poolincentivestypes.ModuleName, - distrtypes.ModuleName, - slashingtypes.ModuleName, - evidencetypes.ModuleName, - stakingtypes.ModuleName, - ibchost.ModuleName, - ibctransfertypes.ModuleName, - icatypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - govtypes.ModuleName, - crisistypes.ModuleName, - genutiltypes.ModuleName, - authz.ModuleName, - paramstypes.ModuleName, - vestingtypes.ModuleName, - gammtypes.ModuleName, - incentivestypes.ModuleName, - lockuptypes.ModuleName, - poolincentivestypes.ModuleName, - tokenfactorytypes.ModuleName, - // superfluid must come after distribution and epochs - superfluidtypes.ModuleName, - txfeestypes.ModuleName, - wasm.ModuleName, - } +// orderBeginBlockers returns the order of BeginBlockers, by module name. +func orderBeginBlockers(allModuleNames []string) []string { + ord := partialord.NewPartialOrdering(allModuleNames) + // Upgrades should be run VERY first + // Epochs is set to be next right now, this in principle could change to come later / be at the end. + // But would have to be a holistic change with other pipelines taken into account. + ord.FirstElements(upgradetypes.ModuleName, epochstypes.ModuleName, capabilitytypes.ModuleName) + + // Staking ordering + // TODO: Perhaps this can be relaxed, left to future work to analyze. + ord.Sequence(distrtypes.ModuleName, slashingtypes.ModuleName, evidencetypes.ModuleName, stakingtypes.ModuleName) + // superfluid must come after distribution & epochs. + // TODO: we actually set it to come after staking, since thats what happened before, and want to minimize chance of break. + ord.After(superfluidtypes.ModuleName, stakingtypes.ModuleName) + // TODO: This can almost certainly be un-constrained, but we keep the constraint to match prior functionality. + // IBChost came after staking, before superfluid. + // TODO: Come back and delete this line after testing the base change. + ord.Sequence(stakingtypes.ModuleName, ibchost.ModuleName, superfluidtypes.ModuleName) + // every remaining module's begin block is a no-op. + return ord.TotalOrdering() } func OrderEndBlockers(allModuleNames []string) []string { diff --git a/osmoutils/partialord/partialord.go b/osmoutils/partialord/partialord.go index d97501b7a01..0c302faf804 100644 --- a/osmoutils/partialord/partialord.go +++ b/osmoutils/partialord/partialord.go @@ -76,6 +76,18 @@ func (ord *PartialOrdering) LastElements(elems ...string) { ord.lastSealed = true } +// Sequence sets a sequence of ordering constraints. +// So if were making an ordering over {A, B, C, D, E}, and elems provided is {D, B, A} +// then we are guaranteed that the total ordering will have D comes before B comes before A. +// (They're may be elements interspersed, e.g. {D, C, E, B, A} is a valid ordering) +func (ord *PartialOrdering) Sequence(seq ...string) { + // We make every node in the sequence have a prior node + for i := 0; i < (len(seq) - 1); i++ { + err := ord.dag.AddEdge(seq[i], seq[i+1]) + handleDAGErr(err) + } +} + // TotalOrdering returns a deterministically chosen total ordering that satisfies all specified // partial ordering constraints. // diff --git a/osmoutils/partialord/partialord_test.go b/osmoutils/partialord/partialord_test.go index 1f8afd4e0c9..9d44f901934 100644 --- a/osmoutils/partialord/partialord_test.go +++ b/osmoutils/partialord/partialord_test.go @@ -53,3 +53,22 @@ func TestNonStandardAPIOrder(t *testing.T) { expOrdering = []string{"A", "B", "C", "D", "E", "F", "G"} require.Equal(t, expOrdering, ord.TotalOrdering()) } + +// This test ad-hocly tests combination of multiple sequences, first elements, and an After +// invokation. +func TestSequence(t *testing.T) { + // This test uses direct ordering before First, and after Last + names := []string{"A", "B", "C", "D", "E", "F", "G"} + ord := partialord.NewPartialOrdering(names) + // Make B A C a sequence + ord.Sequence("B", "A", "C") + // Make A G E a sub-sequence + ord.Sequence("A", "G", "E") + // make first elements D B F + ord.FirstElements("D", "B", "F") + // make C come after E + ord.After("C", "G") + + expOrdering := []string{"D", "B", "F", "A", "G", "C", "E"} + require.Equal(t, expOrdering, ord.TotalOrdering()) +} From 4c379e19d3382b49df418a94afb140413969441f Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 12 Jul 2022 19:59:34 -0400 Subject: [PATCH 060/376] refactor(e2e): run individual nodes; rely on rpc client in setup (#2040) * refactor(e2e): run individual nodes; rely on rpc client in setup * Update tests/e2e/configurer/chain/chain.go * reduce waitUntilRepeatPauseTime to 500ms * remove timeout from RPC status call * 2 second pause time + 60 repeat max --- tests/e2e/configurer/base.go | 47 +---------- tests/e2e/configurer/chain/chain.go | 107 +++++++++++++++++++++++- tests/e2e/configurer/chain/commands.go | 23 +++-- tests/e2e/configurer/chain/validator.go | 9 +- tests/e2e/configurer/upgrade.go | 101 +++++----------------- tests/e2e/e2e_test.go | 6 +- 6 files changed, 156 insertions(+), 137 deletions(-) diff --git a/tests/e2e/configurer/base.go b/tests/e2e/configurer/base.go index e18ddb457d7..f3b126fc51b 100644 --- a/tests/e2e/configurer/base.go +++ b/tests/e2e/configurer/base.go @@ -1,7 +1,6 @@ package configurer import ( - "context" "encoding/json" "fmt" "io" @@ -13,7 +12,6 @@ import ( "time" "github.com/stretchr/testify/require" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" @@ -64,48 +62,11 @@ func (bc *baseConfigurer) RunValidators() error { func (bc *baseConfigurer) runValidators(chainConfig *chain.Config) error { bc.t.Logf("starting %s validator containers...", chainConfig.Id) - - for _, val := range chainConfig.NodeConfigs { - resource, err := bc.containerManager.RunValidatorResource(chainConfig.Id, val.Name, val.ConfigDir) - if err != nil { + for valIndex := range chainConfig.NodeConfigs { + if err := chainConfig.RunNode(valIndex); err != nil { return err } - bc.t.Logf("started %s validator container: %s", resource.Container.Name[1:], resource.Container.ID) - } - - validatorHostPort, err := bc.containerManager.GetValidatorHostPort(chainConfig.Id, 0, "26657/tcp") - if err != nil { - return err - } - - rpcClient, err := rpchttp.New(fmt.Sprintf("tcp://%s", validatorHostPort), "/websocket") - if err != nil { - return err } - - require.Eventually( - bc.t, - func() bool { - ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) - defer cancel() - - status, err := rpcClient.Status(ctx) - if err != nil { - return false - } - - // let the node produce a few blocks - if status.SyncInfo.CatchingUp && status.SyncInfo.LatestBlockHeight < bc.syncUntilHeight { - return false - } - - return true - }, - 5*time.Minute, - time.Second, - "Osmosis node failed to produce blocks", - ) - chainConfig.ExtractValidatorOperatorAddresses() return nil } @@ -209,9 +170,9 @@ func (bc *baseConfigurer) connectIBCChains(chainA *chain.Config, chainB *chain.C func (bc *baseConfigurer) initializeChainConfigFromInitChain(initializedChain *initialization.Chain, chainConfig *chain.Config) { chainConfig.ChainMeta = initializedChain.ChainMeta - chainConfig.NodeConfigs = make([]*chain.ValidatorConfig, 0, len(initializedChain.Nodes)) + chainConfig.NodeConfigs = make([]*chain.NodeConfig, 0, len(initializedChain.Nodes)) for _, validator := range initializedChain.Nodes { - chainConfig.NodeConfigs = append(chainConfig.NodeConfigs, &chain.ValidatorConfig{ + chainConfig.NodeConfigs = append(chainConfig.NodeConfigs, &chain.NodeConfig{ Node: *validator, }) } diff --git a/tests/e2e/configurer/chain/chain.go b/tests/e2e/configurer/chain/chain.go index 7d008db2ecf..527f80b7850 100644 --- a/tests/e2e/configurer/chain/chain.go +++ b/tests/e2e/configurer/chain/chain.go @@ -1,7 +1,14 @@ package chain import ( + "context" + "fmt" "testing" + "time" + + "github.com/stretchr/testify/require" + rpchttp "github.com/tendermint/tendermint/rpc/client/http" + coretypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" @@ -17,7 +24,7 @@ type Config struct { PropHeight int LatestProposalNumber int LatestLockNumber int - NodeConfigs []*ValidatorConfig + NodeConfigs []*NodeConfig t *testing.T containerManager *containers.Manager @@ -31,6 +38,13 @@ type syncInfo struct { SyncInfo status `json:"SyncInfo"` } +const ( + // waitUntilRepeatPauseTime is the time to wait between each check of the node status. + waitUntilRepeatPauseTime = 2 * time.Second + // waitUntilrepeatMax is the maximum number of times to repeat the wait until condition. + waitUntilrepeatMax = 60 +) + func New(t *testing.T, containerManager *containers.Manager, id string, initValidatorConfigs []*initialization.NodeConfig) *Config { return &Config{ ChainMeta: initialization.ChainMeta{ @@ -41,3 +55,94 @@ func New(t *testing.T, containerManager *containers.Manager, id string, initVali containerManager: containerManager, } } + +// RunNode runs a node container for the given nodeIndex. +// The node configuration must be already added to the chain config prior to calling this +// method. +func (c *Config) RunNode(nodeIndex int) error { + c.t.Logf("starting %s validator containers...", c.Id) + + resource, err := c.containerManager.RunValidatorResource(c.Id, c.NodeConfigs[nodeIndex].Name, c.NodeConfigs[nodeIndex].ConfigDir) + if err != nil { + return err + } + + hostPort := resource.GetHostPort("26657/tcp") + rpcClient, err := rpchttp.New("tcp://"+hostPort, "/websocket") + if err != nil { + return err + } + + require.Eventually( + c.t, + func() bool { + if _, err := rpcClient.Health(context.Background()); err != nil { + return false + } + + c.t.Logf("started %s node container: %s", resource.Container.Name[1:], resource.Container.ID) + return true + }, + 5*time.Minute, + time.Second, + "Osmosis node failed to produce blocks", + ) + + c.NodeConfigs[nodeIndex].rpcClient = rpcClient + + if c.NodeConfigs[nodeIndex].IsValidator { + return c.ExtractValidatorOperatorAddress(nodeIndex) + } + + return nil +} + +// WaitUntil waits until validator with validatorIndex reaches doneCondition. Return nil +// if reached, error otherwise. +func (c *Config) WaitUntil(nodeIndex int, doneCondition func(syncInfo coretypes.SyncInfo) bool) error { + var latestBlockHeight int64 + for i := 0; i < waitUntilrepeatMax; i++ { + status, err := c.NodeConfigs[nodeIndex].rpcClient.Status(context.Background()) + if err != nil { + return err + } + latestBlockHeight = status.SyncInfo.LatestBlockHeight + // let the node produce a few blocks + if !doneCondition(status.SyncInfo) { + time.Sleep(waitUntilRepeatPauseTime) + continue + } + return nil + } + return fmt.Errorf("validator with index %d timed out waiting for condition, latest block height was %d", nodeIndex, latestBlockHeight) +} + +// WaitUntilHeight waits for all validators to reach the specified height at the minimum. +// returns error, if any. +func (c *Config) WaitUntilHeight(height int64) error { + // Ensure the nodes are making progress. + doneCondition := func(syncInfo coretypes.SyncInfo) bool { + curHeight := syncInfo.LatestBlockHeight + + if curHeight < height { + c.t.Logf("current block height is %d, waiting to reach: %d", curHeight, height) + return false + } + + return !syncInfo.CatchingUp + } + + for nodeIndex := range c.NodeConfigs { + nodeResource, exists := c.containerManager.GetValidatorResource(c.Id, nodeIndex) + container := nodeResource.Container + c.t.Logf("node container: %s, id: %s, waiting to reach height %d", container.Name[1:], container.ID, height) + if !exists { + return fmt.Errorf("validator on chain %s with index %d does not exist", c.Id, nodeIndex) + } + if err := c.WaitUntil(nodeIndex, doneCondition); err != nil { + c.t.Errorf("validator with index %d failed to start", nodeIndex) + return err + } + } + return nil +} diff --git a/tests/e2e/configurer/chain/commands.go b/tests/e2e/configurer/chain/commands.go index fffc2fa1f8b..6195940f98f 100644 --- a/tests/e2e/configurer/chain/commands.go +++ b/tests/e2e/configurer/chain/commands.go @@ -177,14 +177,19 @@ func (c *Config) SendIBC(dstChain *Config, recipient string, token sdk.Coin) { c.t.Log("successfully sent IBC tokens") } -func (c *Config) ExtractValidatorOperatorAddresses() { - for i, val := range c.NodeConfigs { - cmd := []string{"osmosisd", "debug", "addr", val.PublicKey} - c.t.Logf("extracting validator operator addresses for chain-id: %s", c.Id) - _, errBuf, err := c.containerManager.ExecCmd(c.t, c.Id, i, cmd, "") - require.NoError(c.t, err) - re := regexp.MustCompile("osmovaloper(.{39})") - operAddr := fmt.Sprintf("%s\n", re.FindString(errBuf.String())) - c.NodeConfigs[i].OperatorAddress = strings.TrimSuffix(operAddr, "\n") +func (c *Config) ExtractValidatorOperatorAddress(nodeIndex int) error { + node := c.NodeConfigs[nodeIndex] + + if !node.IsValidator { + return fmt.Errorf("node %s at index %d is not a validator", node.Name, nodeIndex) } + + cmd := []string{"osmosisd", "debug", "addr", node.PublicKey} + c.t.Logf("extracting validator operator addresses for chain-id: %s", c.Id) + _, errBuf, err := c.containerManager.ExecCmd(c.t, c.Id, nodeIndex, cmd, "") + require.NoError(c.t, err) + re := regexp.MustCompile("osmovaloper(.{39})") + operAddr := fmt.Sprintf("%s\n", re.FindString(errBuf.String())) + c.NodeConfigs[nodeIndex].OperatorAddress = strings.TrimSuffix(operAddr, "\n") + return nil } diff --git a/tests/e2e/configurer/chain/validator.go b/tests/e2e/configurer/chain/validator.go index c973d1378d2..e9220401a97 100644 --- a/tests/e2e/configurer/chain/validator.go +++ b/tests/e2e/configurer/chain/validator.go @@ -1,9 +1,14 @@ package chain -import "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +import ( + rpchttp "github.com/tendermint/tendermint/rpc/client/http" -type ValidatorConfig struct { + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +) + +type NodeConfig struct { initialization.Node OperatorAddress string + rpcClient *rpchttp.HTTP } diff --git a/tests/e2e/configurer/upgrade.go b/tests/e2e/configurer/upgrade.go index 364f2ea464c..7489e629092 100644 --- a/tests/e2e/configurer/upgrade.go +++ b/tests/e2e/configurer/upgrade.go @@ -7,8 +7,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/config" "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" @@ -146,35 +144,11 @@ func (uc *UpgradeConfigurer) runProposalUpgrade() error { // wait till all chains halt at upgrade height for _, chainConfig := range uc.chainConfigs { - for validatorIndex := range chainConfig.NodeConfigs { - validatorResource, exists := uc.containerManager.GetValidatorResource(chainConfig.Id, validatorIndex) - require.True(uc.t, exists, "validator container not found: chain id %s, valIdx %d ", chainConfig.Id, validatorIndex) - containerId := validatorResource.Container.ID - containerName := validatorResource.Container.Name[1:] - - // use counter to ensure no new blocks are being created - counter := 0 - uc.t.Logf("waiting to reach upgrade height on %s validator container: %s", containerName, containerId) - require.Eventually( - uc.t, - func() bool { - currentHeight := chainConfig.QueryCurrentChainHeightFromValidator(validatorIndex) - if currentHeight != chainConfig.PropHeight { - uc.t.Logf("current block height on %s is %v, waiting for block %v container: %s", containerName, currentHeight, chainConfig.PropHeight, containerId) - } - if currentHeight > chainConfig.PropHeight { - panic("chain did not halt at upgrade height") - } - if currentHeight == chainConfig.PropHeight { - counter++ - } - return counter == 3 - }, - 5*time.Minute, - time.Second, - ) - uc.t.Logf("reached upgrade height on %s container: %s", containerName, containerId) + uc.t.Logf("waiting to reach upgrade height on chain %s", chainConfig.Id) + if err := chainConfig.WaitUntilHeight(int64(chainConfig.PropHeight)); err != nil { + return err } + uc.t.Logf("upgrade height reached on chain %s", chainConfig.Id) } // remove all containers so we can upgrade them to the new version @@ -189,71 +163,40 @@ func (uc *UpgradeConfigurer) runProposalUpgrade() error { // remove all containers so we can upgrade them to the new version for _, chainConfig := range uc.chainConfigs { - uc.upgradeContainers(chainConfig, chainConfig.PropHeight) + if err := uc.upgradeContainers(chainConfig, chainConfig.PropHeight); err != nil { + return err + } } return nil } func (uc *UpgradeConfigurer) runForkUpgrade() error { for _, chainConfig := range uc.chainConfigs { - for i := range chainConfig.NodeConfigs { - validatorResource, exists := uc.containerManager.GetValidatorResource(chainConfig.Id, i) - if !exists { - return fmt.Errorf("validator container not found: chain id %s, valIdx %d ", chainConfig.Id, i) - } - containerId := validatorResource.Container.ID - containerName := validatorResource.Container.Name[1:] - - uc.t.Logf("waiting to reach fork height on %s validator container: %s", containerName, containerId) - require.Eventually( - uc.t, - func() bool { - currentHeight := chainConfig.QueryCurrentChainHeightFromValidator(i) - if int64(currentHeight) < uc.forkHeight { - uc.t.Logf("current block height on %s is %v, waiting for block %v container: %s", containerName, currentHeight, uc.forkHeight, containerId) - return false - } - return true - }, - 5*time.Minute, - time.Second, - ) - uc.t.Logf("successfully got past fork height on %s container: %s", containerName, containerId) + uc.t.Logf("waiting to reach fork height on chain %s", chainConfig.Id) + if err := chainConfig.WaitUntilHeight(uc.forkHeight); err != nil { + return err } + uc.t.Logf("fork height reached on chain %s", chainConfig.Id) } return nil } -func (uc *UpgradeConfigurer) upgradeContainers(chainConfig *chain.Config, propHeight int) { +func (uc *UpgradeConfigurer) upgradeContainers(chainConfig *chain.Config, propHeight int) error { // upgrade containers to the locally compiled daemon uc.t.Logf("starting upgrade for chain-id: %s...", chainConfig.Id) uc.containerManager.OsmosisRepository = containers.CurrentBranchOsmoRepository uc.containerManager.OsmosisTag = containers.CurrentBranchOsmoTag - for _, val := range chainConfig.NodeConfigs { - validatorResource, err := uc.containerManager.RunValidatorResource(chainConfig.Id, val.Name, val.ConfigDir) - require.NoError(uc.t, err) - uc.t.Logf("started %s validator container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - } - // check that we are creating blocks again - for validatorIndex := range chainConfig.NodeConfigs { - validatorResource, exists := uc.containerManager.GetValidatorResource(chainConfig.Id, validatorIndex) - require.True(uc.t, exists, "validator container not found: chain id %s, valIdx %d ", chainConfig.Id, validatorIndex) - containerId := validatorResource.Container.ID - containerName := validatorResource.Container.Name[1:] + for nodeIndex := range chainConfig.NodeConfigs { + if err := chainConfig.RunNode(nodeIndex); err != nil { + return err + } + } - require.Eventually( - uc.t, - func() bool { - currentHeight := chainConfig.QueryCurrentChainHeightFromValidator(validatorIndex) - if currentHeight <= propHeight { - uc.t.Logf("current block height on %s is %v, waiting to create blocks container: %s", containerName, currentHeight, containerId) - } - return currentHeight > propHeight - }, - 5*time.Minute, - time.Second, - ) - uc.t.Logf("upgrade successful on %s validator container: %s", containerName, containerId) + uc.t.Logf("waiting to upgrade containers on chain %s", chainConfig.Id) + if err := chainConfig.WaitUntilHeight(int64(propHeight)); err != nil { + return err } + uc.t.Logf("upgrade successful on chain %s", chainConfig.Id) + return nil } diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index 48e0a0020ac..34bb446e4ff 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -60,7 +60,7 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { chainA.VoteNoProposal(0, walletName) sfProposalNumber := strconv.Itoa(chainA.LatestProposalNumber) - s.Require().Eventually( + s.Eventually( func() bool { noTotal, yesTotal, noWithVetoTotal, abstainTotal, err := chainA.QueryPropTally(0, sfProposalNumber) if err != nil { @@ -77,9 +77,9 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { ) noTotal, _, _, _, _ := chainA.QueryPropTally(0, sfProposalNumber) noTotalFinal, err := strconv.Atoi(noTotal.String()) - s.Require().NoError(err) + s.NoError(err) - s.Require().Eventually( + s.Eventually( func() bool { intAccountBalance, err := chainA.QueryIntermediaryAccount(0, "gamm/pool/1", chainA.NodeConfigs[1].OperatorAddress) s.Require().NoError(err) From e383d32c6e7fdd27f2d3d6dd5fd07aa56d834ee1 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Tue, 12 Jul 2022 20:41:07 -0500 Subject: [PATCH 061/376] e2e: Reduce repetitive args for tx creation commands (#2043) * Quick PR to reduce repetitive args for tx creation commands * Add --log_format=json --- tests/e2e/configurer/chain/commands.go | 40 +++++++++++++------------- tests/e2e/containers/containers.go | 10 +++++++ 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/tests/e2e/configurer/chain/commands.go b/tests/e2e/configurer/chain/commands.go index 6195940f98f..9500f09e182 100644 --- a/tests/e2e/configurer/chain/commands.go +++ b/tests/e2e/configurer/chain/commands.go @@ -15,8 +15,8 @@ import ( func (c *Config) CreatePool(poolFile, from string) { c.t.Logf("creating pool for chain-id: %s", c.Id) - cmd := []string{"osmosisd", "tx", "gamm", "create-pool", fmt.Sprintf("--pool-file=/osmosis/%s", poolFile), fmt.Sprintf("--chain-id=%s", c.Id), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + cmd := []string{"osmosisd", "tx", "gamm", "create-pool", fmt.Sprintf("--pool-file=/osmosis/%s", poolFile), fmt.Sprintf("--from=%s", from)} + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) require.NoError(c.t, err) validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) @@ -30,8 +30,8 @@ func (c *Config) SubmitUpgradeProposal(upgradeVersion string) { upgradeHeightStr := strconv.Itoa(c.PropHeight) c.t.Logf("submitting upgrade proposal on %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%s", upgradeHeightStr), "--upgrade-info=\"\"", fmt.Sprintf("--chain-id=%s", c.Id), "--from=val", "-b=block", "--yes", "--keyring-backend=test", "--log_format=json"} - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%s", upgradeHeightStr), "--upgrade-info=\"\"", "--from=val"} + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) require.NoError(c.t, err) c.t.Log("successfully submitted upgrade proposal") c.LatestProposalNumber = c.LatestProposalNumber + 1 @@ -42,8 +42,8 @@ func (c *Config) SubmitSuperfluidProposal(asset string) { require.True(c.t, exists) c.t.Logf("submitting superfluid proposal for asset %s on %s container: %s", asset, validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "set-superfluid-assets-proposal", fmt.Sprintf("--superfluid-assets=%s", asset), fmt.Sprintf("--title=\"%s superfluid asset\"", asset), fmt.Sprintf("--description=\"%s superfluid asset\"", asset), "--from=val", "-b=block", "--yes", "--keyring-backend=test", "--log_format=json", fmt.Sprintf("--chain-id=%s", c.Id)} - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "set-superfluid-assets-proposal", fmt.Sprintf("--superfluid-assets=%s", asset), fmt.Sprintf("--title=\"%s superfluid asset\"", asset), fmt.Sprintf("--description=\"%s superfluid asset\"", asset), "--from=val"} + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) require.NoError(c.t, err) c.t.Log("successfully submitted superfluid proposal") c.LatestProposalNumber = c.LatestProposalNumber + 1 @@ -54,8 +54,8 @@ func (c *Config) SubmitTextProposal(text string) { require.True(c.t, exists) c.t.Logf("submitting text proposal on %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "--type=text", fmt.Sprintf("--title=\"%s\"", text), "--description=\"test text proposal\"", "--from=val", "-b=block", "--yes", "--keyring-backend=test", "--log_format=json", fmt.Sprintf("--chain-id=%s", c.Id)} - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "--type=text", fmt.Sprintf("--title=\"%s\"", text), "--description=\"test text proposal\"", "--from=val"} + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) c.t.Log("successfully submitted text proposal") require.NoError(c.t, err) c.LatestProposalNumber = c.LatestProposalNumber + 1 @@ -67,8 +67,8 @@ func (c *Config) DepositProposal() { propStr := strconv.Itoa(c.LatestProposalNumber) c.t.Logf("depositing to proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "deposit", propStr, "500000000uosmo", "--from=val", fmt.Sprintf("--chain-id=%s", c.Id), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + cmd := []string{"osmosisd", "tx", "gov", "deposit", propStr, "500000000uosmo", "--from=val"} + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) require.NoError(c.t, err) c.t.Log("successfully deposited to proposal") } @@ -76,9 +76,9 @@ func (c *Config) DepositProposal() { func (c *Config) VoteYesProposal() { propStr := strconv.Itoa(c.LatestProposalNumber) c.t.Logf("voting yes on proposal for chain-id: %s", c.Id) - cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "yes", "--from=val", fmt.Sprintf("--chain-id=%s", c.Id), "-b=block", "--yes", "--keyring-backend=test"} + cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "yes", "--from=val"} for i := range c.NodeConfigs { - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, i, cmd, "code: 0") + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, i, cmd) require.NoError(c.t, err) validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, i) @@ -90,8 +90,8 @@ func (c *Config) VoteYesProposal() { func (c *Config) VoteNoProposal(validatorIdx int, from string) { propStr := strconv.Itoa(c.LatestProposalNumber) c.t.Logf("voting no on proposal for chain-id: %s", c.Id) - cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "no", fmt.Sprintf("--from=%s", from), fmt.Sprintf("--chain-id=%s", c.Id), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIdx, cmd, "code: 0") + cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "no", fmt.Sprintf("--from=%s", from)} + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, validatorIdx, cmd) require.NoError(c.t, err) validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, validatorIdx) @@ -101,8 +101,8 @@ func (c *Config) VoteNoProposal(validatorIdx int, from string) { func (c *Config) LockTokens(validatorIdx int, tokens string, duration string, from string) { c.t.Logf("locking %s for %s on chain-id: %s", tokens, duration, c.Id) - cmd := []string{"osmosisd", "tx", "lockup", "lock-tokens", tokens, fmt.Sprintf("--chain-id=%s", c.Id), fmt.Sprintf("--duration=%s", duration), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIdx, cmd, "code: 0") + cmd := []string{"osmosisd", "tx", "lockup", "lock-tokens", tokens, fmt.Sprintf("--duration=%s", duration), fmt.Sprintf("--from=%s", from)} + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, validatorIdx, cmd) require.NoError(c.t, err) validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, validatorIdx) @@ -114,8 +114,8 @@ func (c *Config) LockTokens(validatorIdx int, tokens string, duration string, fr func (c *Config) SuperfluidDelegate(valAddress string, from string) { lockStr := strconv.Itoa(c.LatestLockNumber) c.t.Logf("superfluid delegating lock %s to %s on chain-id: %s", lockStr, valAddress, c.Id) - cmd := []string{"osmosisd", "tx", "superfluid", "delegate", lockStr, valAddress, fmt.Sprintf("--chain-id=%s", c.Id), fmt.Sprintf("--from=%s", from), "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, 0, cmd, "code: 0") + cmd := []string{"osmosisd", "tx", "superfluid", "delegate", lockStr, valAddress, fmt.Sprintf("--from=%s", from)} + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) require.NoError(c.t, err) validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) @@ -125,8 +125,8 @@ func (c *Config) SuperfluidDelegate(valAddress string, from string) { func (c *Config) BankSend(validatorIndex int, amount string, sendAddress string, receiveAddress string) { c.t.Logf("sending %s from %s to %s on chain-id: %s", amount, sendAddress, receiveAddress, c.Id) - cmd := []string{"osmosisd", "tx", "bank", "send", sendAddress, receiveAddress, amount, fmt.Sprintf("--chain-id=%s", c.Id), "--from=val", "-b=block", "--yes", "--keyring-backend=test"} - _, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIndex, cmd, "code: 0") + cmd := []string{"osmosisd", "tx", "bank", "send", sendAddress, receiveAddress, amount, "--from=val"} + _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, validatorIndex, cmd) require.NoError(c.t, err) validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) diff --git a/tests/e2e/containers/containers.go b/tests/e2e/containers/containers.go index bd60d2a253a..9edb77ee5a1 100644 --- a/tests/e2e/containers/containers.go +++ b/tests/e2e/containers/containers.go @@ -46,6 +46,16 @@ func NewManager(isUpgrade bool, isFork bool) (docker *Manager, err error) { return docker, nil } +// ExecTxCmd Runs ExecCmd, with flags for txs added. +// namely adding flags `--chain-id={chain-id} -b=block --yes --keyring-backend=test "--log_format=json"`, +// and searching for `code: 0` +func (m *Manager) ExecTxCmd(t *testing.T, chainId string, validatorIndex int, command []string) (bytes.Buffer, bytes.Buffer, error) { + allTxArgs := []string{fmt.Sprintf("--chain-id=%s", chainId), "-b=block", "--yes", "--keyring-backend=test", "--log_format=json"} + txCommand := append(command, allTxArgs...) + successStr := "code: 0" + return m.ExecCmd(t, chainId, validatorIndex, txCommand, successStr) +} + // ExecCmd executes command on chainId by running it on the validator container (specified by validatorIndex) // success is the output of the command that needs to be observed for the command to be deemed successful. // It is found by checking if stdout or stderr contains the success string anywhere within it. From 036c0416282b59195650ecdc3e1168f1e8909107 Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Wed, 13 Jul 2022 15:56:29 +0900 Subject: [PATCH 062/376] chore: Add documentations for superfluid module (#1991) * Add documentations for superfluid module * Fix lint * Implement roman's review --- proto/osmosis/superfluid/genesis.proto | 6 +++ proto/osmosis/superfluid/params.proto | 5 +- proto/osmosis/superfluid/query.proto | 66 ++++++----------------- proto/osmosis/superfluid/superfluid.proto | 17 ++++-- proto/osmosis/superfluid/tx.proto | 3 ++ x/superfluid/keeper/hooks_test.go | 6 +-- x/superfluid/keeper/msg_server.go | 26 +++++++++ x/superfluid/keeper/stake.go | 49 ++++++++++++++--- x/superfluid/types/genesis.pb.go | 12 +++-- x/superfluid/types/params.pb.go | 5 +- x/superfluid/types/query.pb.go | 40 +++++++------- x/superfluid/types/superfluid.pb.go | 19 +++++-- 12 files changed, 158 insertions(+), 96 deletions(-) diff --git a/proto/osmosis/superfluid/genesis.proto b/proto/osmosis/superfluid/genesis.proto index e195858d8ce..af6d7e08fef 100644 --- a/proto/osmosis/superfluid/genesis.proto +++ b/proto/osmosis/superfluid/genesis.proto @@ -10,10 +10,16 @@ option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; // GenesisState defines the module's genesis state. message GenesisState { Params params = 1 [ (gogoproto.nullable) = false ]; + // superfluid_assets defines the registered superfluid assets that have been + // registered via governance. repeated SuperfluidAsset superfluid_assets = 2 [ (gogoproto.nullable) = false ]; + // osmo_equivalent_multipliers is the records of osmo equivilent amount of + // each superfluid registered pool, updated every epoch. repeated OsmoEquivalentMultiplierRecord osmo_equivalent_multipliers = 3 [ (gogoproto.nullable) = false ]; + // intermediary_accounts is a secondary account for superfluid staking that + // plays an intermediary role between validators and the delegators. repeated SuperfluidIntermediaryAccount intermediary_accounts = 4 [ (gogoproto.nullable) = false ]; repeated LockIdIntermediaryAccountConnection intemediary_account_connections = diff --git a/proto/osmosis/superfluid/params.proto b/proto/osmosis/superfluid/params.proto index 79e43a9c465..630ef80864f 100644 --- a/proto/osmosis/superfluid/params.proto +++ b/proto/osmosis/superfluid/params.proto @@ -8,8 +8,9 @@ option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; // Params holds parameters for the superfluid module message Params { - // the risk_factor is to be cut on OSMO equivalent value of lp tokens for - // superfluid staking, default: 5% + // minimum_risk_factor is to be cut on OSMO equivalent value of lp tokens for + // superfluid staking, default: 5%. The minimum risk facotr works as a + // parameter to better incentive vanilla staking. string minimum_risk_factor = 1 [ (gogoproto.moretags) = "yaml:\"minimum_risk_factor\"", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", diff --git a/proto/osmosis/superfluid/query.proto b/proto/osmosis/superfluid/query.proto index aac8702d5b4..1a981242403 100644 --- a/proto/osmosis/superfluid/query.proto +++ b/proto/osmosis/superfluid/query.proto @@ -16,31 +16,36 @@ option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; // Query defines the gRPC querier service. service Query { - // Params returns the total set of minting parameters. + // Params returns the total set of superfluid parameters. rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { option (google.api.http).get = "/osmosis/superfluid/v1beta1/params"; } - // Returns superfluid asset type + // Returns superfluid asset type, whether if it's a native asset or an lp + // share. rpc AssetType(AssetTypeRequest) returns (AssetTypeResponse) { option (google.api.http).get = "/osmosis/superfluid/v1beta1/asset_type"; } - // Returns all superfluid asset types + + // Returns all registered superfluid assets. rpc AllAssets(AllAssetsRequest) returns (AllAssetsResponse) { option (google.api.http).get = "/osmosis/superfluid/v1beta1/all_assets"; } - // Returns superfluid asset Multiplier + + // Returns the osmo equivalent multiplier used in the most recent epoch. rpc AssetMultiplier(AssetMultiplierRequest) returns (AssetMultiplierResponse) { option (google.api.http).get = "/osmosis/superfluid/v1beta1/asset_multiplier"; } - // Returns all superfluid intermediary account + + // Returns all superfluid intermediary accounts. rpc AllIntermediaryAccounts(AllIntermediaryAccountsRequest) returns (AllIntermediaryAccountsResponse) { option (google.api.http).get = "/osmosis/superfluid/v1beta1/all_intermediary_accounts"; } + // Returns intermediary account connected to a superfluid staked lock by id rpc ConnectedIntermediaryAccount(ConnectedIntermediaryAccountRequest) returns (ConnectedIntermediaryAccountResponse) { @@ -48,15 +53,15 @@ service Query { "/osmosis/superfluid/v1beta1/connected_intermediary_account/{lock_id}"; } - // Returns the total amount of osmo superfluidly staked - // response denominated in uosmo + // Returns the total amount of osmo superfluidly staked. + // Response is denominated in uosmo. rpc TotalSuperfluidDelegations(TotalSuperfluidDelegationsRequest) returns (TotalSuperfluidDelegationsResponse) { option (google.api.http).get = "/osmosis/superfluid/v1beta1/all_superfluid_delegations"; } - // Returns the coins superfluid delegated for a delegator, validator, denom + // Returns the coins superfluid delegated for the delegator, validator, denom // triplet rpc SuperfluidDelegationAmount(SuperfluidDelegationAmountRequest) returns (SuperfluidDelegationAmountResponse) { @@ -64,13 +69,14 @@ service Query { "/osmosis/superfluid/v1beta1/superfluid_delegation_amount"; } - // Returns all the superfluid poistions for a specific delegator + // Returns all the delegated superfluid poistions for a specific delegator. rpc SuperfluidDelegationsByDelegator(SuperfluidDelegationsByDelegatorRequest) returns (SuperfluidDelegationsByDelegatorResponse) { option (google.api.http).get = "/osmosis/superfluid/v1beta1/" "superfluid_delegations/{delegator_address}"; } + // Returns all the undelegating superfluid poistions for a specific delegator. rpc SuperfluidUndelegationsByDelegator( SuperfluidUndelegationsByDelegatorRequest) returns (SuperfluidUndelegationsByDelegatorResponse) { @@ -99,21 +105,6 @@ service Query { "estimate_superfluid_delegation_amount_by_validator_denom"; } - // // Returns all the unbonding superfluid positions of a delegator - // rpc SuperfluidUnbondingsByDelegator(SuperfluidUnbondingsByDelegatorRequest) - // returns (SuperfluidUnbondingsByDelegatorResponse) { - // option (google.api.http).get = - // "/osmosis/superfluid/v1beta1/superfluid_unbondings/{delegator_address}"; - // } - - // // Returns all the unbonding superfluid positions of a specific denom - // unbonding from one validator rpc - // SuperfluidUnbondingsByValidatorDenom(SuperfluidUnbondingsByValidatorDenomRequest) - // returns (SuperfluidUnbondingsByValidatorDenomResponse) { - // option (google.api.http).get = - // "/osmosis/superfluid/v1beta1/superfluid_unbondings_by_validator_denom"; - // } - // Returns the specified delegations for a specific delegator rpc TotalDelegationByDelegator(QueryTotalDelegationByDelegatorRequest) returns (QueryTotalDelegationByDelegatorResponse) { @@ -240,33 +231,6 @@ message EstimateSuperfluidDelegatedAmountByValidatorDenomResponse { ]; } -// message SuperfluidUnbondingsByDelegatorRequest { -// string delegator_address = 1; -// } - -// message SuperfluidUnbondingsByDelegatorResponse { -// repeated SuperfluidDelegationRecord superfluid_unbonding_records = 1 -// [ (gogoproto.nullable) = false ]; -// repeated cosmos.base.v1beta1.Coin total_unbonding_coins = 2 [ -// (gogoproto.nullable) = false, -// (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" -// ]; -// } - -// message SuperfluidUnbondingsByValidatorDenomRequest { -// string validator_address = 1; -// string denom = 2; -// } - -// message SuperfluidUnbondingsByValidatorDenomResponse { -// repeated SuperfluidDelegationRecord superfluid_unbonding_records = 1 -// [ (gogoproto.nullable) = false ]; -// repeated cosmos.base.v1beta1.Coin total_unbonding_coins = 2 [ -// (gogoproto.nullable) = false, -// (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" -// ]; -// } - message QueryTotalDelegationByDelegatorRequest { string delegator_address = 1; } message QueryTotalDelegationByDelegatorResponse { diff --git a/proto/osmosis/superfluid/superfluid.proto b/proto/osmosis/superfluid/superfluid.proto index 4c0bf01b5ea..0b35322e401 100644 --- a/proto/osmosis/superfluid/superfluid.proto +++ b/proto/osmosis/superfluid/superfluid.proto @@ -8,6 +8,8 @@ import "cosmos/base/v1beta1/coin.proto"; option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; +// SuperfluidAssetType indicates whether the superfluid asset is +// a native token itself or the lp share of a pool. enum SuperfluidAssetType { option (gogoproto.goproto_enum_prefix) = false; @@ -22,12 +24,16 @@ message SuperfluidAsset { option (gogoproto.goproto_getters) = false; string denom = 1; + // AssetType indicates whether the superfluid asset is a native token or an lp + // share SuperfluidAssetType asset_type = 2; } // SuperfluidIntermediaryAccount takes the role of intermediary between LP token -// and OSMO tokens for superfluid staking +// and OSMO tokens for superfluid staking. The intermediary account is the +// actual account responsible for delegation, not the validator account itself. message SuperfluidIntermediaryAccount { + // Denom indicates the denom of the superfluid asset. string denom = 1; string val_addr = 2; // perpetual gauge for rewards distribution @@ -39,7 +45,7 @@ message SuperfluidIntermediaryAccount { // to be set as the Time-weighted-average-osmo-backing for the entire duration // of epoch N-1. (Thereby locking whats in use for epoch N as based on the prior // epochs rewards) However for now, this is not the TWAP but instead the spot -// price at the boundary. For different types of assets in the future, it could +// price at the boundary. For different types of assets in the future, it could // change. message OsmoEquivalentMultiplierRecord { int64 epoch_number = 1; @@ -52,8 +58,8 @@ message OsmoEquivalentMultiplierRecord { ]; } -// SuperfluidDelegationRecord takes the role of intermediary between LP token -// and OSMO tokens for superfluid staking +// SuperfluidDelegationRecord is a struct used to indicate superfluid +// delegations of an account in the state machine in a user friendly form. message SuperfluidDelegationRecord { string delegator_address = 1; string validator_address = 2; @@ -65,6 +71,9 @@ message SuperfluidDelegationRecord { [ (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin" ]; } +// LockIdIntermediaryAccountConnection is a struct used to indicate the +// relationship between the underlying lock id and superfluid delegation done +// via lp shares. message LockIdIntermediaryAccountConnection { uint64 lock_id = 1; string intermediary_account = 2; diff --git a/proto/osmosis/superfluid/tx.proto b/proto/osmosis/superfluid/tx.proto index 3ed1e4bb123..cf1b80f4a29 100644 --- a/proto/osmosis/superfluid/tx.proto +++ b/proto/osmosis/superfluid/tx.proto @@ -13,9 +13,11 @@ service Msg { // Execute superfluid delegation for a lockup rpc SuperfluidDelegate(MsgSuperfluidDelegate) returns (MsgSuperfluidDelegateResponse); + // Execute superfluid undelegation for a lockup rpc SuperfluidUndelegate(MsgSuperfluidUndelegate) returns (MsgSuperfluidUndelegateResponse); + // Execute superfluid redelegation for a lockup // rpc SuperfluidRedelegate(MsgSuperfluidRedelegate) returns // (MsgSuperfluidRedelegateResponse); @@ -28,6 +30,7 @@ service Msg { // Execute lockup lock and superfluid delegation in a single msg rpc LockAndSuperfluidDelegate(MsgLockAndSuperfluidDelegate) returns (MsgLockAndSuperfluidDelegateResponse); + rpc UnPoolWhitelistedPool(MsgUnPoolWhitelistedPool) returns (MsgUnPoolWhitelistedPoolResponse); } diff --git a/x/superfluid/keeper/hooks_test.go b/x/superfluid/keeper/hooks_test.go index 3924c2d0976..ecfc0ff370d 100644 --- a/x/superfluid/keeper/hooks_test.go +++ b/x/superfluid/keeper/hooks_test.go @@ -20,7 +20,7 @@ func (suite *KeeperTestSuite) TestSuperfluidAfterEpochEnd() { []superfluidDelegation{{0, 0, 0, 1000000}}, // bond denom staked in pool = 15_000_000 // with risk adjustment, the actual bond denom staked via superfluid would be 15_000_000 * (1 - 0.5) = 7_500_000 - // we do an arbitrary swap to set spot price, which adjusts superfluid staked equivilent base denom 20_000_000 * (1 - 0.5) = 10_000_000 during begin block + // we do an arbitrary swap to set spot price, which adjusts superfluid staked equivalent base denom 20_000_000 * (1 - 0.5) = 10_000_000 during begin block // delegation rewards are calculated using the equation (current period cumulative reward ratio - last period cumulative reward ratio) * asset amount // in this test case, the calculation for expected reward would be the following (0.99999 - 0) * 10_000_000 // thus we expect 999_990 stake as rewards @@ -31,9 +31,9 @@ func (suite *KeeperTestSuite) TestSuperfluidAfterEpochEnd() { []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, 2, []superfluidDelegation{{0, 0, 0, 1000000}, {1, 1, 0, 1000000}}, - // reward for the first block propser / lock 0 that has been superfluid staked would be equivilent to calculations done above + // reward for the first block propser / lock 0 that has been superfluid staked would be equivalent to calculations done above // 999_990 stake as rewards. - // reward for the second delegation is expected to be different. Amount superfluid staked would be equivilently 7_500_000 stake. + // reward for the second delegation is expected to be different. Amount superfluid staked would be equivalently 7_500_000 stake. // This would be the first block propsed by the second validator, current period cumulative reward ratio being 999_86.66684, // last period cumulative reward ratio being 0 // Thus as rewards, we expect 999986stake, calculted using the following equation: (999_86.66684 - 0) * 7_500_000 diff --git a/x/superfluid/keeper/msg_server.go b/x/superfluid/keeper/msg_server.go index 1b6e1f11a6e..63d64c53286 100644 --- a/x/superfluid/keeper/msg_server.go +++ b/x/superfluid/keeper/msg_server.go @@ -29,6 +29,19 @@ func NewMsgServerImpl(keeper *Keeper) types.MsgServer { var _ types.MsgServer = msgServer{} +// SuperfluidDelegate creates a delegation for the given lock ID and the validator to delegate to. +// This requires the lock to have locked tokens that have been already registered as a superfluid asset via governance. +// The pre-requisites for a lock to be able to be eligible for superfluid delegation are +// - assets in the lock should be a superfluid registered asset +// - lock should only have a single asset +// - lock should not be unlocking +// - lock should not have a different superfluid staking position +// - lock duration should be greater or equal to the staking.Unbonding time +// Note that the amount of delegation is not equal to the equivalent amount of osmo within the lock. +// Instead, we use the osmo equivalent multiplier stored in the latest epoch, calculate how much +// osmo equivalent is in lock, and use the risk adjusted osmo value. The minimum risk ratio works as a parameter +// to better incentivize and balance between superfluid staking and vanilla staking. +// Delegation does not happen directly from msg.Sender, but instead delegation is done via intermediary account. func (server msgServer) SuperfluidDelegate(goCtx context.Context, msg *types.MsgSuperfluidDelegate) (*types.MsgSuperfluidDelegateResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) @@ -43,6 +56,11 @@ func (server msgServer) SuperfluidDelegate(goCtx context.Context, msg *types.Msg return &types.MsgSuperfluidDelegateResponse{}, err } +// SuperfluidUndelegate undelegates currently superfluid delegated position. +// Old synthetic lock is deleted and a new synthetic lock is created to indicate the unbonding position. +// The actual staking position is instantly undelegated and the undelegated tokens are instantly sent from +// the intermediary account to the module account. +// Note that SuperfluidUndelegation does not start unbonding of the underlying lock iteslf. func (server msgServer) SuperfluidUndelegate(goCtx context.Context, msg *types.MsgSuperfluidUndelegate) (*types.MsgSuperfluidUndelegateResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) @@ -56,6 +74,8 @@ func (server msgServer) SuperfluidUndelegate(goCtx context.Context, msg *types.M return &types.MsgSuperfluidUndelegateResponse{}, err } +// SuperfluidRedelegate is a method to redelegate superfluid staked asset into a different validator. +// Currently this feature is not supported. // func (server msgServer) SuperfluidRedelegate(goCtx context.Context, msg *types.MsgSuperfluidRedelegate) (*types.MsgSuperfluidRedelegateResponse, error) { // ctx := sdk.UnwrapSDKContext(goCtx) @@ -63,6 +83,9 @@ func (server msgServer) SuperfluidUndelegate(goCtx context.Context, msg *types.M // return &types.MsgSuperfluidRedelegateResponse{}, err // } +// SuperfluidUnbondLock starts unbonding for currently superfluid undelegating lock. +// This method would return an error when the underlying lock is not in an superfluid undelegating state, +// or if the lock is not used in superfluid staking. func (server msgServer) SuperfluidUnbondLock(goCtx context.Context, msg *types.MsgSuperfluidUnbondLock) ( *types.MsgSuperfluidUnbondLockResponse, error, ) { @@ -78,6 +101,9 @@ func (server msgServer) SuperfluidUnbondLock(goCtx context.Context, msg *types.M return &types.MsgSuperfluidUnbondLockResponse{}, err } +// LockAndSuperfluidDelegate locks and superfluid delegates given tokens in a single message. +// This method consists of multiple messages, `LockTokens` from the lockup module msg server, and +// `SuperfluidDelegate` from the superfluid module msg server. func (server msgServer) LockAndSuperfluidDelegate(goCtx context.Context, msg *types.MsgLockAndSuperfluidDelegate) (*types.MsgLockAndSuperfluidDelegateResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) diff --git a/x/superfluid/keeper/stake.go b/x/superfluid/keeper/stake.go index a4ec1378f07..1cf129f9d29 100644 --- a/x/superfluid/keeper/stake.go +++ b/x/superfluid/keeper/stake.go @@ -11,6 +11,7 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) +// GetTotalSyntheticAssetsLocked returns the total amount of the given denom locked. func (k Keeper) GetTotalSyntheticAssetsLocked(ctx sdk.Context, denom string) sdk.Int { return k.lk.GetPeriodLocksAccumulation(ctx, lockuptypes.QueryCondition{ LockQueryType: lockuptypes.ByDuration, @@ -19,8 +20,11 @@ func (k Keeper) GetTotalSyntheticAssetsLocked(ctx sdk.Context, denom string) sdk }) } +// GetExpectedDelegationAmount returns the total number of osmo the intermediary account +// has delegated using the most recent osmo equivalent multiplier. +// This is labeled as expected because the way it calculates the amount can +// lead rounding errors from the true delegated amount. func (k Keeper) GetExpectedDelegationAmount(ctx sdk.Context, acc types.SuperfluidIntermediaryAccount) sdk.Int { - // Get total number of Osmo this account should have delegated after refresh // (1) Find how many tokens total T are locked for (denom, validator) pair totalSuperfluidDelegation := k.GetTotalSyntheticAssetsLocked(ctx, stakingSyntheticDenom(acc.Denom, acc.ValAddr)) // (2) Multiply the T tokens, by the number of superfluid osmo per token, to get the total amount @@ -29,8 +33,11 @@ func (k Keeper) GetExpectedDelegationAmount(ctx sdk.Context, acc types.Superflui return refreshedAmount } +// RefreshIntermediaryDelegationAmounts refreshes the amount of delegation for all intermediary accounts. +// This method includes minting new osmo if the refreshed delegation amount has increased, and +// instantly undelegating and burning if the refreshed delgation has decreased. func (k Keeper) RefreshIntermediaryDelegationAmounts(ctx sdk.Context) { - // iterate over every (denom, validator) pair + // iterate over all intermedairy accounts - every (denom, validator) pair accs := k.GetAllIntermediaryAccounts(ctx) for _, acc := range accs { mAddr := acc.GetAccAddress() @@ -54,7 +61,6 @@ func (k Keeper) RefreshIntermediaryDelegationAmounts(ctx sdk.Context) { k.Logger(ctx).Info(fmt.Sprintf("Existing delegation not found for %s with %s during superfluid refresh."+ " It may have been previously bonded, but now unbonded.", mAddr.String(), acc.ValAddr)) } else { - // TODO: Be consistent withn TokensFromShares vs ValidateFromUnbondAmount currentAmount = validator.TokensFromShares(delegation.Shares).RoundInt() } @@ -85,13 +91,16 @@ func (k Keeper) RefreshIntermediaryDelegationAmounts(ctx sdk.Context) { } } +// IncreaseSuperfluidDelegation increases the amount of existing superfluid delegation. +// This method would return an error if the lock has not been superfluid delegated before. func (k Keeper) IncreaseSuperfluidDelegation(ctx sdk.Context, lockID uint64, amount sdk.Coins) error { acc, found := k.GetIntermediaryAccountFromLockId(ctx, lockID) if !found { return nil } - // mint OSMO token based on TWAP of locked denom to denom module account + // mint OSMO token based on the most recent osmo equivalent multiplier + // of locked denom to denom module account osmoAmt := k.GetSuperfluidOSMOTokens(ctx, acc.Denom, amount.AmountOf(acc.Denom)) if osmoAmt.IsZero() { return nil @@ -105,7 +114,9 @@ func (k Keeper) IncreaseSuperfluidDelegation(ctx sdk.Context, lockID uint64, amo return nil } -// basic validation for locks, that sender is correct, and that the lock length is correct. +// basic validation for locks to be eligible for superfluid delegation. This includes checking +// - that the sender is the owner of the lock +// - that the lock is consisted of single coin func (k Keeper) validateLockForSF(ctx sdk.Context, lock *lockuptypes.PeriodLock, sender string) error { if lock.Owner != sender { return lockuptypes.ErrNotLockOwner @@ -116,6 +127,13 @@ func (k Keeper) validateLockForSF(ctx sdk.Context, lock *lockuptypes.PeriodLock, return nil } +// validateLockForSFDelegate runs the following sanity checks on the lock: +// - the sender is the owner of the lock +// - the lock is consisted of a single coin +// - the asset is registered as a superfluid asset via governance +// - the lock is not unlocking +// - lock duration is greater or equal to the unbonding time +// - lock should not be already superfluid staked func (k Keeper) validateLockForSFDelegate(ctx sdk.Context, lock *lockuptypes.PeriodLock, sender string) error { err := k.validateLockForSF(ctx, lock, sender) if err != nil { @@ -157,7 +175,13 @@ func (k Keeper) validateValAddrForDelegate(ctx sdk.Context, valAddr string) (sta return validator, nil } -// TODO: Merge a lot of logic with IncreaseSuperfluidDelegation. +// SuperfluidDelegate superfluid delegates osmo equivalent amount the given lock holds. +// The actual delegation is done by using/creating an intermediary account for the (denom, validator) pair +// and having the intermediary account delegate to the designated validator, not by the sender themselves. +// A state entry of IntermediaryAccountConnection is stored to store the connection between the lock ID +// and the intermediary account, as an intermediary account does not serve for delegations from a single delegator. +// The actual amount of delegation is not equal to the equivalent amount of osmo the lock has. That is, +// the actual amount of delegation is amount * osmo equivalent multiplier * (1 - k.RiskFactor(asset)). func (k Keeper) SuperfluidDelegate(ctx sdk.Context, sender string, lockID uint64, valAddr string) error { lock, err := k.lk.GetLockByID(ctx, lockID) if err != nil { @@ -199,6 +223,10 @@ func (k Keeper) SuperfluidDelegate(ctx sdk.Context, sender string, lockID uint64 return k.mintOsmoTokensAndDelegate(ctx, amount, acc) } +// SuperfluidUndelegate starts undelegating superfluid delegated position for the given lock. +// Undelegation is done instantly and the equivalent amount is sent to the module account +// where it is burnt instantly. Note that this method does not include unbonding the lock +// itself. func (k Keeper) SuperfluidUndelegate(ctx sdk.Context, sender string, lockID uint64) error { lock, err := k.lk.GetLockByID(ctx, lockID) if err != nil { @@ -235,6 +263,8 @@ func (k Keeper) SuperfluidUndelegate(ctx sdk.Context, sender string, lockID uint return k.createSyntheticLockup(ctx, lockID, intermediaryAcc, unlockingStatus) } +// SuperfluidUnbondLock unbonds the lock that has been used for superfluid staking. +// This method would return an error if the underlying lock is not superfluid undelegating. func (k Keeper) SuperfluidUnbondLock(ctx sdk.Context, underlyingLockId uint64, sender string) error { lock, err := k.lk.GetLockByID(ctx, underlyingLockId) if err != nil { @@ -254,6 +284,8 @@ func (k Keeper) SuperfluidUnbondLock(ctx sdk.Context, underlyingLockId uint64, s return k.lk.BeginForceUnlock(ctx, underlyingLockId, sdk.Coins{}) } +// alreadySuperfluidStaking returns true if underlying lock used in superfluid staking. +// This method would also return true for undelegating position for the lock. func (k Keeper) alreadySuperfluidStaking(ctx sdk.Context, lockID uint64) bool { // We need to catch two cases: // (1) lockID has another superfluid bond @@ -270,7 +302,7 @@ func (k Keeper) alreadySuperfluidStaking(ctx sdk.Context, lockID uint64) bool { return len(synthLocks) > 0 } -// mint osmoAmount of OSMO tokens, and immediately delegate them to validator on behalf of intermediary account. +// mintOsmoTokensAndDelegate mints osmoAmount of OSMO tokens, and immediately delegate them to validator on behalf of intermediary account. func (k Keeper) mintOsmoTokensAndDelegate(ctx sdk.Context, osmoAmount sdk.Int, intermediaryAccount types.SuperfluidIntermediaryAccount) error { validator, err := k.validateValAddrForDelegate(ctx, intermediaryAccount.ValAddr) if err != nil { @@ -301,7 +333,8 @@ func (k Keeper) mintOsmoTokensAndDelegate(ctx sdk.Context, osmoAmount sdk.Int, i return err } -// force undelegate osmoAmount worth of delegation shares from delegations between intermediary account and valAddr +// forceUndelegateAndBurnOsmoTokens force undelegates osmoAmount worth of delegation shares +// from delegations between intermediary account and valAddr. // We take the returned tokens, and then immediately burn them. func (k Keeper) forceUndelegateAndBurnOsmoTokens(ctx sdk.Context, osmoAmount sdk.Int, intermediaryAcc types.SuperfluidIntermediaryAccount, diff --git a/x/superfluid/types/genesis.pb.go b/x/superfluid/types/genesis.pb.go index db59dc07336..7d6ef126eeb 100644 --- a/x/superfluid/types/genesis.pb.go +++ b/x/superfluid/types/genesis.pb.go @@ -25,9 +25,15 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // GenesisState defines the module's genesis state. type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - SuperfluidAssets []SuperfluidAsset `protobuf:"bytes,2,rep,name=superfluid_assets,json=superfluidAssets,proto3" json:"superfluid_assets"` - OsmoEquivalentMultipliers []OsmoEquivalentMultiplierRecord `protobuf:"bytes,3,rep,name=osmo_equivalent_multipliers,json=osmoEquivalentMultipliers,proto3" json:"osmo_equivalent_multipliers"` + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + // superfluid_assets defines the registered superfluid assets that have been + // registered via governance. + SuperfluidAssets []SuperfluidAsset `protobuf:"bytes,2,rep,name=superfluid_assets,json=superfluidAssets,proto3" json:"superfluid_assets"` + // osmo_equivalent_multipliers is the records of osmo equivilent amount of + // each superfluid registered pool, updated every epoch. + OsmoEquivalentMultipliers []OsmoEquivalentMultiplierRecord `protobuf:"bytes,3,rep,name=osmo_equivalent_multipliers,json=osmoEquivalentMultipliers,proto3" json:"osmo_equivalent_multipliers"` + // intermediary_accounts is a secondary account for superfluid staking that + // plays an intermediary role between validators and the delegators. IntermediaryAccounts []SuperfluidIntermediaryAccount `protobuf:"bytes,4,rep,name=intermediary_accounts,json=intermediaryAccounts,proto3" json:"intermediary_accounts"` IntemediaryAccountConnections []LockIdIntermediaryAccountConnection `protobuf:"bytes,5,rep,name=intemediary_account_connections,json=intemediaryAccountConnections,proto3" json:"intemediary_account_connections"` } diff --git a/x/superfluid/types/params.pb.go b/x/superfluid/types/params.pb.go index d76a02515f0..c91590dd628 100644 --- a/x/superfluid/types/params.pb.go +++ b/x/superfluid/types/params.pb.go @@ -27,8 +27,9 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Params holds parameters for the superfluid module type Params struct { - // the risk_factor is to be cut on OSMO equivalent value of lp tokens for - // superfluid staking, default: 5% + // minimum_risk_factor is to be cut on OSMO equivalent value of lp tokens for + // superfluid staking, default: 5%. The minimum risk facotr works as a + // parameter to better incentive vanilla staking. MinimumRiskFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=minimum_risk_factor,json=minimumRiskFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"minimum_risk_factor" yaml:"minimum_risk_factor"` } diff --git a/x/superfluid/types/query.pb.go b/x/superfluid/types/query.pb.go index db7120f64d1..197451f98ac 100644 --- a/x/superfluid/types/query.pb.go +++ b/x/superfluid/types/query.pb.go @@ -1505,26 +1505,28 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { - // Params returns the total set of minting parameters. + // Params returns the total set of superfluid parameters. Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Returns superfluid asset type + // Returns superfluid asset type, whether if it's a native asset or an lp + // share. AssetType(ctx context.Context, in *AssetTypeRequest, opts ...grpc.CallOption) (*AssetTypeResponse, error) - // Returns all superfluid asset types + // Returns all registered superfluid assets. AllAssets(ctx context.Context, in *AllAssetsRequest, opts ...grpc.CallOption) (*AllAssetsResponse, error) - // Returns superfluid asset Multiplier + // Returns the osmo equivalent multiplier used in the most recent epoch. AssetMultiplier(ctx context.Context, in *AssetMultiplierRequest, opts ...grpc.CallOption) (*AssetMultiplierResponse, error) - // Returns all superfluid intermediary account + // Returns all superfluid intermediary accounts. AllIntermediaryAccounts(ctx context.Context, in *AllIntermediaryAccountsRequest, opts ...grpc.CallOption) (*AllIntermediaryAccountsResponse, error) // Returns intermediary account connected to a superfluid staked lock by id ConnectedIntermediaryAccount(ctx context.Context, in *ConnectedIntermediaryAccountRequest, opts ...grpc.CallOption) (*ConnectedIntermediaryAccountResponse, error) - // Returns the total amount of osmo superfluidly staked - // response denominated in uosmo + // Returns the total amount of osmo superfluidly staked. + // Response is denominated in uosmo. TotalSuperfluidDelegations(ctx context.Context, in *TotalSuperfluidDelegationsRequest, opts ...grpc.CallOption) (*TotalSuperfluidDelegationsResponse, error) - // Returns the coins superfluid delegated for a delegator, validator, denom + // Returns the coins superfluid delegated for the delegator, validator, denom // triplet SuperfluidDelegationAmount(ctx context.Context, in *SuperfluidDelegationAmountRequest, opts ...grpc.CallOption) (*SuperfluidDelegationAmountResponse, error) - // Returns all the superfluid poistions for a specific delegator + // Returns all the delegated superfluid poistions for a specific delegator. SuperfluidDelegationsByDelegator(ctx context.Context, in *SuperfluidDelegationsByDelegatorRequest, opts ...grpc.CallOption) (*SuperfluidDelegationsByDelegatorResponse, error) + // Returns all the undelegating superfluid poistions for a specific delegator. SuperfluidUndelegationsByDelegator(ctx context.Context, in *SuperfluidUndelegationsByDelegatorRequest, opts ...grpc.CallOption) (*SuperfluidUndelegationsByDelegatorResponse, error) // Returns all the superfluid positions of a specific denom delegated to one // validator @@ -1664,26 +1666,28 @@ func (c *queryClient) TotalDelegationByDelegator(ctx context.Context, in *QueryT // QueryServer is the server API for Query service. type QueryServer interface { - // Params returns the total set of minting parameters. + // Params returns the total set of superfluid parameters. Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Returns superfluid asset type + // Returns superfluid asset type, whether if it's a native asset or an lp + // share. AssetType(context.Context, *AssetTypeRequest) (*AssetTypeResponse, error) - // Returns all superfluid asset types + // Returns all registered superfluid assets. AllAssets(context.Context, *AllAssetsRequest) (*AllAssetsResponse, error) - // Returns superfluid asset Multiplier + // Returns the osmo equivalent multiplier used in the most recent epoch. AssetMultiplier(context.Context, *AssetMultiplierRequest) (*AssetMultiplierResponse, error) - // Returns all superfluid intermediary account + // Returns all superfluid intermediary accounts. AllIntermediaryAccounts(context.Context, *AllIntermediaryAccountsRequest) (*AllIntermediaryAccountsResponse, error) // Returns intermediary account connected to a superfluid staked lock by id ConnectedIntermediaryAccount(context.Context, *ConnectedIntermediaryAccountRequest) (*ConnectedIntermediaryAccountResponse, error) - // Returns the total amount of osmo superfluidly staked - // response denominated in uosmo + // Returns the total amount of osmo superfluidly staked. + // Response is denominated in uosmo. TotalSuperfluidDelegations(context.Context, *TotalSuperfluidDelegationsRequest) (*TotalSuperfluidDelegationsResponse, error) - // Returns the coins superfluid delegated for a delegator, validator, denom + // Returns the coins superfluid delegated for the delegator, validator, denom // triplet SuperfluidDelegationAmount(context.Context, *SuperfluidDelegationAmountRequest) (*SuperfluidDelegationAmountResponse, error) - // Returns all the superfluid poistions for a specific delegator + // Returns all the delegated superfluid poistions for a specific delegator. SuperfluidDelegationsByDelegator(context.Context, *SuperfluidDelegationsByDelegatorRequest) (*SuperfluidDelegationsByDelegatorResponse, error) + // Returns all the undelegating superfluid poistions for a specific delegator. SuperfluidUndelegationsByDelegator(context.Context, *SuperfluidUndelegationsByDelegatorRequest) (*SuperfluidUndelegationsByDelegatorResponse, error) // Returns all the superfluid positions of a specific denom delegated to one // validator diff --git a/x/superfluid/types/superfluid.pb.go b/x/superfluid/types/superfluid.pb.go index 284cd8b2c21..3e2afc2e9cf 100644 --- a/x/superfluid/types/superfluid.pb.go +++ b/x/superfluid/types/superfluid.pb.go @@ -26,6 +26,8 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// SuperfluidAssetType indicates whether the superfluid asset is +// a native token itself or the lp share of a pool. type SuperfluidAssetType int32 const ( @@ -53,7 +55,9 @@ func (SuperfluidAssetType) EnumDescriptor() ([]byte, []int) { // SuperfluidAsset stores the pair of superfluid asset type and denom pair type SuperfluidAsset struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` + Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` + // AssetType indicates whether the superfluid asset is a native token or an lp + // share AssetType SuperfluidAssetType `protobuf:"varint,2,opt,name=asset_type,json=assetType,proto3,enum=osmosis.superfluid.SuperfluidAssetType" json:"asset_type,omitempty"` } @@ -91,8 +95,10 @@ func (m *SuperfluidAsset) XXX_DiscardUnknown() { var xxx_messageInfo_SuperfluidAsset proto.InternalMessageInfo // SuperfluidIntermediaryAccount takes the role of intermediary between LP token -// and OSMO tokens for superfluid staking +// and OSMO tokens for superfluid staking. The intermediary account is the +// actual account responsible for delegation, not the validator account itself. type SuperfluidIntermediaryAccount struct { + // Denom indicates the denom of the superfluid asset. Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` ValAddr string `protobuf:"bytes,2,opt,name=val_addr,json=valAddr,proto3" json:"val_addr,omitempty"` // perpetual gauge for rewards distribution @@ -158,7 +164,7 @@ func (m *SuperfluidIntermediaryAccount) GetGaugeId() uint64 { // to be set as the Time-weighted-average-osmo-backing for the entire duration // of epoch N-1. (Thereby locking whats in use for epoch N as based on the prior // epochs rewards) However for now, this is not the TWAP but instead the spot -// price at the boundary. For different types of assets in the future, it could +// price at the boundary. For different types of assets in the future, it could // change. type OsmoEquivalentMultiplierRecord struct { EpochNumber int64 `protobuf:"varint,1,opt,name=epoch_number,json=epochNumber,proto3" json:"epoch_number,omitempty"` @@ -214,8 +220,8 @@ func (m *OsmoEquivalentMultiplierRecord) GetDenom() string { return "" } -// SuperfluidDelegationRecord takes the role of intermediary between LP token -// and OSMO tokens for superfluid staking +// SuperfluidDelegationRecord is a struct used to indicate superfluid +// delegations of an account in the state machine in a user friendly form. type SuperfluidDelegationRecord struct { DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty"` ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` @@ -284,6 +290,9 @@ func (m *SuperfluidDelegationRecord) GetEquivalentStakedAmount() *types.Coin { return nil } +// LockIdIntermediaryAccountConnection is a struct used to indicate the +// relationship between the underlying lock id and superfluid delegation done +// via lp shares. type LockIdIntermediaryAccountConnection struct { LockId uint64 `protobuf:"varint,1,opt,name=lock_id,json=lockId,proto3" json:"lock_id,omitempty"` IntermediaryAccount string `protobuf:"bytes,2,opt,name=intermediary_account,json=intermediaryAccount,proto3" json:"intermediary_account,omitempty"` From b634d26391cc115b89d0abd5ae1f7ba4f5fbca78 Mon Sep 17 00:00:00 2001 From: Richard Liu Date: Wed, 13 Jul 2022 07:27:23 -0400 Subject: [PATCH 063/376] x/incentives: Simplify gauge tests in module (#1932) * coalesce perpetual and non-perpetual into one test * coalesce denom test in TestGaugeOperations * remove unnecessary redefinition * pr comments * Update x/incentives/keeper/gauge_test.go Co-authored-by: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> * Update x/incentives/keeper/gauge_test.go Co-authored-by: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> * Update x/incentives/keeper/gauge_test.go Co-authored-by: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> * pr comments * finish pr comments * remove %8.8s format specifier in setupAddr * move denom checks to end of each block * add documentation for tdd Co-authored-by: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> --- x/incentives/keeper/gauge_test.go | 382 ++++++++++++------------------ x/incentives/keeper/suite_test.go | 2 - 2 files changed, 153 insertions(+), 231 deletions(-) diff --git a/x/incentives/keeper/gauge_test.go b/x/incentives/keeper/gauge_test.go index 825b78cecee..653202ad142 100644 --- a/x/incentives/keeper/gauge_test.go +++ b/x/incentives/keeper/gauge_test.go @@ -49,233 +49,88 @@ func (suite *KeeperTestSuite) TestNonExistentDenomGaugeCreation() { suite.Require().NoError(err) } -// TestNonPerpetualGaugeOperations tests non perpetual gauge distribution logic. -func (suite *KeeperTestSuite) TestNonPerpetualGaugeOperations() { - // test for module get gauges - suite.SetupTest() - - // initial module gauges check - gauges := suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) - suite.Require().Len(gauges, 0) - - lockOwners := suite.SetupManyLocks(5, defaultLiquidTokens, defaultLPTokens, time.Second) - gaugeID, _, coins, startTime := suite.SetupNewGauge(false, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - // evenly distributed per lock - expectedCoinsPerLock := sdk.Coins{sdk.NewInt64Coin("stake", 2)} - - // check gauges - gauges = suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) - suite.Require().Len(gauges, 1) - suite.Require().Equal(gauges[0].Id, gaugeID) - suite.Require().Equal(gauges[0].Coins, coins) - suite.Require().Equal(gauges[0].NumEpochsPaidOver, uint64(2)) - suite.Require().Equal(gauges[0].FilledEpochs, uint64(0)) - suite.Require().Equal(gauges[0].DistributedCoins, sdk.Coins(nil)) - suite.Require().Equal(gauges[0].StartTime.Unix(), startTime.Unix()) - - // check rewards estimation - rewardsEst := suite.App.IncentivesKeeper.GetRewardsEst(suite.Ctx, lockOwners[0], []lockuptypes.PeriodLock{}, 100) - suite.Require().Equal(expectedCoinsPerLock.String(), rewardsEst.String()) - - // add to gauge - addCoins := sdk.Coins{sdk.NewInt64Coin("stake", 200)} - suite.AddToGauge(addCoins, gaugeID) - - // check gauges - gauges = suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) - suite.Require().Len(gauges, 1) - expectedGauge := types.Gauge{ - Id: gaugeID, - IsPerpetual: false, - DistributeTo: lockuptypes.QueryCondition{ - LockQueryType: lockuptypes.ByDuration, - Denom: "lptoken", - Duration: time.Second, +// TestGaugeOperations tests perpetual and non-perpetual gauge distribution logic using the gauges by denom keeper. +func (suite *KeeperTestSuite) TestGaugeOperations() { + testCases := []struct { + isPerpetual bool + numLocks int + }{ + { + isPerpetual: true, + numLocks: 1, }, - Coins: coins.Add(addCoins...), - NumEpochsPaidOver: 2, - FilledEpochs: 0, - DistributedCoins: sdk.Coins{}, - StartTime: startTime, - } - suite.Require().Equal(gauges[0].String(), expectedGauge.String()) - - // check upcoming gauges - gauges = suite.App.IncentivesKeeper.GetUpcomingGauges(suite.Ctx) - suite.Require().Len(gauges, 1) - - // start distribution - suite.Ctx = suite.Ctx.WithBlockTime(startTime) - gauge, err := suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) - suite.Require().NoError(err) - err = suite.App.IncentivesKeeper.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) - suite.Require().NoError(err) - - // check upcoming gauges - gauges = suite.App.IncentivesKeeper.GetUpcomingGauges(suite.Ctx) - suite.Require().Len(gauges, 0) - - // distribute coins to stakers - distrCoins, err := suite.App.IncentivesKeeper.Distribute(suite.Ctx, []types.Gauge{*gauge}) - suite.Require().NoError(err) - suite.Require().Equal(distrCoins, sdk.Coins{sdk.NewInt64Coin("stake", 105)}) - - // check active gauges - gauges = suite.App.IncentivesKeeper.GetActiveGauges(suite.Ctx) - suite.Require().Len(gauges, 1) - - // check gauge ids by denom - gaugeIds := suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") - suite.Require().Len(gaugeIds, 1) - - // finish distribution - err = suite.App.IncentivesKeeper.MoveActiveGaugeToFinishedGauge(suite.Ctx, *gauge) - suite.Require().NoError(err) - - // check finished gauges - gauges = suite.App.IncentivesKeeper.GetFinishedGauges(suite.Ctx) - suite.Require().Len(gauges, 1) - - // check gauge by ID - gauge, err = suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) - suite.Require().NoError(err) - suite.Require().NotNil(gauge) - suite.Require().Equal(*gauge, gauges[0]) - - // check invalid gauge ID - _, err = suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID+1000) - suite.Require().Error(err) - - rewardsEst = suite.App.IncentivesKeeper.GetRewardsEst(suite.Ctx, lockOwners[0], []lockuptypes.PeriodLock{}, 100) - suite.Require().Equal(sdk.Coins{}, rewardsEst) -} - -// TestPerpetualGaugeOperations tests perpetual gauge distribution logic. -func (suite *KeeperTestSuite) TestPerpetualGaugeOperations() { - // test for module get gauges - suite.SetupTest() - - // initial module gauges check - gauges := suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) - suite.Require().Len(gauges, 0) - - // setup lock and gauge - lockOwner, gaugeID, coins, startTime := suite.SetupLockAndGauge(true) - - // check gauges - gauges = suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) - suite.Require().Len(gauges, 1) - expectedGauge := types.Gauge{ - Id: gaugeID, - IsPerpetual: true, - DistributeTo: lockuptypes.QueryCondition{ - LockQueryType: lockuptypes.ByDuration, - Denom: "lptoken", - Duration: time.Second, + { + isPerpetual: false, + numLocks: 1, }, - Coins: coins, - NumEpochsPaidOver: 1, - FilledEpochs: 0, - DistributedCoins: sdk.Coins{}, - StartTime: startTime, - } - suite.Require().Equal(gauges[0].String(), expectedGauge.String()) - - // check rewards estimation - rewardsEst := suite.App.IncentivesKeeper.GetRewardsEst(suite.Ctx, lockOwner, []lockuptypes.PeriodLock{}, 100) - suite.Require().Equal(coins.String(), rewardsEst.String()) - - // check gauges - gauges = suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) - suite.Require().Len(gauges, 1) - expectedGauge = types.Gauge{ - Id: gaugeID, - IsPerpetual: true, - DistributeTo: lockuptypes.QueryCondition{ - LockQueryType: lockuptypes.ByDuration, - Denom: "lptoken", - Duration: time.Second, + { + isPerpetual: true, + numLocks: 2, + }, + { + isPerpetual: false, + numLocks: 2, }, - Coins: coins, - NumEpochsPaidOver: 1, - FilledEpochs: 0, - DistributedCoins: sdk.Coins{}, - StartTime: startTime, } - suite.Require().Equal(gauges[0].String(), expectedGauge.String()) - - // check upcoming gauges - gauges = suite.App.IncentivesKeeper.GetUpcomingGauges(suite.Ctx) - suite.Require().Len(gauges, 1) - - // start distribution - suite.Ctx = suite.Ctx.WithBlockTime(startTime) - gauge, err := suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) - suite.Require().NoError(err) - err = suite.App.IncentivesKeeper.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) - suite.Require().NoError(err) - - // check upcoming gauges - gauges = suite.App.IncentivesKeeper.GetUpcomingGauges(suite.Ctx) - suite.Require().Len(gauges, 0) - - // distribute coins to stakers, since it's perpetual distribute everything on single distribution - distrCoins, err := suite.App.IncentivesKeeper.Distribute(suite.Ctx, []types.Gauge{*gauge}) - suite.Require().NoError(err) - suite.Require().Equal(distrCoins, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - - // distributing twice without adding more for perpetual gauge - gauge, err = suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) - suite.Require().NoError(err) - distrCoins, err = suite.App.IncentivesKeeper.Distribute(suite.Ctx, []types.Gauge{*gauge}) - suite.Require().NoError(err) - suite.Require().True(distrCoins.Empty()) - - // add to gauge - addCoins := sdk.Coins{sdk.NewInt64Coin("stake", 200)} - suite.AddToGauge(addCoins, gaugeID) - - // distributing twice with adding more for perpetual gauge - gauge, err = suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) - suite.Require().NoError(err) - distrCoins, err = suite.App.IncentivesKeeper.Distribute(suite.Ctx, []types.Gauge{*gauge}) - suite.Require().NoError(err) - suite.Require().Equal(distrCoins, sdk.Coins{sdk.NewInt64Coin("stake", 200)}) - - // check active gauges - gauges = suite.App.IncentivesKeeper.GetActiveGauges(suite.Ctx) - suite.Require().Len(gauges, 1) - - // check gauge ids by denom - gaugeIds := suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") - suite.Require().Len(gaugeIds, 1) - - // check finished gauges - gauges = suite.App.IncentivesKeeper.GetFinishedGauges(suite.Ctx) - suite.Require().Len(gauges, 0) - - // check rewards estimation - rewardsEst = suite.App.IncentivesKeeper.GetRewardsEst(suite.Ctx, lockOwner, []lockuptypes.PeriodLock{}, 100) - suite.Require().Equal(sdk.Coins(nil), rewardsEst) -} - -// TestGaugesByDenom tests gauge distribution using the gauges by denom keeper. -func (suite *KeeperTestSuite) TestGaugesByDenom() { - testGaugeByDenom := func(isPerpetual bool) { + for _, tc := range testCases { // test for module get gauges suite.SetupTest() // initial module gauges check - gaugeIds := suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") - suite.Require().Len(gaugeIds, 0) + gauges := suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) + suite.Require().Len(gauges, 0) + gaugeIdsByDenom := suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") + suite.Require().Len(gaugeIdsByDenom, 0) // setup lock and gauge - _, gaugeID, _, startTime := suite.SetupLockAndGauge(isPerpetual) + lockOwners := suite.SetupManyLocks(tc.numLocks, defaultLiquidTokens, defaultLPTokens, time.Second) + gaugeID, _, coins, startTime := suite.SetupNewGauge(tc.isPerpetual, sdk.Coins{sdk.NewInt64Coin("stake", 12)}) + // evenly distributed per lock + expectedCoinsPerLock := sdk.Coins{sdk.NewInt64Coin("stake", 12/int64(tc.numLocks))} + // set expected epochs + var expectedNumEpochsPaidOver int + if tc.isPerpetual { + expectedNumEpochsPaidOver = 1 + } else { + expectedNumEpochsPaidOver = 2 + } // check gauges - gaugeIds = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") - suite.Require().Len(gaugeIds, 1, "perpetual %b", isPerpetual) - suite.Require().Equal(gaugeIds[0], gaugeID) + gauges = suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) + suite.Require().Len(gauges, 1) + expectedGauge := types.Gauge{ + Id: gaugeID, + IsPerpetual: tc.isPerpetual, + DistributeTo: lockuptypes.QueryCondition{ + LockQueryType: lockuptypes.ByDuration, + Denom: "lptoken", + Duration: time.Second, + }, + Coins: coins, + NumEpochsPaidOver: uint64(expectedNumEpochsPaidOver), + FilledEpochs: 0, + DistributedCoins: sdk.Coins{}, + StartTime: startTime, + } + suite.Require().Equal(expectedGauge.String(), gauges[0].String()) + + // check gauge ids by denom + gaugeIdsByDenom = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") + suite.Require().Len(gaugeIdsByDenom, 1) + suite.Require().Equal(gaugeID, gaugeIdsByDenom[0]) + + // check rewards estimation + rewardsEst := suite.App.IncentivesKeeper.GetRewardsEst(suite.Ctx, lockOwners[0], []lockuptypes.PeriodLock{}, 100) + suite.Require().Equal(expectedCoinsPerLock.String(), rewardsEst.String()) + + // check gauges + gauges = suite.App.IncentivesKeeper.GetNotFinishedGauges(suite.Ctx) + suite.Require().Len(gauges, 1) + suite.Require().Equal(expectedGauge.String(), gauges[0].String()) + + // check upcoming gauges + gauges = suite.App.IncentivesKeeper.GetUpcomingGauges(suite.Ctx) + suite.Require().Len(gauges, 1) // start distribution suite.Ctx = suite.Ctx.WithBlockTime(startTime) @@ -284,33 +139,102 @@ func (suite *KeeperTestSuite) TestGaugesByDenom() { err = suite.App.IncentivesKeeper.MoveUpcomingGaugeToActiveGauge(suite.Ctx, *gauge) suite.Require().NoError(err) + // check active gauges + gauges = suite.App.IncentivesKeeper.GetActiveGauges(suite.Ctx) + suite.Require().Len(gauges, 1) + + // check upcoming gauges + gauges = suite.App.IncentivesKeeper.GetUpcomingGauges(suite.Ctx) + suite.Require().Len(gauges, 0) + // check gauge ids by denom - gaugeIds = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") - suite.Require().Len(gaugeIds, 1) + gaugeIdsByDenom = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") + suite.Require().Len(gaugeIdsByDenom, 1) // check gauge ids by other denom - gaugeIds = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lpt") - suite.Require().Len(gaugeIds, 0) + gaugeIdsByDenom = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lpt") + suite.Require().Len(gaugeIdsByDenom, 0) // distribute coins to stakers - _, err = suite.App.IncentivesKeeper.Distribute(suite.Ctx, []types.Gauge{*gauge}) + distrCoins, err := suite.App.IncentivesKeeper.Distribute(suite.Ctx, []types.Gauge{*gauge}) suite.Require().NoError(err) + // We hardcoded 12 "stake" tokens when initializing gauge + suite.Require().Equal(sdk.Coins{sdk.NewInt64Coin("stake", int64(12/expectedNumEpochsPaidOver))}, distrCoins) + + if tc.isPerpetual { + // distributing twice without adding more for perpetual gauge + gauge, err = suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) + suite.Require().NoError(err) + distrCoins, err = suite.App.IncentivesKeeper.Distribute(suite.Ctx, []types.Gauge{*gauge}) + suite.Require().NoError(err) + suite.Require().True(distrCoins.Empty()) + + // add to gauge + addCoins := sdk.Coins{sdk.NewInt64Coin("stake", 200)} + suite.AddToGauge(addCoins, gaugeID) + + // distributing twice with adding more for perpetual gauge + gauge, err = suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) + suite.Require().NoError(err) + distrCoins, err = suite.App.IncentivesKeeper.Distribute(suite.Ctx, []types.Gauge{*gauge}) + suite.Require().NoError(err) + suite.Require().Equal(sdk.Coins{sdk.NewInt64Coin("stake", 200)}, distrCoins) + } else { + // add to gauge + addCoins := sdk.Coins{sdk.NewInt64Coin("stake", 200)} + suite.AddToGauge(addCoins, gaugeID) + } + + // check active gauges + gauges = suite.App.IncentivesKeeper.GetActiveGauges(suite.Ctx) + suite.Require().Len(gauges, 1) + + // check gauge ids by denom + gaugeIdsByDenom = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") + suite.Require().Len(gaugeIdsByDenom, 1) // finish distribution for non perpetual gauge - if !gauge.IsPerpetual { + if !tc.isPerpetual { err = suite.App.IncentivesKeeper.MoveActiveGaugeToFinishedGauge(suite.Ctx, *gauge) suite.Require().NoError(err) } - expectedNumGauges := 1 - if !isPerpetual { - expectedNumGauges = 0 + // check non-perpetual gauges (finished + rewards estimate empty) + if !tc.isPerpetual { + + // check finished gauges + gauges = suite.App.IncentivesKeeper.GetFinishedGauges(suite.Ctx) + suite.Require().Len(gauges, 1) + + // check gauge by ID + gauge, err = suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID) + suite.Require().NoError(err) + suite.Require().NotNil(gauge) + suite.Require().Equal(gauges[0], *gauge) + + // check invalid gauge ID + _, err = suite.App.IncentivesKeeper.GetGaugeByID(suite.Ctx, gaugeID+1000) + suite.Require().Error(err) + rewardsEst = suite.App.IncentivesKeeper.GetRewardsEst(suite.Ctx, lockOwners[0], []lockuptypes.PeriodLock{}, 100) + suite.Require().Equal(sdk.Coins{}, rewardsEst) + + // check gauge ids by denom + gaugeIdsByDenom = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") + suite.Require().Len(gaugeIdsByDenom, 0) + } else { // check perpetual gauges (not finished + rewards estimate empty) + + // check finished gauges + gauges = suite.App.IncentivesKeeper.GetFinishedGauges(suite.Ctx) + suite.Require().Len(gauges, 0) + + // check rewards estimation + rewardsEst = suite.App.IncentivesKeeper.GetRewardsEst(suite.Ctx, lockOwners[0], []lockuptypes.PeriodLock{}, 100) + suite.Require().Equal(sdk.Coins(nil), rewardsEst) + + // check gauge ids by denom + gaugeIdsByDenom = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") + suite.Require().Len(gaugeIdsByDenom, 1) } - // check gauge ids by denom - gaugeIds = suite.App.IncentivesKeeper.GetAllGaugeIDsByDenom(suite.Ctx, "lptoken") - suite.Require().Len(gaugeIds, expectedNumGauges) } - testGaugeByDenom(true) - testGaugeByDenom(false) } diff --git a/x/incentives/keeper/suite_test.go b/x/incentives/keeper/suite_test.go index 19c56893e75..5d71fd2a61c 100644 --- a/x/incentives/keeper/suite_test.go +++ b/x/incentives/keeper/suite_test.go @@ -57,8 +57,6 @@ func (suite *KeeperTestSuite) setupAddr(addrNum int, prefix string, balance sdk. prefixBz := make([]byte, 8) _, _ = rand.Read(prefixBz) prefix = string(prefixBz) - } else { - prefix = fmt.Sprintf("%8.8s", prefix) } addr := sdk.AccAddress([]byte(fmt.Sprintf("addr%s%8d", prefix, addrNum))) From 79e5708526c82819cb82a2de2802732c563f3fdb Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Wed, 13 Jul 2022 07:14:21 -0700 Subject: [PATCH 064/376] Add basic test for IsActive (#2050) * add basic isactive test * add comments and remove redundant case * remove unnecessary boilerplate --- x/gamm/pool-models/balancer/pool_test.go | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go index 1bafc576d39..c7d6ad8ae6c 100644 --- a/x/gamm/pool-models/balancer/pool_test.go +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -1225,3 +1225,29 @@ func TestBalancerPoolPokeTokenWeights(t *testing.T) { require.Nil(t, pacc.PoolParams.SmoothWeightChangeParams) } } + +// This test (currently trivially) checks to make sure that `IsActive` returns true for balancer pools. +// This is mainly to make sure that if IsActive is ever used as an emergency switch, it is not accidentally left off for any (or all) pools. +// TODO: create a test with mocks to make sure IsActive works as intended when flipped for specific pools/all pools +func (suite *BalancerTestSuite) TestIsActive(t *testing.T) { + tests := map[string]struct { + expectedIsActive bool + }{ + "IsActive is true": { + expectedIsActive: true, + }, + } + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + ctx := suite.CreateTestContext() + + // Initialize a pool + pool, err := balancer.NewBalancerPool(defaultPoolId, defaultBalancerPoolParams, dummyPoolAssets, defaultFutureGovernor, defaultCurBlockTime) + require.NoError(t, err, "test %v", name) + + isActive := pool.IsActive(ctx) + require.Equal(t, tc.expectedIsActive, isActive) + }) + } +} From 50d9348d9cb2b2c8445020f9447c1d655033297d Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Wed, 13 Jul 2022 23:28:50 +0900 Subject: [PATCH 065/376] Fix typos (#2048) --- proto/osmosis/superfluid/genesis.proto | 2 +- proto/osmosis/superfluid/params.proto | 5 +++-- x/superfluid/types/genesis.pb.go | 2 +- x/superfluid/types/params.pb.go | 5 +++-- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/proto/osmosis/superfluid/genesis.proto b/proto/osmosis/superfluid/genesis.proto index af6d7e08fef..346a753afa3 100644 --- a/proto/osmosis/superfluid/genesis.proto +++ b/proto/osmosis/superfluid/genesis.proto @@ -14,7 +14,7 @@ message GenesisState { // registered via governance. repeated SuperfluidAsset superfluid_assets = 2 [ (gogoproto.nullable) = false ]; - // osmo_equivalent_multipliers is the records of osmo equivilent amount of + // osmo_equivalent_multipliers is the records of osmo equivalent amount of // each superfluid registered pool, updated every epoch. repeated OsmoEquivalentMultiplierRecord osmo_equivalent_multipliers = 3 [ (gogoproto.nullable) = false ]; diff --git a/proto/osmosis/superfluid/params.proto b/proto/osmosis/superfluid/params.proto index 630ef80864f..c102db5cbe6 100644 --- a/proto/osmosis/superfluid/params.proto +++ b/proto/osmosis/superfluid/params.proto @@ -9,8 +9,9 @@ option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; // Params holds parameters for the superfluid module message Params { // minimum_risk_factor is to be cut on OSMO equivalent value of lp tokens for - // superfluid staking, default: 5%. The minimum risk facotr works as a - // parameter to better incentive vanilla staking. + // superfluid staking, default: 5%. The minimum risk factor works + // to counter-balance the staked amount on chain's exposure to various asset + // volatilities, and have base staking be 'resistant' to volatility. string minimum_risk_factor = 1 [ (gogoproto.moretags) = "yaml:\"minimum_risk_factor\"", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", diff --git a/x/superfluid/types/genesis.pb.go b/x/superfluid/types/genesis.pb.go index 7d6ef126eeb..adbf10eed44 100644 --- a/x/superfluid/types/genesis.pb.go +++ b/x/superfluid/types/genesis.pb.go @@ -29,7 +29,7 @@ type GenesisState struct { // superfluid_assets defines the registered superfluid assets that have been // registered via governance. SuperfluidAssets []SuperfluidAsset `protobuf:"bytes,2,rep,name=superfluid_assets,json=superfluidAssets,proto3" json:"superfluid_assets"` - // osmo_equivalent_multipliers is the records of osmo equivilent amount of + // osmo_equivalent_multipliers is the records of osmo equivalent amount of // each superfluid registered pool, updated every epoch. OsmoEquivalentMultipliers []OsmoEquivalentMultiplierRecord `protobuf:"bytes,3,rep,name=osmo_equivalent_multipliers,json=osmoEquivalentMultipliers,proto3" json:"osmo_equivalent_multipliers"` // intermediary_accounts is a secondary account for superfluid staking that diff --git a/x/superfluid/types/params.pb.go b/x/superfluid/types/params.pb.go index c91590dd628..3ae9297731b 100644 --- a/x/superfluid/types/params.pb.go +++ b/x/superfluid/types/params.pb.go @@ -28,8 +28,9 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Params holds parameters for the superfluid module type Params struct { // minimum_risk_factor is to be cut on OSMO equivalent value of lp tokens for - // superfluid staking, default: 5%. The minimum risk facotr works as a - // parameter to better incentive vanilla staking. + // superfluid staking, default: 5%. The minimum risk factor works + // to counter-balance the staked amount on chain's exposure to various asset + // volatilities, and have base staking be 'resistant' to volatility. MinimumRiskFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=minimum_risk_factor,json=minimumRiskFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"minimum_risk_factor" yaml:"minimum_risk_factor"` } From bc8541067a152d26dfa76bc855e2088f6090936c Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Wed, 13 Jul 2022 08:03:07 -0700 Subject: [PATCH 066/376] Add test standards and test templates to CONTRIBUTING.md (#1977) * formatting and nit * add writing tests section with examples and templates * markdown linter * add verbosity rule of thumb Co-authored-by: Roman * add example for previous commit Co-authored-by: Roman --- CONTRIBUTING.md | 259 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 259 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9c73f4537d0..8be1c8f2290 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -58,6 +58,265 @@ To contribute a change proposal, use the following workflow: 5. After you receive feedback from a reviewer, make the requested changes, commit them to your branch, and push them to your remote fork again. 6. Once approval is given, feel free to squash & merge! +## Writing tests + +We use table-driven tests because they allow us to test similar logic on many different cases in a way that is easy to both implement and understand. [This article](https://dave.cheney.net/2019/05/07/prefer-table-driven-tests) does a fantastic job explaining the motivation and structure of table-driven testing. + +Making table-driven tests in an environment built on the Cosmos SDK has some quirks to it, but overall the structure should be quite similar to what is laid out in the article linked above. + +We'll lay out three examples below (one that uses our format for messages, one that applies to keeper methods, and one that applies to our GAMM module), each of which will hopefully be simple enough to copy-paste into a test file and use as a starting point for your test-writing in the Osmosis Core repo. + +### Rules of thumb for table-driven tests + +1. Each test case should test one thing +2. Each test case should be independent from one another (i.e. ideally, reordering the tests shouldn't cause them to fail) +3. Functions should not be set as fields for a test case (this usually means that the table-driven approach is being sidestepped and that the logic in the function should probably be factored out to cover multiple/all test cases) +4. Avoid verbosity by creating local variables instead of constantly referring to struct field (e.g. doing `lockupKeeper := suite.App.LockupKeeper` instead of using `suite.App.LockupKeeper` every time). + +### Example #1: [Message-Related Test](https://github.com/osmosis-labs/osmosis/blob/f0270d04bd77cc5e1c23f7913118b3c2ba737e97/x/tokenfactory/keeper/admins_test.go#L122-L181) +This type of test is mainly for functions that would be triggered by incoming messages (we interact directly with the message server since all other metadata is stripped from a message by the time it hits the msg_server): + +```go +func (suite *KeeperTestSuite) TestBurnDenom() { + var addr0bal int64 + + // Create a denom. + suite.CreateDefaultDenom() + + // mint 10 default token for testAcc[0] + suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMint(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 10))) + addr0bal += 10 + + for _, tc := range []struct { + desc string + amount int64 + burnDenom string + admin string + valid bool + }{ + { + desc: "denom does not exist", + amount: 10, + burnDenom: "factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", + admin: suite.TestAccs[0].String(), + valid: false, + }, + { + desc: "burn is not by the admin", + amount: 10, + burnDenom: suite.defaultDenom, + admin: suite.TestAccs[1].String(), + valid: false, + }, + { + desc: "burn amount is bigger than minted amount", + amount: 1000, + burnDenom: suite.defaultDenom, + admin: suite.TestAccs[1].String(), + valid: false, + }, + { + desc: "success case", + amount: 10, + burnDenom: suite.defaultDenom, + admin: suite.TestAccs[0].String(), + valid: true, + }, + } { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + // Test minting to admins own account + _, err := suite.msgServer.Burn(sdk.WrapSDKContext(suite.Ctx), types.NewMsgBurn(tc.admin, sdk.NewInt64Coin(tc.burnDenom, 10))) + if tc.valid { + addr0bal -= 10 + suite.Require().NoError(err) + suite.Require().True(suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom).Amount.Int64() == addr0bal, suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom)) + } else { + suite.Require().Error(err) + suite.Require().True(suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom).Amount.Int64() == addr0bal, suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom)) + } + }) + } +} +``` +### Example #2: [Keeper-Related Test](https://github.com/osmosis-labs/osmosis/blob/f0270d04bd77cc5e1c23f7913118b3c2ba737e97/x/epochs/keeper/abci_test.go#L20-L105) +This type of test is mainly for functions that would be triggered by other modules calling public keeper methods (or just to unit-test keeper methods in general): + +```go +func (suite KeeperTestSuite) TestEpochInfoBeginBlockChanges() { + block1Time := time.Unix(1656907200, 0).UTC() + const defaultIdentifier = "hourly" + const defaultDuration = time.Hour + // eps is short for epsilon - in this case a negligible amount of time. + const eps = time.Nanosecond + + tests := map[string]struct { + // if identifier, duration is not set, we make it defaultIdentifier and defaultDuration. + // EpochCountingStarted, if unspecified, is inferred by CurrentEpoch == 0 + // StartTime is inferred to be block1Time if left blank. + initialEpochInfo types.EpochInfo + blockHeightTimePairs map[int]time.Time + expEpochInfo types.EpochInfo + }{ + "First block running at exactly start time sets epoch tick": { + initialEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}}, + expEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 1, CurrentEpochStartTime: block1Time, CurrentEpochStartHeight: 1}, + }, + "First block run sets start time, subsequent blocks within timer interval do not cause timer tick": { + initialEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}}, + blockHeightTimePairs: map[int]time.Time{2: block1Time.Add(time.Second), 3: block1Time.Add(time.Minute), 4: block1Time.Add(30 * time.Minute)}, + expEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 1, CurrentEpochStartTime: block1Time, CurrentEpochStartHeight: 1}, + }, + "Second block at exactly timer interval later does not tick": { + initialEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}}, + blockHeightTimePairs: map[int]time.Time{2: block1Time.Add(defaultDuration)}, + expEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 1, CurrentEpochStartTime: block1Time, CurrentEpochStartHeight: 1}, + }, + "Second block at timer interval + epsilon later does tick": { + initialEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}}, + blockHeightTimePairs: map[int]time.Time{2: block1Time.Add(defaultDuration).Add(eps)}, + expEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 2, CurrentEpochStartTime: block1Time.Add(time.Hour), CurrentEpochStartHeight: 2}, + }, + "Downtime recovery (many intervals), first block causes 1 tick and sets current start time 1 interval ahead": { + initialEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}}, + blockHeightTimePairs: map[int]time.Time{2: block1Time.Add(24 * time.Hour)}, + expEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 2, CurrentEpochStartTime: block1Time.Add(time.Hour), CurrentEpochStartHeight: 2}, + }, + "Downtime recovery (many intervals), second block is at tick 2, w/ start time 2 intervals ahead": { + initialEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}}, + blockHeightTimePairs: map[int]time.Time{2: block1Time.Add(24 * time.Hour), 3: block1Time.Add(24 * time.Hour).Add(eps)}, + expEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 3, CurrentEpochStartTime: block1Time.Add(2 * time.Hour), CurrentEpochStartHeight: 3}, + }, + "Many blocks between first and second tick": { + initialEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 1, CurrentEpochStartTime: block1Time}, + blockHeightTimePairs: map[int]time.Time{2: block1Time.Add(time.Second), 3: block1Time.Add(2 * time.Second), 4: block1Time.Add(time.Hour).Add(eps)}, + expEpochInfo: types.EpochInfo{StartTime: block1Time, CurrentEpoch: 2, CurrentEpochStartTime: block1Time.Add(time.Hour), CurrentEpochStartHeight: 4}, + }, + "Distinct identifier and duration still works": { + initialEpochInfo: types.EpochInfo{Identifier: "hello", Duration: time.Minute, StartTime: block1Time, CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}}, + blockHeightTimePairs: map[int]time.Time{2: block1Time.Add(time.Second), 3: block1Time.Add(time.Minute).Add(eps)}, + expEpochInfo: types.EpochInfo{Identifier: "hello", Duration: time.Minute, StartTime: block1Time, CurrentEpoch: 2, CurrentEpochStartTime: block1Time.Add(time.Minute), CurrentEpochStartHeight: 3}, + }, + "StartTime in future won't get ticked on first block": { + initialEpochInfo: types.EpochInfo{StartTime: block1Time.Add(time.Second), CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}}, + // currentEpochStartHeight is 1 because thats when the timer was created on-chain + expEpochInfo: types.EpochInfo{StartTime: block1Time.Add(time.Second), CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}, CurrentEpochStartHeight: 1}, + }, + "StartTime in past will get ticked on first block": { + initialEpochInfo: types.EpochInfo{StartTime: block1Time.Add(-time.Second), CurrentEpoch: 0, CurrentEpochStartTime: time.Time{}}, + expEpochInfo: types.EpochInfo{StartTime: block1Time.Add(-time.Second), CurrentEpoch: 1, CurrentEpochStartTime: block1Time.Add(-time.Second), CurrentEpochStartHeight: 1}, + }, + } + for name, test := range tests { + suite.Run(name, func() { + suite.SetupTest() + suite.Ctx = suite.Ctx.WithBlockHeight(1).WithBlockTime(block1Time) + initialEpoch := initializeBlankEpochInfoFields(test.initialEpochInfo, defaultIdentifier, defaultDuration) + suite.App.EpochsKeeper.AddEpochInfo(suite.Ctx, initialEpoch) + suite.App.EpochsKeeper.BeginBlocker(suite.Ctx) + + // get sorted heights + heights := maps.Keys(test.blockHeightTimePairs) + osmoutils.SortSlice(heights) + for _, h := range heights { + // for each height in order, run begin block + suite.Ctx = suite.Ctx.WithBlockHeight(int64(h)).WithBlockTime(test.blockHeightTimePairs[h]) + suite.App.EpochsKeeper.BeginBlocker(suite.Ctx) + } + expEpoch := initializeBlankEpochInfoFields(test.expEpochInfo, initialEpoch.Identifier, initialEpoch.Duration) + actEpoch := suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, initialEpoch.Identifier) + suite.Require().Equal(expEpoch, actEpoch) + }) + } +} +``` + +### Example #3: [Gamm-Related Test](https://github.com/osmosis-labs/osmosis/blob/5be82920fa67a97c2c2dff1c06edd10e0ab66319/x/gamm/pool-models/balancer/pool_test.go#L423-L503) +Since the GAMM module is core to the Osmosis repo, it might be useful to have a good example of a well-structured GAMM-specific test. This example covers a simple getter function and validates the specific error messages around the function (as opposed to merely the presence of an error): + +```go +func TestGetPoolAssetsByDenom(t *testing.T) { + testCases := []struct { + name string + poolAssets []balancer.PoolAsset + expectedPoolAssetsByDenom map[string]balancer.PoolAsset + + err error + }{ + { + name: "zero pool assets", + poolAssets: []balancer.PoolAsset{}, + expectedPoolAssetsByDenom: make(map[string]balancer.PoolAsset), + }, + { + name: "one pool asset", + poolAssets: []balancer.PoolAsset{ + { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + }, + expectedPoolAssetsByDenom: map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + }, + }, + { + name: "two pool assets", + poolAssets: []balancer.PoolAsset{ + { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + { + Token: sdk.NewInt64Coin("atom", 123), + Weight: sdk.NewInt(400), + }, + }, + expectedPoolAssetsByDenom: map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + "atom": { + Token: sdk.NewInt64Coin("atom", 123), + Weight: sdk.NewInt(400), + }, + }, + }, + { + name: "duplicate pool assets", + poolAssets: []balancer.PoolAsset{ + { + Token: sdk.NewInt64Coin("uosmo", 1e12), + Weight: sdk.NewInt(100), + }, + { + Token: sdk.NewInt64Coin("uosmo", 123), + Weight: sdk.NewInt(400), + }, + }, + err: fmt.Errorf(balancer.ErrMsgFormatRepeatingPoolAssetsNotAllowed, "uosmo"), + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + actualPoolAssetsByDenom, err := balancer.GetPoolAssetsByDenom(tc.poolAssets) + + require.Equal(t, tc.err, err) + + if tc.err != nil { + return + } + + require.Equal(t, tc.expectedPoolAssetsByDenom, actualPoolAssetsByDenom) + }) + } +} +``` + ## Working with the SDK ### Updating dependencies for builds From 3b76ec16c92c4fd634bbe456f9e48c7e44ae356b Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Wed, 13 Jul 2022 11:17:58 -0500 Subject: [PATCH 067/376] e2e: move endpoint complexity into config.QueryRPC (#2044) * Minor commit, pushes more complexity into config.QueryRPC * driveby fix: Make QueryPropTally use an int for proposal num * Update tests/e2e/configurer/chain/queries.go Co-authored-by: Roman Co-authored-by: Roman --- tests/e2e/configurer/chain/queries.go | 36 +++++++++++---------------- tests/e2e/e2e_test.go | 5 ++-- 2 files changed, 16 insertions(+), 25 deletions(-) diff --git a/tests/e2e/configurer/chain/queries.go b/tests/e2e/configurer/chain/queries.go index 58219ee2c4f..f4b768c86d1 100644 --- a/tests/e2e/configurer/chain/queries.go +++ b/tests/e2e/configurer/chain/queries.go @@ -20,12 +20,17 @@ import ( superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" ) -func (c *Config) QueryRPC(path string) ([]byte, error) { - var err error +func (c *Config) QueryRPC(validatorIdx int, path string) ([]byte, error) { + // add the URL for the given validator ID, and pre-pend to to path. + hostPort, err := c.containerManager.GetValidatorHostPort(c.Id, validatorIdx, "1317/tcp") + require.NoError(c.t, err) + endpoint := fmt.Sprintf("http://%s", hostPort) + fullQueryPath := fmt.Sprintf("%s/%s", endpoint, path) + var resp *http.Response retriesLeft := 5 for { - resp, err = http.Get(path) + resp, err = http.Get(fullQueryPath) if resp.StatusCode == http.StatusServiceUnavailable { retriesLeft-- @@ -88,17 +93,9 @@ func (c *Config) QueryBalances(validatorIndex int, addr string) (sdk.Coins, erro return balancesResp.GetBalances(), nil } -func (c *Config) QueryPropTally(validatorIdx int, addr string) (sdk.Int, sdk.Int, sdk.Int, sdk.Int, error) { - hostPort, err := c.containerManager.GetValidatorHostPort(c.Id, validatorIdx, "1317/tcp") - require.NoError(c.t, err) - - endpoint := fmt.Sprintf("http://%s", hostPort) - - path := fmt.Sprintf( - "%s/cosmos/gov/v1beta1/proposals/%s/tally", - endpoint, addr, - ) - bz, err := c.QueryRPC(path) +func (c *Config) QueryPropTally(validatorIdx int, proposalNumber int) (sdk.Int, sdk.Int, sdk.Int, sdk.Int, error) { + path := fmt.Sprintf("cosmos/gov/v1beta1/proposals/%d/tally", proposalNumber) + bz, err := c.QueryRPC(validatorIdx, path) require.NoError(c.t, err) var balancesResp govtypes.QueryTallyResultResponse @@ -126,17 +123,12 @@ func (c *Config) QueryValidatorOperatorAddresses() { } func (c *Config) QueryIntermediaryAccount(validatorIdx int, denom string, valAddr string) (int, error) { - hostPort, err := c.containerManager.GetValidatorHostPort(c.Id, validatorIdx, "1317/tcp") - require.NoError(c.t, err) - - endpoint := fmt.Sprintf("http://%s", hostPort) - intAccount := superfluidtypes.GetSuperfluidIntermediaryAccountAddr(denom, valAddr) path := fmt.Sprintf( - "%s/cosmos/staking/v1beta1/validators/%s/delegations/%s", - endpoint, valAddr, intAccount, + "cosmos/staking/v1beta1/validators/%s/delegations/%s", + valAddr, intAccount, ) - bz, err := c.QueryRPC(path) + bz, err := c.QueryRPC(validatorIdx, path) require.NoError(c.t, err) var stakingResp stakingtypes.QueryDelegationResponse diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index 34bb446e4ff..7a05fdcc994 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -59,10 +59,9 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { // set delegator vote to no chainA.VoteNoProposal(0, walletName) - sfProposalNumber := strconv.Itoa(chainA.LatestProposalNumber) s.Eventually( func() bool { - noTotal, yesTotal, noWithVetoTotal, abstainTotal, err := chainA.QueryPropTally(0, sfProposalNumber) + noTotal, yesTotal, noWithVetoTotal, abstainTotal, err := chainA.QueryPropTally(0, chainA.LatestProposalNumber) if err != nil { return false } @@ -75,7 +74,7 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { time.Second, "Osmosis node failed to retrieve prop tally", ) - noTotal, _, _, _, _ := chainA.QueryPropTally(0, sfProposalNumber) + noTotal, _, _, _, _ := chainA.QueryPropTally(0, chainA.LatestProposalNumber) noTotalFinal, err := strconv.Atoi(noTotal.String()) s.NoError(err) From 3e49f3312a7f9e8d66888e748bf4927d085b6347 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Wed, 13 Jul 2022 15:05:40 -0500 Subject: [PATCH 068/376] Simulator reworkings (#1871) * Move over base SDK coin * Add a basic internal simulator state struct * Fix many things in simulator / state struct * Cleanup APIs to use simState & simCtx * Fix (existing) simulator bugs & demo legacy simulator still works as before =) * Minor control flow cleanup * Eventstats function split * Shim a basic action wrapper struct * Wrap more init logic * fix lints * Add intended seeding for sim.GetRand() * More with Actions * Continue Action migration, and new sim manager. This is a broken state until genesis handling under this sim manager is solved * Add basic legacy genesis handling -- should be further cleaned in the future * Flow works, albeit a bit awkward, using new API * Add k.GetNextPoolId * notes from call w/ Bez + generic rand method! * wip * fix merge conflict * Add acc and bank keeper to app interface * Thread simtypes.App everywhere. (First change that needs legacy changes) * Add SelAddrWithDenoms * Message creation done * Mock interface * Add more logic for NewMsgBasedAction * Copy old (gross) simulator tx generation code * Fix linter * more progress * Fix some dumb build errors * Fix error handling * Try a second API for action creation * Migrate one lockup module message * Minor notes from call * Migrate all of lockup * Increase selection success for lock token, make better acc sel API --- .golangci.yml | 3 + app/app.go | 24 +- app/modules.go | 40 +-- osmoutils/coin_helper.go | 12 + osmoutils/test_helpers.go | 10 + simapp/sim_test.go | 196 ++++++------ simapp/state.go | 7 +- simulation/ADR.md | 109 +++++++ simulation/executor/doc.go | 121 +++++++ simulation/executor/event_stats.go | 64 ++++ simulation/executor/expected_keepers.go | 16 + simulation/executor/log.go | 82 +++++ simulation/executor/mock_tendermint.go | 225 +++++++++++++ simulation/executor/operation.go | 138 ++++++++ simulation/executor/params.go | 188 +++++++++++ simulation/executor/params_test.go | 56 ++++ simulation/executor/simulate.go | 302 ++++++++++++++++++ simulation/executor/simulate_dev.go | 135 ++++++++ simulation/executor/util.go | 129 ++++++++ simulation/types/account.go | 154 +++++++++ simulation/types/action.go | 98 ++++++ simulation/types/app.go | 27 ++ simulation/types/genesis_config.go | 34 ++ simulation/types/init_functions.go | 57 ++++ simulation/types/legacy.go | 80 +++++ simulation/types/manager.go | 142 ++++++++ simulation/types/random/sdkrand.go | 168 ++++++++++ simulation/types/randutil.go | 72 +++++ simulation/types/simctx.go | 55 ++++ .../transitionmatrix/transition_matrix.go | 80 +++++ simulation/types/txbuilder.go | 59 ++++ simulation/types/weight.go | 11 + x/gamm/keeper/pool.go | 1 + x/gamm/module.go | 14 + x/gamm/simulation/sim_msgs.go | 52 +++ x/incentives/simulation/operations.go | 4 +- x/lockup/module.go | 44 +-- x/lockup/simulation/operations.go | 184 ++--------- x/simulation/mod.go | 100 ------ x/superfluid/simulation/operations.go | 2 +- 40 files changed, 2874 insertions(+), 421 deletions(-) create mode 100644 osmoutils/coin_helper.go create mode 100644 simulation/ADR.md create mode 100644 simulation/executor/doc.go create mode 100644 simulation/executor/event_stats.go create mode 100644 simulation/executor/expected_keepers.go create mode 100644 simulation/executor/log.go create mode 100644 simulation/executor/mock_tendermint.go create mode 100644 simulation/executor/operation.go create mode 100644 simulation/executor/params.go create mode 100644 simulation/executor/params_test.go create mode 100644 simulation/executor/simulate.go create mode 100644 simulation/executor/simulate_dev.go create mode 100644 simulation/executor/util.go create mode 100644 simulation/types/account.go create mode 100644 simulation/types/action.go create mode 100644 simulation/types/app.go create mode 100644 simulation/types/genesis_config.go create mode 100644 simulation/types/init_functions.go create mode 100644 simulation/types/legacy.go create mode 100644 simulation/types/manager.go create mode 100644 simulation/types/random/sdkrand.go create mode 100644 simulation/types/randutil.go create mode 100644 simulation/types/simctx.go create mode 100644 simulation/types/transitionmatrix/transition_matrix.go create mode 100644 simulation/types/txbuilder.go create mode 100644 simulation/types/weight.go create mode 100644 x/gamm/simulation/sim_msgs.go delete mode 100644 x/simulation/mod.go diff --git a/.golangci.yml b/.golangci.yml index 88baa9a2a63..7c9d3d831d1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -105,6 +105,9 @@ issues: - linters: - staticcheck text: "SA1024: cutset contains duplicate characters" # proved to not provide much value, only false positives. + - linters: + - staticcheck + text: "SA9004: only the first constant in this group has an explicit type" # explicitly recommended in go syntax - linters: - stylecheck text: "ST1003:" # requires identifiers with "id" to be "ID". diff --git a/app/app.go b/app/app.go index 2eb703be2ac..7c1c9b58829 100644 --- a/app/app.go +++ b/app/app.go @@ -29,7 +29,6 @@ import ( "github.com/cosmos/cosmos-sdk/server/api" "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" - sdksimapp "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -53,6 +52,7 @@ import ( v8 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v8" v9 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v9" _ "github.com/osmosis-labs/osmosis/v7/client/docs/statik" + simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" ) const appName = "OsmosisApp" @@ -87,7 +87,7 @@ var ( // EmptyWasmOpts defines a type alias for a list of wasm options. EmptyWasmOpts []wasm.Option - _ sdksimapp.App = (*OsmosisApp)(nil) + // _ sdksimapp.App = (*OsmosisApp)(nil) Upgrades = []upgrades.Upgrade{v4.Upgrade, v5.Upgrade, v7.Upgrade, v9.Upgrade, v11.Upgrade} Forks = []upgrades.Fork{v3.Fork, v6.Fork, v8.Fork, v10.Fork} @@ -128,7 +128,7 @@ type OsmosisApp struct { invCheckPeriod uint mm *module.Manager - sm *module.SimulationManager + sm *simulation.Manager configurator module.Configurator } @@ -231,11 +231,6 @@ func NewOsmosisApp( // Tell the app's module manager how to set the order of EndBlockers, which are run at the end of every block. app.mm.SetOrderEndBlockers(OrderEndBlockers(app.mm.ModuleNames())...) - // NOTE: The genutils moodule 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(OrderInitGenesis(app.mm.ModuleNames())...) app.mm.RegisterInvariants(app.CrisisKeeper) @@ -246,12 +241,9 @@ func NewOsmosisApp( app.setupUpgradeHandlers() // 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(simulationModules(app, encodingConfig, skipGenesisInvariants)...) + app.sm = createSimulationManager(app, encodingConfig, skipGenesisInvariants) - app.sm.RegisterStoreDecoders() + // app.sm.RegisterStoreDecoders() // add test gRPC service for testing gRPC queries in isolation testdata.RegisterQueryServer(app.GRPCQueryRouter(), testdata.QueryImpl{}) @@ -312,6 +304,10 @@ func MakeCodecs() (codec.Codec, *codec.LegacyAmino) { return config.Marshaler, config.Amino } +func (app *OsmosisApp) GetBaseApp() *baseapp.BaseApp { + return app.BaseApp +} + // Name returns the name of the App. func (app *OsmosisApp) Name() string { return app.BaseApp.Name() } @@ -365,7 +361,7 @@ func (app *OsmosisApp) InterfaceRegistry() types.InterfaceRegistry { } // SimulationManager implements the SimulationApp interface. -func (app *OsmosisApp) SimulationManager() *module.SimulationManager { +func (app *OsmosisApp) SimulationManager() *simulation.Manager { return app.sm } diff --git a/app/modules.go b/app/modules.go index fce87e2a77f..b30332e45b0 100644 --- a/app/modules.go +++ b/app/modules.go @@ -43,6 +43,7 @@ import ( appparams "github.com/osmosis-labs/osmosis/v7/app/params" _ "github.com/osmosis-labs/osmosis/v7/client/docs/statik" "github.com/osmosis-labs/osmosis/v7/osmoutils/partialord" + simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" "github.com/osmosis-labs/osmosis/v7/x/epochs" epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" "github.com/osmosis-labs/osmosis/v7/x/gamm" @@ -170,6 +171,11 @@ func OrderEndBlockers(allModuleNames []string) []string { // OrderInitGenesis returns module names in order for init genesis calls. func OrderInitGenesis(allModuleNames []string) []string { + // NOTE: The genutils moodule 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. return []string{ capabilitytypes.ModuleName, authtypes.ModuleName, @@ -202,34 +208,20 @@ func OrderInitGenesis(allModuleNames []string) []string { } } -// simulationModules returns modules for simulation manager -func simulationModules( +// createSimulationManager returns a simulation manager +// must be ran after modulemanager.SetInitGenesisOrder +func createSimulationManager( app *OsmosisApp, encodingConfig appparams.EncodingConfig, skipGenesisInvariants bool, -) []module.AppModuleSimulation { +) *simulation.Manager { appCodec := encodingConfig.Marshaler - // recreate list of modules, to ensure no issues with overriding prior module structs. - modules := appModules(app, encodingConfig, skipGenesisInvariants) overrideModules := map[string]module.AppModuleSimulation{ authtypes.ModuleName: auth.NewAppModule(appCodec, *app.AccountKeeper, authsims.RandomGenesisAccounts), } - - simModules := []module.AppModuleSimulation{} - for _, appModule := range modules { - // For every module, see if we override it. If so, use override. - // Else, if we can cast the app module into a simulation module add it. - // otherwise no simulation module. - if simModule, ok := overrideModules[appModule.Name()]; ok { - simModules = append(simModules, simModule) - } else { - if simModule, ok := appModule.(module.AppModuleSimulation); ok { - simModules = append(simModules, simModule) - } - } - } - return simModules + simulationManager := simulation.NewSimulationManager(*app.mm, overrideModules) + return &simulationManager } // ModuleAccountAddrs returns all the app's module account addresses. @@ -241,3 +233,11 @@ func (app *OsmosisApp) ModuleAccountAddrs() map[string]bool { return modAccAddrs } + +func (app *OsmosisApp) GetAccountKeeper() simulation.AccountKeeper { + return app.AppKeepers.AccountKeeper +} + +func (app *OsmosisApp) GetBankKeeper() simulation.BankKeeper { + return app.AppKeepers.BankKeeper +} diff --git a/osmoutils/coin_helper.go b/osmoutils/coin_helper.go new file mode 100644 index 00000000000..77680435e68 --- /dev/null +++ b/osmoutils/coin_helper.go @@ -0,0 +1,12 @@ +package osmoutils + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// TODO: Get this into the SDK https://github.com/cosmos/cosmos-sdk/issues/12538 +func CoinsDenoms(coins sdk.Coins) []string { + denoms := make([]string, len(coins)) + for i, coin := range coins { + denoms[i] = coin.Denom + } + return denoms +} diff --git a/osmoutils/test_helpers.go b/osmoutils/test_helpers.go index a331ce00c3a..de6725fbe18 100644 --- a/osmoutils/test_helpers.go +++ b/osmoutils/test_helpers.go @@ -1,6 +1,7 @@ package osmoutils import ( + "reflect" "testing" "github.com/stretchr/testify/require" @@ -16,3 +17,12 @@ func ConditionalPanic(t *testing.T, expectPanic bool, sut func()) { } require.NotPanics(t, sut) } + +// GetType uses reflection to return a string representation of the name of a given struct. +func GetType(myvar interface{}) string { + if t := reflect.TypeOf(myvar); t.Kind() == reflect.Ptr { + return "*" + t.Elem().Name() + } else { + return t.Name() + } +} diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 422146e9f76..05af96af639 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -1,23 +1,18 @@ package simapp import ( - "encoding/json" - "fmt" - "math/rand" "os" "testing" "github.com/osmosis-labs/osmosis/v7/app" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/baseapp" sdkSimapp "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/store" simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" + + osmosim "github.com/osmosis-labs/osmosis/v7/simulation/executor" + simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" ) // Profile with: @@ -38,7 +33,7 @@ func TestFullAppSimulation(t *testing.T) { // -Enabled=true -NumBlocks=1000 -BlockSize=200 \ // -Period=1 -Commit=true -Seed=57 -v -timeout 24h sdkSimapp.FlagEnabledValue = true - sdkSimapp.FlagNumBlocksValue = 20 + sdkSimapp.FlagNumBlocksValue = 100 sdkSimapp.FlagBlockSizeValue = 25 sdkSimapp.FlagCommitValue = true sdkSimapp.FlagVerboseValue = true @@ -87,23 +82,26 @@ func fullAppSimulation(tb testing.TB, is_testing bool) { interBlockCacheOpt(), fauxMerkleModeOpt) + initFns := simtypes.InitFunctions{ + RandomAccountFn: simtypes.WrapRandAccFnForResampling(simulation2.RandomAccounts, osmosis.ModuleAccountAddrs()), + AppInitialStateFn: AppStateFn(osmosis.AppCodec(), osmosis.SimulationManager()), + } + // Run randomized simulation: - _, simParams, simErr := simulation.SimulateFromSeed( + _, simParams, simErr := osmosim.SimulateFromSeed( tb, os.Stdout, - osmosis.BaseApp, - AppStateFn(osmosis.AppCodec(), osmosis.SimulationManager()), - simulation2.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 - sdkSimapp.SimulationOperations(osmosis, osmosis.AppCodec(), config), // Run all registered operations - osmosis.ModuleAccountAddrs(), + osmosis, + initFns, + osmosis.SimulationManager().Actions(config.Seed, osmosis.AppCodec()), // Run all registered operations config, osmosis.AppCodec(), ) - + simParams = simParams // export state and simParams before the simulation error is checked - if err = sdkSimapp.CheckExportSimulation(osmosis, config, simParams); err != nil { - tb.Fatal(err) - } + // if err = sdkSimapp.CheckExportSimulation(osmosis, config, simParams); err != nil { + // tb.Fatal(err) + // } if simErr != nil { tb.Fatal(simErr) @@ -122,83 +120,83 @@ func interBlockCacheOpt() func(*baseapp.BaseApp) { // // TODO: Make another test for the fuzzer itself, which just has noOp txs // // and doesn't depend on the application. -func TestAppStateDeterminism(t *testing.T) { - // if !sdkSimapp.FlagEnabledValue { - // t.Skip("skipping application simulation") - // } - - config := sdkSimapp.NewConfigFromFlags() - config.InitialBlockHeight = 1 - config.ExportParamsPath = "" - config.OnOperation = false - config.AllInvariants = false - config.ChainID = helpers.SimAppChainID - - // This file is needed to provide the correct path - // to reflect.wasm test file needed for wasmd simulation testing. - config.ParamsFile = "params.json" - - numSeeds := 3 - numTimesToRunPerSeed := 5 - appHashList := make([]json.RawMessage, numTimesToRunPerSeed) - - for i := 0; i < numSeeds; i++ { - config.Seed = rand.Int63() - - for j := 0; j < numTimesToRunPerSeed; j++ { - var logger log.Logger - if sdkSimapp.FlagVerboseValue { - logger = log.TestingLogger() - } else { - logger = log.NewNopLogger() - } - - db := dbm.NewMemDB() - app := app.NewOsmosisApp( - logger, - db, - nil, - true, - map[int64]bool{}, - app.DefaultNodeHome, - sdkSimapp.FlagPeriodValue, - app.MakeEncodingConfig(), - sdkSimapp.EmptyAppOptions{}, - app.GetWasmEnabledProposals(), - app.EmptyWasmOpts, - interBlockCacheOpt()) - - fmt.Printf( - "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", - config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, - ) - - _, _, err := simulation.SimulateFromSeed( - t, - os.Stdout, - app.BaseApp, - AppStateFn(app.AppCodec(), app.SimulationManager()), - simulation2.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 - sdkSimapp.SimulationOperations(app, app.AppCodec(), config), - app.ModuleAccountAddrs(), - config, - app.AppCodec(), - ) - require.NoError(t, err) - - if config.Commit { - sdkSimapp.PrintStats(db) - } - - appHash := app.LastCommitID().Hash - appHashList[j] = appHash - - if j != 0 { - require.Equal( - t, string(appHashList[0]), string(appHashList[j]), - "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, - ) - } - } - } -} +// func TestAppStateDeterminism(t *testing.T) { +// // if !sdkSimapp.FlagEnabledValue { +// // t.Skip("skipping application simulation") +// // } + +// config := sdkSimapp.NewConfigFromFlags() +// config.InitialBlockHeight = 1 +// config.ExportParamsPath = "" +// config.OnOperation = false +// config.AllInvariants = false +// config.ChainID = helpers.SimAppChainID + +// // This file is needed to provide the correct path +// // to reflect.wasm test file needed for wasmd simulation testing. +// config.ParamsFile = "params.json" + +// numSeeds := 3 +// numTimesToRunPerSeed := 5 +// appHashList := make([]json.RawMessage, numTimesToRunPerSeed) + +// for i := 0; i < numSeeds; i++ { +// config.Seed = rand.Int63() + +// for j := 0; j < numTimesToRunPerSeed; j++ { +// var logger log.Logger +// if sdkSimapp.FlagVerboseValue { +// logger = log.TestingLogger() +// } else { +// logger = log.NewNopLogger() +// } + +// db := dbm.NewMemDB() +// app := app.NewOsmosisApp( +// logger, +// db, +// nil, +// true, +// map[int64]bool{}, +// app.DefaultNodeHome, +// sdkSimapp.FlagPeriodValue, +// app.MakeEncodingConfig(), +// sdkSimapp.EmptyAppOptions{}, +// app.GetWasmEnabledProposals(), +// app.EmptyWasmOpts, +// interBlockCacheOpt()) + +// fmt.Printf( +// "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", +// config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, +// ) + +// _, _, err := simulation.SimulateFromSeed( +// t, +// os.Stdout, +// app.BaseApp, +// AppStateFn(app.AppCodec(), app.SimulationManager()), +// simulation2.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 +// sdkSimapp.SimulationOperations(app, app.AppCodec(), config), +// app.ModuleAccountAddrs(), +// config, +// app.AppCodec(), +// ) +// require.NoError(t, err) + +// if config.Commit { +// sdkSimapp.PrintStats(db) +// } + +// appHash := app.LastCommitID().Hash +// appHashList[j] = appHash + +// if j != 0 { +// require.Equal( +// t, string(appHashList[0]), string(appHashList[j]), +// "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, +// ) +// } +// } +// } +// } diff --git a/simapp/state.go b/simapp/state.go index 7f5e1be7868..afeaca64ca8 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -8,6 +8,7 @@ import ( "time" "github.com/osmosis-labs/osmosis/v7/app" + simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" "github.com/cosmos/cosmos-sdk/codec" sdksimapp "github.com/cosmos/cosmos-sdk/simapp" @@ -23,7 +24,7 @@ import ( // AppStateFn returns the initial application state using a genesis or the simulation parameters. // It panics if the user provides files for both of them. // If a file is not given for the genesis or the sim params, it creates a randomized one. -func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simtypes.AppStateFn { +func AppStateFn(cdc codec.JSONCodec, simManager *simulation.Manager) simtypes.AppStateFn { return func(r *rand.Rand, accs []simtypes.Account, config simtypes.Config, ) (appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time) { if sdksimapp.FlagGenesisTimeValue == 0 { @@ -137,7 +138,7 @@ func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simty // AppStateRandomizedFn creates calls each module's GenesisState generator function // and creates the simulation params. func AppStateRandomizedFn( - simManager *module.SimulationManager, r *rand.Rand, cdc codec.JSONCodec, + simManager *simulation.Manager, r *rand.Rand, cdc codec.JSONCodec, accs []simtypes.Account, genesisTimestamp time.Time, appParams simtypes.AppParams, ) (json.RawMessage, []simtypes.Account) { numAccs := int64(len(accs)) @@ -179,7 +180,7 @@ func AppStateRandomizedFn( GenTimestamp: genesisTimestamp, } - simManager.GenerateGenesisStates(simState) + simManager.GenerateGenesisStates(simState, &simulation.SimCtx{}) appState, err := json.Marshal(genesisState) if err != nil { diff --git a/simulation/ADR.md b/simulation/ADR.md new file mode 100644 index 00000000000..51f0de25ebe --- /dev/null +++ b/simulation/ADR.md @@ -0,0 +1,109 @@ +# Simulator ADR + +(NOTE these are some notes for myself, that I moved from paper to laptop. I didn't actually write out the relevant parts for anyone else to have a better time in reviewing (the target architecture and why)) + +We have 5 correlated testing goals, that I'd like the simulator refactor to simultaneously achieve. +On top of this, there are improved dev UX / debugging goals, that any refactor should make easy as well. +We detail what we wish to achieve below, then details of what we do today, and finally a blurb on how we get to where we want to go. + +## Testing feature goals + +### Build a complex state machine + +One goal of the state machine is to construct very complex state machine states. +The only way for us to build state machine states that we don't apriori anticipate, +is to randomly generate many state transitions. + +State transitions in the SDK come from: +* txs +* Beginning a block +* Ending a block + +So we seek to compose those to achieve this simulation. + +### Fuzz test individual SDK Messages + +We want to be able to use golang fuzz testing tools to thoroughly test edge case behavior of given message type. + +### Run memoryless state consistency tests + +On complex states, check that all of state is "consistent" acccording to various checks. +(Known as "invariants" in the current SDK architecture) + +### Make memory-ful property tests + +Simulator takes as input property tests +A property test can specify a list of actions it wants to run before & after +And this function can maintain its own local state/memory (Not State machine state) + +(CFMM k value) + +```go +func CheckCfmmK() { + +} +``` + +### Make dependent, multi-msg + +Q: Do we consider these property tests or Actions +Its altering state (2 txs), so seems like an Action +But if it fails on the important part (if outcoins > inCoins), we want the simulator to fail with an informative error. + +(Join <> Exit invariants) + +```go +shares := SimulateJoinPoolMessage(inCoins) +outCoins := ExitPool(shares) +assert outCoins <= inCoins +``` + +## Dev UX goals + +### Simple API + +Have minimal overhead for randomizing a message, e.g. Just having: +```golang +func MakeRandomizedJoinPoolMsg(sim simulator.Helper) sdk.Msg { + pool_id := sim.FuzzLessThan(k.GetNextPoolId(ctx)) + sender := sim.FuzzAddrWithDenoms(k.GetPool(ctx, pool_id).Assets()) + token_in_maxs := sim.FuzzTokensSubset(sender, k.GetPool(pool_id).Assets().Denoms()) + share_out_amount := gamm.EstimateJoinPoolShareOut(ctx, pool_id, token_in_maxs) + share_out_amount = sim.FuzzEqualInt(share_out_amount) + + return &MsgJoinPool{ + sender, + pool_id, + token_in_maxs, + share_out_amount + } +} +``` + +### Unscrew up genesis handling + +Genesis handling is a tremendous mess right now in the simulator. I've spent many hours in the refactor, and I still have trouble tracking wtf it was doing. The old genesis handling / simState config should be entirely scrapped. + +### Weight management + +Weight management should be done globally at the simulator, with a config. Not per module. +At most each module can 'optionally' provide a 'weight-hint' from an enum, rather than a number. + +### Observability into simulation run + +We should make all logs go into a standard database, have an easy way of seeing the history +and seeing how many message attempts failed + +### Replay + +* Be able to replay old simulation messages (so going off the messages in sequence) +* Be able to run blocks from a real network `osmosisd export-history-for-simulator` + +## What exists in the SDK to date + +The SDK to date only has tooling for constructing complex state machines, and memoryless checks (dubbed invariants) +Moreover, this is done with fairly painful dev UX's. + +## Architecture + +We solve building a complex state machine+ \ No newline at end of file diff --git a/simulation/executor/doc.go b/simulation/executor/doc.go new file mode 100644 index 00000000000..6543bc5c153 --- /dev/null +++ b/simulation/executor/doc.go @@ -0,0 +1,121 @@ +/* +Package simulation implements a full fledged Cosmos SDK application used for executing +simulation test suites. + +Simulation App + +The SimApp type defines an application used for running extensive simulation +testing suites. It contains all core modules, including governance, staking, +slashing, and distribution. + +Simulation is executed with various inputs including the number of blocks to +simulate, the block size, whether the app should commit or not, the invariant +checking period, and a seed which is used as a source of pseudo-randomness. + +In addition to the various inputs, simulation runs mainly in three modes: + +1. Completely random where the initial state, module parameters and simulation +parameters are pseudo-randomly generated. + +2. From a genesis file where the initial state and the module parameters are defined. +This mode is helpful for running simulations on a known state such as a live +network export where a new (mostly likely breaking) version of the application +needs to be tested. + +3. From a params file where the initial state is pseudo-randomly generated but the +module and simulation parameters can be provided manually. This allows for a more +controlled and deterministic simulation setup while allowing the state space to +still be pseudo-randomly simulated. + +The simulation test suite also supports testing determinism and import/export +functionality. + +Randomness + +Currently, simulation uses a single seed (integer) as a source for a PRNG by +which all random operations are executed from. Any call to the PRNG changes all +future operations as the internal state of the PRNG is modified. For example, +if a new message type is created and needs to be simulated, the new introduced +PRNG call will change all subsequent operations. + +This may can often be problematic when testing fixes to simulation faults. One +current solution to this is to use a params file as mentioned above. In the future +the simulation suite is expected to support a series of PRNGs that can be used +uniquely per module and simulation component so that they will not effect each +others state execution outcome. + +Usage + +To execute a completely pseudo-random simulation: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -v -timeout 24h + +To execute simulation from a genesis file: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -Genesis=/path/to/genesis.json \ + -v -timeout 24h + +To execute simulation from a simulation params file: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -Params=/path/to/params.json \ + -v -timeout 24h + +To export the simulation params to a file at a given block height: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -ExportParamsPath=/path/to/params.json \ + -ExportParamsHeight=50 \ + -v -timeout 24h + + +To export the simulation app state (i.e genesis) to a file: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -ExportStatePath=/path/to/genesis.json \ + v -timeout 24h + +Params + +Params that are provided to simulation from a JSON file are used to used to set +both module parameters and simulation parameters. See sim_test.go for the full +set of parameters that can be provided. +*/ +package simulation diff --git a/simulation/executor/event_stats.go b/simulation/executor/event_stats.go new file mode 100644 index 00000000000..0965ed34899 --- /dev/null +++ b/simulation/executor/event_stats.go @@ -0,0 +1,64 @@ +package simulation + +import ( + "encoding/json" + "fmt" + "io" + "io/ioutil" +) + +// EventStats defines an object that keeps a tally of each event that has occurred +// during a simulation. +type EventStats map[string]map[string]map[string]int + +// NewEventStats creates a new empty EventStats object +func NewEventStats() EventStats { + return make(EventStats) +} + +// Tally increases the count of a simulation event. +func (es EventStats) Tally(route, op, evResult string) { + _, ok := es[route] + if !ok { + es[route] = make(map[string]map[string]int) + } + + _, ok = es[route][op] + if !ok { + es[route][op] = make(map[string]int) + } + + es[route][op][evResult]++ +} + +// Print the event stats in JSON format. +func (es EventStats) Print(w io.Writer) { + obj, err := json.MarshalIndent(es, "", " ") + if err != nil { + panic(err) + } + + fmt.Fprintln(w, string(obj)) +} + +// ExportJSON saves the event stats as a JSON file on a given path +func (es EventStats) ExportJSON(path string) { + bz, err := json.MarshalIndent(es, "", " ") + if err != nil { + panic(err) + } + + err = ioutil.WriteFile(path, bz, 0600) + if err != nil { + panic(err) + } +} + +func (es EventStats) exportEvents(ExportStatsPath string, w io.Writer) { + if ExportStatsPath != "" { + fmt.Println("Exporting simulation statistics...") + es.ExportJSON(ExportStatsPath) + } else { + es.Print(w) + } +} diff --git a/simulation/executor/expected_keepers.go b/simulation/executor/expected_keepers.go new file mode 100644 index 00000000000..c54831b8a40 --- /dev/null +++ b/simulation/executor/expected_keepers.go @@ -0,0 +1,16 @@ +package simulation + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// AccountKeeper defines the expected account keeper used for simulations (noalias) +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI +} + +// BankKeeper defines the expected interface needed to retrieve account balances. +type BankKeeper interface { + SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins +} diff --git a/simulation/executor/log.go b/simulation/executor/log.go new file mode 100644 index 00000000000..df563cc18f9 --- /dev/null +++ b/simulation/executor/log.go @@ -0,0 +1,82 @@ +package simulation + +import ( + "fmt" + "os" + "path" + "testing" + "time" +) + +// log writter +type LogWriter interface { + AddEntry(OperationEntry) + PrintLogs() +} + +// LogWriter - return a dummy or standard log writer given the testingmode +func NewLogWriter(tb testing.TB) LogWriter { + // TODO: Figure out whats going on / why here + testingMode, _, _ := getTestingMode(tb) + + if !testingMode { + return &DummyLogWriter{} + } + + return &StandardLogWriter{} +} + +// log writter +type StandardLogWriter struct { + OpEntries []OperationEntry `json:"op_entries" yaml:"op_entries"` +} + +// add an entry to the log writter +func (lw *StandardLogWriter) AddEntry(opEntry OperationEntry) { + lw.OpEntries = append(lw.OpEntries, opEntry) +} + +// PrintLogs - print the logs to a simulation file +func (lw *StandardLogWriter) PrintLogs() { + f := createLogFile() + defer f.Close() + + for i := 0; i < len(lw.OpEntries); i++ { + writeEntry := fmt.Sprintf("%s\n", (lw.OpEntries[i]).MustMarshal()) + _, err := f.WriteString(writeEntry) + + if err != nil { + panic("Failed to write logs to file") + } + } +} + +func createLogFile() *os.File { + var f *os.File + + fileName := fmt.Sprintf("%s.log", time.Now().Format("2006-01-02_15:04:05")) + folderPath := path.Join(os.ExpandEnv("$HOME"), ".simapp", "simulations") + filePath := path.Join(folderPath, fileName) + + err := os.MkdirAll(folderPath, os.ModePerm) + if err != nil { + panic(err) + } + + f, err = os.Create(filePath) + if err != nil { + panic(err) + } + fmt.Printf("Logs to writing to %s\n", filePath) + + return f +} + +// dummy log writter +type DummyLogWriter struct{} + +// do nothing +func (lw *DummyLogWriter) AddEntry(_ OperationEntry) {} + +// do nothing +func (lw *DummyLogWriter) PrintLogs() {} diff --git a/simulation/executor/mock_tendermint.go b/simulation/executor/mock_tendermint.go new file mode 100644 index 00000000000..e4f096db132 --- /dev/null +++ b/simulation/executor/mock_tendermint.go @@ -0,0 +1,225 @@ +package simulation + +import ( + "fmt" + "math/rand" + "sort" + "testing" + "time" + + "github.com/cosmos/cosmos-sdk/types/simulation" + abci "github.com/tendermint/tendermint/abci/types" + cryptoenc "github.com/tendermint/tendermint/crypto/encoding" + tmbytes "github.com/tendermint/tendermint/libs/bytes" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "golang.org/x/exp/maps" + + markov "github.com/osmosis-labs/osmosis/v7/simulation/types/transitionmatrix" +) + +type mockValidator struct { + val abci.ValidatorUpdate + livenessState int +} + +func (mv mockValidator) String() string { + return fmt.Sprintf("mockValidator{%s power:%v state:%v}", + mv.val.PubKey.String(), + mv.val.Power, + mv.livenessState) +} + +type mockValidators map[string]mockValidator + +// get mockValidators from abci validators +func newMockValidators(r *rand.Rand, abciVals []abci.ValidatorUpdate, params Params) mockValidators { + validators := make(mockValidators) + + for _, validator := range abciVals { + str := fmt.Sprintf("%X", validator.PubKey.GetEd25519()) + liveliness := markov.GetMemberOfInitialState(r, params.InitialLivenessWeightings()) + + validators[str] = mockValidator{ + val: validator, + livenessState: liveliness, + } + } + + return validators +} + +func (mv mockValidators) Clone() mockValidators { + validators := make(mockValidators, len(mv)) + keys := mv.getKeys() + for _, k := range keys { + validators[k] = mv[k] + } + return validators +} + +// TODO describe usage +func (mv mockValidators) getKeys() []string { + keys := maps.Keys(mv) + sort.Strings(keys) + return keys +} + +// randomProposer picks a random proposer from the current validator set +func (mv mockValidators) randomProposer(r *rand.Rand) tmbytes.HexBytes { + keys := mv.getKeys() + if len(keys) == 0 { + return nil + } + + key := keys[r.Intn(len(keys))] + + proposer := mv[key].val + pk, err := cryptoenc.PubKeyFromProto(proposer.PubKey) + if err != nil { //nolint:wsl + panic(err) + } + + return pk.Address() +} + +// updateValidators mimics Tendermint's update logic. +func updateValidators( + tb testing.TB, + r *rand.Rand, + params simulation.Params, + current map[string]mockValidator, + updates []abci.ValidatorUpdate, + // logWriter LogWriter, + event func(route, op, evResult string), +) map[string]mockValidator { + nextSet := mockValidators(current).Clone() + for _, update := range updates { + str := fmt.Sprintf("%X", update.PubKey.GetEd25519()) + + if update.Power == 0 { + if _, ok := nextSet[str]; !ok { + tb.Fatalf("tried to delete a nonexistent validator: %s", str) + } + + // logWriter.AddEntry(NewOperationEntry())("kicked", str) + event("end_block", "validator_updates", "kicked") + delete(nextSet, str) + } else if _, ok := nextSet[str]; ok { + // validator already exists, update weight + nextSet[str] = mockValidator{update, nextSet[str].livenessState} + event("end_block", "validator_updates", "updated") + } else { + // Set this new validator + nextSet[str] = mockValidator{ + update, + markov.GetMemberOfInitialState(r, params.InitialLivenessWeightings()), + } + event("end_block", "validator_updates", "added") + } + } + + return nextSet +} + +// RandomRequestBeginBlock generates a list of signing validators according to +// the provided list of validators, signing fraction, and evidence fraction +func RandomRequestBeginBlock(r *rand.Rand, params Params, + validators mockValidators, pastTimes []time.Time, + pastVoteInfos [][]abci.VoteInfo, + event func(route, op, evResult string), header tmproto.Header) abci.RequestBeginBlock { + if len(validators) == 0 { + return abci.RequestBeginBlock{ + Header: header, + } + } + + voteInfos := make([]abci.VoteInfo, len(validators)) + + for i, key := range validators.getKeys() { + mVal := validators[key] + mVal.livenessState = params.LivenessTransitionMatrix().NextState(r, mVal.livenessState) + signed := true + + if mVal.livenessState == 1 { + // spotty connection, 50% probability of success + // See https://github.com/golang/go/issues/23804#issuecomment-365370418 + // for reasoning behind computing like this + signed = r.Int63()%2 == 0 + } else if mVal.livenessState == 2 { + // offline + signed = false + } + + if signed { + event("begin_block", "signing", "signed") + } else { + event("begin_block", "signing", "missed") + } + + pubkey, err := cryptoenc.PubKeyFromProto(mVal.val.PubKey) + if err != nil { + panic(err) + } + + voteInfos[i] = abci.VoteInfo{ + Validator: abci.Validator{ + Address: pubkey.Address(), + Power: mVal.val.Power, + }, + SignedLastBlock: signed, + } + } + + // return if no past times + if len(pastTimes) == 0 { + return abci.RequestBeginBlock{ + Header: header, + LastCommitInfo: abci.LastCommitInfo{ + Votes: voteInfos, + }, + } + } + + // TODO: Determine capacity before allocation + evidence := make([]abci.Evidence, 0) + // TODO: Change this to be markov based & clean this up + for r.Float64() < params.EvidenceFraction() { + height := header.Height + time := header.Time + vals := voteInfos + + if r.Float64() < params.PastEvidenceFraction() && header.Height > 1 { + height = int64(r.Intn(int(header.Height)-1)) + 1 // Tendermint starts at height 1 + // array indices offset by one + time = pastTimes[height-1] + vals = pastVoteInfos[height-1] + } + + validator := vals[r.Intn(len(vals))].Validator + + var totalVotingPower int64 + for _, val := range vals { + totalVotingPower += val.Validator.Power + } + + evidence = append(evidence, + abci.Evidence{ + Type: abci.EvidenceType_DUPLICATE_VOTE, + Validator: validator, + Height: height, + Time: time, + TotalVotingPower: totalVotingPower, + }, + ) + + event("begin_block", "evidence", "ok") + } + + return abci.RequestBeginBlock{ + Header: header, + LastCommitInfo: abci.LastCommitInfo{ + Votes: voteInfos, + }, + ByzantineValidators: evidence, + } +} diff --git a/simulation/executor/operation.go b/simulation/executor/operation.go new file mode 100644 index 00000000000..38a018a61d7 --- /dev/null +++ b/simulation/executor/operation.go @@ -0,0 +1,138 @@ +package simulation + +import ( + "encoding/json" + "math/rand" + "sort" + + "github.com/cosmos/cosmos-sdk/types/simulation" + + simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" + // simtypes "github.com/osmosis-labs/osmosis/simulation/types" +) + +// entry kinds for use within OperationEntry +const ( + BeginBlockEntryKind = "begin_block" + EndBlockEntryKind = "end_block" + MsgEntryKind = "msg" + QueuedMsgEntryKind = "queued_msg" +) + +// OperationEntry - an operation entry for logging (ex. BeginBlock, EndBlock, XxxMsg, etc) +type OperationEntry struct { + EntryKind string `json:"entry_kind" yaml:"entry_kind"` + Height int64 `json:"height" yaml:"height"` + Order int64 `json:"order" yaml:"order"` + Operation json.RawMessage `json:"operation" yaml:"operation"` +} + +// NewOperationEntry creates a new OperationEntry instance +func NewOperationEntry(entry string, height, order int64, op json.RawMessage) OperationEntry { + return OperationEntry{ + EntryKind: entry, + Height: height, + Order: order, + Operation: op, + } +} + +// BeginBlockEntry - operation entry for begin block +func BeginBlockEntry(height int64) OperationEntry { + return NewOperationEntry(BeginBlockEntryKind, height, -1, nil) +} + +// EndBlockEntry - operation entry for end block +func EndBlockEntry(height int64) OperationEntry { + return NewOperationEntry(EndBlockEntryKind, height, -1, nil) +} + +// MsgEntry - operation entry for standard msg +func MsgEntry(height, order int64, opMsg simulation.OperationMsg) OperationEntry { + return NewOperationEntry(MsgEntryKind, height, order, opMsg.MustMarshal()) +} + +// QueuedMsgEntry creates an operation entry for a given queued message. +func QueuedMsgEntry(height int64, opMsg simulation.OperationMsg) OperationEntry { + return NewOperationEntry(QueuedMsgEntryKind, height, -1, opMsg.MustMarshal()) +} + +// MustMarshal marshals the operation entry, panic on error. +func (oe OperationEntry) MustMarshal() json.RawMessage { + out, err := json.Marshal(oe) + if err != nil { + panic(err) + } + + return out +} + +// OperationQueue defines an object for a queue of operations +type OperationQueue map[int][]simulation.Operation + +// NewOperationQueue creates a new OperationQueue instance. +func NewOperationQueue() OperationQueue { + return make(OperationQueue) +} + +// queueOperations adds all future operations into the operation queue. +// TODO: Change FutureOperation to FutureAction +func queueOperations(queuedOps OperationQueue, queuedTimeOps []simulation.FutureOperation, futureOps []simulation.FutureOperation) { + if futureOps == nil { + return + } + + for _, futureOp := range futureOps { + futureOp := futureOp + if futureOp.BlockHeight != 0 { + if val, ok := queuedOps[futureOp.BlockHeight]; ok { + queuedOps[futureOp.BlockHeight] = append(val, futureOp.Op) + } else { + queuedOps[futureOp.BlockHeight] = []simulation.Operation{futureOp.Op} + } + + continue + } + + // TODO: Replace with proper sorted data structure, so don't have the + // copy entire slice + index := sort.Search( + len(queuedTimeOps), + func(i int) bool { + return queuedTimeOps[i].BlockTime.After(futureOp.BlockTime) + }, + ) + + queuedTimeOps = append(queuedTimeOps, simulation.FutureOperation{}) + copy(queuedTimeOps[index+1:], queuedTimeOps[index:]) + queuedTimeOps[index] = futureOp + } +} +func totalWeight(actions []simtypes.Action) int { + totalWeight := 0 + for _, action := range actions { + totalWeight += int(action.Weight()) + } + + return totalWeight +} + +type selectActionFn func(r *rand.Rand) simtypes.Action + +func getSelectActionFn(actions []simtypes.Action) selectActionFn { + totalOpWeight := totalWeight(actions) + + return func(r *rand.Rand) simtypes.Action { + x := r.Intn(totalOpWeight) + // TODO: Change to an accum list approach + for i := 0; i < len(actions); i++ { + if x <= int(actions[i].Weight()) { + return actions[i] + } + + x -= int(actions[i].Weight()) + } + // shouldn't happen + return actions[0] + } +} diff --git a/simulation/executor/params.go b/simulation/executor/params.go new file mode 100644 index 00000000000..44c90395173 --- /dev/null +++ b/simulation/executor/params.go @@ -0,0 +1,188 @@ +package simulation + +import ( + "encoding/json" + "fmt" + "math/rand" + + abci "github.com/tendermint/tendermint/abci/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types/simulation" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + markov "github.com/osmosis-labs/osmosis/v7/simulation/types/transitionmatrix" +) + +const ( + // Minimum time per block + minTimePerBlock int64 = 10000 / 2 + + // Maximum time per block + maxTimePerBlock int64 = 10000 +) + +// TODO: explain transitional matrix usage +var ( + // Currently there are 3 different liveness types, + // fully online, spotty connection, offline. + defaultLivenessTransitionMatrix, _ = markov.CreateTransitionMatrix([][]int{ + {90, 20, 1}, + {10, 50, 5}, + {0, 10, 1000}, + }) + + // 3 states: rand in range [0, 4*provided blocksize], + // rand in range [0, 2 * provided blocksize], 0 + defaultBlockSizeTransitionMatrix, _ = markov.CreateTransitionMatrix([][]int{ + {85, 5, 0}, + {15, 92, 1}, + {0, 3, 99}, + }) +) + +// Params define the parameters necessary for running the simulations +type Params struct { + pastEvidenceFraction float64 + numKeys int + evidenceFraction float64 + initialLivenessWeightings []int + livenessTransitionMatrix simulation.TransitionMatrix + blockSizeTransitionMatrix simulation.TransitionMatrix +} + +func (p Params) PastEvidenceFraction() float64 { + return p.pastEvidenceFraction +} + +func (p Params) NumKeys() int { + return p.numKeys +} + +func (p Params) EvidenceFraction() float64 { + return p.evidenceFraction +} + +func (p Params) InitialLivenessWeightings() []int { + return p.initialLivenessWeightings +} + +func (p Params) LivenessTransitionMatrix() simulation.TransitionMatrix { + return p.livenessTransitionMatrix +} + +func (p Params) BlockSizeTransitionMatrix() simulation.TransitionMatrix { + return p.blockSizeTransitionMatrix +} + +// RandomParams returns random simulation parameters +func RandomParams(r *rand.Rand) Params { + return Params{ + pastEvidenceFraction: r.Float64(), + numKeys: simulation.RandIntBetween(r, 2, 2500), // number of accounts created for the simulation + evidenceFraction: r.Float64() / 2, + initialLivenessWeightings: []int{simulation.RandIntBetween(r, 1, 80), r.Intn(10), r.Intn(10)}, + livenessTransitionMatrix: defaultLivenessTransitionMatrix, + blockSizeTransitionMatrix: defaultBlockSizeTransitionMatrix, + } +} + +// Param change proposals + +// ParamChange defines the object used for simulating parameter change proposals +type ParamChange struct { + subspace string + key string + simValue simulation.SimValFn +} + +func (spc ParamChange) Subspace() string { + return spc.subspace +} + +func (spc ParamChange) Key() string { + return spc.key +} + +func (spc ParamChange) SimValue() simulation.SimValFn { + return spc.simValue +} + +// NewSimParamChange creates a new ParamChange instance +func NewSimParamChange(subspace, key string, simVal simulation.SimValFn) simulation.ParamChange { + return ParamChange{ + subspace: subspace, + key: key, + simValue: simVal, + } +} + +// ComposedKey creates a new composed key for the param change proposal +func (spc ParamChange) ComposedKey() string { + return spc.Subspace() + "/" + spc.Key() +} + +// Proposal Contents + +// WeightedProposalContent defines a common struct for proposal contents defined by +// external modules (i.e outside gov) +type WeightedProposalContent struct { + appParamsKey string // key used to retrieve the value of the weight from the simulation application params + defaultWeight int // default weight + contentSimulatorFn simulation.ContentSimulatorFn // content simulator function +} + +func NewWeightedProposalContent(appParamsKey string, defaultWeight int, contentSimulatorFn simulation.ContentSimulatorFn) simulation.WeightedProposalContent { + return &WeightedProposalContent{appParamsKey: appParamsKey, defaultWeight: defaultWeight, contentSimulatorFn: contentSimulatorFn} +} + +func (w WeightedProposalContent) AppParamsKey() string { + return w.appParamsKey +} + +func (w WeightedProposalContent) DefaultWeight() int { + return w.defaultWeight +} + +func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { + return w.contentSimulatorFn +} + +// Param change proposals + +// randomConsensusParams returns random simulation consensus parameters, it extracts the Evidence from the Staking genesis state. +func randomConsensusParams(r *rand.Rand, appState json.RawMessage, cdc codec.JSONCodec) *abci.ConsensusParams { + var genesisState map[string]json.RawMessage + err := json.Unmarshal(appState, &genesisState) + if err != nil { + panic(err) + } + + stakingGenesisState := stakingtypes.GetGenesisStateFromAppState(cdc, genesisState) + consensusParams := &abci.ConsensusParams{ + Block: &abci.BlockParams{ + MaxBytes: int64(simulation.RandIntBetween(r, 20000000, 30000000)), + MaxGas: -1, + }, + Validator: &tmproto.ValidatorParams{ + PubKeyTypes: []string{types.ABCIPubKeyTypeEd25519}, + }, + Evidence: &tmproto.EvidenceParams{ + MaxAgeNumBlocks: int64(stakingGenesisState.Params.UnbondingTime / AverageBlockTime), + MaxAgeDuration: stakingGenesisState.Params.UnbondingTime, + }, + Version: &tmproto.VersionParams{ + AppVersion: uint64(simulation.RandIntBetween(r, 0, 10000)), + }, + } + + bz, err := json.MarshalIndent(&consensusParams, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated consensus parameters:\n%s\n", bz) + + return consensusParams +} diff --git a/simulation/executor/params_test.go b/simulation/executor/params_test.go new file mode 100644 index 00000000000..3eb3ad8bc76 --- /dev/null +++ b/simulation/executor/params_test.go @@ -0,0 +1,56 @@ +package simulation + +import ( + "fmt" + "math/rand" + "testing" + + "github.com/stretchr/testify/require" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" +) + +func TestParamChange(t *testing.T) { + subspace, key := "theSubspace", "key" + f := func(r *rand.Rand) string { + return "theResult" + } + + pChange := NewSimParamChange(subspace, key, f) + + require.Equal(t, subspace, pChange.Subspace()) + require.Equal(t, key, pChange.Key()) + require.Equal(t, f(nil), pChange.SimValue()(nil)) + require.Equal(t, fmt.Sprintf("%s/%s", subspace, key), pChange.ComposedKey()) +} + +func TestNewWeightedProposalContent(t *testing.T) { + key := "theKey" + weight := 1 + content := &testContent{} + f := func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { + return content + } + + pContent := NewWeightedProposalContent(key, weight, f) + + require.Equal(t, key, pContent.AppParamsKey()) + require.Equal(t, weight, pContent.DefaultWeight()) + + ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil) + require.Equal(t, content, pContent.ContentSimulatorFn()(nil, ctx, nil)) +} + +type testContent struct { +} + +func (t testContent) GetTitle() string { return "" } +func (t testContent) GetDescription() string { return "" } +func (t testContent) GetIsExpedited() bool { return false } +func (t testContent) SetIsExpedited(isExpedited bool) {} +func (t testContent) ProposalRoute() string { return "" } +func (t testContent) ProposalType() string { return "" } +func (t testContent) ValidateBasic() error { return nil } +func (t testContent) String() string { return "" } diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go new file mode 100644 index 00000000000..d648d7bdbd8 --- /dev/null +++ b/simulation/executor/simulate.go @@ -0,0 +1,302 @@ +package simulation + +import ( + "fmt" + "io" + "math/rand" + "os" + "os/signal" + "syscall" + "testing" + "time" + + abci "github.com/tendermint/tendermint/abci/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" + + simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" +) + +const AverageBlockTime = 6 * time.Second + +// initialize the chain for the simulation +func initChain( + r *rand.Rand, + params Params, + accounts []simulation.Account, + app simtypes.App, + appStateFn simulation.AppStateFn, + config simulation.Config, + cdc codec.JSONCodec, +) (mockValidators, time.Time, []simulation.Account, string) { + // TODO: Cleanup the whole config dependency with appStateFn + appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) + consensusParams := randomConsensusParams(r, appState, cdc) + req := abci.RequestInitChain{ + AppStateBytes: appState, + ChainId: chainID, + ConsensusParams: consensusParams, + Time: genesisTimestamp, + } + // Valid app version can only be zero on app initialization. + req.ConsensusParams.Version.AppVersion = 0 + res := app.GetBaseApp().InitChain(req) + validators := newMockValidators(r, res.Validators, params) + + return validators, genesisTimestamp, accounts, chainID +} + +// SimulateFromSeedLegacy tests an application by running the provided +// operations, testing the provided invariants, but using the provided config.Seed. +// TODO: Restore SimulateFromSeedLegacy by adding a wrapper that can take in +// func SimulateFromSeedLegacy( +// tb testing.TB, +// w io.Writer, +// app *baseapp.BaseApp, +// appStateFn simulation.AppStateFn, +// randAccFn simulation.RandomAccountFn, +// ops legacysimexec.WeightedOperations, +// blockedAddrs map[string]bool, +// config simulation.Config, +// cdc codec.JSONCodec, +// ) (stopEarly bool, exportedParams Params, err error) { +// actions := simtypes.ActionsFromWeightedOperations(ops) +// initFns := simtypes.InitFunctions{ +// RandomAccountFn: simtypes.WrapRandAccFnForResampling(randAccFn, blockedAddrs), +// AppInitialStateFn: appStateFn, +// } +// return SimulateFromSeed(tb, w, app, initFns, actions, config, cdc) +// } + +// SimulateFromSeed tests an application by running the provided +// operations, testing the provided invariants, but using the provided config.Seed. +// TODO: Inputs should be: +// * SimManager for module configs +// * Config file for params +// * whatever is needed for logging (tb + w rn) +func SimulateFromSeed( + tb testing.TB, + w io.Writer, + app simtypes.App, + initFunctions simtypes.InitFunctions, + actions []simtypes.Action, + config simulation.Config, + cdc codec.JSONCodec, +) (stopEarly bool, exportedParams Params, err error) { + // in case we have to end early, don't os.Exit so that we can run cleanup code. + testingMode, _, b := getTestingMode(tb) + + fmt.Fprintf(w, "Starting SimulateFromSeed with randomness created with seed %d\n", int(config.Seed)) + r := rand.New(rand.NewSource(config.Seed)) + simParams := RandomParams(r) + fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(simParams)) + + accs := initFunctions.RandomAccountFn(r, simParams.NumKeys()) + if len(accs) == 0 { + return true, simParams, fmt.Errorf("must have greater than zero genesis accounts") + } + + validators, genesisTimestamp, accs, chainID := initChain(r, simParams, accs, app, initFunctions.AppInitialStateFn, config, cdc) + + config.ChainID = chainID + if config.InitialBlockHeight == 0 { + config.InitialBlockHeight = 1 + } + + fmt.Printf( + "Starting the simulation from time %v (unixtime %v)\n", + genesisTimestamp.UTC().Format(time.UnixDate), genesisTimestamp.Unix(), + ) + + initialHeader := tmproto.Header{ + ChainID: chainID, + Height: int64(config.InitialBlockHeight), + Time: genesisTimestamp, + ProposerAddress: validators.randomProposer(r), + } + + simState := newSimulatorState(simParams, initialHeader, tb, w, validators).WithLogParam(config.Lean) + + simCtx := simtypes.NewSimCtx(r, app, accs, simState.header.ChainID) + + // Setup code to catch SIGTERM's + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) + + go func() { + receivedSignal := <-c + fmt.Fprintf(w, "\nExiting early due to %s, on block %d, operation %d\n", receivedSignal, simState.header.Height, simState.opCount) + err = fmt.Errorf("exited due to %s", receivedSignal) + stopEarly = true + }() + + blockSimulator := createBlockSimulator(testingMode, w, simParams, actions, simState, config) + + if !testingMode { + b.ResetTimer() + } else { + // recover logs in case of panic + defer func() { + if r := recover(); r != nil { + _, _ = fmt.Fprintf(w, "simulation halted due to panic on block %d\n", simState.header.Height) + simState.logWriter.PrintLogs() + panic(r) + } + }() + } + + // set exported params to the initial state + if config.ExportParamsPath != "" && config.ExportParamsHeight == 0 { + exportedParams = simParams + } + + for height := config.InitialBlockHeight; height < config.NumBlocks+config.InitialBlockHeight && !stopEarly; height++ { + stopEarly = simState.SimulateBlock(simCtx, blockSimulator) + if stopEarly { + break + } + + if config.Commit { + simCtx.App.GetBaseApp().Commit() + } + } + + if !stopEarly { + fmt.Fprintf( + w, + "\nSimulation complete; Final height (blocks): %d, final time (seconds): %v, operations ran: %d\n", + simState.header.Height, simState.header.Time, simState.opCount, + ) + } + + simState.eventStats.exportEvents(config.ExportStatsPath, w) + return stopEarly, exportedParams, nil +} + +type blockSimFn func(simCtx *simtypes.SimCtx, ctx sdk.Context, header tmproto.Header) (opCount int) + +// Returns a function to simulate blocks. Written like this to avoid constant +// parameters being passed everytime, to minimize memory overhead. +func createBlockSimulator(testingMode bool, w io.Writer, params Params, actions []simtypes.Action, + simState *simState, config simulation.Config) blockSimFn { + lastBlockSizeState := 0 // state for [4 * uniform distribution] + blocksize := 0 + selectAction := getSelectActionFn(actions) + + return func( + simCtx *simtypes.SimCtx, ctx sdk.Context, header tmproto.Header, + ) (opCount int) { + _, _ = fmt.Fprintf( + w, "\rSimulating... block %d/%d, operation %d/%d.", + header.Height, config.NumBlocks, opCount, blocksize, + ) + lastBlockSizeState, blocksize = getBlockSize(simCtx, params, lastBlockSizeState, config.BlockSize) + + // TODO: Fix according to the r plans + // Predetermine the blocksize slice so that we can do things like block + // out certain operations without changing the ops that follow. + // NOTE: This is poor mans seeding, it will improve in our simctx plans =) + blockActions := make([]simtypes.Action, 0, blocksize) + for i := 0; i < blocksize; i++ { + blockActions = append(blockActions, selectAction(simCtx.GetRand())) + } + + for i := 0; i < blocksize; i++ { + action := blockActions[i] + // TODO: We need to make a simCtx.WithSeededRand, that replaces the rand map internally + // but allows updates to accounts. + opMsg, futureOps, err := action.Execute(simCtx, ctx) + opMsg.LogEvent(simState.eventStats.Tally) + + if !simState.leanLogs || opMsg.OK { + simState.logWriter.AddEntry(MsgEntry(header.Height, int64(i), opMsg)) + } + + if err != nil { + simState.logWriter.PrintLogs() + simState.tb.Fatalf(`error on block %d/%d, operation (%d/%d) from x/%s: +%v +Comment: %s`, + header.Height, config.NumBlocks, opCount, blocksize, opMsg.Route, err, opMsg.Comment) + } + + queueOperations(simState.operationQueue, simState.timeOperationQueue, futureOps) + + if testingMode && opCount%50 == 0 { + fmt.Fprintf(w, "\rSimulating... block %d/%d, operation %d/%d. ", + header.Height, config.NumBlocks, opCount, blocksize) + } + + opCount++ + } + + return opCount + } +} + +// nolint: errcheck +func (simState *simState) runQueuedOperations(simCtx *simtypes.SimCtx, ctx sdk.Context) (numOpsRan int) { + height := int(simState.header.Height) + queuedOp, ok := simState.operationQueue[height] + if !ok { + return 0 + } + + numOpsRan = len(queuedOp) + for i := 0; i < numOpsRan; i++ { + // TODO: Fix according to the r plans + r := simCtx.GetRand() + + // For now, queued operations cannot queue more operations. + // If a need arises for us to support queued messages to queue more messages, this can + // be changed. + opMsg, _, err := queuedOp[i](r, simCtx.App.GetBaseApp(), ctx, simCtx.Accounts, simCtx.ChainID) + opMsg.LogEvent(simState.eventStats.Tally) + + if !simState.leanLogs || opMsg.OK { + simState.logWriter.AddEntry((QueuedMsgEntry(int64(height), opMsg))) + } + + if err != nil { + simState.logWriter.PrintLogs() + simState.tb.FailNow() + } + } + delete(simState.operationQueue, height) + + return numOpsRan +} + +func (simState *simState) runQueuedTimeOperations(simCtx *simtypes.SimCtx, ctx sdk.Context) ( + numOpsRan int) { + queueOps := simState.timeOperationQueue + currentTime := simState.header.Time + numOpsRan = 0 + for len(queueOps) > 0 && currentTime.After(queueOps[0].BlockTime) { + // TODO: Fix according to the r plans + r := simCtx.GetRand() + + // For now, queued operations cannot queue more operations. + // If a need arises for us to support queued messages to queue more messages, this can + // be changed. + opMsg, _, err := queueOps[0].Op(r, simCtx.App.GetBaseApp(), ctx, simCtx.Accounts, simCtx.ChainID) + opMsg.LogEvent(simState.eventStats.Tally) + + if !simState.leanLogs || opMsg.OK { + simState.logWriter.AddEntry(QueuedMsgEntry(simState.header.Height, opMsg)) + } + + if err != nil { + simState.logWriter.PrintLogs() + simState.tb.FailNow() + } + + queueOps = queueOps[1:] + numOpsRan++ + } + simState.timeOperationQueue = queueOps + return numOpsRan +} diff --git a/simulation/executor/simulate_dev.go b/simulation/executor/simulate_dev.go new file mode 100644 index 00000000000..8f14b7da083 --- /dev/null +++ b/simulation/executor/simulate_dev.go @@ -0,0 +1,135 @@ +package simulation + +import ( + "fmt" + "io" + "testing" + "time" + + "github.com/cosmos/cosmos-sdk/types/simulation" + abci "github.com/tendermint/tendermint/abci/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + + simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" +) + +type simState struct { + // TODO: Fix things so this can be interface + simParams Params + header tmproto.Header + + // These are operations which have been queued by previous operations + // TODO: Replace with new action syntax + operationQueue map[int][]simulation.Operation + timeOperationQueue []simulation.FutureOperation + + curValidators mockValidators + nextValidators mockValidators + + // TODO: Figure out why we need this??? + // Probably should get removed + tb testing.TB + + // We technically have to store past block times for every block within the unbonding period. + // For simplicity, we take the RAM overhead and store all past times. + pastTimes []time.Time + pastVoteInfos [][]abci.VoteInfo + + leanLogs bool + logWriter LogWriter + w io.Writer + + // eventStats is an obviously bad design, but for now we leave it as future + // work for us to clean up and architect well. + // We should be collecting this raw data, and able to stream it out into a database. + // Its fine to keep some basic aggregate statistics, but not where it should end. + eventStats EventStats + opCount int +} + +func newSimulatorState(simParams Params, initialHeader tmproto.Header, tb testing.TB, w io.Writer, validators mockValidators) *simState { + return &simState{ + simParams: simParams, + header: initialHeader, + operationQueue: NewOperationQueue(), + timeOperationQueue: []simulation.FutureOperation{}, + curValidators: validators.Clone(), + nextValidators: validators.Clone(), + tb: tb, + pastTimes: []time.Time{}, + pastVoteInfos: [][]abci.VoteInfo{}, + logWriter: NewLogWriter(tb), + w: w, + eventStats: NewEventStats(), + opCount: 0, + } +} + +func (simState *simState) WithLogParam(leanLogs bool) *simState { + simState.leanLogs = leanLogs + return simState +} + +// simulate a block, update state +func (simState *simState) SimulateBlock(simCtx *simtypes.SimCtx, blockSimulator blockSimFn) (stopEarly bool) { + if simState.header.ProposerAddress == nil { + fmt.Fprintf(simState.w, "\nSimulation stopped early as all validators have been unbonded; nobody left to propose a block!\n") + return true + } + + requestBeginBlock := simState.beginBlock(simCtx) + ctx := simCtx.App.GetBaseApp().NewContext(false, simState.header) + + // Run queued operations. Ignores blocksize if blocksize is too small + numQueuedOpsRan := simState.runQueuedOperations(simCtx, ctx) + numQueuedTimeOpsRan := simState.runQueuedTimeOperations(simCtx, ctx) + + // run standard operations + // TODO: rename blockSimulator arg + operations := blockSimulator(simCtx, ctx, simState.header) + simState.opCount += operations + numQueuedOpsRan + numQueuedTimeOpsRan + + responseEndBlock := simState.endBlock(simCtx) + + simState.prepareNextSimState(simCtx, requestBeginBlock, responseEndBlock) + + return false +} + +func (simState *simState) beginBlock(simCtx *simtypes.SimCtx) abci.RequestBeginBlock { + // Generate a random RequestBeginBlock with the current validator set + requestBeginBlock := RandomRequestBeginBlock(simCtx.GetRand(), simState.simParams, simState.curValidators, simState.pastTimes, simState.pastVoteInfos, simState.eventStats.Tally, simState.header) + // Run the BeginBlock handler + simState.logWriter.AddEntry(BeginBlockEntry(simState.header.Height)) + simCtx.App.GetBaseApp().BeginBlock(requestBeginBlock) + return requestBeginBlock +} + +func (simState *simState) endBlock(simCtx *simtypes.SimCtx) abci.ResponseEndBlock { + res := simCtx.App.GetBaseApp().EndBlock(abci.RequestEndBlock{}) + simState.logWriter.AddEntry(EndBlockEntry(simState.header.Height)) + return res +} + +func (simState *simState) prepareNextSimState(simCtx *simtypes.SimCtx, req abci.RequestBeginBlock, res abci.ResponseEndBlock) { + // Log the current block's header time for future lookup + simState.pastTimes = append(simState.pastTimes, simState.header.Time) + simState.pastVoteInfos = append(simState.pastVoteInfos, req.LastCommitInfo.Votes) + + simState.header.Height++ + + timeDiff := maxTimePerBlock - minTimePerBlock + simState.header.Time = simState.header.Time.Add( + time.Duration(minTimePerBlock) * time.Second) + simState.header.Time = simState.header.Time.Add( + time.Duration(int64(simCtx.GetRand().Intn(int(timeDiff)))) * time.Second) + + // Draw the block proposer from proposers for n+1 + simState.header.ProposerAddress = simState.nextValidators.randomProposer(simCtx.GetRand()) + // find N + 2 valset + nPlus2Validators := updateValidators(simState.tb, simCtx.GetRand(), simState.simParams, simState.nextValidators, res.ValidatorUpdates, simState.eventStats.Tally) + + // now set variables in perspective of block n+1 + simState.curValidators = simState.nextValidators + simState.nextValidators = nPlus2Validators +} diff --git a/simulation/executor/util.go b/simulation/executor/util.go new file mode 100644 index 00000000000..2ecbbbd3ee6 --- /dev/null +++ b/simulation/executor/util.go @@ -0,0 +1,129 @@ +package simulation + +import ( + "encoding/json" + "fmt" + "math/rand" + "testing" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/simapp/helpers" + sdk "github.com/cosmos/cosmos-sdk/types" + simulation "github.com/cosmos/cosmos-sdk/types/simulation" + + simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" +) + +func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) { + testingMode = false + + if _t, ok := tb.(*testing.T); ok { + t = _t + testingMode = true + } else { + //nolint:forcetypeassert + b = tb.(*testing.B) + } + + return testingMode, t, b +} + +// getBlockSize returns a block size as determined from the transition matrix. +// It targets making average block size the provided parameter. The three +// states it moves between are: +// - "over stuffed" blocks with average size of 2 * avgblocksize, +// - normal sized blocks, hitting avgBlocksize on average, +// - and empty blocks, with no txs / only txs scheduled from the past. +func getBlockSize(simCtx *simtypes.SimCtx, params Params, lastBlockSizeState, avgBlockSize int) (state, blockSize int) { + r := simCtx.GetSeededRand("get block size") + // TODO: Make default blocksize transition matrix actually make the average + // blocksize equal to avgBlockSize. + state = params.BlockSizeTransitionMatrix().NextState(r, lastBlockSizeState) + + switch state { + case 0: + blockSize = r.Intn(avgBlockSize * 4) + + case 1: + blockSize = r.Intn(avgBlockSize * 2) + + default: + blockSize = 0 + } + + return state, blockSize +} + +func mustMarshalJSONIndent(o interface{}) []byte { + bz, err := json.MarshalIndent(o, "", " ") + if err != nil { + panic(fmt.Sprintf("failed to JSON encode: %s", err)) + } + + return bz +} + +// OperationInput is a struct that holds all the needed values to generate a tx and deliver it +type OperationInput struct { + R *rand.Rand + App *baseapp.BaseApp + TxGen client.TxConfig + Cdc *codec.ProtoCodec + Msg sdk.Msg + MsgType string + CoinsSpentInMsg sdk.Coins + Context sdk.Context + SimAccount simulation.Account + AccountKeeper AccountKeeper + Bankkeeper BankKeeper + ModuleName string +} + +// GenAndDeliverTxWithRandFees generates a transaction with a random fee and delivers it. +func GenAndDeliverTxWithRandFees(txCtx OperationInput) (simulation.OperationMsg, []simulation.FutureOperation, error) { + account := txCtx.AccountKeeper.GetAccount(txCtx.Context, txCtx.SimAccount.Address) + spendable := txCtx.Bankkeeper.SpendableCoins(txCtx.Context, account.GetAddress()) + + var fees sdk.Coins + var err error + + coins, hasNeg := spendable.SafeSub(txCtx.CoinsSpentInMsg) + if hasNeg { + return simulation.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "message doesn't leave room for fees"), nil, err + } + + spendableFeeCoins := coins.FilterDenoms([]string{sdk.DefaultBondDenom}) + fees, err = simulation.RandomFees(txCtx.R, txCtx.Context, spendableFeeCoins) + if err != nil { + return simulation.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to generate fees"), nil, err + } + return GenAndDeliverTx(txCtx, fees) +} + +// GenAndDeliverTx generates a transactions and delivers it. +func GenAndDeliverTx(txCtx OperationInput, fees sdk.Coins) (simulation.OperationMsg, []simulation.FutureOperation, error) { + account := txCtx.AccountKeeper.GetAccount(txCtx.Context, txCtx.SimAccount.Address) + tx, err := helpers.GenTx( + txCtx.TxGen, + []sdk.Msg{txCtx.Msg}, + fees, + helpers.DefaultGenTxGas, + txCtx.Context.ChainID(), + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + txCtx.SimAccount.PrivKey, + ) + + if err != nil { + return simulation.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to generate mock tx"), nil, err + } + + _, _, err = txCtx.App.Deliver(txCtx.TxGen.TxEncoder(), tx) + if err != nil { + return simulation.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to deliver tx"), nil, err + } + + return simulation.NewOperationMsg(txCtx.Msg, true, "", txCtx.Cdc), nil, nil +} diff --git a/simulation/types/account.go b/simulation/types/account.go new file mode 100644 index 00000000000..7b2f504d934 --- /dev/null +++ b/simulation/types/account.go @@ -0,0 +1,154 @@ +package simulation + +import ( + "fmt" + "math" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" +) + +func (sim *SimCtx) RandomSimAccount() simulation.Account { + return sim.randomSimAccount(sim.Accounts) +} + +func (sim *SimCtx) randomSimAccount(accs []simulation.Account) simulation.Account { + r := sim.GetSeededRand("select random account") + idx := r.Intn(len(accs)) + return accs[idx] +} + +type SimAccountConstraint = func(account simulation.Account) bool + +// returns acc, accExists := sim.RandomSimAccountWithConstraint(f) +// where acc is a uniformly sampled account from all accounts satisfying the constraint f +// a constraint is satisfied for an account `acc` if f(acc) = true +// accExists is false, if there is no such account. +func (sim *SimCtx) RandomSimAccountWithConstraint(f SimAccountConstraint) (simulation.Account, bool) { + filteredAddrs := []simulation.Account{} + for _, acc := range sim.Accounts { + if f(acc) { + filteredAddrs = append(filteredAddrs, acc) + } + } + + if len(filteredAddrs) == 0 { + return simulation.Account{}, false + } + return sim.randomSimAccount(filteredAddrs), true +} + +func (sim *SimCtx) RandomExistingAddress() sdk.AccAddress { + acc := sim.RandomSimAccount() + return acc.Address +} + +func (sim *SimCtx) AddAccount(acc simulation.Account) { + if _, found := sim.FindAccount(acc.Address); !found { + sim.Accounts = append(sim.Accounts, acc) + } +} + +// FindAccount iterates over all the simulation accounts to find the one that matches +// the given address +// TODO: Benchmark time in here, we should probably just make a hashmap indexing this. +func (sim *SimCtx) FindAccount(address sdk.Address) (simulation.Account, bool) { + for _, acc := range sim.Accounts { + if acc.Address.Equals(address) { + return acc, true + } + } + + return simulation.Account{}, false +} + +// Returns (account, randSubsetCoins, found), so if found = false, then no such address exists. +// randSubsetCoins is a random subset of the provided denoms, if the account is found. +// TODO: Write unit test +func (sim *SimCtx) SelAddrWithDenoms(ctx sdk.Context, denoms []string) (simulation.Account, sdk.Coins, bool) { + accHasDenoms := func(acc simulation.Account) bool { + for _, denom := range denoms { + if sim.App.GetBankKeeper().GetBalance(ctx, acc.Address, denom).Amount.IsZero() { + return false + } + } + return true + } + + acc, accExists := sim.RandomSimAccountWithConstraint(accHasDenoms) + if !accExists { + return acc, sdk.Coins{}, false + } + balance := sim.RandCoinSubset(ctx, acc.Address, denoms) + return acc, balance, true +} + +// RandGeometricCoin uniformly samples a denom from the addr's balances. +// Then it samples an Exponentially distributed amount of the addr's coins, with rate = 10. +// (Meaning that on average it samples 10% of the chosen balance) +func (sim *SimCtx) RandExponentialCoin(ctx sdk.Context, addr sdk.AccAddress) sdk.Coin { + balances := sim.App.GetBankKeeper().GetAllBalances(ctx, addr) + coin := RandSelect(sim, balances...) + // TODO: Reconsider if this becomes problematic in the future, but currently thinking it + // should be fine for simulation. + r := sim.GetSeededRand("Exponential distribution") + lambda := float64(10) + sample := r.ExpFloat64() / lambda + // truncate exp at 1, which will only be reached in .0045% of the time. + // .000045 ~= (1 - CDF(1, Exp[\lambda=10])) = e^{-10} + sample = math.Min(1, sample) + // Do some hacky scaling to get this into an SDK decimal, + // were going to treat it as an integer in the range [0, 10000] + maxRange := int64(10000) + intSample := int64(math.Round(sample * float64(maxRange))) + newAmount := coin.Amount.MulRaw(intSample).QuoRaw(maxRange) + return sdk.NewCoin(coin.Denom, newAmount) +} + +func (sim *SimCtx) RandCoinSubset(ctx sdk.Context, addr sdk.AccAddress, denoms []string) sdk.Coins { + subsetCoins := sdk.Coins{} + for _, denom := range denoms { + bal := sim.App.GetBankKeeper().GetBalance(ctx, addr, denom) + amt, err := sim.RandPositiveInt(bal.Amount) + if err != nil { + panic(err) + } + subsetCoins = subsetCoins.Add(sdk.NewCoin(bal.Denom, amt)) + } + return subsetCoins +} + +// RandomFees returns a random fee by selecting a random coin denomination and +// amount from the account's available balance. If the user doesn't have enough +// funds for paying fees, it returns empty coins. +func (sim *SimCtx) RandomFees(ctx sdk.Context, spendableCoins sdk.Coins) (sdk.Coins, error) { + if spendableCoins.Empty() { + return nil, nil + } + + // TODO: Revisit this + r := sim.GetRand() + perm := r.Perm(len(spendableCoins)) + var randCoin sdk.Coin + for _, index := range perm { + randCoin = spendableCoins[index] + if !randCoin.Amount.IsZero() { + break + } + } + + if randCoin.Amount.IsZero() { + return nil, fmt.Errorf("no coins found for random fees") + } + + amt, err := sim.RandPositiveInt(randCoin.Amount) + if err != nil { + return nil, err + } + + // Create a random fee and verify the fees are within the account's spendable + // balance. + fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) + + return fees, nil +} diff --git a/simulation/types/action.go b/simulation/types/action.go new file mode 100644 index 00000000000..2a4dc173153 --- /dev/null +++ b/simulation/types/action.go @@ -0,0 +1,98 @@ +package simulation + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" + + legacysimexec "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// Action represents a simulator action. +// The details of this struct are internal, +// we currently plan on maintaining 3 constructors for it. +// * ActionFromWeightedOperation - for legacy simulator compatibility +// * ActionFromMsg - An easy API to go from creating a message via simctx to something simulator can deal with +// * ActionFromDependentMessages - API for defining a series of messages that depend on one another, and should satisfy +// some properties post-execution. +type Action interface { + Name() string + // I envision this weight being provided from a config. + // Module providers can optionally provide a default from an enum, + // but this should not be the default. + // TODO: Maybe we make a "WithWeight" fn? + Weight() Weight + Execute(*SimCtx, sdk.Context) ( + OperationMsg simulation.OperationMsg, futureOps []simulation.FutureOperation, err error) +} + +type weightedOperationAction struct { + op simulation.WeightedOperation +} + +func (a weightedOperationAction) Name() string { return "weighted_op" } +func (a weightedOperationAction) Weight() Weight { return Weight(a.op.Weight()) } +func (a weightedOperationAction) Execute(sim *SimCtx, ctx sdk.Context) ( + simulation.OperationMsg, []simulation.FutureOperation, error) { + return a.op.Op()(sim.GetRand(), sim.App.GetBaseApp(), ctx, sim.Accounts, sim.ChainID) +} + +func ActionsFromWeightedOperations(ops legacysimexec.WeightedOperations) []Action { + actions := make([]Action, 0, len(ops)) + for _, op := range ops { + actions = append(actions, weightedOperationAction{op: op}) + } + return actions +} + +var _ Action = msgBasedAction{} + +func NewMsgBasedAction[M sdk.Msg](actionName string, msgGenerator func(sim *SimCtx, ctx sdk.Context) (M, error)) Action { + wrappedMsgGen := func(sim *SimCtx, ctx sdk.Context) (sdk.Msg, error) { + return msgGenerator(sim, ctx) + } + // TODO: This likely won't work, and we need to instead make a mock sim ctx and ctx to get this. + // TODO: Also do we even want this? Isn't the goal to write simulation event hooks based on Name + // var sampleMsg M + // msgName := osmoutils.GetType(sampleMsg) + return msgBasedAction{name: actionName, weight: Normal, msgGenerator: wrappedMsgGen} +} + +// TODO: Decide if I want NewMsgBasedAction to auto-curry +func CurryMsgGenerator[K interface{}, M sdk.Msg](k K, f func(K, *SimCtx, sdk.Context) (M, error)) func(*SimCtx, sdk.Context) (M, error) { + return func(sim *SimCtx, ctx sdk.Context) (M, error) { + return f(k, sim, ctx) + } +} + +func NewCurriedMsgBasedAction[K interface{}, M sdk.Msg](actionName string, k K, f func(K, *SimCtx, sdk.Context) (M, error)) Action { + msgGenerator := CurryMsgGenerator(k, f) + return NewMsgBasedAction(actionName, msgGenerator) +} + +type msgBasedAction struct { + name string + weight Weight + msgGenerator func(sim *SimCtx, ctx sdk.Context) (sdk.Msg, error) +} + +func (m msgBasedAction) WithWeight(weight Weight) msgBasedAction { + m.weight = weight + return m +} + +func (m msgBasedAction) Name() string { return m.name } +func (m msgBasedAction) Weight() Weight { return m.weight } +func (m msgBasedAction) Execute(sim *SimCtx, ctx sdk.Context) ( + OperationMsg simulation.OperationMsg, futureOps []simulation.FutureOperation, err error) { + msg, err := m.msgGenerator(sim, ctx) + if err != nil { + return simulation.NoOpMsg(m.name, m.name, fmt.Sprintf("unable to build msg due to: %v", err)), nil, nil + } + tx, err := sim.txbuilder(ctx, msg, m.name) + if err != nil { + return simulation.NoOpMsg(m.name, m.name, "unable to build tx"), nil, err + } + return sim.deliverTx(tx, msg, m.name) +} diff --git a/simulation/types/app.go b/simulation/types/app.go new file mode 100644 index 00000000000..e5a8e845bfc --- /dev/null +++ b/simulation/types/app.go @@ -0,0 +1,27 @@ +package simulation + +import ( + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +type App interface { + GetBaseApp() *baseapp.BaseApp + AppCodec() codec.Codec + GetAccountKeeper() AccountKeeper + GetBankKeeper() BankKeeper +} + +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI + // GetAllAccounts(ctx sdk.Context) []authtypes.AccountI +} + +type BankKeeper interface { + GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin + GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + // TODO: Revisit + SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins +} diff --git a/simulation/types/genesis_config.go b/simulation/types/genesis_config.go new file mode 100644 index 00000000000..3790f0acb0f --- /dev/null +++ b/simulation/types/genesis_config.go @@ -0,0 +1,34 @@ +package simulation + +// SimulationState is the input parameters used on each of the module's randomized +// GenesisState generator function +// type GenesisConfig struct { +// AppParams simulation.AppParams +// Cdc codec.JSONCodec // application codec +// Rand *rand.Rand // random number +// GenState map[string]json.RawMessage // genesis state +// Accounts []simulation.Account // simulation accounts +// InitialStake int64 // initial coins per account +// NumBonded int64 // number of initially bonded accounts +// GenTimestamp time.Time // genesis timestamp +// UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration +// ParamChanges []simulation.ParamChange // simulated parameter changes from modules +// Contents []simulation.WeightedProposalContent // proposal content generator functions with their default weight and app sim key +// } + +// LegacyConfig +// SimulationState is the input parameters used on each of the module's randomized +// GenesisState generator function +// type SimulationState struct { +// AppParams simulation.AppParams +// Cdc codec.JSONCodec // application codec +// Rand *rand.Rand // random number +// GenState map[string]json.RawMessage // genesis state +// Accounts []simulation.Account // simulation accounts +// InitialStake int64 // initial coins per account +// NumBonded int64 // number of initially bonded accounts +// GenTimestamp time.Time // genesis timestamp +// UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration +// ParamChanges []simulation.ParamChange // simulated parameter changes from modules +// Contents []simulation.WeightedProposalContent // proposal content generator functions with their default weight and app sim key +// } diff --git a/simulation/types/init_functions.go b/simulation/types/init_functions.go new file mode 100644 index 00000000000..b7009744d12 --- /dev/null +++ b/simulation/types/init_functions.go @@ -0,0 +1,57 @@ +package simulation + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" +) + +// TODO: Consider adding consensus parameters / simulator params / tendermint params to this. +type InitFunctions struct { + // Why does this take in Numkeys / why isn't this part of the initial state function / config to decide? + RandomAccountFn simulation.RandomAccountFn + AppInitialStateFn simulation.AppStateFn +} + +// TODO: cleanup args in the future, should ideally just be a slice. +func DefaultSimInitFunctions(moduleAccountAddresses map[string]bool) InitFunctions { + return InitFunctions{ + RandomAccountFn: WrapRandAccFnForResampling(RandomSimAccounts, moduleAccountAddresses), + } +} + +func WrapRandAccFnForResampling(randFn simulation.RandomAccountFn, blockList map[string]bool) simulation.RandomAccountFn { + // TODO: do resampling + return func(r *rand.Rand, n int) []simulation.Account { + initAccs := randFn(r, n) + cleanedAccs := make([]simulation.Account, 0, n) + for _, acc := range initAccs { + if _, contains := blockList[acc.Address.String()]; !contains { + cleanedAccs = append(cleanedAccs, acc) + } + } + return cleanedAccs + } +} + +// RandomAccounts generates n random accounts +func RandomSimAccounts(r *rand.Rand, n int) []simulation.Account { + accs := make([]simulation.Account, n) + + for i := 0; i < n; i++ { + // don't need that much entropy for simulation + privkeySeed := make([]byte, 15) + r.Read(privkeySeed) + + accs[i].PrivKey = secp256k1.GenPrivKeyFromSecret(privkeySeed) + accs[i].PubKey = accs[i].PrivKey.PubKey() + accs[i].Address = sdk.AccAddress(accs[i].PubKey.Address()) + + accs[i].ConsKey = ed25519.GenPrivKeyFromSecret(privkeySeed) + } + + return accs +} diff --git a/simulation/types/legacy.go b/simulation/types/legacy.go new file mode 100644 index 00000000000..3afee2e3970 --- /dev/null +++ b/simulation/types/legacy.go @@ -0,0 +1,80 @@ +package simulation + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/simapp/helpers" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx" +) + +// TODO: Must delete +func GenAndDeliverTxWithRandFees( + r *rand.Rand, + app *baseapp.BaseApp, + txGen client.TxConfig, + msg legacytx.LegacyMsg, + coinsSpentInMsg sdk.Coins, + ctx sdk.Context, + simAccount simulation.Account, + ak AccountKeeper, + bk BankKeeper, + moduleName string, +) (simulation.OperationMsg, []simulation.FutureOperation, error) { + account := ak.GetAccount(ctx, simAccount.Address) + spendable := bk.SpendableCoins(ctx, account.GetAddress()) + + var fees sdk.Coins + var err error + + coins, hasNeg := spendable.SafeSub(coinsSpentInMsg) + if hasNeg { + return simulation.NoOpMsg(moduleName, msg.Type(), "message doesn't leave room for fees"), nil, err + } + + // Only allow fees in "uosmo" + coins = sdk.NewCoins(sdk.NewCoin("uosmo", coins.AmountOf("uosmo"))) + + fees, err = simulation.RandomFees(r, ctx, coins) + if err != nil { + return simulation.NoOpMsg(moduleName, msg.Type(), "unable to generate fees"), nil, err + } + return GenAndDeliverTx(app, txGen, msg, fees, ctx, simAccount, ak, moduleName) +} + +// TODO: Must delete +func GenAndDeliverTx( + app *baseapp.BaseApp, + txGen client.TxConfig, + msg legacytx.LegacyMsg, + fees sdk.Coins, + ctx sdk.Context, + simAccount simulation.Account, + ak AccountKeeper, + moduleName string, +) (simulation.OperationMsg, []simulation.FutureOperation, error) { + account := ak.GetAccount(ctx, simAccount.Address) + tx, err := helpers.GenTx( + txGen, + []sdk.Msg{msg}, + fees, + helpers.DefaultGenTxGas, + ctx.ChainID(), + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + simAccount.PrivKey, + ) + if err != nil { + return simulation.NoOpMsg(moduleName, msg.Type(), "unable to generate mock tx"), nil, err + } + + _, _, err = app.Deliver(txGen.TxEncoder(), tx) + if err != nil { + return simulation.NoOpMsg(moduleName, msg.Type(), "unable to deliver tx"), nil, err + } + + return simulation.NewOperationMsg(msg, true, "", nil), nil, nil +} diff --git a/simulation/types/manager.go b/simulation/types/manager.go new file mode 100644 index 00000000000..1f0270d354b --- /dev/null +++ b/simulation/types/manager.go @@ -0,0 +1,142 @@ +package simulation + +import ( + "encoding/json" + "io/ioutil" + "math/rand" + "sort" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/types/simulation" + "golang.org/x/exp/maps" +) + +// AppModuleSimulation defines the standard functions that every module should expose +// for the SDK blockchain simulator +type AppModuleSimulationV2 interface { + module.AppModule + + // randomized genesis states + // TODO: Come back and improve SimulationState interface + // TODO: Move this to an extension interface + // default: simState.GenState[types.ModuleName] = app.DefaultGenesis(simState.Cdc) + GenerateGenesisState(*module.SimulationState, *SimCtx) + Actions() []Action + // PropertyTests() +} + +// SimulationManager defines a simulation manager that provides the high level utility +// for managing and executing simulation functionalities for a group of modules +type Manager struct { + moduleManager module.Manager + Modules map[string]AppModuleSimulationV2 // map of all non-legacy app modules; + legacyModules map[string]module.AppModuleSimulation // legacy app modules +} + +func NewSimulationManager(manager module.Manager, overrideModules map[string]module.AppModuleSimulation) Manager { + if manager.OrderInitGenesis == nil { + panic("manager.OrderInitGenesis is unset, needs to be set prior to creating simulation manager") + } + + simModules := map[string]AppModuleSimulationV2{} + legacySimModules := map[string]module.AppModuleSimulation{} + appModuleNamesSorted := maps.Keys(manager.Modules) + sort.Strings(appModuleNamesSorted) + + for _, moduleName := range appModuleNamesSorted { + // for every module, see if we override it. If so, use override. + // Else, if we can cast the app module into a simulation module add it. + // otherwise no simulation module. + if simModule, ok := overrideModules[moduleName]; ok { + legacySimModules[moduleName] = simModule + } else { + appModule := manager.Modules[moduleName] + if simModule, ok := appModule.(AppModuleSimulationV2); ok { + simModules[moduleName] = simModule + } else if simModule, ok := appModule.(module.AppModuleSimulation); ok { + legacySimModules[moduleName] = simModule + } + // cannot cast, so we continue + } + } + return Manager{moduleManager: manager, legacyModules: legacySimModules, Modules: simModules} +} + +func loadAppParamsForWasm(path string) simulation.AppParams { + bz, err := ioutil.ReadFile(path) + if err != nil { + panic(err) + } + + appParams := make(simulation.AppParams) + err = json.Unmarshal(bz, &appParams) + if err != nil { + panic(err) + } + return appParams +} + +func (m Manager) legacyActions(seed int64, cdc codec.JSONCodec) []Action { + // We do not support the legacy simulator config format, and just (unfortunately) + // hardcode this one filepath for wasm. + // TODO: Clean this up / make a better plan + + simState := module.SimulationState{ + AppParams: loadAppParamsForWasm("params.json"), + ParamChanges: []simulation.ParamChange{}, + Contents: []simulation.WeightedProposalContent{}, + Cdc: cdc, + } + + r := rand.New(rand.NewSource(seed)) + // first pass generate randomized params + proposal contents + for _, moduleName := range m.moduleManager.OrderInitGenesis { + if simModule, ok := m.legacyModules[moduleName]; ok { + simState.ParamChanges = append(simState.ParamChanges, simModule.RandomizedParams(r)...) + simState.Contents = append(simState.Contents, simModule.ProposalContents(simState)...) + } + } + // second pass generate actions + weightedOps := []simulation.WeightedOperation{} + for _, moduleName := range m.moduleManager.OrderInitGenesis { + if simModule, ok := m.legacyModules[moduleName]; ok { + weightedOps = append(weightedOps, simModule.WeightedOperations(simState)...) + } + } + return ActionsFromWeightedOperations(weightedOps) +} + +// TODO: Can we use sim here instead? Perhaps by passing in the simulation module manager to the simulator. +func (m Manager) Actions(seed int64, cdc codec.JSONCodec) []Action { + actions := m.legacyActions(seed, cdc) + for _, simModule := range m.Modules { + actions = append(actions, simModule.Actions()...) + } + return actions +} + +// TODO: Fix this +// Unfortunately I'm temporarily giving up on fixing genesis logic, its very screwed up in the legacy designs +// and I want to move on to the more interesting goals of this simulation refactor. +// We do need to come back and un-screw up alot of this genesis work. +// +// Thankfully for Osmosis-custom modules, we don't really care about genesis logic. (yet) +// The architectural errors for future readers revolve around on the design of the +// * Design of the AppStateFn (just look at it, osmosis/simapp/state.go) +// * Abstraction leaks overt amounts of code riddle it! +// * Configs being read key by key per module via AppParams, should be a typed config +// * Operation/Action weights being read from params, rather than from come generic config loading +// * every module not just returning a genesis struct, and instead mutating things in place +// The only error corrected in the genesis work over what was present in prior code is: +// better rand handling (simCtx), and calling genesis in the InitGenesis ordering. +func (m Manager) GenerateGenesisStates(simState *module.SimulationState, sim *SimCtx) { + for _, moduleName := range m.moduleManager.OrderInitGenesis { + if simModule, ok := m.Modules[moduleName]; ok { + simModule.GenerateGenesisState(simState, sim) + } + if simModule, ok := m.legacyModules[moduleName]; ok { + simModule.GenerateGenesisState(simState) + } + } +} diff --git a/simulation/types/random/sdkrand.go b/simulation/types/random/sdkrand.go new file mode 100644 index 00000000000..a2ab78b86aa --- /dev/null +++ b/simulation/types/random/sdkrand.go @@ -0,0 +1,168 @@ +package sdkrand + +import ( + "errors" + "math/big" + "math/rand" + "time" + "unsafe" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + letterIdxBits = 6 // 6 bits to represent a letter index + letterIdxMask = 1<= 0; { + if remain == 0 { + cache, remain = r.Int63(), letterIdxMax + } + if idx := int(cache & letterIdxMask); idx < len(letterBytes) { + b[i] = letterBytes[idx] + i-- + } + cache >>= letterIdxBits + remain-- + } + + return *(*string)(unsafe.Pointer(&b)) +} + +// RandPositiveInt get a rand positive sdk.Int +func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { + if !max.GTE(sdk.OneInt()) { + return sdk.Int{}, errors.New("max too small") + } + + max = max.Sub(sdk.OneInt()) + + return sdk.NewIntFromBigInt(new(big.Int).Rand(r, max.BigInt())).Add(sdk.OneInt()), nil +} + +// RandomAmount generates a random amount +// Note: The range of RandomAmount includes max, and is, in fact, biased to return max as well as 0. +func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int { + var randInt = big.NewInt(0) + + switch r.Intn(10) { + case 0: + // randInt = big.NewInt(0) + case 1: + randInt = max.BigInt() + default: // NOTE: there are 10 total cases. + randInt = big.NewInt(0).Rand(r, max.BigInt()) // up to max - 1 + } + + return sdk.NewIntFromBigInt(randInt) +} + +// RandomDecAmount generates a random decimal amount +// Note: The range of RandomDecAmount includes max, and is, in fact, biased to return max as well as 0. +func RandomDecAmount(r *rand.Rand, max sdk.Dec) sdk.Dec { + var randInt = big.NewInt(0) + + switch r.Intn(10) { + case 0: + // randInt = big.NewInt(0) + case 1: + randInt = max.BigInt() // the underlying big int with all precision bits. + default: // NOTE: there are 10 total cases. + randInt = big.NewInt(0).Rand(r, max.BigInt()) + } + + return sdk.NewDecFromBigIntWithPrec(randInt, sdk.Precision) +} + +// RandTimestamp generates a random timestamp +func RandTimestamp(r *rand.Rand) time.Time { + // json.Marshal breaks for timestamps greater with year greater than 9999 + unixTime := r.Int63n(253373529600) + return time.Unix(unixTime, 0) +} + +// RandIntBetween returns a random int between two numbers inclusively. +func RandIntBetween(r *rand.Rand, min, max int) int { + return r.Intn(max-min) + min +} + +// returns random subset of the provided coins +// will return at least one coin unless coins argument is empty or malformed +// i.e. 0 amt in coins +func RandSubsetCoins(r *rand.Rand, coins sdk.Coins) sdk.Coins { + if len(coins) == 0 { + return sdk.Coins{} + } + // make sure at least one coin added + denomIdx := r.Intn(len(coins)) + coin := coins[denomIdx] + amt, err := RandPositiveInt(r, coin.Amount) + // malformed coin. 0 amt in coins + if err != nil { + return sdk.Coins{} + } + + subset := sdk.Coins{sdk.NewCoin(coin.Denom, amt)} + + for i, c := range coins { + // skip denom that we already chose earlier + if i == denomIdx { + continue + } + // coin flip if multiple coins + // if there is single coin then return random amount of it + if r.Intn(2) == 0 && len(coins) != 1 { + continue + } + + amt, err := RandPositiveInt(r, c.Amount) + // ignore errors and try another denom + if err != nil { + continue + } + + subset = append(subset, sdk.NewCoin(c.Denom, amt)) + } + + return subset.Sort() +} + +// DeriveRand derives a new Rand deterministically from another random source. +// Unlike rand.New(rand.NewSource(seed)), the result is "more random" +// depending on the source and state of r. +// +// NOTE: not crypto safe. +func DeriveRand(r *rand.Rand) *rand.Rand { + const num = 8 // TODO what's a good number? Too large is too slow. + ms := multiSource(make([]rand.Source, num)) + + for i := 0; i < num; i++ { + ms[i] = rand.NewSource(r.Int63()) + } + + return rand.New(ms) +} + +type multiSource []rand.Source + +func (ms multiSource) Int63() (r int64) { + for _, source := range ms { + r ^= source.Int63() + } + + return r +} + +func (ms multiSource) Seed(seed int64) { + panic("multiSource Seed should not be called") +} diff --git a/simulation/types/randutil.go b/simulation/types/randutil.go new file mode 100644 index 00000000000..093c164fd55 --- /dev/null +++ b/simulation/types/randutil.go @@ -0,0 +1,72 @@ +package simulation + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "golang.org/x/exp/constraints" + + sdkrand "github.com/osmosis-labs/osmosis/v7/simulation/types/random" +) + +func RandLTBound[T constraints.Integer](sim *SimCtx, upperbound T) T { + return RandLTEBound(sim, upperbound-T(1)) +} + +func RandLTEBound[T constraints.Integer](sim *SimCtx, upperbound T) T { + max := int(upperbound) + r := sim.RandIntBetween(0, max+1) + t := T(r) + return t +} + +func RandSelect[T interface{}](sim *SimCtx, args ...T) T { + choice := RandLTBound(sim, len(args)) + return args[choice] +} + +// RandStringOfLength generates a random string of a particular length +func (sim *SimCtx) RandStringOfLength(n int) string { + r := sim.GetSeededRand("random string of bounded length") + return sdkrand.RandStringOfLength(r, n) +} + +// RandPositiveInt get a rand positive sdk.Int +func (sim *SimCtx) RandPositiveInt(max sdk.Int) (sdk.Int, error) { + r := sim.GetSeededRand("random bounded positive int") + return sdkrand.RandPositiveInt(r, max) +} + +// RandomAmount generates a random amount +// that is biased to return max and 0. +func (sim *SimCtx) RandomAmount(max sdk.Int) sdk.Int { + r := sim.GetSeededRand("random bounded positive int") + return sdkrand.RandomAmount(r, max) +} + +// RandomDecAmount generates a random decimal amount +// Note: The range of RandomDecAmount includes max, and is, in fact, biased to return max as well as 0. +func (sim *SimCtx) RandomDecAmount(max sdk.Dec) sdk.Dec { + r := sim.GetSeededRand("random bounded positive int") + return sdkrand.RandomDecAmount(r, max) +} + +// RandTimestamp generates a random timestamp +func (sim *SimCtx) RandTimestamp() time.Time { + r := sim.GetSeededRand("random timestamp") + return sdkrand.RandTimestamp(r) +} + +// RandIntBetween returns a random int between two numbers, inclusive of min, exclusive of max. +func (sim *SimCtx) RandIntBetween(min, max int) int { + r := sim.GetSeededRand("random int between") + return sdkrand.RandIntBetween(r, min, max) +} + +// returns random subset of the provided coins +// will return at least one coin unless coins argument is empty or malformed +// i.e. 0 amt in coins +func (sim *SimCtx) RandSubsetCoins(coins sdk.Coins) sdk.Coins { + r := sim.GetSeededRand("random subset coins") + return sdkrand.RandSubsetCoins(r, coins) +} diff --git a/simulation/types/simctx.go b/simulation/types/simctx.go new file mode 100644 index 00000000000..b7826787777 --- /dev/null +++ b/simulation/types/simctx.go @@ -0,0 +1,55 @@ +package simulation + +import ( + "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types/simulation" +) + +//nolint:structcheck +//TODO: Contemplate name better +type SimCtx struct { + r *rand.Rand + // TODO: delete this, once we cleanup simulator initialization logic, + // and can then setup SimCtx with base seed. + internalSeed int64 + rCounter int64 + seededMap map[string]*rand.Rand + + App App + Accounts []simulation.Account + Cdc codec.JSONCodec // application codec + ChainID string + + txbuilder func(ctx sdk.Context, msg sdk.Msg, msgName string) (sdk.Tx, error) +} + +func NewSimCtx(r *rand.Rand, app App, accounts []simulation.Account, chainID string) *SimCtx { + sim := &SimCtx{ + r: r, + internalSeed: r.Int63(), + rCounter: 0, + seededMap: map[string]*rand.Rand{}, + + App: app, + Accounts: accounts, + ChainID: chainID, + } + sim.txbuilder = sim.defaultTxBuilder + return sim +} + +func (sim *SimCtx) GetRand() *rand.Rand { + sim.rCounter += 1 + r := rand.New(rand.NewSource(sim.internalSeed + sim.rCounter)) + return r +} + +// TODO: Refactor to eventually seed a new prng from seed +// and maintain a cache of seed -> rand +func (sim *SimCtx) GetSeededRand(seed string) *rand.Rand { + return sim.r +} diff --git a/simulation/types/transitionmatrix/transition_matrix.go b/simulation/types/transitionmatrix/transition_matrix.go new file mode 100644 index 00000000000..737041d0ce7 --- /dev/null +++ b/simulation/types/transitionmatrix/transition_matrix.go @@ -0,0 +1,80 @@ +package markov + +import ( + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/types/simulation" +) + +// TransitionMatrix is _almost_ a left stochastic matrix. It is technically +// not one due to not normalizing the column values. In the future, if we want +// to find the steady state distribution, it will be quite easy to normalize +// these values to get a stochastic matrix. Floats aren't currently used as +// the default due to non-determinism across architectures +type TransitionMatrix struct { + weights [][]int + // total in each column + totals []int + n int +} + +// CreateTransitionMatrix creates a transition matrix from the provided weights. +// TODO: Provide example usage +func CreateTransitionMatrix(weights [][]int) (simulation.TransitionMatrix, error) { + n := len(weights) + for i := 0; i < n; i++ { + if len(weights[i]) != n { + return TransitionMatrix{}, + fmt.Errorf("transition matrix: non-square matrix provided, error on row %d", i) + } + } + + totals := make([]int, n) + + for row := 0; row < n; row++ { + for col := 0; col < n; col++ { + totals[col] += weights[row][col] + } + } + + return TransitionMatrix{weights, totals, n}, nil +} + +// NextState returns the next state randomly chosen using r, and the weightings +// provided in the transition matrix. +func (t TransitionMatrix) NextState(r *rand.Rand, i int) int { + randNum := r.Intn(t.totals[i]) + for row := 0; row < t.n; row++ { + if randNum < t.weights[row][i] { + return row + } + + randNum -= t.weights[row][i] + } + // This line should never get executed + return -1 +} + +// GetMemberOfInitialState takes an initial array of weights, of size n. +// It returns a weighted random number in [0,n). +func GetMemberOfInitialState(r *rand.Rand, weights []int) int { + n := len(weights) + total := 0 + + for i := 0; i < n; i++ { + total += weights[i] + } + + randNum := r.Intn(total) + + for state := 0; state < n; state++ { + if randNum < weights[state] { + return state + } + + randNum -= weights[state] + } + // This line should never get executed + return -1 +} diff --git a/simulation/types/txbuilder.go b/simulation/types/txbuilder.go new file mode 100644 index 00000000000..7a432dc411c --- /dev/null +++ b/simulation/types/txbuilder.go @@ -0,0 +1,59 @@ +package simulation + +import ( + "errors" + "fmt" + + "github.com/cosmos/cosmos-sdk/simapp/helpers" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" + + "github.com/osmosis-labs/osmosis/v7/app/params" +) + +//nolint:deadcode,unused +func noopTxBuilder() func(ctx sdk.Context, msg sdk.Msg) (sdk.Tx, error) { + return func(sdk.Context, sdk.Msg) (sdk.Tx, error) { return nil, errors.New("unimplemented") } +} + +// TODO: Comeback and clean this up to not suck +func (sim *SimCtx) defaultTxBuilder( + ctx sdk.Context, + msg sdk.Msg, + msgName string, // TODO fix +) (sdk.Tx, error) { + account, found := sim.FindAccount(msg.GetSigners()[0]) + if !found { + return nil, errors.New("unable to generate mock tx: sim acct not found") + } + authAcc := sim.App.GetAccountKeeper().GetAccount(ctx, account.Address) + txConfig := params.MakeEncodingConfig().TxConfig // TODO: unhardcode + // TODO: Consider making a default tx builder that charges some random fees + // Low value for amount of work right now though. + fees := sdk.Coins{} + tx, err := helpers.GenTx( + txConfig, + []sdk.Msg{msg}, + fees, + helpers.DefaultGenTxGas, + ctx.ChainID(), + []uint64{authAcc.GetAccountNumber()}, + []uint64{authAcc.GetSequence()}, + account.PrivKey, + ) + if err != nil { + return nil, fmt.Errorf("unable to generate mock tx %v", err) + } + return tx, nil +} + +// TODO: Fix these args +func (sim *SimCtx) deliverTx(tx sdk.Tx, msg sdk.Msg, msgName string) (simulation.OperationMsg, []simulation.FutureOperation, error) { + txConfig := params.MakeEncodingConfig().TxConfig // TODO: unhardcode + _, _, err := sim.App.GetBaseApp().Deliver(txConfig.TxEncoder(), tx) + if err != nil { + return simulation.NoOpMsg(msgName, msgName, "unable to deliver tx"), nil, err + } + + return simulation.NewOperationMsg(msg, true, "", nil), nil, nil +} diff --git a/simulation/types/weight.go b/simulation/types/weight.go new file mode 100644 index 00000000000..bd5f2e1f1b9 --- /dev/null +++ b/simulation/types/weight.go @@ -0,0 +1,11 @@ +package simulation + +type Weight int64 + +const ( + Undefined Weight = 0 + Rare = 1 + Infrequent = 5 + Normal = 10 + Frequent = 20 +) diff --git a/x/gamm/keeper/pool.go b/x/gamm/keeper/pool.go index e3639c2d85e..0a4bd46a814 100644 --- a/x/gamm/keeper/pool.go +++ b/x/gamm/keeper/pool.go @@ -24,6 +24,7 @@ func (k Keeper) UnmarshalPool(bz []byte) (types.PoolI, error) { // GetPoolAndPoke returns a PoolI based on it's identifier if one exists. Prior // to returning the pool, the weights of the pool are updated via PokePool. +// TODO: Consider rename to GetPool due to downstream API confusion. func (k Keeper) GetPoolAndPoke(ctx sdk.Context, poolId uint64) (types.PoolI, error) { store := ctx.KVStore(k.storeKey) poolKey := types.GetKeyPrefixPools(poolId) diff --git a/x/gamm/module.go b/x/gamm/module.go index 596e57830ce..df389ae704e 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -16,9 +16,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" "github.com/osmosis-labs/osmosis/v7/x/gamm/client/cli" "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" + gammsimulation "github.com/osmosis-labs/osmosis/v7/x/gamm/simulation" "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) @@ -154,3 +156,15 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 1 } + +// **** simulation implementation **** +func (am AppModule) GenerateGenesisState(m *module.SimulationState, s *simulation.SimCtx) { + m.GenState[types.ModuleName] = am.DefaultGenesis(m.Cdc) +} + +func (am AppModule) Actions() []simulation.Action { + return []simulation.Action{ + simulation.NewMsgBasedAction("MsgJoinPool", gammsimulation.CurrySimMsgJoinPool(am.keeper)), + simulation.NewCurriedMsgBasedAction("Msg create univ2 pool", am.keeper, gammsimulation.RandomCreateUniv2PoolMsg), + } +} diff --git a/x/gamm/simulation/sim_msgs.go b/x/gamm/simulation/sim_msgs.go new file mode 100644 index 00000000000..29841a1c087 --- /dev/null +++ b/x/gamm/simulation/sim_msgs.go @@ -0,0 +1,52 @@ +package gammsimulation + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/server/rosetta/lib/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/osmosis-labs/osmosis/v7/osmoutils" + simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" + "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" + balancertypes "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" + gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +func CurrySimMsgJoinPool(k keeper.Keeper) func(sim *simulation.SimCtx, ctx sdk.Context) (*gammtypes.MsgJoinPool, error) { + return func(sim *simulation.SimCtx, ctx sdk.Context) (*gammtypes.MsgJoinPool, error) { + return RandomJoinPoolMsg(k, sim, ctx) + } +} + +func RandomJoinPoolMsg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*gammtypes.MsgJoinPool, error) { + // Get pool + pool_id := simulation.RandLTBound(sim, k.GetNextPoolNumber(ctx)) + pool, err := k.GetPoolAndPoke(ctx, pool_id) + if err != nil { + return &gammtypes.MsgJoinPool{}, err + } + // Get address that has all denoms in the pool + poolDenoms := osmoutils.CoinsDenoms(pool.GetTotalPoolLiquidity(ctx)) + sender, tokenInMaxs, senderExists := sim.SelAddrWithDenoms(ctx, poolDenoms) + if !senderExists { + return &gammtypes.MsgJoinPool{}, fmt.Errorf("no sender with denoms %s exists", poolDenoms) + } + // TODO: Make FuzzTokenSubset API, token_in_maxs := sim.FuzzTokensSubset(sender, poolDenoms) + // TODO: Add some slippage tolerance + minShareOutAmt, _, _ := pool.CalcJoinPoolShares(ctx, tokenInMaxs, pool.GetSwapFee(ctx)) + // TODO: Make MinShareOutAmt fuzz API: minShareOutAmt = sim.FuzzEqualInt(share_out_amount) + return &gammtypes.MsgJoinPool{ + Sender: sender.Address.String(), + PoolId: pool_id, + ShareOutAmount: minShareOutAmt, + TokenInMaxs: tokenInMaxs, + }, nil +} + +func RandomCreateUniv2PoolMsg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*balancertypes.MsgCreateBalancerPool, error) { + // 1) Select two denoms, ideally with some frequency weighting based on distribution amongst addrs + // 2) Select sender with both denoms + creation fee + // 3) Create pool + return nil, errors.ErrNotImplemented +} diff --git a/x/incentives/simulation/operations.go b/x/incentives/simulation/operations.go index 22ec9f383d4..f1e656150eb 100644 --- a/x/incentives/simulation/operations.go +++ b/x/incentives/simulation/operations.go @@ -4,7 +4,7 @@ import ( "math/rand" "time" - osmo_simulation "github.com/osmosis-labs/osmosis/v7/x/simulation" + osmo_simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" "github.com/cosmos/cosmos-sdk/baseapp" @@ -133,8 +133,8 @@ func SimulateMsgCreateGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankK } msg := types.MsgCreateGauge{ - IsPerpetual: isPerpetual, Owner: simAccount.Address.String(), + IsPerpetual: isPerpetual, DistributeTo: distributeTo, Coins: rewards, StartTime: startTime, diff --git a/x/lockup/module.go b/x/lockup/module.go index 1157559f32e..05de92c6caf 100644 --- a/x/lockup/module.go +++ b/x/lockup/module.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "math/rand" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" @@ -16,13 +15,14 @@ import ( cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" "github.com/osmosis-labs/osmosis/v7/x/lockup/client/cli" "github.com/osmosis-labs/osmosis/v7/x/lockup/client/rest" "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - "github.com/osmosis-labs/osmosis/v7/x/lockup/simulation" + + locksimulation "github.com/osmosis-labs/osmosis/v7/x/lockup/simulation" "github.com/osmosis-labs/osmosis/v7/x/lockup/types" ) @@ -178,37 +178,23 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val return []abci.ValidatorUpdate{} } +// ConsensusVersion implements AppModule/ConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return 1 } + // ___________________________________________________________________________ -// AppModuleSimulation functions +// AppModuleSimulationV2 functions // GenerateGenesisState creates a randomized GenState of the pool-incentives module. -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - // TODO -} - -// ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { - return nil // TODO -} - -// RandomizedParams creates randomized pool-incentives param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { - return nil // TODO -} - -// RegisterStoreDecoder registers a decoder for supply module's types. -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - // TODO +func (am AppModule) GenerateGenesisState(simState *module.SimulationState, s *simulation.SimCtx) { + simState.GenState[types.ModuleName] = am.DefaultGenesis(simState.Cdc) } // WeightedOperations returns the all the lockup module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, - am.accountKeeper, am.bankKeeper, am.keeper, - ) +func (am AppModule) Actions() []simulation.Action { + return []simulation.Action{ + simulation.NewCurriedMsgBasedAction("lock tokens", am.keeper, locksimulation.RandomMsgLockTokens), + simulation.NewCurriedMsgBasedAction("unlock all tokens", am.keeper, locksimulation.RandomMsgBeginUnlockingAll), + simulation.NewCurriedMsgBasedAction("unlock lock", am.keeper, locksimulation.RandomMsgBeginUnlocking), + } } - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } diff --git a/x/lockup/simulation/operations.go b/x/lockup/simulation/operations.go index 084bf7411e7..f815a2afa59 100644 --- a/x/lockup/simulation/operations.go +++ b/x/lockup/simulation/operations.go @@ -1,177 +1,55 @@ package simulation import ( - "math/rand" + "errors" "time" - osmo_simulation "github.com/osmosis-labs/osmosis/v7/x/simulation" - - "github.com/cosmos/cosmos-sdk/baseapp" + legacysimulationtype "github.com/cosmos/cosmos-sdk/types/simulation" + simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/cosmos/cosmos-sdk/codec" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// Simulation operation weights constants. -const ( - DefaultWeightMsgLockTokens int = 10 - DefaultWeightMsgBeginUnlockingAll int = 10 - DefaultWeightMsgBeginUnlocking int = 10 - OpWeightMsgLockTokens = "op_weight_msg_create_lockup" - OpWeightMsgBeginUnlockingAll = "op_weight_msg_begin_unlocking_all" - OpWeightMsgBeginUnlocking = "op_weight_msg_begin_unlocking" ) -// WeightedOperations returns all the operations from the module with their respective weights. -func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, ak stakingTypes.AccountKeeper, - bk stakingTypes.BankKeeper, k keeper.Keeper, -) simulation.WeightedOperations { - var ( - weightMsgLockTokens int - weightMsgBeginUnlockingAll int - weightMsgBeginUnlocking int - ) - - appParams.GetOrGenerate(cdc, OpWeightMsgLockTokens, &weightMsgLockTokens, nil, - func(_ *rand.Rand) { - weightMsgLockTokens = DefaultWeightMsgLockTokens - weightMsgBeginUnlockingAll = DefaultWeightMsgBeginUnlockingAll - weightMsgBeginUnlocking = DefaultWeightMsgBeginUnlocking - }, - ) - - return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgLockTokens, - SimulateMsgLockTokens(ak, bk, k), - ), - simulation.NewWeightedOperation( - weightMsgBeginUnlockingAll, - SimulateMsgBeginUnlockingAll(ak, bk, k), - ), - simulation.NewWeightedOperation( - weightMsgBeginUnlocking, - SimulateMsgBeginUnlocking(ak, bk, k), - ), - } -} - -func genLockTokens(r *rand.Rand, acct simtypes.Account, coins sdk.Coins) (res sdk.Coins) { - numCoins := 1 + r.Intn(Min(coins.Len(), 6)) - denomIndices := r.Perm(numCoins) - for i := 0; i < numCoins; i++ { - denom := coins[denomIndices[i]].Denom - amt, _ := simtypes.RandPositiveInt(r, coins[i].Amount) - res = append(res, sdk.Coin{Denom: denom, Amount: amt}) - } - - res.Sort() - return -} - -func Min(x, y int) int { - if x < y { - return x - } - return y -} - -func Max(x, y int) int { - if x > y { - return x - } - return y +func RandomMsgLockTokens(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgLockTokens, error) { + sender := sim.RandomSimAccount() + lockCoins := sim.RandExponentialCoin(ctx, sender.Address) + duration := simulation.RandSelect(sim, time.Minute, time.Hour, time.Hour*24) + return &types.MsgLockTokens{ + Owner: sender.Address.String(), + Duration: duration, + Coins: sdk.Coins{lockCoins}, + }, nil } -// SimulateMsgLockTokens generates a MsgLockTokens with random values. -func SimulateMsgLockTokens(ak stakingTypes.AccountKeeper, bk stakingTypes.BankKeeper, k keeper.Keeper) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - simCoins := bk.SpendableCoins(ctx, simAccount.Address) - if simCoins.Len() <= 0 { - return simtypes.NoOpMsg( - types.ModuleName, types.TypeMsgLockTokens, "Account have no coin"), nil, nil - } - lockTokens := genLockTokens(r, simAccount, simCoins) - - durationSecs := r.Intn(1 * 60 * 60 * 24 * 7) // range of 1 week - duration := time.Duration(durationSecs) * time.Second - - msg := types.MsgLockTokens{ - Owner: simAccount.Address.String(), - Duration: duration, - Coins: lockTokens, - } - - txGen := simappparams.MakeTestEncodingConfig().TxConfig - return osmo_simulation.GenAndDeliverTxWithRandFees( - r, app, txGen, &msg, lockTokens, ctx, simAccount, ak, bk, types.ModuleName) - } +func RandomMsgBeginUnlockingAll(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgBeginUnlockingAll, error) { + sender := sim.RandomSimAccount() + return &types.MsgBeginUnlockingAll{ + Owner: sender.Address.String(), + }, nil } -func SimulateMsgBeginUnlockingAll(ak stakingTypes.AccountKeeper, bk stakingTypes.BankKeeper, k keeper.Keeper) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - simCoins := bk.SpendableCoins(ctx, simAccount.Address) - if simCoins.Len() <= 0 { - return simtypes.NoOpMsg( - types.ModuleName, types.TypeMsgBeginUnlockingAll, "Account have no coin"), nil, nil - } - - msg := types.MsgBeginUnlockingAll{ - Owner: simAccount.Address.String(), - } - - txGen := simappparams.MakeTestEncodingConfig().TxConfig - return osmo_simulation.GenAndDeliverTxWithRandFees( - r, app, txGen, &msg, nil, ctx, simAccount, ak, bk, types.ModuleName) +func RandomMsgBeginUnlocking(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgBeginUnlocking, error) { + sender, senderExists := sim.RandomSimAccountWithConstraint(accountHasLockConstraint(k, ctx)) + if !senderExists { + return nil, errors.New("no addr has created a lock") } + lock := randLock(k, sim, ctx, sender.Address) + return &types.MsgBeginUnlocking{ + Owner: sender.Address.String(), + ID: lock.ID, + }, nil } -func SimulateMsgBeginUnlocking(ak stakingTypes.AccountKeeper, bk stakingTypes.BankKeeper, k keeper.Keeper) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - simCoins := bk.SpendableCoins(ctx, simAccount.Address) - if simCoins.Len() <= 0 { - return simtypes.NoOpMsg( - types.ModuleName, types.TypeMsgBeginUnlocking, "Account have no coin"), nil, nil - } - - lock := RandomAccountLock(ctx, r, k, simAccount.Address) - if lock == nil { - return simtypes.NoOpMsg( - types.ModuleName, types.TypeMsgBeginUnlocking, "Account have no period lock"), nil, nil - } - - msg := types.MsgBeginUnlocking{ - Owner: simAccount.Address.String(), - ID: lock.ID, - } - - txGen := simappparams.MakeTestEncodingConfig().TxConfig - return osmo_simulation.GenAndDeliverTxWithRandFees( - r, app, txGen, &msg, nil, ctx, simAccount, ak, bk, types.ModuleName) +func accountHasLockConstraint(k keeper.Keeper, ctx sdk.Context) simulation.SimAccountConstraint { + return func(acc legacysimulationtype.Account) bool { + return len(k.GetAccountPeriodLocks(ctx, acc.Address)) != 0 } } -func RandomAccountLock(ctx sdk.Context, r *rand.Rand, k keeper.Keeper, addr sdk.AccAddress) *types.PeriodLock { +func randLock(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context, addr sdk.AccAddress) types.PeriodLock { locks := k.GetAccountPeriodLocks(ctx, addr) - if len(locks) == 0 { - return nil - } - return &locks[r.Intn(len(locks))] + return simulation.RandSelect(sim, locks...) } diff --git a/x/simulation/mod.go b/x/simulation/mod.go deleted file mode 100644 index 736b2ee6bc5..00000000000 --- a/x/simulation/mod.go +++ /dev/null @@ -1,100 +0,0 @@ -package simulation - -import ( - "math/rand" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/simapp/helpers" - - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx" - stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -type SimulationContext struct { - R *rand.Rand - SdkCtx sdk.Context - App *baseapp.BaseApp - Accs []simtypes.Account - simAccount *simtypes.Account -} - -func NewSimulationContext(r *rand.Rand, ctx sdk.Context, app *baseapp.BaseApp, accs []simtypes.Account) SimulationContext { - return SimulationContext{r, ctx, app, accs, nil} -} - -func (ctx *SimulationContext) GetMsgSender() simtypes.Account { - if ctx.simAccount == nil { - sel := ctx.R.Intn(len(ctx.Accs)) - ctx.simAccount = &ctx.Accs[sel] - } - return *ctx.simAccount -} - -func GenAndDeliverTxWithRandFees( - r *rand.Rand, - app *baseapp.BaseApp, - txGen client.TxConfig, - msg legacytx.LegacyMsg, - coinsSpentInMsg sdk.Coins, - ctx sdk.Context, - simAccount simtypes.Account, - ak stakingTypes.AccountKeeper, - bk stakingTypes.BankKeeper, - moduleName string, -) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - account := ak.GetAccount(ctx, simAccount.Address) - spendable := bk.SpendableCoins(ctx, account.GetAddress()) - - var fees sdk.Coins - var err error - - coins, hasNeg := spendable.SafeSub(coinsSpentInMsg) - if hasNeg { - return simtypes.NoOpMsg(moduleName, msg.Type(), "message doesn't leave room for fees"), nil, err - } - - // Only allow fees in "uosmo" - coins = sdk.NewCoins(sdk.NewCoin("uosmo", coins.AmountOf("uosmo"))) - - fees, err = simtypes.RandomFees(r, ctx, coins) - if err != nil { - return simtypes.NoOpMsg(moduleName, msg.Type(), "unable to generate fees"), nil, err - } - return GenAndDeliverTx(app, txGen, msg, fees, ctx, simAccount, ak, moduleName) -} - -func GenAndDeliverTx( - app *baseapp.BaseApp, - txGen client.TxConfig, - msg legacytx.LegacyMsg, - fees sdk.Coins, - ctx sdk.Context, - simAccount simtypes.Account, - ak stakingTypes.AccountKeeper, - moduleName string, -) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - account := ak.GetAccount(ctx, simAccount.Address) - tx, err := helpers.GenTx( - txGen, - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - ctx.ChainID(), - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) - if err != nil { - return simtypes.NoOpMsg(moduleName, msg.Type(), "unable to generate mock tx"), nil, err - } - - _, _, err = app.Deliver(txGen.TxEncoder(), tx) - if err != nil { - return simtypes.NoOpMsg(moduleName, msg.Type(), "unable to deliver tx"), nil, err - } - - return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil -} diff --git a/x/superfluid/simulation/operations.go b/x/superfluid/simulation/operations.go index 11748bb2c5e..1061a688bb8 100644 --- a/x/superfluid/simulation/operations.go +++ b/x/superfluid/simulation/operations.go @@ -3,7 +3,7 @@ package simulation import ( "math/rand" - osmo_simulation "github.com/osmosis-labs/osmosis/v7/x/simulation" + osmo_simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" "github.com/cosmos/cosmos-sdk/baseapp" From fb76a7326ec1c927fd168739ad8c529cbee12028 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Wed, 13 Jul 2022 18:42:16 -0500 Subject: [PATCH 069/376] Move simulator test to tests package, temporarily disable from CI until determinism is fixed (#2052) * Move simulator test to tests package, temporarily disable from CI until determinism is fixed * Update simulation/types/action.go Co-authored-by: Adam Tucker * Improve logging to be more helpful, fix lockup bug * Fix bug Co-authored-by: Adam Tucker --- .github/workflows/sim.yml | 2 +- Makefile | 4 +- osmoutils/slice_helper.go | 10 ++ simapp/params.json | 3 - simulation/executor/simulate.go | 23 +++ simulation/types/action.go | 2 +- simulation/types/txbuilder.go | 4 +- {simapp => tests/simulator}/genesis.go | 0 tests/simulator/params.json | 3 + {simapp => tests/simulator}/sim_test.go | 179 +++++++++++++----------- {simapp => tests/simulator}/state.go | 0 x/lockup/keeper/lock.go | 4 + x/lockup/simulation/operations.go | 8 +- 13 files changed, 149 insertions(+), 93 deletions(-) delete mode 100644 simapp/params.json rename {simapp => tests/simulator}/genesis.go (100%) create mode 100644 tests/simulator/params.json rename {simapp => tests/simulator}/sim_test.go (57%) rename {simapp => tests/simulator}/state.go (100%) diff --git a/.github/workflows/sim.yml b/.github/workflows/sim.yml index cf2b59c99dd..c57ce38711a 100644 --- a/.github/workflows/sim.yml +++ b/.github/workflows/sim.yml @@ -18,4 +18,4 @@ jobs: run: go version - name: Run simulation run: | - make test-sim + # make test-sim diff --git a/Makefile b/Makefile index 44f86d8786f..766e6f39f58 100644 --- a/Makefile +++ b/Makefile @@ -208,9 +208,9 @@ sync-docs: ### Tests & Simulation ### ############################################################################### -PACKAGES_UNIT=$(shell go list ./... | grep -E -v 'simapp|e2e') +PACKAGES_UNIT=$(shell go list ./... | grep -E -v 'tests/simulator|e2e') PACKAGES_E2E=$(shell go list ./... | grep '/e2e') -PACKAGES_SIM=$(shell go list ./... | grep '/simapp') +PACKAGES_SIM=$(shell go list ./... | grep '/tests/simulator') TEST_PACKAGES=./... include sims.mk diff --git a/osmoutils/slice_helper.go b/osmoutils/slice_helper.go index 700dcff30df..1128789c19a 100644 --- a/osmoutils/slice_helper.go +++ b/osmoutils/slice_helper.go @@ -12,3 +12,13 @@ func SortSlice[T constraints.Ordered](s []T) { return s[i] < s[j] }) } + +func Filter[T interface{}](filter func(T) bool, s []T) []T { + filteredSlice := []T{} + for _, s := range s { + if filter(s) { + filteredSlice = append(filteredSlice, s) + } + } + return filteredSlice +} diff --git a/simapp/params.json b/simapp/params.json deleted file mode 100644 index 8906d3a3efb..00000000000 --- a/simapp/params.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "op_reflect_contract_path": "../wasmbinding/testdata/reflect.wasm" -} diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index d648d7bdbd8..4fd61d25f9d 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -6,6 +6,8 @@ import ( "math/rand" "os" "os/signal" + "runtime" + "runtime/debug" "syscall" "testing" "time" @@ -141,6 +143,8 @@ func SimulateFromSeed( // recover logs in case of panic defer func() { if r := recover(); r != nil { + // TODO: Come back and cleanup the entire panic recovery logging. + // printPanicRecoveryError(r) _, _ = fmt.Fprintf(w, "simulation halted due to panic on block %d\n", simState.header.Height) simState.logWriter.PrintLogs() panic(r) @@ -176,6 +180,25 @@ func SimulateFromSeed( return stopEarly, exportedParams, nil } +//nolint:deadcode,unused +func printPanicRecoveryError(recoveryError interface{}) { + errStackTrace := string(debug.Stack()) + switch e := recoveryError.(type) { + case string: + fmt.Println("Recovering from (string) panic: " + e) + case runtime.Error: + fmt.Println("recovered (runtime.Error) panic: " + e.Error()) + case error: + fmt.Println("recovered (error) panic: " + e.Error()) + default: + fmt.Println("recovered (default) panic. Could not capture logs in ctx, see stdout") + fmt.Println("Recovering from panic ", recoveryError) + debug.PrintStack() + return + } + fmt.Println("stack trace: " + errStackTrace) +} + type blockSimFn func(simCtx *simtypes.SimCtx, ctx sdk.Context, header tmproto.Header) (opCount int) // Returns a function to simulate blocks. Written like this to avoid constant diff --git a/simulation/types/action.go b/simulation/types/action.go index 2a4dc173153..64eaac5a96c 100644 --- a/simulation/types/action.go +++ b/simulation/types/action.go @@ -92,7 +92,7 @@ func (m msgBasedAction) Execute(sim *SimCtx, ctx sdk.Context) ( } tx, err := sim.txbuilder(ctx, msg, m.name) if err != nil { - return simulation.NoOpMsg(m.name, m.name, "unable to build tx"), nil, err + return simulation.NoOpMsg(m.name, m.name, fmt.Sprintf("unable to build tx due to: %v", err)), nil, err } return sim.deliverTx(tx, msg, m.name) } diff --git a/simulation/types/txbuilder.go b/simulation/types/txbuilder.go index 7a432dc411c..87d0719c0bc 100644 --- a/simulation/types/txbuilder.go +++ b/simulation/types/txbuilder.go @@ -50,9 +50,9 @@ func (sim *SimCtx) defaultTxBuilder( // TODO: Fix these args func (sim *SimCtx) deliverTx(tx sdk.Tx, msg sdk.Msg, msgName string) (simulation.OperationMsg, []simulation.FutureOperation, error) { txConfig := params.MakeEncodingConfig().TxConfig // TODO: unhardcode - _, _, err := sim.App.GetBaseApp().Deliver(txConfig.TxEncoder(), tx) + _, results, err := sim.App.GetBaseApp().Deliver(txConfig.TxEncoder(), tx) if err != nil { - return simulation.NoOpMsg(msgName, msgName, "unable to deliver tx"), nil, err + return simulation.NoOpMsg(msgName, msgName, fmt.Sprintf("unable to deliver tx. \nreason: %v\n results: %v\n msg: %s\n tx: %s", err, results, msg, tx)), nil, err } return simulation.NewOperationMsg(msg, true, "", nil), nil, nil diff --git a/simapp/genesis.go b/tests/simulator/genesis.go similarity index 100% rename from simapp/genesis.go rename to tests/simulator/genesis.go diff --git a/tests/simulator/params.json b/tests/simulator/params.json new file mode 100644 index 00000000000..5878b72fd13 --- /dev/null +++ b/tests/simulator/params.json @@ -0,0 +1,3 @@ +{ + "op_reflect_contract_path": "../../wasmbinding/testdata/reflect.wasm" +} diff --git a/simapp/sim_test.go b/tests/simulator/sim_test.go similarity index 57% rename from simapp/sim_test.go rename to tests/simulator/sim_test.go index 05af96af639..a27fdec46f9 100644 --- a/simapp/sim_test.go +++ b/tests/simulator/sim_test.go @@ -1,13 +1,21 @@ package simapp import ( + "encoding/json" + "fmt" + "math/rand" "os" "testing" + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/libs/log" + dbm "github.com/tendermint/tm-db" + "github.com/osmosis-labs/osmosis/v7/app" "github.com/cosmos/cosmos-sdk/baseapp" sdkSimapp "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/store" simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" @@ -118,85 +126,92 @@ func interBlockCacheOpt() func(*baseapp.BaseApp) { return baseapp.SetInterBlockCache(store.NewCommitKVStoreCacheManager()) } -// // TODO: Make another test for the fuzzer itself, which just has noOp txs -// // and doesn't depend on the application. -// func TestAppStateDeterminism(t *testing.T) { -// // if !sdkSimapp.FlagEnabledValue { -// // t.Skip("skipping application simulation") -// // } - -// config := sdkSimapp.NewConfigFromFlags() -// config.InitialBlockHeight = 1 -// config.ExportParamsPath = "" -// config.OnOperation = false -// config.AllInvariants = false -// config.ChainID = helpers.SimAppChainID - -// // This file is needed to provide the correct path -// // to reflect.wasm test file needed for wasmd simulation testing. -// config.ParamsFile = "params.json" - -// numSeeds := 3 -// numTimesToRunPerSeed := 5 -// appHashList := make([]json.RawMessage, numTimesToRunPerSeed) - -// for i := 0; i < numSeeds; i++ { -// config.Seed = rand.Int63() - -// for j := 0; j < numTimesToRunPerSeed; j++ { -// var logger log.Logger -// if sdkSimapp.FlagVerboseValue { -// logger = log.TestingLogger() -// } else { -// logger = log.NewNopLogger() -// } - -// db := dbm.NewMemDB() -// app := app.NewOsmosisApp( -// logger, -// db, -// nil, -// true, -// map[int64]bool{}, -// app.DefaultNodeHome, -// sdkSimapp.FlagPeriodValue, -// app.MakeEncodingConfig(), -// sdkSimapp.EmptyAppOptions{}, -// app.GetWasmEnabledProposals(), -// app.EmptyWasmOpts, -// interBlockCacheOpt()) - -// fmt.Printf( -// "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", -// config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, -// ) - -// _, _, err := simulation.SimulateFromSeed( -// t, -// os.Stdout, -// app.BaseApp, -// AppStateFn(app.AppCodec(), app.SimulationManager()), -// simulation2.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 -// sdkSimapp.SimulationOperations(app, app.AppCodec(), config), -// app.ModuleAccountAddrs(), -// config, -// app.AppCodec(), -// ) -// require.NoError(t, err) - -// if config.Commit { -// sdkSimapp.PrintStats(db) -// } - -// appHash := app.LastCommitID().Hash -// appHashList[j] = appHash - -// if j != 0 { -// require.Equal( -// t, string(appHashList[0]), string(appHashList[j]), -// "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, -// ) -// } -// } -// } -// } +// TODO: Make another test for the fuzzer itself, which just has noOp txs +// and doesn't depend on the application. +func TestAppStateDeterminism(t *testing.T) { + // if !sdkSimapp.FlagEnabledValue { + // t.Skip("skipping application simulation") + // } + + config := sdkSimapp.NewConfigFromFlags() + config.InitialBlockHeight = 1 + config.ExportParamsPath = "" + config.NumBlocks = 10 + config.OnOperation = false + config.AllInvariants = false + config.ChainID = helpers.SimAppChainID + + // This file is needed to provide the correct path + // to reflect.wasm test file needed for wasmd simulation testing. + config.ParamsFile = "params.json" + + numSeeds := 3 + numTimesToRunPerSeed := 5 + appHashList := make([]json.RawMessage, numTimesToRunPerSeed) + + for i := 0; i < numSeeds; i++ { + config.Seed = rand.Int63() + + for j := 0; j < numTimesToRunPerSeed; j++ { + var logger log.Logger + logger = log.TestingLogger() + // if sdkSimapp.FlagVerboseValue { + // logger = log.TestingLogger() + // } else { + // logger = log.NewNopLogger() + // } + + db := dbm.NewMemDB() + osmosis := app.NewOsmosisApp( + logger, + db, + nil, + true, + map[int64]bool{}, + app.DefaultNodeHome, + sdkSimapp.FlagPeriodValue, + app.MakeEncodingConfig(), + sdkSimapp.EmptyAppOptions{}, + app.GetWasmEnabledProposals(), + app.EmptyWasmOpts, + interBlockCacheOpt()) + + fmt.Printf( + "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", + config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, + ) + + initFns := simtypes.InitFunctions{ + RandomAccountFn: simtypes.WrapRandAccFnForResampling(simulation2.RandomAccounts, osmosis.ModuleAccountAddrs()), + AppInitialStateFn: AppStateFn(osmosis.AppCodec(), osmosis.SimulationManager()), + } + + // Run randomized simulation: + _, _, simErr := osmosim.SimulateFromSeed( + t, + os.Stdout, + osmosis, + initFns, + osmosis.SimulationManager().Actions(config.Seed, osmosis.AppCodec()), // Run all registered operations + config, + osmosis.AppCodec(), + ) + + require.NoError(t, simErr) + + if config.Commit { + sdkSimapp.PrintStats(db) + } + + appHash := osmosis.LastCommitID().Hash + appHashList[j] = appHash + + if j != 0 { + require.Equal( + t, string(appHashList[0]), string(appHashList[j]), + "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, + ) + } + } + } +} diff --git a/simapp/state.go b/tests/simulator/state.go similarity index 100% rename from simapp/state.go rename to tests/simulator/state.go diff --git a/x/lockup/keeper/lock.go b/x/lockup/keeper/lock.go index 4181b316e94..fc4305b031d 100644 --- a/x/lockup/keeper/lock.go +++ b/x/lockup/keeper/lock.go @@ -184,6 +184,10 @@ func (k Keeper) beginUnlock(ctx sdk.Context, lock types.PeriodLock, coins sdk.Co return fmt.Errorf("requested amount to unlock exceeds locked tokens") } + if lock.IsUnlocking() { + return fmt.Errorf("trying to unlock a lock that is already unlocking") + } + // If the amount were unlocking is empty, or the entire coins amount, unlock the entire lock. // Otherwise, split the lock into two locks, and fully unlock the newly created lock. // (By virtue, the newly created lock we split into should have the unlock amount) diff --git a/x/lockup/simulation/operations.go b/x/lockup/simulation/operations.go index f815a2afa59..a0ab4d5285b 100644 --- a/x/lockup/simulation/operations.go +++ b/x/lockup/simulation/operations.go @@ -6,6 +6,7 @@ import ( legacysimulationtype "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/osmosis-labs/osmosis/v7/osmoutils" simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" "github.com/osmosis-labs/osmosis/v7/x/lockup/types" @@ -43,13 +44,16 @@ func RandomMsgBeginUnlocking(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Co }, nil } +var notUnlockingFilter = func(l types.PeriodLock) bool { return !l.IsUnlocking() } + func accountHasLockConstraint(k keeper.Keeper, ctx sdk.Context) simulation.SimAccountConstraint { return func(acc legacysimulationtype.Account) bool { - return len(k.GetAccountPeriodLocks(ctx, acc.Address)) != 0 + return len(osmoutils.Filter(notUnlockingFilter, k.GetAccountPeriodLocks(ctx, acc.Address))) != 0 } } func randLock(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context, addr sdk.AccAddress) types.PeriodLock { locks := k.GetAccountPeriodLocks(ctx, addr) - return simulation.RandSelect(sim, locks...) + notUnlockingLocks := osmoutils.Filter(notUnlockingFilter, locks) + return simulation.RandSelect(sim, notUnlockingLocks...) } From d3c974a0cb7f4922711cdb0797e0c0ba1e2bef8b Mon Sep 17 00:00:00 2001 From: Roman Date: Wed, 13 Jul 2022 22:18:27 -0400 Subject: [PATCH 070/376] refactor(e2e): improve abstractions for node, chain and containers (#2053) * refactor(e2e): improve abstractions for node, chain and containers * increase timeout for commands * clean up * Update tests/e2e/configurer/chain/queries.go Co-authored-by: Adam Tucker Co-authored-by: Adam Tucker --- tests/e2e/configurer/base.go | 22 ++- tests/e2e/configurer/chain/chain.go | 138 +++++++--------- tests/e2e/configurer/chain/commands.go | 210 +++++++----------------- tests/e2e/configurer/chain/node.go | 115 +++++++++++++ tests/e2e/configurer/chain/queries.go | 97 +++++------ tests/e2e/configurer/chain/validator.go | 14 -- tests/e2e/configurer/factory.go | 3 +- tests/e2e/configurer/setup.go | 4 +- tests/e2e/configurer/upgrade.go | 48 ++++-- tests/e2e/containers/containers.go | 142 +++++++--------- tests/e2e/e2e_setup_test.go | 6 +- tests/e2e/e2e_test.go | 56 ++++--- 12 files changed, 421 insertions(+), 434 deletions(-) create mode 100644 tests/e2e/configurer/chain/node.go delete mode 100644 tests/e2e/configurer/chain/validator.go diff --git a/tests/e2e/configurer/base.go b/tests/e2e/configurer/base.go index f3b126fc51b..023a53e04c2 100644 --- a/tests/e2e/configurer/base.go +++ b/tests/e2e/configurer/base.go @@ -62,8 +62,8 @@ func (bc *baseConfigurer) RunValidators() error { func (bc *baseConfigurer) runValidators(chainConfig *chain.Config) error { bc.t.Logf("starting %s validator containers...", chainConfig.Id) - for valIndex := range chainConfig.NodeConfigs { - if err := chainConfig.RunNode(valIndex); err != nil { + for _, node := range chainConfig.NodeConfigs { + if err := node.Run(); err != nil { return err } } @@ -104,10 +104,16 @@ func (bc *baseConfigurer) runIBCRelayer(chainConfigA *chain.Config, chainConfigB return err } + relayerNodeA := chainConfigA.NodeConfigs[0] + relayerNodeB := chainConfigB.NodeConfigs[0] + hermesResource, err := bc.containerManager.RunHermesResource( chainConfigA.Id, - chainConfigA.NodeConfigs[0].Mnemonic, - chainConfigB.Id, chainConfigB.NodeConfigs[0].Mnemonic, + relayerNodeA.Name, + relayerNodeA.Mnemonic, + chainConfigB.Id, + relayerNodeB.Name, + relayerNodeB.Mnemonic, hermesCfgPath) if err != nil { return err @@ -147,7 +153,7 @@ func (bc *baseConfigurer) runIBCRelayer(chainConfigA *chain.Config, chainConfigB time.Second, "hermes relayer not healthy") - bc.t.Logf("started Hermes relayer container: %s", bc.containerManager.GetHermesContainerID()) + bc.t.Logf("started Hermes relayer container: %s", hermesResource.Container.ID) // XXX: Give time to both networks to start, otherwise we might see gRPC // transport errors. @@ -160,7 +166,7 @@ func (bc *baseConfigurer) runIBCRelayer(chainConfigA *chain.Config, chainConfigB func (bc *baseConfigurer) connectIBCChains(chainA *chain.Config, chainB *chain.Config) error { bc.t.Logf("connecting %s and %s chains via IBC", chainA.ChainMeta.Id, chainB.ChainMeta.Id) cmd := []string{"hermes", "create", "channel", chainA.ChainMeta.Id, chainB.ChainMeta.Id, "--port-a=transfer", "--port-b=transfer"} - _, _, err := bc.containerManager.ExecCmd(bc.t, "", 0, cmd, "successfully opened init channel") + _, _, err := bc.containerManager.ExecHermesCmd(bc.t, cmd, "successfully opened init channel") if err != nil { return err } @@ -172,8 +178,6 @@ func (bc *baseConfigurer) initializeChainConfigFromInitChain(initializedChain *i chainConfig.ChainMeta = initializedChain.ChainMeta chainConfig.NodeConfigs = make([]*chain.NodeConfig, 0, len(initializedChain.Nodes)) for _, validator := range initializedChain.Nodes { - chainConfig.NodeConfigs = append(chainConfig.NodeConfigs, &chain.NodeConfig{ - Node: *validator, - }) + chainConfig.NodeConfigs = append(chainConfig.NodeConfigs, chain.NewNodeConfig(bc.t, validator, chainConfig.Id, bc.containerManager)) } } diff --git a/tests/e2e/configurer/chain/chain.go b/tests/e2e/configurer/chain/chain.go index 527f80b7850..a3145d70372 100644 --- a/tests/e2e/configurer/chain/chain.go +++ b/tests/e2e/configurer/chain/chain.go @@ -1,13 +1,12 @@ package chain import ( - "context" "fmt" "testing" "time" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" coretypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" @@ -21,7 +20,7 @@ type Config struct { // voting period is number of blocks it takes to deposit, 1.2 seconds per validator to vote on the prop, and a buffer. VotingPeriod float32 // upgrade proposal height for chain. - PropHeight int + UpgradePropHeight int64 LatestProposalNumber int LatestLockNumber int NodeConfigs []*NodeConfig @@ -30,15 +29,10 @@ type Config struct { containerManager *containers.Manager } -type status struct { - LatestHeight string `json:"latest_block_height"` -} - -type syncInfo struct { - SyncInfo status `json:"SyncInfo"` -} - const ( + // defaultNodeIndex to use for querying and executing transactions. + // It is used when we are indifferent about the node we are working with. + defaultNodeIndex = 0 // waitUntilRepeatPauseTime is the time to wait between each check of the node status. waitUntilRepeatPauseTime = 2 * time.Second // waitUntilrepeatMax is the maximum number of times to repeat the wait until condition. @@ -56,93 +50,77 @@ func New(t *testing.T, containerManager *containers.Manager, id string, initVali } } -// RunNode runs a node container for the given nodeIndex. -// The node configuration must be already added to the chain config prior to calling this -// method. -func (c *Config) RunNode(nodeIndex int) error { - c.t.Logf("starting %s validator containers...", c.Id) +// WaitUntilHeight waits for all validators to reach the specified height at the minimum. +// returns error, if any. +func (c *Config) WaitUntilHeight(height int64) error { + // Ensure the nodes are making progress. + doneCondition := func(syncInfo coretypes.SyncInfo) bool { + curHeight := syncInfo.LatestBlockHeight + + if curHeight < height { + c.t.Logf("current block height is %d, waiting to reach: %d", curHeight, height) + return false + } - resource, err := c.containerManager.RunValidatorResource(c.Id, c.NodeConfigs[nodeIndex].Name, c.NodeConfigs[nodeIndex].ConfigDir) - if err != nil { - return err + return !syncInfo.CatchingUp } - hostPort := resource.GetHostPort("26657/tcp") - rpcClient, err := rpchttp.New("tcp://"+hostPort, "/websocket") - if err != nil { - return err + for _, node := range c.NodeConfigs { + c.t.Logf("node container: %s, waiting to reach height %d", node.Name, height) + if err := node.WaitUntil(doneCondition); err != nil { + return err + } } + return nil +} + +func (c *Config) SendIBC(dstChain *Config, recipient string, token sdk.Coin) { + c.t.Logf("IBC sending %s from %s to %s (%s)", token, c.Id, dstChain.Id, recipient) + + dstNode, err := dstChain.GetDefaultNode() + require.NoError(c.t, err) + + balancesDstPre, err := dstNode.QueryBalances(recipient) + require.NoError(c.t, err) + + cmd := []string{"hermes", "tx", "raw", "ft-transfer", dstChain.Id, c.Id, "transfer", "channel-0", token.Amount.String(), fmt.Sprintf("--denom=%s", token.Denom), fmt.Sprintf("--receiver=%s", recipient), "--timeout-height-offset=1000"} + _, _, err = c.containerManager.ExecHermesCmd(c.t, cmd, "Success") + require.NoError(c.t, err) require.Eventually( c.t, func() bool { - if _, err := rpcClient.Health(context.Background()); err != nil { + balancesDstPost, err := dstNode.QueryBalances(recipient) + require.NoError(c.t, err) + ibcCoin := balancesDstPost.Sub(balancesDstPre) + if ibcCoin.Len() == 1 { + tokenPre := balancesDstPre.AmountOfNoDenomValidation(ibcCoin[0].Denom) + tokenPost := balancesDstPost.AmountOfNoDenomValidation(ibcCoin[0].Denom) + resPre := initialization.OsmoToken.Amount + resPost := tokenPost.Sub(tokenPre) + return resPost.Uint64() == resPre.Uint64() + } else { return false } - - c.t.Logf("started %s node container: %s", resource.Container.Name[1:], resource.Container.ID) - return true }, 5*time.Minute, time.Second, - "Osmosis node failed to produce blocks", + "tx not received on destination chain", ) - c.NodeConfigs[nodeIndex].rpcClient = rpcClient - - if c.NodeConfigs[nodeIndex].IsValidator { - return c.ExtractValidatorOperatorAddress(nodeIndex) - } - - return nil + c.t.Log("successfully sent IBC tokens") } -// WaitUntil waits until validator with validatorIndex reaches doneCondition. Return nil -// if reached, error otherwise. -func (c *Config) WaitUntil(nodeIndex int, doneCondition func(syncInfo coretypes.SyncInfo) bool) error { - var latestBlockHeight int64 - for i := 0; i < waitUntilrepeatMax; i++ { - status, err := c.NodeConfigs[nodeIndex].rpcClient.Status(context.Background()) - if err != nil { - return err - } - latestBlockHeight = status.SyncInfo.LatestBlockHeight - // let the node produce a few blocks - if !doneCondition(status.SyncInfo) { - time.Sleep(waitUntilRepeatPauseTime) - continue - } - return nil - } - return fmt.Errorf("validator with index %d timed out waiting for condition, latest block height was %d", nodeIndex, latestBlockHeight) +// GetDefaultNode returns the default node of the chain. +// The default node is the first one created. Returns error if no +// ndoes created. +func (c *Config) GetDefaultNode() (*NodeConfig, error) { + return c.getNodeAtIndex(defaultNodeIndex) } -// WaitUntilHeight waits for all validators to reach the specified height at the minimum. -// returns error, if any. -func (c *Config) WaitUntilHeight(height int64) error { - // Ensure the nodes are making progress. - doneCondition := func(syncInfo coretypes.SyncInfo) bool { - curHeight := syncInfo.LatestBlockHeight - - if curHeight < height { - c.t.Logf("current block height is %d, waiting to reach: %d", curHeight, height) - return false - } - - return !syncInfo.CatchingUp +func (c *Config) getNodeAtIndex(nodeIndex int) (*NodeConfig, error) { + if nodeIndex > len(c.NodeConfigs) { + return nil, fmt.Errorf("node index (%d) is greter than the number of nodes available (%d)", nodeIndex, len(c.NodeConfigs)) } - - for nodeIndex := range c.NodeConfigs { - nodeResource, exists := c.containerManager.GetValidatorResource(c.Id, nodeIndex) - container := nodeResource.Container - c.t.Logf("node container: %s, id: %s, waiting to reach height %d", container.Name[1:], container.ID, height) - if !exists { - return fmt.Errorf("validator on chain %s with index %d does not exist", c.Id, nodeIndex) - } - if err := c.WaitUntil(nodeIndex, doneCondition); err != nil { - c.t.Errorf("validator with index %d failed to start", nodeIndex) - return err - } - } - return nil + return c.NodeConfigs[nodeIndex], nil } diff --git a/tests/e2e/configurer/chain/commands.go b/tests/e2e/configurer/chain/commands.go index 9500f09e182..488ccd76dbd 100644 --- a/tests/e2e/configurer/chain/commands.go +++ b/tests/e2e/configurer/chain/commands.go @@ -5,191 +5,97 @@ import ( "regexp" "strconv" "strings" - "time" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" ) -func (c *Config) CreatePool(poolFile, from string) { - c.t.Logf("creating pool for chain-id: %s", c.Id) +func (n *NodeConfig) CreatePool(poolFile, from string) { + n.t.Logf("creating pool for chain-id: %s", n.chainId) cmd := []string{"osmosisd", "tx", "gamm", "create-pool", fmt.Sprintf("--pool-file=/osmosis/%s", poolFile), fmt.Sprintf("--from=%s", from)} - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) - require.NoError(c.t, err) - - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) - require.True(c.t, exists) - c.t.Logf("successfully created pool from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Logf("successfully created pool from container: %s", n.Name) } -func (c *Config) SubmitUpgradeProposal(upgradeVersion string) { - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) - require.True(c.t, exists) - - upgradeHeightStr := strconv.Itoa(c.PropHeight) - c.t.Logf("submitting upgrade proposal on %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%s", upgradeHeightStr), "--upgrade-info=\"\"", "--from=val"} - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) - require.NoError(c.t, err) - c.t.Log("successfully submitted upgrade proposal") - c.LatestProposalNumber = c.LatestProposalNumber + 1 +func (n *NodeConfig) SubmitUpgradeProposal(upgradeVersion string, upgradeHeight int64) { + n.t.Logf("submitting upgrade proposal on container: %s", n.Name) + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%d", upgradeHeight), "--upgrade-info=\"\"", "--from=val"} + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Log("successfully submitted upgrade proposal") } -func (c *Config) SubmitSuperfluidProposal(asset string) { - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) - require.True(c.t, exists) - - c.t.Logf("submitting superfluid proposal for asset %s on %s container: %s", asset, validatorResource.Container.Name[1:], validatorResource.Container.ID) +func (n *NodeConfig) SubmitSuperfluidProposal(asset string) { + n.t.Logf("submitting superfluid proposal for asset %s on container: %s", asset, n.Name) cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "set-superfluid-assets-proposal", fmt.Sprintf("--superfluid-assets=%s", asset), fmt.Sprintf("--title=\"%s superfluid asset\"", asset), fmt.Sprintf("--description=\"%s superfluid asset\"", asset), "--from=val"} - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) - require.NoError(c.t, err) - c.t.Log("successfully submitted superfluid proposal") - c.LatestProposalNumber = c.LatestProposalNumber + 1 + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Log("successfully submitted superfluid proposal") } -func (c *Config) SubmitTextProposal(text string) { - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) - require.True(c.t, exists) - - c.t.Logf("submitting text proposal on %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) +func (n *NodeConfig) SubmitTextProposal(text string) { + n.t.Logf("submitting text proposal on container: %s", n.Name) cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "--type=text", fmt.Sprintf("--title=\"%s\"", text), "--description=\"test text proposal\"", "--from=val"} - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) - c.t.Log("successfully submitted text proposal") - require.NoError(c.t, err) - c.LatestProposalNumber = c.LatestProposalNumber + 1 + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Log("successfully submitted text proposal") } -func (c *Config) DepositProposal() { - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) - require.True(c.t, exists) - - propStr := strconv.Itoa(c.LatestProposalNumber) - c.t.Logf("depositing to proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - cmd := []string{"osmosisd", "tx", "gov", "deposit", propStr, "500000000uosmo", "--from=val"} - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) - require.NoError(c.t, err) - c.t.Log("successfully deposited to proposal") +func (n *NodeConfig) DepositProposal(proposalNumber int) { + n.t.Logf("depositing to proposal from container: %s", n.Name) + cmd := []string{"osmosisd", "tx", "gov", "deposit", fmt.Sprintf("%d", proposalNumber), "500000000uosmo", "--from=val"} + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Log("successfully deposited to proposal") } -func (c *Config) VoteYesProposal() { - propStr := strconv.Itoa(c.LatestProposalNumber) - c.t.Logf("voting yes on proposal for chain-id: %s", c.Id) - cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "yes", "--from=val"} - for i := range c.NodeConfigs { - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, i, cmd) - require.NoError(c.t, err) - - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, i) - require.True(c.t, exists) - c.t.Logf("successfully voted yes on proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) - } +func (n *NodeConfig) VoteYesProposal(from string, proposalNumber int) { + n.t.Logf("voting yes on proposal for chain-id: %s", n.chainId) + cmd := []string{"osmosisd", "tx", "gov", "vote", fmt.Sprintf("%d", proposalNumber), "yes", fmt.Sprintf("--from=%s", from)} + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Logf("successfully voted yes on proposal from container: %s", n.Name) } -func (c *Config) VoteNoProposal(validatorIdx int, from string) { - propStr := strconv.Itoa(c.LatestProposalNumber) - c.t.Logf("voting no on proposal for chain-id: %s", c.Id) - cmd := []string{"osmosisd", "tx", "gov", "vote", propStr, "no", fmt.Sprintf("--from=%s", from)} - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, validatorIdx, cmd) - require.NoError(c.t, err) - - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, validatorIdx) - require.True(c.t, exists) - c.t.Logf("successfully voted no for proposal from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) +func (n *NodeConfig) VoteNoProposal(from string, proposalNumber int) { + n.t.Logf("voting no on proposal for chain-id: %s", n.chainId) + cmd := []string{"osmosisd", "tx", "gov", "vote", fmt.Sprintf("%d", proposalNumber), "no", fmt.Sprintf("--from=%s", from)} + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Logf("successfully voted no for proposal from container: %s", n.Name) } -func (c *Config) LockTokens(validatorIdx int, tokens string, duration string, from string) { - c.t.Logf("locking %s for %s on chain-id: %s", tokens, duration, c.Id) +func (n *NodeConfig) LockTokens(tokens string, duration string, from string) { + n.t.Logf("locking %s for %s on chain-id: %s", tokens, duration, n.chainId) cmd := []string{"osmosisd", "tx", "lockup", "lock-tokens", tokens, fmt.Sprintf("--duration=%s", duration), fmt.Sprintf("--from=%s", from)} - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, validatorIdx, cmd) - require.NoError(c.t, err) - - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, validatorIdx) - require.True(c.t, exists) - c.t.Logf("successfully created lock %v from %s container: %s", c.LatestLockNumber, validatorResource.Container.Name[1:], validatorResource.Container.ID) - c.LatestLockNumber = c.LatestLockNumber + 1 + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Logf("successfully created lock from container: %s", n.Name) } -func (c *Config) SuperfluidDelegate(valAddress string, from string) { - lockStr := strconv.Itoa(c.LatestLockNumber) - c.t.Logf("superfluid delegating lock %s to %s on chain-id: %s", lockStr, valAddress, c.Id) +func (n *NodeConfig) SuperfluidDelegate(lockNumber int, valAddress string, from string) { + lockStr := strconv.Itoa(lockNumber) + n.t.Logf("superfluid delegating lock %s to %s on chain-id: %s", lockStr, valAddress, n.chainId) cmd := []string{"osmosisd", "tx", "superfluid", "delegate", lockStr, valAddress, fmt.Sprintf("--from=%s", from)} - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, 0, cmd) - require.NoError(c.t, err) - - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) - require.True(c.t, exists) - c.t.Logf("successfully superfluid delegated from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Logf("successfully superfluid delegated from container: %s", n.Name) } -func (c *Config) BankSend(validatorIndex int, amount string, sendAddress string, receiveAddress string) { - c.t.Logf("sending %s from %s to %s on chain-id: %s", amount, sendAddress, receiveAddress, c.Id) +func (n *NodeConfig) BankSend(amount string, sendAddress string, receiveAddress string) { + n.t.Logf("bank sending %s from %s to %s on chain-id: %s", amount, sendAddress, receiveAddress, n.chainId) cmd := []string{"osmosisd", "tx", "bank", "send", sendAddress, receiveAddress, amount, "--from=val"} - _, _, err := c.containerManager.ExecTxCmd(c.t, c.Id, validatorIndex, cmd) - require.NoError(c.t, err) - - validatorResource, exists := c.containerManager.GetValidatorResource(c.Id, 0) - require.True(c.t, exists) - c.t.Logf("successfully sent tx from %s container: %s", validatorResource.Container.Name[1:], validatorResource.Container.ID) + _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) + require.NoError(n.t, err) + n.t.Logf("successfully sent tx from container: %s", n.Name) } -func (c *Config) CreateWallet(validatorIndex int, walletName string) string { +func (n *NodeConfig) CreateWallet(walletName string) string { cmd := []string{"osmosisd", "keys", "add", walletName, "--keyring-backend=test"} - outBuf, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIndex, cmd, "") - require.NoError(c.t, err) + outBuf, _, err := n.containerManager.ExecCmd(n.t, n.Name, cmd, "") + require.NoError(n.t, err) re := regexp.MustCompile("osmo1(.{38})") walletAddr := fmt.Sprintf("%s\n", re.FindString(outBuf.String())) walletAddr = strings.TrimSuffix(walletAddr, "\n") return walletAddr } - -func (c *Config) SendIBC(dstChain *Config, recipient string, token sdk.Coin) { - c.t.Logf("sending %s from %s to %s (%s)", token, c.Id, dstChain.Id, recipient) - balancesBPre, err := dstChain.QueryBalances(0, recipient) - require.NoError(c.t, err) - - cmd := []string{"hermes", "tx", "raw", "ft-transfer", dstChain.Id, c.Id, "transfer", "channel-0", token.Amount.String(), fmt.Sprintf("--denom=%s", token.Denom), fmt.Sprintf("--receiver=%s", recipient), "--timeout-height-offset=1000"} - _, _, err = c.containerManager.ExecCmd(c.t, "", 0, cmd, "Success") - require.NoError(c.t, err) - - require.Eventually( - c.t, - func() bool { - balancesBPost, err := dstChain.QueryBalances(0, recipient) - require.NoError(c.t, err) - ibcCoin := balancesBPost.Sub(balancesBPre) - if ibcCoin.Len() == 1 { - tokenPre := balancesBPre.AmountOfNoDenomValidation(ibcCoin[0].Denom) - tokenPost := balancesBPost.AmountOfNoDenomValidation(ibcCoin[0].Denom) - resPre := initialization.OsmoToken.Amount - resPost := tokenPost.Sub(tokenPre) - return resPost.Uint64() == resPre.Uint64() - } else { - return false - } - }, - 5*time.Minute, - time.Second, - "tx not received on destination chain", - ) - - c.t.Log("successfully sent IBC tokens") -} - -func (c *Config) ExtractValidatorOperatorAddress(nodeIndex int) error { - node := c.NodeConfigs[nodeIndex] - - if !node.IsValidator { - return fmt.Errorf("node %s at index %d is not a validator", node.Name, nodeIndex) - } - - cmd := []string{"osmosisd", "debug", "addr", node.PublicKey} - c.t.Logf("extracting validator operator addresses for chain-id: %s", c.Id) - _, errBuf, err := c.containerManager.ExecCmd(c.t, c.Id, nodeIndex, cmd, "") - require.NoError(c.t, err) - re := regexp.MustCompile("osmovaloper(.{39})") - operAddr := fmt.Sprintf("%s\n", re.FindString(errBuf.String())) - c.NodeConfigs[nodeIndex].OperatorAddress = strings.TrimSuffix(operAddr, "\n") - return nil -} diff --git a/tests/e2e/configurer/chain/node.go b/tests/e2e/configurer/chain/node.go new file mode 100644 index 00000000000..7c082af2b0c --- /dev/null +++ b/tests/e2e/configurer/chain/node.go @@ -0,0 +1,115 @@ +package chain + +import ( + "context" + "fmt" + "regexp" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + rpchttp "github.com/tendermint/tendermint/rpc/client/http" + coretypes "github.com/tendermint/tendermint/rpc/core/types" + + "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" +) + +type NodeConfig struct { + initialization.Node + + OperatorAddress string + chainId string + rpcClient *rpchttp.HTTP + t *testing.T + containerManager *containers.Manager +} + +// NewNodeConfig returens new initialized NodeConfig. +func NewNodeConfig(t *testing.T, initNode *initialization.Node, chainId string, containerManager *containers.Manager) *NodeConfig { + return &NodeConfig{ + Node: *initNode, + chainId: chainId, + containerManager: containerManager, + t: t, + } +} + +// Run runs a node container for the given nodeIndex. +// The node configuration must be already added to the chain config prior to calling this +// method. +func (n *NodeConfig) Run() error { + n.t.Logf("starting %s validator container: %s", n.chainId, n.Name) + resource, err := n.containerManager.RunNodeResource(n.chainId, n.Name, n.ConfigDir) + if err != nil { + return err + } + + hostPort := resource.GetHostPort("26657/tcp") + rpcClient, err := rpchttp.New("tcp://"+hostPort, "/websocket") + if err != nil { + return err + } + + require.Eventually( + n.t, + func() bool { + if _, err := rpcClient.Health(context.Background()); err != nil { + return false + } + + n.t.Logf("started %s node container: %s", resource.Container.Name[1:], resource.Container.ID) + return true + }, + 5*time.Minute, + time.Second, + "Osmosis node failed to produce blocks", + ) + + n.rpcClient = rpcClient + + if err := n.extractOperatorAddressIfValidator(); err != nil { + return err + } + + return nil +} + +// WaitUntil waits until node reaches doneCondition. Return nil +// if reached, error otherwise. +func (n *NodeConfig) WaitUntil(doneCondition func(syncInfo coretypes.SyncInfo) bool) error { + var latestBlockHeight int64 + for i := 0; i < waitUntilrepeatMax; i++ { + status, err := n.rpcClient.Status(context.Background()) + if err != nil { + return err + } + latestBlockHeight = status.SyncInfo.LatestBlockHeight + // let the node produce a few blocks + if !doneCondition(status.SyncInfo) { + time.Sleep(waitUntilRepeatPauseTime) + continue + } + return nil + } + return fmt.Errorf("node %s timed out waiting for condition, latest block height was %d", n.Name, latestBlockHeight) +} + +func (n *NodeConfig) extractOperatorAddressIfValidator() error { + if !n.IsValidator { + n.t.Logf("node (%s) is not a validator, skipping", n.Name) + return nil + } + + cmd := []string{"osmosisd", "debug", "addr", n.PublicKey} + n.t.Logf("extracting validator operator addresses for validator: %s", n.Name) + _, errBuf, err := n.containerManager.ExecCmd(n.t, n.Name, cmd, "") + if err != nil { + return err + } + re := regexp.MustCompile("osmovaloper(.{39})") + operAddr := fmt.Sprintf("%s\n", re.FindString(errBuf.String())) + n.OperatorAddress = strings.TrimSuffix(operAddr, "\n") + return nil +} diff --git a/tests/e2e/configurer/chain/queries.go b/tests/e2e/configurer/chain/queries.go index f4b768c86d1..3e44415e6a2 100644 --- a/tests/e2e/configurer/chain/queries.go +++ b/tests/e2e/configurer/chain/queries.go @@ -1,13 +1,11 @@ package chain import ( - "encoding/json" + "context" "fmt" "io" "net/http" - "regexp" "strconv" - "strings" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -20,10 +18,10 @@ import ( superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" ) -func (c *Config) QueryRPC(validatorIdx int, path string) ([]byte, error) { +func (n *NodeConfig) QueryGRPCGateway(path string) ([]byte, error) { // add the URL for the given validator ID, and pre-pend to to path. - hostPort, err := c.containerManager.GetValidatorHostPort(c.Id, validatorIdx, "1317/tcp") - require.NoError(c.t, err) + hostPort, err := n.containerManager.GetHostPort(n.Name, "1317/tcp") + require.NoError(n.t, err) endpoint := fmt.Sprintf("http://%s", hostPort) fullQueryPath := fmt.Sprintf("%s/%s", endpoint, path) @@ -56,47 +54,23 @@ func (c *Config) QueryRPC(validatorIdx int, path string) ([]byte, error) { return bz, nil } -func (c *Config) QueryChainStatus(validatorIdx int) []byte { - cmd := []string{"osmosisd", "status"} - _, errBuf, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIdx, cmd, "NodeInfo") - require.NoError(c.t, err) - return errBuf.Bytes() -} - -func (c *Config) QueryCurrentChainHeightFromValidator(validatorIdx int) int { - var block syncInfo - require.Eventually( - c.t, - func() bool { - out := c.QueryChainStatus(validatorIdx) - err := json.Unmarshal(out, &block) - return err == nil - }, - 1*time.Minute, - time.Second, - "Osmosis node failed to retrieve height info", - ) - currentHeight, err := strconv.Atoi(block.SyncInfo.LatestHeight) - require.NoError(c.t, err) - return currentHeight -} - -func (c *Config) QueryBalances(validatorIndex int, addr string) (sdk.Coins, error) { - cmd := []string{"osmosisd", "query", "bank", "balances", addr, "--output=json"} - outBuf, _, err := c.containerManager.ExecCmd(c.t, c.Id, validatorIndex, cmd, "balances") - require.NoError(c.t, err) +// QueryBalancer returns balances at the address. +func (n *NodeConfig) QueryBalances(address string) (sdk.Coins, error) { + path := fmt.Sprintf("cosmos/bank/v1beta1/balances/%s", address) + bz, err := n.QueryGRPCGateway(path) + require.NoError(n.t, err) var balancesResp banktypes.QueryAllBalancesResponse - err = util.Cdc.UnmarshalJSON(outBuf.Bytes(), &balancesResp) - require.NoError(c.t, err) - + if err := util.Cdc.UnmarshalJSON(bz, &balancesResp); err != nil { + return sdk.Coins{}, err + } return balancesResp.GetBalances(), nil } -func (c *Config) QueryPropTally(validatorIdx int, proposalNumber int) (sdk.Int, sdk.Int, sdk.Int, sdk.Int, error) { +func (n *NodeConfig) QueryPropTally(proposalNumber int) (sdk.Int, sdk.Int, sdk.Int, sdk.Int, error) { path := fmt.Sprintf("cosmos/gov/v1beta1/proposals/%d/tally", proposalNumber) - bz, err := c.QueryRPC(validatorIdx, path) - require.NoError(c.t, err) + bz, err := n.QueryGRPCGateway(path) + require.NoError(n.t, err) var balancesResp govtypes.QueryTallyResultResponse if err := util.Cdc.UnmarshalJSON(bz, &balancesResp); err != nil { @@ -110,33 +84,40 @@ func (c *Config) QueryPropTally(validatorIdx int, proposalNumber int) (sdk.Int, return noTotal, yesTotal, noWithVetoTotal, abstainTotal, nil } -func (c *Config) QueryValidatorOperatorAddresses() { - for i, val := range c.NodeConfigs { - cmd := []string{"osmosisd", "debug", "addr", val.PublicKey} - c.t.Logf("extracting validator operator addresses for chain-id: %s", c.Id) - _, errBuf, err := c.containerManager.ExecCmd(c.t, c.Id, i, cmd, "") - require.NoError(c.t, err) - re := regexp.MustCompile("osmovaloper(.{39})") - operAddr := fmt.Sprintf("%s\n", re.FindString(errBuf.String())) - c.NodeConfigs[i].OperatorAddress = strings.TrimSuffix(operAddr, "\n") - } -} - -func (c *Config) QueryIntermediaryAccount(validatorIdx int, denom string, valAddr string) (int, error) { +func (n *NodeConfig) QueryIntermediaryAccount(denom string, valAddr string) (int, error) { intAccount := superfluidtypes.GetSuperfluidIntermediaryAccountAddr(denom, valAddr) path := fmt.Sprintf( "cosmos/staking/v1beta1/validators/%s/delegations/%s", valAddr, intAccount, ) - bz, err := c.QueryRPC(validatorIdx, path) - require.NoError(c.t, err) + + bz, err := n.QueryGRPCGateway(path) + require.NoError(n.t, err) var stakingResp stakingtypes.QueryDelegationResponse err = util.Cdc.UnmarshalJSON(bz, &stakingResp) - require.NoError(c.t, err) + require.NoError(n.t, err) intAccBalance := stakingResp.DelegationResponse.Balance.Amount.String() intAccountBalance, err := strconv.Atoi(intAccBalance) - require.NoError(c.t, err) + require.NoError(n.t, err) return intAccountBalance, err } + +// QueryHashFromBlock gets block hash at a specific height. Otherwise, error. +func (n *NodeConfig) QueryHashFromBlock(height int64) (string, error) { + block, err := n.rpcClient.Block(context.Background(), &height) + if err != nil { + return "", err + } + return block.BlockID.Hash.String(), nil +} + +// QueryCurrentHeight returns the current block height of the node or error. +func (n *NodeConfig) QueryCurrentHeight() (int64, error) { + status, err := n.rpcClient.Status(context.Background()) + if err != nil { + return 0, err + } + return status.SyncInfo.LatestBlockHeight, nil +} diff --git a/tests/e2e/configurer/chain/validator.go b/tests/e2e/configurer/chain/validator.go deleted file mode 100644 index e9220401a97..00000000000 --- a/tests/e2e/configurer/chain/validator.go +++ /dev/null @@ -1,14 +0,0 @@ -package chain - -import ( - rpchttp "github.com/tendermint/tendermint/rpc/client/http" - - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" -) - -type NodeConfig struct { - initialization.Node - - OperatorAddress string - rpcClient *rpchttp.HTTP -} diff --git a/tests/e2e/configurer/factory.go b/tests/e2e/configurer/factory.go index f25db50c14c..ed9e4d7f799 100644 --- a/tests/e2e/configurer/factory.go +++ b/tests/e2e/configurer/factory.go @@ -24,7 +24,8 @@ type Configurer interface { } var ( - // whatever number of validator configs get posted here are how many validators that will spawn on chain A and B respectively + // each started validator containers corresponds to one of + // the configurations below. validatorConfigsChainA = []*initialization.NodeConfig{ { Name: "prune-default-snapshot", diff --git a/tests/e2e/configurer/setup.go b/tests/e2e/configurer/setup.go index d12944fdb32..3698b399494 100644 --- a/tests/e2e/configurer/setup.go +++ b/tests/e2e/configurer/setup.go @@ -38,7 +38,9 @@ func withUpgrade(setupHandler setupFn) setupFn { return fmt.Errorf("to run with upgrade, %v must be set during initialization", &UpgradeConfigurer{}) } - upgradeConfigurer.CreatePreUpgradeState() + if err := upgradeConfigurer.CreatePreUpgradeState(); err != nil { + return err + } if err := upgradeConfigurer.RunUpgrade(); err != nil { return err diff --git a/tests/e2e/configurer/upgrade.go b/tests/e2e/configurer/upgrade.go index 7489e629092..b4c9f73b2c5 100644 --- a/tests/e2e/configurer/upgrade.go +++ b/tests/e2e/configurer/upgrade.go @@ -106,17 +106,26 @@ func (uc *UpgradeConfigurer) ConfigureChain(chainConfig *chain.Config) error { return nil } -func (uc *UpgradeConfigurer) CreatePreUpgradeState() { +func (uc *UpgradeConfigurer) CreatePreUpgradeState() error { chainA := uc.chainConfigs[0] + chainANode, err := chainA.GetDefaultNode() + if err != nil { + return err + } chainB := uc.chainConfigs[1] + chainBNode, err := chainB.GetDefaultNode() + if err != nil { + return err + } chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, initialization.OsmoToken) chainB.SendIBC(chainA, chainA.NodeConfigs[0].PublicAddress, initialization.OsmoToken) chainA.SendIBC(chainB, chainB.NodeConfigs[0].PublicAddress, initialization.StakeToken) chainB.SendIBC(chainA, chainA.NodeConfigs[0].PublicAddress, initialization.StakeToken) - chainA.CreatePool("pool1A.json", initialization.ValidatorWalletName) - chainB.CreatePool("pool1B.json", initialization.ValidatorWalletName) + chainANode.CreatePool("pool1A.json", initialization.ValidatorWalletName) + chainBNode.CreatePool("pool1B.json", initialization.ValidatorWalletName) + return nil } func (uc *UpgradeConfigurer) RunSetup() error { @@ -134,18 +143,27 @@ func (uc *UpgradeConfigurer) runProposalUpgrade() error { // submit, deposit, and vote for upgrade proposal // prop height = current height + voting period + time it takes to submit proposal + small buffer for _, chainConfig := range uc.chainConfigs { - currentHeight := chainConfig.QueryCurrentChainHeightFromValidator(0) - chainConfig.PropHeight = currentHeight + int(chainConfig.VotingPeriod) + int(config.PropSubmitBlocks) + int(config.PropBufferBlocks) + node, err := chainConfig.GetDefaultNode() + if err != nil { + return err + } + currentHeight, err := node.QueryCurrentHeight() + if err != nil { + return err + } + + chainConfig.UpgradePropHeight = currentHeight + int64(chainConfig.VotingPeriod) + int64(config.PropSubmitBlocks) + int64(config.PropBufferBlocks) + node.SubmitUpgradeProposal(uc.upgradeVersion, chainConfig.UpgradePropHeight) + chainConfig.LatestProposalNumber += 1 - chainConfig.SubmitUpgradeProposal(uc.upgradeVersion) - chainConfig.DepositProposal() - chainConfig.VoteYesProposal() + node.DepositProposal(chainConfig.LatestProposalNumber) + node.VoteYesProposal(initialization.ValidatorWalletName, chainConfig.LatestProposalNumber) } // wait till all chains halt at upgrade height for _, chainConfig := range uc.chainConfigs { uc.t.Logf("waiting to reach upgrade height on chain %s", chainConfig.Id) - if err := chainConfig.WaitUntilHeight(int64(chainConfig.PropHeight)); err != nil { + if err := chainConfig.WaitUntilHeight(chainConfig.UpgradePropHeight); err != nil { return err } uc.t.Logf("upgrade height reached on chain %s", chainConfig.Id) @@ -154,7 +172,7 @@ func (uc *UpgradeConfigurer) runProposalUpgrade() error { // remove all containers so we can upgrade them to the new version for _, chainConfig := range uc.chainConfigs { for _, validatorConfig := range chainConfig.NodeConfigs { - err := uc.containerManager.RemoveValidatorResource(chainConfig.Id, validatorConfig.Name) + err := uc.containerManager.RemoveNodeResource(validatorConfig.Name) if err != nil { return err } @@ -163,7 +181,7 @@ func (uc *UpgradeConfigurer) runProposalUpgrade() error { // remove all containers so we can upgrade them to the new version for _, chainConfig := range uc.chainConfigs { - if err := uc.upgradeContainers(chainConfig, chainConfig.PropHeight); err != nil { + if err := uc.upgradeContainers(chainConfig, chainConfig.UpgradePropHeight); err != nil { return err } } @@ -181,20 +199,20 @@ func (uc *UpgradeConfigurer) runForkUpgrade() error { return nil } -func (uc *UpgradeConfigurer) upgradeContainers(chainConfig *chain.Config, propHeight int) error { +func (uc *UpgradeConfigurer) upgradeContainers(chainConfig *chain.Config, propHeight int64) error { // upgrade containers to the locally compiled daemon uc.t.Logf("starting upgrade for chain-id: %s...", chainConfig.Id) uc.containerManager.OsmosisRepository = containers.CurrentBranchOsmoRepository uc.containerManager.OsmosisTag = containers.CurrentBranchOsmoTag - for nodeIndex := range chainConfig.NodeConfigs { - if err := chainConfig.RunNode(nodeIndex); err != nil { + for _, node := range chainConfig.NodeConfigs { + if err := node.Run(); err != nil { return err } } uc.t.Logf("waiting to upgrade containers on chain %s", chainConfig.Id) - if err := chainConfig.WaitUntilHeight(int64(propHeight)); err != nil { + if err := chainConfig.WaitUntilHeight(propHeight); err != nil { return err } uc.t.Logf("upgrade successful on chain %s", chainConfig.Id) diff --git a/tests/e2e/containers/containers.go b/tests/e2e/containers/containers.go index 9edb77ee5a1..c49523406de 100644 --- a/tests/e2e/containers/containers.go +++ b/tests/e2e/containers/containers.go @@ -15,25 +15,25 @@ import ( "github.com/stretchr/testify/require" ) +const hermesContainerName = "hermes-relayer" + var errRegex = regexp.MustCompile(`(E|e)rror`) // Manager is a wrapper around all Docker instances, and the Docker API. // It provides utilities to run and interact with all Docker containers used within e2e testing. type Manager struct { ImageConfig - pool *dockertest.Pool - network *dockertest.Network - - hermesResource *dockertest.Resource - valResources map[string][]*dockertest.Resource + pool *dockertest.Pool + network *dockertest.Network + resources map[string]*dockertest.Resource } // NewManager creates a new Manager instance and initializes // all Docker specific utilies. Returns an error if initialiation fails. func NewManager(isUpgrade bool, isFork bool) (docker *Manager, err error) { docker = &Manager{ - ImageConfig: NewImageConfig(isUpgrade, isFork), - valResources: make(map[string][]*dockertest.Resource), + ImageConfig: NewImageConfig(isUpgrade, isFork), + resources: make(map[string]*dockertest.Resource), } docker.pool, err = dockertest.NewPool("") if err != nil { @@ -49,33 +49,36 @@ func NewManager(isUpgrade bool, isFork bool) (docker *Manager, err error) { // ExecTxCmd Runs ExecCmd, with flags for txs added. // namely adding flags `--chain-id={chain-id} -b=block --yes --keyring-backend=test "--log_format=json"`, // and searching for `code: 0` -func (m *Manager) ExecTxCmd(t *testing.T, chainId string, validatorIndex int, command []string) (bytes.Buffer, bytes.Buffer, error) { +func (m *Manager) ExecTxCmd(t *testing.T, chainId string, containerName string, command []string) (bytes.Buffer, bytes.Buffer, error) { allTxArgs := []string{fmt.Sprintf("--chain-id=%s", chainId), "-b=block", "--yes", "--keyring-backend=test", "--log_format=json"} txCommand := append(command, allTxArgs...) successStr := "code: 0" - return m.ExecCmd(t, chainId, validatorIndex, txCommand, successStr) + return m.ExecCmd(t, containerName, txCommand, successStr) +} + +// ExecHermesCmd executes command on the hermes relaer container. +func (m *Manager) ExecHermesCmd(t *testing.T, command []string, success string) (bytes.Buffer, bytes.Buffer, error) { + return m.ExecCmd(t, hermesContainerName, command, success) } -// ExecCmd executes command on chainId by running it on the validator container (specified by validatorIndex) +// ExecCmd executes command by running it on the node container (specified by containerName) // success is the output of the command that needs to be observed for the command to be deemed successful. // It is found by checking if stdout or stderr contains the success string anywhere within it. // returns container std out, container std err, and error if any. // An error is returned if the command fails to execute or if the success string is not found in the output. -func (m *Manager) ExecCmd(t *testing.T, chainId string, validatorIndex int, command []string, success string) (bytes.Buffer, bytes.Buffer, error) { - ctx, cancel := context.WithTimeout(context.Background(), time.Minute) - defer cancel() - var containerId string - if chainId == "" { - containerId = m.hermesResource.Container.ID - } else { - containerId = m.valResources[chainId][validatorIndex].Container.ID +func (m *Manager) ExecCmd(t *testing.T, containerName string, command []string, success string) (bytes.Buffer, bytes.Buffer, error) { + if _, ok := m.resources[containerName]; !ok { + return bytes.Buffer{}, bytes.Buffer{}, fmt.Errorf("no resource %s found", containerName) } + containerId := m.resources[containerName].Container.ID var ( outBuf bytes.Buffer errBuf bytes.Buffer ) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() // We use the `require.Eventually` function because it is only allowed to do one transaction per block without // sequence numbers. For simplicity, we avoid keeping track of the sequence number and just use the `require.Eventually`. require.Eventually( @@ -130,11 +133,11 @@ func (m *Manager) ExecCmd(t *testing.T, chainId string, validatorIndex int, comm } // RunHermesResource runs a Hermes container. Returns the container resource and error if any. -func (m *Manager) RunHermesResource(chainAID, osmoAValMnemonic, chainBID, osmoBValMnemonic string, hermesCfgPath string) (*dockertest.Resource, error) { - var err error - m.hermesResource, err = m.pool.RunWithOptions( +// the name of the hermes container is "--relayer" +func (m *Manager) RunHermesResource(chainAID, osmoARelayerNodeName, osmoAValMnemonic, chainBID, osmoBRelayerNodeName, osmoBValMnemonic string, hermesCfgPath string) (*dockertest.Resource, error) { + hermesResource, err := m.pool.RunWithOptions( &dockertest.RunOptions{ - Name: fmt.Sprintf("%s-%s-relayer", chainAID, chainBID), + Name: hermesContainerName, Repository: m.RelayerRepository, Tag: m.RelayerTag, NetworkID: m.network.Network.ID, @@ -156,8 +159,8 @@ func (m *Manager) RunHermesResource(chainAID, osmoAValMnemonic, chainBID, osmoBV fmt.Sprintf("OSMO_B_E2E_CHAIN_ID=%s", chainBID), fmt.Sprintf("OSMO_A_E2E_VAL_MNEMONIC=%s", osmoAValMnemonic), fmt.Sprintf("OSMO_B_E2E_VAL_MNEMONIC=%s", osmoBValMnemonic), - fmt.Sprintf("OSMO_A_E2E_VAL_HOST=%s", m.valResources[chainAID][0].Container.Name[1:]), - fmt.Sprintf("OSMO_B_E2E_VAL_HOST=%s", m.valResources[chainBID][0].Container.Name[1:]), + fmt.Sprintf("OSMO_A_E2E_VAL_HOST=%s", osmoARelayerNodeName), + fmt.Sprintf("OSMO_B_E2E_VAL_HOST=%s", osmoBRelayerNodeName), }, Entrypoint: []string{ "sh", @@ -170,24 +173,20 @@ func (m *Manager) RunHermesResource(chainAID, osmoAValMnemonic, chainBID, osmoBV if err != nil { return nil, err } - return m.hermesResource, nil -} - -// GetHermesContainerId returns the Hermes container ID. -func (m *Manager) GetHermesContainerID() string { - return m.hermesResource.Container.ID + m.resources[hermesContainerName] = hermesResource + return hermesResource, nil } -// RunValidatorResource runs a validator container. Assings valContainerName to the container. +// RunNodeResource runs a node container. Assings containerName to the container. // Mounts the container on valConfigDir volume on the running host. Returns the container resource and error if any. -func (m *Manager) RunValidatorResource(chainId string, valContainerName, valCondifDir string) (*dockertest.Resource, error) { +func (m *Manager) RunNodeResource(chainId string, containerName, valCondifDir string) (*dockertest.Resource, error) { pwd, err := os.Getwd() if err != nil { return nil, err } runOpts := &dockertest.RunOptions{ - Name: valContainerName, + Name: containerName, Repository: m.OsmosisRepository, Tag: m.OsmosisTag, NetworkID: m.network.Network.ID, @@ -203,11 +202,7 @@ func (m *Manager) RunValidatorResource(chainId string, valContainerName, valCond return nil, err } - chainValidatorResources, exists := m.valResources[chainId] - if !exists { - chainValidatorResources = make([]*dockertest.Resource, 0) - } - m.valResources[chainId] = append(chainValidatorResources, resource) + m.resources[containerName] = resource return resource, nil } @@ -251,62 +246,49 @@ func (m *Manager) PurgeResource(resource *dockertest.Resource) error { return m.pool.Purge(resource) } -// GetValidatorResource returns the validator resource at validatorIndex for the given chainId. -func (m *Manager) GetValidatorResource(chainId string, validatorIndex int) (*dockertest.Resource, bool) { - chainValidators, exists := m.valResources[chainId] - if !exists || validatorIndex >= len(chainValidators) { - return nil, false +// GetNodeResource returns the node resource for containerName. +func (m *Manager) GetNodeResource(containerName string) (*dockertest.Resource, error) { + resource, exists := m.resources[containerName] + if !exists { + return nil, fmt.Errorf("node resource not found: container name: %s", containerName) } - return chainValidators[validatorIndex], true + return resource, nil } -// GetValidatorHostPort returns the port-forwarding address of the running host -// necessary to connect to the validator's portId exposed inside the container. -// The validator container is determined by chainId and validatorIndex. +// GetHostPort returns the port-forwarding address of the running host +// necessary to connect to the portId exposed inside the container. +// The container is determined by containerName. // Returns the host-port or error if any. -func (m *Manager) GetValidatorHostPort(chainId string, validatorIndex int, portId string) (string, error) { - validatorResource, exists := m.GetValidatorResource(chainId, validatorIndex) - if !exists { - return "", fmt.Errorf("validator resource not found: chainId: %s, validatorIndex: %d", chainId, validatorIndex) +func (m *Manager) GetHostPort(containerName string, portId string) (string, error) { + resource, err := m.GetNodeResource(containerName) + if err != nil { + return "", err } - return validatorResource.GetHostPort(portId), nil + return resource.GetHostPort(portId), nil } -// RemoveValidatorResource removes a validator container specified by chainId and containerName. +// RemoveNodeResource removes a node container specified by containerName. // Returns error if any. -func (m *Manager) RemoveValidatorResource(chainId string, containerName string) error { - chainValidators, exists := m.valResources[chainId] - if !exists { - return fmt.Errorf("no validators on chain %s", chainId) +func (m *Manager) RemoveNodeResource(containerName string) error { + resource, err := m.GetNodeResource(containerName) + if err != nil { + return err } - - for validatorIndex, validator := range chainValidators { - if validator.Container.Name[1:] == containerName { - var opts docker.RemoveContainerOptions - opts.ID = validator.Container.ID - opts.Force = true - if err := m.pool.Client.RemoveContainer(opts); err != nil { - return err - } - m.valResources[chainId] = append(chainValidators[:validatorIndex], chainValidators[validatorIndex+1:]...) - return nil - } + var opts docker.RemoveContainerOptions + opts.ID = resource.Container.ID + opts.Force = true + if err := m.pool.Client.RemoveContainer(opts); err != nil { + return err } - - return fmt.Errorf("no validator container %s on chain %s", containerName, chainId) + delete(m.resources, containerName) + return nil } // ClearResources removes all outstanding Docker resources created by the Manager. func (m *Manager) ClearResources() error { - if err := m.pool.Purge(m.hermesResource); err != nil { - return err - } - - for _, vr := range m.valResources { - for _, r := range vr { - if err := m.pool.Purge(r); err != nil { - return err - } + for _, resource := range m.resources { + if err := m.pool.Purge(resource); err != nil { + return err } } diff --git a/tests/e2e/e2e_setup_test.go b/tests/e2e/e2e_setup_test.go index acd8940ce06..0877079dbfa 100644 --- a/tests/e2e/e2e_setup_test.go +++ b/tests/e2e/e2e_setup_test.go @@ -47,11 +47,11 @@ func (s *IntegrationTestSuite) SetupSuite() { // The e2e test flow is as follows: // // 1. Configure two chains - chan A and chain B. - // * For each chain, set up two validators - // * Initialize configs and genesis for all validators. + // * For each chain, set up several validator nodes + // * Initialize configs and genesis for all them. // 2. Start both networks. // 3. Run IBC relayer betweeen the two chains. - // 4. Execute various e2e tests, including IBC. + // 4. Execute various e2e tests, including IBC, upgrade, superfluid. if str := os.Getenv(skipUpgradeEnv); len(str) > 0 { s.skipUpgrade, err = strconv.ParseBool(str) s.Require().NoError(err) diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index 7a05fdcc994..d80b04334c6 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -12,10 +12,12 @@ func (s *IntegrationTestSuite) TestCreatePoolPostUpgrade() { if s.skipUpgrade { s.T().Skip("pool creation tests are broken when upgrade is skipped. To be fixed in #1843") } + chain := s.configurer.GetChainConfig(0) + node, err := chain.GetDefaultNode() + s.NoError(err) - chainA := s.configurer.GetChainConfig(0) - chainA.CreatePool("pool2A.json", initialization.ValidatorWalletName) - chainA.CreatePool("pool2B.json", initialization.ValidatorWalletName) + node.CreatePool("pool2A.json", initialization.ValidatorWalletName) + node.CreatePool("pool2B.json", initialization.ValidatorWalletName) } func (s *IntegrationTestSuite) TestIBCTokenTransfer() { @@ -39,29 +41,41 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { } const walletName = "superfluid-wallet" - chainA := s.configurer.GetChainConfig(0) + chain := s.configurer.GetChainConfig(0) + node, err := chain.GetDefaultNode() + s.NoError(err) - chainA.SubmitSuperfluidProposal("gamm/pool/1") + // enable superfluid via proposal. + node.SubmitSuperfluidProposal("gamm/pool/1") + chain.LatestProposalNumber += 1 + node.DepositProposal(chain.LatestProposalNumber) + for _, node := range chain.NodeConfigs { + node.VoteYesProposal(initialization.ValidatorWalletName, chain.LatestProposalNumber) + } + + walletAddr := node.CreateWallet(walletName) + // send gamm tokens to node's other wallet (non self-delegation wallet) + node.BankSend("100000000000000000000gamm/pool/1", chain.NodeConfigs[0].PublicAddress, walletAddr) + // lock tokens from node 0 on chain A + node.LockTokens("100000000000000000000gamm/pool/1", "240s", walletName) + chain.LatestLockNumber += 1 + // superfluid delegate from non self-delegation wallet to validator 1 on chain. + node.SuperfluidDelegate(chain.LatestLockNumber, chain.NodeConfigs[1].OperatorAddress, walletName) - chainA.DepositProposal() - chainA.VoteYesProposal() - walletAddr := chainA.CreateWallet(0, walletName) - // send gamm tokens to validator's other wallet (non self-delegation wallet) - chainA.BankSend(0, "100000000000000000000gamm/pool/1", chainA.NodeConfigs[0].PublicAddress, walletAddr) - // lock tokens from validator 0 on chain A - chainA.LockTokens(0, "100000000000000000000gamm/pool/1", "240s", walletName) - // superfluid delegate from validator 0 non self-delegation wallet to validator 1 on chain A - chainA.SuperfluidDelegate(chainA.NodeConfigs[1].OperatorAddress, walletName) // create a text prop, deposit and vote yes - chainA.SubmitTextProposal("superfluid vote overwrite test") - chainA.DepositProposal() - chainA.VoteYesProposal() + node.SubmitTextProposal("superfluid vote overwrite test") + chain.LatestProposalNumber += 1 + node.DepositProposal(chain.LatestProposalNumber) + for _, node := range chain.NodeConfigs { + node.VoteYesProposal(initialization.ValidatorWalletName, chain.LatestProposalNumber) + } + // set delegator vote to no - chainA.VoteNoProposal(0, walletName) + node.VoteNoProposal(walletName, chain.LatestProposalNumber) s.Eventually( func() bool { - noTotal, yesTotal, noWithVetoTotal, abstainTotal, err := chainA.QueryPropTally(0, chainA.LatestProposalNumber) + noTotal, yesTotal, noWithVetoTotal, abstainTotal, err := node.QueryPropTally(chain.LatestProposalNumber) if err != nil { return false } @@ -74,13 +88,13 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { time.Second, "Osmosis node failed to retrieve prop tally", ) - noTotal, _, _, _, _ := chainA.QueryPropTally(0, chainA.LatestProposalNumber) + noTotal, _, _, _, _ := node.QueryPropTally(chain.LatestProposalNumber) noTotalFinal, err := strconv.Atoi(noTotal.String()) s.NoError(err) s.Eventually( func() bool { - intAccountBalance, err := chainA.QueryIntermediaryAccount(0, "gamm/pool/1", chainA.NodeConfigs[1].OperatorAddress) + intAccountBalance, err := node.QueryIntermediaryAccount("gamm/pool/1", chain.NodeConfigs[1].OperatorAddress) s.Require().NoError(err) if err != nil { return false From 9edce1105b7f16d76f79d416a4ff318b2dc67d2b Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Thu, 14 Jul 2022 06:16:35 -0700 Subject: [PATCH 071/376] x/gamm: refactor balancer pool_test.go tests to be properly table-driven (#1969) * refactor odd balancer pool tests * update with roman's suggestions Co-authored-by: Roman * add additional check to error case * minor changes to comments and variable names for clarity Co-authored-by: Roman --- x/gamm/pool-models/balancer/pool_test.go | 177 +++++++++-------------- 1 file changed, 72 insertions(+), 105 deletions(-) diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go index c7d6ad8ae6c..fd13bd7766a 100644 --- a/x/gamm/pool-models/balancer/pool_test.go +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -33,131 +33,98 @@ var ( // TestUpdateIntermediaryPoolAssetsLiquidity tests if `updateIntermediaryPoolAssetsLiquidity` returns poolAssetsByDenom map // with the updated liquidity given by the parameter func TestUpdateIntermediaryPoolAssetsLiquidity(t *testing.T) { - testCases := []struct { - name string - - // returns newLiquidity, originalPoolAssetsByDenom, expectedPoolAssetsByDenom - setup func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) + const ( + uosmoValueOriginal = 1_000_000_000_000 + atomValueOriginal = 123 + ionValueOriginal = 657 - err error + // Weight does not affect calculations so it is shared + weight = 100 + ) + testCases := []struct { + name string + newLiquidity sdk.Coins + poolAssets map[string]balancer.PoolAsset + expectPass bool + err error }{ { name: "regular case with multiple pool assets and a subset of newLiquidity to update", - - setup: func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) { - const ( - uosmoValueOriginal = 1_000_000_000_000 - atomValueOriginal = 123 - ionValueOriginal = 657 - - // Weight does not affect calculations so it is shared - weight = 100 - ) - - newLiquidity := sdk.NewCoins( - sdk.NewInt64Coin("uosmo", 1_000), - sdk.NewInt64Coin("atom", 2_000), - sdk.NewInt64Coin("ion", 3_000)) - - originalPoolAssetsByDenom := map[string]balancer.PoolAsset{ - "uosmo": { - Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), - Weight: sdk.NewInt(weight), - }, - "atom": { - Token: sdk.NewInt64Coin("atom", atomValueOriginal), - Weight: sdk.NewInt(weight), - }, - "ion": { - Token: sdk.NewInt64Coin("ion", ionValueOriginal), - Weight: sdk.NewInt(weight), - }, - } - - expectedPoolAssetsByDenom := map[string]balancer.PoolAsset{} - for k, v := range originalPoolAssetsByDenom { - expectedValue := balancer.PoolAsset{Token: v.Token, Weight: v.Weight} - expectedValue.Token.Amount = expectedValue.Token.Amount.Add(newLiquidity.AmountOf(k)) - expectedPoolAssetsByDenom[k] = expectedValue - } - - return newLiquidity, originalPoolAssetsByDenom, expectedPoolAssetsByDenom + newLiquidity: sdk.NewCoins( + sdk.NewInt64Coin("uosmo", 1_000), + sdk.NewInt64Coin("atom", 2_000), + sdk.NewInt64Coin("ion", 3_000)), + poolAssets: map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), + Weight: sdk.NewInt(weight), + }, + "atom": { + Token: sdk.NewInt64Coin("atom", atomValueOriginal), + Weight: sdk.NewInt(weight), + }, + "ion": { + Token: sdk.NewInt64Coin("ion", ionValueOriginal), + Weight: sdk.NewInt(weight), + }, }, + expectPass: true, }, { - name: "new liquidity has no coins", - - setup: func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) { - const ( - uosmoValueOriginal = 1_000_000_000_000 - atomValueOriginal = 123 - ionValueOriginal = 657 - - // Weight does not affect calculations so it is shared - weight = 100 - ) - - newLiquidity := sdk.NewCoins() - - originalPoolAssetsByDenom := map[string]balancer.PoolAsset{ - "uosmo": { - Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), - Weight: sdk.NewInt(weight), - }, - "atom": { - Token: sdk.NewInt64Coin("atom", atomValueOriginal), - Weight: sdk.NewInt(weight), - }, - "ion": { - Token: sdk.NewInt64Coin("ion", ionValueOriginal), - Weight: sdk.NewInt(weight), - }, - } - - return newLiquidity, originalPoolAssetsByDenom, originalPoolAssetsByDenom + name: "new liquidity has no coins", + newLiquidity: sdk.NewCoins(), + poolAssets: map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), + Weight: sdk.NewInt(weight), + }, + "atom": { + Token: sdk.NewInt64Coin("atom", atomValueOriginal), + Weight: sdk.NewInt(weight), + }, + "ion": { + Token: sdk.NewInt64Coin("ion", ionValueOriginal), + Weight: sdk.NewInt(weight), + }, }, + expectPass: true, }, { name: "newLiquidity has a coin that poolAssets don't", - - setup: func() (sdk.Coins, map[string]balancer.PoolAsset, map[string]balancer.PoolAsset) { - const ( - uosmoValueOriginal = 1_000_000_000_000 - - // Weight does not affect calculations so it is shared - weight = 100 - ) - - newLiquidity := sdk.NewCoins( - sdk.NewInt64Coin("juno", 1_000)) - - originalPoolAssetsByDenom := map[string]balancer.PoolAsset{ - "uosmo": { - Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), - Weight: sdk.NewInt(weight), - }, - } - - return newLiquidity, originalPoolAssetsByDenom, originalPoolAssetsByDenom + newLiquidity: sdk.NewCoins( + sdk.NewInt64Coin("juno", 1_000)), + poolAssets: map[string]balancer.PoolAsset{ + "uosmo": { + Token: sdk.NewInt64Coin("uosmo", uosmoValueOriginal), + Weight: sdk.NewInt(weight), + }, }, - - err: fmt.Errorf(balancer.ErrMsgFormatFailedInterimLiquidityUpdate, "juno"), + expectPass: false, + err: fmt.Errorf(balancer.ErrMsgFormatFailedInterimLiquidityUpdate, "juno"), }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - newLiquidity, originalPoolAssetsByDenom, expectedPoolAssetsByDenom := tc.setup() - - err := balancer.UpdateIntermediaryPoolAssetsLiquidity(newLiquidity, originalPoolAssetsByDenom) + expectedPoolAssetsByDenom := map[string]balancer.PoolAsset{} + for denom, asset := range tc.poolAssets { + expectedValue := asset + expectedValue.Token.Amount = expectedValue.Token.Amount.Add(tc.newLiquidity.AmountOf(denom)) + expectedPoolAssetsByDenom[denom] = expectedValue + } - require.Equal(t, tc.err, err) + err := balancer.UpdateIntermediaryPoolAssetsLiquidity(tc.newLiquidity, tc.poolAssets) - if tc.err != nil { - return + if tc.expectPass { + require.NoError(t, tc.err, "test: %v", tc.name) + // make sure actual pool assets are properly updated + require.Equal(t, expectedPoolAssetsByDenom, tc.poolAssets) + } else { + require.Error(t, tc.err, "test: %v", tc.name) + require.Equal(t, tc.err, err) + require.Equal(t, expectedPoolAssetsByDenom, tc.poolAssets) } - - require.Equal(t, expectedPoolAssetsByDenom, originalPoolAssetsByDenom) + return }) } } From b234bb093628b69452dfb5eebb9a2cfc80afd3ea Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 14 Jul 2022 13:34:06 -0400 Subject: [PATCH 072/376] refactor(x/gamm): swap events (#1983) * refactor(x/gamm): swap events * md lint * Update x/gamm/spec/README.md Co-authored-by: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> * Update x/gamm/spec/README.md Co-authored-by: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> * Update x/gamm/spec/README.md Co-authored-by: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Co-authored-by: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> --- x/gamm/keeper/internal/events/emit.go | 70 +++++++ x/gamm/keeper/internal/events/emit_test.go | 88 ++++++++ x/gamm/keeper/keeper.go | 41 ---- x/gamm/keeper/msg_server_test.go | 226 +++++++++++++++++++++ x/gamm/keeper/multihop.go | 3 + x/gamm/keeper/share.go | 5 +- x/gamm/keeper/swap.go | 3 +- x/gamm/keeper/swap_test.go | 102 ++++++---- x/gamm/spec/README.md | 170 +++++++++------- x/gamm/types/events.go | 37 ---- 10 files changed, 547 insertions(+), 198 deletions(-) create mode 100644 x/gamm/keeper/internal/events/emit.go create mode 100644 x/gamm/keeper/internal/events/emit_test.go create mode 100644 x/gamm/keeper/msg_server_test.go diff --git a/x/gamm/keeper/internal/events/emit.go b/x/gamm/keeper/internal/events/emit.go new file mode 100644 index 00000000000..a9d68682fde --- /dev/null +++ b/x/gamm/keeper/internal/events/emit.go @@ -0,0 +1,70 @@ +package events + +import ( + "strconv" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +func EmitSwapEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) { + if ctx.EventManager() == nil { + return + } + + ctx.EventManager().EmitEvents(sdk.Events{ + newSwapEvent(sender, poolId, input, output), + }) +} + +func newSwapEvent(sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) sdk.Event { + return sdk.NewEvent( + types.TypeEvtTokenSwapped, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), + sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(poolId, 10)), + sdk.NewAttribute(types.AttributeKeyTokensIn, input.String()), + sdk.NewAttribute(types.AttributeKeyTokensOut, output.String()), + ) +} + +func EmitAddLiquidityEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) { + if ctx.EventManager() == nil { + return + } + + ctx.EventManager().EmitEvents(sdk.Events{ + newAddLiquidityEvent(sender, poolId, liquidity), + }) +} + +func newAddLiquidityEvent(sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) sdk.Event { + return sdk.NewEvent( + types.TypeEvtPoolJoined, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), + sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(poolId, 10)), + sdk.NewAttribute(types.AttributeKeyTokensIn, liquidity.String()), + ) +} + +func EmitRemoveLiquidityEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) { + if ctx.EventManager() == nil { + return + } + + ctx.EventManager().EmitEvents(sdk.Events{ + newRemoveLiquidityEvent(sender, poolId, liquidity), + }) +} + +func newRemoveLiquidityEvent(sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) sdk.Event { + return sdk.NewEvent( + types.TypeEvtPoolExited, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), + sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(poolId, 10)), + sdk.NewAttribute(types.AttributeKeyTokensOut, liquidity.String()), + ) +} diff --git a/x/gamm/keeper/internal/events/emit_test.go b/x/gamm/keeper/internal/events/emit_test.go new file mode 100644 index 00000000000..dcaa845b427 --- /dev/null +++ b/x/gamm/keeper/internal/events/emit_test.go @@ -0,0 +1,88 @@ +package events_test + +import ( + "strconv" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" + + "github.com/osmosis-labs/osmosis/v7/app/apptesting" + "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper/internal/events" + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +type GammEventsTestSuite struct { + apptesting.KeeperTestHelper +} + +const ( + addressString = "addr1---------------" + testDenomA = "denoma" + testDenomB = "denomb" + testDenomC = "denomc" + testDenomD = "denomd" +) + +func TestGammEventsTestSuite(t *testing.T) { + suite.Run(t, new(GammEventsTestSuite)) +} + +func (suite *GammEventsTestSuite) TestEmitSwapEvent() { + + testcases := map[string]struct { + ctx sdk.Context + testAccountAddr sdk.AccAddress + poolId uint64 + tokensIn sdk.Coins + tokensOut sdk.Coins + }{ + "basic valid": { + ctx: suite.CreateTestContext(), + testAccountAddr: sdk.AccAddress([]byte(addressString)), + poolId: 1, + tokensIn: sdk.NewCoins(sdk.NewCoin(testDenomA, sdk.NewInt(1234))), + tokensOut: sdk.NewCoins(sdk.NewCoin(testDenomB, sdk.NewInt(5678))), + }, + "context with no event manager": { + ctx: sdk.Context{}, + }, + "valid with multiple tokens in and out": { + ctx: suite.CreateTestContext(), + testAccountAddr: sdk.AccAddress([]byte(addressString)), + poolId: 200, + tokensIn: sdk.NewCoins(sdk.NewCoin(testDenomA, sdk.NewInt(12)), sdk.NewCoin(testDenomB, sdk.NewInt(99))), + tokensOut: sdk.NewCoins(sdk.NewCoin(testDenomC, sdk.NewInt(88)), sdk.NewCoin(testDenomD, sdk.NewInt(34))), + }, + } + + for name, tc := range testcases { + suite.Run(name, func() { + expectedEvents := sdk.Events{ + sdk.NewEvent( + types.TypeEvtTokenSwapped, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeySender, tc.testAccountAddr.String()), + sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(tc.poolId, 10)), + sdk.NewAttribute(types.AttributeKeyTokensIn, tc.tokensIn.String()), + sdk.NewAttribute(types.AttributeKeyTokensOut, tc.tokensOut.String()), + ), + } + + hasNoEventManager := tc.ctx.EventManager() == nil + + // System under test. + events.EmitSwapEvent(tc.ctx, tc.testAccountAddr, tc.poolId, tc.tokensIn, tc.tokensOut) + + // Assertions + if hasNoEventManager { + // If there is no event manager on context, this is a no-op. + return + } + + eventManager := tc.ctx.EventManager() + actualEvents := eventManager.Events() + suite.Equal(expectedEvents, actualEvents) + }) + } +} diff --git a/x/gamm/keeper/keeper.go b/x/gamm/keeper/keeper.go index 97d937d0703..6e557a5247e 100644 --- a/x/gamm/keeper/keeper.go +++ b/x/gamm/keeper/keeper.go @@ -2,7 +2,6 @@ package keeper import ( "fmt" - "strconv" "github.com/osmosis-labs/osmosis/v7/x/gamm/types" @@ -61,46 +60,6 @@ func NewKeeper(cdc codec.BinaryCodec, storeKey sdk.StoreKey, paramSpace paramtyp } } -// nolint: unused -func (k *Keeper) createSwapEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.TypeEvtTokenSwapped, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), - sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(poolId, 10)), - sdk.NewAttribute(types.AttributeKeyTokensIn, input.String()), - sdk.NewAttribute(types.AttributeKeyTokensOut, output.String()), - ), - }) -} - -// nolint: unused -func (k *Keeper) createAddLiquidityEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.TypeEvtPoolJoined, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), - sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(poolId, 10)), - sdk.NewAttribute(types.AttributeKeyTokensIn, liquidity.String()), - ), - }) -} - -// nolint: unused -func (k *Keeper) createRemoveLiquidityEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.TypeEvtPoolExited, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), - sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(poolId, 10)), - sdk.NewAttribute(types.AttributeKeyTokensOut, liquidity.String()), - ), - }) -} - // Set the gamm hooks. func (k *Keeper) SetHooks(gh types.GammHooks) *Keeper { if k.hooks != nil { diff --git a/x/gamm/keeper/msg_server_test.go b/x/gamm/keeper/msg_server_test.go new file mode 100644 index 00000000000..a4011404e5f --- /dev/null +++ b/x/gamm/keeper/msg_server_test.go @@ -0,0 +1,226 @@ +package keeper_test + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" + + "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +const ( + doesNotExistDenom = "nodenom" +) + +var _ = suite.TestingSuite(nil) + +// TestSwapExactAmountIn_Events tests that events are correctly emitted +// when calling SwapExactAmountIn. +func (suite *KeeperTestSuite) TestSwapExactAmountIn_Events() { + const ( + tokenInMinAmount = 1 + tokenIn = 5 + ) + + testcases := map[string]struct { + routes []types.SwapAmountInRoute + tokenIn sdk.Coin + tokenOutMinAmount sdk.Int + expectError bool + expectedSwapEvents int + expectedMessageEvents int + }{ + "zero hops": { + routes: []types.SwapAmountInRoute{}, + tokenIn: sdk.NewCoin("foo", sdk.NewInt(tokenIn)), + tokenOutMinAmount: sdk.NewInt(tokenInMinAmount), + expectedMessageEvents: 1, // 1 gamm. + }, + "one hop": { + routes: []types.SwapAmountInRoute{ + { + PoolId: 1, + TokenOutDenom: "bar", + }, + }, + tokenIn: sdk.NewCoin("foo", sdk.NewInt(tokenIn)), + tokenOutMinAmount: sdk.NewInt(tokenInMinAmount), + expectedSwapEvents: 1, + expectedMessageEvents: 3, // 1 gamm + 2 tendermint. + }, + "two hops": { + routes: []types.SwapAmountInRoute{ + { + PoolId: 1, + TokenOutDenom: "bar", + }, + { + PoolId: 2, + TokenOutDenom: "baz", + }, + }, + tokenIn: sdk.NewCoin("foo", sdk.NewInt(tokenIn)), + tokenOutMinAmount: sdk.NewInt(tokenInMinAmount), + expectedSwapEvents: 2, + expectedMessageEvents: 5, // 1 gamm + 4 tendermint. + }, + "invalid - two hops, denom does not exist": { + routes: []types.SwapAmountInRoute{ + { + PoolId: 1, + TokenOutDenom: "bar", + }, + { + PoolId: 2, + TokenOutDenom: "baz", + }, + }, + tokenIn: sdk.NewCoin(doesNotExistDenom, sdk.NewInt(tokenIn)), + tokenOutMinAmount: sdk.NewInt(tokenInMinAmount), + expectError: true, + }, + } + + for name, tc := range testcases { + suite.Run(name, func() { + suite.Setup() + ctx := suite.Ctx + + suite.PrepareBalancerPool() + suite.PrepareBalancerPool() + + msgServer := keeper.NewMsgServerImpl(suite.App.GAMMKeeper) + + // Reset event counts to 0 by creating a new manager. + ctx = ctx.WithEventManager(sdk.NewEventManager()) + suite.Equal(0, len(ctx.EventManager().Events())) + + response, err := msgServer.SwapExactAmountIn(sdk.WrapSDKContext(ctx), &types.MsgSwapExactAmountIn{ + Sender: suite.TestAccs[0].String(), + Routes: tc.routes, + TokenIn: tc.tokenIn, + TokenOutMinAmount: tc.tokenOutMinAmount, + }) + + if !tc.expectError { + suite.NoError(err) + suite.NotNil(response) + } + + assertEventEmitted(suite, ctx, types.TypeEvtTokenSwapped, tc.expectedSwapEvents) + assertEventEmitted(suite, ctx, sdk.EventTypeMessage, tc.expectedMessageEvents) + }) + } +} + +// TestSwapExactAmountOut_Events tests that events are correctly emitted +// when calling SwapExactAmountOut. +func (suite *KeeperTestSuite) TestSwapExactAmountOut_Events() { + const ( + // Max positive int64. + tokenInMaxAmount = int64(^uint64(0) >> 1) + tokenOut = 5 + ) + + testcases := map[string]struct { + routes []types.SwapAmountOutRoute + tokenOut sdk.Coin + tokenInMaxAmount sdk.Int + expectError bool + expectedSwapEvents int + expectedMessageEvents int + }{ + "zero hops": { + routes: []types.SwapAmountOutRoute{}, + tokenOut: sdk.NewCoin("foo", sdk.NewInt(tokenOut)), + tokenInMaxAmount: sdk.NewInt(tokenInMaxAmount), + expectedMessageEvents: 1, // 1 gamm. + }, + "one hop": { + routes: []types.SwapAmountOutRoute{ + { + PoolId: 1, + TokenInDenom: "bar", + }, + }, + tokenOut: sdk.NewCoin("foo", sdk.NewInt(tokenOut)), + tokenInMaxAmount: sdk.NewInt(tokenInMaxAmount), + expectedSwapEvents: 1, + expectedMessageEvents: 3, // 1 gamm + 2 tendermint. + }, + "two hops": { + routes: []types.SwapAmountOutRoute{ + { + PoolId: 1, + TokenInDenom: "bar", + }, + { + PoolId: 2, + TokenInDenom: "baz", + }, + }, + tokenOut: sdk.NewCoin("foo", sdk.NewInt(tokenOut)), + tokenInMaxAmount: sdk.NewInt(tokenInMaxAmount), + expectedSwapEvents: 2, + expectedMessageEvents: 5, // 1 gamm + 4 tendermint. + }, + "invalid - two hops, denom does not exist": { + routes: []types.SwapAmountOutRoute{ + { + PoolId: 1, + TokenInDenom: "bar", + }, + { + PoolId: 2, + TokenInDenom: "baz", + }, + }, + tokenOut: sdk.NewCoin(doesNotExistDenom, sdk.NewInt(tokenOut)), + tokenInMaxAmount: sdk.NewInt(tokenInMaxAmount), + expectError: true, + }, + } + + for name, tc := range testcases { + suite.Run(name, func() { + suite.Setup() + ctx := suite.Ctx + + suite.PrepareBalancerPool() + suite.PrepareBalancerPool() + + msgServer := keeper.NewMsgServerImpl(suite.App.GAMMKeeper) + + // Reset event counts to 0 by creating a new manager. + ctx = ctx.WithEventManager(sdk.NewEventManager()) + suite.Equal(0, len(ctx.EventManager().Events())) + + response, err := msgServer.SwapExactAmountOut(sdk.WrapSDKContext(ctx), &types.MsgSwapExactAmountOut{ + Sender: suite.TestAccs[0].String(), + Routes: tc.routes, + TokenOut: tc.tokenOut, + TokenInMaxAmount: tc.tokenInMaxAmount, + }) + + if !tc.expectError { + suite.NoError(err) + suite.NotNil(response) + } + + assertEventEmitted(suite, ctx, types.TypeEvtTokenSwapped, tc.expectedSwapEvents) + assertEventEmitted(suite, ctx, sdk.EventTypeMessage, tc.expectedMessageEvents) + }) + } +} + +func assertEventEmitted(suite *KeeperTestSuite, ctx sdk.Context, eventTypeExpected string, numEventsExpected int) { + allEvents := ctx.EventManager().Events() + // filter out other events + actualEvents := make([]sdk.Event, 0, 1) + for _, event := range allEvents { + if event.Type == eventTypeExpected { + actualEvents = append(actualEvents, event) + } + } + suite.Equal(numEventsExpected, len(actualEvents)) +} diff --git a/x/gamm/keeper/multihop.go b/x/gamm/keeper/multihop.go index 852cdd9cb7b..1e80fb17c8d 100644 --- a/x/gamm/keeper/multihop.go +++ b/x/gamm/keeper/multihop.go @@ -52,6 +52,9 @@ func (k Keeper) MultihopSwapExactAmountOut( if err != nil { return sdk.Int{}, err } + if len(insExpected) == 0 { + return sdk.Int{}, nil + } insExpected[0] = tokenInMaxAmount diff --git a/x/gamm/keeper/share.go b/x/gamm/keeper/share.go index ae76041b03c..7423c264ba6 100644 --- a/x/gamm/keeper/share.go +++ b/x/gamm/keeper/share.go @@ -3,6 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper/internal/events" "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) @@ -22,7 +23,7 @@ func (k Keeper) applyJoinPoolStateChange(ctx sdk.Context, pool types.PoolI, join return err } - ctx.EventManager().EmitEvent(types.CreateAddLiquidityEvent(ctx, joiner, pool.GetId(), joinCoins)) + events.EmitAddLiquidityEvent(ctx, joiner, pool.GetId(), joinCoins) k.hooks.AfterJoinPool(ctx, joiner, pool.GetId(), joinCoins, numShares) k.RecordTotalLiquidityIncrease(ctx, joinCoins) return nil @@ -44,7 +45,7 @@ func (k Keeper) applyExitPoolStateChange(ctx sdk.Context, pool types.PoolI, exit return err } - ctx.EventManager().EmitEvent(types.CreateRemoveLiquidityEvent(ctx, exiter, pool.GetId(), exitCoins)) + events.EmitRemoveLiquidityEvent(ctx, exiter, pool.GetId(), exitCoins) k.hooks.AfterExitPool(ctx, exiter, pool.GetId(), numShares, exitCoins) k.RecordTotalLiquidityDecrease(ctx, exitCoins) return nil diff --git a/x/gamm/keeper/swap.go b/x/gamm/keeper/swap.go index ec3f6f71acb..a9fa3ee6533 100644 --- a/x/gamm/keeper/swap.go +++ b/x/gamm/keeper/swap.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper/internal/events" "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) @@ -166,7 +167,7 @@ func (k Keeper) updatePoolForSwap( return err } - ctx.EventManager().EmitEvent(types.CreateSwapEvent(ctx, sender, pool.GetId(), tokensIn, tokensOut)) + events.EmitSwapEvent(ctx, sender, pool.GetId(), tokensIn, tokensOut) k.hooks.AfterSwap(ctx, sender, pool.GetId(), tokensIn, tokensOut) k.RecordTotalLiquidityIncrease(ctx, tokensIn) k.RecordTotalLiquidityDecrease(ctx, tokensOut) diff --git a/x/gamm/keeper/swap_test.go b/x/gamm/keeper/swap_test.go index 4b4f9beb1f3..9b647d093b9 100644 --- a/x/gamm/keeper/swap_test.go +++ b/x/gamm/keeper/swap_test.go @@ -4,10 +4,14 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) +var _ = suite.TestingSuite(nil) + func (suite *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() { type param struct { tokenIn sdk.Coin @@ -80,29 +84,34 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() { } for _, test := range tests { - // Init suite for each test. - suite.SetupTest() - poolId := suite.PrepareBalancerPool() - keeper := suite.App.GAMMKeeper - - if test.expectPass { - spotPriceBefore, err := keeper.CalculateSpotPrice(suite.Ctx, poolId, test.param.tokenIn.Denom, test.param.tokenOutDenom) - suite.NoError(err, "test: %v", test.name) - - tokenOutAmount, err := keeper.SwapExactAmountIn(suite.Ctx, suite.TestAccs[0], poolId, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount) - suite.NoError(err, "test: %v", test.name) - suite.True(tokenOutAmount.Equal(test.param.expectedTokenOut), "test: %v", test.name) - - spotPriceAfter, err := keeper.CalculateSpotPrice(suite.Ctx, poolId, test.param.tokenIn.Denom, test.param.tokenOutDenom) - suite.NoError(err, "test: %v", test.name) - - // Ratio of the token out should be between the before spot price and after spot price. - tradeAvgPrice := test.param.tokenIn.Amount.ToDec().Quo(tokenOutAmount.ToDec()) - suite.True(tradeAvgPrice.GT(spotPriceBefore) && tradeAvgPrice.LT(spotPriceAfter), "test: %v", test.name) - } else { - _, err := keeper.SwapExactAmountIn(suite.Ctx, suite.TestAccs[0], poolId, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount) - suite.Error(err, "test: %v", test.name) - } + suite.Run(test.name, func() { + // Init suite for each test. + suite.SetupTest() + poolId := suite.PrepareBalancerPool() + keeper := suite.App.GAMMKeeper + ctx := suite.Ctx + + if test.expectPass { + spotPriceBefore, err := keeper.CalculateSpotPrice(ctx, poolId, test.param.tokenIn.Denom, test.param.tokenOutDenom) + suite.NoError(err, "test: %v", test.name) + + tokenOutAmount, err := keeper.SwapExactAmountIn(ctx, suite.TestAccs[0], poolId, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount) + suite.NoError(err, "test: %v", test.name) + suite.True(tokenOutAmount.Equal(test.param.expectedTokenOut), "test: %v", test.name) + + assertEventEmitted(suite, ctx, types.TypeEvtTokenSwapped, 1) + + spotPriceAfter, err := keeper.CalculateSpotPrice(ctx, poolId, test.param.tokenIn.Denom, test.param.tokenOutDenom) + suite.NoError(err, "test: %v", test.name) + + // Ratio of the token out should be between the before spot price and after spot price. + tradeAvgPrice := test.param.tokenIn.Amount.ToDec().Quo(tokenOutAmount.ToDec()) + suite.True(tradeAvgPrice.GT(spotPriceBefore) && tradeAvgPrice.LT(spotPriceAfter), "test: %v", test.name) + } else { + _, err := keeper.SwapExactAmountIn(ctx, suite.TestAccs[0], poolId, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount) + suite.Error(err, "test: %v", test.name) + } + }) } } @@ -178,32 +187,37 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountOut() { } for _, test := range tests { - // Init suite for each test. - suite.SetupTest() - poolId := suite.PrepareBalancerPool() + suite.Run(test.name, func() { + // Init suite for each test. + suite.SetupTest() + poolId := suite.PrepareBalancerPool() - keeper := suite.App.GAMMKeeper + keeper := suite.App.GAMMKeeper + ctx := suite.Ctx - if test.expectPass { - spotPriceBefore, err := keeper.CalculateSpotPrice(suite.Ctx, poolId, test.param.tokenInDenom, test.param.tokenOut.Denom) - suite.NoError(err, "test: %v", test.name) + if test.expectPass { + spotPriceBefore, err := keeper.CalculateSpotPrice(ctx, poolId, test.param.tokenInDenom, test.param.tokenOut.Denom) + suite.NoError(err, "test: %v", test.name) - tokenInAmount, err := keeper.SwapExactAmountOut(suite.Ctx, suite.TestAccs[0], poolId, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut) - suite.NoError(err, "test: %v", test.name) - suite.True(tokenInAmount.Equal(test.param.expectedTokenInAmount), - "test: %v\n expect_eq actual: %s, expected: %s", - test.name, tokenInAmount, test.param.expectedTokenInAmount) + tokenInAmount, err := keeper.SwapExactAmountOut(ctx, suite.TestAccs[0], poolId, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut) + suite.NoError(err, "test: %v", test.name) + suite.True(tokenInAmount.Equal(test.param.expectedTokenInAmount), + "test: %v\n expect_eq actual: %s, expected: %s", + test.name, tokenInAmount, test.param.expectedTokenInAmount) - spotPriceAfter, err := keeper.CalculateSpotPrice(suite.Ctx, poolId, test.param.tokenInDenom, test.param.tokenOut.Denom) - suite.NoError(err, "test: %v", test.name) + assertEventEmitted(suite, ctx, types.TypeEvtTokenSwapped, 1) - // Ratio of the token out should be between the before spot price and after spot price. - tradeAvgPrice := tokenInAmount.ToDec().Quo(test.param.tokenOut.Amount.ToDec()) - suite.True(tradeAvgPrice.GT(spotPriceBefore) && tradeAvgPrice.LT(spotPriceAfter), "test: %v", test.name) - } else { - _, err := keeper.SwapExactAmountOut(suite.Ctx, suite.TestAccs[0], poolId, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut) - suite.Error(err, "test: %v", test.name) - } + spotPriceAfter, err := keeper.CalculateSpotPrice(ctx, poolId, test.param.tokenInDenom, test.param.tokenOut.Denom) + suite.NoError(err, "test: %v", test.name) + + // Ratio of the token out should be between the before spot price and after spot price. + tradeAvgPrice := tokenInAmount.ToDec().Quo(test.param.tokenOut.Amount.ToDec()) + suite.True(tradeAvgPrice.GT(spotPriceBefore) && tradeAvgPrice.LT(spotPriceAfter), "test: %v", test.name) + } else { + _, err := keeper.SwapExactAmountOut(suite.Ctx, suite.TestAccs[0], poolId, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut) + suite.Error(err, "test: %v", test.name) + } + }) } } diff --git a/x/gamm/spec/README.md b/x/gamm/spec/README.md index 5189919cca9..a986d7f355a 100644 --- a/x/gamm/spec/README.md +++ b/x/gamm/spec/README.md @@ -147,13 +147,9 @@ The GAMM module also has a **PoolCreationFee** parameter, which currently is set [comment]: <> (TODO Add better description of how the weights affect things) - -

- - ## Messages The `x/gamm` module supports the following message types: @@ -196,7 +192,6 @@ The `x/gamm` module supports the following message types: ## Transactions - ### Create pool Create a new liquidity pool and provide initial liquidity to it. @@ -235,13 +230,13 @@ The configuration json file contains the following parameters: "future-governor": "" } ``` + ::: ::: warning There is now a 100 OSMO fee for creating pools. ::: - ### Join pool Add liquidity to a specified pool to get an **exact** amount of LP shares while specifying a **maximum** number tokens willing to swap to receive said LP shares. @@ -257,9 +252,8 @@ Join `pool 3` with a **maximum** of `.037753 AKT` and the corresponding amount o ```sh osmosisd tx gamm join-pool --pool-id 3 --max-amounts-in 37753ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4 --share-amount-out 1227549469722224220 --from WALLET_NAME --chain-id osmosis-1 ``` -::: - +::: ### Exit pool @@ -276,9 +270,8 @@ Exit `pool 3` with for **exactly** `1.136326462628731195 gamm/pool/3` in order t ```sh osmosisd tx gamm exit-pool --pool-id 3 --min-amounts-out 33358ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4 --share-amount-in 1136326462628731195 --from WALLET_NAME --chain-id osmosis-1 ``` -::: - +::: ### Join-swap-extern-amount-in @@ -297,10 +290,8 @@ Join `pool 3` with **exactly** `.200000 AKT` (and `0 OSMO`) to get a **minimum** ```sh osmosisd tx gamm join-swap-extern-amount-in 200000ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4 3234812471272883046 --pool-id 3 --from WALLET_NAME --chain-id osmosis-1 ``` -::: - - +::: ### Exit-swap-extern-amount-out @@ -319,10 +310,8 @@ Exit `pool 3` by removing a **maximum** of `3.408979387886193586 gamm/pool/3` an ```sh osmosisd tx gamm exit-swap-extern-amount-out 199430ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4 3408979387886193586 --pool-id 3 --from WALLET_NAME --chain-id osmosis-1 ``` -::: - - +::: ### Join-swap-share-amount-out @@ -339,10 +328,8 @@ Swap a **maximum** of `0.312466 OSMO` for the corresponding amount of `AKT`, the ```sh osmosisd tx gamm join-swap-share-amount-out uosmo 312466 14481270389710236872 --pool-id 3 --from WALLET_NAME --chain-id osmosis-1 ``` -::: - - +::: ### Exit-swap-share-amount-in @@ -359,14 +346,13 @@ Exit `pool 3` by removing **exactly** `14.563185400026723131 gamm/pool/3` and sw ```sh osmosisd tx gamm exit-swap-share-amount-in uosmo 14563185400026723131 298548 --pool-id 3 --from WALLET_NAME --chain-id osmosis-1 ``` -::: +::: ### Swap-exact-amount-in Swap an **exact** amount of tokens for a **minimum** of another token, similar to swapping a token on the trade screen GUI. - ```sh osmosisd tx gamm swap-exact-amount-in [token-in] [token-out-min-amount] --pool-id --from --chain-id ``` @@ -378,9 +364,8 @@ Swap **exactly** `.407239 AKT` through `pool 3` into a **minimum** of `.140530 O ```sh osmosisd tx gamm swap-exact-amount-in 407239ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4 140530 --swap-route-pool-ids 3 --swap-route-denoms uosmo --from WALLET_NAME --chain-id osmosis-1 ``` -::: - +::: ### Swap-exact-amount-out @@ -398,15 +383,11 @@ Swap a **maximum** of `.407239 AKT` through `pool 3` into **exactly** `.140530 O osmosisd tx gamm swap-exact-amount-out 140530uosmo 407239 --swap-route-pool-ids 3 --swap-route-denoms ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4 --from WALLET_NAME --chain-id osmosis-1 ``` - [comment]: <> (Other resources Creating a liquidity bootstrapping pool and Creating a pool with a pool file) ::: - - ## Queries and Transactions - ## Queries The **Query** submodule of the GAMM module provides the logic to request information from the liquidity pools. It contains the following functions: @@ -423,26 +404,35 @@ The **Query** submodule of the GAMM module provides the logic to request informa - [Total Share](#total-share) ### Estimate Swap Exact Amount In + Query the estimated result of the [Swap Exact Amount In](#swap-exact-amount-in) transaction. Note that the flags *swap-route-pool* and *swap-route-denoms* are required. + #### Usage + ```sh osmosisd query gamm estimate-swap-exact-amount-in [flags] ``` + #### Example + Query the amount of ATOM the sender would receive for swapping 1 OSMO in pool 1. ```sh osmosisd query gamm estimate-swap-exact-amount-in 1 osmo123nfq6m8f88m4g3sky570unsnk4zng4uqv7cm8 1000000uosmo --swap-route-pool-ids 1 --swap-route-denoms ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 ``` - ### Estimate Swap Exact Amount Out + Query the estimated result of the [Swap Exact Amount Out](#swap-exact-amount-out) transaction. Note that the flags *swap-route-pool* and *swap-route-denoms* are required. + #### Usage + ```sh osmosisd query gamm estimate-swap-exact-amount-out [flags] ``` + #### Example + Query the amount of OSMO the sender would require to swap 1 ATOM out of pool 1. ```sh @@ -450,14 +440,17 @@ osmosisd query gamm estimate-swap-exact-amount-out 1 osmo123nfq6m8f88m4g3sky570u ``` ### Num Pools + Query the number of active pools. #### Usage + ```sh osmosisd query gamm num-pools ``` ## Pool + Query the parameter and assets of a specific pool. ### Usage @@ -474,10 +467,12 @@ Query parameters and assets from pool 1. osmosisd query gamm pool 1 ``` - ### Pool Assets + Query the assets of a specific pool. This query is a reduced form of the [Pool](#pool) query. + #### Usage + ```sh osmosisd query gamm pool-assets [flags] ``` @@ -490,56 +485,64 @@ Query the assets from pool 1. osmosisd query gamm pool-assets 1 ``` - ### Pool Params + Query the parameters of a specific pool. This query is a reduced form of the [Pool](#pool) query. + #### Usage + ```sh osmosisd query gamm pool-params [flags] ``` Query the parameters from pool 1. + #### Example + ```sh osmosisd query gamm pool-params 1 ``` - ### Pools -Query parameters and assets of all active pools. +Query parameters and assets of all active pools. #### Usage + Query the price of OSMO based on the price of ATOM in pool 1. ```sh osmosisd query gamm spot-price 1 uosmo ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 ``` - ### Total Liquidity + Query the total liquidity of all active pools. + #### Usage + ```sh osmosisd query gamm total-liquidity ``` - ### Total Share + Query the total amount of GAMM shares of a specific pool. + #### Usage + ```sh osmosisd query gamm total-share [flags] ``` + #### Example + Query the total amount of GAMM shares of pool 1. ```sh osmosisd query gamm total-share 1 ``` - - ## Transactions The **Transaction** submodule of the GAMM module provides the logic to create and interact with the liquidity pools. It contains the following functions: @@ -569,9 +572,8 @@ Query the amount of ATOM (or `ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA ```sh osmosisd query gamm estimate-swap-exact-amount-in 1 osmo123nfq6m8f88m4g3sky570unsnk4zng4uqv7cm8 1000000uosmo --swap-route-pool-ids 1 --swap-route-denoms ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 ``` -::: - +::: ### Estimate-swap-exact-amount-out @@ -588,9 +590,8 @@ Query the amount of `OSMO` the `sender` would require to swap 1 ATOM (or `100000 ```sh osmosisd query gamm estimate-swap-exact-amount-out 1 osmo123nfq6m8f88m4g3sky570unsnk4zng4uqv7cm8 1000000ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 --swap-route-pool-ids 1 --swap-route-denoms uosmo ``` -::: - +::: ### Num-pools @@ -600,8 +601,6 @@ Query the number of active pools. osmosisd query gamm num-pools ``` - - ### Pool Query the parameter and assets of a specific pool. @@ -644,12 +643,11 @@ Which outputs: amount: "21388879300450" weight: "500000.000000000000000000" ``` -::: +::: ### Pool-assets - Query the assets of a specific pool. This query is a reduced form of the [pool](#pool) query. ```sh @@ -677,8 +675,8 @@ poolAssets: denom: uosmo weight: "536870912000000" ``` -::: +::: ### Pool Params @@ -703,26 +701,19 @@ swap_fee: "0.003000000000000000" exit_fee: "0.000000000000000000" smooth_weight_change_params: null ``` -::: - +::: ### Pools - Query parameters and assets of all active pools. ```sh osmosisd query gamm pools ``` - - - - ### Spot-price - Query the spot price of a pool asset based on a specific pool it is in. ```sh @@ -746,26 +737,16 @@ spotPrice: "5.314387014412388547" In other words, at the time of this writing, ~5.314 OSMO is equivalent to 1 ATOM. ::: - - - - ### Total-liquidity - Query the total liquidity of all active pools. ```sh osmosisd query gamm total-liquidity ``` - - - - ### Total-share - Query the total amount of GAMM shares of a specific pool. ```sh @@ -792,9 +773,8 @@ Indicating there are a total of `252328895.834096787303097071 gamm/pool/1` at th ::: - - ### Create Pool + Create a new liquidity pool and provide the initial liquidity to it. Pool initialization parameters must be provided through a JSON file using the flag *pool-file*. #### Usage @@ -814,7 +794,9 @@ The configuration file *config.json* must specify the following parameters. "future-governor": [number of hours] } ``` + #### Example + Create a new ATOM-OSMO liquidity pool with a swap and exit fee of 1%. ```sh @@ -833,9 +815,8 @@ The configuration file contains the following parameters. } ``` - - ### Join Pool + Join a specific pool with a custom amount of tokens. Note that the flags *pool-id*, *max-amounts-in* and *share-amount-out* are required. #### Usage @@ -852,8 +833,8 @@ Join pool 1 with 1 OSMO and the respective amount of ATOM, using myKeyringWallet osmosisd tx gamm join-pool --pool-id 2 --max-amounts-in 1000000uosmo --max-amounts-in 1000000uion --share-amount-out 1000000 --from myKeyringWallet ``` - ### Exit Pool + Exit a specific pool with a custom amount of tokens. Note that the flags *pool-id*, *min-amounts-out* and *share-amount-in* are required. #### Usage @@ -870,8 +851,8 @@ Exit pool one with 1 OSMO and the respective amount of ATOM using myKeyringWalle osmosisd tx gamm exit-pool --pool-id 1 --min-amounts-out 1000000uosmo --share-amount-in 1000000 --from myKeyringWallet ``` - ### Join Swap Extern Amount In + Note that the flags *pool-id* is required. #### Usage @@ -886,8 +867,8 @@ osmosisd tx gamm join-swap-extern-amount-in [token-in] [share-out-min-amount] [f osmosisd tx gamm join-swap-extern-amount-in 1000000uosmo 1000000 --pool-id 1 --from myKeyringWallet ``` - ### Exit Swap Extern Amount Out + Note that the flag *pool-id* is required. ```sh @@ -900,8 +881,8 @@ osmosisd tx gamm exit-swap-extern-amount-out [token-out] [share-in-max-amount] [ osmosisd tx gamm exit-swap-extern-amount-out 1000000uosmo 1000000 --pool-id 1 --from myKeyringWallet ``` - ### Join Swap Share Amount Out + Note that the flag *pool-id* is required. #### Usage @@ -916,8 +897,8 @@ osmosisd tx gamm join-swap-share-amount-out [token-in-denom] [token-in-max-amoun osmosisd tx gamm join-swap-share-amount-out uosmo 1000000 1000000 --pool-id 1 --from myKeyringWallet ``` - ### Exit Swap Share Amount In + Note that the flag *pool-id* is required. #### Usage @@ -933,6 +914,7 @@ osmosisd tx gamm exit-swap-share-amount-in uosmo 1000000 1000000 --pool-id 1 --f ``` ### Swap Exact Amount In + Swap an exact amount of tokens into a specific pool. Note that the flags *swap-route-pool-ids* and *swap-route-denoms* are required. #### Usage @@ -949,8 +931,8 @@ Swap 1 OSMO through pool 1 into at least 0.3 ATOM using MyKeyringWallet. osmosisd tx gamm swap-exact-amount-in 1000000uosmo 300000 --swap-route-pool-ids 1 --swap-route-denoms ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 --from MyKeyringWallet ``` - ### Swap Exact Amount Out + Swap an exact amount of tokens out of a specific pool. Note that the flags *swap-route-pool-ids* and *swap-route-denoms* are required. ### Usage @@ -968,6 +950,48 @@ osmosisd tx gamm swap-exact-amount-out 1000000ibc/27394FB092D2ECCD56123C74F36E4C ``` ## Other resources + * [Creating a liquidity bootstrapping pool](./client/docs/create-lbp-pool.md) * [Creating a pool with a pool file](./client/docs/create-pool.md) +## Events + +There are 4 types of events that exist in GAMM: + +* `sdk.EventTypeMessage` - "message" +* `types.TypeEvtPoolJoined` - "pool_joined" +* `types.TypeEvtPoolExited` - "pool_exited" +* `types.TypeEvtPoolCreated` - "pool_created" +* `types.TypeEvtTokenSwapped` - "token_swapped" + +### `sdk.EventTypeMessage` + +This event is emitted in the message server when any of the gamm messages finish execution. + +TBD + +### `types.TypeEvtPoolExited` + +TBD + +### `types.TypeEvtPoolCreated` + +TBD + +### `types.TypeEvtTokenSwapped` + +This event is emitted after one of `SwapExactAmountOut` or `SwapExactAmountIn` updates +pool state successfully. + +It consists of the following attributes: + +* `sdk.AttributeKeyModule` - "module" + * The value is the module's name - "gamm". +* sdk.AttributeKeySender + * The value is the address of the sender who created the swap message. +* types.AttributeKeyPoolId + * The value is the pool id of the pool where swap occurs. +* types.AttributeKeyTokensIn + * The value is the string representation of the tokens being swapped in. +* types.AttributeKeyTokensOut + * The value is the string representation of the tokens being swapped out. diff --git a/x/gamm/types/events.go b/x/gamm/types/events.go index e65c07f42d1..baed080cf77 100644 --- a/x/gamm/types/events.go +++ b/x/gamm/types/events.go @@ -1,11 +1,5 @@ package types -import ( - "strconv" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - const ( TypeEvtPoolJoined = "pool_joined" TypeEvtPoolExited = "pool_exited" @@ -18,34 +12,3 @@ const ( AttributeKeyTokensIn = "tokens_in" AttributeKeyTokensOut = "tokens_out" ) - -func CreateSwapEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) sdk.Event { - return sdk.NewEvent( - TypeEvtTokenSwapped, - sdk.NewAttribute(sdk.AttributeKeyModule, AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), - sdk.NewAttribute(AttributeKeyPoolId, strconv.FormatUint(poolId, 10)), - sdk.NewAttribute(AttributeKeyTokensIn, input.String()), - sdk.NewAttribute(AttributeKeyTokensOut, output.String()), - ) -} - -func CreateAddLiquidityEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) sdk.Event { - return sdk.NewEvent( - TypeEvtPoolJoined, - sdk.NewAttribute(sdk.AttributeKeyModule, AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), - sdk.NewAttribute(AttributeKeyPoolId, strconv.FormatUint(poolId, 10)), - sdk.NewAttribute(AttributeKeyTokensIn, liquidity.String()), - ) -} - -func CreateRemoveLiquidityEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, liquidity sdk.Coins) sdk.Event { - return sdk.NewEvent( - TypeEvtPoolExited, - sdk.NewAttribute(sdk.AttributeKeyModule, AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), - sdk.NewAttribute(AttributeKeyPoolId, strconv.FormatUint(poolId, 10)), - sdk.NewAttribute(AttributeKeyTokensOut, liquidity.String()), - ) -} From 12b961e01372e52f05bb0663a66b4b807b16db92 Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 14 Jul 2022 15:04:45 -0400 Subject: [PATCH 073/376] refactor(x/mint): introduce distributeDeveloperRewards methods; unit tests (1/2) (#2065) --- x/mint/keeper/export_test.go | 16 +- x/mint/keeper/keeper.go | 108 +++++++----- x/mint/keeper/keeper_test.go | 311 ++++++++++++++++++++++++++++++++--- 3 files changed, 368 insertions(+), 67 deletions(-) diff --git a/x/mint/keeper/export_test.go b/x/mint/keeper/export_test.go index 2dfe835160d..67dd378ed54 100644 --- a/x/mint/keeper/export_test.go +++ b/x/mint/keeper/export_test.go @@ -1,8 +1,14 @@ package keeper -import sdk "github.com/cosmos/cosmos-sdk/types" +import ( + sdk "github.com/cosmos/cosmos-sdk/types" -type ErrInvalidRatio = invalidRatioError + "github.com/osmosis-labs/osmosis/v7/x/mint/types" +) + +type ( + ErrInvalidRatio = invalidRatioError +) const ( DeveloperVestingAmount = developerVestingAmount @@ -16,6 +22,10 @@ var ( GetProportions = getProportions ) -func (k Keeper) DistributeToModule(ctx sdk.Context, recipientModule string, mintedCoin sdk.Coin, proportion sdk.Dec) (sdk.Coin, error) { +func (k Keeper) DistributeToModule(ctx sdk.Context, recipientModule string, mintedCoin sdk.Coin, proportion sdk.Dec) (sdk.Int, error) { return k.distributeToModule(ctx, recipientModule, mintedCoin, proportion) } + +func (k Keeper) DistributeDeveloperRewards(ctx sdk.Context, totalMintedCoin sdk.Coin, developerRewardsProportion sdk.Dec, developerRewardsReceivers []types.WeightedAddress) (sdk.Int, error) { + return k.distributeDeveloperRewards(ctx, totalMintedCoin, developerRewardsProportion, developerRewardsReceivers) +} diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index dbca5cdb54e..f010155c8e7 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -33,7 +33,7 @@ type invalidRatioError struct { } func (e invalidRatioError) Error() string { - return fmt.Sprintf("mint allocation ratio %s is greater than 1", e.ActualRatio) + return fmt.Sprintf("mint allocation ratio (%s) is greater than 1", e.ActualRatio) } var ( @@ -198,98 +198,126 @@ func (k Keeper) DistributeMintedCoin(ctx sdk.Context, mintedCoin sdk.Coin) error params := k.GetParams(ctx) proportions := params.DistributionProportions - // allocate staking incentives into fee collector account to be moved to on next begin blocker by staking module - stakingIncentivesCoin, err := k.distributeToModule(ctx, k.feeCollectorName, mintedCoin, proportions.Staking) + // allocate staking incentives into fee collector account to be moved to on next begin blocker by staking module account. + stakingIncentivesAmount, err := k.distributeToModule(ctx, k.feeCollectorName, mintedCoin, proportions.Staking) if err != nil { return err } - // allocate pool allocation ratio to pool-incentives module account account - poolIncentivesCoin, err := k.distributeToModule(ctx, poolincentivestypes.ModuleName, mintedCoin, proportions.PoolIncentives) + // allocate pool allocation ratio to pool-incentives module account. + poolIncentivesAmount, err := k.distributeToModule(ctx, poolincentivestypes.ModuleName, mintedCoin, proportions.PoolIncentives) if err != nil { return err } - devRewardCoin, err := getProportions(ctx, mintedCoin, proportions.DeveloperRewards) + // allocate dev rewards to respective accounts from developer vesting module account. + devRewardAmount, err := k.distributeDeveloperRewards(ctx, mintedCoin, proportions.DeveloperRewards, params.WeightedDeveloperRewardsReceivers) if err != nil { return err } + + // subtract from original provision to ensure no coins left over after the allocations + communityPoolAmount := mintedCoin.Amount.Sub(stakingIncentivesAmount).Sub(poolIncentivesAmount).Sub(devRewardAmount) + err = k.distrKeeper.FundCommunityPool(ctx, sdk.NewCoins(sdk.NewCoin(params.MintDenom, communityPoolAmount)), k.accountKeeper.GetModuleAddress(types.ModuleName)) + if err != nil { + return err + } + + // call an hook after the minting and distribution of new coins + k.hooks.AfterDistributeMintedCoin(ctx, mintedCoin) + + return err +} + +// distributeToModule distributes mintedCoin multiplied by proportion to the recepientModule account. +func (k Keeper) distributeToModule(ctx sdk.Context, recipientModule string, mintedCoin sdk.Coin, proportion sdk.Dec) (sdk.Int, error) { + distributionCoin, err := getProportions(ctx, mintedCoin, proportion) + if err != nil { + return sdk.Int{}, err + } + if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, recipientModule, sdk.NewCoins(distributionCoin)); err != nil { + return sdk.Int{}, err + } + return distributionCoin.Amount, nil +} + +// distributeDeveloperRewards distributes developer rewards from developer vesting module account +// to the respective account receivers by weight (developerRewardsReceivers). +// If no developer reward receivers given, funds the community pool instead. +// Returns the total amount distributed from the developer vesting module account. +// Updates supply offsets to reflect the amount of coins distributed. This is done so because the developer rewards distributions are +// allocated from its own module account, not the mint module accont (TODO: next step in https://github.com/osmosis-labs/osmosis/issues/1916). +// Returns nil on success, error otherwise. +// With respect to input parameters, errors occur when: +// - developerRewardsProportion is greater than 1. +// - invalid address in developer rewards receivers. +// - the balance of developer module account is less than totalMintedCoin * developerRewardsProportion. +// - the balance of mint module is less than totalMintedCoin * developerRewardsProportion. +// CONTRACT: +// - weights in developerRewardsReceivers add up to 1. +// - addresses in developerRewardsReceivers are valid. +func (k Keeper) distributeDeveloperRewards(ctx sdk.Context, totalMintedCoin sdk.Coin, developerRewardsProportion sdk.Dec, developerRewardsReceivers []types.WeightedAddress) (sdk.Int, error) { + devRewardCoin, err := getProportions(ctx, totalMintedCoin, developerRewardsProportion) + if err != nil { + return sdk.Int{}, err + } devRewardCoins := sdk.NewCoins(devRewardCoin) // This is supposed to come from the developer vesting module address, not the mint module address // we over-allocated to the mint module address earlier though, so we burn it right here. if err := k.bankKeeper.BurnCoins(ctx, types.ModuleName, devRewardCoins); err != nil { - return err + return sdk.Int{}, err } // Take the current balance of the developer rewards pool and remove it from the supply offset // We re-introduce the new supply at the end, in order to avoid any rounding discrepancies. - developerAccountBalance := k.bankKeeper.GetBalance(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), mintedCoin.Denom) - k.bankKeeper.AddSupplyOffset(ctx, mintedCoin.Denom, developerAccountBalance.Amount) + developerAccountBalance := k.bankKeeper.GetBalance(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), totalMintedCoin.Denom) + k.bankKeeper.AddSupplyOffset(ctx, totalMintedCoin.Denom, developerAccountBalance.Amount) - if len(params.WeightedDeveloperRewardsReceivers) == 0 { + if len(developerRewardsReceivers) == 0 { // fund community pool when rewards address is empty if err := k.distrKeeper.FundCommunityPool(ctx, devRewardCoins, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)); err != nil { - return err + return sdk.Int{}, err } } else { // allocate developer rewards to addresses by weight - for _, w := range params.WeightedDeveloperRewardsReceivers { + for _, w := range developerRewardsReceivers { devPortionCoin, err := getProportions(ctx, devRewardCoin, w.Weight) if err != nil { - return err + return sdk.Int{}, err } devRewardPortionCoins := sdk.NewCoins(devPortionCoin) if w.Address == "" { err := k.distrKeeper.FundCommunityPool(ctx, devRewardPortionCoins, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) if err != nil { - return err + return sdk.Int{}, err } } else { devRewardsAddr, err := sdk.AccAddressFromBech32(w.Address) if err != nil { - return err + return sdk.Int{}, err } // If recipient is vesting account, pay to account according to its vesting condition err = k.bankKeeper.SendCoinsFromModuleToAccount( ctx, types.DeveloperVestingModuleAcctName, devRewardsAddr, devRewardPortionCoins) if err != nil { - return err + return sdk.Int{}, err } } } } // Take the new balance of the developer rewards pool and add it back to the supply offset deduction - developerAccountBalance = k.bankKeeper.GetBalance(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), mintedCoin.Denom) - k.bankKeeper.AddSupplyOffset(ctx, mintedCoin.Denom, developerAccountBalance.Amount.Neg()) - - // subtract from original provision to ensure no coins left over after the allocations - communityPoolCoin := mintedCoin.Sub(stakingIncentivesCoin).Sub(poolIncentivesCoin).Sub(devRewardCoin) - err = k.distrKeeper.FundCommunityPool(ctx, sdk.NewCoins(communityPoolCoin), k.accountKeeper.GetModuleAddress(types.ModuleName)) - if err != nil { - return err - } + developerAccountBalance = k.bankKeeper.GetBalance(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), totalMintedCoin.Denom) + k.bankKeeper.AddSupplyOffset(ctx, totalMintedCoin.Denom, developerAccountBalance.Amount.Neg()) - // call an hook after the minting and distribution of new coins - k.hooks.AfterDistributeMintedCoin(ctx, mintedCoin) - - return err -} - -func (k Keeper) distributeToModule(ctx sdk.Context, recipientModule string, mintedCoin sdk.Coin, proportion sdk.Dec) (sdk.Coin, error) { - distributionCoin, err := getProportions(ctx, mintedCoin, proportion) - if err != nil { - return sdk.Coin{}, err - } - if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, recipientModule, sdk.NewCoins(distributionCoin)); err != nil { - return sdk.Coin{}, err - } - return distributionCoin, nil + return devRewardCoin.Amount, nil } // getProportions gets the balance of the `MintedDenom` from minted coins and returns coins according to the // allocation ratio. Returns error if ratio is greater than 1. +// TODO: this currently rounds down and is the cause of rounding discrepancies. +// To be fixed in: https://github.com/osmosis-labs/osmosis/issues/1917 func getProportions(ctx sdk.Context, mintedCoin sdk.Coin, ratio sdk.Dec) (sdk.Coin, error) { if ratio.GT(sdk.OneDec()) { return sdk.Coin{}, invalidRatioError{ratio} diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index c619af24699..3483eb790e3 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -1,12 +1,16 @@ package keeper_test import ( + "fmt" "testing" "time" + "github.com/cosmos/btcutil/bech32" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/distribution" + distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" @@ -25,6 +29,13 @@ type KeeperTestSuite struct { queryClient types.QueryClient } +var ( + testAddressOne = sdk.AccAddress([]byte("addr1---------------")) + testAddressTwo = sdk.AccAddress([]byte("addr2---------------")) + testAddressThree = sdk.AccAddress([]byte("addr3---------------")) + testAddressFour = sdk.AccAddress([]byte("addr4---------------")) +) + func TestKeeperTestSuite(t *testing.T) { suite.Run(t, new(KeeperTestSuite)) } @@ -133,7 +144,7 @@ func (suite *KeeperTestSuite) TestGetProportions() { } } -func (suite *KeeperTestSuite) TestDistrAssetToDeveloperRewardsAddr() { +func (suite *KeeperTestSuite) TestDistributeMintedCoin_ToDeveloperRewardsAddr() { var ( distrTo = lockuptypes.QueryCondition{ LockQueryType: lockuptypes.ByDuration, @@ -142,7 +153,7 @@ func (suite *KeeperTestSuite) TestDistrAssetToDeveloperRewardsAddr() { } params = suite.App.MintKeeper.GetParams(suite.Ctx) gaugeCoins = sdk.Coins{sdk.NewInt64Coin("stake", 10000)} - gaugeCreator = sdk.AccAddress([]byte("addr2---------------")) + gaugeCreator = testAddressTwo mintLPtokens = sdk.Coins{sdk.NewInt64Coin(distrTo.Denom, 200)} ) @@ -155,7 +166,7 @@ func (suite *KeeperTestSuite) TestDistrAssetToDeveloperRewardsAddr() { name: "one dev reward address", weightedAddresses: []types.WeightedAddress{ { - Address: sdk.AccAddress([]byte("addr1---------------")).String(), + Address: testAddressOne.String(), Weight: sdk.NewDec(1), }}, mintCoin: sdk.NewCoin("stake", sdk.NewInt(10000)), @@ -164,11 +175,11 @@ func (suite *KeeperTestSuite) TestDistrAssetToDeveloperRewardsAddr() { name: "multiple dev reward addresses", weightedAddresses: []types.WeightedAddress{ { - Address: sdk.AccAddress([]byte("addr3---------------")).String(), + Address: testAddressThree.String(), Weight: sdk.NewDecWithPrec(6, 1), }, { - Address: sdk.AccAddress([]byte("addr4---------------")).String(), + Address: testAddressFour.String(), Weight: sdk.NewDecWithPrec(4, 1), }}, mintCoin: sdk.NewCoin("stake", sdk.NewInt(100000)), @@ -389,7 +400,7 @@ func (suite *KeeperTestSuite) TestDistributeToModule() { ) tests := map[string]struct { - preMintAmount sdk.Coin + preMintCoin sdk.Coin recepientModule string mintedCoin sdk.Coin @@ -399,21 +410,21 @@ func (suite *KeeperTestSuite) TestDistributeToModule() { expectPanic bool }{ "pre-mint == distribute - poolincentives module - full amount - success": { - preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + preMintCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), recepientModule: poolincentivestypes.ModuleName, mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), proportion: sdk.NewDec(1), }, "pre-mint > distribute - developer vesting module - two thirds - success": { - preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(101)), + preMintCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(101)), recepientModule: poolincentivestypes.ModuleName, mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), proportion: sdk.NewDecWithPrec(2, 1).Quo(sdk.NewDecWithPrec(3, 1)), }, "pre-mint < distribute (0) - error": { - preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0)), + preMintCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0)), recepientModule: poolincentivestypes.ModuleName, mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), @@ -422,7 +433,7 @@ func (suite *KeeperTestSuite) TestDistributeToModule() { expectedError: true, }, "denom does not exist - error": { - preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + preMintCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), recepientModule: poolincentivestypes.ModuleName, mintedCoin: sdk.NewCoin(denomDoesNotExist, sdk.NewInt(100)), @@ -431,7 +442,7 @@ func (suite *KeeperTestSuite) TestDistributeToModule() { expectedError: true, }, "invalid module account -panic": { - preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), + preMintCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), recepientModule: moduleAccountDoesNotExist, mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), @@ -440,7 +451,7 @@ func (suite *KeeperTestSuite) TestDistributeToModule() { expectPanic: true, }, "proportion greater than 1 - error": { - preMintAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(300)), + preMintCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(300)), recepientModule: poolincentivestypes.ModuleName, mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), @@ -459,37 +470,289 @@ func (suite *KeeperTestSuite) TestDistributeToModule() { ctx := suite.Ctx // Setup. - suite.NoError(mintKeeper.MintCoins(ctx, sdk.NewCoins(tc.preMintAmount))) + suite.NoError(mintKeeper.MintCoins(ctx, sdk.NewCoins(tc.preMintCoin))) // TODO: Should not be truncated. Remove truncation after rounding errors are addressed and resolved. // Ref: https://github.com/osmosis-labs/osmosis/issues/1917 expectedDistributed := tc.mintedCoin.Amount.ToDec().Mul(tc.proportion).TruncateInt() - oldMintModuleBalance := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.ModuleName), tc.mintedCoin.Denom) - oldRecepientModuleBalance := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(tc.recepientModule), tc.mintedCoin.Denom) + oldMintModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.ModuleName), tc.mintedCoin.Denom).Amount + oldRecepientModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(tc.recepientModule), tc.mintedCoin.Denom).Amount // Test. actualDistributed, err := mintKeeper.DistributeToModule(ctx, tc.recepientModule, tc.mintedCoin, tc.proportion) // Assertions. - actualMintModuleBalance := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.ModuleName), tc.mintedCoin.Denom) - actualRecepientModuleBalance := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(tc.recepientModule), tc.mintedCoin.Denom) + actualMintModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.ModuleName), tc.mintedCoin.Denom).Amount + actualRecepientModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(tc.recepientModule), tc.mintedCoin.Denom).Amount if tc.expectedError { suite.Error(err) - suite.Equal(actualDistributed, sdk.Coin{}) + suite.Equal(actualDistributed, sdk.Int{}) // Old balances should not change. - suite.Equal(oldMintModuleBalance.Amount.Int64(), actualMintModuleBalance.Amount.Int64()) - suite.Equal(oldRecepientModuleBalance.Amount.Int64(), actualRecepientModuleBalance.Amount.Int64()) + suite.Equal(oldMintModuleBalanceAmount.Int64(), actualMintModuleBalanceAmount.Int64()) + suite.Equal(oldRecepientModuleBalanceAmount.Int64(), actualRecepientModuleBalanceAmount.Int64()) return } suite.NoError(err) - suite.Equal(tc.mintedCoin.Denom, actualDistributed.Denom) - suite.Equal(expectedDistributed, actualDistributed.Amount) + suite.Equal(expectedDistributed, actualDistributed) // Updated balances. - suite.Equal(oldMintModuleBalance.Sub(actualDistributed).Amount.Int64(), actualMintModuleBalance.Amount.Int64()) - suite.Equal(oldRecepientModuleBalance.Add(actualDistributed).Amount.Int64(), actualRecepientModuleBalance.Amount.Int64()) + suite.Equal(oldMintModuleBalanceAmount.Sub(actualDistributed).Int64(), actualMintModuleBalanceAmount.Int64()) + suite.Equal(oldRecepientModuleBalanceAmount.Add(actualDistributed).Int64(), actualRecepientModuleBalanceAmount.Int64()) + }) + }) + } +} + +// TestDistributeDeveloperRewards tests the following: +// - distribution from developer module account to the given weighted addressed occurs. +// - developer vesting module account balance is correctly updated. +// - all developer addressed are updated with correct proportions. +// - mint module account balance is updated - burn over allocations. +// - if recepients are empty - community pool us updated. +func (suite *KeeperTestSuite) TestDistributeDeveloperRewards() { + const ( + invalidAddress = "invalid" + ) + + var ( + validLargePreMintAmount = sdk.NewInt(keeper.DeveloperVestingAmount) + validPreMintAmountAddOne = sdk.NewInt(keeper.DeveloperVestingAmount).Add(sdk.OneInt()) + validPreMintCoin = sdk.NewCoin(sdk.DefaultBondDenom, validLargePreMintAmount) + validPreMintCoinSubOne = sdk.NewCoin(sdk.DefaultBondDenom, validLargePreMintAmount.Sub(sdk.OneInt())) + ) + + tests := map[string]struct { + preMintCoin sdk.Coin + + mintedCoin sdk.Coin + proportion sdk.Dec + recepientAddresses []types.WeightedAddress + + expectedError error + expectPanic bool + // See testcases with this flag set to true for details. + allowBalanceChange bool + // See testcases with this flag set to true for details. + expectSameAddresses bool + }{ + "valid case with 1 weighted address": { + preMintCoin: validPreMintCoin, + + mintedCoin: validPreMintCoin, + proportion: sdk.NewDecWithPrec(153, 3), + recepientAddresses: []types.WeightedAddress{ + { + Address: testAddressOne.String(), + Weight: sdk.NewDec(1), + }, + }, + }, + "valid case with 3 weighted addresses and custom large mint amount under pre mint": { + preMintCoin: validPreMintCoin, + + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(939_123_546_789)), + proportion: sdk.NewDecWithPrec(31347, 5), + recepientAddresses: []types.WeightedAddress{ // .231 + .4 + .369 + { + Address: testAddressOne.String(), + Weight: sdk.NewDecWithPrec(231, 3), + }, + { + Address: testAddressTwo.String(), + Weight: sdk.NewDecWithPrec(4, 1), + }, + { + Address: testAddressThree.String(), + Weight: sdk.NewDecWithPrec(369, 3), + }, + }, + }, + "valid case with 2 addresses that are the same": { + preMintCoin: validPreMintCoin, + + mintedCoin: validPreMintCoin, + proportion: sdk.NewDecWithPrec(123, 3), + recepientAddresses: []types.WeightedAddress{ + { + Address: testAddressOne.String(), + Weight: sdk.NewDecWithPrec(5, 1), + }, + { + Address: testAddressOne.String(), + Weight: sdk.NewDecWithPrec(5, 1), + }, + }, + // Since we have double the full amount allocated + /// to the same address, the balance assertions will + // differ by expecting the full minted amount. + expectSameAddresses: true, + }, + "valid case with 0 reward receivers - goes to community pool": { + preMintCoin: validPreMintCoin, + + mintedCoin: validPreMintCoin, + proportion: sdk.NewDecWithPrec(153, 3), + }, + "valid case with 0 amount of total minted coin": { + preMintCoin: validPreMintCoin, + + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, sdk.ZeroInt()), + proportion: sdk.NewDecWithPrec(153, 3), + recepientAddresses: []types.WeightedAddress{ + { + Address: testAddressOne.String(), + Weight: sdk.NewDec(1), + }, + }, + }, + "invalid value for developer rewards proportion (> 1) - error": { + preMintCoin: validPreMintCoin, + + mintedCoin: validPreMintCoin, + proportion: sdk.NewDec(2), + recepientAddresses: []types.WeightedAddress{ + { + Address: testAddressOne.String(), + Weight: sdk.NewDec(1), + }, + }, + + expectedError: keeper.ErrInvalidRatio{ActualRatio: sdk.NewDec(2)}, + }, + "invalid address in developer reward receivers - error": { + preMintCoin: validPreMintCoin, + + mintedCoin: validPreMintCoin, + proportion: sdk.NewDecWithPrec(153, 3), + recepientAddresses: []types.WeightedAddress{ + { + Address: invalidAddress, + Weight: sdk.NewDec(1), + }, + }, + + expectedError: sdkerrors.Wrap(bech32.ErrInvalidLength(len(invalidAddress)), "decoding bech32 failed"), + // This case should not happen in practice due to parameter validation. + // The method spec also requires that all recepient addresses are valid by CONTRACT. + // Since we still handle error returned by the converion from string to address, + // we try to cover it explicitly. However, it changes balance so we don't test it. + allowBalanceChange: true, + }, + "pre-mint < distribute * proportion - error": { + preMintCoin: validPreMintCoinSubOne, + + mintedCoin: validPreMintCoin, + proportion: sdk.OneDec(), + recepientAddresses: []types.WeightedAddress{ + { + Address: testAddressOne.String(), + Weight: sdk.NewDec(1), + }, + }, + expectedError: sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, fmt.Sprintf("%s is smaller than %s", validPreMintCoinSubOne, validPreMintCoin)), + }, + "distribute * proportion < pre-mint but distribute * proportion > developer vesting amount - error": { + preMintCoin: validPreMintCoin, + + mintedCoin: sdk.NewCoin(sdk.DefaultBondDenom, validPreMintAmountAddOne), + proportion: sdk.OneDec(), + recepientAddresses: []types.WeightedAddress{ + { + Address: testAddressOne.String(), + Weight: sdk.NewDec(1), + }, + }, + expectedError: sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, fmt.Sprintf("%s is smaller than %s", validPreMintCoin, sdk.NewCoin(sdk.DefaultBondDenom, validPreMintAmountAddOne))), + }, + } + for name, tc := range tests { + suite.Run(name, func() { + suite.Setup() + + osmoutils.ConditionalPanic(suite.T(), tc.expectPanic, func() { + mintKeeper := suite.App.MintKeeper + bankKeeper := suite.App.BankKeeper + accountKeeper := suite.App.AccountKeeper + ctx := suite.Ctx + + // Setup. + suite.NoError(mintKeeper.MintCoins(ctx, sdk.NewCoins(tc.preMintCoin))) + + // TODO: Should not be truncated. Remove truncation after rounding errors are addressed and resolved. + // Ref: https://github.com/osmosis-labs/osmosis/issues/1917 + expectedDistributed := tc.mintedCoin.Amount.ToDec().Mul(tc.proportion).TruncateInt() + + oldMintModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.ModuleName), tc.mintedCoin.Denom).Amount + oldDeveloperVestingModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), tc.mintedCoin.Denom).Amount + oldCommunityPoolBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(distributiontypes.ModuleName), tc.mintedCoin.Denom).Amount + oldDeveloperRewardsBalanceAmounts := make([]sdk.Int, len(tc.recepientAddresses)) + for i, weightedAddress := range tc.recepientAddresses { + // No error check to be able to test invalid addresses. + address, _ := sdk.AccAddressFromBech32(weightedAddress.Address) + oldDeveloperRewardsBalanceAmounts[i] = bankKeeper.GetBalance(ctx, address, tc.mintedCoin.Denom).Amount + } + + // Test. + actualDistributed, err := mintKeeper.DistributeDeveloperRewards(ctx, tc.mintedCoin, tc.proportion, tc.recepientAddresses) + + // Assertions. + actualMintModuleBalance := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.ModuleName), tc.mintedCoin.Denom) + actualDeveloperVestingModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), tc.mintedCoin.Denom).Amount + actualCommunityPoolModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(distributiontypes.ModuleName), tc.mintedCoin.Denom).Amount + + if tc.expectedError != nil { + suite.Error(err) + suite.Equal(tc.expectedError.Error(), err.Error()) + suite.Equal(actualDistributed, sdk.Int{}) + + // See testcases with this flag set to true for details. + if tc.allowBalanceChange { + return + } + // Old balances should not change. + suite.Equal(oldMintModuleBalanceAmount.Int64(), actualMintModuleBalance.Amount.Int64()) + suite.Equal(oldDeveloperVestingModuleBalanceAmount.Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) + suite.Equal(oldCommunityPoolBalanceAmount.Int64(), actualCommunityPoolModuleBalanceAmount.Int64()) + return + } + + suite.NoError(err) + suite.Equal(expectedDistributed, actualDistributed) + + // Updated balances. + + // Burn from mint module account. We over-allocate. + // To be fixed: https://github.com/osmosis-labs/osmosis/issues/2025 + suite.Equal(oldMintModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualMintModuleBalance.Amount.Int64()) + + // Allocate to community pool when no addresses are provided. + if len(tc.recepientAddresses) == 0 { + suite.Equal(oldDeveloperVestingModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) + suite.Equal(oldCommunityPoolBalanceAmount.Add(expectedDistributed).Int64(), actualCommunityPoolModuleBalanceAmount.Int64()) + return + } + + // TODO: these should be equal, slightly off due to known rounding issues: https://github.com/osmosis-labs/osmosis/issues/1917 + // suite.Equal(oldDeveloperVestingModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) + + for i, weightedAddress := range tc.recepientAddresses { + address, err := sdk.AccAddressFromBech32(weightedAddress.Address) + suite.NoError(err) + + // TODO: truncation should not occur: https://github.com/osmosis-labs/osmosis/issues/1917 + expectedAllocation := expectedDistributed.ToDec().Mul(tc.recepientAddresses[i].Weight).TruncateInt() + actualDeveloperRewardsBalanceAmounts := bankKeeper.GetBalance(ctx, address, tc.mintedCoin.Denom).Amount + + // Edge case. See testcases with this flag set to true for details. + if tc.expectSameAddresses { + suite.Equal(oldDeveloperRewardsBalanceAmounts[i].Add(expectedAllocation.Mul(sdk.NewInt(2))).Int64(), actualDeveloperRewardsBalanceAmounts.Int64()) + return + } + + suite.Equal(oldDeveloperRewardsBalanceAmounts[i].Add(expectedAllocation).Int64(), actualDeveloperRewardsBalanceAmounts.Int64()) + } }) }) } From 314e7d36db3613a3768b803ff3b7c29e1de7efd8 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Thu, 14 Jul 2022 14:44:24 -0500 Subject: [PATCH 074/376] Fix simulator determinism & enable it (#2054) * This commit fixes simulator determinism + a couple other bugs * Restore old API for lockup * Fix last introduced bug * Remove this lint from linter * Apply tx.SignWithPrivKey improvement --- .github/workflows/sim.yml | 2 +- .golangci.yml | 3 ++ simulation/executor/event_stats.go | 3 +- simulation/executor/params.go | 2 +- simulation/executor/simulate.go | 1 + simulation/executor/util.go | 48 ----------------------- simulation/types/account.go | 18 ++++++++- simulation/types/manager.go | 8 +++- simulation/types/txbuilder.go | 63 +++++++++++++++++++++++++++++- tests/simulator/sim_test.go | 15 +++---- x/lockup/simulation/operations.go | 9 +++-- x/mint/simulation/genesis.go | 7 ---- 12 files changed, 104 insertions(+), 75 deletions(-) diff --git a/.github/workflows/sim.yml b/.github/workflows/sim.yml index c57ce38711a..cf2b59c99dd 100644 --- a/.github/workflows/sim.yml +++ b/.github/workflows/sim.yml @@ -18,4 +18,4 @@ jobs: run: go version - name: Run simulation run: | - # make test-sim + make test-sim diff --git a/.golangci.yml b/.golangci.yml index 7c9d3d831d1..60b55e94d19 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -111,5 +111,8 @@ issues: - linters: - stylecheck text: "ST1003:" # requires identifiers with "id" to be "ID". + - linters: + - stylecheck + text: "ST1005:" # punctuation in error messages max-issues-per-linter: 10000 max-same-issues: 10000 diff --git a/simulation/executor/event_stats.go b/simulation/executor/event_stats.go index 0965ed34899..cd2d01a064b 100644 --- a/simulation/executor/event_stats.go +++ b/simulation/executor/event_stats.go @@ -56,9 +56,10 @@ func (es EventStats) ExportJSON(path string) { func (es EventStats) exportEvents(ExportStatsPath string, w io.Writer) { if ExportStatsPath != "" { - fmt.Println("Exporting simulation statistics...") + fmt.Printf("Exporting simulation statistics to %s...", ExportStatsPath) es.ExportJSON(ExportStatsPath) } else { + // TODO: Don't print, also export to a file of timestamp'd path es.Print(w) } } diff --git a/simulation/executor/params.go b/simulation/executor/params.go index 44c90395173..ccf226334b9 100644 --- a/simulation/executor/params.go +++ b/simulation/executor/params.go @@ -81,7 +81,7 @@ func (p Params) BlockSizeTransitionMatrix() simulation.TransitionMatrix { func RandomParams(r *rand.Rand) Params { return Params{ pastEvidenceFraction: r.Float64(), - numKeys: simulation.RandIntBetween(r, 2, 2500), // number of accounts created for the simulation + numKeys: simulation.RandIntBetween(r, 50, 2500), // number of accounts created for the simulation evidenceFraction: r.Float64() / 2, initialLivenessWeightings: []int{simulation.RandIntBetween(r, 1, 80), r.Intn(10), r.Intn(10)}, livenessTransitionMatrix: defaultLivenessTransitionMatrix, diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index 4fd61d25f9d..13f2b932a90 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -174,6 +174,7 @@ func SimulateFromSeed( "\nSimulation complete; Final height (blocks): %d, final time (seconds): %v, operations ran: %d\n", simState.header.Height, simState.header.Time, simState.opCount, ) + simState.logWriter.PrintLogs() } simState.eventStats.exportEvents(config.ExportStatsPath, w) diff --git a/simulation/executor/util.go b/simulation/executor/util.go index 2ecbbbd3ee6..e21849d4d5d 100644 --- a/simulation/executor/util.go +++ b/simulation/executor/util.go @@ -9,7 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" simulation "github.com/cosmos/cosmos-sdk/types/simulation" @@ -80,50 +79,3 @@ type OperationInput struct { Bankkeeper BankKeeper ModuleName string } - -// GenAndDeliverTxWithRandFees generates a transaction with a random fee and delivers it. -func GenAndDeliverTxWithRandFees(txCtx OperationInput) (simulation.OperationMsg, []simulation.FutureOperation, error) { - account := txCtx.AccountKeeper.GetAccount(txCtx.Context, txCtx.SimAccount.Address) - spendable := txCtx.Bankkeeper.SpendableCoins(txCtx.Context, account.GetAddress()) - - var fees sdk.Coins - var err error - - coins, hasNeg := spendable.SafeSub(txCtx.CoinsSpentInMsg) - if hasNeg { - return simulation.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "message doesn't leave room for fees"), nil, err - } - - spendableFeeCoins := coins.FilterDenoms([]string{sdk.DefaultBondDenom}) - fees, err = simulation.RandomFees(txCtx.R, txCtx.Context, spendableFeeCoins) - if err != nil { - return simulation.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to generate fees"), nil, err - } - return GenAndDeliverTx(txCtx, fees) -} - -// GenAndDeliverTx generates a transactions and delivers it. -func GenAndDeliverTx(txCtx OperationInput, fees sdk.Coins) (simulation.OperationMsg, []simulation.FutureOperation, error) { - account := txCtx.AccountKeeper.GetAccount(txCtx.Context, txCtx.SimAccount.Address) - tx, err := helpers.GenTx( - txCtx.TxGen, - []sdk.Msg{txCtx.Msg}, - fees, - helpers.DefaultGenTxGas, - txCtx.Context.ChainID(), - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - txCtx.SimAccount.PrivKey, - ) - - if err != nil { - return simulation.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to generate mock tx"), nil, err - } - - _, _, err = txCtx.App.Deliver(txCtx.TxGen.TxEncoder(), tx) - if err != nil { - return simulation.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to deliver tx"), nil, err - } - - return simulation.NewOperationMsg(txCtx.Msg, true, "", txCtx.Cdc), nil, nil -} diff --git a/simulation/types/account.go b/simulation/types/account.go index 7b2f504d934..dcde70d0842 100644 --- a/simulation/types/account.go +++ b/simulation/types/account.go @@ -1,6 +1,7 @@ package simulation import ( + "errors" "fmt" "math" @@ -62,6 +63,17 @@ func (sim *SimCtx) FindAccount(address sdk.Address) (simulation.Account, bool) { return simulation.Account{}, false } +func (sim *SimCtx) RandomSimAccountWithBalance(ctx sdk.Context) (simulation.Account, error) { + accHasBal := func(acc simulation.Account) bool { + return len(sim.App.GetBankKeeper().SpendableCoins(ctx, acc.Address)) != 0 + } + acc, found := sim.RandomSimAccountWithConstraint(accHasBal) + if !found { + return simulation.Account{}, errors.New("no address with balance found. Check simulator configuration, this should be very rare.") + } + return acc, nil +} + // Returns (account, randSubsetCoins, found), so if found = false, then no such address exists. // randSubsetCoins is a random subset of the provided denoms, if the account is found. // TODO: Write unit test @@ -86,8 +98,12 @@ func (sim *SimCtx) SelAddrWithDenoms(ctx sdk.Context, denoms []string) (simulati // RandGeometricCoin uniformly samples a denom from the addr's balances. // Then it samples an Exponentially distributed amount of the addr's coins, with rate = 10. // (Meaning that on average it samples 10% of the chosen balance) +// Pre-condition: Addr must have a spendable balance func (sim *SimCtx) RandExponentialCoin(ctx sdk.Context, addr sdk.AccAddress) sdk.Coin { - balances := sim.App.GetBankKeeper().GetAllBalances(ctx, addr) + balances := sim.App.GetBankKeeper().SpendableCoins(ctx, addr) + if len(balances) == 0 { + panic("precondition for RandExponentialCoin broken: Addr has 0 spendable balance") + } coin := RandSelect(sim, balances...) // TODO: Reconsider if this becomes problematic in the future, but currently thinking it // should be fine for simulation. diff --git a/simulation/types/manager.go b/simulation/types/manager.go index 1f0270d354b..063f693b64c 100644 --- a/simulation/types/manager.go +++ b/simulation/types/manager.go @@ -10,6 +10,8 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/simulation" "golang.org/x/exp/maps" + + "github.com/osmosis-labs/osmosis/v7/osmoutils" ) // AppModuleSimulation defines the standard functions that every module should expose @@ -110,8 +112,10 @@ func (m Manager) legacyActions(seed int64, cdc codec.JSONCodec) []Action { // TODO: Can we use sim here instead? Perhaps by passing in the simulation module manager to the simulator. func (m Manager) Actions(seed int64, cdc codec.JSONCodec) []Action { actions := m.legacyActions(seed, cdc) - for _, simModule := range m.Modules { - actions = append(actions, simModule.Actions()...) + moduleKeys := maps.Keys(m.Modules) + osmoutils.SortSlice(moduleKeys) + for _, simModuleName := range moduleKeys { + actions = append(actions, m.Modules[simModuleName].Actions()...) } return actions } diff --git a/simulation/types/txbuilder.go b/simulation/types/txbuilder.go index 87d0719c0bc..05c9c47fbe0 100644 --- a/simulation/types/txbuilder.go +++ b/simulation/types/txbuilder.go @@ -4,11 +4,17 @@ import ( "errors" "fmt" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/osmosis-labs/osmosis/v7/app/params" + + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + authsign "github.com/cosmos/cosmos-sdk/x/auth/signing" ) //nolint:deadcode,unused @@ -31,7 +37,7 @@ func (sim *SimCtx) defaultTxBuilder( // TODO: Consider making a default tx builder that charges some random fees // Low value for amount of work right now though. fees := sdk.Coins{} - tx, err := helpers.GenTx( + tx, err := genTx( txConfig, []sdk.Msg{msg}, fees, @@ -57,3 +63,58 @@ func (sim *SimCtx) deliverTx(tx sdk.Tx, msg sdk.Msg, msgName string) (simulation return simulation.NewOperationMsg(msg, true, "", nil), nil, nil } + +// GenTx generates a signed mock transaction. +// TODO: Surely theres proper API's in the SDK for this? +// (This was copied from SDK simapp, and deleted the egregiously non-deterministic memo handling) +func genTx(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accNums, accSeqs []uint64, priv ...cryptotypes.PrivKey) (sdk.Tx, error) { + sigs := make([]signing.SignatureV2, len(priv)) + memo := "sample_memo" + signMode := gen.SignModeHandler().DefaultMode() + + // 1st round: set SignatureV2 with empty signatures, to set correct + // signer infos. + for i, p := range priv { + sigs[i] = signing.SignatureV2{ + PubKey: p.PubKey(), + Data: &signing.SingleSignatureData{ + SignMode: signMode, + }, + Sequence: accSeqs[i], + } + } + + txBuilder := gen.NewTxBuilder() + err := txBuilder.SetMsgs(msgs...) + if err != nil { + return nil, err + } + err = txBuilder.SetSignatures(sigs...) + if err != nil { + return nil, err + } + txBuilder.SetMemo(memo) + txBuilder.SetFeeAmount(feeAmt) + txBuilder.SetGasLimit(gas) + + // 2nd round: once all signer infos are set, every signer can sign. + for i, p := range priv { + signerData := authsign.SignerData{ + ChainID: chainID, + AccountNumber: accNums[i], + Sequence: accSeqs[i], + } + sig, err := tx.SignWithPrivKey(signMode, signerData, txBuilder, p, gen, accSeqs[i]) + if err != nil { + panic(err) + } + //nolint:forcetypeassert + sigs[i] = sig + err = txBuilder.SetSignatures(sigs...) + if err != nil { + panic(err) + } + } + + return txBuilder.GetTx(), nil +} diff --git a/tests/simulator/sim_test.go b/tests/simulator/sim_test.go index a27fdec46f9..195e3455b38 100644 --- a/tests/simulator/sim_test.go +++ b/tests/simulator/sim_test.go @@ -1,7 +1,6 @@ package simapp import ( - "encoding/json" "fmt" "math/rand" "os" @@ -134,9 +133,9 @@ func TestAppStateDeterminism(t *testing.T) { // } config := sdkSimapp.NewConfigFromFlags() - config.InitialBlockHeight = 1 config.ExportParamsPath = "" - config.NumBlocks = 10 + config.NumBlocks = 50 + config.BlockSize = 5 config.OnOperation = false config.AllInvariants = false config.ChainID = helpers.SimAppChainID @@ -147,7 +146,7 @@ func TestAppStateDeterminism(t *testing.T) { numSeeds := 3 numTimesToRunPerSeed := 5 - appHashList := make([]json.RawMessage, numTimesToRunPerSeed) + appHashList := make([]string, numTimesToRunPerSeed) for i := 0; i < numSeeds; i++ { config.Seed = rand.Int63() @@ -199,16 +198,12 @@ func TestAppStateDeterminism(t *testing.T) { require.NoError(t, simErr) - if config.Commit { - sdkSimapp.PrintStats(db) - } - appHash := osmosis.LastCommitID().Hash - appHashList[j] = appHash + appHashList[j] = fmt.Sprintf("%X", appHash) if j != 0 { require.Equal( - t, string(appHashList[0]), string(appHashList[j]), + t, appHashList[0], appHashList[j], "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, ) } diff --git a/x/lockup/simulation/operations.go b/x/lockup/simulation/operations.go index a0ab4d5285b..7056a595a96 100644 --- a/x/lockup/simulation/operations.go +++ b/x/lockup/simulation/operations.go @@ -15,13 +15,16 @@ import ( ) func RandomMsgLockTokens(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgLockTokens, error) { - sender := sim.RandomSimAccount() - lockCoins := sim.RandExponentialCoin(ctx, sender.Address) + sender, err := sim.RandomSimAccountWithBalance(ctx) + if err != nil { + return nil, err + } + lockCoin := sim.RandExponentialCoin(ctx, sender.Address) duration := simulation.RandSelect(sim, time.Minute, time.Hour, time.Hour*24) return &types.MsgLockTokens{ Owner: sender.Address.String(), Duration: duration, - Coins: sdk.Coins{lockCoins}, + Coins: sdk.Coins{lockCoin}, }, nil } diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index bb121e631aa..b750d55821c 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -3,8 +3,6 @@ package simulation // DONTCOVER import ( - "encoding/json" - "fmt" "math/rand" "github.com/osmosis-labs/osmosis/v7/x/mint/types" @@ -140,11 +138,6 @@ func RandomizedGenState(simState *module.SimulationState) { mintGenesis := types.NewGenesisState(minter, params, reductionStartedEpoch) - bz, err := json.MarshalIndent(&mintGenesis, "", " ") - if err != nil { - panic(err) - } - fmt.Printf("Selected pseudo-randomly generated minting parameters:\n%s\n", bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(mintGenesis) } From 1486c847dd49d0e3f8301b3fabfa01e66e07ba81 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Thu, 14 Jul 2022 16:15:53 -0400 Subject: [PATCH 075/376] feat: mutation testing setup (#1853) Use make test-mutation Co-authored-by: Dev Ojha --- Makefile | 5 +++++ go.mod | 4 ++++ go.sum | 12 ++++++++++++ scripts/mutation-test.sh | 32 ++++++++++++++++++++++++++++++++ tools/tools.go | 1 + 5 files changed, 54 insertions(+) create mode 100644 scripts/mutation-test.sh diff --git a/Makefile b/Makefile index 766e6f39f58..6eb060d1786 100644 --- a/Makefile +++ b/Makefile @@ -237,6 +237,9 @@ test-e2e: test-e2e-skip-upgrade: @VERSION=$(VERSION) OSMOSIS_E2E_SKIP_UPGRADE=True go test -mod=readonly -timeout=25m -v $(PACKAGES_E2E) +test-mutation: + @sh scripts/mutation-test.sh + benchmark: @go test -mod=readonly -bench=. $(PACKAGES_UNIT) @@ -253,6 +256,8 @@ docker-build-e2e-init-chain: docker-build-e2e-init-node: @docker build -t osmosis-e2e-init-node:debug --build-arg E2E_SCRIPT_NAME=node -f tests/e2e/initialization/init.Dockerfile . +.PHONY: test-mutation + ############################################################################### ### Linting ### ############################################################################### diff --git a/go.mod b/go.mod index 2f7557701a7..067730b5f42 100644 --- a/go.mod +++ b/go.mod @@ -24,6 +24,7 @@ require ( github.com/stretchr/testify v1.8.0 github.com/tendermint/tendermint v0.34.19 github.com/tendermint/tm-db v0.6.8-0.20220506192307-f628bb5dc95b + github.com/zimmski/go-mutesting v0.0.0-20210610104036-6d9217011a00 golang.org/x/exp v0.0.0-20220613132600-b0d781184e0d google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd google.golang.org/grpc v1.46.2 @@ -151,6 +152,7 @@ require ( github.com/imdario/mergo v0.3.12 // indirect github.com/improbable-eng/grpc-web v0.14.1 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/jessevdk/go-flags v1.4.0 // indirect github.com/jgautheron/goconst v1.5.1 // indirect github.com/jingyugao/rowserrcheck v1.1.1 // indirect github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af // indirect @@ -246,6 +248,8 @@ require ( github.com/xeipuuv/gojsonschema v1.2.0 // indirect github.com/yagipy/maintidx v1.0.0 // indirect github.com/yeya24/promlinter v0.2.0 // indirect + github.com/zimmski/go-tool v0.0.0-20150119110811-2dfdc9ac8439 // indirect + github.com/zimmski/osutil v0.0.0-20190128123334-0d0b3ca231ac // indirect github.com/zondax/hid v0.9.0 // indirect gitlab.com/bosi/decorder v0.2.1 // indirect go.etcd.io/bbolt v1.3.6 // indirect diff --git a/go.sum b/go.sum index 2b6732e6289..976dfb6b888 100644 --- a/go.sum +++ b/go.sum @@ -757,6 +757,7 @@ github.com/influxdata/influxdb1-client v0.0.0-20200827194710-b269163b24ab/go.mod github.com/jackpal/go-nat-pmp v1.0.2-0.20160603034137-1fa385a6f458/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= github.com/jedisct1/go-minisign v0.0.0-20190909160543-45766022959e/go.mod h1:G1CVv03EnqU1wYL2dFwXxW2An0az9JTl/ZsqXQeBlkU= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jgautheron/goconst v1.5.1 h1:HxVbL1MhydKs8R8n/HE5NPvzfaYmQJA3o879lE4+WcM= github.com/jgautheron/goconst v1.5.1/go.mod h1:aAosetZ5zaeC/2EfMeRswtxUFBpe2Hr7HzkgX4fanO4= @@ -796,6 +797,7 @@ github.com/julz/importas v0.1.0/go.mod h1:oSFU2R4XK/P7kNBrnL/FEQlDGN1/6WoxXEjSSX github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= github.com/karalabe/usb v0.0.0-20190919080040-51dc0efba356/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/errcheck v1.6.0 h1:YTDO4pNy7AUN/021p+JGHycQyYNIyMoenM1YDVK6RlY= github.com/kisielk/errcheck v1.6.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= @@ -890,6 +892,7 @@ github.com/mattn/go-runewidth v0.0.10 h1:CoZ3S2P7pvtP45xOtBw+/mDL2z0RKI576gSkzRR github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-sqlite3 v1.14.9/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/mattn/goveralls v0.0.3/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI= github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= @@ -994,6 +997,7 @@ github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= @@ -1384,6 +1388,12 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/zimmski/go-mutesting v0.0.0-20210610104036-6d9217011a00 h1:KNiPkpQpqXvq40f8hh/1T7QasLJT/1MuBoOYA2vlxJk= +github.com/zimmski/go-mutesting v0.0.0-20210610104036-6d9217011a00/go.mod h1:RJt5SMnyha63GbdwCKJiX9djvvEC4KsfXJSZ5oTmSPw= +github.com/zimmski/go-tool v0.0.0-20150119110811-2dfdc9ac8439 h1:yHqsjUkj0HWbKPw/6ZqC0/eMklaRpqubA199vaRLzzE= +github.com/zimmski/go-tool v0.0.0-20150119110811-2dfdc9ac8439/go.mod h1:G4FVqCRvfz74AEB1crDNdQuvMfOoKtk7DlePsnV2yGs= +github.com/zimmski/osutil v0.0.0-20190128123334-0d0b3ca231ac h1:uiFRlKzyIzHeLOthe0ethUkSGW7POlqxU3Tc21R8QpQ= +github.com/zimmski/osutil v0.0.0-20190128123334-0d0b3ca231ac/go.mod h1:wJ9WGevuM/rw8aB2pQPFMUgXZWeaouI0ueFamR0DUPE= github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8= github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= gitlab.com/bosi/decorder v0.2.1 h1:ehqZe8hI4w7O4b1vgsDZw1YU1PE7iJXrQWFMsocbQ1w= @@ -1759,6 +1769,7 @@ golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190307163923-6a08e3108db3/go.mod h1:25r3+/G6/xytQM8iWZKq3Hn0kr0rgFKPUNVEL/dr3z4= @@ -1783,6 +1794,7 @@ golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20190916130336-e45ffcd953cc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191010075000-0337d82405ff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191018212557-ed542cd5b28a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= diff --git a/scripts/mutation-test.sh b/scripts/mutation-test.sh new file mode 100644 index 00000000000..350aa0d9c7c --- /dev/null +++ b/scripts/mutation-test.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +set -eo pipefail + +DISABLED_MUTATORS='branch/*' + +# Only consider the following: +# * go files in types or keeper packages +# * ignore test and Protobuf files +MUTATION_SOURCES=$(find ./x -type f \( -path '*/keeper/*' -or -path '*/types/*' \) \( -name '*.go' -and -not -name '*_test.go' -and -not -name '*pb*' \)) + +# XXX: Filter on a module-by-module basis and expand when we think other modules +# are ready. Once all modules are considered stable enough to be tested, remove +# this filter entirely. +MUTATION_SOURCES=$(echo "$MUTATION_SOURCES" | grep './x/tokenfactory') + +# Collect multiple lines into a single line to be fed into go-mutesting +MUTATION_SOURCES=$(echo $MUTATION_SOURCES | tr '\n' ' ') + +OUTPUT=$(go run github.com/zimmski/go-mutesting/cmd/go-mutesting --disable=$DISABLED_MUTATORS $MUTATION_SOURCES) + +# Fetch the final result output and the overall mutation testing score +RESULT=$(echo "$OUTPUT" | grep 'The mutation score') +SCORE=$(echo "$RESULT" | grep -Eo '[[:digit:]]\.[[:digit:]]+') + +echo $RESULT + +# Return a non-zero exit code if the score is below 75% +if (( $(echo "$SCORE < 0.75" |bc -l) )); then + echo "Mutation testing score below desired level ($SCORE < 0.75)" + exit 1 +fi diff --git a/tools/tools.go b/tools/tools.go index a16035f6194..61580ec665d 100644 --- a/tools/tools.go +++ b/tools/tools.go @@ -9,5 +9,6 @@ package tools import ( _ "github.com/golangci/golangci-lint/cmd/golangci-lint" + _ "github.com/zimmski/go-mutesting/cmd/go-mutesting" _ "mvdan.cc/gofumpt" ) From 1ec35454eaae3407a696516b25f306e80382da5c Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 15 Jul 2022 10:26:52 +0700 Subject: [PATCH 076/376] routine fumptage (#2056) * routine fumptage * Update settings.json * Fix gofmt * Fix gofmt Co-authored-by: Dev Ojha Co-authored-by: Dev Ojha --- simulation/executor/event_stats.go | 2 +- simulation/executor/log.go | 1 - simulation/executor/mock_tendermint.go | 3 ++- simulation/executor/operation.go | 1 + simulation/executor/params_test.go | 3 +-- simulation/executor/simulate.go | 6 ++++-- simulation/types/action.go | 6 ++++-- simulation/types/random/sdkrand.go | 4 ++-- tests/e2e/configurer/upgrade.go | 1 - x/gamm/keeper/internal/events/emit_test.go | 1 - x/gamm/keeper/pool_service_test.go | 6 +++--- x/incentives/client/cli/cli_test.go | 1 - x/incentives/keeper/distribute_test.go | 1 - x/incentives/keeper/gauge_test.go | 1 - x/mint/keeper/keeper_test.go | 8 +++++--- x/txfees/keeper/hooks_test.go | 2 +- 16 files changed, 24 insertions(+), 23 deletions(-) diff --git a/simulation/executor/event_stats.go b/simulation/executor/event_stats.go index cd2d01a064b..8b3f06e9bb4 100644 --- a/simulation/executor/event_stats.go +++ b/simulation/executor/event_stats.go @@ -48,7 +48,7 @@ func (es EventStats) ExportJSON(path string) { panic(err) } - err = ioutil.WriteFile(path, bz, 0600) + err = ioutil.WriteFile(path, bz, 0o600) if err != nil { panic(err) } diff --git a/simulation/executor/log.go b/simulation/executor/log.go index df563cc18f9..d429497a484 100644 --- a/simulation/executor/log.go +++ b/simulation/executor/log.go @@ -44,7 +44,6 @@ func (lw *StandardLogWriter) PrintLogs() { for i := 0; i < len(lw.OpEntries); i++ { writeEntry := fmt.Sprintf("%s\n", (lw.OpEntries[i]).MustMarshal()) _, err := f.WriteString(writeEntry) - if err != nil { panic("Failed to write logs to file") } diff --git a/simulation/executor/mock_tendermint.go b/simulation/executor/mock_tendermint.go index e4f096db132..db9f1bfae22 100644 --- a/simulation/executor/mock_tendermint.go +++ b/simulation/executor/mock_tendermint.go @@ -126,7 +126,8 @@ func updateValidators( func RandomRequestBeginBlock(r *rand.Rand, params Params, validators mockValidators, pastTimes []time.Time, pastVoteInfos [][]abci.VoteInfo, - event func(route, op, evResult string), header tmproto.Header) abci.RequestBeginBlock { + event func(route, op, evResult string), header tmproto.Header, +) abci.RequestBeginBlock { if len(validators) == 0 { return abci.RequestBeginBlock{ Header: header, diff --git a/simulation/executor/operation.go b/simulation/executor/operation.go index 38a018a61d7..76387ed2b82 100644 --- a/simulation/executor/operation.go +++ b/simulation/executor/operation.go @@ -108,6 +108,7 @@ func queueOperations(queuedOps OperationQueue, queuedTimeOps []simulation.Future queuedTimeOps[index] = futureOp } } + func totalWeight(actions []simtypes.Action) int { totalWeight := 0 for _, action := range actions { diff --git a/simulation/executor/params_test.go b/simulation/executor/params_test.go index 3eb3ad8bc76..88cc5d564c4 100644 --- a/simulation/executor/params_test.go +++ b/simulation/executor/params_test.go @@ -43,8 +43,7 @@ func TestNewWeightedProposalContent(t *testing.T) { require.Equal(t, content, pContent.ContentSimulatorFn()(nil, ctx, nil)) } -type testContent struct { -} +type testContent struct{} func (t testContent) GetTitle() string { return "" } func (t testContent) GetDescription() string { return "" } diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index 13f2b932a90..5cda014a20f 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -205,7 +205,8 @@ type blockSimFn func(simCtx *simtypes.SimCtx, ctx sdk.Context, header tmproto.He // Returns a function to simulate blocks. Written like this to avoid constant // parameters being passed everytime, to minimize memory overhead. func createBlockSimulator(testingMode bool, w io.Writer, params Params, actions []simtypes.Action, - simState *simState, config simulation.Config) blockSimFn { + simState *simState, config simulation.Config, +) blockSimFn { lastBlockSizeState := 0 // state for [4 * uniform distribution] blocksize := 0 selectAction := getSelectActionFn(actions) @@ -295,7 +296,8 @@ func (simState *simState) runQueuedOperations(simCtx *simtypes.SimCtx, ctx sdk.C } func (simState *simState) runQueuedTimeOperations(simCtx *simtypes.SimCtx, ctx sdk.Context) ( - numOpsRan int) { + numOpsRan int, +) { queueOps := simState.timeOperationQueue currentTime := simState.header.Time numOpsRan = 0 diff --git a/simulation/types/action.go b/simulation/types/action.go index 64eaac5a96c..4cdfa130b30 100644 --- a/simulation/types/action.go +++ b/simulation/types/action.go @@ -34,7 +34,8 @@ type weightedOperationAction struct { func (a weightedOperationAction) Name() string { return "weighted_op" } func (a weightedOperationAction) Weight() Weight { return Weight(a.op.Weight()) } func (a weightedOperationAction) Execute(sim *SimCtx, ctx sdk.Context) ( - simulation.OperationMsg, []simulation.FutureOperation, error) { + simulation.OperationMsg, []simulation.FutureOperation, error, +) { return a.op.Op()(sim.GetRand(), sim.App.GetBaseApp(), ctx, sim.Accounts, sim.ChainID) } @@ -85,7 +86,8 @@ func (m msgBasedAction) WithWeight(weight Weight) msgBasedAction { func (m msgBasedAction) Name() string { return m.name } func (m msgBasedAction) Weight() Weight { return m.weight } func (m msgBasedAction) Execute(sim *SimCtx, ctx sdk.Context) ( - OperationMsg simulation.OperationMsg, futureOps []simulation.FutureOperation, err error) { + OperationMsg simulation.OperationMsg, futureOps []simulation.FutureOperation, err error, +) { msg, err := m.msgGenerator(sim, ctx) if err != nil { return simulation.NoOpMsg(m.name, m.name, fmt.Sprintf("unable to build msg due to: %v", err)), nil, nil diff --git a/simulation/types/random/sdkrand.go b/simulation/types/random/sdkrand.go index a2ab78b86aa..89c950ef346 100644 --- a/simulation/types/random/sdkrand.go +++ b/simulation/types/random/sdkrand.go @@ -53,7 +53,7 @@ func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { // RandomAmount generates a random amount // Note: The range of RandomAmount includes max, and is, in fact, biased to return max as well as 0. func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int { - var randInt = big.NewInt(0) + randInt := big.NewInt(0) switch r.Intn(10) { case 0: @@ -70,7 +70,7 @@ func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int { // RandomDecAmount generates a random decimal amount // Note: The range of RandomDecAmount includes max, and is, in fact, biased to return max as well as 0. func RandomDecAmount(r *rand.Rand, max sdk.Dec) sdk.Dec { - var randInt = big.NewInt(0) + randInt := big.NewInt(0) switch r.Intn(10) { case 0: diff --git a/tests/e2e/configurer/upgrade.go b/tests/e2e/configurer/upgrade.go index b4c9f73b2c5..287d665b6a6 100644 --- a/tests/e2e/configurer/upgrade.go +++ b/tests/e2e/configurer/upgrade.go @@ -71,7 +71,6 @@ func (uc *UpgradeConfigurer) ConfigureChain(chainConfig *chain.Config) error { } chainInitResource, err := uc.containerManager.RunChainInitResource(chainConfig.Id, int(chainConfig.VotingPeriod), validatorConfigBytes, tmpDir, int(forkHeight)) - if err != nil { return err } diff --git a/x/gamm/keeper/internal/events/emit_test.go b/x/gamm/keeper/internal/events/emit_test.go index dcaa845b427..15d60dc5d52 100644 --- a/x/gamm/keeper/internal/events/emit_test.go +++ b/x/gamm/keeper/internal/events/emit_test.go @@ -29,7 +29,6 @@ func TestGammEventsTestSuite(t *testing.T) { } func (suite *GammEventsTestSuite) TestEmitSwapEvent() { - testcases := map[string]struct { ctx sdk.Context testAccountAddr sdk.AccAddress diff --git a/x/gamm/keeper/pool_service_test.go b/x/gamm/keeper/pool_service_test.go index 343aded9fa6..2e8492ee9be 100644 --- a/x/gamm/keeper/pool_service_test.go +++ b/x/gamm/keeper/pool_service_test.go @@ -579,10 +579,10 @@ func (suite *KeeperTestSuite) TestJoinPoolExitPool_InverseRelationship() { poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, tc.pool) suite.Require().NoError(err) - balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) + balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) - _, _, err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) - suite.Require().NoError(err) + _, _, err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) + suite.Require().NoError(err) _, err = suite.App.GAMMKeeper.ExitPool(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) diff --git a/x/incentives/client/cli/cli_test.go b/x/incentives/client/cli/cli_test.go index fce100e1225..71930765188 100644 --- a/x/incentives/client/cli/cli_test.go +++ b/x/incentives/client/cli/cli_test.go @@ -78,7 +78,6 @@ func (s *IntegrationTestSuite) SetupSuite() { _, err = s.network.WaitForHeight(1) s.Require().NoError(err) - } func (s *IntegrationTestSuite) TearDownSuite() { diff --git a/x/incentives/keeper/distribute_test.go b/x/incentives/keeper/distribute_test.go index 9699cf05a28..59077e2fbf3 100644 --- a/x/incentives/keeper/distribute_test.go +++ b/x/incentives/keeper/distribute_test.go @@ -174,7 +174,6 @@ func (suite *KeeperTestSuite) TestSyntheticDistribute() { suite.Require().Equal(tc.expectedRewards[i].String(), rewards, "test %v, person %d", tc.name, i) } } - } // TestGetModuleToDistributeCoins tests the sum of coins yet to be distributed for all of the module is correct. diff --git a/x/incentives/keeper/gauge_test.go b/x/incentives/keeper/gauge_test.go index 653202ad142..e46fb22cbc7 100644 --- a/x/incentives/keeper/gauge_test.go +++ b/x/incentives/keeper/gauge_test.go @@ -236,5 +236,4 @@ func (suite *KeeperTestSuite) TestGaugeOperations() { suite.Require().Len(gaugeIdsByDenom, 1) } } - } diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 3483eb790e3..73baaa8c384 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -168,7 +168,8 @@ func (suite *KeeperTestSuite) TestDistributeMintedCoin_ToDeveloperRewardsAddr() { Address: testAddressOne.String(), Weight: sdk.NewDec(1), - }}, + }, + }, mintCoin: sdk.NewCoin("stake", sdk.NewInt(10000)), }, { @@ -181,7 +182,8 @@ func (suite *KeeperTestSuite) TestDistributeMintedCoin_ToDeveloperRewardsAddr() { Address: testAddressFour.String(), Weight: sdk.NewDecWithPrec(4, 1), - }}, + }, + }, mintCoin: sdk.NewCoin("stake", sdk.NewInt(100000)), }, { @@ -236,7 +238,7 @@ func (suite *KeeperTestSuite) TestDistributeMintedCoin_ToDeveloperRewardsAddr() feePool.CommunityPool.AmountOf("stake")) } else { suite.Equal( - //distribution go to community pool because nil dev reward addresses. + // distribution go to community pool because nil dev reward addresses. tc.mintCoin.Amount.ToDec().Mul((params.DistributionProportions.DeveloperRewards).Add(params.DistributionProportions.CommunityPool)), feePool.CommunityPool.AmountOf("stake")) } diff --git a/x/txfees/keeper/hooks_test.go b/x/txfees/keeper/hooks_test.go index 9995ea275f9..6b5f97b1ef8 100644 --- a/x/txfees/keeper/hooks_test.go +++ b/x/txfees/keeper/hooks_test.go @@ -64,7 +64,7 @@ func (suite *KeeperTestSuite) TestTxFeesAfterEpochEnd() { }, } - var finalOutputAmount = sdk.NewInt(0) + finalOutputAmount := sdk.NewInt(0) for _, tc := range tests { tc := tc From 582b016f1278e72d58496403b4e45e04e7fbc7b6 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Thu, 14 Jul 2022 22:37:25 -0500 Subject: [PATCH 077/376] Update labeler.yml (#2078) --- .github/labeler.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/labeler.yml b/.github/labeler.yml index 49370713b54..f2e92a95691 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -9,6 +9,13 @@ - app/upgrades/**/* # Also match any module.go update - x/**/module.go +"C:simulator": + # Match all of simulation & tests/simulator folder + - simulation/**/* + - simulation/**/**/* + - tests/simulator/** + # Match any module update + - x/**/simulation/*.go "C:wasm": - app/wasm/**/* "C:x/claim": From 29ce363b11534044ae5ecffd20de1ea7fb8f6ae6 Mon Sep 17 00:00:00 2001 From: khanh <50263489+catShaark@users.noreply.github.com> Date: Fri, 15 Jul 2022 11:38:50 +0700 Subject: [PATCH 078/376] modify test for Pow and PowApprox (#1965) * modify test for Pow and PowApprox * Update osmomath/math_test.go Co-authored-by: Dev Ojha * Update osmomath/math_test.go Co-authored-by: Dev Ojha * Update osmomath/math_test.go Co-authored-by: Roman * Update osmomath/math_test.go Co-authored-by: Roman * add more test case * update branch; add test case for zero base * Delete start_node.sh Co-authored-by: Dev Ojha Co-authored-by: Roman --- osmomath/math.go | 4 + osmomath/math_test.go | 178 ++++++++++++++++++++++++++++++++---------- 2 files changed, 141 insertions(+), 41 deletions(-) diff --git a/osmomath/math.go b/osmomath/math.go index def0f501446..d8f341bb605 100644 --- a/osmomath/math.go +++ b/osmomath/math.go @@ -84,6 +84,10 @@ func Pow(base sdk.Dec, exp sdk.Dec) sdk.Dec { // Contract: 0 < base <= 2 // 0 <= exp < 1. func PowApprox(base sdk.Dec, exp sdk.Dec, precision sdk.Dec) sdk.Dec { + if !base.IsPositive() { + panic(fmt.Errorf("base must be greater than 0")) + } + if exp.IsZero() { return sdk.OneDec() } diff --git a/osmomath/math_test.go b/osmomath/math_test.go index c01caf80ed1..b369db336b3 100644 --- a/osmomath/math_test.go +++ b/osmomath/math_test.go @@ -1,10 +1,13 @@ package osmomath import ( + "fmt" "testing" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/osmosis-labs/osmosis/v7/osmoutils" + "github.com/stretchr/testify/require" ) @@ -23,50 +26,143 @@ func TestAbsDifferenceWithSign(t *testing.T) { } func TestPowApprox(t *testing.T) { - base, err := sdk.NewDecFromStr("0.8") - require.NoError(t, err) - exp, err := sdk.NewDecFromStr("0.32") - require.NoError(t, err) - - s := PowApprox(base, exp, powPrecision) - expectedDec, err := sdk.NewDecFromStr("0.93108385") - require.NoError(t, err) - - require.True( - t, - expectedDec.Sub(s).Abs().LTE(powPrecision), - "expected value & actual value's difference should less than precision", - ) + testCases := []struct { + base sdk.Dec + exp sdk.Dec + powPrecision sdk.Dec + expectedResult sdk.Dec + }{ + { + // medium base, small exp + base: sdk.MustNewDecFromStr("0.8"), + exp: sdk.MustNewDecFromStr("0.32"), + powPrecision: sdk.MustNewDecFromStr("0.00000001"), + expectedResult: sdk.MustNewDecFromStr("0.93108385"), + }, + { + // zero exp + base: sdk.MustNewDecFromStr("0.8"), + exp: sdk.ZeroDec(), + powPrecision: sdk.MustNewDecFromStr("0.00001"), + expectedResult: sdk.OneDec(), + }, + { + // zero base, this should panic + base: sdk.ZeroDec(), + exp: sdk.OneDec(), + powPrecision: sdk.MustNewDecFromStr("0.00001"), + expectedResult: sdk.ZeroDec(), + }, + { + // large base, small exp + base: sdk.MustNewDecFromStr("1.9999"), + exp: sdk.MustNewDecFromStr("0.23"), + powPrecision: sdk.MustNewDecFromStr("0.000000001"), + expectedResult: sdk.MustNewDecFromStr("1.172821461"), + }, + { + // large base, large integer exp + base: sdk.MustNewDecFromStr("1.777"), + exp: sdk.MustNewDecFromStr("20"), + powPrecision: sdk.MustNewDecFromStr("0.000000000001"), + expectedResult: sdk.MustNewDecFromStr("98570.862372081602"), + }, + { + // medium base, large exp, high precision + base: sdk.MustNewDecFromStr("1.556"), + exp: sdk.MustNewDecFromStr("20.9123"), + powPrecision: sdk.MustNewDecFromStr("0.0000000000000001"), + expectedResult: sdk.MustNewDecFromStr("10360.058421529811344618"), + }, + { + // high base, large exp, high precision + base: sdk.MustNewDecFromStr("1.886"), + exp: sdk.MustNewDecFromStr("31.9123"), + powPrecision: sdk.MustNewDecFromStr("0.00000000000001"), + expectedResult: sdk.MustNewDecFromStr("621110716.84727942280335811"), + }, + { + // base equal one + base: sdk.MustNewDecFromStr("1"), + exp: sdk.MustNewDecFromStr("123"), + powPrecision: sdk.MustNewDecFromStr("0.00000001"), + expectedResult: sdk.OneDec(), + }, + } - base, err = sdk.NewDecFromStr("0.8") - require.NoError(t, err) - exp = sdk.ZeroDec() - require.NoError(t, err) - - s = PowApprox(base, exp, powPrecision) - expectedDec = sdk.OneDec() - require.NoError(t, err) - - require.True( - t, - expectedDec.Sub(s).Abs().LTE(powPrecision), - "expected value & actual value's difference should less than precision", - ) + for i, tc := range testCases { + var actualResult sdk.Dec + osmoutils.ConditionalPanic(t, tc.base.Equal(sdk.ZeroDec()), func() { + fmt.Println(tc.base) + actualResult = PowApprox(tc.base, tc.exp, tc.powPrecision) + require.True( + t, + tc.expectedResult.Sub(actualResult).Abs().LTE(tc.powPrecision), + fmt.Sprintf("test %d failed: expected value & actual value's difference should be less than precision", i), + ) + }) + } } func TestPow(t *testing.T) { - base, err := sdk.NewDecFromStr("1.68") - require.NoError(t, err) - exp, err := sdk.NewDecFromStr("0.32") - require.NoError(t, err) - - s := Pow(base, exp) - expectedDec, err := sdk.NewDecFromStr("1.18058965") - require.NoError(t, err) + testCases := []struct { + base sdk.Dec + exp sdk.Dec + expectedResult sdk.Dec + }{ + { + // medium base, small exp + base: sdk.MustNewDecFromStr("0.8"), + exp: sdk.MustNewDecFromStr("0.32"), + expectedResult: sdk.MustNewDecFromStr("0.93108385"), + }, + { + // zero exp + base: sdk.MustNewDecFromStr("0.8"), + exp: sdk.ZeroDec(), + expectedResult: sdk.OneDec(), + }, + { + // zero base, this should panic + base: sdk.ZeroDec(), + exp: sdk.OneDec(), + expectedResult: sdk.ZeroDec(), + }, + { + // large base, small exp + base: sdk.MustNewDecFromStr("1.9999"), + exp: sdk.MustNewDecFromStr("0.23"), + expectedResult: sdk.MustNewDecFromStr("1.172821461"), + }, + { + // small base, large exp + base: sdk.MustNewDecFromStr("0.0000123"), + exp: sdk.MustNewDecFromStr("123"), + expectedResult: sdk.ZeroDec(), + }, + { + // large base, large exp + base: sdk.MustNewDecFromStr("1.777"), + exp: sdk.MustNewDecFromStr("20"), + expectedResult: sdk.MustNewDecFromStr("98570.862372081602"), + }, + { + // base equal one + base: sdk.MustNewDecFromStr("1"), + exp: sdk.MustNewDecFromStr("123"), + expectedResult: sdk.OneDec(), + }, + } - require.True( - t, - expectedDec.Sub(s).Abs().LTE(powPrecision), - "expected value & actual value's difference should less than precision", - ) + for i, tc := range testCases { + var actualResult sdk.Dec + osmoutils.ConditionalPanic(t, tc.base.Equal(sdk.ZeroDec()), func() { + actualResult = Pow(tc.base, tc.exp) + require.True( + t, + tc.expectedResult.Sub(actualResult).Abs().LTE(powPrecision), + fmt.Sprintf("test %d failed: expected value & actual value's difference should be less than precision", i), + ) + }) + } } From bd75cb5641f88822520696d388dec1748fdb8ae6 Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Fri, 15 Jul 2022 13:53:17 +0900 Subject: [PATCH 079/376] chore(e2e): use `require.Eventually` in QueryRPC (#2063) --- tests/e2e/configurer/chain/queries.go | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/tests/e2e/configurer/chain/queries.go b/tests/e2e/configurer/chain/queries.go index 3e44415e6a2..672ecebdb5e 100644 --- a/tests/e2e/configurer/chain/queries.go +++ b/tests/e2e/configurer/chain/queries.go @@ -26,24 +26,15 @@ func (n *NodeConfig) QueryGRPCGateway(path string) ([]byte, error) { fullQueryPath := fmt.Sprintf("%s/%s", endpoint, path) var resp *http.Response - retriesLeft := 5 - for { + require.Eventually(n.t, func() bool { resp, err = http.Get(fullQueryPath) - - if resp.StatusCode == http.StatusServiceUnavailable { - retriesLeft-- - if retriesLeft == 0 { - return nil, err - } - time.Sleep(10 * time.Second) - } else { - break + if err != nil { + n.t.Logf("error while executing HTTP request: %s", err.Error()) + return false } - } - if err != nil { - return nil, fmt.Errorf("failed to execute HTTP request: %w", err) - } + return resp.StatusCode != http.StatusServiceUnavailable + }, time.Minute, time.Second*10, "failed to execute HTTP request") defer resp.Body.Close() From 243c51d3c0de407ee8d87a8711d8c95da32fdd39 Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Fri, 15 Jul 2022 14:46:46 +0900 Subject: [PATCH 080/376] chore: cleanup superfluid testing (#2027) * Cleanup * Roman's code review * Roman's review --- x/superfluid/keeper/distribution_test.go | 5 +- x/superfluid/keeper/edge_case_test.go | 8 +- x/superfluid/keeper/grpc_query_test.go | 34 +- x/superfluid/keeper/hooks_test.go | 8 +- .../keeper/intermediary_account_test.go | 2 +- x/superfluid/keeper/keeper_test.go | 93 +++ x/superfluid/keeper/slash_test.go | 7 +- x/superfluid/keeper/stake_test.go | 662 ++++-------------- 8 files changed, 262 insertions(+), 557 deletions(-) diff --git a/x/superfluid/keeper/distribution_test.go b/x/superfluid/keeper/distribution_test.go index dad228dc539..1e77f51c8ed 100644 --- a/x/superfluid/keeper/distribution_test.go +++ b/x/superfluid/keeper/distribution_test.go @@ -63,16 +63,13 @@ func (suite *KeeperTestSuite) TestMoveSuperfluidDelegationRewardToGauges() { suite.Run(tc.name, func() { suite.SetupTest() - // Generate delegator addresses - delAddrs := CreateRandomAccounts(tc.delegatorNumber) - // setup validators valAddrs := suite.SetupValidators(tc.validatorStats) denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) // setup superfluid delegations - intermediaryAccs, _ := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, tc.superDelegations, denoms) + _, intermediaryAccs, _ := suite.setupSuperfluidDelegations(valAddrs, tc.superDelegations, denoms) unbondingDuration := suite.App.StakingKeeper.GetParams(suite.Ctx).UnbondingTime // allocate rewards to first validator diff --git a/x/superfluid/keeper/edge_case_test.go b/x/superfluid/keeper/edge_case_test.go index c4ba9287a5a..a03a17883f3 100644 --- a/x/superfluid/keeper/edge_case_test.go +++ b/x/superfluid/keeper/edge_case_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" ) @@ -49,7 +50,7 @@ func (suite *KeeperTestSuite) TestSuperfluidDelegatedValidatorJailed() { for _, del := range tc.superDelegations { valAddr := valAddrs[del.valIndex] delAddr := delAddrs[del.delIndex] - lock := suite.SetupSuperfluidDelegate(delAddr, valAddr, denoms[del.lpIndex], del.lpAmount) + lock := suite.setupSuperfluidDelegate(delAddr, valAddr, denoms[del.lpIndex], del.lpAmount) // save accounts and locks for future use locks = append(locks, lock) @@ -125,8 +126,6 @@ func (suite *KeeperTestSuite) TestTryUnbondingSuperfluidLockupDirectly() { tc := tc suite.Run(tc.name, func() { suite.SetupTest() - // Generate delegator addresses - delAddrs := CreateRandomAccounts(tc.delegatorNumber) // setup validators valAddrs := suite.SetupValidators(tc.validatorStats) @@ -134,8 +133,7 @@ func (suite *KeeperTestSuite) TestTryUnbondingSuperfluidLockupDirectly() { denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) // setup superfluid delegations - _, _, _ = delAddrs, valAddrs, denoms - _, locks := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, tc.superDelegations, denoms) + _, _, locks := suite.setupSuperfluidDelegations(valAddrs, tc.superDelegations, denoms) for _, lock := range locks { err := suite.App.LockupKeeper.BeginUnlock(suite.Ctx, lock.ID, sdk.Coins{}) diff --git a/x/superfluid/keeper/grpc_query_test.go b/x/superfluid/keeper/grpc_query_test.go index 8b027179e33..cd9f6aabe5a 100644 --- a/x/superfluid/keeper/grpc_query_test.go +++ b/x/superfluid/keeper/grpc_query_test.go @@ -43,9 +43,6 @@ func (suite *KeeperTestSuite) TestGRPCSuperfluidAsset() { func (suite *KeeperTestSuite) TestGRPCQuerySuperfluidDelegations() { suite.SetupTest() - // Generate delegator addresses - delAddrs := CreateRandomAccounts(2) - // setup 2 validators valAddrs := suite.SetupValidators([]stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}) @@ -60,13 +57,13 @@ func (suite *KeeperTestSuite) TestGRPCQuerySuperfluidDelegations() { } // setup superfluid delegations - _, locks := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, superfluidDelegations, denoms) + delegatorAddresses, _, locks := suite.setupSuperfluidDelegations(valAddrs, superfluidDelegations, denoms) // for each superfluid delegation, query the amount and make sure it is 1000000 for _, delegation := range superfluidDelegations { lpDenom := denoms[delegation.lpIndex] res, err := suite.queryClient.SuperfluidDelegationAmount(sdk.WrapSDKContext(suite.Ctx), &types.SuperfluidDelegationAmountRequest{ - DelegatorAddress: delAddrs[delegation.delIndex].String(), + DelegatorAddress: delegatorAddresses[delegation.delIndex].String(), ValidatorAddress: valAddrs[delegation.valIndex].String(), Denom: lpDenom, }) @@ -75,7 +72,7 @@ func (suite *KeeperTestSuite) TestGRPCQuerySuperfluidDelegations() { } // for each delegator, query all their superfluid delegations and make sure they have 2 delegations - for _, delegator := range delAddrs { + for _, delegator := range delegatorAddresses { res, err := suite.queryClient.SuperfluidDelegationsByDelegator(sdk.WrapSDKContext(suite.Ctx), &types.SuperfluidDelegationsByDelegatorRequest{ DelegatorAddress: delegator.String(), }) @@ -139,12 +136,8 @@ func (suite *KeeperTestSuite) TestGRPCQuerySuperfluidDelegations() { func (suite *KeeperTestSuite) TestGRPCQuerySuperfluidDelegationsDontIncludeUnbonding() { suite.SetupTest() - // Generate delegator addresses - delAddrs := CreateRandomAccounts(2) - // setup 2 validators valAddrs := suite.SetupValidators([]stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}) - denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) // create a delegation of 1000000 for every combination of 2 delegations, 2 validators, and 2 superfluid denoms @@ -156,7 +149,7 @@ func (suite *KeeperTestSuite) TestGRPCQuerySuperfluidDelegationsDontIncludeUnbon } // setup superfluid delegations - _, locks := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, superfluidDelegations, denoms) + delegatorAddresses, _, locks := suite.setupSuperfluidDelegations(valAddrs, superfluidDelegations, denoms) // start unbonding the superfluid delegations of denom0 from delegator0 to validator0 err := suite.querier.SuperfluidUndelegate(suite.Ctx, locks[0].Owner, locks[0].ID) @@ -164,7 +157,7 @@ func (suite *KeeperTestSuite) TestGRPCQuerySuperfluidDelegationsDontIncludeUnbon // query to make sure that the amount delegated for the now unbonding delegation is 0 res, err := suite.queryClient.SuperfluidDelegationAmount(sdk.WrapSDKContext(suite.Ctx), &types.SuperfluidDelegationAmountRequest{ - DelegatorAddress: delAddrs[0].String(), + DelegatorAddress: delegatorAddresses[0].String(), ValidatorAddress: valAddrs[0].String(), Denom: denoms[0], }) @@ -173,7 +166,7 @@ func (suite *KeeperTestSuite) TestGRPCQuerySuperfluidDelegationsDontIncludeUnbon // query to make sure that the unbonding delegation is not included in delegator query res2, err := suite.queryClient.SuperfluidDelegationsByDelegator(sdk.WrapSDKContext(suite.Ctx), &types.SuperfluidDelegationsByDelegatorRequest{ - DelegatorAddress: delAddrs[0].String(), + DelegatorAddress: delegatorAddresses[0].String(), }) suite.Require().NoError(err) suite.Require().Len(res2.SuperfluidDelegationRecords, 1) @@ -206,9 +199,6 @@ func (suite *KeeperTestSuite) TestGRPCQuerySuperfluidDelegationsDontIncludeUnbon func (suite *KeeperTestSuite) TestGRPCQueryTotalDelegationByDelegator() { suite.SetupTest() - // Generate delegator addresses - delAddrs := CreateRandomAccounts(2) - // setup 2 validators valAddrs := suite.SetupValidators([]stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}) @@ -223,13 +213,13 @@ func (suite *KeeperTestSuite) TestGRPCQueryTotalDelegationByDelegator() { } // setup superfluid delegations - suite.SetupSuperfluidDelegations(delAddrs, valAddrs, superfluidDelegations, denoms) + delegatorAddresses, _, _ := suite.setupSuperfluidDelegations(valAddrs, superfluidDelegations, denoms) // setup normal delegations - bond0to0 := stakingtypes.NewDelegation(delAddrs[0], valAddrs[0], sdk.NewDec(9000000)) - bond0to1 := stakingtypes.NewDelegation(delAddrs[0], valAddrs[1], sdk.NewDec(9000000)) - bond1to0 := stakingtypes.NewDelegation(delAddrs[1], valAddrs[0], sdk.NewDec(9000000)) - bond1to1 := stakingtypes.NewDelegation(delAddrs[1], valAddrs[1], sdk.NewDec(9000000)) + bond0to0 := stakingtypes.NewDelegation(delegatorAddresses[0], valAddrs[0], sdk.NewDec(9000000)) + bond0to1 := stakingtypes.NewDelegation(delegatorAddresses[0], valAddrs[1], sdk.NewDec(9000000)) + bond1to0 := stakingtypes.NewDelegation(delegatorAddresses[1], valAddrs[0], sdk.NewDec(9000000)) + bond1to1 := stakingtypes.NewDelegation(delegatorAddresses[1], valAddrs[1], sdk.NewDec(9000000)) suite.App.StakingKeeper.SetDelegation(suite.Ctx, bond0to0) suite.App.StakingKeeper.SetDelegation(suite.Ctx, bond0to1) @@ -245,7 +235,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryTotalDelegationByDelegator() { // for each delegator, query all their superfluid delegations and normal delegations. Making sure they have 4 delegations // Making sure TotalEquivalentStakedAmount is equal to converted amount + normal delegations - for _, delegator := range delAddrs { + for _, delegator := range delegatorAddresses { res, err := suite.queryClient.TotalDelegationByDelegator(sdk.WrapSDKContext(suite.Ctx), &types.QueryTotalDelegationByDelegatorRequest{ DelegatorAddress: delegator.String(), }) diff --git a/x/superfluid/keeper/hooks_test.go b/x/superfluid/keeper/hooks_test.go index ecfc0ff370d..9017467354d 100644 --- a/x/superfluid/keeper/hooks_test.go +++ b/x/superfluid/keeper/hooks_test.go @@ -49,8 +49,7 @@ func (suite *KeeperTestSuite) TestSuperfluidAfterEpochEnd() { denoms, poolIds := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20)}) // Generate delegator addresses - delAddrs := CreateRandomAccounts(tc.delegatorNumber) - intermediaryAccs, locks := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, tc.superDelegations, denoms) + delAddrs, intermediaryAccs, locks := suite.setupSuperfluidDelegations(valAddrs, tc.superDelegations, denoms) suite.checkIntermediaryAccountDelegations(intermediaryAccs) // run swap and set spot price @@ -257,16 +256,13 @@ func (suite *KeeperTestSuite) TestBeforeSlashingUnbondingDelegationHook() { slashFactor := sdk.NewDecWithPrec(5, 2) - // Generate delegator addresses - delAddrs := CreateRandomAccounts(tc.delegatorNumber) - // setup validators valAddrs := suite.SetupValidators(tc.validatorStats) denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) // setup superfluid delegations - intermediaryAccs, _ := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, tc.superDelegations, denoms) + _, intermediaryAccs, _ := suite.setupSuperfluidDelegations(valAddrs, tc.superDelegations, denoms) suite.checkIntermediaryAccountDelegations(intermediaryAccs) for _, lockId := range tc.superUnbondingLockIds { diff --git a/x/superfluid/keeper/intermediary_account_test.go b/x/superfluid/keeper/intermediary_account_test.go index ee86ab52e3c..29cbe67a3c0 100644 --- a/x/superfluid/keeper/intermediary_account_test.go +++ b/x/superfluid/keeper/intermediary_account_test.go @@ -52,7 +52,7 @@ func (suite *KeeperTestSuite) TestIntermediaryAccountCreation() { suite.Require().Equal(uint64(0), interAcc.GaugeId) suite.Require().Equal("", interAcc.ValAddr) - lock := suite.SetupSuperfluidDelegate(delAddr, valAddr, denom, superDelegation.lpAmount) + lock := suite.setupSuperfluidDelegate(delAddr, valAddr, denom, superDelegation.lpAmount) // check that intermediary Account connection is established interAccConnection := suite.App.SuperfluidKeeper.GetLockIdIntermediaryAccountConnection(suite.Ctx, lock.ID) diff --git a/x/superfluid/keeper/keeper_test.go b/x/superfluid/keeper/keeper_test.go index a6bd2272cc3..fa5a73d1fc8 100644 --- a/x/superfluid/keeper/keeper_test.go +++ b/x/superfluid/keeper/keeper_test.go @@ -14,6 +14,7 @@ import ( epochtypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" @@ -152,6 +153,98 @@ func (suite *KeeperTestSuite) SetupGammPoolsAndSuperfluidAssets(multipliers []sd return denoms, poolIds } +func (suite *KeeperTestSuite) setupSuperfluidDelegations(valAddrs []sdk.ValAddress, superDelegations []superfluidDelegation, denoms []string) ([]sdk.AccAddress, []types.SuperfluidIntermediaryAccount, []lockuptypes.PeriodLock) { + flagIntermediaryAcc := make(map[string]bool) + intermediaryAccs := []types.SuperfluidIntermediaryAccount{} + locks := []lockuptypes.PeriodLock{} + delAddrs := []sdk.AccAddress{} + + // we do sanity check on the test cases. + // if superfluid staking is happening with single val and multiple superfluid delegations, + // we should be running `AddTokensToLockByID`, instead of creating new locks + delegatorAddressMap := make(map[int64]sdk.AccAddress) + for _, superDelegation := range superDelegations { + // either create or use existing delegator address + var delAddr sdk.AccAddress + if cachedAddr, ok := delegatorAddressMap[superDelegation.delIndex]; ok { + delAddr = cachedAddr + } else { + pk := ed25519.GenPrivKey().PubKey() + delAddr = sdk.AccAddress(pk.Address()) + delegatorAddressMap[superDelegation.delIndex] = delAddr + delAddrs = append(delAddrs, delAddr) + } + + valAddr := valAddrs[superDelegation.valIndex] + lock := suite.setupSuperfluidDelegate(delAddr, valAddr, denoms[superDelegation.lpIndex], superDelegation.lpAmount) + address := suite.App.SuperfluidKeeper.GetLockIdIntermediaryAccountConnection(suite.Ctx, lock.ID) + gotAcc := suite.App.SuperfluidKeeper.GetIntermediaryAccount(suite.Ctx, address) + + // save accounts for future use + if flagIntermediaryAcc[gotAcc.String()] == false { + flagIntermediaryAcc[gotAcc.String()] = true + intermediaryAccs = append(intermediaryAccs, gotAcc) + } + // save locks for future use + locks = append(locks, lock) + } + return delAddrs, intermediaryAccs, locks +} + +func (suite *KeeperTestSuite) checkIntermediaryAccountDelegations(intermediaryAccs []types.SuperfluidIntermediaryAccount) { + for _, acc := range intermediaryAccs { + valAddr, err := sdk.ValAddressFromBech32(acc.ValAddr) + suite.Require().NoError(err) + + // check delegation from intermediary account to validator + delegation, found := suite.App.StakingKeeper.GetDelegation(suite.Ctx, acc.GetAccAddress(), valAddr) + suite.Require().True(found) + suite.Require().True(delegation.Shares.GTE(sdk.NewDec(10000000))) + + // check delegated tokens + validator, found := suite.App.StakingKeeper.GetValidator(suite.Ctx, valAddr) + suite.Require().True(found) + delegatedTokens := validator.TokensFromShares(delegation.Shares).TruncateInt() + suite.Require().True(delegatedTokens.GTE(sdk.NewInt(10000000))) + } +} + +func (suite *KeeperTestSuite) setupSuperfluidDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, denom string, amount int64) lockuptypes.PeriodLock { + unbondingDuration := suite.App.StakingKeeper.GetParams(suite.Ctx).UnbondingTime + + // create lockup of LP token + coins := sdk.Coins{sdk.NewInt64Coin(denom, amount)} + lastLockID := suite.App.LockupKeeper.GetLastLockID(suite.Ctx) + + lockID := suite.LockTokens(delAddr, coins, unbondingDuration) + lock, err := suite.App.LockupKeeper.GetLockByID(suite.Ctx, lockID) + suite.Require().NoError(err) + + // here we check if check `LockTokens` added to existing locks or created a new lock. + // if `LockTokens` created a new lock, we continue SuperfluidDelegate + // if lock has been existing before, we wouldn't have to call SuperfluidDelegate separately, as hooks on LockTokens would have automatically called IncreaseSuperfluidDelegation + if lastLockID != lockID { + err = suite.App.SuperfluidKeeper.SuperfluidDelegate(suite.Ctx, lock.Owner, lock.ID, valAddr.String()) + suite.Require().NoError(err) + } else { + // here we handle two cases. + // 1. the lock has existed before but has not been superflud staking + // 2. the lock has existed before and has been superfluid staking + + // we check if synth lock that has existed before, if it did, it means that the lock has been superfluid staked + // we do not care about unbonding synthlocks, as superfluid delegation has no effect + + _, err := suite.App.LockupKeeper.GetSyntheticLockup(suite.Ctx, lockID, keeper.StakingSyntheticDenom(lock.Coins[0].Denom, valAddr.String())) + // if lock has existed before but has not been superfluid staked, we do initial superfluid staking + if err != nil { + err = suite.App.SuperfluidKeeper.SuperfluidDelegate(suite.Ctx, lock.Owner, lock.ID, valAddr.String()) + suite.Require().NoError(err) + } + } + + return *lock +} + func TestKeeperTestSuite(t *testing.T) { suite.Run(t, new(KeeperTestSuite)) } diff --git a/x/superfluid/keeper/slash_test.go b/x/superfluid/keeper/slash_test.go index 8f09c51bc1f..bbe302047a1 100644 --- a/x/superfluid/keeper/slash_test.go +++ b/x/superfluid/keeper/slash_test.go @@ -72,7 +72,7 @@ func (suite *KeeperTestSuite) TestBeforeValidatorSlashed() { for _, del := range tc.superDelegations { valAddr := valAddrs[del.valIndex] delAddr := delAddrs[del.delIndex] - lock := suite.SetupSuperfluidDelegate(delAddr, valAddr, denoms[del.lpIndex], del.lpAmount) + lock := suite.setupSuperfluidDelegate(delAddr, valAddr, denoms[del.lpIndex], del.lpAmount) // save accounts and locks for future use locks = append(locks, lock) @@ -145,16 +145,13 @@ func (suite *KeeperTestSuite) TestSlashLockupsForUnbondingDelegationSlash() { suite.Run(tc.name, func() { suite.SetupTest() - // Generate delegator addresses - delAddrs := CreateRandomAccounts(tc.delegatorNumber) - // setup validators valAddrs := suite.SetupValidators(tc.validatorStats) denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) // setup superfluid delegations - intermediaryAccs, _ := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, tc.superDelegations, denoms) + _, intermediaryAccs, _ := suite.setupSuperfluidDelegations(valAddrs, tc.superDelegations, denoms) suite.checkIntermediaryAccountDelegations(intermediaryAccs) for _, lockId := range tc.superUnbondingLockIds { diff --git a/x/superfluid/keeper/stake_test.go b/x/superfluid/keeper/stake_test.go index 9a4b487ce08..f72ce71624f 100644 --- a/x/superfluid/keeper/stake_test.go +++ b/x/superfluid/keeper/stake_test.go @@ -1,13 +1,11 @@ package keeper_test import ( - "fmt" "time" abci "github.com/tendermint/tendermint/abci/types" lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" @@ -15,146 +13,35 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -type normalDelegation struct { - delIndex int64 - valIndex int64 - coinAmount int64 -} - type superfluidDelegation struct { delIndex int64 valIndex int64 lpIndex int64 lpAmount int64 } -type superfluidRedelegation struct { - lockId uint64 - oldValIndex int64 - newValIndex int64 -} - -type osmoEquivalentMultiplier struct { - lpIndex int64 - price sdk.Dec -} - -func (suite *KeeperTestSuite) SetupNormalDelegation(delAddrs []sdk.AccAddress, valAddrs []sdk.ValAddress, del normalDelegation) error { - val, found := suite.App.StakingKeeper.GetValidator(suite.Ctx, valAddrs[del.valIndex]) - if !found { - return fmt.Errorf("validator not found") - } - _, err := suite.App.StakingKeeper.Delegate(suite.Ctx, delAddrs[del.delIndex], sdk.NewIntFromUint64(uint64(del.coinAmount)), stakingtypes.Bonded, val, false) - return err -} - -func (suite *KeeperTestSuite) SetupSuperfluidDelegations(delAddrs []sdk.AccAddress, valAddrs []sdk.ValAddress, superDelegations []superfluidDelegation, denoms []string) ([]types.SuperfluidIntermediaryAccount, []lockuptypes.PeriodLock) { - flagIntermediaryAcc := make(map[string]bool) - intermediaryAccs := []types.SuperfluidIntermediaryAccount{} - locks := []lockuptypes.PeriodLock{} - - // setup superfluid delegations - - // we do sanity check on the test cases. - // if superfluid staking is happening with single val and multiple superfluid delegations, - // we should be running `AddTokensToLockByID`, instead of creating new locks - for _, del := range superDelegations { - delAddr := delAddrs[del.delIndex] - valAddr := valAddrs[del.valIndex] - lock := suite.SetupSuperfluidDelegate(delAddr, valAddr, denoms[del.lpIndex], del.lpAmount) - address := suite.App.SuperfluidKeeper.GetLockIdIntermediaryAccountConnection(suite.Ctx, lock.ID) - gotAcc := suite.App.SuperfluidKeeper.GetIntermediaryAccount(suite.Ctx, address) - - // save accounts for future use - if flagIntermediaryAcc[gotAcc.String()] == false { - flagIntermediaryAcc[gotAcc.String()] = true - intermediaryAccs = append(intermediaryAccs, gotAcc) - } - // save locks for future use - locks = append(locks, lock) - } - return intermediaryAccs, locks -} - -func (suite *KeeperTestSuite) checkIntermediaryAccountDelegations(intermediaryAccs []types.SuperfluidIntermediaryAccount) { - for _, acc := range intermediaryAccs { - valAddr, err := sdk.ValAddressFromBech32(acc.ValAddr) - suite.Require().NoError(err) - - // check delegation from intermediary account to validator - delegation, found := suite.App.StakingKeeper.GetDelegation(suite.Ctx, acc.GetAccAddress(), valAddr) - suite.Require().True(found) - suite.Require().True(delegation.Shares.GTE(sdk.NewDec(10000000))) - - // check delegated tokens - validator, found := suite.App.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - delegatedTokens := validator.TokensFromShares(delegation.Shares).TruncateInt() - suite.Require().True(delegatedTokens.GTE(sdk.NewInt(10000000))) - } -} - -func (suite *KeeperTestSuite) SetupSuperfluidDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, denom string, amount int64) lockuptypes.PeriodLock { - unbondingDuration := suite.App.StakingKeeper.GetParams(suite.Ctx).UnbondingTime - - // create lockup of LP token - coins := sdk.Coins{sdk.NewInt64Coin(denom, amount)} - lastLockID := suite.App.LockupKeeper.GetLastLockID(suite.Ctx) - - lockID := suite.LockTokens(delAddr, coins, unbondingDuration) - lock, err := suite.App.LockupKeeper.GetLockByID(suite.Ctx, lockID) - suite.Require().NoError(err) - - // here we check if check `LockTokens` added to existing locks or created a new lock. - // if `LockTokens` created a new lock, we continue SuperfluidDelegate - // if lock has been existing before, we wouldn't have to call SuperfluidDelegate separately, as hooks on LockTokens would have automatically called IncreaseSuperfluidDelegation - if lastLockID != lockID { - err = suite.App.SuperfluidKeeper.SuperfluidDelegate(suite.Ctx, lock.Owner, lock.ID, valAddr.String()) - suite.Require().NoError(err) - } else { - // here we handle two cases. - // 1. the lock has existed before but has not been superflud staking - // 2. the lock has existed before and has been superfluid staking - - // we check if synth lock that has existed before, if it did, it means that the lock has been superfluid staked - // we do not care about unbonding synthlocks, as superfluid delegation has no effect - - _, err := suite.App.LockupKeeper.GetSyntheticLockup(suite.Ctx, lockID, keeper.StakingSyntheticDenom(lock.Coins[0].Denom, valAddr.String())) - // if lock has existed before but has not been superfluid staked, we do initial superfluid staking - if err != nil { - err = suite.App.SuperfluidKeeper.SuperfluidDelegate(suite.Ctx, lock.Owner, lock.ID, valAddr.String()) - suite.Require().NoError(err) - } - } - - return *lock -} func (suite *KeeperTestSuite) TestSuperfluidDelegate() { testCases := []struct { name string validatorStats []stakingtypes.BondStatus - delegatorNumber int superDelegations []superfluidDelegation expInterDelegation []sdk.Dec }{ { "with single validator and single superfluid delegation", []stakingtypes.BondStatus{stakingtypes.Bonded}, - 1, []superfluidDelegation{{0, 0, 0, 1000000}}, []sdk.Dec{sdk.NewDec(10000000)}, // 50% x 20 x 1000000 }, { "with single validator and additional superfluid delegations", []stakingtypes.BondStatus{stakingtypes.Bonded}, - 1, []superfluidDelegation{{0, 0, 0, 1000000}, {0, 0, 0, 1000000}}, []sdk.Dec{sdk.NewDec(20000000)}, // 50% x 20 x 1000000 x 2 }, { "with multiple validators and multiple superfluid delegations", []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, - 2, []superfluidDelegation{{0, 0, 0, 1000000}, {1, 1, 0, 1000000}}, []sdk.Dec{sdk.NewDec(10000000), sdk.NewDec(10000000)}, // 50% x 20 x 1000000 }, @@ -166,9 +53,6 @@ func (suite *KeeperTestSuite) TestSuperfluidDelegate() { suite.SetupTest() bondDenom := suite.App.StakingKeeper.BondDenom(suite.Ctx) - // Generate delegator addresses - delAddrs := CreateRandomAccounts(tc.delegatorNumber) - // setup validators valAddrs := suite.SetupValidators(tc.validatorStats) @@ -179,8 +63,7 @@ func (suite *KeeperTestSuite) TestSuperfluidDelegate() { presupplyWithOffset := suite.App.BankKeeper.GetSupplyWithOffset(suite.Ctx, bondDenom) // setup superfluid delegations - _, _, _ = delAddrs, valAddrs, denoms - intermediaryAccs, locks := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, tc.superDelegations, denoms) + _, intermediaryAccs, locks := suite.setupSuperfluidDelegations(valAddrs, tc.superDelegations, denoms) // ensure post-superfluid delegations osmo supplywithoffset is the same while supply is not postsupply := suite.App.BankKeeper.GetSupply(suite.Ctx, bondDenom) @@ -257,9 +140,7 @@ func (suite *KeeperTestSuite) TestSuperfluidUndelegate() { testCases := []struct { name string validatorStats []stakingtypes.BondStatus - delegatorNumber int superDelegations []superfluidDelegation - addMoreTokensLockIds []uint64 superUnbondingLockIds []uint64 expSuperUnbondingErr []bool // expected amount of delegation to intermediary account @@ -268,9 +149,7 @@ func (suite *KeeperTestSuite) TestSuperfluidUndelegate() { { "with single validator and single superfluid delegation and single undelegation", []stakingtypes.BondStatus{stakingtypes.Bonded}, - 1, []superfluidDelegation{{0, 0, 0, 1000000}}, - []uint64{}, []uint64{1}, []bool{false}, []sdk.Dec{sdk.ZeroDec()}, @@ -287,9 +166,7 @@ func (suite *KeeperTestSuite) TestSuperfluidUndelegate() { { "with single validator and additional superfluid delegations and single undelegation", []stakingtypes.BondStatus{stakingtypes.Bonded}, - 1, []superfluidDelegation{{0, 0, 0, 1000000}, {0, 0, 0, 1000000}}, - []uint64{}, []uint64{1}, []bool{false}, []sdk.Dec{sdk.ZeroDec()}, @@ -297,9 +174,7 @@ func (suite *KeeperTestSuite) TestSuperfluidUndelegate() { { "with multiple validators and multiple superfluid delegations and multiple undelegations", []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, - 2, []superfluidDelegation{{0, 0, 0, 1000000}, {1, 1, 0, 1000000}}, - []uint64{}, []uint64{1, 2}, []bool{false, false}, []sdk.Dec{sdk.ZeroDec()}, @@ -307,9 +182,7 @@ func (suite *KeeperTestSuite) TestSuperfluidUndelegate() { { "undelegating not available lock id", []stakingtypes.BondStatus{stakingtypes.Bonded}, - 1, []superfluidDelegation{{0, 0, 0, 1000000}}, - []uint64{}, []uint64{2}, []bool{true}, []sdk.Dec{}, @@ -317,9 +190,7 @@ func (suite *KeeperTestSuite) TestSuperfluidUndelegate() { { "try undelegating twice for same lock id", []stakingtypes.BondStatus{stakingtypes.Bonded}, - 1, []superfluidDelegation{{0, 0, 0, 1000000}}, - []uint64{}, []uint64{1, 1}, []bool{false, true}, []sdk.Dec{sdk.ZeroDec()}, @@ -333,30 +204,15 @@ func (suite *KeeperTestSuite) TestSuperfluidUndelegate() { bondDenom := suite.App.StakingKeeper.GetParams(suite.Ctx).BondDenom - // Generate delegator addresses - delAddrs := CreateRandomAccounts(tc.delegatorNumber) - // setup validators valAddrs := suite.SetupValidators(tc.validatorStats) denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) // setup superfluid delegations - intermediaryAccs, _ := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, tc.superDelegations, denoms) + _, intermediaryAccs, _ := suite.setupSuperfluidDelegations(valAddrs, tc.superDelegations, denoms) suite.checkIntermediaryAccountDelegations(intermediaryAccs) - for _, lockId := range tc.addMoreTokensLockIds { - lock, err := suite.App.LockupKeeper.GetLockByID(suite.Ctx, lockId) - suite.Require().NoError(err) - lockOwner, err := sdk.AccAddressFromBech32(lock.Owner) - suite.Require().NoError(err) - coin := sdk.NewInt64Coin("gamm/pool/1", 1000000) - suite.App.BankKeeper.MintCoins(suite.Ctx, minttypes.ModuleName, sdk.NewCoins(coin)) - suite.App.BankKeeper.SendCoinsFromModuleToAccount(suite.Ctx, minttypes.ModuleName, lockOwner, sdk.NewCoins(coin)) - _, err = suite.App.LockupKeeper.AddTokensToLockByID(suite.Ctx, lockId, lockOwner, coin) - suite.Require().NoError(err) - } - for index, lockId := range tc.superUnbondingLockIds { // get intermediary account accAddr := suite.App.SuperfluidKeeper.GetLockIdIntermediaryAccountConnection(suite.Ctx, lockId) @@ -445,16 +301,13 @@ func (suite *KeeperTestSuite) TestSuperfluidUndelegate() { func (suite *KeeperTestSuite) TestSuperfluidUnbondLock() { suite.SetupTest() - // Generate delegator addresses - delAddrs := CreateRandomAccounts(1) - // setup validators valAddrs := suite.SetupValidators([]stakingtypes.BondStatus{stakingtypes.Bonded}) denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) // setup superfluid delegations - intermediaryAccs, locks := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, []superfluidDelegation{{0, 0, 0, 1000000}}, denoms) + _, intermediaryAccs, locks := suite.setupSuperfluidDelegations(valAddrs, []superfluidDelegation{{0, 0, 0, 1000000}}, denoms) suite.checkIntermediaryAccountDelegations(intermediaryAccs) for _, lock := range locks { @@ -527,6 +380,151 @@ func (suite *KeeperTestSuite) TestSuperfluidUnbondLock() { } } +func (suite *KeeperTestSuite) TestRefreshIntermediaryDelegationAmounts() { + testCases := []struct { + name string + validatorStats []stakingtypes.BondStatus + superDelegations []superfluidDelegation + // denom of the superfluid asset is the key, multiplier is the value + multipliersByDenom map[string]sdk.Dec + }{ + { + "with single validator and single delegation", + []stakingtypes.BondStatus{stakingtypes.Bonded}, + []superfluidDelegation{{0, 0, 0, 1000000}}, + map[string]sdk.Dec{"gamm/pool/1": sdk.NewDec(10)}, + }, + { + "with single validator and additional delegations", + []stakingtypes.BondStatus{stakingtypes.Bonded}, + []superfluidDelegation{{0, 0, 0, 1000000}, {0, 0, 0, 1000000}}, + map[string]sdk.Dec{"gamm/pool/1": sdk.NewDec(10)}, + }, + { + "with multiple validator and multiple superfluid delegations", + []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, + []superfluidDelegation{{0, 0, 0, 1000000}, {1, 1, 0, 1000000}}, + map[string]sdk.Dec{"gamm/pool/1": sdk.NewDec(10)}, + }, + { + "with single validator and multiple denom superfluid delegations", + []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, + []superfluidDelegation{{0, 0, 0, 1000000}, {0, 0, 1, 1000000}}, + map[string]sdk.Dec{"gamm/pool/1": sdk.NewDec(10), "gamm/pool/2": sdk.NewDec(10)}, + }, + { + "with multiple validators and multiple denom superfluid delegations", + []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, + []superfluidDelegation{{0, 0, 0, 1000000}, {0, 1, 1, 1000000}}, + map[string]sdk.Dec{"gamm/pool/1": sdk.NewDec(10), "gamm/pool/2": sdk.NewDec(10)}, + }, + { + "zero price multiplier check", + []stakingtypes.BondStatus{stakingtypes.Bonded}, + []superfluidDelegation{{0, 0, 0, 1000000}}, + map[string]sdk.Dec{"gamm/pool/1": sdk.NewDec(0)}, + }, + { + "dust price multiplier check", + []stakingtypes.BondStatus{stakingtypes.Bonded}, + []superfluidDelegation{{0, 0, 0, 1000000}}, + map[string]sdk.Dec{"gamm/pool/1": sdk.NewDecWithPrec(1, 10)}, // 10^-10 + }, + } + + for _, tc := range testCases { + tc := tc + suite.Run(tc.name, func() { + suite.SetupTest() + + // setup validators + valAddrs := suite.SetupValidators(tc.validatorStats) + + denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) + + // setup superfluid delegations + _, intermediaryAccs, locks := suite.setupSuperfluidDelegations(valAddrs, tc.superDelegations, denoms) + suite.checkIntermediaryAccountDelegations(intermediaryAccs) + + // we make a map of intermediary account to delegation shares to store delegation share + // before refreshing intermediary account delegations on epoch + interAccIndexToDenomShare := make(map[int]sdk.Dec) + for accIndex, intermediaryAcc := range intermediaryAccs { + valAddr, err := sdk.ValAddressFromBech32(intermediaryAcc.ValAddr) + suite.Require().NoError(err) + delegation, found := suite.App.StakingKeeper.GetDelegation(suite.Ctx, intermediaryAcc.GetAccAddress(), valAddr) + suite.Require().True(found) + + interAccIndexToDenomShare[accIndex] = delegation.Shares + } + + for denom, multiplier := range tc.multipliersByDenom { + suite.App.SuperfluidKeeper.SetOsmoEquivalentMultiplier(suite.Ctx, 2, denom, multiplier) + } + + suite.App.SuperfluidKeeper.RefreshIntermediaryDelegationAmounts(suite.Ctx) + + originalMultiplier := sdk.NewDec(20) + for interAccIndex, intermediaryAcc := range intermediaryAccs { + multiplier := tc.multipliersByDenom[intermediaryAcc.Denom] + oldDelegation := interAccIndexToDenomShare[interAccIndex] + expDelegation := oldDelegation.Mul(multiplier).Quo(originalMultiplier) + lpTokenAmount := sdk.NewInt(1000000) + decAmt := multiplier.Mul(lpTokenAmount.ToDec()) + asset := suite.App.SuperfluidKeeper.GetSuperfluidAsset(suite.Ctx, intermediaryAcc.Denom) + expAmount := suite.App.SuperfluidKeeper.GetRiskAdjustedOsmoValue(suite.Ctx, asset, decAmt.RoundInt()) + + // check delegation changes + valAddr, err := sdk.ValAddressFromBech32(intermediaryAcc.ValAddr) + suite.Require().NoError(err) + delegation, found := suite.App.StakingKeeper.GetDelegation(suite.Ctx, intermediaryAcc.GetAccAddress(), valAddr) + if expAmount.IsPositive() { + suite.Require().True(found) + suite.Require().Equal(delegation.Shares, expDelegation) + } else { + suite.Require().False(found) + } + } + + // unbond all lockups + for _, lock := range locks { + // superfluid undelegate + // handling the case same lockup is used for further delegation + cacheCtx, write := suite.Ctx.CacheContext() + err := suite.App.SuperfluidKeeper.SuperfluidUndelegate(cacheCtx, lock.Owner, lock.ID) + if err == nil { + write() + } + } + unbondingDuration := suite.App.StakingKeeper.GetParams(suite.Ctx).UnbondingTime + + for _, intermediaryAcc := range intermediaryAccs { + suite.Ctx = suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(unbondingDuration + time.Second)) + suite.App.EndBlocker(suite.Ctx, abci.RequestEndBlock{Height: suite.Ctx.BlockHeight()}) + + unbonded := suite.App.BankKeeper.GetBalance(suite.Ctx, intermediaryAcc.GetAccAddress(), sdk.DefaultBondDenom) + suite.Require().True(unbonded.IsZero()) + } + + // refresh intermediary account delegations + suite.App.SuperfluidKeeper.RefreshIntermediaryDelegationAmounts(suite.Ctx) + + for _, intermediaryAcc := range intermediaryAccs { + // check unbonded amount is removed after refresh operation + refreshed := suite.App.BankKeeper.GetBalance(suite.Ctx, intermediaryAcc.GetAccAddress(), sdk.DefaultBondDenom) + suite.Require().True(refreshed.IsZero()) + } + + }) + } +} + +// type superfluidRedelegation struct { +// lockId uint64 +// oldValIndex int64 +// newValIndex int64 +// } + // func (suite *KeeperTestSuite) TestSuperfluidRedelegate() { // testCases := []struct { // name string @@ -676,367 +674,3 @@ func (suite *KeeperTestSuite) TestSuperfluidUnbondLock() { // }) // } // } - -func (suite *KeeperTestSuite) TestRefreshIntermediaryDelegationAmounts() { - testCases := []struct { - name string - validatorStats []stakingtypes.BondStatus - delegatorNumber int - superDelegations []superfluidDelegation - roundOneMultipliers []osmoEquivalentMultiplier - roundTwoMultipliers []osmoEquivalentMultiplier - checkAccIndexes []int64 - }{ - { - "with single validator and single delegation", - []stakingtypes.BondStatus{stakingtypes.Bonded}, - 1, - []superfluidDelegation{{0, 0, 0, 1000000}}, - []osmoEquivalentMultiplier{{0, sdk.NewDec(10)}}, - []osmoEquivalentMultiplier{}, - []int64{0}, - }, - { - "with single validator and additional delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded}, - 1, - []superfluidDelegation{{0, 0, 0, 1000000}, {0, 0, 0, 1000000}}, - []osmoEquivalentMultiplier{{0, sdk.NewDec(10)}}, - []osmoEquivalentMultiplier{}, - []int64{0}, - }, - { - "with multiple validator and multiple superfluid delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, - 2, - []superfluidDelegation{{0, 0, 0, 1000000}, {1, 1, 0, 1000000}}, - []osmoEquivalentMultiplier{{0, sdk.NewDec(10)}}, - []osmoEquivalentMultiplier{}, - []int64{0, 1}, - }, - { - "with single validator and multiple denom superfluid delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, - 2, - []superfluidDelegation{{0, 0, 0, 1000000}, {0, 0, 1, 1000000}}, - []osmoEquivalentMultiplier{{0, sdk.NewDec(10)}, {1, sdk.NewDec(10)}}, - []osmoEquivalentMultiplier{}, - []int64{0, 1}, - }, - { - "with multiple validators and multiple denom superfluid delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, - 2, - []superfluidDelegation{{0, 0, 0, 1000000}, {0, 1, 1, 1000000}}, - []osmoEquivalentMultiplier{{0, sdk.NewDec(10)}, {1, sdk.NewDec(10)}}, - []osmoEquivalentMultiplier{}, - []int64{0, 1}, - }, - { - "zero price multiplier check", - []stakingtypes.BondStatus{stakingtypes.Bonded}, - 2, - []superfluidDelegation{{0, 0, 0, 1000000}}, - []osmoEquivalentMultiplier{{0, sdk.NewDec(0)}}, - []osmoEquivalentMultiplier{}, - []int64{0}, - }, - { - "refresh case from zero to non-zero", - []stakingtypes.BondStatus{stakingtypes.Bonded}, - 2, - []superfluidDelegation{{0, 0, 0, 1000000}}, - []osmoEquivalentMultiplier{{0, sdk.NewDec(0)}}, - []osmoEquivalentMultiplier{{0, sdk.NewDec(10)}}, - []int64{0}, - }, - { - "dust price multiplier check", - []stakingtypes.BondStatus{stakingtypes.Bonded}, - 2, - []superfluidDelegation{{0, 0, 0, 1000000}}, - []osmoEquivalentMultiplier{{0, sdk.NewDecWithPrec(1, 10)}}, // 10^-10 - []osmoEquivalentMultiplier{}, - []int64{0}, - }, - { - "refresh case from dust to non-dust", - []stakingtypes.BondStatus{stakingtypes.Bonded}, - 2, - []superfluidDelegation{{0, 0, 0, 1000000}}, - []osmoEquivalentMultiplier{{0, sdk.NewDecWithPrec(1, 10)}}, // 10^-10 - []osmoEquivalentMultiplier{{0, sdk.NewDec(10)}}, - []int64{0}, - }, - } - - for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { - suite.SetupTest() - - bondDenom := suite.App.StakingKeeper.BondDenom(suite.Ctx) - - // Generate delegator addresses - delAddrs := CreateRandomAccounts(tc.delegatorNumber) - - // setup validators - valAddrs := suite.SetupValidators(tc.validatorStats) - - denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) - - // setup superfluid delegations - intermediaryAccs, locks := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, tc.superDelegations, denoms) - suite.checkIntermediaryAccountDelegations(intermediaryAccs) - intermediaryDels := []sdk.Dec{} - - for _, intAccIndex := range tc.checkAccIndexes { - expAcc := intermediaryAccs[intAccIndex] - valAddr, err := sdk.ValAddressFromBech32(expAcc.ValAddr) - suite.Require().NoError(err) - - // check delegation from intermediary account to validator - delegation, found := suite.App.StakingKeeper.GetDelegation(suite.Ctx, expAcc.GetAccAddress(), valAddr) - suite.Require().True(found) - intermediaryDels = append(intermediaryDels, delegation.Shares) - } - - // multiplier change before refresh - multiplierByDenom := make(map[string]sdk.Dec) - for _, multiplier := range tc.roundOneMultipliers { - denom := denoms[multiplier.lpIndex] - multiplierByDenom[denom] = multiplier.price - suite.App.SuperfluidKeeper.SetOsmoEquivalentMultiplier(suite.Ctx, 2, denom, multiplier.price) - } - - // get pre-superfluid delgations osmo supply and supplyWithOffset - presupply := suite.App.BankKeeper.GetSupply(suite.Ctx, bondDenom) - presupplyWithOffset := suite.App.BankKeeper.GetSupplyWithOffset(suite.Ctx, bondDenom) - - // refresh intermediary account delegations - suite.App.SuperfluidKeeper.RefreshIntermediaryDelegationAmounts(suite.Ctx) - - // ensure post-superfluid delegations osmo supplywithoffset is the same while supply is not - postsupply := suite.App.BankKeeper.GetSupply(suite.Ctx, bondDenom) - postsupplyWithOffset := suite.App.BankKeeper.GetSupplyWithOffset(suite.Ctx, bondDenom) - suite.Require().False(postsupply.IsEqual(presupply), "presupply: %s postsupply: %s", presupply, postsupply) - suite.Require().True(postsupplyWithOffset.IsEqual(presupplyWithOffset)) - - originMultiplier := sdk.NewDec(20) - for index, intAccIndex := range tc.checkAccIndexes { - expAcc := intermediaryAccs[intAccIndex] - multiplier, ok := multiplierByDenom[expAcc.Denom] - if !ok { - multiplier = originMultiplier - } - - // calculating the estimated delegation amount for multiplier change - expDelegation := intermediaryDels[index].Mul(multiplier).Quo(originMultiplier) - lpTokenAmount := sdk.NewInt(1000000) - decAmt := multiplier.Mul(lpTokenAmount.ToDec()) - asset := suite.App.SuperfluidKeeper.GetSuperfluidAsset(suite.Ctx, expAcc.Denom) - expAmount := suite.App.SuperfluidKeeper.GetRiskAdjustedOsmoValue(suite.Ctx, asset, decAmt.RoundInt()) - - valAddr, err := sdk.ValAddressFromBech32(expAcc.ValAddr) - suite.Require().NoError(err) - - // check delegation changes - delegation, found := suite.App.StakingKeeper.GetDelegation(suite.Ctx, expAcc.GetAccAddress(), valAddr) - if expAmount.IsPositive() { - suite.Require().True(found) - suite.Require().Equal(delegation.Shares, expDelegation) - } else { - suite.Require().False(found) - } - } - - // if second round multipliers exists, execute round two multipliers mock and finish tests - if len(tc.roundTwoMultipliers) > 0 { - multiplier2ByDenom := make(map[string]sdk.Dec) - for _, multiplier := range tc.roundTwoMultipliers { - denom := denoms[multiplier.lpIndex] - multiplier2ByDenom[denom] = multiplier.price - suite.App.SuperfluidKeeper.SetOsmoEquivalentMultiplier(suite.Ctx, 3, denom, multiplier.price) - } - // refresh intermediary account delegations - suite.App.SuperfluidKeeper.RefreshIntermediaryDelegationAmounts(suite.Ctx) - - for index, intAccIndex := range tc.checkAccIndexes { - expAcc := intermediaryAccs[intAccIndex] - valAddr, err := sdk.ValAddressFromBech32(expAcc.ValAddr) - suite.Require().NoError(err) - - expDelegation := intermediaryDels[index].Mul(multiplier2ByDenom[expAcc.Denom]).Quo(originMultiplier) - - // check delegation changes - delegation, found := suite.App.StakingKeeper.GetDelegation(suite.Ctx, expAcc.GetAccAddress(), valAddr) - - suite.Require().True(found) - suite.Require().Equal(delegation.Shares, expDelegation) - } - return - } - - // unbond all lockups - for _, lock := range locks { - // superfluid undelegate - // handling the case same lockup is used for further delegation - cacheCtx, write := suite.Ctx.CacheContext() - err := suite.App.SuperfluidKeeper.SuperfluidUndelegate(cacheCtx, lock.Owner, lock.ID) - if err == nil { - write() - } - } - unbondingDuration := suite.App.StakingKeeper.GetParams(suite.Ctx).UnbondingTime - - // check intermediary account changes after unbonding operations - for _, intAccIndex := range tc.checkAccIndexes { - expAcc := intermediaryAccs[intAccIndex] - suite.Ctx = suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(unbondingDuration + time.Second)) - suite.App.EndBlocker(suite.Ctx, abci.RequestEndBlock{Height: suite.Ctx.BlockHeight()}) - - unbonded := suite.App.BankKeeper.GetBalance(suite.Ctx, expAcc.GetAccAddress(), sdk.DefaultBondDenom) - suite.Require().True(unbonded.IsZero()) - } - - // refresh intermediary account delegations - suite.App.SuperfluidKeeper.RefreshIntermediaryDelegationAmounts(suite.Ctx) - - // check if intermediary accounts does not have free balance after refresh operation - for _, intAccIndex := range tc.checkAccIndexes { - expAcc := intermediaryAccs[intAccIndex] - // check unbonded amount is removed after refresh operation - refreshed := suite.App.BankKeeper.GetBalance(suite.Ctx, expAcc.GetAccAddress(), sdk.DefaultBondDenom) - suite.Require().True(refreshed.IsZero()) - } - }) - } -} - -func (suite *KeeperTestSuite) TestSuperfluidDelegationGovernanceVoting() { - testCases := []struct { - name string - validatorStats []stakingtypes.BondStatus - superDelegations [][]superfluidDelegation - normalDelegations []normalDelegation - }{ - { - "with single validator and single delegation", - []stakingtypes.BondStatus{stakingtypes.Bonded}, - [][]superfluidDelegation{{{0, 0, 0, 1000000}}}, - nil, - }, - { - "with single validator and additional delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded}, - [][]superfluidDelegation{{{0, 0, 0, 1000000}, {0, 0, 0, 1000000}}}, - nil, - }, - { - "with multiple validator and multiple superfluid delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, - [][]superfluidDelegation{{{0, 0, 0, 1000000}}, {{1, 1, 0, 1000000}}}, - nil, - }, - { - "with single validator and multiple denom superfluid delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, - [][]superfluidDelegation{{{0, 0, 0, 1000000}, {0, 0, 1, 1000000}}}, - nil, - }, - { - "with multiple validators and multiple denom superfluid delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, - [][]superfluidDelegation{{{0, 0, 0, 1000000}, {0, 1, 1, 1000000}}}, - nil, - }, - { - "many delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Bonded}, - [][]superfluidDelegation{ - {{0, 0, 0, 1000000}, {0, 1, 1, 1000000}}, - {{1, 0, 0, 1000000}, {1, 0, 1, 1000000}}, - {{2, 1, 1, 1000000}, {2, 1, 0, 1000000}}, - {{3, 0, 0, 1000000}, {3, 1, 1, 1000000}}, - }, - nil, - }, - { - "with normal delegations", - []stakingtypes.BondStatus{stakingtypes.Bonded}, - [][]superfluidDelegation{ - {{0, 0, 0, 1000000}, {0, 0, 1, 1000000}}, - }, - []normalDelegation{ - {0, 0, 1000000}, - }, - }, - } - - for _, tc := range testCases { - tc := tc - - suite.Run(tc.name, func() { - suite.SetupTest() - - denoms, _ := suite.SetupGammPoolsAndSuperfluidAssets([]sdk.Dec{sdk.NewDec(20), sdk.NewDec(20)}) - - // Generate delegator addresses - delAddrs := CreateRandomAccounts(len(tc.superDelegations)) - - // setup validators - valAddrs := suite.SetupValidators(tc.validatorStats) - - // setup superfluid delegations - for _, sfdel := range tc.superDelegations { - intermediaryAccs, _ := suite.SetupSuperfluidDelegations(delAddrs, valAddrs, sfdel, denoms) - suite.checkIntermediaryAccountDelegations(intermediaryAccs) - } - - // setup normal delegations - for _, del := range tc.normalDelegations { - err := suite.SetupNormalDelegation(delAddrs, valAddrs, del) - suite.NoError(err) - } - - // all expected delegated amounts to a validator from a delegator - delegatedAmount := func(delidx, validx int) sdk.Int { - res := sdk.ZeroInt() - for _, del := range tc.superDelegations[delidx] { - if del.valIndex == int64(validx) { - res = res.AddRaw(del.lpAmount) - } - } - if len(tc.normalDelegations) != 0 { - del := tc.normalDelegations[delidx] - res = res.AddRaw(del.coinAmount / 10) // LP price is 10 osmo in this test - } - return res - } - for delidx := range tc.superDelegations { - // store all actual delegations to a validator - sharePerValidatorMap := make(map[string]sdk.Dec) - for validx := range tc.validatorStats { - sharePerValidatorMap[valAddrs[validx].String()] = sdk.ZeroDec() - } - addToSharePerValidatorMap := func(val sdk.ValAddress, share sdk.Dec) { - if existing, ok := sharePerValidatorMap[val.String()]; ok { - share.AddMut(existing) - } - sharePerValidatorMap[val.String()] = share - } - - // iterate delegations and add eligible shares to the sharePerValidatorMap - suite.App.SuperfluidKeeper.IterateDelegations(suite.Ctx, delAddrs[delidx], func(_ int64, del stakingtypes.DelegationI) bool { - addToSharePerValidatorMap(del.GetValidatorAddr(), del.GetShares()) - return false - }) - - // check if the expected delegated amount equals to actual - for validx := range tc.validatorStats { - suite.Equal(delegatedAmount(delidx, validx).Int64()*10, sharePerValidatorMap[valAddrs[validx].String()].RoundInt().Int64()) - } - } - }) - } -} From 90d6dd132742cd798a2592beff43965fb36eba17 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 15 Jul 2022 11:53:24 -0500 Subject: [PATCH 081/376] Move random genesis to an extension interface (#2081) --- simulation/types/manager.go | 18 ++++++++++++------ x/gamm/module.go | 3 --- x/lockup/module.go | 5 ----- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/simulation/types/manager.go b/simulation/types/manager.go index 063f693b64c..f4eea1d690e 100644 --- a/simulation/types/manager.go +++ b/simulation/types/manager.go @@ -19,15 +19,16 @@ import ( type AppModuleSimulationV2 interface { module.AppModule - // randomized genesis states - // TODO: Come back and improve SimulationState interface - // TODO: Move this to an extension interface - // default: simState.GenState[types.ModuleName] = app.DefaultGenesis(simState.Cdc) - GenerateGenesisState(*module.SimulationState, *SimCtx) Actions() []Action // PropertyTests() } +type AppModuleSimulationV2WithRandGenesis interface { + AppModuleSimulationV2 + // TODO: Come back and improve SimulationState interface + RandomGenesisState(*module.SimulationState, *SimCtx) +} + // SimulationManager defines a simulation manager that provides the high level utility // for managing and executing simulation functionalities for a group of modules type Manager struct { @@ -137,7 +138,12 @@ func (m Manager) Actions(seed int64, cdc codec.JSONCodec) []Action { func (m Manager) GenerateGenesisStates(simState *module.SimulationState, sim *SimCtx) { for _, moduleName := range m.moduleManager.OrderInitGenesis { if simModule, ok := m.Modules[moduleName]; ok { - simModule.GenerateGenesisState(simState, sim) + // if we define a random genesis function use it, otherwise use default genesis + if mod, ok := simModule.(AppModuleSimulationV2WithRandGenesis); ok { + mod.RandomGenesisState(simState, sim) + } else { + simState.GenState[simModule.Name()] = simModule.DefaultGenesis(simState.Cdc) + } } if simModule, ok := m.legacyModules[moduleName]; ok { simModule.GenerateGenesisState(simState) diff --git a/x/gamm/module.go b/x/gamm/module.go index df389ae704e..ce1f7ae38cd 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -158,9 +158,6 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val func (AppModule) ConsensusVersion() uint64 { return 1 } // **** simulation implementation **** -func (am AppModule) GenerateGenesisState(m *module.SimulationState, s *simulation.SimCtx) { - m.GenState[types.ModuleName] = am.DefaultGenesis(m.Cdc) -} func (am AppModule) Actions() []simulation.Action { return []simulation.Action{ diff --git a/x/lockup/module.go b/x/lockup/module.go index 05de92c6caf..f5665e27540 100644 --- a/x/lockup/module.go +++ b/x/lockup/module.go @@ -185,11 +185,6 @@ func (AppModule) ConsensusVersion() uint64 { return 1 } // AppModuleSimulationV2 functions -// GenerateGenesisState creates a randomized GenState of the pool-incentives module. -func (am AppModule) GenerateGenesisState(simState *module.SimulationState, s *simulation.SimCtx) { - simState.GenState[types.ModuleName] = am.DefaultGenesis(simState.Cdc) -} - // WeightedOperations returns the all the lockup module operations with their respective weights. func (am AppModule) Actions() []simulation.Action { return []simulation.Action{ From 53216a4e3d0e2b5eac9f495d7f6e87b178d4b820 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 15 Jul 2022 20:07:48 -0500 Subject: [PATCH 082/376] Simulation executor cleanup (#2082) * Delete legacy param methods/structs & split up more functions into parts * Fix mutability for operation scheduling, mild initialization simplification * Fix bugs (seems like time queue operations never worked, even upstream), workaround for 1 time queue bug * Fix unused lint * Delete the time queue as the legacy implementation was broken. Its not too far off from being workable, but will be easier to rewrite well abstracted, with a clear use case in this repo. * Move cursed initialization logic to its standalone function * Delete sim param argument that didn't make sense * Make simState.SimulateAllBlocks function * Move action result logging to dedicated function, remove some extra code --- simulation/executor/expected_keepers.go | 16 -- simulation/executor/mock_tendermint.go | 42 +++-- simulation/executor/operation.go | 29 +--- simulation/executor/params.go | 63 -------- simulation/executor/params_test.go | 55 ------- simulation/executor/simulate.go | 203 +++++++++++------------- simulation/executor/simulate_dev.go | 60 +++++-- simulation/executor/util.go | 23 --- simulation/types/action.go | 11 +- simulation/types/manager.go | 7 +- tests/simulator/sim_test.go | 9 +- 11 files changed, 180 insertions(+), 338 deletions(-) delete mode 100644 simulation/executor/expected_keepers.go delete mode 100644 simulation/executor/params_test.go diff --git a/simulation/executor/expected_keepers.go b/simulation/executor/expected_keepers.go deleted file mode 100644 index c54831b8a40..00000000000 --- a/simulation/executor/expected_keepers.go +++ /dev/null @@ -1,16 +0,0 @@ -package simulation - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// AccountKeeper defines the expected account keeper used for simulations (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} diff --git a/simulation/executor/mock_tendermint.go b/simulation/executor/mock_tendermint.go index db9f1bfae22..e840c39c1fb 100644 --- a/simulation/executor/mock_tendermint.go +++ b/simulation/executor/mock_tendermint.go @@ -134,11 +134,25 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params, } } + voteInfos := randomVoteInfos(r, params, validators, event) + evidence := randomDoubleSignEvidence(r, params, validators, pastTimes, pastVoteInfos, event, header, voteInfos) + + return abci.RequestBeginBlock{ + Header: header, + LastCommitInfo: abci.LastCommitInfo{ + Votes: voteInfos, + }, + ByzantineValidators: evidence, + } +} + +func randomVoteInfos(r *rand.Rand, simParams Params, validators mockValidators, event func(route, op, evResult string), +) []abci.VoteInfo { voteInfos := make([]abci.VoteInfo, len(validators)) for i, key := range validators.getKeys() { mVal := validators[key] - mVal.livenessState = params.LivenessTransitionMatrix().NextState(r, mVal.livenessState) + mVal.livenessState = simParams.LivenessTransitionMatrix().NextState(r, mVal.livenessState) signed := true if mVal.livenessState == 1 { @@ -171,18 +185,19 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params, } } + return voteInfos +} + +func randomDoubleSignEvidence(r *rand.Rand, params Params, + validators mockValidators, pastTimes []time.Time, + pastVoteInfos [][]abci.VoteInfo, + event func(route, op, evResult string), header tmproto.Header, voteInfos []abci.VoteInfo) []abci.Evidence { + evidence := []abci.Evidence{} // return if no past times if len(pastTimes) == 0 { - return abci.RequestBeginBlock{ - Header: header, - LastCommitInfo: abci.LastCommitInfo{ - Votes: voteInfos, - }, - } + return evidence } - // TODO: Determine capacity before allocation - evidence := make([]abci.Evidence, 0) // TODO: Change this to be markov based & clean this up for r.Float64() < params.EvidenceFraction() { height := header.Height @@ -215,12 +230,5 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params, event("begin_block", "evidence", "ok") } - - return abci.RequestBeginBlock{ - Header: header, - LastCommitInfo: abci.LastCommitInfo{ - Votes: voteInfos, - }, - ByzantineValidators: evidence, - } + return evidence } diff --git a/simulation/executor/operation.go b/simulation/executor/operation.go index 76387ed2b82..fcc3013525a 100644 --- a/simulation/executor/operation.go +++ b/simulation/executor/operation.go @@ -1,14 +1,14 @@ package simulation +// TODO: Figure out how to delete everything in this file OR migrate to improved logging concepts + import ( "encoding/json" "math/rand" - "sort" "github.com/cosmos/cosmos-sdk/types/simulation" simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" - // simtypes "github.com/osmosis-labs/osmosis/simulation/types" ) // entry kinds for use within OperationEntry @@ -77,35 +77,18 @@ func NewOperationQueue() OperationQueue { // queueOperations adds all future operations into the operation queue. // TODO: Change FutureOperation to FutureAction -func queueOperations(queuedOps OperationQueue, queuedTimeOps []simulation.FutureOperation, futureOps []simulation.FutureOperation) { - if futureOps == nil { - return - } - +func (simState *simState) queueOperations(futureOps []simulation.FutureOperation) { for _, futureOp := range futureOps { futureOp := futureOp if futureOp.BlockHeight != 0 { - if val, ok := queuedOps[futureOp.BlockHeight]; ok { - queuedOps[futureOp.BlockHeight] = append(val, futureOp.Op) + if val, ok := simState.operationQueue[futureOp.BlockHeight]; ok { + simState.operationQueue[futureOp.BlockHeight] = append(val, futureOp.Op) } else { - queuedOps[futureOp.BlockHeight] = []simulation.Operation{futureOp.Op} + simState.operationQueue[futureOp.BlockHeight] = []simulation.Operation{futureOp.Op} } continue } - - // TODO: Replace with proper sorted data structure, so don't have the - // copy entire slice - index := sort.Search( - len(queuedTimeOps), - func(i int) bool { - return queuedTimeOps[i].BlockTime.After(futureOp.BlockTime) - }, - ) - - queuedTimeOps = append(queuedTimeOps, simulation.FutureOperation{}) - copy(queuedTimeOps[index+1:], queuedTimeOps[index:]) - queuedTimeOps[index] = futureOp } } diff --git a/simulation/executor/params.go b/simulation/executor/params.go index ccf226334b9..19a21f9fe75 100644 --- a/simulation/executor/params.go +++ b/simulation/executor/params.go @@ -89,69 +89,6 @@ func RandomParams(r *rand.Rand) Params { } } -// Param change proposals - -// ParamChange defines the object used for simulating parameter change proposals -type ParamChange struct { - subspace string - key string - simValue simulation.SimValFn -} - -func (spc ParamChange) Subspace() string { - return spc.subspace -} - -func (spc ParamChange) Key() string { - return spc.key -} - -func (spc ParamChange) SimValue() simulation.SimValFn { - return spc.simValue -} - -// NewSimParamChange creates a new ParamChange instance -func NewSimParamChange(subspace, key string, simVal simulation.SimValFn) simulation.ParamChange { - return ParamChange{ - subspace: subspace, - key: key, - simValue: simVal, - } -} - -// ComposedKey creates a new composed key for the param change proposal -func (spc ParamChange) ComposedKey() string { - return spc.Subspace() + "/" + spc.Key() -} - -// Proposal Contents - -// WeightedProposalContent defines a common struct for proposal contents defined by -// external modules (i.e outside gov) -type WeightedProposalContent struct { - appParamsKey string // key used to retrieve the value of the weight from the simulation application params - defaultWeight int // default weight - contentSimulatorFn simulation.ContentSimulatorFn // content simulator function -} - -func NewWeightedProposalContent(appParamsKey string, defaultWeight int, contentSimulatorFn simulation.ContentSimulatorFn) simulation.WeightedProposalContent { - return &WeightedProposalContent{appParamsKey: appParamsKey, defaultWeight: defaultWeight, contentSimulatorFn: contentSimulatorFn} -} - -func (w WeightedProposalContent) AppParamsKey() string { - return w.appParamsKey -} - -func (w WeightedProposalContent) DefaultWeight() int { - return w.defaultWeight -} - -func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { - return w.contentSimulatorFn -} - -// Param change proposals - // randomConsensusParams returns random simulation consensus parameters, it extracts the Evidence from the Staking genesis state. func randomConsensusParams(r *rand.Rand, appState json.RawMessage, cdc codec.JSONCodec) *abci.ConsensusParams { var genesisState map[string]json.RawMessage diff --git a/simulation/executor/params_test.go b/simulation/executor/params_test.go deleted file mode 100644 index 88cc5d564c4..00000000000 --- a/simulation/executor/params_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package simulation - -import ( - "fmt" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" -) - -func TestParamChange(t *testing.T) { - subspace, key := "theSubspace", "key" - f := func(r *rand.Rand) string { - return "theResult" - } - - pChange := NewSimParamChange(subspace, key, f) - - require.Equal(t, subspace, pChange.Subspace()) - require.Equal(t, key, pChange.Key()) - require.Equal(t, f(nil), pChange.SimValue()(nil)) - require.Equal(t, fmt.Sprintf("%s/%s", subspace, key), pChange.ComposedKey()) -} - -func TestNewWeightedProposalContent(t *testing.T) { - key := "theKey" - weight := 1 - content := &testContent{} - f := func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { - return content - } - - pContent := NewWeightedProposalContent(key, weight, f) - - require.Equal(t, key, pContent.AppParamsKey()) - require.Equal(t, weight, pContent.DefaultWeight()) - - ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil) - require.Equal(t, content, pContent.ContentSimulatorFn()(nil, ctx, nil)) -} - -type testContent struct{} - -func (t testContent) GetTitle() string { return "" } -func (t testContent) GetDescription() string { return "" } -func (t testContent) GetIsExpedited() bool { return false } -func (t testContent) SetIsExpedited(isExpedited bool) {} -func (t testContent) ProposalRoute() string { return "" } -func (t testContent) ProposalType() string { return "" } -func (t testContent) ValidateBasic() error { return nil } -func (t testContent) String() string { return "" } diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index 5cda014a20f..ebaa1eabfc2 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -31,11 +31,11 @@ func initChain( accounts []simulation.Account, app simtypes.App, appStateFn simulation.AppStateFn, - config simulation.Config, + config *simulation.Config, cdc codec.JSONCodec, -) (mockValidators, time.Time, []simulation.Account, string) { +) (mockValidators, time.Time, []simulation.Account) { // TODO: Cleanup the whole config dependency with appStateFn - appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) + appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, *config) consensusParams := randomConsensusParams(r, appState, cdc) req := abci.RequestInitChain{ AppStateBytes: appState, @@ -48,7 +48,13 @@ func initChain( res := app.GetBaseApp().InitChain(req) validators := newMockValidators(r, res.Validators, params) - return validators, genesisTimestamp, accounts, chainID + // update config + config.ChainID = chainID + if config.InitialBlockHeight == 0 { + config.InitialBlockHeight = 1 + } + + return validators, genesisTimestamp, accounts } // SimulateFromSeedLegacy tests an application by running the provided @@ -79,6 +85,8 @@ func initChain( // * SimManager for module configs // * Config file for params // * whatever is needed for logging (tb + w rn) +// OR: Could be a struct or something with options, +// to give caller ability to step through / instrument benchmarking if they wanted to, and add a cleanup function. func SimulateFromSeed( tb testing.TB, w io.Writer, @@ -87,43 +95,16 @@ func SimulateFromSeed( actions []simtypes.Action, config simulation.Config, cdc codec.JSONCodec, -) (stopEarly bool, exportedParams Params, err error) { +) (stopEarly bool, err error) { // in case we have to end early, don't os.Exit so that we can run cleanup code. - testingMode, _, b := getTestingMode(tb) - - fmt.Fprintf(w, "Starting SimulateFromSeed with randomness created with seed %d\n", int(config.Seed)) - r := rand.New(rand.NewSource(config.Seed)) - simParams := RandomParams(r) - fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(simParams)) - - accs := initFunctions.RandomAccountFn(r, simParams.NumKeys()) - if len(accs) == 0 { - return true, simParams, fmt.Errorf("must have greater than zero genesis accounts") - } - - validators, genesisTimestamp, accs, chainID := initChain(r, simParams, accs, app, initFunctions.AppInitialStateFn, config, cdc) - - config.ChainID = chainID - if config.InitialBlockHeight == 0 { - config.InitialBlockHeight = 1 - } - - fmt.Printf( - "Starting the simulation from time %v (unixtime %v)\n", - genesisTimestamp.UTC().Format(time.UnixDate), genesisTimestamp.Unix(), - ) + // TODO: Understand exit pattern, this is so screwed up. Then delete ^ - initialHeader := tmproto.Header{ - ChainID: chainID, - Height: int64(config.InitialBlockHeight), - Time: genesisTimestamp, - ProposerAddress: validators.randomProposer(r), + // Encapsulate the bizarre initialization logic that must be cleaned. + simCtx, simState, simParams, err := cursedInitializationLogic(tb, w, app, initFunctions, &config, cdc) + if err != nil { + return true, err } - simState := newSimulatorState(simParams, initialHeader, tb, w, validators).WithLogParam(config.Lean) - - simCtx := simtypes.NewSimCtx(r, app, accs, simState.header.ChainID) - // Setup code to catch SIGTERM's c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) @@ -135,6 +116,7 @@ func SimulateFromSeed( stopEarly = true }() + testingMode, _, b := getTestingMode(tb) blockSimulator := createBlockSimulator(testingMode, w, simParams, actions, simState, config) if !testingMode { @@ -152,33 +134,56 @@ func SimulateFromSeed( }() } - // set exported params to the initial state - if config.ExportParamsPath != "" && config.ExportParamsHeight == 0 { - exportedParams = simParams - } + stopEarly = simState.SimulateAllBlocks(w, simCtx, blockSimulator, config) - for height := config.InitialBlockHeight; height < config.NumBlocks+config.InitialBlockHeight && !stopEarly; height++ { - stopEarly = simState.SimulateBlock(simCtx, blockSimulator) - if stopEarly { - break - } + simState.eventStats.exportEvents(config.ExportStatsPath, w) + return stopEarly, nil +} - if config.Commit { - simCtx.App.GetBaseApp().Commit() - } +// The goal of this function is to group the extremely badly abstracted genesis logic, +// into a single function we can target continuing to improve / abstract better. +// It outputs SimCtx and SimState which are "cleaner" interface abstractions for the rest of the simulator. +// It also outputs SimParams which is not great. +// It also can modify config. +func cursedInitializationLogic( + tb testing.TB, + w io.Writer, + app simtypes.App, + initFunctions simtypes.InitFunctions, + config *simulation.Config, + cdc codec.JSONCodec) (*simtypes.SimCtx, *simState, Params, error) { + fmt.Fprintf(w, "Starting SimulateFromSeed with randomness created with seed %d\n", int(config.Seed)) + + r := rand.New(rand.NewSource(config.Seed)) + simParams := RandomParams(r) + fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(simParams)) + + accs := initFunctions.RandomAccountFn(r, simParams.NumKeys()) + if len(accs) == 0 { + return nil, nil, simParams, fmt.Errorf("must have greater than zero genesis accounts") } - if !stopEarly { - fmt.Fprintf( - w, - "\nSimulation complete; Final height (blocks): %d, final time (seconds): %v, operations ran: %d\n", - simState.header.Height, simState.header.Time, simState.opCount, - ) - simState.logWriter.PrintLogs() + validators, genesisTimestamp, accs := initChain(r, simParams, accs, app, initFunctions.AppInitialStateFn, config, cdc) + + fmt.Printf( + "Starting the simulation from time %v (unixtime %v)\n", + genesisTimestamp.UTC().Format(time.UnixDate), genesisTimestamp.Unix(), + ) + + simCtx := simtypes.NewSimCtx(r, app, accs, config.ChainID) + + initialHeader := tmproto.Header{ + ChainID: config.ChainID, + Height: int64(config.InitialBlockHeight), + Time: genesisTimestamp, + ProposerAddress: validators.randomProposer(r), } - simState.eventStats.exportEvents(config.ExportStatsPath, w) - return stopEarly, exportedParams, nil + simState := newSimulatorState(simParams, initialHeader, tb, w, validators).WithLogParam(config.Lean) + + // TODO: If simulation has a param export path configured, export params here. + + return simCtx, simState, simParams, nil } //nolint:deadcode,unused @@ -215,8 +220,8 @@ func createBlockSimulator(testingMode bool, w io.Writer, params Params, actions simCtx *simtypes.SimCtx, ctx sdk.Context, header tmproto.Header, ) (opCount int) { _, _ = fmt.Fprintf( - w, "\rSimulating... block %d/%d, operation %d/%d.", - header.Height, config.NumBlocks, opCount, blocksize, + w, "\rSimulating... block %d/%d, operation 0/%d.", + header.Height, config.NumBlocks, blocksize, ) lastBlockSizeState, blocksize = getBlockSize(simCtx, params, lastBlockSizeState, config.BlockSize) @@ -234,31 +239,35 @@ func createBlockSimulator(testingMode bool, w io.Writer, params Params, actions // TODO: We need to make a simCtx.WithSeededRand, that replaces the rand map internally // but allows updates to accounts. opMsg, futureOps, err := action.Execute(simCtx, ctx) - opMsg.LogEvent(simState.eventStats.Tally) - - if !simState.leanLogs || opMsg.OK { - simState.logWriter.AddEntry(MsgEntry(header.Height, int64(i), opMsg)) - } + simState.logActionResult(header, i, config, blocksize, opMsg, err) - if err != nil { - simState.logWriter.PrintLogs() - simState.tb.Fatalf(`error on block %d/%d, operation (%d/%d) from x/%s: -%v -Comment: %s`, - header.Height, config.NumBlocks, opCount, blocksize, opMsg.Route, err, opMsg.Comment) - } + simState.queueOperations(futureOps) - queueOperations(simState.operationQueue, simState.timeOperationQueue, futureOps) - - if testingMode && opCount%50 == 0 { + if testingMode && i%50 == 0 { fmt.Fprintf(w, "\rSimulating... block %d/%d, operation %d/%d. ", - header.Height, config.NumBlocks, opCount, blocksize) + header.Height, config.NumBlocks, i, blocksize) } - - opCount++ } - return opCount + return blocksize + } +} + +// This is inheriting old functionality. We should break this as part of making logging be usable / make sense. +func (simState *simState) logActionResult( + header tmproto.Header, actionIndex int, config simulation.Config, blocksize int, + opMsg simulation.OperationMsg, actionErr error) { + opMsg.LogEvent(simState.eventStats.Tally) + if !simState.leanLogs || opMsg.OK { + simState.logWriter.AddEntry(MsgEntry(header.Height, int64(actionIndex), opMsg)) + } + + if actionErr != nil { + simState.logWriter.PrintLogs() + simState.tb.Fatalf(`error on block %d/%d, operation (%d/%d) from x/%s: +%v +Comment: %s`, + header.Height, config.NumBlocks, actionIndex, blocksize, opMsg.Route, actionErr, opMsg.Comment) } } @@ -287,6 +296,10 @@ func (simState *simState) runQueuedOperations(simCtx *simtypes.SimCtx, ctx sdk.C if err != nil { simState.logWriter.PrintLogs() + simState.tb.Fatalf(`error on block %d, height queued operation (%d/%d) from x/%s: +%v +Comment: %s`, + simState.header.Height, i, numOpsRan, opMsg.Route, err, opMsg.Comment) simState.tb.FailNow() } } @@ -294,35 +307,3 @@ func (simState *simState) runQueuedOperations(simCtx *simtypes.SimCtx, ctx sdk.C return numOpsRan } - -func (simState *simState) runQueuedTimeOperations(simCtx *simtypes.SimCtx, ctx sdk.Context) ( - numOpsRan int, -) { - queueOps := simState.timeOperationQueue - currentTime := simState.header.Time - numOpsRan = 0 - for len(queueOps) > 0 && currentTime.After(queueOps[0].BlockTime) { - // TODO: Fix according to the r plans - r := simCtx.GetRand() - - // For now, queued operations cannot queue more operations. - // If a need arises for us to support queued messages to queue more messages, this can - // be changed. - opMsg, _, err := queueOps[0].Op(r, simCtx.App.GetBaseApp(), ctx, simCtx.Accounts, simCtx.ChainID) - opMsg.LogEvent(simState.eventStats.Tally) - - if !simState.leanLogs || opMsg.OK { - simState.logWriter.AddEntry(QueuedMsgEntry(simState.header.Height, opMsg)) - } - - if err != nil { - simState.logWriter.PrintLogs() - simState.tb.FailNow() - } - - queueOps = queueOps[1:] - numOpsRan++ - } - simState.timeOperationQueue = queueOps - return numOpsRan -} diff --git a/simulation/executor/simulate_dev.go b/simulation/executor/simulate_dev.go index 8f14b7da083..243e2a269dd 100644 --- a/simulation/executor/simulate_dev.go +++ b/simulation/executor/simulate_dev.go @@ -20,8 +20,7 @@ type simState struct { // These are operations which have been queued by previous operations // TODO: Replace with new action syntax - operationQueue map[int][]simulation.Operation - timeOperationQueue []simulation.FutureOperation + operationQueue map[int][]simulation.Operation curValidators mockValidators nextValidators mockValidators @@ -49,19 +48,18 @@ type simState struct { func newSimulatorState(simParams Params, initialHeader tmproto.Header, tb testing.TB, w io.Writer, validators mockValidators) *simState { return &simState{ - simParams: simParams, - header: initialHeader, - operationQueue: NewOperationQueue(), - timeOperationQueue: []simulation.FutureOperation{}, - curValidators: validators.Clone(), - nextValidators: validators.Clone(), - tb: tb, - pastTimes: []time.Time{}, - pastVoteInfos: [][]abci.VoteInfo{}, - logWriter: NewLogWriter(tb), - w: w, - eventStats: NewEventStats(), - opCount: 0, + simParams: simParams, + header: initialHeader, + operationQueue: NewOperationQueue(), + curValidators: validators.Clone(), + nextValidators: validators.Clone(), + tb: tb, + pastTimes: []time.Time{}, + pastVoteInfos: [][]abci.VoteInfo{}, + logWriter: NewLogWriter(tb), + w: w, + eventStats: NewEventStats(), + opCount: 0, } } @@ -70,6 +68,34 @@ func (simState *simState) WithLogParam(leanLogs bool) *simState { return simState } +func (simState *simState) SimulateAllBlocks( + w io.Writer, + simCtx *simtypes.SimCtx, + blockSimulator blockSimFn, + config simulation.Config) (stopEarly bool) { + stopEarly = false + for height := config.InitialBlockHeight; height < config.NumBlocks+config.InitialBlockHeight && !stopEarly; height++ { + stopEarly = simState.SimulateBlock(simCtx, blockSimulator) + if stopEarly { + break + } + + if config.Commit { + simCtx.App.GetBaseApp().Commit() + } + } + + if !stopEarly { + fmt.Fprintf( + w, + "\nSimulation complete; Final height (blocks): %d, final time (seconds): %v, operations ran: %d\n", + simState.header.Height, simState.header.Time, simState.opCount, + ) + simState.logWriter.PrintLogs() + } + return stopEarly +} + // simulate a block, update state func (simState *simState) SimulateBlock(simCtx *simtypes.SimCtx, blockSimulator blockSimFn) (stopEarly bool) { if simState.header.ProposerAddress == nil { @@ -82,12 +108,12 @@ func (simState *simState) SimulateBlock(simCtx *simtypes.SimCtx, blockSimulator // Run queued operations. Ignores blocksize if blocksize is too small numQueuedOpsRan := simState.runQueuedOperations(simCtx, ctx) - numQueuedTimeOpsRan := simState.runQueuedTimeOperations(simCtx, ctx) + // numQueuedTimeOpsRan := simState.runQueuedTimeOperations(simCtx, ctx) // run standard operations // TODO: rename blockSimulator arg operations := blockSimulator(simCtx, ctx, simState.header) - simState.opCount += operations + numQueuedOpsRan + numQueuedTimeOpsRan + simState.opCount += operations + numQueuedOpsRan // + numQueuedTimeOpsRan responseEndBlock := simState.endBlock(simCtx) diff --git a/simulation/executor/util.go b/simulation/executor/util.go index e21849d4d5d..f15a9b5aaf8 100644 --- a/simulation/executor/util.go +++ b/simulation/executor/util.go @@ -3,15 +3,8 @@ package simulation import ( "encoding/json" "fmt" - "math/rand" "testing" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - simulation "github.com/cosmos/cosmos-sdk/types/simulation" - simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" ) @@ -63,19 +56,3 @@ func mustMarshalJSONIndent(o interface{}) []byte { return bz } - -// OperationInput is a struct that holds all the needed values to generate a tx and deliver it -type OperationInput struct { - R *rand.Rand - App *baseapp.BaseApp - TxGen client.TxConfig - Cdc *codec.ProtoCodec - Msg sdk.Msg - MsgType string - CoinsSpentInMsg sdk.Coins - Context sdk.Context - SimAccount simulation.Account - AccountKeeper AccountKeeper - Bankkeeper BankKeeper - ModuleName string -} diff --git a/simulation/types/action.go b/simulation/types/action.go index 4cdfa130b30..bae758e347b 100644 --- a/simulation/types/action.go +++ b/simulation/types/action.go @@ -28,10 +28,11 @@ type Action interface { } type weightedOperationAction struct { - op simulation.WeightedOperation + moduleName string + op simulation.WeightedOperation } -func (a weightedOperationAction) Name() string { return "weighted_op" } +func (a weightedOperationAction) Name() string { return fmt.Sprintf("%s: weighted_op", a.moduleName) } func (a weightedOperationAction) Weight() Weight { return Weight(a.op.Weight()) } func (a weightedOperationAction) Execute(sim *SimCtx, ctx sdk.Context) ( simulation.OperationMsg, []simulation.FutureOperation, error, @@ -40,9 +41,13 @@ func (a weightedOperationAction) Execute(sim *SimCtx, ctx sdk.Context) ( } func ActionsFromWeightedOperations(ops legacysimexec.WeightedOperations) []Action { + return actionsFromWeightedOperations("no module name", ops) +} + +func actionsFromWeightedOperations(moduleName string, ops legacysimexec.WeightedOperations) []Action { actions := make([]Action, 0, len(ops)) for _, op := range ops { - actions = append(actions, weightedOperationAction{op: op}) + actions = append(actions, weightedOperationAction{moduleName: moduleName, op: op}) } return actions } diff --git a/simulation/types/manager.go b/simulation/types/manager.go index f4eea1d690e..335490fc5fa 100644 --- a/simulation/types/manager.go +++ b/simulation/types/manager.go @@ -101,13 +101,14 @@ func (m Manager) legacyActions(seed int64, cdc codec.JSONCodec) []Action { } } // second pass generate actions - weightedOps := []simulation.WeightedOperation{} + actions := []Action{} for _, moduleName := range m.moduleManager.OrderInitGenesis { if simModule, ok := m.legacyModules[moduleName]; ok { - weightedOps = append(weightedOps, simModule.WeightedOperations(simState)...) + weightedOps := simModule.WeightedOperations(simState) + actions = append(actions, actionsFromWeightedOperations(moduleName, weightedOps)...) } } - return ActionsFromWeightedOperations(weightedOps) + return actions } // TODO: Can we use sim here instead? Perhaps by passing in the simulation module manager to the simulator. diff --git a/tests/simulator/sim_test.go b/tests/simulator/sim_test.go index 195e3455b38..af74440d808 100644 --- a/tests/simulator/sim_test.go +++ b/tests/simulator/sim_test.go @@ -95,7 +95,7 @@ func fullAppSimulation(tb testing.TB, is_testing bool) { } // Run randomized simulation: - _, simParams, simErr := osmosim.SimulateFromSeed( + _, simErr := osmosim.SimulateFromSeed( tb, os.Stdout, osmosis, @@ -104,11 +104,6 @@ func fullAppSimulation(tb testing.TB, is_testing bool) { config, osmosis.AppCodec(), ) - simParams = simParams - // export state and simParams before the simulation error is checked - // if err = sdkSimapp.CheckExportSimulation(osmosis, config, simParams); err != nil { - // tb.Fatal(err) - // } if simErr != nil { tb.Fatal(simErr) @@ -186,7 +181,7 @@ func TestAppStateDeterminism(t *testing.T) { } // Run randomized simulation: - _, _, simErr := osmosim.SimulateFromSeed( + _, simErr := osmosim.SimulateFromSeed( t, os.Stdout, osmosis, From 55e74441c711cb9461a4a2c90a389bb988e25831 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 15 Jul 2022 20:14:09 -0500 Subject: [PATCH 083/376] Rand isolation (#2090) * Add rand isolation logic & rand manager struct * Move App & ChainID to private on SimCtx * Add GetRand test * Make SeededRand same seed test * Add wrap rand usage in simulation --- simulation/executor/simulate.go | 26 ++--- simulation/executor/simulate_dev.go | 8 +- simulation/types/account.go | 8 +- simulation/types/action.go | 2 +- simulation/types/randmanager_test.go | 87 ++++++++++++++++ simulation/types/simctx.go | 148 +++++++++++++++++++++++---- simulation/types/txbuilder.go | 4 +- 7 files changed, 238 insertions(+), 45 deletions(-) create mode 100644 simulation/types/randmanager_test.go diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index ebaa1eabfc2..527d87909ff 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -225,20 +225,20 @@ func createBlockSimulator(testingMode bool, w io.Writer, params Params, actions ) lastBlockSizeState, blocksize = getBlockSize(simCtx, params, lastBlockSizeState, config.BlockSize) - // TODO: Fix according to the r plans - // Predetermine the blocksize slice so that we can do things like block - // out certain operations without changing the ops that follow. - // NOTE: This is poor mans seeding, it will improve in our simctx plans =) - blockActions := make([]simtypes.Action, 0, blocksize) + blockNumStr := fmt.Sprintf("block %d", header.Height) for i := 0; i < blocksize; i++ { - blockActions = append(blockActions, selectAction(simCtx.GetRand())) - } + // Sample and execute every action using independent randomness. + // Thus any change within one action's randomness won't waterfall + // to every other action and the overall order of txs. + // We can also use this to limit which operations we run, in debugging a simulator run. + actionSeed := fmt.Sprintf("%s operation %d", blockNumStr, i) + actionSimCtx, cleanup := simCtx.WrapRand(actionSeed) + + // Select and execute tx + action := selectAction(actionSimCtx.GetSeededRand("action select")) + opMsg, futureOps, err := action.Execute(actionSimCtx, ctx) + cleanup() - for i := 0; i < blocksize; i++ { - action := blockActions[i] - // TODO: We need to make a simCtx.WithSeededRand, that replaces the rand map internally - // but allows updates to accounts. - opMsg, futureOps, err := action.Execute(simCtx, ctx) simState.logActionResult(header, i, config, blocksize, opMsg, err) simState.queueOperations(futureOps) @@ -287,7 +287,7 @@ func (simState *simState) runQueuedOperations(simCtx *simtypes.SimCtx, ctx sdk.C // For now, queued operations cannot queue more operations. // If a need arises for us to support queued messages to queue more messages, this can // be changed. - opMsg, _, err := queuedOp[i](r, simCtx.App.GetBaseApp(), ctx, simCtx.Accounts, simCtx.ChainID) + opMsg, _, err := queuedOp[i](r, simCtx.BaseApp(), ctx, simCtx.Accounts, simCtx.ChainID()) opMsg.LogEvent(simState.eventStats.Tally) if !simState.leanLogs || opMsg.OK { diff --git a/simulation/executor/simulate_dev.go b/simulation/executor/simulate_dev.go index 243e2a269dd..20ab9bf4d8a 100644 --- a/simulation/executor/simulate_dev.go +++ b/simulation/executor/simulate_dev.go @@ -81,7 +81,7 @@ func (simState *simState) SimulateAllBlocks( } if config.Commit { - simCtx.App.GetBaseApp().Commit() + simCtx.BaseApp().Commit() } } @@ -104,7 +104,7 @@ func (simState *simState) SimulateBlock(simCtx *simtypes.SimCtx, blockSimulator } requestBeginBlock := simState.beginBlock(simCtx) - ctx := simCtx.App.GetBaseApp().NewContext(false, simState.header) + ctx := simCtx.BaseApp().NewContext(false, simState.header) // Run queued operations. Ignores blocksize if blocksize is too small numQueuedOpsRan := simState.runQueuedOperations(simCtx, ctx) @@ -127,12 +127,12 @@ func (simState *simState) beginBlock(simCtx *simtypes.SimCtx) abci.RequestBeginB requestBeginBlock := RandomRequestBeginBlock(simCtx.GetRand(), simState.simParams, simState.curValidators, simState.pastTimes, simState.pastVoteInfos, simState.eventStats.Tally, simState.header) // Run the BeginBlock handler simState.logWriter.AddEntry(BeginBlockEntry(simState.header.Height)) - simCtx.App.GetBaseApp().BeginBlock(requestBeginBlock) + simCtx.BaseApp().BeginBlock(requestBeginBlock) return requestBeginBlock } func (simState *simState) endBlock(simCtx *simtypes.SimCtx) abci.ResponseEndBlock { - res := simCtx.App.GetBaseApp().EndBlock(abci.RequestEndBlock{}) + res := simCtx.BaseApp().EndBlock(abci.RequestEndBlock{}) simState.logWriter.AddEntry(EndBlockEntry(simState.header.Height)) return res } diff --git a/simulation/types/account.go b/simulation/types/account.go index dcde70d0842..670c345f12f 100644 --- a/simulation/types/account.go +++ b/simulation/types/account.go @@ -65,7 +65,7 @@ func (sim *SimCtx) FindAccount(address sdk.Address) (simulation.Account, bool) { func (sim *SimCtx) RandomSimAccountWithBalance(ctx sdk.Context) (simulation.Account, error) { accHasBal := func(acc simulation.Account) bool { - return len(sim.App.GetBankKeeper().SpendableCoins(ctx, acc.Address)) != 0 + return len(sim.BankKeeper().SpendableCoins(ctx, acc.Address)) != 0 } acc, found := sim.RandomSimAccountWithConstraint(accHasBal) if !found { @@ -80,7 +80,7 @@ func (sim *SimCtx) RandomSimAccountWithBalance(ctx sdk.Context) (simulation.Acco func (sim *SimCtx) SelAddrWithDenoms(ctx sdk.Context, denoms []string) (simulation.Account, sdk.Coins, bool) { accHasDenoms := func(acc simulation.Account) bool { for _, denom := range denoms { - if sim.App.GetBankKeeper().GetBalance(ctx, acc.Address, denom).Amount.IsZero() { + if sim.BankKeeper().GetBalance(ctx, acc.Address, denom).Amount.IsZero() { return false } } @@ -100,7 +100,7 @@ func (sim *SimCtx) SelAddrWithDenoms(ctx sdk.Context, denoms []string) (simulati // (Meaning that on average it samples 10% of the chosen balance) // Pre-condition: Addr must have a spendable balance func (sim *SimCtx) RandExponentialCoin(ctx sdk.Context, addr sdk.AccAddress) sdk.Coin { - balances := sim.App.GetBankKeeper().SpendableCoins(ctx, addr) + balances := sim.BankKeeper().SpendableCoins(ctx, addr) if len(balances) == 0 { panic("precondition for RandExponentialCoin broken: Addr has 0 spendable balance") } @@ -124,7 +124,7 @@ func (sim *SimCtx) RandExponentialCoin(ctx sdk.Context, addr sdk.AccAddress) sdk func (sim *SimCtx) RandCoinSubset(ctx sdk.Context, addr sdk.AccAddress, denoms []string) sdk.Coins { subsetCoins := sdk.Coins{} for _, denom := range denoms { - bal := sim.App.GetBankKeeper().GetBalance(ctx, addr, denom) + bal := sim.BankKeeper().GetBalance(ctx, addr, denom) amt, err := sim.RandPositiveInt(bal.Amount) if err != nil { panic(err) diff --git a/simulation/types/action.go b/simulation/types/action.go index bae758e347b..0d1830556f6 100644 --- a/simulation/types/action.go +++ b/simulation/types/action.go @@ -37,7 +37,7 @@ func (a weightedOperationAction) Weight() Weight { return Weight(a.op.Weight()) func (a weightedOperationAction) Execute(sim *SimCtx, ctx sdk.Context) ( simulation.OperationMsg, []simulation.FutureOperation, error, ) { - return a.op.Op()(sim.GetRand(), sim.App.GetBaseApp(), ctx, sim.Accounts, sim.ChainID) + return a.op.Op()(sim.GetRand(), sim.BaseApp(), ctx, sim.Accounts, sim.ChainID()) } func ActionsFromWeightedOperations(ops legacysimexec.WeightedOperations) []Action { diff --git a/simulation/types/randmanager_test.go b/simulation/types/randmanager_test.go new file mode 100644 index 00000000000..4e7fa116d47 --- /dev/null +++ b/simulation/types/randmanager_test.go @@ -0,0 +1,87 @@ +package simulation + +import ( + "math/rand" + "testing" + + "github.com/stretchr/testify/require" +) + +var defaultSeed = int64(10) + +func getDefaultRandInstance() *rand.Rand { + return rand.New(rand.NewSource(defaultSeed)) +} + +func getKDefaultRandManager(k int) []randManager { + rms := make([]randManager, k) + for i := 0; i < k; i++ { + rms[i] = newRandManager(getDefaultRandInstance()) + } + return rms +} + +func randInstancesEqual(rands []*rand.Rand) bool { + value := rands[0].Int() + for i := 1; i < len(rands); i++ { + if rands[i].Int() != value { + return false + } + } + return true +} + +// Test that the rand manager GetRand() are all independent of one another. +func TestRandManagerGetRandIndependence(t *testing.T) { + rms := getKDefaultRandManager(3) + expectedEqualRands := []*rand.Rand{} + // We want to test that in each of the the following three scenarios, r2 is equal: + // 1) r1 := rm.GetRand(); r2 := rm.GetRand(); + // 2) r1 := rm.GetRand(); r2 := rm.GetRand(); _ = r1.Int() + // 3) r1 := rm.GetRand(); r1.Int(); r2 := rm.GetRand(); + scenario1RM := rms[0] + scenario1RM.GetRand() + r2 := scenario1RM.GetRand() + expectedEqualRands = append(expectedEqualRands, r2) + + scenario2RM := rms[1] + r1 := scenario2RM.GetRand() + r2 = scenario2RM.GetRand() + r1.Int() + expectedEqualRands = append(expectedEqualRands, r2) + + scenario3RM := rms[2] + r1 = scenario3RM.GetRand() + r1.Int() + r2 = scenario3RM.GetRand() + expectedEqualRands = append(expectedEqualRands, r2) + require.True(t, randInstancesEqual(expectedEqualRands)) +} + +// Test that the rand manager GetSeededRand() for the same seed are all returning the same rand instance. +func TestRandManagerSameSeedGetSeededRand(t *testing.T) { + rms := getKDefaultRandManager(3) + seed := "test seed" + // We want to test that in each of the the following three scenarios, we generated the same 'trace' of values. + // 1) r1 := rm.GetSeededRand(seed); r1.Int(); r2 := rm.GetSeededRand(seed); r2.Int(); + // 2) r1 := rm.GetSeededRand(seed); r2 := rm.GetSeededRand(seed); r1.Int(); r2.Int(); + // 3) r1 := rm.GetSeededRand(seed); r2 := rm.GetSeededRand(seed); r2.Int(); r1.Int(); + scenario1RM := rms[0] + r1 := scenario1RM.GetSeededRand(seed) + v1 := r1.Int() + r2 := scenario1RM.GetSeededRand(seed) + scenario1Trace := []int{v1, r2.Int()} + + scenario2RM := rms[1] + r1 = scenario2RM.GetSeededRand(seed) + r2 = scenario2RM.GetSeededRand(seed) + scenario2Trace := []int{r1.Int(), r2.Int()} + + scenario3RM := rms[2] + r1 = scenario3RM.GetSeededRand(seed) + r2 = scenario3RM.GetSeededRand(seed) + scenario3Trace := []int{r2.Int(), r1.Int()} + + require.Equal(t, scenario1Trace, scenario2Trace) + require.Equal(t, scenario1Trace, scenario3Trace) +} diff --git a/simulation/types/simctx.go b/simulation/types/simctx.go index b7826787777..fb3b8c1ee4c 100644 --- a/simulation/types/simctx.go +++ b/simulation/types/simctx.go @@ -1,8 +1,12 @@ package simulation import ( + "crypto/sha256" + "encoding/binary" + "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/codec" @@ -12,44 +16,146 @@ import ( //nolint:structcheck //TODO: Contemplate name better type SimCtx struct { - r *rand.Rand - // TODO: delete this, once we cleanup simulator initialization logic, - // and can then setup SimCtx with base seed. - internalSeed int64 - rCounter int64 - seededMap map[string]*rand.Rand + rm randManager - App App Accounts []simulation.Account Cdc codec.JSONCodec // application codec - ChainID string + + app App + chainID string txbuilder func(ctx sdk.Context, msg sdk.Msg, msgName string) (sdk.Tx, error) } func NewSimCtx(r *rand.Rand, app App, accounts []simulation.Account, chainID string) *SimCtx { sim := &SimCtx{ - r: r, - internalSeed: r.Int63(), - rCounter: 0, - seededMap: map[string]*rand.Rand{}, - - App: app, + rm: newRandManager(r), + app: app, Accounts: accounts, - ChainID: chainID, + chainID: chainID, } sim.txbuilder = sim.defaultTxBuilder return sim } +// TODO: Consider rename to Rand() func (sim *SimCtx) GetRand() *rand.Rand { - sim.rCounter += 1 - r := rand.New(rand.NewSource(sim.internalSeed + sim.rCounter)) - return r + return sim.rm.GetRand() } -// TODO: Refactor to eventually seed a new prng from seed -// and maintain a cache of seed -> rand +// TODO: Consider rename to SeededRand() +// or DomainSeparatedRand func (sim *SimCtx) GetSeededRand(seed string) *rand.Rand { - return sim.r + return sim.rm.GetSeededRand(seed) +} + +// WrapRand returns a new sim object and a cleanup function to write +// Accounts changes to the parent (and invalidate the prior) +func (sim *SimCtx) WrapRand(domainSeparator string) (wrappedSim *SimCtx, cleanup func()) { + wrappedSim = &SimCtx{ + rm: sim.rm.WrapRand(domainSeparator), + app: sim.app, + Accounts: sim.Accounts, + Cdc: sim.Cdc, + chainID: sim.chainID, + txbuilder: sim.txbuilder, + } + cleanup = func() { + sim.Accounts = wrappedSim.Accounts + wrappedSim.Accounts = nil + } + return wrappedSim, cleanup +} + +func (sim SimCtx) ChainID() string { + return sim.chainID +} + +func (sim SimCtx) BaseApp() *baseapp.BaseApp { + return sim.app.GetBaseApp() +} + +func (sim SimCtx) AppCodec() codec.Codec { + return sim.app.AppCodec() +} + +func (sim SimCtx) AccountKeeper() AccountKeeper { + return sim.app.GetAccountKeeper() +} + +func (sim SimCtx) BankKeeper() BankKeeper { + return sim.app.GetBankKeeper() +} + +// randManager is built to give API's for randomness access +// which allow the caller to avoid "butterfly effects". +// e.g. in the Simulator, I don't want adding one new rand call to a message +// to create an entirely new "run" shape. +type randManager struct { + // TODO: delete this, once we cleanup simulator initialization logic, + // and can then setup SimCtx with base seed. + internalSeed int64 + rCounter int64 + seededMap map[string]*rand.Rand + + // if debug = true, we maintain a list of "seen" calls to Wrap, + // to ensure no duplicates ever get made. + // TODO: Find a way to expose this to executor. + // Perhaps we move this to an internal package? + debug bool + seenWraps map[string]bool +} + +// TODO: Refactor to take in seed as API's improve +func newRandManager(r *rand.Rand) randManager { + return randManager{ + internalSeed: r.Int63(), + rCounter: 0, + seededMap: map[string]*rand.Rand{}, + debug: false, + seenWraps: map[string]bool{}, + } +} + +func stringToSeed(s string) int64 { + // take first 8 bytes of the sha256 hash of s. + // We use this for seeding our rand instances. + // We use a hash just for convenience, we don't need cryptographic collision resistance, + // just simple collisions being unlikely. + bz := sha256.Sum256([]byte(s)) + seedInt := binary.BigEndian.Uint64(bz[:8]) + return int64(seedInt) +} + +func (rm *randManager) WrapRand(domainSeparator string) randManager { + if rm.debug { + if _, found := rm.seenWraps[domainSeparator]; found { + panic(fmt.Sprintf("domain separator %s reused!", domainSeparator)) + } + rm.seenWraps[domainSeparator] = true + } + + sepInt := stringToSeed(domainSeparator) + newSeed := rm.internalSeed + sepInt + r := rand.New(rand.NewSource(newSeed)) + return newRandManager(r) +} + +func (rm *randManager) GetRand() *rand.Rand { + rm.rCounter += 1 + r := rand.New(rand.NewSource(rm.internalSeed + rm.rCounter)) + return r +} + +// TODO: Consider rename to DomainSeparatedRand +func (rm *randManager) GetSeededRand(seed string) *rand.Rand { + // use value in map if present + if r, ok := rm.seededMap[seed]; ok { + return r + } + seedInt := stringToSeed(seed) + newSeed := rm.internalSeed + seedInt + r := rand.New(rand.NewSource(newSeed)) + rm.seededMap[seed] = r + return r } diff --git a/simulation/types/txbuilder.go b/simulation/types/txbuilder.go index 05c9c47fbe0..f7d07d1c50a 100644 --- a/simulation/types/txbuilder.go +++ b/simulation/types/txbuilder.go @@ -32,7 +32,7 @@ func (sim *SimCtx) defaultTxBuilder( if !found { return nil, errors.New("unable to generate mock tx: sim acct not found") } - authAcc := sim.App.GetAccountKeeper().GetAccount(ctx, account.Address) + authAcc := sim.AccountKeeper().GetAccount(ctx, account.Address) txConfig := params.MakeEncodingConfig().TxConfig // TODO: unhardcode // TODO: Consider making a default tx builder that charges some random fees // Low value for amount of work right now though. @@ -56,7 +56,7 @@ func (sim *SimCtx) defaultTxBuilder( // TODO: Fix these args func (sim *SimCtx) deliverTx(tx sdk.Tx, msg sdk.Msg, msgName string) (simulation.OperationMsg, []simulation.FutureOperation, error) { txConfig := params.MakeEncodingConfig().TxConfig // TODO: unhardcode - _, results, err := sim.App.GetBaseApp().Deliver(txConfig.TxEncoder(), tx) + _, results, err := sim.BaseApp().Deliver(txConfig.TxEncoder(), tx) if err != nil { return simulation.NoOpMsg(msgName, msgName, fmt.Sprintf("unable to deliver tx. \nreason: %v\n results: %v\n msg: %s\n tx: %s", err, results, msg, tx)), nil, err } From 9df8cf020e30b7c7137fa7e775ee7edc55f22aeb Mon Sep 17 00:00:00 2001 From: Roman Date: Sat, 16 Jul 2022 10:34:22 -0400 Subject: [PATCH 084/376] fix(e2e): upgrade proposals (#2070) --- tests/e2e/configurer/chain/commands.go | 34 ++++++++++++++------------ tests/e2e/configurer/upgrade.go | 26 +++++++++----------- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/tests/e2e/configurer/chain/commands.go b/tests/e2e/configurer/chain/commands.go index 488ccd76dbd..5de83568a41 100644 --- a/tests/e2e/configurer/chain/commands.go +++ b/tests/e2e/configurer/chain/commands.go @@ -10,7 +10,7 @@ import ( ) func (n *NodeConfig) CreatePool(poolFile, from string) { - n.t.Logf("creating pool for chain-id: %s", n.chainId) + n.t.Logf("creating pool from file %s from container %s", poolFile, n.Name) cmd := []string{"osmosisd", "tx", "gamm", "create-pool", fmt.Sprintf("--pool-file=/osmosis/%s", poolFile), fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) @@ -18,7 +18,7 @@ func (n *NodeConfig) CreatePool(poolFile, from string) { } func (n *NodeConfig) SubmitUpgradeProposal(upgradeVersion string, upgradeHeight int64) { - n.t.Logf("submitting upgrade proposal on container: %s", n.Name) + n.t.Logf("submitting upgrade proposal %s for height %d, from container: %s", upgradeVersion, upgradeHeight, n.Name) cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%d", upgradeHeight), "--upgrade-info=\"\"", "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) @@ -30,43 +30,43 @@ func (n *NodeConfig) SubmitSuperfluidProposal(asset string) { cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "set-superfluid-assets-proposal", fmt.Sprintf("--superfluid-assets=%s", asset), fmt.Sprintf("--title=\"%s superfluid asset\"", asset), fmt.Sprintf("--description=\"%s superfluid asset\"", asset), "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Log("successfully submitted superfluid proposal") + n.t.Logf("successfully submitted superfluid proposal for asset %s on container: %s", asset, n.Name) } func (n *NodeConfig) SubmitTextProposal(text string) { - n.t.Logf("submitting text proposal on container: %s", n.Name) + n.t.Logf("submitting text proposal from container: %s", n.Name) cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "--type=text", fmt.Sprintf("--title=\"%s\"", text), "--description=\"test text proposal\"", "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Log("successfully submitted text proposal") + n.t.Logf("successfully submitted from container: %s", n.Name) } func (n *NodeConfig) DepositProposal(proposalNumber int) { - n.t.Logf("depositing to proposal from container: %s", n.Name) + n.t.Logf("depositing to proposal from container %s, on proposal: %d", n.Name, proposalNumber) cmd := []string{"osmosisd", "tx", "gov", "deposit", fmt.Sprintf("%d", proposalNumber), "500000000uosmo", "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Log("successfully deposited to proposal") + n.t.Logf("successfully deposited from container %s, on proposal: %d", n.Name, proposalNumber) } func (n *NodeConfig) VoteYesProposal(from string, proposalNumber int) { - n.t.Logf("voting yes on proposal for chain-id: %s", n.chainId) + n.t.Logf("voting yes on proposal from node container: %s, on proposal: %d", n.Name, proposalNumber) cmd := []string{"osmosisd", "tx", "gov", "vote", fmt.Sprintf("%d", proposalNumber), "yes", fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully voted yes on proposal from container: %s", n.Name) + n.t.Logf("successfully voted yes from node container: %s, on proposal: %d", n.Name, proposalNumber) } func (n *NodeConfig) VoteNoProposal(from string, proposalNumber int) { - n.t.Logf("voting no on proposal for chain-id: %s", n.chainId) + n.t.Logf("voting no on proposal from node container: %s, on proposal: %d", n.Name, proposalNumber) cmd := []string{"osmosisd", "tx", "gov", "vote", fmt.Sprintf("%d", proposalNumber), "no", fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully voted no for proposal from container: %s", n.Name) + n.t.Logf("successfully voted no from node container: %s, on proposal: %d", n.Name, proposalNumber) } func (n *NodeConfig) LockTokens(tokens string, duration string, from string) { - n.t.Logf("locking %s for %s on chain-id: %s", tokens, duration, n.chainId) + n.t.Logf("locking %s for %s on from container %s", tokens, duration, n.Name) cmd := []string{"osmosisd", "tx", "lockup", "lock-tokens", tokens, fmt.Sprintf("--duration=%s", duration), fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) @@ -75,27 +75,29 @@ func (n *NodeConfig) LockTokens(tokens string, duration string, from string) { func (n *NodeConfig) SuperfluidDelegate(lockNumber int, valAddress string, from string) { lockStr := strconv.Itoa(lockNumber) - n.t.Logf("superfluid delegating lock %s to %s on chain-id: %s", lockStr, valAddress, n.chainId) + n.t.Logf("superfluid delegating lock %s to %s from container %s", lockStr, valAddress, n.Name) cmd := []string{"osmosisd", "tx", "superfluid", "delegate", lockStr, valAddress, fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully superfluid delegated from container: %s", n.Name) + n.t.Logf("successfully superfluid delegated lock %s to %s from container: %s", lockStr, valAddress, n.Name) } func (n *NodeConfig) BankSend(amount string, sendAddress string, receiveAddress string) { - n.t.Logf("bank sending %s from %s to %s on chain-id: %s", amount, sendAddress, receiveAddress, n.chainId) + n.t.Logf("bank sending %s from address %s to %s, from container %s", amount, sendAddress, receiveAddress, n.Name) cmd := []string{"osmosisd", "tx", "bank", "send", sendAddress, receiveAddress, amount, "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully sent tx from container: %s", n.Name) + n.t.Logf("successfully sent bank sent %s from address %s to %s, from container %s", amount, sendAddress, receiveAddress, n.Name) } func (n *NodeConfig) CreateWallet(walletName string) string { + n.t.Logf("creating wallet %s, from container %s", walletName, n.Name) cmd := []string{"osmosisd", "keys", "add", walletName, "--keyring-backend=test"} outBuf, _, err := n.containerManager.ExecCmd(n.t, n.Name, cmd, "") require.NoError(n.t, err) re := regexp.MustCompile("osmo1(.{38})") walletAddr := fmt.Sprintf("%s\n", re.FindString(outBuf.String())) walletAddr = strings.TrimSuffix(walletAddr, "\n") + n.t.Logf("created wallet %s, waller address - %s from container %s", walletName, walletAddr, n.Name) return walletAddr } diff --git a/tests/e2e/configurer/upgrade.go b/tests/e2e/configurer/upgrade.go index 287d665b6a6..3131a52d5ae 100644 --- a/tests/e2e/configurer/upgrade.go +++ b/tests/e2e/configurer/upgrade.go @@ -142,21 +142,19 @@ func (uc *UpgradeConfigurer) runProposalUpgrade() error { // submit, deposit, and vote for upgrade proposal // prop height = current height + voting period + time it takes to submit proposal + small buffer for _, chainConfig := range uc.chainConfigs { - node, err := chainConfig.GetDefaultNode() - if err != nil { - return err - } - currentHeight, err := node.QueryCurrentHeight() - if err != nil { - return err + for validatorIdx, node := range chainConfig.NodeConfigs { + if validatorIdx == 0 { + currentHeight, err := node.QueryCurrentHeight() + if err != nil { + return err + } + chainConfig.UpgradePropHeight = currentHeight + int64(chainConfig.VotingPeriod) + int64(config.PropSubmitBlocks) + int64(config.PropBufferBlocks) + node.SubmitUpgradeProposal(uc.upgradeVersion, chainConfig.UpgradePropHeight) + chainConfig.LatestProposalNumber += 1 + node.DepositProposal(chainConfig.LatestProposalNumber) + } + node.VoteYesProposal(initialization.ValidatorWalletName, chainConfig.LatestProposalNumber) } - - chainConfig.UpgradePropHeight = currentHeight + int64(chainConfig.VotingPeriod) + int64(config.PropSubmitBlocks) + int64(config.PropBufferBlocks) - node.SubmitUpgradeProposal(uc.upgradeVersion, chainConfig.UpgradePropHeight) - chainConfig.LatestProposalNumber += 1 - - node.DepositProposal(chainConfig.LatestProposalNumber) - node.VoteYesProposal(initialization.ValidatorWalletName, chainConfig.LatestProposalNumber) } // wait till all chains halt at upgrade height From 8e6e4de0bc65d521185f2aa82ff5884c107bd8c5 Mon Sep 17 00:00:00 2001 From: Roman Date: Sat, 16 Jul 2022 14:54:04 -0400 Subject: [PATCH 085/376] ci: manual job to replace import paths (#2094) * ci: manual job to replace import paths * Update .github/workflows/import_paths.yml Co-authored-by: Dev Ojha Co-authored-by: Dev Ojha --- .github/workflows/import_paths.yml | 77 ++++++++++++++++++++++++++++++ scripts/replace_import_paths.sh | 30 ++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 .github/workflows/import_paths.yml create mode 100755 scripts/replace_import_paths.sh diff --git a/.github/workflows/import_paths.yml b/.github/workflows/import_paths.yml new file mode 100644 index 00000000000..0af5f0c0379 --- /dev/null +++ b/.github/workflows/import_paths.yml @@ -0,0 +1,77 @@ +# This is a manua workflow that does the following when trigerred: +# - Runs a script to find and replace Go import path major version with given version. +# - Commits and pushes changes to the source-branch. +# - Opens a PR from the source branch to the target-branch. + +name: Update Go Import Paths + +on: + workflow_dispatch: + inputs: + version: + description: 'Current Version that we want to change' + default: '10' + required: true + target-branch: + description: 'Target Branch' + default: 'main' + required: true + source-branch: + description: 'Source Branch' + default: 'update-paths' + required: true + +jobs: + update-import-paths: + runs-on: ubuntu-latest + + steps: + - + name: Check out repository code + uses: actions/checkout@v2 + - + name: Setup Golang + uses: actions/setup-go@v2.1.4 + with: + go-version: 1.18 + - + name: Display go version + run: go version + - + name: Get data from build cache + uses: actions/cache@v2 + with: + # In order: + # * Module download cache + # * Build cache (Linux) + # * Build cache (Mac) + # * Build cache (Windows) + path: | + ~/go/pkg/mod + ~/.cache/go-build + ~/Library/Caches/go-build + ~\AppData\Local\go-build + key: ${{ runner.os }}-go-${{ matrix.go-version }}-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go-${{ matrix.go-version }}- + - + name: Run find & replace script + run: ./scripts/replace_import_paths.sh ${{ inputs.version }} + - name: Commit and push changes + uses: devops-infra/action-commit-push@master + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + commit_message: "auto: update Go import paths to v${{ inputs.version }}" + target_branch: update-paths + - name: Open PR + uses: devops-infra/action-pull-request@v0.5.0 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + title: ${{ github.event.commits[0].message }} + source_branch: ${{ inputs.source-branch }} + target_branch: ${{ inputs.target-branch }} + assignee: ${{ github.actor }} + draft: true + label: T:auto,T:code-hygiene + body: "**Automated pull request**\n\nUpdating Go import paths to v${{ inputs.version }}" + get_diff: true diff --git a/scripts/replace_import_paths.sh b/scripts/replace_import_paths.sh new file mode 100755 index 00000000000..45ef110daf2 --- /dev/null +++ b/scripts/replace_import_paths.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +NEXT_MAJOR_VERSION=$1 +import_path_to_replace=$(go list -m) + +version_to_replace=$(echo $import_path_to_replace | sed 's/g.*v//') + +echo Current import paths are $version_to_replace, replacing with $NEXT_MAJOR_VERSION + +# list all folders containing Go modules. +modules=$(go list ./... | sed "s/g.*v${version_to_replace}\///") + +replace_paths() { + file="${1}" + sed -i "s/github.com\/osmosis-labs\/osmosis\/v${version_to_replace}/github.com\/osmosis-labs\/osmosis\/v${NEXT_MAJOR_VERSION}/g" ${file} +} + +# Replace all files within Go packages. +for mod in $modules; +do + for file in $mod/*; do + if [ -f "${file}" ]; then + replace_paths $file + fi + done +done + +replace_paths "go.mod" + +go mod vendor >/dev/null From e9907ce6107c10d8596270cc18b83bfd0ca64dbb Mon Sep 17 00:00:00 2001 From: Richard Liu Date: Sun, 17 Jul 2022 14:47:45 -0400 Subject: [PATCH 086/376] x/gamm: Add fixed gas cost for swaps (#2016) * add gas for swap + test * test file comments * move swap consumption to balancer only * fix one more test case * add to changelog * Update CHANGELOG.md Co-authored-by: Aleksandr Bezobchuk * rm TODO now that we have issue * underscore for clarity * gofmt Co-authored-by: Aleksandr Bezobchuk --- CHANGELOG.md | 2 ++ x/gamm/keeper/swap.go | 1 + x/gamm/keeper/swap_test.go | 8 ++++++++ x/gamm/pool-models/balancer/pool.go | 2 ++ x/gamm/types/constants.go | 3 ++- 5 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7e31401dab..d2ec2eea37b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +* [#2016](https://github.com/osmosis-labs/osmosis/pull/2016) Add fixed 10000 gas cost for each Balancer swap + ### Breaking Changes diff --git a/x/gamm/keeper/swap.go b/x/gamm/keeper/swap.go index a9fa3ee6533..3658404ec58 100644 --- a/x/gamm/keeper/swap.go +++ b/x/gamm/keeper/swap.go @@ -114,6 +114,7 @@ func (k Keeper) swapExactAmountOut( return sdk.Int{}, sdkerrors.Wrapf(types.ErrTooManyTokensOut, "can't get more tokens out than there are tokens in the pool") } + tokenIn, err := pool.SwapInAmtGivenOut(ctx, sdk.Coins{tokenOut}, tokenInDenom, swapFee) if err != nil { return sdk.Int{}, err diff --git a/x/gamm/keeper/swap_test.go b/x/gamm/keeper/swap_test.go index 9b647d093b9..4837a9f25fd 100644 --- a/x/gamm/keeper/swap_test.go +++ b/x/gamm/keeper/swap_test.go @@ -95,9 +95,13 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() { spotPriceBefore, err := keeper.CalculateSpotPrice(ctx, poolId, test.param.tokenIn.Denom, test.param.tokenOutDenom) suite.NoError(err, "test: %v", test.name) + prevGasConsumed := suite.Ctx.GasMeter().GasConsumed() tokenOutAmount, err := keeper.SwapExactAmountIn(ctx, suite.TestAccs[0], poolId, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount) suite.NoError(err, "test: %v", test.name) suite.True(tokenOutAmount.Equal(test.param.expectedTokenOut), "test: %v", test.name) + gasConsumedForSwap := suite.Ctx.GasMeter().GasConsumed() - prevGasConsumed + // We consume `types.GasFeeForSwap` directly, so the extra I/O operation mean we end up consuming more. + suite.Assert().Greater(gasConsumedForSwap, uint64(types.BalancerGasFeeForSwap)) assertEventEmitted(suite, ctx, types.TypeEvtTokenSwapped, 1) @@ -199,11 +203,15 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountOut() { spotPriceBefore, err := keeper.CalculateSpotPrice(ctx, poolId, test.param.tokenInDenom, test.param.tokenOut.Denom) suite.NoError(err, "test: %v", test.name) + prevGasConsumed := suite.Ctx.GasMeter().GasConsumed() tokenInAmount, err := keeper.SwapExactAmountOut(ctx, suite.TestAccs[0], poolId, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut) suite.NoError(err, "test: %v", test.name) suite.True(tokenInAmount.Equal(test.param.expectedTokenInAmount), "test: %v\n expect_eq actual: %s, expected: %s", test.name, tokenInAmount, test.param.expectedTokenInAmount) + gasConsumedForSwap := suite.Ctx.GasMeter().GasConsumed() - prevGasConsumed + // We consume `types.GasFeeForSwap` directly, so the extra I/O operation mean we end up consuming more. + suite.Assert().Greater(gasConsumedForSwap, uint64(types.BalancerGasFeeForSwap)) assertEventEmitted(suite, ctx, types.TypeEvtTokenSwapped, 1) diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index 2a34b982b48..4169067aa0e 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -584,6 +584,8 @@ func (p *Pool) SwapInAmtGivenOut( // ApplySwap. func (p *Pool) applySwap(ctx sdk.Context, tokensIn sdk.Coins, tokensOut sdk.Coins) error { + // Fixed gas consumption per swap to prevent spam + ctx.GasMeter().ConsumeGas(types.BalancerGasFeeForSwap, "balancer swap computation") // Also ensures that len(tokensIn) = 1 = len(tokensOut) inPoolAsset, outPoolAsset, err := p.parsePoolAssetsCoins(tokensIn, tokensOut) if err != nil { diff --git a/x/gamm/types/constants.go b/x/gamm/types/constants.go index acdde3c66e2..4043af1c55b 100644 --- a/x/gamm/types/constants.go +++ b/x/gamm/types/constants.go @@ -11,7 +11,8 @@ const ( OneShareExponent = 18 // Raise 10 to the power of SigFigsExponent to determine number of significant figures. // i.e. SigFigExponent = 8 is 10^8 which is 100000000. This gives 8 significant figures. - SigFigsExponent = 8 + SigFigsExponent = 8 + BalancerGasFeeForSwap = 10_000 ) var ( From cf46695926cf0a786912aeaeb129b3f14610b0e8 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sun, 17 Jul 2022 21:14:08 -0500 Subject: [PATCH 087/376] E2E: speedup execution time, add basic time tracking (#2103) * Add unified log method, cleanup boilerplate, add time tracking * Add setupTime, try test config * Round time log * Lower tx poll interval * Lower query polling intervals --- tests/e2e/configurer/base.go | 4 ++- tests/e2e/configurer/chain/commands.go | 44 +++++++++++++------------- tests/e2e/configurer/chain/node.go | 15 +++++++++ tests/e2e/configurer/chain/queries.go | 2 +- tests/e2e/containers/containers.go | 2 +- tests/e2e/e2e_test.go | 4 +-- tests/e2e/initialization/node.go | 1 + 7 files changed, 45 insertions(+), 27 deletions(-) diff --git a/tests/e2e/configurer/base.go b/tests/e2e/configurer/base.go index 023a53e04c2..3826e10fcbe 100644 --- a/tests/e2e/configurer/base.go +++ b/tests/e2e/configurer/base.go @@ -177,7 +177,9 @@ func (bc *baseConfigurer) connectIBCChains(chainA *chain.Config, chainB *chain.C func (bc *baseConfigurer) initializeChainConfigFromInitChain(initializedChain *initialization.Chain, chainConfig *chain.Config) { chainConfig.ChainMeta = initializedChain.ChainMeta chainConfig.NodeConfigs = make([]*chain.NodeConfig, 0, len(initializedChain.Nodes)) + setupTime := time.Now() for _, validator := range initializedChain.Nodes { - chainConfig.NodeConfigs = append(chainConfig.NodeConfigs, chain.NewNodeConfig(bc.t, validator, chainConfig.Id, bc.containerManager)) + conf := chain.NewNodeConfig(bc.t, validator, chainConfig.Id, bc.containerManager).WithSetupTime(setupTime) + chainConfig.NodeConfigs = append(chainConfig.NodeConfigs, conf) } } diff --git a/tests/e2e/configurer/chain/commands.go b/tests/e2e/configurer/chain/commands.go index 5de83568a41..ac806545f70 100644 --- a/tests/e2e/configurer/chain/commands.go +++ b/tests/e2e/configurer/chain/commands.go @@ -10,94 +10,94 @@ import ( ) func (n *NodeConfig) CreatePool(poolFile, from string) { - n.t.Logf("creating pool from file %s from container %s", poolFile, n.Name) + n.LogActionF("creating pool from file %s", poolFile) cmd := []string{"osmosisd", "tx", "gamm", "create-pool", fmt.Sprintf("--pool-file=/osmosis/%s", poolFile), fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully created pool from container: %s", n.Name) + n.LogActionF("successfully created pool") } func (n *NodeConfig) SubmitUpgradeProposal(upgradeVersion string, upgradeHeight int64) { - n.t.Logf("submitting upgrade proposal %s for height %d, from container: %s", upgradeVersion, upgradeHeight, n.Name) + n.LogActionF("submitting upgrade proposal %s for height %d", upgradeVersion, upgradeHeight) cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%d", upgradeHeight), "--upgrade-info=\"\"", "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Log("successfully submitted upgrade proposal") + n.LogActionF("successfully submitted upgrade proposal") } func (n *NodeConfig) SubmitSuperfluidProposal(asset string) { - n.t.Logf("submitting superfluid proposal for asset %s on container: %s", asset, n.Name) + n.LogActionF("submitting superfluid proposal for asset %s", asset) cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "set-superfluid-assets-proposal", fmt.Sprintf("--superfluid-assets=%s", asset), fmt.Sprintf("--title=\"%s superfluid asset\"", asset), fmt.Sprintf("--description=\"%s superfluid asset\"", asset), "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully submitted superfluid proposal for asset %s on container: %s", asset, n.Name) + n.LogActionF("successfully submitted superfluid proposal for asset %s", asset) } func (n *NodeConfig) SubmitTextProposal(text string) { - n.t.Logf("submitting text proposal from container: %s", n.Name) + n.LogActionF("submitting text gov proposal") cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "--type=text", fmt.Sprintf("--title=\"%s\"", text), "--description=\"test text proposal\"", "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully submitted from container: %s", n.Name) + n.LogActionF("successfully submitted text gov proposal") } func (n *NodeConfig) DepositProposal(proposalNumber int) { - n.t.Logf("depositing to proposal from container %s, on proposal: %d", n.Name, proposalNumber) + n.LogActionF("depositing on proposal: %d", proposalNumber) cmd := []string{"osmosisd", "tx", "gov", "deposit", fmt.Sprintf("%d", proposalNumber), "500000000uosmo", "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully deposited from container %s, on proposal: %d", n.Name, proposalNumber) + n.LogActionF("successfully deposited on proposal %d", proposalNumber) } func (n *NodeConfig) VoteYesProposal(from string, proposalNumber int) { - n.t.Logf("voting yes on proposal from node container: %s, on proposal: %d", n.Name, proposalNumber) + n.LogActionF("voting yes on proposal: %d", proposalNumber) cmd := []string{"osmosisd", "tx", "gov", "vote", fmt.Sprintf("%d", proposalNumber), "yes", fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully voted yes from node container: %s, on proposal: %d", n.Name, proposalNumber) + n.LogActionF("successfully voted yes on proposal %d", proposalNumber) } func (n *NodeConfig) VoteNoProposal(from string, proposalNumber int) { - n.t.Logf("voting no on proposal from node container: %s, on proposal: %d", n.Name, proposalNumber) + n.LogActionF("voting no on proposal: %d", proposalNumber) cmd := []string{"osmosisd", "tx", "gov", "vote", fmt.Sprintf("%d", proposalNumber), "no", fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully voted no from node container: %s, on proposal: %d", n.Name, proposalNumber) + n.LogActionF("successfully voted no on proposal: %d", proposalNumber) } func (n *NodeConfig) LockTokens(tokens string, duration string, from string) { - n.t.Logf("locking %s for %s on from container %s", tokens, duration, n.Name) + n.LogActionF("locking %s for %s", tokens, duration) cmd := []string{"osmosisd", "tx", "lockup", "lock-tokens", tokens, fmt.Sprintf("--duration=%s", duration), fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully created lock from container: %s", n.Name) + n.LogActionF("successfully created lock") } func (n *NodeConfig) SuperfluidDelegate(lockNumber int, valAddress string, from string) { lockStr := strconv.Itoa(lockNumber) - n.t.Logf("superfluid delegating lock %s to %s from container %s", lockStr, valAddress, n.Name) + n.LogActionF("superfluid delegating lock %s to %s", lockStr, valAddress) cmd := []string{"osmosisd", "tx", "superfluid", "delegate", lockStr, valAddress, fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully superfluid delegated lock %s to %s from container: %s", lockStr, valAddress, n.Name) + n.LogActionF("successfully superfluid delegated lock %s to %s", lockStr, valAddress) } func (n *NodeConfig) BankSend(amount string, sendAddress string, receiveAddress string) { - n.t.Logf("bank sending %s from address %s to %s, from container %s", amount, sendAddress, receiveAddress, n.Name) + n.LogActionF("bank sending %s from address %s to %s", amount, sendAddress, receiveAddress) cmd := []string{"osmosisd", "tx", "bank", "send", sendAddress, receiveAddress, amount, "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) - n.t.Logf("successfully sent bank sent %s from address %s to %s, from container %s", amount, sendAddress, receiveAddress, n.Name) + n.LogActionF("successfully sent bank sent %s from address %s to %s", amount, sendAddress, receiveAddress) } func (n *NodeConfig) CreateWallet(walletName string) string { - n.t.Logf("creating wallet %s, from container %s", walletName, n.Name) + n.LogActionF("creating wallet %s", walletName) cmd := []string{"osmosisd", "keys", "add", walletName, "--keyring-backend=test"} outBuf, _, err := n.containerManager.ExecCmd(n.t, n.Name, cmd, "") require.NoError(n.t, err) re := regexp.MustCompile("osmo1(.{38})") walletAddr := fmt.Sprintf("%s\n", re.FindString(outBuf.String())) walletAddr = strings.TrimSuffix(walletAddr, "\n") - n.t.Logf("created wallet %s, waller address - %s from container %s", walletName, walletAddr, n.Name) + n.LogActionF("created wallet %s, waller address - %s", walletName, walletAddr) return walletAddr } diff --git a/tests/e2e/configurer/chain/node.go b/tests/e2e/configurer/chain/node.go index 7c082af2b0c..7af3a36d85d 100644 --- a/tests/e2e/configurer/chain/node.go +++ b/tests/e2e/configurer/chain/node.go @@ -24,6 +24,9 @@ type NodeConfig struct { rpcClient *rpchttp.HTTP t *testing.T containerManager *containers.Manager + + // Add this to help with logging / tracking time since start. + setupTime time.Time } // NewNodeConfig returens new initialized NodeConfig. @@ -33,6 +36,7 @@ func NewNodeConfig(t *testing.T, initNode *initialization.Node, chainId string, chainId: chainId, containerManager: containerManager, t: t, + setupTime: time.Now(), } } @@ -113,3 +117,14 @@ func (n *NodeConfig) extractOperatorAddressIfValidator() error { n.OperatorAddress = strings.TrimSuffix(operAddr, "\n") return nil } + +func (n *NodeConfig) WithSetupTime(t time.Time) *NodeConfig { + n.setupTime = t + return n +} + +func (n *NodeConfig) LogActionF(msg string, args ...interface{}) { + timeSinceStart := time.Since(n.setupTime).Round(time.Millisecond) + s := fmt.Sprintf(msg, args...) + n.t.Logf("[%s] %s. From container %s", timeSinceStart, s, n.Name) +} diff --git a/tests/e2e/configurer/chain/queries.go b/tests/e2e/configurer/chain/queries.go index 672ecebdb5e..b9fb7dff099 100644 --- a/tests/e2e/configurer/chain/queries.go +++ b/tests/e2e/configurer/chain/queries.go @@ -34,7 +34,7 @@ func (n *NodeConfig) QueryGRPCGateway(path string) ([]byte, error) { } return resp.StatusCode != http.StatusServiceUnavailable - }, time.Minute, time.Second*10, "failed to execute HTTP request") + }, time.Minute, time.Millisecond*10, "failed to execute HTTP request") defer resp.Body.Close() diff --git a/tests/e2e/containers/containers.go b/tests/e2e/containers/containers.go index c49523406de..a45637d678d 100644 --- a/tests/e2e/containers/containers.go +++ b/tests/e2e/containers/containers.go @@ -125,7 +125,7 @@ func (m *Manager) ExecCmd(t *testing.T, containerName string, command []string, return true }, time.Minute, - time.Second, + 50*time.Millisecond, "tx returned a non-zero code", ) diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index d80b04334c6..0113b675d3a 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -85,7 +85,7 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { return true }, 1*time.Minute, - time.Second, + 10*time.Millisecond, "Osmosis node failed to retrieve prop tally", ) noTotal, _, _, _, _ := node.QueryPropTally(chain.LatestProposalNumber) @@ -106,7 +106,7 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { return true }, 1*time.Minute, - time.Second, + 10*time.Millisecond, "superfluid delegation vote overwrite not working as expected", ) } diff --git a/tests/e2e/initialization/node.go b/tests/e2e/initialization/node.go index 1f4733896b3..3300cfbd010 100644 --- a/tests/e2e/initialization/node.go +++ b/tests/e2e/initialization/node.go @@ -310,6 +310,7 @@ func (n *internalNode) initValidatorConfigs(c *internalChain, persistentPeers [] valConfig.StateSync.Enable = false valConfig.LogLevel = "info" valConfig.P2P.PersistentPeers = strings.Join(persistentPeers, ",") + valConfig.Consensus = tmconfig.TestConsensusConfig() tmconfig.WriteConfigFile(tmCfgPath, valConfig) return nil From 7fb5f824007ace3bf16274cc22e18d49b544485a Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Sun, 17 Jul 2022 19:22:49 -0700 Subject: [PATCH 088/376] x/gamm: Make all internal set functions private (#2013) Closes: #1945 ## What is the purpose of the change I believe these functions were only public because they needed to be for an older SDK version. I think it would be appropriate to make them private now so that they aren't exposed to other modules. ## Brief Changelog - Made the following functions private: `SetParams` `SetPool` `SetTotalLiquidity` `SetDenomLiquidity` - Commented out old upgrade code that prevented `SetParams` and `SetPool` from being made private - Removed use of `SetParams` in a superfluid test ## Testing and Verifying This change is a trivial rework / code cleanup without any test coverage. ## Documentation and Release Note - Does this pull request introduce a new feature or user-facing behavior changes? (no) - Is a relevant changelog entry added to the `Unreleased` section in `CHANGELOG.md`? (no) - How is the feature or change documented? (not documented) --- CHANGELOG.md | 1 + app/apptesting/test_suite.go | 9 ++------- app/upgrades/v4/upgrade_test.go | 13 ++++++++----- app/upgrades/v4/upgrades.go | 5 ++--- app/upgrades/v9/prop214.go | 9 +++++---- app/upgrades/v9/prop214_test.go | 12 ++++++------ x/gamm/keeper/export_test.go | 12 ++++++++++++ x/gamm/keeper/genesis.go | 6 +++--- x/gamm/keeper/params.go | 2 +- x/gamm/keeper/pool.go | 4 ++-- x/gamm/keeper/pool_service.go | 2 +- x/gamm/keeper/share.go | 4 ++-- x/gamm/keeper/swap.go | 2 +- x/gamm/keeper/total_liquidity.go | 10 +++++----- 14 files changed, 51 insertions(+), 40 deletions(-) create mode 100644 x/gamm/keeper/export_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index d2ec2eea37b..235e00b7588 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,6 +64,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#1665](https://github.com/osmosis-labs/osmosis/pull/1665) Delete app/App interface, instead use simapp.App * [#1630](https://github.com/osmosis-labs/osmosis/pull/1630) Delete the v043_temp module, now that we're on an updated SDK version. * [#1667](https://github.com/osmosis-labs/osmosis/pull/1673) Move wasm-bindings code out of app package into its own root level package. +* [#2013](https://github.com/osmosis-labs/osmosis/pull/2013) Make `SetParams`, `SetPool`, `SetTotalLiquidity`, and `SetDenomLiquidity` GAMM APIs private ### Features diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index a73be4ece5e..0e892295587 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -174,16 +174,11 @@ func (s *KeeperTestHelper) AllocateRewardsToValidator(valAddr sdk.ValAddress, re // SetupGammPoolsWithBondDenomMultiplier uses given multipliers to set initial pool supply of bond denom. func (s *KeeperTestHelper) SetupGammPoolsWithBondDenomMultiplier(multipliers []sdk.Dec) []gammtypes.PoolI { - s.App.GAMMKeeper.SetParams(s.Ctx, gammtypes.Params{ - PoolCreationFee: sdk.Coins{}, - }) - bondDenom := s.App.StakingKeeper.BondDenom(s.Ctx) // TODO: use sdk crypto instead of tendermint to generate address acc1 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes()) - poolCreationFee := s.App.GAMMKeeper.GetParams(s.Ctx) - s.FundAcc(acc1, poolCreationFee.PoolCreationFee) + params := s.App.GAMMKeeper.GetParams(s.Ctx) pools := []gammtypes.PoolI{} for index, multiplier := range multipliers { @@ -193,7 +188,7 @@ func (s *KeeperTestHelper) SetupGammPoolsWithBondDenomMultiplier(multipliers []s s.FundAcc(acc1, sdk.NewCoins( sdk.NewCoin(bondDenom, uosmoAmount.Mul(sdk.NewInt(10))), sdk.NewInt64Coin(token, 100000), - )) + ).Add(params.PoolCreationFee...)) var ( defaultFutureGovernor = "" diff --git a/app/upgrades/v4/upgrade_test.go b/app/upgrades/v4/upgrade_test.go index 0a402b6f768..0f66dd3dfea 100644 --- a/app/upgrades/v4/upgrade_test.go +++ b/app/upgrades/v4/upgrade_test.go @@ -7,12 +7,13 @@ import ( "testing" "time" - "github.com/osmosis-labs/osmosis/v7/app" - v4 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v4" "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "github.com/osmosis-labs/osmosis/v7/app" + v4 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v4" + sdk "github.com/cosmos/cosmos-sdk/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) @@ -107,9 +108,11 @@ func (suite *UpgradeTestSuite) TestUpgradePayments() { suite.Require().Equal(feePool.GetCommunityPool(), sdk.NewDecCoins(sdk.NewInt64DecCoin("uosmo", expectedBal))) // Check that gamm Minimum Fee has been set correctly - gammParams := suite.app.GAMMKeeper.GetParams(suite.ctx) - expectedCreationFee := sdk.NewCoins(sdk.NewCoin("uosmo", sdk.OneInt())) - suite.Require().Equal(gammParams.PoolCreationFee, expectedCreationFee) + + // Kept as comments for recordkeeping. Since SetParams is now private, the changes being tested for can no longer be made: + // gammParams := suite.app.GAMMKeeper.GetParams(suite.ctx) + // expectedCreationFee := sdk.NewCoins(sdk.NewCoin("uosmo", sdk.OneInt())) + // suite.Require().Equal(gammParams.PoolCreationFee, expectedCreationFee) }, true, }, diff --git a/app/upgrades/v4/upgrades.go b/app/upgrades/v4/upgrades.go index e5b60ae3615..eac31d0abf5 100644 --- a/app/upgrades/v4/upgrades.go +++ b/app/upgrades/v4/upgrades.go @@ -7,7 +7,6 @@ import ( "github.com/osmosis-labs/osmosis/v7/app/keepers" "github.com/osmosis-labs/osmosis/v7/app/upgrades" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" ) // CreateUpgradeHandler returns an x/upgrade handler for the Osmosis v4 on-chain @@ -22,8 +21,8 @@ func CreateUpgradeHandler( keepers *keepers.AppKeepers, ) upgradetypes.UpgradeHandler { return func(ctx sdk.Context, _plan upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { - // configure upgrade for x/gamm module pool creation fee param - keepers.GAMMKeeper.SetParams(ctx, gammtypes.NewParams(sdk.Coins{sdk.NewInt64Coin("uosmo", 1)})) // 1 uOSMO + // Kept as comments for recordkeeping. SetParams is now private: + // keepers.GAMMKeeper.SetParams(ctx, gammtypes.NewParams(sdk.Coins{sdk.NewInt64Coin("uosmo", 1)})) // 1 uOSMO Prop12(ctx, keepers.BankKeeper, keepers.DistrKeeper) diff --git a/app/upgrades/v9/prop214.go b/app/upgrades/v9/prop214.go index 769b2cc7710..7458c9eded7 100644 --- a/app/upgrades/v9/prop214.go +++ b/app/upgrades/v9/prop214.go @@ -25,8 +25,9 @@ func ExecuteProp214(ctx sdk.Context, gamm *gammkeeper.Keeper) { balancerPool.PoolParams.SwapFee = sdk.MustNewDecFromStr("0.002") - err = gamm.SetPool(ctx, balancerPool) - if err != nil { - panic(err) - } + // Kept as comments for recordkeeping. SetPool is now private: + // err = gamm.SetPool(ctx, balancerPool) + // if err != nil { + // panic(err) + // } } diff --git a/app/upgrades/v9/prop214_test.go b/app/upgrades/v9/prop214_test.go index 4445d2791bd..0fc62d6cb71 100644 --- a/app/upgrades/v9/prop214_test.go +++ b/app/upgrades/v9/prop214_test.go @@ -3,7 +3,6 @@ package v9_test import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" "github.com/osmosis-labs/osmosis/v7/app/apptesting" @@ -26,11 +25,12 @@ func (suite *UpgradeTestSuite) TestProp214() { poolId := suite.PrepareBalancerPool() v9.ExecuteProp214(suite.Ctx, suite.App.GAMMKeeper) - pool, err := suite.App.GAMMKeeper.GetPoolAndPoke(suite.Ctx, poolId) + _, err := suite.App.GAMMKeeper.GetPoolAndPoke(suite.Ctx, poolId) suite.Require().NoError(err) - swapFee := pool.GetSwapFee(suite.Ctx) - expectedSwapFee := sdk.MustNewDecFromStr("0.002") - - suite.Require().Equal(expectedSwapFee, swapFee) + // Kept as comments for recordkeeping. Since SetPool is now private, the changes being tested for can no longer be made: + // swapFee := pool.GetSwapFee(suite.Ctx) + // expectedSwapFee := sdk.MustNewDecFromStr("0.002") + // + // suite.Require().Equal(expectedSwapFee, swapFee) } diff --git a/x/gamm/keeper/export_test.go b/x/gamm/keeper/export_test.go new file mode 100644 index 00000000000..005c6960e91 --- /dev/null +++ b/x/gamm/keeper/export_test.go @@ -0,0 +1,12 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +) + +// SetParams sets the total set of params. +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.setParams(ctx, params) +} diff --git a/x/gamm/keeper/genesis.go b/x/gamm/keeper/genesis.go index e299d4f80f0..ca66abfe584 100644 --- a/x/gamm/keeper/genesis.go +++ b/x/gamm/keeper/genesis.go @@ -10,7 +10,7 @@ import ( // InitGenesis initializes the x/gamm module's state from a provided genesis // state, which includes the current live pools, global pool parameters (e.g. pool creation fee), next pool number etc. func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState, unpacker codectypes.AnyUnpacker) { - k.SetParams(ctx, genState.Params) + k.setParams(ctx, genState.Params) k.setNextPoolNumber(ctx, genState.NextPoolNumber) // Sums up the liquidity in all genesis state pools to find the total liquidity across all pools. @@ -22,7 +22,7 @@ func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState, unpack if err != nil { panic(err) } - err = k.SetPool(ctx, pool) + err = k.setPool(ctx, pool) if err != nil { panic(err) } @@ -33,7 +33,7 @@ func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState, unpack } } - k.SetTotalLiquidity(ctx, liquidity) + k.setTotalLiquidity(ctx, liquidity) } // ExportGenesis returns the capability module's exported genesis. diff --git a/x/gamm/keeper/params.go b/x/gamm/keeper/params.go index 5a65da4960a..420c3413e1d 100644 --- a/x/gamm/keeper/params.go +++ b/x/gamm/keeper/params.go @@ -13,6 +13,6 @@ func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { } // SetParams sets the total set of params. -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { +func (k Keeper) setParams(ctx sdk.Context, params types.Params) { k.paramSpace.SetParamSet(ctx, ¶ms) } diff --git a/x/gamm/keeper/pool.go b/x/gamm/keeper/pool.go index 0a4bd46a814..f347d5eeaba 100644 --- a/x/gamm/keeper/pool.go +++ b/x/gamm/keeper/pool.go @@ -81,7 +81,7 @@ func (k Keeper) GetPoolsAndPoke(ctx sdk.Context) (res []types.PoolI, err error) return res, nil } -func (k Keeper) SetPool(ctx sdk.Context, pool types.PoolI) error { +func (k Keeper) setPool(ctx sdk.Context, pool types.PoolI) error { bz, err := k.MarshalPool(pool) if err != nil { return err @@ -255,7 +255,7 @@ func (k *Keeper) SetStableSwapScalingFactors(ctx sdk.Context, scalingFactors []u stableswapPool.ScalingFactor = scalingFactors - if err = k.SetPool(ctx, stableswapPool); err != nil { + if err = k.setPool(ctx, stableswapPool); err != nil { return err } return nil diff --git a/x/gamm/keeper/pool_service.go b/x/gamm/keeper/pool_service.go index 47fe5f03ebe..fe6aeef3f7b 100644 --- a/x/gamm/keeper/pool_service.go +++ b/x/gamm/keeper/pool_service.go @@ -160,7 +160,7 @@ func (k Keeper) CreatePool(ctx sdk.Context, msg types.CreatePoolMsg) (uint64, er Display: poolShareDisplayDenom, }) - if err := k.SetPool(ctx, pool); err != nil { + if err := k.setPool(ctx, pool); err != nil { return 0, err } diff --git a/x/gamm/keeper/share.go b/x/gamm/keeper/share.go index 7423c264ba6..a5de4174066 100644 --- a/x/gamm/keeper/share.go +++ b/x/gamm/keeper/share.go @@ -18,7 +18,7 @@ func (k Keeper) applyJoinPoolStateChange(ctx sdk.Context, pool types.PoolI, join return err } - err = k.SetPool(ctx, pool) + err = k.setPool(ctx, pool) if err != nil { return err } @@ -40,7 +40,7 @@ func (k Keeper) applyExitPoolStateChange(ctx sdk.Context, pool types.PoolI, exit return err } - err = k.SetPool(ctx, pool) + err = k.setPool(ctx, pool) if err != nil { return err } diff --git a/x/gamm/keeper/swap.go b/x/gamm/keeper/swap.go index 3658404ec58..a899c20bfd9 100644 --- a/x/gamm/keeper/swap.go +++ b/x/gamm/keeper/swap.go @@ -149,7 +149,7 @@ func (k Keeper) updatePoolForSwap( tokensIn := sdk.Coins{tokenIn} tokensOut := sdk.Coins{tokenOut} - err := k.SetPool(ctx, pool) + err := k.setPool(ctx, pool) if err != nil { return err } diff --git a/x/gamm/keeper/total_liquidity.go b/x/gamm/keeper/total_liquidity.go index 851b62c18ca..c82b0e9126b 100644 --- a/x/gamm/keeper/total_liquidity.go +++ b/x/gamm/keeper/total_liquidity.go @@ -16,13 +16,13 @@ func (k Keeper) GetTotalLiquidity(ctx sdk.Context) sdk.Coins { return coins } -func (k Keeper) SetTotalLiquidity(ctx sdk.Context, coins sdk.Coins) { +func (k Keeper) setTotalLiquidity(ctx sdk.Context, coins sdk.Coins) { for _, coin := range coins { - k.SetDenomLiquidity(ctx, coin.Denom, coin.Amount) + k.setDenomLiquidity(ctx, coin.Denom, coin.Amount) } } -func (k Keeper) SetDenomLiquidity(ctx sdk.Context, denom string, amount sdk.Int) { +func (k Keeper) setDenomLiquidity(ctx sdk.Context, denom string, amount sdk.Int) { store := ctx.KVStore(k.storeKey) bz, err := amount.Marshal() if err != nil { @@ -68,7 +68,7 @@ func (k Keeper) RecordTotalLiquidityIncrease(ctx sdk.Context, coins sdk.Coins) { for _, coin := range coins { amount := k.GetDenomLiquidity(ctx, coin.Denom) amount = amount.Add(coin.Amount) - k.SetDenomLiquidity(ctx, coin.Denom, amount) + k.setDenomLiquidity(ctx, coin.Denom, amount) } } @@ -76,6 +76,6 @@ func (k Keeper) RecordTotalLiquidityDecrease(ctx sdk.Context, coins sdk.Coins) { for _, coin := range coins { amount := k.GetDenomLiquidity(ctx, coin.Denom) amount = amount.Sub(coin.Amount) - k.SetDenomLiquidity(ctx, coin.Denom, amount) + k.setDenomLiquidity(ctx, coin.Denom, amount) } } From dcc82d72d6609828b6ff83a8a4c0fadd7b44273b Mon Sep 17 00:00:00 2001 From: Roman Date: Sun, 17 Jul 2022 22:47:29 -0400 Subject: [PATCH 089/376] ci: improve import path action (#2104) --- .github/workflows/import_paths.yml | 28 ++++++++++++---------------- scripts/replace_import_paths.sh | 20 ++++++++++++++++++-- 2 files changed, 30 insertions(+), 18 deletions(-) diff --git a/.github/workflows/import_paths.yml b/.github/workflows/import_paths.yml index 0af5f0c0379..bf6ea8ec420 100644 --- a/.github/workflows/import_paths.yml +++ b/.github/workflows/import_paths.yml @@ -57,21 +57,17 @@ jobs: - name: Run find & replace script run: ./scripts/replace_import_paths.sh ${{ inputs.version }} - - name: Commit and push changes - uses: devops-infra/action-commit-push@master + - name: Create Pull Request + uses: peter-evans/create-pull-request@v4 with: - github_token: ${{ secrets.GITHUB_TOKEN }} - commit_message: "auto: update Go import paths to v${{ inputs.version }}" - target_branch: update-paths - - name: Open PR - uses: devops-infra/action-pull-request@v0.5.0 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - title: ${{ github.event.commits[0].message }} - source_branch: ${{ inputs.source-branch }} - target_branch: ${{ inputs.target-branch }} - assignee: ${{ github.actor }} - draft: true - label: T:auto,T:code-hygiene + token: ${{ secrets.ADD_TO_PROJECT_PAT }} + title: "auto: update Go import paths to v${{ inputs.version }}" + commit-message: "auto: update Go import paths to v${{ inputs.version }}" body: "**Automated pull request**\n\nUpdating Go import paths to v${{ inputs.version }}" - get_diff: true + base: ${{ inputs.target-branch }} + branch-suffix: random + branch: ${{ inputs.source-branch }} + delete-branch: true + assignees: ${{ github.actor }} + draft: true + labels: T:auto,T:code-hygiene diff --git a/scripts/replace_import_paths.sh b/scripts/replace_import_paths.sh index 45ef110daf2..7211bfb5534 100755 --- a/scripts/replace_import_paths.sh +++ b/scripts/replace_import_paths.sh @@ -1,5 +1,7 @@ #!/bin/bash +set -euo pipefail + NEXT_MAJOR_VERSION=$1 import_path_to_replace=$(go list -m) @@ -15,7 +17,7 @@ replace_paths() { sed -i "s/github.com\/osmosis-labs\/osmosis\/v${version_to_replace}/github.com\/osmosis-labs\/osmosis\/v${NEXT_MAJOR_VERSION}/g" ${file} } -# Replace all files within Go packages. +echo "Replacing import paths in Go files" for mod in $modules; do for file in $mod/*; do @@ -25,6 +27,20 @@ do done done -replace_paths "go.mod" +echo "Replacing import paths in proto files" +for file in $(find proto/osmosis -type f -name "*.proto"); do + replace_paths $file +done +# protocgen.sh +replace_paths "scripts/protocgen.sh" + +echo "Updating go.mod and vendoring" +# go.mod +replace_paths "go.mod" go mod vendor >/dev/null + +echo "running make proto-gen" +# ensure protos match generated Go files +# N.B.: This must be run after go mod vendor. +make proto-gen >/dev/null From 363192573d9f7a513b950da9b9699d51e92dc326 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sun, 17 Jul 2022 22:00:46 -0500 Subject: [PATCH 090/376] mutation script: minor changes (#2112) * Changes I made to mutation test script for it to work locally * add .gitignore --- .gitignore | 2 ++ Makefile | 2 +- scripts/mutation-test.sh | 3 +++ 3 files changed, 6 insertions(+), 1 deletion(-) mode change 100644 => 100755 scripts/mutation-test.sh diff --git a/.gitignore b/.gitignore index 445b336984d..191166787bd 100644 --- a/.gitignore +++ b/.gitignore @@ -204,3 +204,5 @@ tools-stamp /tests/localosmosis/.osmosisd/* *.save *.save.* + +mutation_test_result.txt \ No newline at end of file diff --git a/Makefile b/Makefile index 6eb060d1786..79a7f1e4f64 100644 --- a/Makefile +++ b/Makefile @@ -238,7 +238,7 @@ test-e2e-skip-upgrade: @VERSION=$(VERSION) OSMOSIS_E2E_SKIP_UPGRADE=True go test -mod=readonly -timeout=25m -v $(PACKAGES_E2E) test-mutation: - @sh scripts/mutation-test.sh + @bash scripts/mutation-test.sh benchmark: @go test -mod=readonly -bench=. $(PACKAGES_UNIT) diff --git a/scripts/mutation-test.sh b/scripts/mutation-test.sh old mode 100644 new mode 100755 index 350aa0d9c7c..7653a6551b1 --- a/scripts/mutation-test.sh +++ b/scripts/mutation-test.sh @@ -23,6 +23,9 @@ OUTPUT=$(go run github.com/zimmski/go-mutesting/cmd/go-mutesting --disable=$DISA RESULT=$(echo "$OUTPUT" | grep 'The mutation score') SCORE=$(echo "$RESULT" | grep -Eo '[[:digit:]]\.[[:digit:]]+') +echo "writing mutation test result to mutation_test_result.txt" +echo "$OUTPUT" > mutation_test_result.txt + echo $RESULT # Return a non-zero exit code if the score is below 75% From 1a99255c9f5c1684db3108f9d4e501a110fea065 Mon Sep 17 00:00:00 2001 From: Roman Date: Mon, 18 Jul 2022 09:36:09 -0400 Subject: [PATCH 091/376] chore(app/upgrades): set app version correctly for v11 (#2071) * chore(app/upgrades): set app version correctly for v11 * lint --- app/upgrades/v11/upgrades.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/app/upgrades/v11/upgrades.go b/app/upgrades/v11/upgrades.go index 58bf0897984..f7ec51f188e 100644 --- a/app/upgrades/v11/upgrades.go +++ b/app/upgrades/v11/upgrades.go @@ -9,6 +9,10 @@ import ( "github.com/osmosis-labs/osmosis/v7/app/upgrades" ) +// We set the app version to pre-upgrade because it will be incremented by one +// after the upgrade is applied by the handler. +const preUpgradeAppVersion = 10 + func CreateUpgradeHandler( mm *module.Manager, configurator module.Configurator, @@ -16,6 +20,13 @@ func CreateUpgradeHandler( keepers *keepers.AppKeepers, ) upgradetypes.UpgradeHandler { return func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + // Although the app version was already set during the v9 upgrade, our v10 was a fork. + // As a result, the upgrade handler was not executed to increment the app version. + // This change helps to correctly set the app version for v11. + if err := keepers.UpgradeKeeper.SetAppVersion(ctx, preUpgradeAppVersion); err != nil { + return nil, err + } + return mm.RunMigrations(ctx, configurator, fromVM) } } From 36a98c9f14b5cd8a66ba8222424e41507f2ac48b Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Mon, 18 Jul 2022 09:05:40 -0500 Subject: [PATCH 092/376] auto: update Go import paths to v10 (#2115) Co-authored-by: p0mvn Co-authored-by: Roman --- app/ante.go | 8 +- app/app.go | 28 +-- app/apptesting/gamm.go | 4 +- app/apptesting/test_suite.go | 10 +- app/config.go | 2 +- app/encoding.go | 2 +- app/keepers/keepers.go | 46 ++-- app/keepers/modules.go | 24 +- app/modules.go | 44 ++-- app/upgrades/types.go | 2 +- app/upgrades/v10/constants.go | 2 +- app/upgrades/v10/fork.go | 2 +- app/upgrades/v10/upgrades_test.go | 4 +- app/upgrades/v11/constants.go | 2 +- app/upgrades/v11/upgrades.go | 4 +- app/upgrades/v3/constants.go | 2 +- app/upgrades/v3/forks.go | 2 +- app/upgrades/v4/constants.go | 2 +- app/upgrades/v4/upgrade_test.go | 4 +- app/upgrades/v4/upgrades.go | 4 +- app/upgrades/v5/constants.go | 2 +- app/upgrades/v5/upgrades.go | 6 +- app/upgrades/v5/whitelist_feetokens.go | 4 +- app/upgrades/v6/constants.go | 2 +- app/upgrades/v6/forks.go | 2 +- app/upgrades/v7/constants.go | 4 +- app/upgrades/v7/upgrades.go | 8 +- app/upgrades/v8/constants.go | 4 +- app/upgrades/v8/forks.go | 2 +- app/upgrades/v8/incentive_props.go | 6 +- app/upgrades/v8/msg_filter_ante.go | 2 +- app/upgrades/v8/msg_filter_ante_test.go | 6 +- app/upgrades/v8/unpool_whitelist.go | 4 +- app/upgrades/v9/constants.go | 4 +- app/upgrades/v9/msg_filter_ante_test.go | 6 +- app/upgrades/v9/prop214.go | 4 +- app/upgrades/v9/prop214_test.go | 4 +- app/upgrades/v9/upgrades.go | 6 +- .../cmd/balances_from_state_export.go | 8 +- cmd/osmosisd/cmd/genesis.go | 10 +- cmd/osmosisd/cmd/root.go | 4 +- cmd/osmosisd/main.go | 6 +- go.mod | 4 +- osmomath/math_test.go | 2 +- osmoutils/partialord/internal/dag/dag_test.go | 2 +- osmoutils/partialord/partialord.go | 2 +- osmoutils/partialord/partialord_test.go | 2 +- proto/osmosis/epochs/genesis.proto | 2 +- proto/osmosis/epochs/query.proto | 2 +- .../pool-models/balancer/balancerPool.proto | 2 +- .../gamm/pool-models/balancer/tx/tx.proto | 2 +- .../stableswap/stableswap_pool.proto | 2 +- .../gamm/pool-models/stableswap/tx.proto | 2 +- proto/osmosis/gamm/v1beta1/genesis.proto | 2 +- proto/osmosis/gamm/v1beta1/query.proto | 2 +- proto/osmosis/gamm/v1beta1/tx.proto | 2 +- proto/osmosis/incentives/gauge.proto | 2 +- proto/osmosis/incentives/genesis.proto | 2 +- proto/osmosis/incentives/params.proto | 2 +- proto/osmosis/incentives/query.proto | 2 +- proto/osmosis/incentives/tx.proto | 2 +- proto/osmosis/lockup/genesis.proto | 2 +- proto/osmosis/lockup/lock.proto | 2 +- proto/osmosis/lockup/query.proto | 2 +- proto/osmosis/lockup/tx.proto | 2 +- proto/osmosis/mint/v1beta1/genesis.proto | 2 +- proto/osmosis/mint/v1beta1/mint.proto | 2 +- proto/osmosis/mint/v1beta1/query.proto | 2 +- .../pool-incentives/v1beta1/genesis.proto | 2 +- .../osmosis/pool-incentives/v1beta1/gov.proto | 2 +- .../pool-incentives/v1beta1/incentives.proto | 2 +- .../pool-incentives/v1beta1/query.proto | 2 +- proto/osmosis/store/v1beta1/tree.proto | 2 +- proto/osmosis/superfluid/genesis.proto | 2 +- proto/osmosis/superfluid/params.proto | 2 +- proto/osmosis/superfluid/query.proto | 2 +- proto/osmosis/superfluid/superfluid.proto | 2 +- proto/osmosis/superfluid/tx.proto | 2 +- proto/osmosis/superfluid/v1beta1/gov.proto | 2 +- .../v1beta1/authorityMetadata.proto | 2 +- .../tokenfactory/v1beta1/genesis.proto | 2 +- .../osmosis/tokenfactory/v1beta1/params.proto | 2 +- .../osmosis/tokenfactory/v1beta1/query.proto | 2 +- proto/osmosis/tokenfactory/v1beta1/tx.proto | 2 +- proto/osmosis/txfees/v1beta1/feetoken.proto | 2 +- proto/osmosis/txfees/v1beta1/genesis.proto | 2 +- proto/osmosis/txfees/v1beta1/gov.proto | 2 +- proto/osmosis/txfees/v1beta1/query.proto | 2 +- scripts/protocgen.sh | 2 +- simulation/executor/mock_tendermint.go | 2 +- simulation/executor/operation.go | 2 +- simulation/executor/params.go | 2 +- simulation/executor/simulate.go | 2 +- simulation/executor/simulate_dev.go | 2 +- simulation/executor/util.go | 2 +- simulation/types/manager.go | 2 +- simulation/types/randutil.go | 2 +- simulation/types/txbuilder.go | 2 +- store/legacy/v101/tree.go | 2 +- store/legacy/v101/tree_test.go | 4 +- store/tree.pb.go | 40 ++-- store/tree_test.go | 2 +- tests/e2e/configurer/base.go | 8 +- tests/e2e/configurer/chain/chain.go | 4 +- tests/e2e/configurer/chain/node.go | 4 +- tests/e2e/configurer/chain/queries.go | 4 +- tests/e2e/configurer/current.go | 6 +- tests/e2e/configurer/factory.go | 6 +- tests/e2e/configurer/upgrade.go | 8 +- tests/e2e/e2e_setup_test.go | 2 +- tests/e2e/e2e_test.go | 2 +- tests/e2e/initialization/chain/main.go | 2 +- tests/e2e/initialization/config.go | 16 +- tests/e2e/initialization/init.go | 2 +- tests/e2e/initialization/init_test.go | 2 +- tests/e2e/initialization/node.go | 4 +- tests/e2e/initialization/node/main.go | 2 +- tests/e2e/initialization/util.go | 2 +- tests/e2e/util/codec.go | 4 +- tests/simulator/genesis.go | 2 +- tests/simulator/sim_test.go | 6 +- tests/simulator/state.go | 4 +- wasmbinding/message_plugin.go | 10 +- wasmbinding/queries.go | 8 +- wasmbinding/query_plugin.go | 2 +- wasmbinding/test/custom_msg_test.go | 6 +- wasmbinding/test/custom_query_test.go | 8 +- wasmbinding/test/helpers_test.go | 2 +- wasmbinding/test/messages_test.go | 6 +- wasmbinding/test/queries_test.go | 4 +- wasmbinding/test/store_run_test.go | 2 +- wasmbinding/wasm.go | 4 +- x/epochs/client/cli/cli_test.go | 6 +- x/epochs/client/cli/query.go | 2 +- x/epochs/client/cli/tx.go | 2 +- x/epochs/keeper/abci.go | 2 +- x/epochs/keeper/abci_test.go | 6 +- x/epochs/keeper/epoch.go | 2 +- x/epochs/keeper/epoch_test.go | 2 +- x/epochs/keeper/genesis.go | 2 +- x/epochs/keeper/genesis_test.go | 4 +- x/epochs/keeper/grpc_query.go | 2 +- x/epochs/keeper/grpc_query_test.go | 2 +- x/epochs/keeper/keeper.go | 2 +- x/epochs/keeper/keeper_test.go | 4 +- x/epochs/module.go | 8 +- x/epochs/types/genesis.pb.go | 58 ++--- x/epochs/types/hooks.go | 2 +- x/epochs/types/hooks_test.go | 4 +- x/epochs/types/query.pb.go | 48 ++-- x/gamm/client/cli/cli_test.go | 12 +- x/gamm/client/cli/query.go | 4 +- x/gamm/client/cli/tx.go | 4 +- x/gamm/client/testutil/test_helpers.go | 2 +- x/gamm/keeper/export_test.go | 2 +- x/gamm/keeper/gas_test.go | 6 +- x/gamm/keeper/genesis.go | 2 +- x/gamm/keeper/genesis_test | 8 +- x/gamm/keeper/grpc_query.go | 4 +- x/gamm/keeper/grpc_query_test.go | 2 +- x/gamm/keeper/internal/events/emit.go | 2 +- x/gamm/keeper/internal/events/emit_test.go | 6 +- x/gamm/keeper/invariants.go | 2 +- x/gamm/keeper/keeper.go | 2 +- x/gamm/keeper/keeper_test.go | 8 +- x/gamm/keeper/marshal_bench_test.go | 8 +- x/gamm/keeper/msg_server.go | 4 +- x/gamm/keeper/msg_server_test.go | 4 +- x/gamm/keeper/multihop.go | 2 +- x/gamm/keeper/multihop_test.go | 2 +- x/gamm/keeper/params.go | 2 +- x/gamm/keeper/pool.go | 6 +- x/gamm/keeper/pool_service.go | 2 +- x/gamm/keeper/pool_service_test.go | 6 +- x/gamm/keeper/pool_test.go | 2 +- x/gamm/keeper/share.go | 4 +- x/gamm/keeper/swap.go | 4 +- x/gamm/keeper/swap_test.go | 4 +- x/gamm/keeper/total_liquidity.go | 2 +- x/gamm/module.go | 12 +- x/gamm/pool-models/balancer/amm.go | 4 +- x/gamm/pool-models/balancer/amm_test.go | 4 +- .../pool-models/balancer/balancerPool.pb.go | 104 ++++----- x/gamm/pool-models/balancer/codec.go | 2 +- x/gamm/pool-models/balancer/marshal_test.go | 2 +- x/gamm/pool-models/balancer/msgs.go | 2 +- x/gamm/pool-models/balancer/msgs_test.go | 4 +- x/gamm/pool-models/balancer/pool.go | 6 +- x/gamm/pool-models/balancer/pool_asset.go | 2 +- x/gamm/pool-models/balancer/pool_params.go | 2 +- .../pool-models/balancer/pool_suite_test.go | 10 +- x/gamm/pool-models/balancer/pool_test.go | 6 +- x/gamm/pool-models/balancer/tx.pb.go | 54 ++--- x/gamm/pool-models/balancer/util_test.go | 6 +- x/gamm/pool-models/internal/cfmm_common/lp.go | 4 +- .../internal/cfmm_common/lp_test.go | 8 +- .../internal/test_helpers/test_helpers.go | 4 +- x/gamm/pool-models/stableswap/amm.go | 4 +- x/gamm/pool-models/stableswap/amm_test.go | 2 +- x/gamm/pool-models/stableswap/codec.go | 2 +- x/gamm/pool-models/stableswap/msgs.go | 2 +- x/gamm/pool-models/stableswap/msgs_test.go | 4 +- x/gamm/pool-models/stableswap/pool.go | 4 +- x/gamm/pool-models/stableswap/pool_params.go | 2 +- .../stableswap/stableswap_pool.pb.go | 82 +++---- x/gamm/pool-models/stableswap/tx.pb.go | 74 +++--- x/gamm/pool-models/stableswap/util_test.go | 2 +- x/gamm/simulation/sim_msgs.go | 10 +- x/gamm/twap/hook_listener.go | 2 +- x/gamm/twap/module.go | 6 +- x/gamm/types/genesis.pb.go | 49 ++-- x/gamm/types/msgs_test.go | 2 +- x/gamm/types/params.go | 2 +- x/gamm/types/query.pb.go | 162 ++++++------- x/gamm/types/tx.pb.go | 139 ++++++------ x/incentives/client/cli/cli_test.go | 12 +- x/incentives/client/cli/query.go | 4 +- x/incentives/client/cli/tx.go | 4 +- x/incentives/keeper/bench_test.go | 6 +- x/incentives/keeper/distribute.go | 4 +- x/incentives/keeper/distribute_test.go | 4 +- x/incentives/keeper/export_test.go | 2 +- x/incentives/keeper/gauge.go | 6 +- x/incentives/keeper/gauge_test.go | 4 +- x/incentives/keeper/genesis.go | 2 +- x/incentives/keeper/genesis_test.go | 6 +- x/incentives/keeper/grpc_query.go | 4 +- x/incentives/keeper/grpc_query_test.go | 6 +- x/incentives/keeper/hooks.go | 6 +- x/incentives/keeper/iterator.go | 4 +- x/incentives/keeper/keeper.go | 2 +- x/incentives/keeper/keeper_test.go | 4 +- x/incentives/keeper/msg_server.go | 4 +- x/incentives/keeper/params.go | 2 +- x/incentives/keeper/store.go | 2 +- x/incentives/keeper/suite_test.go | 4 +- x/incentives/keeper/utils.go | 2 +- x/incentives/keeper/utils_test.go | 2 +- x/incentives/module.go | 10 +- x/incentives/simulation/genesis.go | 2 +- x/incentives/simulation/operations.go | 8 +- x/incentives/types/expected_keepers.go | 4 +- x/incentives/types/gauge.go | 2 +- x/incentives/types/gauge.pb.go | 70 +++--- x/incentives/types/genesis.pb.go | 46 ++-- x/incentives/types/msgs.go | 2 +- x/incentives/types/msgs_test.go | 2 +- x/incentives/types/params.go | 2 +- x/incentives/types/params.pb.go | 10 +- x/incentives/types/query.pb.go | 143 ++++++------ x/incentives/types/tx.pb.go | 80 +++---- x/lockup/abci.go | 2 +- x/lockup/client/cli/cli_test.go | 10 +- x/lockup/client/cli/query.go | 2 +- x/lockup/client/cli/tx.go | 2 +- x/lockup/client/rest/query.go | 2 +- x/lockup/client/rest/tx.go | 2 +- x/lockup/client/testutil/test_helpers.go | 2 +- x/lockup/keeper/admin_keeper.go | 2 +- x/lockup/keeper/admin_keeper_test.go | 2 +- x/lockup/keeper/bench_test.go | 4 +- x/lockup/keeper/export_test.go | 2 +- x/lockup/keeper/genesis.go | 2 +- x/lockup/keeper/genesis_test.go | 6 +- x/lockup/keeper/grpc_query.go | 2 +- x/lockup/keeper/grpc_query_test.go | 2 +- x/lockup/keeper/invariants.go | 2 +- x/lockup/keeper/iterator.go | 2 +- x/lockup/keeper/keeper.go | 2 +- x/lockup/keeper/keeper_test.go | 6 +- x/lockup/keeper/lock.go | 4 +- x/lockup/keeper/lock_refs.go | 2 +- x/lockup/keeper/lock_test.go | 2 +- x/lockup/keeper/migration.go | 2 +- x/lockup/keeper/migration_test.go | 2 +- x/lockup/keeper/msg_server.go | 4 +- x/lockup/keeper/msg_server_test.go | 4 +- x/lockup/keeper/store.go | 2 +- x/lockup/keeper/synthetic_lock.go | 2 +- x/lockup/keeper/synthetic_lock_test.go | 2 +- x/lockup/keeper/utils.go | 2 +- x/lockup/keeper/utils_test.go | 2 +- x/lockup/module.go | 12 +- x/lockup/simulation/operations.go | 8 +- x/lockup/types/genesis.pb.go | 12 +- x/lockup/types/lock.pb.go | 72 +++--- x/lockup/types/query.pb.go | 182 +++++++-------- x/lockup/types/tx.pb.go | 76 +++---- x/mint/client/cli/cli_test.go | 4 +- x/mint/client/cli/query.go | 2 +- x/mint/client/rest/grpc_query_test.go | 4 +- x/mint/client/rest/query.go | 2 +- x/mint/keeper/export_test.go | 2 +- x/mint/keeper/genesis.go | 2 +- x/mint/keeper/genesis_test.go | 6 +- x/mint/keeper/grpc_query.go | 2 +- x/mint/keeper/grpc_query_test.go | 2 +- x/mint/keeper/hooks.go | 4 +- x/mint/keeper/hooks_test.go | 8 +- x/mint/keeper/keeper.go | 4 +- x/mint/keeper/keeper_test.go | 12 +- x/mint/module.go | 10 +- x/mint/simulation/decoder.go | 2 +- x/mint/simulation/decoder_test.go | 6 +- x/mint/simulation/genesis.go | 2 +- x/mint/simulation/genesis_test.go | 4 +- x/mint/types/expected_keepers.go | 2 +- x/mint/types/genesis.pb.go | 12 +- x/mint/types/mint.pb.go | 94 ++++---- x/mint/types/minter_test.go | 2 +- x/mint/types/params.go | 2 +- x/mint/types/query.pb.go | 50 ++--- x/pool-incentives/client/cli/cli_test.go | 6 +- x/pool-incentives/client/cli/query.go | 2 +- x/pool-incentives/client/cli/tx.go | 4 +- x/pool-incentives/client/proposal_handler.go | 4 +- x/pool-incentives/client/rest/tx.go | 2 +- x/pool-incentives/handler.go | 4 +- x/pool-incentives/keeper/distr.go | 2 +- x/pool-incentives/keeper/distr_test.go | 4 +- x/pool-incentives/keeper/geneis_test.go | 6 +- x/pool-incentives/keeper/genesis.go | 2 +- x/pool-incentives/keeper/gov.go | 2 +- x/pool-incentives/keeper/grpc_query.go | 4 +- x/pool-incentives/keeper/grpc_query_test.go | 6 +- x/pool-incentives/keeper/hooks.go | 4 +- x/pool-incentives/keeper/keeper.go | 8 +- x/pool-incentives/keeper/keeper_test.go | 6 +- x/pool-incentives/keeper/params.go | 2 +- x/pool-incentives/module.go | 6 +- x/pool-incentives/types/expected_keepers.go | 6 +- x/pool-incentives/types/genesis.pb.go | 40 ++-- x/pool-incentives/types/genesis_test.go | 2 +- x/pool-incentives/types/gov.pb.go | 10 +- x/pool-incentives/types/gov_test.go | 2 +- x/pool-incentives/types/incentives.pb.go | 58 ++--- x/pool-incentives/types/incentives_test.go | 2 +- x/pool-incentives/types/query.pb.go | 112 ++++----- x/pool-incentives/types/query_test.go | 2 +- x/pool-incentives/types/record_test.go | 2 +- x/superfluid/abci.go | 4 +- x/superfluid/client/cli/query.go | 2 +- x/superfluid/client/cli/tx.go | 2 +- x/superfluid/client/proposal_handler.go | 4 +- x/superfluid/keeper/distribution_test.go | 4 +- x/superfluid/keeper/edge_case_test.go | 2 +- x/superfluid/keeper/epoch.go | 10 +- x/superfluid/keeper/genesis.go | 2 +- x/superfluid/keeper/genesis_test.go | 6 +- x/superfluid/keeper/gov/gov.go | 4 +- x/superfluid/keeper/gov/gov_test.go | 8 +- x/superfluid/keeper/gov/suite_test.go | 4 +- x/superfluid/keeper/grpc_query.go | 6 +- x/superfluid/keeper/grpc_query_test.go | 2 +- x/superfluid/keeper/hooks.go | 4 +- x/superfluid/keeper/intermediary_account.go | 4 +- .../keeper/intermediary_account_test.go | 2 +- x/superfluid/keeper/invariants.go | 2 +- x/superfluid/keeper/keeper.go | 2 +- x/superfluid/keeper/keeper_test.go | 16 +- x/superfluid/keeper/msg_server.go | 8 +- x/superfluid/keeper/msg_server_test.go | 8 +- x/superfluid/keeper/params.go | 2 +- x/superfluid/keeper/slash.go | 4 +- x/superfluid/keeper/slash_test.go | 4 +- x/superfluid/keeper/stake.go | 6 +- x/superfluid/keeper/stake_test.go | 6 +- x/superfluid/keeper/superfluid_asset.go | 4 +- x/superfluid/keeper/superfluid_asset_store.go | 2 +- x/superfluid/keeper/superfluid_asset_test.go | 2 +- x/superfluid/keeper/synthetic_lock_wrapper.go | 2 +- x/superfluid/keeper/twap_price.go | 4 +- x/superfluid/keeper/twap_price_test.go | 2 +- x/superfluid/keeper/unpool.go | 6 +- x/superfluid/keeper/unpool_test.go | 8 +- x/superfluid/module.go | 10 +- x/superfluid/proposal_handler.go | 6 +- x/superfluid/simulation/genesis.go | 2 +- x/superfluid/simulation/operations.go | 8 +- x/superfluid/simulation/proposals.go | 6 +- x/superfluid/types/expected_keepers.go | 8 +- x/superfluid/types/genesis.pb.go | 50 ++--- x/superfluid/types/gov.go | 2 +- x/superfluid/types/gov.pb.go | 12 +- x/superfluid/types/params.pb.go | 12 +- x/superfluid/types/query.pb.go | 212 +++++++++--------- x/superfluid/types/superfluid.pb.go | 90 ++++---- x/superfluid/types/tx.pb.go | 76 +++---- x/tokenfactory/client/cli/query.go | 2 +- x/tokenfactory/client/cli/tx.go | 2 +- x/tokenfactory/keeper/admins.go | 2 +- x/tokenfactory/keeper/admins_test.go | 2 +- x/tokenfactory/keeper/bankactions.go | 2 +- x/tokenfactory/keeper/createdenom.go | 2 +- x/tokenfactory/keeper/createdenom_test.go | 2 +- x/tokenfactory/keeper/genesis.go | 2 +- x/tokenfactory/keeper/genesis_test.go | 2 +- x/tokenfactory/keeper/grpc_query.go | 2 +- x/tokenfactory/keeper/keeper.go | 2 +- x/tokenfactory/keeper/keeper_test.go | 6 +- x/tokenfactory/keeper/msg_server.go | 2 +- x/tokenfactory/keeper/params.go | 2 +- x/tokenfactory/module.go | 6 +- x/tokenfactory/types/authorityMetadata.pb.go | 10 +- x/tokenfactory/types/denoms_test.go | 4 +- x/tokenfactory/types/genesis.pb.go | 12 +- x/tokenfactory/types/genesis_test.go | 2 +- x/tokenfactory/types/params.go | 2 +- x/tokenfactory/types/params.pb.go | 40 ++-- x/tokenfactory/types/query.pb.go | 74 +++--- x/tokenfactory/types/tx.pb.go | 60 ++--- x/txfees/client/cli/query.go | 2 +- x/txfees/client/cli/tx.go | 2 +- x/txfees/handler.go | 4 +- x/txfees/keeper/feedecorator.go | 4 +- x/txfees/keeper/feedecorator_test.go | 4 +- x/txfees/keeper/feetokens.go | 2 +- x/txfees/keeper/feetokens_test.go | 2 +- x/txfees/keeper/genesis.go | 2 +- x/txfees/keeper/gov.go | 2 +- x/txfees/keeper/grpc_query.go | 2 +- x/txfees/keeper/hooks.go | 6 +- x/txfees/keeper/hooks_test.go | 4 +- x/txfees/keeper/keeper.go | 2 +- x/txfees/keeper/keeper_test.go | 6 +- x/txfees/keeper/txfee_filters/arb_tx.go | 2 +- x/txfees/module.go | 6 +- x/txfees/module_test.go | 2 +- x/txfees/types/expected_keepers.go | 2 +- x/txfees/types/feetoken.pb.go | 12 +- x/txfees/types/genesis.pb.go | 12 +- x/txfees/types/gov.pb.go | 12 +- x/txfees/types/query.pb.go | 76 +++---- 433 files changed, 2104 insertions(+), 2101 deletions(-) diff --git a/app/ante.go b/app/ante.go index ba999fc802a..cb3d70fa381 100644 --- a/app/ante.go +++ b/app/ante.go @@ -11,11 +11,11 @@ import ( ante "github.com/cosmos/cosmos-sdk/x/auth/ante" "github.com/cosmos/cosmos-sdk/x/auth/signing" - osmoante "github.com/osmosis-labs/osmosis/v7/ante" - v9 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v9" + osmoante "github.com/osmosis-labs/osmosis/v10/ante" + v9 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v9" - txfeeskeeper "github.com/osmosis-labs/osmosis/v7/x/txfees/keeper" - txfeestypes "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + txfeeskeeper "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper" + txfeestypes "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) // Link to default ante handler used by cosmos sdk: diff --git a/app/app.go b/app/app.go index 7c1c9b58829..cc3db5234ec 100644 --- a/app/app.go +++ b/app/app.go @@ -39,20 +39,20 @@ import ( "github.com/cosmos/cosmos-sdk/x/crisis" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" - appparams "github.com/osmosis-labs/osmosis/v7/app/params" - "github.com/osmosis-labs/osmosis/v7/app/upgrades" - v10 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v10" - v11 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v11" - v3 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v3" - v4 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v4" - v5 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v5" - v6 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v6" - v7 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v7" - v8 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v8" - v9 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v9" - _ "github.com/osmosis-labs/osmosis/v7/client/docs/statik" - simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" + "github.com/osmosis-labs/osmosis/v10/app/keepers" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" + v10 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v10" + v11 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v11" + v3 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v3" + v4 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v4" + v5 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v5" + v6 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v6" + v7 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v7" + v8 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v8" + v9 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v9" + _ "github.com/osmosis-labs/osmosis/v10/client/docs/statik" + simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" ) const appName = "OsmosisApp" diff --git a/app/apptesting/gamm.go b/app/apptesting/gamm.go index 556efb75358..87a43c74f84 100644 --- a/app/apptesting/gamm.go +++ b/app/apptesting/gamm.go @@ -3,8 +3,8 @@ package apptesting import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var DefaultAcctFunds sdk.Coins = sdk.NewCoins( diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index 0e892295587..4cb5a7c7d34 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -23,11 +23,11 @@ import ( tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - lockupkeeper "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + lockupkeeper "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) type KeeperTestHelper struct { diff --git a/app/config.go b/app/config.go index 72e8975ef0d..fd27d842870 100644 --- a/app/config.go +++ b/app/config.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/osmosis-labs/osmosis/v7/app/params" + "github.com/osmosis-labs/osmosis/v10/app/params" dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/baseapp" diff --git a/app/encoding.go b/app/encoding.go index 809483a93d4..b2178eb0ebb 100644 --- a/app/encoding.go +++ b/app/encoding.go @@ -1,7 +1,7 @@ package app import ( - "github.com/osmosis-labs/osmosis/v7/app/params" + "github.com/osmosis-labs/osmosis/v10/app/params" "github.com/cosmos/cosmos-sdk/std" ) diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index 180fc6d2baf..cbd1b94e616 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -47,29 +47,29 @@ import ( // IBC Transfer: Defines the "transfer" IBC port transfer "github.com/cosmos/ibc-go/v3/modules/apps/transfer" - _ "github.com/osmosis-labs/osmosis/v7/client/docs/statik" - owasm "github.com/osmosis-labs/osmosis/v7/wasmbinding" - epochskeeper "github.com/osmosis-labs/osmosis/v7/x/epochs/keeper" - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - gammkeeper "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - incentiveskeeper "github.com/osmosis-labs/osmosis/v7/x/incentives/keeper" - incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockupkeeper "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - mintkeeper "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" - poolincentives "github.com/osmosis-labs/osmosis/v7/x/pool-incentives" - poolincentiveskeeper "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/keeper" - poolincentivestypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid" - superfluidkeeper "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" - tokenfactorykeeper "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/keeper" - tokenfactorytypes "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" - "github.com/osmosis-labs/osmosis/v7/x/txfees" - txfeeskeeper "github.com/osmosis-labs/osmosis/v7/x/txfees/keeper" - txfeestypes "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + _ "github.com/osmosis-labs/osmosis/v10/client/docs/statik" + owasm "github.com/osmosis-labs/osmosis/v10/wasmbinding" + epochskeeper "github.com/osmosis-labs/osmosis/v10/x/epochs/keeper" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + gammkeeper "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + incentiveskeeper "github.com/osmosis-labs/osmosis/v10/x/incentives/keeper" + incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockupkeeper "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + mintkeeper "github.com/osmosis-labs/osmosis/v10/x/mint/keeper" + minttypes "github.com/osmosis-labs/osmosis/v10/x/mint/types" + poolincentives "github.com/osmosis-labs/osmosis/v10/x/pool-incentives" + poolincentiveskeeper "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/keeper" + poolincentivestypes "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid" + superfluidkeeper "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + superfluidtypes "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" + tokenfactorykeeper "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" + tokenfactorytypes "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees" + txfeeskeeper "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper" + txfeestypes "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) type AppKeepers struct { diff --git a/app/keepers/modules.go b/app/keepers/modules.go index 83af806ebdf..cf6555b3252 100644 --- a/app/keepers/modules.go +++ b/app/keepers/modules.go @@ -27,18 +27,18 @@ import ( upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" ica "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts" - _ "github.com/osmosis-labs/osmosis/v7/client/docs/statik" - "github.com/osmosis-labs/osmosis/v7/x/epochs" - "github.com/osmosis-labs/osmosis/v7/x/gamm" - "github.com/osmosis-labs/osmosis/v7/x/incentives" - "github.com/osmosis-labs/osmosis/v7/x/lockup" - "github.com/osmosis-labs/osmosis/v7/x/mint" - poolincentives "github.com/osmosis-labs/osmosis/v7/x/pool-incentives" - poolincentivesclient "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/client" - superfluid "github.com/osmosis-labs/osmosis/v7/x/superfluid" - superfluidclient "github.com/osmosis-labs/osmosis/v7/x/superfluid/client" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory" - "github.com/osmosis-labs/osmosis/v7/x/txfees" + _ "github.com/osmosis-labs/osmosis/v10/client/docs/statik" + "github.com/osmosis-labs/osmosis/v10/x/epochs" + "github.com/osmosis-labs/osmosis/v10/x/gamm" + "github.com/osmosis-labs/osmosis/v10/x/incentives" + "github.com/osmosis-labs/osmosis/v10/x/lockup" + "github.com/osmosis-labs/osmosis/v10/x/mint" + poolincentives "github.com/osmosis-labs/osmosis/v10/x/pool-incentives" + poolincentivesclient "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/client" + superfluid "github.com/osmosis-labs/osmosis/v10/x/superfluid" + superfluidclient "github.com/osmosis-labs/osmosis/v10/x/superfluid/client" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory" + "github.com/osmosis-labs/osmosis/v10/x/txfees" ) // AppModuleBasics returns ModuleBasics for the module BasicManager. diff --git a/app/modules.go b/app/modules.go index b30332e45b0..b3ed20189ce 100644 --- a/app/modules.go +++ b/app/modules.go @@ -40,28 +40,28 @@ import ( "github.com/cosmos/cosmos-sdk/x/upgrade" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - appparams "github.com/osmosis-labs/osmosis/v7/app/params" - _ "github.com/osmosis-labs/osmosis/v7/client/docs/statik" - "github.com/osmosis-labs/osmosis/v7/osmoutils/partialord" - simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" - "github.com/osmosis-labs/osmosis/v7/x/epochs" - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - "github.com/osmosis-labs/osmosis/v7/x/incentives" - incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - "github.com/osmosis-labs/osmosis/v7/x/lockup" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/mint" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" - poolincentives "github.com/osmosis-labs/osmosis/v7/x/pool-incentives" - poolincentivestypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" - superfluid "github.com/osmosis-labs/osmosis/v7/x/superfluid" - superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory" - tokenfactorytypes "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" - "github.com/osmosis-labs/osmosis/v7/x/txfees" - txfeestypes "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" + _ "github.com/osmosis-labs/osmosis/v10/client/docs/statik" + "github.com/osmosis-labs/osmosis/v10/osmoutils/partialord" + simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives" + incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/mint" + minttypes "github.com/osmosis-labs/osmosis/v10/x/mint/types" + poolincentives "github.com/osmosis-labs/osmosis/v10/x/pool-incentives" + poolincentivestypes "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" + superfluid "github.com/osmosis-labs/osmosis/v10/x/superfluid" + superfluidtypes "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory" + tokenfactorytypes "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees" + txfeestypes "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) // moduleAccountPermissions defines module account permissions diff --git a/app/upgrades/types.go b/app/upgrades/types.go index 02e715e1dad..8b03250a634 100644 --- a/app/upgrades/types.go +++ b/app/upgrades/types.go @@ -7,7 +7,7 @@ import ( upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" abci "github.com/tendermint/tendermint/abci/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/keepers" ) // BaseAppParamManager defines an interrace that BaseApp is expected to fullfil diff --git a/app/upgrades/v10/constants.go b/app/upgrades/v10/constants.go index 21c1bac4650..db6c9ff5f02 100644 --- a/app/upgrades/v10/constants.go +++ b/app/upgrades/v10/constants.go @@ -1,7 +1,7 @@ package v10 import ( - "github.com/osmosis-labs/osmosis/v7/app/upgrades" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" ) // Last executed block on the v9 code was 4713064. diff --git a/app/upgrades/v10/fork.go b/app/upgrades/v10/fork.go index 6e0444dce6e..d7f2b409739 100644 --- a/app/upgrades/v10/fork.go +++ b/app/upgrades/v10/fork.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/keepers" ) func RunForkLogic(ctx sdk.Context, appKeepers *keepers.AppKeepers) { diff --git a/app/upgrades/v10/upgrades_test.go b/app/upgrades/v10/upgrades_test.go index 2f072445639..d5ced00644c 100644 --- a/app/upgrades/v10/upgrades_test.go +++ b/app/upgrades/v10/upgrades_test.go @@ -6,8 +6,8 @@ import ( "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - v10 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v10" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + v10 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v10" ) type UpgradeTestSuite struct { diff --git a/app/upgrades/v11/constants.go b/app/upgrades/v11/constants.go index 4b0e8f2aded..fa9fa4455c7 100644 --- a/app/upgrades/v11/constants.go +++ b/app/upgrades/v11/constants.go @@ -1,7 +1,7 @@ package v11 import ( - "github.com/osmosis-labs/osmosis/v7/app/upgrades" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" store "github.com/cosmos/cosmos-sdk/store/types" ) diff --git a/app/upgrades/v11/upgrades.go b/app/upgrades/v11/upgrades.go index f7ec51f188e..be6e5c21cba 100644 --- a/app/upgrades/v11/upgrades.go +++ b/app/upgrades/v11/upgrades.go @@ -5,8 +5,8 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" - "github.com/osmosis-labs/osmosis/v7/app/upgrades" + "github.com/osmosis-labs/osmosis/v10/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" ) // We set the app version to pre-upgrade because it will be incremented by one diff --git a/app/upgrades/v3/constants.go b/app/upgrades/v3/constants.go index 6d47d6677ba..f206b506cb1 100644 --- a/app/upgrades/v3/constants.go +++ b/app/upgrades/v3/constants.go @@ -1,6 +1,6 @@ package v3 -import "github.com/osmosis-labs/osmosis/v7/app/upgrades" +import "github.com/osmosis-labs/osmosis/v10/app/upgrades" const ( // UpgradeName defines the on-chain upgrade name for the Osmosis v3 upgrade. diff --git a/app/upgrades/v3/forks.go b/app/upgrades/v3/forks.go index 28fac0d1a32..ce23aab4de1 100644 --- a/app/upgrades/v3/forks.go +++ b/app/upgrades/v3/forks.go @@ -5,7 +5,7 @@ import ( govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/osmosis-labs/osmosis/v7/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/keepers" ) // RunForkLogic executes height-gated on-chain fork logic for the Osmosis v3 diff --git a/app/upgrades/v4/constants.go b/app/upgrades/v4/constants.go index 33654160b88..2557e2f6f2b 100644 --- a/app/upgrades/v4/constants.go +++ b/app/upgrades/v4/constants.go @@ -1,7 +1,7 @@ package v4 import ( - "github.com/osmosis-labs/osmosis/v7/app/upgrades" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" store "github.com/cosmos/cosmos-sdk/store/types" ) diff --git a/app/upgrades/v4/upgrade_test.go b/app/upgrades/v4/upgrade_test.go index 0f66dd3dfea..f0ffb4b44f0 100644 --- a/app/upgrades/v4/upgrade_test.go +++ b/app/upgrades/v4/upgrade_test.go @@ -11,8 +11,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/osmosis-labs/osmosis/v7/app" - v4 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v4" + "github.com/osmosis-labs/osmosis/v10/app" + v4 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v4" sdk "github.com/cosmos/cosmos-sdk/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" diff --git a/app/upgrades/v4/upgrades.go b/app/upgrades/v4/upgrades.go index eac31d0abf5..f2b4e2266b0 100644 --- a/app/upgrades/v4/upgrades.go +++ b/app/upgrades/v4/upgrades.go @@ -5,8 +5,8 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" - "github.com/osmosis-labs/osmosis/v7/app/upgrades" + "github.com/osmosis-labs/osmosis/v10/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" ) // CreateUpgradeHandler returns an x/upgrade handler for the Osmosis v4 on-chain diff --git a/app/upgrades/v5/constants.go b/app/upgrades/v5/constants.go index 39dfb39105c..661f22ad5a2 100644 --- a/app/upgrades/v5/constants.go +++ b/app/upgrades/v5/constants.go @@ -1,7 +1,7 @@ package v5 import ( - "github.com/osmosis-labs/osmosis/v7/app/upgrades" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" store "github.com/cosmos/cosmos-sdk/store/types" ) diff --git a/app/upgrades/v5/upgrades.go b/app/upgrades/v5/upgrades.go index efb21a5c1f8..3a00ae37d9c 100644 --- a/app/upgrades/v5/upgrades.go +++ b/app/upgrades/v5/upgrades.go @@ -10,9 +10,9 @@ import ( "github.com/cosmos/cosmos-sdk/x/authz" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" - "github.com/osmosis-labs/osmosis/v7/app/upgrades" - txfeestypes "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" + txfeestypes "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) func CreateUpgradeHandler( diff --git a/app/upgrades/v5/whitelist_feetokens.go b/app/upgrades/v5/whitelist_feetokens.go index 2345ea81559..28ad342e24b 100644 --- a/app/upgrades/v5/whitelist_feetokens.go +++ b/app/upgrades/v5/whitelist_feetokens.go @@ -7,8 +7,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - gammkeeper "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + gammkeeper "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) // Every asset with a liquid osmo pairing pool on Osmosis, as of 12/01/21 diff --git a/app/upgrades/v6/constants.go b/app/upgrades/v6/constants.go index 83b26923a11..e1d05d1df80 100644 --- a/app/upgrades/v6/constants.go +++ b/app/upgrades/v6/constants.go @@ -1,6 +1,6 @@ package v6 -import "github.com/osmosis-labs/osmosis/v7/app/upgrades" +import "github.com/osmosis-labs/osmosis/v10/app/upgrades" const ( // UpgradeName defines the on-chain upgrade name for the Osmosis v6 upgrade. diff --git a/app/upgrades/v6/forks.go b/app/upgrades/v6/forks.go index f51eee496e4..1bdaa11d759 100644 --- a/app/upgrades/v6/forks.go +++ b/app/upgrades/v6/forks.go @@ -3,7 +3,7 @@ package v6 import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/keepers" ) // RunForkLogic executes height-gated on-chain fork logic for the Osmosis v6 diff --git a/app/upgrades/v7/constants.go b/app/upgrades/v7/constants.go index f561859b2cc..2e2b94785a0 100644 --- a/app/upgrades/v7/constants.go +++ b/app/upgrades/v7/constants.go @@ -3,8 +3,8 @@ package v7 import ( "github.com/CosmWasm/wasmd/x/wasm" - "github.com/osmosis-labs/osmosis/v7/app/upgrades" - superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" + superfluidtypes "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" store "github.com/cosmos/cosmos-sdk/store/types" ) diff --git a/app/upgrades/v7/upgrades.go b/app/upgrades/v7/upgrades.go index c07ac041470..3222f6226a7 100644 --- a/app/upgrades/v7/upgrades.go +++ b/app/upgrades/v7/upgrades.go @@ -7,10 +7,10 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" - "github.com/osmosis-labs/osmosis/v7/app/upgrades" - lockupkeeper "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" + lockupkeeper "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" + superfluidtypes "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) func CreateUpgradeHandler( diff --git a/app/upgrades/v8/constants.go b/app/upgrades/v8/constants.go index a0fc2128ecb..933e1c496b3 100644 --- a/app/upgrades/v8/constants.go +++ b/app/upgrades/v8/constants.go @@ -1,8 +1,8 @@ package v8 import ( - "github.com/osmosis-labs/osmosis/v7/app/upgrades" - v8constants "github.com/osmosis-labs/osmosis/v7/app/upgrades/v8/constants" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" + v8constants "github.com/osmosis-labs/osmosis/v10/app/upgrades/v8/constants" ) const ( diff --git a/app/upgrades/v8/forks.go b/app/upgrades/v8/forks.go index 025ef17e77f..3ddc37ef71f 100644 --- a/app/upgrades/v8/forks.go +++ b/app/upgrades/v8/forks.go @@ -3,7 +3,7 @@ package v8 import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/keepers" ) // RunForkLogic executes height-gated on-chain fork logic for the Osmosis v8 diff --git a/app/upgrades/v8/incentive_props.go b/app/upgrades/v8/incentive_props.go index 07ba90d918e..a0563c42799 100644 --- a/app/upgrades/v8/incentive_props.go +++ b/app/upgrades/v8/incentive_props.go @@ -2,9 +2,9 @@ package v8 import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - poolincentiveskeeper "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/keeper" - poolincentivestypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + poolincentiveskeeper "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/keeper" + poolincentivestypes "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) // This file implements logic for accelerated incentive proposals. diff --git a/app/upgrades/v8/msg_filter_ante.go b/app/upgrades/v8/msg_filter_ante.go index 056ad4ac0bb..ff32df8cc47 100644 --- a/app/upgrades/v8/msg_filter_ante.go +++ b/app/upgrades/v8/msg_filter_ante.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + superfluidtypes "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) // MsgFilterDecorator defines an AnteHandler decorator for the v8 upgrade that diff --git a/app/upgrades/v8/msg_filter_ante_test.go b/app/upgrades/v8/msg_filter_ante_test.go index f3082ab59d8..202cb029893 100644 --- a/app/upgrades/v8/msg_filter_ante_test.go +++ b/app/upgrades/v8/msg_filter_ante_test.go @@ -7,9 +7,9 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/app" - v8 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v8" - superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/app" + v8 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v8" + superfluidtypes "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) func noOpAnteDecorator() sdk.AnteHandler { diff --git a/app/upgrades/v8/unpool_whitelist.go b/app/upgrades/v8/unpool_whitelist.go index 7ecb1ce43f7..9131715f77c 100644 --- a/app/upgrades/v8/unpool_whitelist.go +++ b/app/upgrades/v8/unpool_whitelist.go @@ -5,8 +5,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - gammkeeper "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - superfluidkeeper "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" + gammkeeper "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + superfluidkeeper "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" ) const ustDenom = "ibc/BE1BB42D4BE3C30D50B68D7C41DB4DFCE9678E8EF8C539F6E6A9345048894FCC" diff --git a/app/upgrades/v9/constants.go b/app/upgrades/v9/constants.go index 791e83fd329..32d78d07b3e 100644 --- a/app/upgrades/v9/constants.go +++ b/app/upgrades/v9/constants.go @@ -1,13 +1,13 @@ package v9 import ( - "github.com/osmosis-labs/osmosis/v7/app/upgrades" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" store "github.com/cosmos/cosmos-sdk/store/types" icahosttypes "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts/host/types" - tokenfactorytypes "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + tokenfactorytypes "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) // UpgradeName defines the on-chain upgrade name for the Osmosis v9 upgrade. diff --git a/app/upgrades/v9/msg_filter_ante_test.go b/app/upgrades/v9/msg_filter_ante_test.go index 0a3d9b5fee5..a6ff7f34aee 100644 --- a/app/upgrades/v9/msg_filter_ante_test.go +++ b/app/upgrades/v9/msg_filter_ante_test.go @@ -9,9 +9,9 @@ import ( ibcchanneltypes "github.com/cosmos/ibc-go/v3/modules/core/04-channel/types" - "github.com/osmosis-labs/osmosis/v7/app" - v8 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v8" - v9 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v9" + "github.com/osmosis-labs/osmosis/v10/app" + v8 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v8" + v9 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v9" ) func noOpAnteDecorator() sdk.AnteHandler { diff --git a/app/upgrades/v9/prop214.go b/app/upgrades/v9/prop214.go index 7458c9eded7..c6d482065fe 100644 --- a/app/upgrades/v9/prop214.go +++ b/app/upgrades/v9/prop214.go @@ -3,8 +3,8 @@ package v9 import ( sdk "github.com/cosmos/cosmos-sdk/types" - gammkeeper "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" + gammkeeper "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" ) // Executes prop214, https://www.mintscan.io/osmosis/proposals/214 diff --git a/app/upgrades/v9/prop214_test.go b/app/upgrades/v9/prop214_test.go index 0fc62d6cb71..1c6ab54e1d7 100644 --- a/app/upgrades/v9/prop214_test.go +++ b/app/upgrades/v9/prop214_test.go @@ -5,8 +5,8 @@ import ( "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - v9 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v9" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + v9 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v9" ) type UpgradeTestSuite struct { diff --git a/app/upgrades/v9/upgrades.go b/app/upgrades/v9/upgrades.go index dfe54bde5aa..e412f928281 100644 --- a/app/upgrades/v9/upgrades.go +++ b/app/upgrades/v9/upgrades.go @@ -10,15 +10,15 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ica "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts" icacontrollertypes "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts/controller/types" icahosttypes "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts/host/types" icatypes "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts/types" - "github.com/osmosis-labs/osmosis/v7/app/keepers" - "github.com/osmosis-labs/osmosis/v7/app/upgrades" + "github.com/osmosis-labs/osmosis/v10/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" ) const preUpgradeAppVersion = 8 diff --git a/cmd/osmosisd/cmd/balances_from_state_export.go b/cmd/osmosisd/cmd/balances_from_state_export.go index 558f4a791ce..cfdfc50d679 100644 --- a/cmd/osmosisd/cmd/balances_from_state_export.go +++ b/cmd/osmosisd/cmd/balances_from_state_export.go @@ -11,10 +11,10 @@ import ( tmjson "github.com/tendermint/tendermint/libs/json" tmtypes "github.com/tendermint/tendermint/types" - appparams "github.com/osmosis-labs/osmosis/v7/app/params" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" diff --git a/cmd/osmosisd/cmd/genesis.go b/cmd/osmosisd/cmd/genesis.go index ba03b5e1ded..5fe5c764ae1 100644 --- a/cmd/osmosisd/cmd/genesis.go +++ b/cmd/osmosisd/cmd/genesis.go @@ -25,12 +25,12 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - appParams "github.com/osmosis-labs/osmosis/v7/app/params" + appParams "github.com/osmosis-labs/osmosis/v10/app/params" - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" - poolincentivestypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + minttypes "github.com/osmosis-labs/osmosis/v10/x/mint/types" + poolincentivestypes "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) //nolint:ineffassign diff --git a/cmd/osmosisd/cmd/root.go b/cmd/osmosisd/cmd/root.go index 2304d159b5e..62a6ff7f247 100644 --- a/cmd/osmosisd/cmd/root.go +++ b/cmd/osmosisd/cmd/root.go @@ -7,7 +7,7 @@ import ( "github.com/prometheus/client_golang/prometheus" - "github.com/osmosis-labs/osmosis/v7/app/params" + "github.com/osmosis-labs/osmosis/v10/app/params" "github.com/spf13/cast" "github.com/spf13/cobra" @@ -40,7 +40,7 @@ import ( "github.com/CosmWasm/wasmd/x/wasm" wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - osmosis "github.com/osmosis-labs/osmosis/v7/app" + osmosis "github.com/osmosis-labs/osmosis/v10/app" ) // NewRootCmd creates a new root command for simd. It is called once in the diff --git a/cmd/osmosisd/main.go b/cmd/osmosisd/main.go index 0a8f95b9834..5eb17ba3dba 100644 --- a/cmd/osmosisd/main.go +++ b/cmd/osmosisd/main.go @@ -5,9 +5,9 @@ import ( svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - osmosis "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/app/params" - "github.com/osmosis-labs/osmosis/v7/cmd/osmosisd/cmd" + osmosis "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/cmd/osmosisd/cmd" ) func main() { diff --git a/go.mod b/go.mod index 067730b5f42..c0e14c9b56f 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/osmosis-labs/osmosis/v7 +module github.com/osmosis-labs/osmosis/v10 go 1.18 @@ -71,7 +71,7 @@ require ( github.com/coinbase/rosetta-sdk-go v0.7.0 // indirect github.com/confio/ics23/go v0.7.0 // indirect github.com/containerd/continuity v0.3.0 // indirect - github.com/cosmos/btcutil v1.0.4 // indirect + github.com/cosmos/btcutil v1.0.4 github.com/cosmos/gorocksdb v1.2.0 // indirect github.com/cosmos/ledger-cosmos-go v0.11.1 // indirect github.com/cosmos/ledger-go v0.9.2 // indirect diff --git a/osmomath/math_test.go b/osmomath/math_test.go index b369db336b3..385c5e9c017 100644 --- a/osmomath/math_test.go +++ b/osmomath/math_test.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/osmoutils" + "github.com/osmosis-labs/osmosis/v10/osmoutils" "github.com/stretchr/testify/require" ) diff --git a/osmoutils/partialord/internal/dag/dag_test.go b/osmoutils/partialord/internal/dag/dag_test.go index ec99d230307..e7ae94769be 100644 --- a/osmoutils/partialord/internal/dag/dag_test.go +++ b/osmoutils/partialord/internal/dag/dag_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/osmoutils/partialord/internal/dag" + "github.com/osmosis-labs/osmosis/v10/osmoutils/partialord/internal/dag" ) type edge struct { diff --git a/osmoutils/partialord/partialord.go b/osmoutils/partialord/partialord.go index 0c302faf804..cc53c089ad2 100644 --- a/osmoutils/partialord/partialord.go +++ b/osmoutils/partialord/partialord.go @@ -3,7 +3,7 @@ package partialord import ( "sort" - "github.com/osmosis-labs/osmosis/v7/osmoutils/partialord/internal/dag" + "github.com/osmosis-labs/osmosis/v10/osmoutils/partialord/internal/dag" ) type PartialOrdering struct { diff --git a/osmoutils/partialord/partialord_test.go b/osmoutils/partialord/partialord_test.go index 9d44f901934..280c67bdf8a 100644 --- a/osmoutils/partialord/partialord_test.go +++ b/osmoutils/partialord/partialord_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/osmoutils/partialord" + "github.com/osmosis-labs/osmosis/v10/osmoutils/partialord" ) func TestAPI(t *testing.T) { diff --git a/proto/osmosis/epochs/genesis.proto b/proto/osmosis/epochs/genesis.proto index fda5903c0c7..c3e310a7df3 100644 --- a/proto/osmosis/epochs/genesis.proto +++ b/proto/osmosis/epochs/genesis.proto @@ -5,7 +5,7 @@ import "gogoproto/gogo.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/timestamp.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/epochs/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/epochs/types"; // EpochInfo is a struct that describes the data going into // a timer defined by the x/epochs module. diff --git a/proto/osmosis/epochs/query.proto b/proto/osmosis/epochs/query.proto index 0e4776a526f..6047dd482d8 100644 --- a/proto/osmosis/epochs/query.proto +++ b/proto/osmosis/epochs/query.proto @@ -6,7 +6,7 @@ import "google/api/annotations.proto"; import "cosmos/base/query/v1beta1/pagination.proto"; import "osmosis/epochs/genesis.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/epochs/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/epochs/types"; // Query defines the gRPC querier service. service Query { diff --git a/proto/osmosis/gamm/pool-models/balancer/balancerPool.proto b/proto/osmosis/gamm/pool-models/balancer/balancerPool.proto index 60f96f417e3..c2fb6ab9709 100644 --- a/proto/osmosis/gamm/pool-models/balancer/balancerPool.proto +++ b/proto/osmosis/gamm/pool-models/balancer/balancerPool.proto @@ -14,7 +14,7 @@ import "google/protobuf/timestamp.proto"; import "cosmos/auth/v1beta1/auth.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer"; // Parameters for changing the weights in a balancer pool smoothly from // a start weight and end weight over a period of time. diff --git a/proto/osmosis/gamm/pool-models/balancer/tx/tx.proto b/proto/osmosis/gamm/pool-models/balancer/tx/tx.proto index bb2a20641d3..edcaa7714e9 100644 --- a/proto/osmosis/gamm/pool-models/balancer/tx/tx.proto +++ b/proto/osmosis/gamm/pool-models/balancer/tx/tx.proto @@ -4,7 +4,7 @@ package osmosis.gamm.poolmodels.balancer.v1beta1; import "gogoproto/gogo.proto"; import "osmosis/gamm/pool-models/balancer/balancerPool.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer"; service Msg { rpc CreateBalancerPool(MsgCreateBalancerPool) diff --git a/proto/osmosis/gamm/pool-models/stableswap/stableswap_pool.proto b/proto/osmosis/gamm/pool-models/stableswap/stableswap_pool.proto index 9e625397b13..f73315a22b9 100644 --- a/proto/osmosis/gamm/pool-models/stableswap/stableswap_pool.proto +++ b/proto/osmosis/gamm/pool-models/stableswap/stableswap_pool.proto @@ -10,7 +10,7 @@ import "google/protobuf/timestamp.proto"; import "cosmos/auth/v1beta1/auth.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/stableswap"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/stableswap"; // PoolParams defined the parameters that will be managed by the pool // governance in the future. This params are not managed by the chain diff --git a/proto/osmosis/gamm/pool-models/stableswap/tx.proto b/proto/osmosis/gamm/pool-models/stableswap/tx.proto index d38b220cef4..eb53c86cd48 100644 --- a/proto/osmosis/gamm/pool-models/stableswap/tx.proto +++ b/proto/osmosis/gamm/pool-models/stableswap/tx.proto @@ -5,7 +5,7 @@ import "cosmos/base/v1beta1/coin.proto"; import "gogoproto/gogo.proto"; import "osmosis/gamm/pool-models/stableswap/stableswap_pool.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/stableswap"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/stableswap"; service Msg { rpc CreateStableswapPool(MsgCreateStableswapPool) diff --git a/proto/osmosis/gamm/v1beta1/genesis.proto b/proto/osmosis/gamm/v1beta1/genesis.proto index 4ef5340b1b7..bece17a3d6e 100644 --- a/proto/osmosis/gamm/v1beta1/genesis.proto +++ b/proto/osmosis/gamm/v1beta1/genesis.proto @@ -15,7 +15,7 @@ message Params { ]; } -option go_package = "github.com/osmosis-labs/osmosis/v7/x/gamm/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/gamm/types"; // GenesisState defines the gamm module's genesis state. message GenesisState { diff --git a/proto/osmosis/gamm/v1beta1/query.proto b/proto/osmosis/gamm/v1beta1/query.proto index 29db4073604..6f862e8b95e 100644 --- a/proto/osmosis/gamm/v1beta1/query.proto +++ b/proto/osmosis/gamm/v1beta1/query.proto @@ -10,7 +10,7 @@ import "google/api/annotations.proto"; import "google/protobuf/any.proto"; import "cosmos_proto/cosmos.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/gamm/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/gamm/types"; service Query { rpc Pools(QueryPoolsRequest) returns (QueryPoolsResponse) { diff --git a/proto/osmosis/gamm/v1beta1/tx.proto b/proto/osmosis/gamm/v1beta1/tx.proto index 950357b920f..8552c6e0110 100644 --- a/proto/osmosis/gamm/v1beta1/tx.proto +++ b/proto/osmosis/gamm/v1beta1/tx.proto @@ -4,7 +4,7 @@ package osmosis.gamm.v1beta1; import "gogoproto/gogo.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/gamm/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/gamm/types"; service Msg { rpc JoinPool(MsgJoinPool) returns (MsgJoinPoolResponse); diff --git a/proto/osmosis/incentives/gauge.proto b/proto/osmosis/incentives/gauge.proto index 1f5fd02a0dd..53e46c85840 100644 --- a/proto/osmosis/incentives/gauge.proto +++ b/proto/osmosis/incentives/gauge.proto @@ -7,7 +7,7 @@ import "google/protobuf/timestamp.proto"; import "cosmos/base/v1beta1/coin.proto"; import "osmosis/lockup/lock.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/incentives/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/incentives/types"; // Gauge is an object that stores and distributes yields to recipients who // satisfy certain conditions. Currently gauges support conditions around the diff --git a/proto/osmosis/incentives/genesis.proto b/proto/osmosis/incentives/genesis.proto index 6010b968c58..5a13d2ba84c 100644 --- a/proto/osmosis/incentives/genesis.proto +++ b/proto/osmosis/incentives/genesis.proto @@ -6,7 +6,7 @@ import "google/protobuf/duration.proto"; import "osmosis/incentives/params.proto"; import "osmosis/incentives/gauge.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/incentives/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/incentives/types"; // GenesisState defines the incentives module's various parameters when first // initialized diff --git a/proto/osmosis/incentives/params.proto b/proto/osmosis/incentives/params.proto index 9cfa281bb58..58e4c7baca7 100644 --- a/proto/osmosis/incentives/params.proto +++ b/proto/osmosis/incentives/params.proto @@ -3,7 +3,7 @@ package osmosis.incentives; import "gogoproto/gogo.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/incentives/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/incentives/types"; // Params holds parameters for the incentives module message Params { diff --git a/proto/osmosis/incentives/query.proto b/proto/osmosis/incentives/query.proto index 5e66273f917..01d03fe701b 100644 --- a/proto/osmosis/incentives/query.proto +++ b/proto/osmosis/incentives/query.proto @@ -9,7 +9,7 @@ import "cosmos/base/query/v1beta1/pagination.proto"; import "osmosis/incentives/gauge.proto"; import "osmosis/lockup/lock.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/incentives/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/incentives/types"; // Query defines the gRPC querier service service Query { diff --git a/proto/osmosis/incentives/tx.proto b/proto/osmosis/incentives/tx.proto index f9f2bfd18c4..697d211d414 100644 --- a/proto/osmosis/incentives/tx.proto +++ b/proto/osmosis/incentives/tx.proto @@ -7,7 +7,7 @@ import "cosmos/base/v1beta1/coin.proto"; import "osmosis/incentives/gauge.proto"; import "osmosis/lockup/lock.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/incentives/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/incentives/types"; service Msg { rpc CreateGauge(MsgCreateGauge) returns (MsgCreateGaugeResponse); diff --git a/proto/osmosis/lockup/genesis.proto b/proto/osmosis/lockup/genesis.proto index 52f498084b4..14e462960a3 100644 --- a/proto/osmosis/lockup/genesis.proto +++ b/proto/osmosis/lockup/genesis.proto @@ -4,7 +4,7 @@ package osmosis.lockup; import "gogoproto/gogo.proto"; import "osmosis/lockup/lock.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/lockup/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/lockup/types"; // GenesisState defines the lockup module's genesis state. message GenesisState { diff --git a/proto/osmosis/lockup/lock.proto b/proto/osmosis/lockup/lock.proto index 09bcf262e2b..ef4148890ff 100644 --- a/proto/osmosis/lockup/lock.proto +++ b/proto/osmosis/lockup/lock.proto @@ -6,7 +6,7 @@ import "google/protobuf/duration.proto"; import "google/protobuf/timestamp.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/lockup/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/lockup/types"; // PeriodLock is a single lock unit by period defined by the x/lockup module. // It's a record of a locked coin at a specific time. It stores owner, duration, diff --git a/proto/osmosis/lockup/query.proto b/proto/osmosis/lockup/query.proto index 780a5e8c683..8bf53b272a1 100644 --- a/proto/osmosis/lockup/query.proto +++ b/proto/osmosis/lockup/query.proto @@ -8,7 +8,7 @@ import "google/protobuf/timestamp.proto"; import "google/protobuf/duration.proto"; import "osmosis/lockup/lock.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/lockup/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/lockup/types"; // Query defines the gRPC querier service. service Query { diff --git a/proto/osmosis/lockup/tx.proto b/proto/osmosis/lockup/tx.proto index a9f7236ef3b..fa31444128d 100644 --- a/proto/osmosis/lockup/tx.proto +++ b/proto/osmosis/lockup/tx.proto @@ -6,7 +6,7 @@ import "google/protobuf/duration.proto"; import "cosmos/base/v1beta1/coin.proto"; import "osmosis/lockup/lock.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/lockup/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/lockup/types"; // Msg defines the Msg service. service Msg { diff --git a/proto/osmosis/mint/v1beta1/genesis.proto b/proto/osmosis/mint/v1beta1/genesis.proto index 80ebfa46bc7..ef215f37e68 100644 --- a/proto/osmosis/mint/v1beta1/genesis.proto +++ b/proto/osmosis/mint/v1beta1/genesis.proto @@ -4,7 +4,7 @@ package osmosis.mint.v1beta1; import "gogoproto/gogo.proto"; import "osmosis/mint/v1beta1/mint.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/mint/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/mint/types"; // GenesisState defines the mint module's genesis state. message GenesisState { diff --git a/proto/osmosis/mint/v1beta1/mint.proto b/proto/osmosis/mint/v1beta1/mint.proto index ebbca045887..f8502f6f6bf 100644 --- a/proto/osmosis/mint/v1beta1/mint.proto +++ b/proto/osmosis/mint/v1beta1/mint.proto @@ -1,7 +1,7 @@ syntax = "proto3"; package osmosis.mint.v1beta1; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/mint/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/mint/types"; import "gogoproto/gogo.proto"; import "google/protobuf/timestamp.proto"; diff --git a/proto/osmosis/mint/v1beta1/query.proto b/proto/osmosis/mint/v1beta1/query.proto index 90bbdfb252d..8cd9aecfc46 100644 --- a/proto/osmosis/mint/v1beta1/query.proto +++ b/proto/osmosis/mint/v1beta1/query.proto @@ -5,7 +5,7 @@ import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; import "osmosis/mint/v1beta1/mint.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/mint/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/mint/types"; // Query provides defines the gRPC querier service. service Query { diff --git a/proto/osmosis/pool-incentives/v1beta1/genesis.proto b/proto/osmosis/pool-incentives/v1beta1/genesis.proto index 6b4f4ba24c1..0c1c6f27830 100644 --- a/proto/osmosis/pool-incentives/v1beta1/genesis.proto +++ b/proto/osmosis/pool-incentives/v1beta1/genesis.proto @@ -5,7 +5,7 @@ import "gogoproto/gogo.proto"; import "google/protobuf/duration.proto"; import "osmosis/pool-incentives/v1beta1/incentives.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types"; // GenesisState defines the pool incentives module's genesis state. message GenesisState { diff --git a/proto/osmosis/pool-incentives/v1beta1/gov.proto b/proto/osmosis/pool-incentives/v1beta1/gov.proto index d7c9c4c7f7f..cd35c68fab9 100644 --- a/proto/osmosis/pool-incentives/v1beta1/gov.proto +++ b/proto/osmosis/pool-incentives/v1beta1/gov.proto @@ -4,7 +4,7 @@ package osmosis.poolincentives.v1beta1; import "gogoproto/gogo.proto"; import "osmosis/pool-incentives/v1beta1/incentives.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types"; // ReplacePoolIncentivesProposal is a gov Content type for updating the pool // incentives. If a ReplacePoolIncentivesProposal passes, the proposal’s records diff --git a/proto/osmosis/pool-incentives/v1beta1/incentives.proto b/proto/osmosis/pool-incentives/v1beta1/incentives.proto index cb4ab408c2b..22676871c5d 100644 --- a/proto/osmosis/pool-incentives/v1beta1/incentives.proto +++ b/proto/osmosis/pool-incentives/v1beta1/incentives.proto @@ -4,7 +4,7 @@ package osmosis.poolincentives.v1beta1; import "gogoproto/gogo.proto"; import "google/protobuf/duration.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types"; message Params { option (gogoproto.goproto_stringer) = false; diff --git a/proto/osmosis/pool-incentives/v1beta1/query.proto b/proto/osmosis/pool-incentives/v1beta1/query.proto index e104e588ad9..0c10931c51b 100644 --- a/proto/osmosis/pool-incentives/v1beta1/query.proto +++ b/proto/osmosis/pool-incentives/v1beta1/query.proto @@ -7,7 +7,7 @@ import "google/protobuf/duration.proto"; import "osmosis/incentives/gauge.proto"; import "osmosis/pool-incentives/v1beta1/incentives.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types"; service Query { // GaugeIds takes the pool id and returns the matching gauge ids and durations diff --git a/proto/osmosis/store/v1beta1/tree.proto b/proto/osmosis/store/v1beta1/tree.proto index 85ef7f25064..0f1d8a406a6 100644 --- a/proto/osmosis/store/v1beta1/tree.proto +++ b/proto/osmosis/store/v1beta1/tree.proto @@ -4,7 +4,7 @@ package osmosis.store.v1beta1; import "gogoproto/gogo.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/store"; +option go_package = "github.com/osmosis-labs/osmosis/v10/store"; message Node { repeated Child children = 1; } diff --git a/proto/osmosis/superfluid/genesis.proto b/proto/osmosis/superfluid/genesis.proto index 346a753afa3..d1a654963de 100644 --- a/proto/osmosis/superfluid/genesis.proto +++ b/proto/osmosis/superfluid/genesis.proto @@ -5,7 +5,7 @@ import "gogoproto/gogo.proto"; import "osmosis/superfluid/superfluid.proto"; import "osmosis/superfluid/params.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/superfluid/types"; // GenesisState defines the module's genesis state. message GenesisState { diff --git a/proto/osmosis/superfluid/params.proto b/proto/osmosis/superfluid/params.proto index c102db5cbe6..418bc8a81bf 100644 --- a/proto/osmosis/superfluid/params.proto +++ b/proto/osmosis/superfluid/params.proto @@ -4,7 +4,7 @@ package osmosis.superfluid; import "gogoproto/gogo.proto"; import "google/protobuf/duration.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/superfluid/types"; // Params holds parameters for the superfluid module message Params { diff --git a/proto/osmosis/superfluid/query.proto b/proto/osmosis/superfluid/query.proto index 1a981242403..fe28d424f50 100644 --- a/proto/osmosis/superfluid/query.proto +++ b/proto/osmosis/superfluid/query.proto @@ -12,7 +12,7 @@ import "osmosis/lockup/lock.proto"; import "cosmos/base/query/v1beta1/pagination.proto"; import "cosmos/staking/v1beta1/staking.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/superfluid/types"; // Query defines the gRPC querier service. service Query { diff --git a/proto/osmosis/superfluid/superfluid.proto b/proto/osmosis/superfluid/superfluid.proto index 0b35322e401..707d6223ad0 100644 --- a/proto/osmosis/superfluid/superfluid.proto +++ b/proto/osmosis/superfluid/superfluid.proto @@ -6,7 +6,7 @@ import "google/protobuf/duration.proto"; import "google/protobuf/timestamp.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/superfluid/types"; // SuperfluidAssetType indicates whether the superfluid asset is // a native token itself or the lp share of a pool. diff --git a/proto/osmosis/superfluid/tx.proto b/proto/osmosis/superfluid/tx.proto index cf1b80f4a29..c79025f9e0d 100644 --- a/proto/osmosis/superfluid/tx.proto +++ b/proto/osmosis/superfluid/tx.proto @@ -6,7 +6,7 @@ import "google/protobuf/duration.proto"; import "cosmos/base/v1beta1/coin.proto"; import "osmosis/superfluid/superfluid.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/superfluid/types"; // Msg defines the Msg service. service Msg { diff --git a/proto/osmosis/superfluid/v1beta1/gov.proto b/proto/osmosis/superfluid/v1beta1/gov.proto index 2ad153d144a..a8c669fbc75 100644 --- a/proto/osmosis/superfluid/v1beta1/gov.proto +++ b/proto/osmosis/superfluid/v1beta1/gov.proto @@ -4,7 +4,7 @@ package osmosis.superfluid.v1beta1; import "gogoproto/gogo.proto"; import "osmosis/superfluid/superfluid.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/superfluid/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/superfluid/types"; // SetSuperfluidAssetsProposal is a gov Content type to update the superfluid // assets diff --git a/proto/osmosis/tokenfactory/v1beta1/authorityMetadata.proto b/proto/osmosis/tokenfactory/v1beta1/authorityMetadata.proto index 75befa6445a..03e254dcb99 100644 --- a/proto/osmosis/tokenfactory/v1beta1/authorityMetadata.proto +++ b/proto/osmosis/tokenfactory/v1beta1/authorityMetadata.proto @@ -4,7 +4,7 @@ package osmosis.tokenfactory.v1beta1; import "gogoproto/gogo.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types"; // DenomAuthorityMetadata specifies metadata for addresses that have specific // capabilities over a token factory denom. Right now there is only one Admin diff --git a/proto/osmosis/tokenfactory/v1beta1/genesis.proto b/proto/osmosis/tokenfactory/v1beta1/genesis.proto index 67f94646700..1cbedaae65f 100644 --- a/proto/osmosis/tokenfactory/v1beta1/genesis.proto +++ b/proto/osmosis/tokenfactory/v1beta1/genesis.proto @@ -5,7 +5,7 @@ import "gogoproto/gogo.proto"; import "osmosis/tokenfactory/v1beta1/authorityMetadata.proto"; import "osmosis/tokenfactory/v1beta1/params.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types"; // GenesisState defines the tokenfactory module's genesis state. message GenesisState { diff --git a/proto/osmosis/tokenfactory/v1beta1/params.proto b/proto/osmosis/tokenfactory/v1beta1/params.proto index 0aafb65ecf4..d8bf24d553f 100644 --- a/proto/osmosis/tokenfactory/v1beta1/params.proto +++ b/proto/osmosis/tokenfactory/v1beta1/params.proto @@ -6,7 +6,7 @@ import "osmosis/tokenfactory/v1beta1/authorityMetadata.proto"; import "cosmos_proto/cosmos.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types"; // Params defines the parameters for the tokenfactory module. message Params { diff --git a/proto/osmosis/tokenfactory/v1beta1/query.proto b/proto/osmosis/tokenfactory/v1beta1/query.proto index d4811ad9f08..74c3ffe90f2 100644 --- a/proto/osmosis/tokenfactory/v1beta1/query.proto +++ b/proto/osmosis/tokenfactory/v1beta1/query.proto @@ -7,7 +7,7 @@ import "cosmos/base/query/v1beta1/pagination.proto"; import "osmosis/tokenfactory/v1beta1/authorityMetadata.proto"; import "osmosis/tokenfactory/v1beta1/params.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types"; // Query defines the gRPC querier service. service Query { diff --git a/proto/osmosis/tokenfactory/v1beta1/tx.proto b/proto/osmosis/tokenfactory/v1beta1/tx.proto index 7391d4dd295..fd33ba3b571 100644 --- a/proto/osmosis/tokenfactory/v1beta1/tx.proto +++ b/proto/osmosis/tokenfactory/v1beta1/tx.proto @@ -4,7 +4,7 @@ package osmosis.tokenfactory.v1beta1; import "gogoproto/gogo.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types"; // Msg defines the tokefactory module's gRPC message service. service Msg { diff --git a/proto/osmosis/txfees/v1beta1/feetoken.proto b/proto/osmosis/txfees/v1beta1/feetoken.proto index c7cd36e34e0..22e91ce35dc 100644 --- a/proto/osmosis/txfees/v1beta1/feetoken.proto +++ b/proto/osmosis/txfees/v1beta1/feetoken.proto @@ -3,7 +3,7 @@ package osmosis.txfees.v1beta1; import "gogoproto/gogo.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/txfees/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/txfees/types"; // FeeToken is a struct that specifies a coin denom, and pool ID pair. // This marks the token as eligible for use as a tx fee asset in Osmosis. diff --git a/proto/osmosis/txfees/v1beta1/genesis.proto b/proto/osmosis/txfees/v1beta1/genesis.proto index 9b6fb48c4e9..31bdd233a63 100644 --- a/proto/osmosis/txfees/v1beta1/genesis.proto +++ b/proto/osmosis/txfees/v1beta1/genesis.proto @@ -4,7 +4,7 @@ package osmosis.txfees.v1beta1; import "gogoproto/gogo.proto"; import "osmosis/txfees/v1beta1/feetoken.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/txfees/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/txfees/types"; // GenesisState defines the txfees module's genesis state. message GenesisState { diff --git a/proto/osmosis/txfees/v1beta1/gov.proto b/proto/osmosis/txfees/v1beta1/gov.proto index 253e822d612..15f904bc571 100644 --- a/proto/osmosis/txfees/v1beta1/gov.proto +++ b/proto/osmosis/txfees/v1beta1/gov.proto @@ -4,7 +4,7 @@ package osmosis.txfees.v1beta1; import "gogoproto/gogo.proto"; import "osmosis/txfees/v1beta1/feetoken.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/txfees/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/txfees/types"; // UpdateFeeTokenProposal is a gov Content type for adding a new whitelisted fee // token. It must specify a denom along with gamm pool ID to use as a spot price diff --git a/proto/osmosis/txfees/v1beta1/query.proto b/proto/osmosis/txfees/v1beta1/query.proto index abb36616184..38ab374a9c8 100644 --- a/proto/osmosis/txfees/v1beta1/query.proto +++ b/proto/osmosis/txfees/v1beta1/query.proto @@ -7,7 +7,7 @@ import "google/protobuf/duration.proto"; import "osmosis/txfees/v1beta1/feetoken.proto"; -option go_package = "github.com/osmosis-labs/osmosis/v7/x/txfees/types"; +option go_package = "github.com/osmosis-labs/osmosis/v10/x/txfees/types"; service Query { // FeeTokens returns a list of all the whitelisted fee tokens and their diff --git a/scripts/protocgen.sh b/scripts/protocgen.sh index 433450a4318..5d26203659d 100755 --- a/scripts/protocgen.sh +++ b/scripts/protocgen.sh @@ -24,7 +24,7 @@ cd .. # move proto files to the right places # # Note: Proto files are suffixed with the current binary version. -cp -r github.com/osmosis-labs/osmosis/v7/* ./ +cp -r github.com/osmosis-labs/osmosis/v10/* ./ rm -rf github.com go mod tidy -compat=1.18 diff --git a/simulation/executor/mock_tendermint.go b/simulation/executor/mock_tendermint.go index e840c39c1fb..33f463f1f23 100644 --- a/simulation/executor/mock_tendermint.go +++ b/simulation/executor/mock_tendermint.go @@ -14,7 +14,7 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "golang.org/x/exp/maps" - markov "github.com/osmosis-labs/osmosis/v7/simulation/types/transitionmatrix" + markov "github.com/osmosis-labs/osmosis/v10/simulation/types/transitionmatrix" ) type mockValidator struct { diff --git a/simulation/executor/operation.go b/simulation/executor/operation.go index fcc3013525a..89e61d57744 100644 --- a/simulation/executor/operation.go +++ b/simulation/executor/operation.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/simulation" - simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" + simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" ) // entry kinds for use within OperationEntry diff --git a/simulation/executor/params.go b/simulation/executor/params.go index 19a21f9fe75..e3011aef7ff 100644 --- a/simulation/executor/params.go +++ b/simulation/executor/params.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/simulation" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - markov "github.com/osmosis-labs/osmosis/v7/simulation/types/transitionmatrix" + markov "github.com/osmosis-labs/osmosis/v10/simulation/types/transitionmatrix" ) const ( diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index 527d87909ff..0cfb9354cfd 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -19,7 +19,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/simulation" - simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" + simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" ) const AverageBlockTime = 6 * time.Second diff --git a/simulation/executor/simulate_dev.go b/simulation/executor/simulate_dev.go index 20ab9bf4d8a..8d1faab0e4a 100644 --- a/simulation/executor/simulate_dev.go +++ b/simulation/executor/simulate_dev.go @@ -10,7 +10,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" + simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" ) type simState struct { diff --git a/simulation/executor/util.go b/simulation/executor/util.go index f15a9b5aaf8..85654166bbb 100644 --- a/simulation/executor/util.go +++ b/simulation/executor/util.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" + simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" ) func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) { diff --git a/simulation/types/manager.go b/simulation/types/manager.go index 335490fc5fa..b45f4ee9be6 100644 --- a/simulation/types/manager.go +++ b/simulation/types/manager.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/simulation" "golang.org/x/exp/maps" - "github.com/osmosis-labs/osmosis/v7/osmoutils" + "github.com/osmosis-labs/osmosis/v10/osmoutils" ) // AppModuleSimulation defines the standard functions that every module should expose diff --git a/simulation/types/randutil.go b/simulation/types/randutil.go index 093c164fd55..b6f21364ac7 100644 --- a/simulation/types/randutil.go +++ b/simulation/types/randutil.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "golang.org/x/exp/constraints" - sdkrand "github.com/osmosis-labs/osmosis/v7/simulation/types/random" + sdkrand "github.com/osmosis-labs/osmosis/v10/simulation/types/random" ) func RandLTBound[T constraints.Integer](sim *SimCtx, upperbound T) T { diff --git a/simulation/types/txbuilder.go b/simulation/types/txbuilder.go index f7d07d1c50a..a59a94cff79 100644 --- a/simulation/types/txbuilder.go +++ b/simulation/types/txbuilder.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/types/tx/signing" - "github.com/osmosis-labs/osmosis/v7/app/params" + "github.com/osmosis-labs/osmosis/v10/app/params" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" authsign "github.com/cosmos/cosmos-sdk/x/auth/signing" diff --git a/store/legacy/v101/tree.go b/store/legacy/v101/tree.go index 3946a593005..b15148c8a4e 100644 --- a/store/legacy/v101/tree.go +++ b/store/legacy/v101/tree.go @@ -10,7 +10,7 @@ import ( stypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/store" + "github.com/osmosis-labs/osmosis/v10/store" ) type Child struct { diff --git a/store/legacy/v101/tree_test.go b/store/legacy/v101/tree_test.go index 3287138a9ee..5b9b884ab31 100644 --- a/store/legacy/v101/tree_test.go +++ b/store/legacy/v101/tree_test.go @@ -18,8 +18,8 @@ import ( iavlstore "github.com/cosmos/cosmos-sdk/store/iavl" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/store" - v101 "github.com/osmosis-labs/osmosis/v7/store/legacy/v101" + "github.com/osmosis-labs/osmosis/v10/store" + v101 "github.com/osmosis-labs/osmosis/v10/store/legacy/v101" ) func setupStore() sdk.KVStore { diff --git a/store/tree.pb.go b/store/tree.pb.go index 895f4a19087..00a61989379 100644 --- a/store/tree.pb.go +++ b/store/tree.pb.go @@ -167,26 +167,26 @@ func init() { func init() { proto.RegisterFile("osmosis/store/v1beta1/tree.proto", fileDescriptor_72b0b7af579d13be) } var fileDescriptor_72b0b7af579d13be = []byte{ - // 297 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0xd1, 0x4d, 0x4b, 0xc3, 0x30, - 0x18, 0x07, 0xf0, 0x46, 0x3b, 0xd1, 0xb8, 0x53, 0x99, 0x50, 0x86, 0x64, 0xa5, 0x07, 0xe9, 0x65, - 0x89, 0xd3, 0x83, 0x3b, 0x4a, 0x3d, 0x09, 0xe2, 0xa1, 0x47, 0x6f, 0x69, 0x9a, 0x75, 0xc1, 0xb6, - 0x99, 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, 0x3a, 0x73, 0xce, 0xa1, 0x9d, 0x71, 0x3a, 0x33, 0x03, 0x77, - 0x05, 0x36, 0x32, 0x0c, 0x57, 0x35, 0x02, 0xeb, 0x1a, 0x81, 0x8f, 0x1a, 0x81, 0xd7, 0x06, 0x59, - 0xeb, 0x06, 0x59, 0x6f, 0x0d, 0xb2, 0x1e, 0x82, 0x5f, 0x49, 0xba, 0x3e, 0xe3, 0x8c, 0xc6, 0xea, - 0xab, 0x20, 0xcb, 0xab, 0xf6, 0x4b, 0xe2, 0x03, 0xf3, 0x72, 0x97, 0x9f, 0x01, 0x00, 0x00, 0xff, - 0xff, 0x63, 0x3c, 0x1f, 0x09, 0xaa, 0x01, 0x00, 0x00, + // 299 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0xd1, 0x4f, 0x4b, 0xfb, 0x30, + 0x18, 0x07, 0xf0, 0xe6, 0xf7, 0xeb, 0x44, 0xe3, 0x4e, 0x65, 0x42, 0x19, 0x92, 0x95, 0x1e, 0xa4, + 0x1e, 0x96, 0xac, 0x7a, 0xd9, 0x51, 0xb6, 0x93, 0x20, 0x1e, 0x7a, 0xf4, 0x96, 0xa6, 0x59, 0x17, + 0x6c, 0x9b, 0xd9, 0xa4, 0x43, 0xdf, 0x85, 0x2f, 0x6b, 0xc7, 0x1d, 0xc5, 0xc3, 0x90, 0xf6, 0x8d, + 0xc8, 0xd2, 0xfa, 0x0f, 0x04, 0x4f, 0xc9, 0x93, 0x7c, 0x78, 0x9e, 0x2f, 0x09, 0xf4, 0xa4, 0xca, + 0xa5, 0x12, 0x8a, 0x28, 0x2d, 0x4b, 0x4e, 0xd6, 0x61, 0xcc, 0x35, 0x0d, 0x89, 0x2e, 0x39, 0xc7, + 0xab, 0x52, 0x6a, 0xe9, 0x9c, 0x74, 0x02, 0x1b, 0x81, 0x3b, 0x31, 0x1c, 0xa4, 0x32, 0x95, 0x46, + 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0xab, 0x01, 0x00, 0x00, } func (m *Node) Marshal() (dAtA []byte, err error) { diff --git a/store/tree_test.go b/store/tree_test.go index 5ced86a0d15..319abf780b7 100644 --- a/store/tree_test.go +++ b/store/tree_test.go @@ -15,7 +15,7 @@ import ( iavlstore "github.com/cosmos/cosmos-sdk/store/iavl" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/store" + "github.com/osmosis-labs/osmosis/v10/store" ) type TreeTestSuite struct { diff --git a/tests/e2e/configurer/base.go b/tests/e2e/configurer/base.go index 3826e10fcbe..0503df2953c 100644 --- a/tests/e2e/configurer/base.go +++ b/tests/e2e/configurer/base.go @@ -13,10 +13,10 @@ import ( "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer/chain" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/util" ) // baseConfigurer is the base implementation for the diff --git a/tests/e2e/configurer/chain/chain.go b/tests/e2e/configurer/chain/chain.go index a3145d70372..d4b4b13fbff 100644 --- a/tests/e2e/configurer/chain/chain.go +++ b/tests/e2e/configurer/chain/chain.go @@ -9,8 +9,8 @@ import ( "github.com/stretchr/testify/require" coretypes "github.com/tendermint/tendermint/rpc/core/types" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) type Config struct { diff --git a/tests/e2e/configurer/chain/node.go b/tests/e2e/configurer/chain/node.go index 7af3a36d85d..2c76a6ef51e 100644 --- a/tests/e2e/configurer/chain/node.go +++ b/tests/e2e/configurer/chain/node.go @@ -12,8 +12,8 @@ import ( rpchttp "github.com/tendermint/tendermint/rpc/client/http" coretypes "github.com/tendermint/tendermint/rpc/core/types" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) type NodeConfig struct { diff --git a/tests/e2e/configurer/chain/queries.go b/tests/e2e/configurer/chain/queries.go index b9fb7dff099..49f3472ce02 100644 --- a/tests/e2e/configurer/chain/queries.go +++ b/tests/e2e/configurer/chain/queries.go @@ -14,8 +14,8 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" - superfluidtypes "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/util" + superfluidtypes "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) func (n *NodeConfig) QueryGRPCGateway(path string) ([]byte, error) { diff --git a/tests/e2e/configurer/current.go b/tests/e2e/configurer/current.go index 8e058e2fcd4..90af8e1a360 100644 --- a/tests/e2e/configurer/current.go +++ b/tests/e2e/configurer/current.go @@ -5,9 +5,9 @@ import ( "testing" "time" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer/chain" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) type CurrentBranchConfigurer struct { diff --git a/tests/e2e/configurer/factory.go b/tests/e2e/configurer/factory.go index ed9e4d7f799..92c52bb8e4b 100644 --- a/tests/e2e/configurer/factory.go +++ b/tests/e2e/configurer/factory.go @@ -4,9 +4,9 @@ import ( "errors" "testing" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer/chain" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) type Configurer interface { diff --git a/tests/e2e/configurer/upgrade.go b/tests/e2e/configurer/upgrade.go index 3131a52d5ae..d6fab3b2eba 100644 --- a/tests/e2e/configurer/upgrade.go +++ b/tests/e2e/configurer/upgrade.go @@ -7,10 +7,10 @@ import ( "testing" "time" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/chain" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer/config" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/containers" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer/chain" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer/config" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/containers" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) type UpgradeSettings struct { diff --git a/tests/e2e/e2e_setup_test.go b/tests/e2e/e2e_setup_test.go index 0877079dbfa..8d4417b866b 100644 --- a/tests/e2e/e2e_setup_test.go +++ b/tests/e2e/e2e_setup_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/suite" - configurer "github.com/osmosis-labs/osmosis/v7/tests/e2e/configurer" + configurer "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer" ) const ( diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index 0113b675d3a..6b8df0bfc1c 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -5,7 +5,7 @@ import ( "strconv" "time" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) func (s *IntegrationTestSuite) TestCreatePoolPostUpgrade() { diff --git a/tests/e2e/initialization/chain/main.go b/tests/e2e/initialization/chain/main.go index 3c12471224f..586cb9fddcc 100644 --- a/tests/e2e/initialization/chain/main.go +++ b/tests/e2e/initialization/chain/main.go @@ -7,7 +7,7 @@ import ( "os" "time" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) func main() { diff --git a/tests/e2e/initialization/config.go b/tests/e2e/initialization/config.go index 66644e3482a..b32fb0dea6f 100644 --- a/tests/e2e/initialization/config.go +++ b/tests/e2e/initialization/config.go @@ -18,14 +18,14 @@ import ( "github.com/gogo/protobuf/proto" tmjson "github.com/tendermint/tendermint/libs/json" - epochtypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" - poolitypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" - txfeestypes "github.com/osmosis-labs/osmosis/v7/x/txfees/types" - - "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" + epochtypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + minttypes "github.com/osmosis-labs/osmosis/v10/x/mint/types" + poolitypes "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" + txfeestypes "github.com/osmosis-labs/osmosis/v10/x/txfees/types" + + "github.com/osmosis-labs/osmosis/v10/tests/e2e/util" ) // NodeConfig is a confiuration for the node supplied from the test runner diff --git a/tests/e2e/initialization/init.go b/tests/e2e/initialization/init.go index df03c842731..427dbdad3a5 100644 --- a/tests/e2e/initialization/init.go +++ b/tests/e2e/initialization/init.go @@ -6,7 +6,7 @@ import ( "path/filepath" "time" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/util" ) func InitChain(id, dataDir string, nodeConfigs []*NodeConfig, votingPeriod time.Duration, forkHeight int) (*Chain, error) { diff --git a/tests/e2e/initialization/init_test.go b/tests/e2e/initialization/init_test.go index 926ef9950d8..4cb54ab2ad8 100644 --- a/tests/e2e/initialization/init_test.go +++ b/tests/e2e/initialization/init_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) const forkHeight = 10 diff --git a/tests/e2e/initialization/node.go b/tests/e2e/initialization/node.go index 3300cfbd010..68536e736a7 100644 --- a/tests/e2e/initialization/node.go +++ b/tests/e2e/initialization/node.go @@ -29,8 +29,8 @@ import ( "github.com/tendermint/tendermint/privval" tmtypes "github.com/tendermint/tendermint/types" - osmosisApp "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" + osmosisApp "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/util" ) type internalNode struct { diff --git a/tests/e2e/initialization/node/main.go b/tests/e2e/initialization/node/main.go index b8130c3d118..14ea881783b 100644 --- a/tests/e2e/initialization/node/main.go +++ b/tests/e2e/initialization/node/main.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/initialization" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) func main() { diff --git a/tests/e2e/initialization/util.go b/tests/e2e/initialization/util.go index 1aa7790c6ef..9a2db5045aa 100644 --- a/tests/e2e/initialization/util.go +++ b/tests/e2e/initialization/util.go @@ -6,7 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec/unknownproto" sdktx "github.com/cosmos/cosmos-sdk/types/tx" - "github.com/osmosis-labs/osmosis/v7/tests/e2e/util" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/util" ) func decodeTx(txBytes []byte) (*sdktx.Tx, error) { diff --git a/tests/e2e/util/codec.go b/tests/e2e/util/codec.go index fc1d0ea1ab5..91bfb5d5dcd 100644 --- a/tests/e2e/util/codec.go +++ b/tests/e2e/util/codec.go @@ -8,8 +8,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - osmosisApp "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/app/params" + osmosisApp "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/app/params" ) var ( diff --git a/tests/simulator/genesis.go b/tests/simulator/genesis.go index 2be960330ba..0eb2b766ec0 100644 --- a/tests/simulator/genesis.go +++ b/tests/simulator/genesis.go @@ -5,7 +5,7 @@ import ( "io" "io/ioutil" - "github.com/osmosis-labs/osmosis/v7/app" + "github.com/osmosis-labs/osmosis/v10/app" tmjson "github.com/tendermint/tendermint/libs/json" tmtypes "github.com/tendermint/tendermint/types" diff --git a/tests/simulator/sim_test.go b/tests/simulator/sim_test.go index af74440d808..97b1212deef 100644 --- a/tests/simulator/sim_test.go +++ b/tests/simulator/sim_test.go @@ -10,7 +10,7 @@ import ( "github.com/tendermint/tendermint/libs/log" dbm "github.com/tendermint/tm-db" - "github.com/osmosis-labs/osmosis/v7/app" + "github.com/osmosis-labs/osmosis/v10/app" "github.com/cosmos/cosmos-sdk/baseapp" sdkSimapp "github.com/cosmos/cosmos-sdk/simapp" @@ -18,8 +18,8 @@ import ( "github.com/cosmos/cosmos-sdk/store" simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" - osmosim "github.com/osmosis-labs/osmosis/v7/simulation/executor" - simtypes "github.com/osmosis-labs/osmosis/v7/simulation/types" + osmosim "github.com/osmosis-labs/osmosis/v10/simulation/executor" + simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" ) // Profile with: diff --git a/tests/simulator/state.go b/tests/simulator/state.go index afeaca64ca8..a6b6cc46183 100644 --- a/tests/simulator/state.go +++ b/tests/simulator/state.go @@ -7,8 +7,8 @@ import ( "math/rand" "time" - "github.com/osmosis-labs/osmosis/v7/app" - simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" + "github.com/osmosis-labs/osmosis/v10/app" + simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" "github.com/cosmos/cosmos-sdk/codec" sdksimapp "github.com/cosmos/cosmos-sdk/simapp" diff --git a/wasmbinding/message_plugin.go b/wasmbinding/message_plugin.go index 6995bec723a..7590b5a98cb 100644 --- a/wasmbinding/message_plugin.go +++ b/wasmbinding/message_plugin.go @@ -9,12 +9,12 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - "github.com/osmosis-labs/osmosis/v7/wasmbinding/bindings" - gammkeeper "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/wasmbinding/bindings" + gammkeeper "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" - tokenfactorykeeper "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/keeper" - tokenfactorytypes "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + tokenfactorykeeper "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" + tokenfactorytypes "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) func CustomMessageDecorator(gammKeeper *gammkeeper.Keeper, bank *bankkeeper.BaseKeeper, tokenFactory *tokenfactorykeeper.Keeper) func(wasmkeeper.Messenger) wasmkeeper.Messenger { diff --git a/wasmbinding/queries.go b/wasmbinding/queries.go index 8136b5005a0..6665fc24bd5 100644 --- a/wasmbinding/queries.go +++ b/wasmbinding/queries.go @@ -7,10 +7,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/wasmbinding/bindings" - gammkeeper "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - tokenfactorykeeper "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/keeper" + "github.com/osmosis-labs/osmosis/v10/wasmbinding/bindings" + gammkeeper "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + tokenfactorykeeper "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" ) type QueryPlugin struct { diff --git a/wasmbinding/query_plugin.go b/wasmbinding/query_plugin.go index d23567b1f1c..1f44dc87b9e 100644 --- a/wasmbinding/query_plugin.go +++ b/wasmbinding/query_plugin.go @@ -8,7 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/wasmbinding/bindings" + "github.com/osmosis-labs/osmosis/v10/wasmbinding/bindings" ) func CustomQuerier(qp *QueryPlugin) func(ctx sdk.Context, request json.RawMessage) ([]byte, error) { diff --git a/wasmbinding/test/custom_msg_test.go b/wasmbinding/test/custom_msg_test.go index be4b81a8699..c6b8400856e 100644 --- a/wasmbinding/test/custom_msg_test.go +++ b/wasmbinding/test/custom_msg_test.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" "github.com/stretchr/testify/require" @@ -13,8 +13,8 @@ import ( wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/wasmbinding/bindings" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/wasmbinding/bindings" ) func TestCreateDenomMsg(t *testing.T) { diff --git a/wasmbinding/test/custom_query_test.go b/wasmbinding/test/custom_query_test.go index 2a1bcd2c29a..270be30583f 100644 --- a/wasmbinding/test/custom_query_test.go +++ b/wasmbinding/test/custom_query_test.go @@ -15,10 +15,10 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/wasmbinding" - "github.com/osmosis-labs/osmosis/v7/wasmbinding/bindings" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/wasmbinding" + "github.com/osmosis-labs/osmosis/v10/wasmbinding/bindings" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" ) // we must pay this many uosmo for every pool we create diff --git a/wasmbinding/test/helpers_test.go b/wasmbinding/test/helpers_test.go index b4e0b9b34a3..715caa773f5 100644 --- a/wasmbinding/test/helpers_test.go +++ b/wasmbinding/test/helpers_test.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app" + "github.com/osmosis-labs/osmosis/v10/app" ) func CreateTestInput() (*app.OsmosisApp, sdk.Context) { diff --git a/wasmbinding/test/messages_test.go b/wasmbinding/test/messages_test.go index e5288d4db58..5b8c58b13b0 100644 --- a/wasmbinding/test/messages_test.go +++ b/wasmbinding/test/messages_test.go @@ -7,9 +7,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/wasmbinding" - "github.com/osmosis-labs/osmosis/v7/wasmbinding/bindings" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/wasmbinding" + "github.com/osmosis-labs/osmosis/v10/wasmbinding/bindings" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/wasmbinding/test/queries_test.go b/wasmbinding/test/queries_test.go index b87bcefef92..a1cba5f08fa 100644 --- a/wasmbinding/test/queries_test.go +++ b/wasmbinding/test/queries_test.go @@ -9,8 +9,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/wasmbinding" - "github.com/osmosis-labs/osmosis/v7/wasmbinding/bindings" + "github.com/osmosis-labs/osmosis/v10/wasmbinding" + "github.com/osmosis-labs/osmosis/v10/wasmbinding/bindings" ) func TestFullDenom(t *testing.T) { diff --git a/wasmbinding/test/store_run_test.go b/wasmbinding/test/store_run_test.go index 9a6059183b2..25602540656 100644 --- a/wasmbinding/test/store_run_test.go +++ b/wasmbinding/test/store_run_test.go @@ -13,7 +13,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app" + "github.com/osmosis-labs/osmosis/v10/app" ) func TestNoStorageWithoutProposal(t *testing.T) { diff --git a/wasmbinding/wasm.go b/wasmbinding/wasm.go index af3fdd55bd2..35cc86bce2b 100644 --- a/wasmbinding/wasm.go +++ b/wasmbinding/wasm.go @@ -5,8 +5,8 @@ import ( wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - gammkeeper "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - tokenfactorykeeper "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/keeper" + gammkeeper "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + tokenfactorykeeper "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" ) func RegisterCustomPlugins( diff --git a/x/epochs/client/cli/cli_test.go b/x/epochs/client/cli/cli_test.go index c30a1d8d20a..a187eed9351 100644 --- a/x/epochs/client/cli/cli_test.go +++ b/x/epochs/client/cli/cli_test.go @@ -4,9 +4,9 @@ import ( "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/epochs/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/epochs/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" diff --git a/x/epochs/client/cli/query.go b/x/epochs/client/cli/query.go index 5084b89ad3c..139cb724f43 100644 --- a/x/epochs/client/cli/query.go +++ b/x/epochs/client/cli/query.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/epochs/client/cli/tx.go b/x/epochs/client/cli/tx.go index cf041d50b9d..eae8573010a 100644 --- a/x/epochs/client/cli/tx.go +++ b/x/epochs/client/cli/tx.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" // "github.com/cosmos/cosmos-sdk/client/flags". - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) // GetTxCmd returns the transaction commands for this module. diff --git a/x/epochs/keeper/abci.go b/x/epochs/keeper/abci.go index d1fe97219b4..c891b407baa 100644 --- a/x/epochs/keeper/abci.go +++ b/x/epochs/keeper/abci.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/epochs/keeper/abci_test.go b/x/epochs/keeper/abci_test.go index 1c331261c23..d90d9f41b4b 100644 --- a/x/epochs/keeper/abci_test.go +++ b/x/epochs/keeper/abci_test.go @@ -7,12 +7,12 @@ import ( "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - simapp "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + simapp "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "golang.org/x/exp/maps" - "github.com/osmosis-labs/osmosis/v7/osmoutils" + "github.com/osmosis-labs/osmosis/v10/osmoutils" ) // This test is responsible for testing how epochs increment based off diff --git a/x/epochs/keeper/epoch.go b/x/epochs/keeper/epoch.go index b04013a2f7c..9dcf262910c 100644 --- a/x/epochs/keeper/epoch.go +++ b/x/epochs/keeper/epoch.go @@ -6,7 +6,7 @@ import ( "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/epochs/keeper/epoch_test.go b/x/epochs/keeper/epoch_test.go index dea59d69830..d0f2768bbda 100644 --- a/x/epochs/keeper/epoch_test.go +++ b/x/epochs/keeper/epoch_test.go @@ -3,7 +3,7 @@ package keeper_test import ( "time" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) func (suite *KeeperTestSuite) TestAddEpochInfo() { diff --git a/x/epochs/keeper/genesis.go b/x/epochs/keeper/genesis.go index 38211254322..ddbbe18f118 100644 --- a/x/epochs/keeper/genesis.go +++ b/x/epochs/keeper/genesis.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { diff --git a/x/epochs/keeper/genesis_test.go b/x/epochs/keeper/genesis_test.go index 36390df34c7..db593295ab2 100644 --- a/x/epochs/keeper/genesis_test.go +++ b/x/epochs/keeper/genesis_test.go @@ -7,9 +7,9 @@ import ( "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - simapp "github.com/osmosis-labs/osmosis/v7/app" + simapp "github.com/osmosis-labs/osmosis/v10/app" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) func TestEpochsExportGenesis(t *testing.T) { diff --git a/x/epochs/keeper/grpc_query.go b/x/epochs/keeper/grpc_query.go index 61d26f0a031..66734c4f17e 100644 --- a/x/epochs/keeper/grpc_query.go +++ b/x/epochs/keeper/grpc_query.go @@ -8,7 +8,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) var _ types.QueryServer = Querier{} diff --git a/x/epochs/keeper/grpc_query_test.go b/x/epochs/keeper/grpc_query_test.go index d97b4fc9153..4f5560dea3a 100644 --- a/x/epochs/keeper/grpc_query_test.go +++ b/x/epochs/keeper/grpc_query_test.go @@ -3,7 +3,7 @@ package keeper_test import ( gocontext "context" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) func (suite *KeeperTestSuite) TestQueryEpochInfos() { diff --git a/x/epochs/keeper/keeper.go b/x/epochs/keeper/keeper.go index 6ae659d3e71..4c56599eda3 100644 --- a/x/epochs/keeper/keeper.go +++ b/x/epochs/keeper/keeper.go @@ -3,7 +3,7 @@ package keeper import ( "fmt" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/epochs/keeper/keeper_test.go b/x/epochs/keeper/keeper_test.go index 88e82dc9246..2a392316be2 100644 --- a/x/epochs/keeper/keeper_test.go +++ b/x/epochs/keeper/keeper_test.go @@ -5,8 +5,8 @@ import ( "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) type KeeperTestSuite struct { diff --git a/x/epochs/module.go b/x/epochs/module.go index ac1201ae189..f32d5d3c788 100644 --- a/x/epochs/module.go +++ b/x/epochs/module.go @@ -16,10 +16,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/osmosis-labs/osmosis/v7/x/epochs/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/epochs/keeper" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/client/rest" + "github.com/osmosis-labs/osmosis/v10/x/epochs/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/epochs/keeper" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/client/rest" ) var ( diff --git a/x/epochs/types/genesis.pb.go b/x/epochs/types/genesis.pb.go index 7095bf15ba5..fb7fb750ec3 100644 --- a/x/epochs/types/genesis.pb.go +++ b/x/epochs/types/genesis.pb.go @@ -209,35 +209,35 @@ func init() { proto.RegisterFile("osmosis/epochs/genesis.proto", fileDescriptor_ var fileDescriptor_7ecf3e4d59074cbd = []byte{ // 479 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x53, 0x3f, 0x8f, 0xd3, 0x30, - 0x1c, 0xad, 0xb9, 0x52, 0x52, 0xdf, 0x21, 0xc0, 0x3a, 0x8e, 0x50, 0x41, 0x12, 0xc2, 0x12, 0x09, - 0x70, 0xd4, 0x03, 0x09, 0x09, 0x06, 0xa4, 0x02, 0xe2, 0xdf, 0x80, 0x94, 0x32, 0x20, 0x96, 0x2a, - 0x69, 0xdd, 0xc4, 0x52, 0x13, 0x47, 0xf1, 0x2f, 0x27, 0xba, 0xf1, 0x11, 0x3a, 0xf2, 0x91, 0x6e, - 0xbc, 0x91, 0xa9, 0xa0, 0x76, 0x63, 0xbc, 0x4f, 0x80, 0x62, 0x27, 0xa5, 0x70, 0x87, 0xd8, 0x62, - 0xbf, 0xf7, 0x7b, 0xcf, 0xef, 0xe9, 0x17, 0x7c, 0x4b, 0xc8, 0x54, 0x48, 0x2e, 0x7d, 0x96, 0x8b, - 0x71, 0x22, 0xfd, 0x98, 0x65, 0x4c, 0x72, 0x49, 0xf3, 0x42, 0x80, 0x20, 0x07, 0x35, 0x4a, 0x35, - 0x4a, 0x8f, 0xfa, 0x11, 0x83, 0xb0, 0xdf, 0xdb, 0x8f, 0x45, 0x2c, 0x14, 0xc5, 0xaf, 0xbe, 0x34, - 0xbb, 0x67, 0xc5, 0x42, 0xc4, 0x33, 0xe6, 0xab, 0x53, 0x54, 0x4e, 0xfd, 0x49, 0x59, 0x84, 0xc0, - 0x45, 0x56, 0xe3, 0xf6, 0xdf, 0x38, 0xf0, 0x94, 0x49, 0x08, 0xd3, 0x5c, 0x13, 0xdc, 0x45, 0x1b, - 0x77, 0x5f, 0x56, 0x4e, 0x6f, 0xb2, 0xa9, 0x20, 0x16, 0xc6, 0x7c, 0xc2, 0x32, 0xe0, 0x53, 0xce, - 0x0a, 0x13, 0x39, 0xc8, 0xeb, 0x06, 0x5b, 0x37, 0xe4, 0x23, 0xc6, 0x12, 0xc2, 0x02, 0x46, 0x95, - 0x8c, 0x79, 0xc1, 0x41, 0x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 0xe3, 0xbd, 0x57, 0x7a, 0x25, 0x87, 0x10, - 0x02, 0x23, 0xcf, 0x70, 0x47, 0xef, 0xa2, 0x89, 0x9c, 0x1d, 0x6f, 0xf7, 0xf0, 0x0e, 0x3d, 0x7f, - 0x45, 0xe9, 0x66, 0x8f, 0x06, 0xed, 0x2a, 0x7f, 0x50, 0x8f, 0x0d, 0xde, 0x1d, 0xaf, 0x2c, 0x74, - 0xb2, 0xb2, 0xd0, 0x8f, 0x95, 0x85, 0x16, 0x6b, 0xab, 0x75, 0xb2, 0xb6, 0x5a, 0xdf, 0xd6, 0x56, - 0xeb, 0x53, 0x3f, 0xe6, 0x90, 0x94, 0x11, 0x1d, 0x8b, 0xd4, 0xaf, 0x45, 0x1f, 0xcc, 0xc2, 0x48, - 0x36, 0x07, 0xff, 0xe8, 0xb1, 0xff, 0xb9, 0xf9, 0x4f, 0x60, 0x9e, 0x33, 0x19, 0x75, 0x54, 0xdd, - 0x0f, 0x7f, 0x05, 0x00, 0x00, 0xff, 0xff, 0xc4, 0x35, 0x0e, 0x9c, 0x46, 0x03, 0x00, 0x00, + 0x1c, 0xad, 0x69, 0x29, 0xad, 0xef, 0x10, 0x60, 0x1d, 0x47, 0xa8, 0x20, 0x09, 0x61, 0x89, 0x04, + 0x38, 0xb4, 0x30, 0xc1, 0x80, 0x54, 0x40, 0xfc, 0x11, 0x12, 0x52, 0xca, 0x80, 0x58, 0xaa, 0xa4, + 0x75, 0x13, 0x4b, 0x4d, 0x1c, 0xc5, 0xbf, 0x9c, 0xe8, 0xc6, 0x47, 0xe8, 0xc8, 0x47, 0xba, 0xf1, + 0x46, 0xa6, 0x82, 0xda, 0x8d, 0xf1, 0x3e, 0x01, 0x8a, 0x9d, 0x94, 0xc2, 0x1d, 0x62, 0x8b, 0xfd, + 0xde, 0xef, 0x3d, 0xbf, 0xa7, 0x5f, 0xf0, 0x2d, 0x21, 0x13, 0x21, 0xb9, 0xf4, 0x58, 0x26, 0x26, + 0xb1, 0xf4, 0x22, 0x96, 0x32, 0xc9, 0x25, 0xcd, 0x72, 0x01, 0x82, 0x1c, 0x56, 0x28, 0xd5, 0x28, + 0x3d, 0xea, 0x87, 0x0c, 0x82, 0x7e, 0xef, 0x20, 0x12, 0x91, 0x50, 0x14, 0xaf, 0xfc, 0xd2, 0xec, + 0x9e, 0x19, 0x09, 0x11, 0xcd, 0x99, 0xa7, 0x4e, 0x61, 0x31, 0xf3, 0xa6, 0x45, 0x1e, 0x00, 0x17, + 0x69, 0x85, 0x5b, 0x7f, 0xe3, 0xc0, 0x13, 0x26, 0x21, 0x48, 0x32, 0x4d, 0x70, 0x96, 0x2d, 0xdc, + 0x7d, 0x59, 0x3a, 0xbd, 0x49, 0x67, 0x82, 0x98, 0x18, 0xf3, 0x29, 0x4b, 0x81, 0xcf, 0x38, 0xcb, + 0x0d, 0x64, 0x23, 0xb7, 0xeb, 0xef, 0xdc, 0x90, 0x8f, 0x18, 0x4b, 0x08, 0x72, 0x18, 0x97, 0x32, + 0xc6, 0x05, 0x1b, 0xb9, 0x7b, 0x83, 0x1e, 0xd5, 0x1e, 0xb4, 0xf6, 0xa0, 0x1f, 0x6a, 0x8f, 0xe1, + 0xed, 0xe3, 0x95, 0xd5, 0x38, 0x5d, 0x59, 0xd7, 0x16, 0x41, 0x32, 0x7f, 0xe2, 0xfc, 0x9e, 0x75, + 0x96, 0xdf, 0x2d, 0xe4, 0x77, 0xd5, 0x45, 0x49, 0x27, 0x31, 0xee, 0xd4, 0x4f, 0x37, 0x9a, 0x4a, + 0xf7, 0xe6, 0x19, 0xdd, 0x17, 0x15, 0x61, 0xd8, 0x2f, 0x65, 0x7f, 0xae, 0x2c, 0x52, 0x8f, 0xdc, + 0x17, 0x09, 0x07, 0x96, 0x64, 0xb0, 0x38, 0x5d, 0x59, 0x57, 0xb4, 0x59, 0x8d, 0x39, 0x5f, 0x4b, + 0xab, 0xad, 0x3a, 0xb9, 0x8b, 0x2f, 0x4f, 0x8a, 0x3c, 0x67, 0x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xbe, + 0x1f, 0xfd, 0x0a, 0x00, 0x00, 0xff, 0xff, 0x80, 0x23, 0xaf, 0xf8, 0x47, 0x03, 0x00, 0x00, } func (m *EpochInfo) Marshal() (dAtA []byte, err error) { diff --git a/x/epochs/types/hooks.go b/x/epochs/types/hooks.go index f4519419fe4..b3d3adcf204 100644 --- a/x/epochs/types/hooks.go +++ b/x/epochs/types/hooks.go @@ -3,7 +3,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/osmoutils" + "github.com/osmosis-labs/osmosis/v10/osmoutils" ) type EpochHooks interface { diff --git a/x/epochs/types/hooks_test.go b/x/epochs/types/hooks_test.go index 3b3425dd0d5..78394b8745c 100644 --- a/x/epochs/types/hooks_test.go +++ b/x/epochs/types/hooks_test.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) type KeeperTestSuite struct { diff --git a/x/epochs/types/query.pb.go b/x/epochs/types/query.pb.go index c02a5e48ff6..47a74e050fa 100644 --- a/x/epochs/types/query.pb.go +++ b/x/epochs/types/query.pb.go @@ -211,30 +211,30 @@ var fileDescriptor_574bd176519c765f = []byte{ // 410 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x52, 0xcf, 0x6e, 0xd3, 0x30, 0x18, 0x8f, 0x5b, 0xa8, 0x84, 0x29, 0x17, 0x0b, 0x95, 0x10, 0x21, 0x53, 0x82, 0x80, 0x0a, 0xa9, - 0x31, 0x29, 0x07, 0x24, 0x2e, 0xa0, 0x22, 0x0e, 0x88, 0x13, 0x39, 0xf6, 0x82, 0x92, 0xe0, 0xa6, -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, 0x00, 0x00, + 0xff, 0xff, 0x5a, 0x35, 0x94, 0xdc, 0x43, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/gamm/client/cli/cli_test.go b/x/gamm/client/cli/cli_test.go index f98623f0772..532db9bc5c2 100644 --- a/x/gamm/client/cli/cli_test.go +++ b/x/gamm/client/cli/cli_test.go @@ -7,12 +7,12 @@ import ( "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/gamm/client/cli" - gammtestutil "github.com/osmosis-labs/osmosis/v7/x/gamm/client/testutil" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/gamm/client/cli" + gammtestutil "github.com/osmosis-labs/osmosis/v10/x/gamm/client/testutil" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" diff --git a/x/gamm/client/cli/query.go b/x/gamm/client/cli/query.go index 08e722bf42a..061577dc8a8 100644 --- a/x/gamm/client/cli/query.go +++ b/x/gamm/client/cli/query.go @@ -12,8 +12,8 @@ import ( "github.com/spf13/cobra" "gopkg.in/yaml.v2" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) // GetQueryCmd returns the cli query commands for this module. diff --git a/x/gamm/client/cli/tx.go b/x/gamm/client/cli/tx.go index 0f1fb2d86ca..506c092fcca 100644 --- a/x/gamm/client/cli/tx.go +++ b/x/gamm/client/cli/tx.go @@ -9,8 +9,8 @@ import ( "github.com/spf13/cobra" flag "github.com/spf13/pflag" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/gamm/client/testutil/test_helpers.go b/x/gamm/client/testutil/test_helpers.go index 630ecae2dd4..ce6f8bc2f84 100644 --- a/x/gamm/client/testutil/test_helpers.go +++ b/x/gamm/client/testutil/test_helpers.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - gammcli "github.com/osmosis-labs/osmosis/v7/x/gamm/client/cli" + gammcli "github.com/osmosis-labs/osmosis/v10/x/gamm/client/cli" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/gamm/keeper/export_test.go b/x/gamm/keeper/export_test.go index 005c6960e91..9ea0cae71eb 100644 --- a/x/gamm/keeper/export_test.go +++ b/x/gamm/keeper/export_test.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) // SetParams sets the total set of params. diff --git a/x/gamm/keeper/gas_test.go b/x/gamm/keeper/gas_test.go index b5dd575306f..8a94b3b6e79 100644 --- a/x/gamm/keeper/gas_test.go +++ b/x/gamm/keeper/gas_test.go @@ -4,9 +4,9 @@ import ( "fmt" "strconv" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - balancertypes "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + balancertypes "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/gamm/keeper/genesis.go b/x/gamm/keeper/genesis.go index ca66abfe584..590581408e7 100644 --- a/x/gamm/keeper/genesis.go +++ b/x/gamm/keeper/genesis.go @@ -4,7 +4,7 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) // InitGenesis initializes the x/gamm module's state from a provided genesis diff --git a/x/gamm/keeper/genesis_test b/x/gamm/keeper/genesis_test index 30d011e07ca..f522de32fa0 100644 --- a/x/gamm/keeper/genesis_test +++ b/x/gamm/keeper/genesis_test @@ -11,10 +11,10 @@ import ( "github.com/tendermint/tendermint/crypto/ed25519" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - osmoapp "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/gamm" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + osmoapp "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/gamm" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func TestGammInitGenesis(t *testing.T) { diff --git a/x/gamm/keeper/grpc_query.go b/x/gamm/keeper/grpc_query.go index 5bc9c77c6b2..a404369e698 100644 --- a/x/gamm/keeper/grpc_query.go +++ b/x/gamm/keeper/grpc_query.go @@ -14,8 +14,8 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var sdkIntMaxValue = sdk.NewInt(0) diff --git a/x/gamm/keeper/grpc_query_test.go b/x/gamm/keeper/grpc_query_test.go index 5544c95316d..5dfa6aa1e97 100644 --- a/x/gamm/keeper/grpc_query_test.go +++ b/x/gamm/keeper/grpc_query_test.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func (suite *KeeperTestSuite) TestQueryPool() { diff --git a/x/gamm/keeper/internal/events/emit.go b/x/gamm/keeper/internal/events/emit.go index a9d68682fde..32d0559e860 100644 --- a/x/gamm/keeper/internal/events/emit.go +++ b/x/gamm/keeper/internal/events/emit.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func EmitSwapEvent(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) { diff --git a/x/gamm/keeper/internal/events/emit_test.go b/x/gamm/keeper/internal/events/emit_test.go index 15d60dc5d52..eac138c0e1a 100644 --- a/x/gamm/keeper/internal/events/emit_test.go +++ b/x/gamm/keeper/internal/events/emit_test.go @@ -7,9 +7,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper/internal/events" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper/internal/events" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) type GammEventsTestSuite struct { diff --git a/x/gamm/keeper/invariants.go b/x/gamm/keeper/invariants.go index 95f970d3f59..e25639a0321 100644 --- a/x/gamm/keeper/invariants.go +++ b/x/gamm/keeper/invariants.go @@ -7,7 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) const poolBalanceInvariantName = "pool-account-balance-equals-expected" diff --git a/x/gamm/keeper/keeper.go b/x/gamm/keeper/keeper.go index 6e557a5247e..f88f3903896 100644 --- a/x/gamm/keeper/keeper.go +++ b/x/gamm/keeper/keeper.go @@ -3,7 +3,7 @@ package keeper import ( "fmt" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/gamm/keeper/keeper_test.go b/x/gamm/keeper/keeper_test.go index 1433fc51305..6f5b26a25db 100644 --- a/x/gamm/keeper/keeper_test.go +++ b/x/gamm/keeper/keeper_test.go @@ -7,10 +7,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - balancertypes "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + balancertypes "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) type KeeperTestSuite struct { diff --git a/x/gamm/keeper/marshal_bench_test.go b/x/gamm/keeper/marshal_bench_test.go index f9f0f9db9a0..132c6ddd550 100644 --- a/x/gamm/keeper/marshal_bench_test.go +++ b/x/gamm/keeper/marshal_bench_test.go @@ -5,10 +5,10 @@ import ( "testing" "time" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - balancertypes "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + balancertypes "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" sdk "github.com/cosmos/cosmos-sdk/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" diff --git a/x/gamm/keeper/msg_server.go b/x/gamm/keeper/msg_server.go index 357a4da60aa..5e3ce495e61 100644 --- a/x/gamm/keeper/msg_server.go +++ b/x/gamm/keeper/msg_server.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) type msgServer struct { diff --git a/x/gamm/keeper/msg_server_test.go b/x/gamm/keeper/msg_server_test.go index a4011404e5f..a52251162e2 100644 --- a/x/gamm/keeper/msg_server_test.go +++ b/x/gamm/keeper/msg_server_test.go @@ -4,8 +4,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) const ( diff --git a/x/gamm/keeper/multihop.go b/x/gamm/keeper/multihop.go index 1e80fb17c8d..a964874fde3 100644 --- a/x/gamm/keeper/multihop.go +++ b/x/gamm/keeper/multihop.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) // MultihopSwapExactAmountIn defines the input denom and input amount for the first pool, diff --git a/x/gamm/keeper/multihop_test.go b/x/gamm/keeper/multihop_test.go index e92ee724e19..17a08debead 100644 --- a/x/gamm/keeper/multihop_test.go +++ b/x/gamm/keeper/multihop_test.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func (suite *KeeperTestSuite) TestBalancerPoolSimpleMultihopSwapExactAmountIn() { diff --git a/x/gamm/keeper/params.go b/x/gamm/keeper/params.go index 420c3413e1d..50ff384dc7e 100644 --- a/x/gamm/keeper/params.go +++ b/x/gamm/keeper/params.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/gamm/keeper/pool.go b/x/gamm/keeper/pool.go index f347d5eeaba..9617ffb3f03 100644 --- a/x/gamm/keeper/pool.go +++ b/x/gamm/keeper/pool.go @@ -8,9 +8,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/stableswap" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/stableswap" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func (k Keeper) MarshalPool(pool types.PoolI) ([]byte, error) { diff --git a/x/gamm/keeper/pool_service.go b/x/gamm/keeper/pool_service.go index fe6aeef3f7b..904e14e96d4 100644 --- a/x/gamm/keeper/pool_service.go +++ b/x/gamm/keeper/pool_service.go @@ -8,7 +8,7 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) // CalculateSpotPrice returns the spot price of the quote asset in terms of the base asset, diff --git a/x/gamm/keeper/pool_service_test.go b/x/gamm/keeper/pool_service_test.go index 2e8492ee9be..9201d44d094 100644 --- a/x/gamm/keeper/pool_service_test.go +++ b/x/gamm/keeper/pool_service_test.go @@ -6,9 +6,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - balancertypes "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + balancertypes "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var ( diff --git a/x/gamm/keeper/pool_test.go b/x/gamm/keeper/pool_test.go index 78aa914d16a..fa4e7e02047 100644 --- a/x/gamm/keeper/pool_test.go +++ b/x/gamm/keeper/pool_test.go @@ -7,7 +7,7 @@ package keeper_test // "github.com/cosmos/cosmos-sdk/simapp" // sdk "github.com/cosmos/cosmos-sdk/types" -// "github.com/osmosis-labs/osmosis/v7/x/gamm/types" +// "github.com/osmosis-labs/osmosis/v10/x/gamm/types" // ) // func (suite *KeeperTestSuite) TestCleanupPool() { diff --git a/x/gamm/keeper/share.go b/x/gamm/keeper/share.go index a5de4174066..194e7727117 100644 --- a/x/gamm/keeper/share.go +++ b/x/gamm/keeper/share.go @@ -3,8 +3,8 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper/internal/events" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper/internal/events" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func (k Keeper) applyJoinPoolStateChange(ctx sdk.Context, pool types.PoolI, joiner sdk.AccAddress, numShares sdk.Int, joinCoins sdk.Coins) error { diff --git a/x/gamm/keeper/swap.go b/x/gamm/keeper/swap.go index a899c20bfd9..3c03818ac90 100644 --- a/x/gamm/keeper/swap.go +++ b/x/gamm/keeper/swap.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper/internal/events" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper/internal/events" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) // SwapExactAmountIn attempts to swap one asset, tokenIn, for another asset diff --git a/x/gamm/keeper/swap_test.go b/x/gamm/keeper/swap_test.go index 4837a9f25fd..a6416198880 100644 --- a/x/gamm/keeper/swap_test.go +++ b/x/gamm/keeper/swap_test.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var _ = suite.TestingSuite(nil) diff --git a/x/gamm/keeper/total_liquidity.go b/x/gamm/keeper/total_liquidity.go index c82b0e9126b..e6db8b7dde8 100644 --- a/x/gamm/keeper/total_liquidity.go +++ b/x/gamm/keeper/total_liquidity.go @@ -4,7 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func (k Keeper) GetTotalLiquidity(ctx sdk.Context) sdk.Coins { diff --git a/x/gamm/module.go b/x/gamm/module.go index ce1f7ae38cd..a5352f99272 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -16,12 +16,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - gammsimulation "github.com/osmosis-labs/osmosis/v7/x/gamm/simulation" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + gammsimulation "github.com/osmosis-labs/osmosis/v10/x/gamm/simulation" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var ( diff --git a/x/gamm/pool-models/balancer/amm.go b/x/gamm/pool-models/balancer/amm.go index a574cef411d..d24714d5a2c 100644 --- a/x/gamm/pool-models/balancer/amm.go +++ b/x/gamm/pool-models/balancer/amm.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/osmomath" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/osmomath" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) // subPoolAssetWeights subtracts the weights of two different pool asset slices. diff --git a/x/gamm/pool-models/balancer/amm_test.go b/x/gamm/pool-models/balancer/amm_test.go index 707da15924a..1912a05bba0 100644 --- a/x/gamm/pool-models/balancer/amm_test.go +++ b/x/gamm/pool-models/balancer/amm_test.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/test_helpers" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/internal/test_helpers" ) type BalancerTestSuite struct { diff --git a/x/gamm/pool-models/balancer/balancerPool.pb.go b/x/gamm/pool-models/balancer/balancerPool.pb.go index a19f10e90e1..c6d887afc99 100644 --- a/x/gamm/pool-models/balancer/balancerPool.pb.go +++ b/x/gamm/pool-models/balancer/balancerPool.pb.go @@ -298,58 +298,58 @@ func init() { var fileDescriptor_7e991f749f68c2a4 = []byte{ // 831 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0x4f, 0x6f, 0xeb, 0x44, - 0x10, 0x8f, 0x93, 0xb4, 0x79, 0xdd, 0x3c, 0x1e, 0xea, 0xbe, 0x1c, 0xdc, 0x54, 0xc4, 0xd5, 0x22, - 0xa1, 0x27, 0xf4, 0x62, 0xab, 0x0f, 0x24, 0xa4, 0x1e, 0x40, 0x4d, 0x5b, 0x50, 0x6f, 0xc5, 0x45, - 0x6a, 0x41, 0x95, 0xac, 0x4d, 0xb2, 0xb1, 0xad, 0xda, 0x5e, 0xcb, 0xbb, 0x49, 0xdb, 0x6f, 0xc0, - 0xb1, 0xc7, 0x72, 0xeb, 0x9d, 0x2b, 0x7c, 0x87, 0x0a, 0x2e, 0x3d, 0x22, 0x0e, 0x06, 0xb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 0x1e, 0x48, 0x0b, 0x1e, 0xeb, 0xa9, 0x60, 0x21, 0x05, 0x66, 0xae, 0x3e, 0xee, 0x79, 0x37, 0x35, + 0x3e, 0x54, 0xf8, 0x73, 0x08, 0x7a, 0x16, 0x32, 0x8c, 0xc1, 0xa0, 0x20, 0xae, 0x95, 0x51, 0x93, + 0x33, 0xd8, 0x7d, 0xb2, 0x32, 0xee, 0xf5, 0x51, 0xe8, 0x43, 0xf5, 0xa1, 0xe4, 0xfd, 0x76, 0xfd, + 0xfb, 0x2b, 0xab, 0x74, 0x79, 0x65, 0x95, 0x7e, 0xf9, 0xa9, 0xbd, 0x22, 0x88, 0xee, 0x75, 0x8f, + 0xae, 0x6f, 0x5b, 0xc6, 0xcd, 0x6d, 0xcb, 0xf8, 0xf3, 0xb6, 0x65, 0x5c, 0xdc, 0xb5, 0x4a, 0x37, + 0x77, 0xad, 0xd2, 0x6f, 0x77, 0xad, 0xd2, 0x77, 0xef, 0xe6, 0x0a, 0xeb, 0x4e, 0xdb, 0x11, 0xee, + 0xb1, 0xc2, 0x70, 0xc6, 0x9d, 0xcf, 0x9c, 0xb3, 0xe5, 0x7f, 0xa8, 0xbd, 0x55, 0xf9, 0x91, 0xff, + 0xfc, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfd, 0x85, 0x4a, 0xe3, 0x7c, 0x07, 0x00, 0x00, } func (m *SmoothWeightChangeParams) Marshal() (dAtA []byte, err error) { diff --git a/x/gamm/pool-models/balancer/codec.go b/x/gamm/pool-models/balancer/codec.go index e01898a4b8e..06f6a4c3c08 100644 --- a/x/gamm/pool-models/balancer/codec.go +++ b/x/gamm/pool-models/balancer/codec.go @@ -1,7 +1,7 @@ package balancer import ( - types "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + types "github.com/osmosis-labs/osmosis/v10/x/gamm/types" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" diff --git a/x/gamm/pool-models/balancer/marshal_test.go b/x/gamm/pool-models/balancer/marshal_test.go index 56756466942..656c894ea88 100644 --- a/x/gamm/pool-models/balancer/marshal_test.go +++ b/x/gamm/pool-models/balancer/marshal_test.go @@ -8,7 +8,7 @@ import ( "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/gamm/pool-models/balancer/msgs.go b/x/gamm/pool-models/balancer/msgs.go index 400fa26f93a..229b02e0eb2 100644 --- a/x/gamm/pool-models/balancer/msgs.go +++ b/x/gamm/pool-models/balancer/msgs.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) const ( diff --git a/x/gamm/pool-models/balancer/msgs_test.go b/x/gamm/pool-models/balancer/msgs_test.go index c0d556994c9..420ce37ae63 100644 --- a/x/gamm/pool-models/balancer/msgs_test.go +++ b/x/gamm/pool-models/balancer/msgs_test.go @@ -8,8 +8,8 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" - appParams "github.com/osmosis-labs/osmosis/v7/app/params" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + appParams "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func TestMsgCreateBalancerPool(t *testing.T) { diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index 4169067aa0e..f0c887b7bd8 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -10,9 +10,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/osmomath" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/cfmm_common" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/osmomath" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/internal/cfmm_common" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) //nolint:deadcode diff --git a/x/gamm/pool-models/balancer/pool_asset.go b/x/gamm/pool-models/balancer/pool_asset.go index ecfc06411cc..2041ccd9ed8 100644 --- a/x/gamm/pool-models/balancer/pool_asset.go +++ b/x/gamm/pool-models/balancer/pool_asset.go @@ -5,7 +5,7 @@ import ( "sort" "strings" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" "gopkg.in/yaml.v2" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/gamm/pool-models/balancer/pool_params.go b/x/gamm/pool-models/balancer/pool_params.go index 1d25fe33402..886363851c8 100644 --- a/x/gamm/pool-models/balancer/pool_params.go +++ b/x/gamm/pool-models/balancer/pool_params.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func NewPoolParams(swapFee, exitFee sdk.Dec, params *SmoothWeightChangeParams) PoolParams { diff --git a/x/gamm/pool-models/balancer/pool_suite_test.go b/x/gamm/pool-models/balancer/pool_suite_test.go index 20c21e5734a..0459810672f 100644 --- a/x/gamm/pool-models/balancer/pool_suite_test.go +++ b/x/gamm/pool-models/balancer/pool_suite_test.go @@ -11,11 +11,11 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - v10 "github.com/osmosis-labs/osmosis/v7/app/upgrades/v10" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + v10 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v10" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) const ( diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go index fd13bd7766a..f96943d7510 100644 --- a/x/gamm/pool-models/balancer/pool_test.go +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -9,9 +9,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var ( diff --git a/x/gamm/pool-models/balancer/tx.pb.go b/x/gamm/pool-models/balancer/tx.pb.go index b10cb4e3eed..dd2f853aa3c 100644 --- a/x/gamm/pool-models/balancer/tx.pb.go +++ b/x/gamm/pool-models/balancer/tx.pb.go @@ -152,33 +152,33 @@ func init() { var fileDescriptor_0647ee155de97433 = []byte{ // 427 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xc1, 0x8a, 0xd4, 0x30, - 0x18, 0x80, 0x27, 0x3b, 0x43, 0xc5, 0x0c, 0x1e, 0x0c, 0xab, 0x94, 0x11, 0xdb, 0x52, 0x2f, 0xf5, - 0x30, 0x09, 0x3b, 0x0a, 0x82, 0x07, 0xc5, 0xba, 0xb8,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9f, 0x91, 0xcd, 0xfe, 0xb5, 0x4c, 0x1d, 0xb3, 0x8a, 0x4f, 0x7e, 0x05, 0x00, - 0x00, 0xff, 0xff, 0x56, 0x65, 0x86, 0x28, 0x31, 0x03, 0x00, 0x00, + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xc1, 0x6e, 0xd3, 0x30, + 0x18, 0x80, 0xeb, 0xb5, 0x0a, 0xc2, 0x15, 0x07, 0xac, 0x81, 0xa2, 0x22, 0x92, 0x28, 0x5c, 0xc2, + 0xa1, 0x36, 0x2d, 0x9c, 0xb8, 0x4c, 0x84, 0x89, 0x69, 0x87, 0x49, 0x23, 0xb7, 0x71, 0x99, 0x9c, + 0xc5, 0x84, 0x4a, 0x49, 0x1c, 0xd9, 0x6e, 0x55, 0xde, 0x82, 0x27, 0xe0, 0xc8, 0x33, 0xf0, 0x08, + 0x3b, 0xee, 0xc8, 0x29, 0x42, 0xe9, 0x1b, 0xf4, 0x09, 0x90, 0xed, 0x04, 0x0d, 0x29, 0x13, 0x48, + 0xdc, 0x9c, 0xdf, 0xdf, 0xff, 0xfd, 0xff, 0xef, 0xfc, 0x70, 0xce, 0x65, 0xc9, 0xe5, 0x4a, 0x92, + 0x9c, 0x96, 0x25, 0xa9, 0x39, 0x2f, 0xe6, 0x25, 0xcf, 0x58, 0x21, 0x49, 0x4a, 0x0b, 0x5a, 0x5d, + 0x31, 0x41, 0xd4, 0x96, 0xa8, 0x2d, 0xae, 0x05, 0x57, 0x1c, 0x45, 0x1d, 0x8e, 0x35, 0x8e, 0x35, + 0x6e, 0x69, 0xdc, 0xd3, 0x78, 0xb3, 0x48, 0x99, 0xa2, 0x8b, 0xd9, 0x61, 0xce, 0x73, 0x6e, 0x92, + 0x88, 0x3e, 0xd9, 0xfc, 0xd9, 0xab, 0xbf, 0x97, 0xeb, 0x0f, 0xe7, 0x9c, 0x17, 0x36, 0x2b, 0xfc, + 0x7e, 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f, 0x01, 0x44, 0x03, 0x7f, 0xe1, 0x08, 0xff, 0xeb, 0x5a, 0xe0, + 0xc1, 0x66, 0x66, 0x27, 0xff, 0x29, 0xe8, 0xa7, 0x89, 0x2f, 0xae, 0x5b, 0x0f, 0xdc, 0xb4, 0x1e, + 0xf8, 0xd9, 0x7a, 0xe0, 0xcb, 0xce, 0x1b, 0xdd, 0xec, 0xbc, 0xd1, 0x8f, 0x9d, 0x37, 0xfa, 0x70, + 0x94, 0xaf, 0xd4, 0xa7, 0x75, 0x8a, 0xaf, 0x78, 0x49, 0xba, 0x62, 0xf3, 0x82, 0xa6, 0xb2, 0xff, + 0x20, 0x9b, 0xc5, 0x0b, 0xb2, 0xbd, 0x7b, 0x2f, 0x53, 0xc7, 0xec, 0xe2, 0xcb, 0x5f, 0x01, 0x00, + 0x00, 0xff, 0xff, 0x69, 0x2b, 0x7d, 0x0d, 0x32, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/gamm/pool-models/balancer/util_test.go b/x/gamm/pool-models/balancer/util_test.go index c5e8405b696..bfab4df455d 100644 --- a/x/gamm/pool-models/balancer/util_test.go +++ b/x/gamm/pool-models/balancer/util_test.go @@ -12,9 +12,9 @@ import ( tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func createTestPool(t *testing.T, swapFee, exitFee sdk.Dec, poolAssets ...balancer.PoolAsset) types.PoolI { diff --git a/x/gamm/pool-models/internal/cfmm_common/lp.go b/x/gamm/pool-models/internal/cfmm_common/lp.go index ffcd9559f5e..f963fe18cbc 100644 --- a/x/gamm/pool-models/internal/cfmm_common/lp.go +++ b/x/gamm/pool-models/internal/cfmm_common/lp.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) const errMsgFormatSharesLargerThanMax = "%s resulted shares is larger than the max amount of %s" diff --git a/x/gamm/pool-models/internal/cfmm_common/lp_test.go b/x/gamm/pool-models/internal/cfmm_common/lp_test.go index abb62f267c8..e203acd6aff 100644 --- a/x/gamm/pool-models/internal/cfmm_common/lp_test.go +++ b/x/gamm/pool-models/internal/cfmm_common/lp_test.go @@ -6,10 +6,10 @@ import ( "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/cfmm_common" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/stableswap" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/internal/cfmm_common" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/stableswap" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/gamm/pool-models/internal/test_helpers/test_helpers.go b/x/gamm/pool-models/internal/test_helpers/test_helpers.go index ba1f7dad435..60921ef9529 100644 --- a/x/gamm/pool-models/internal/test_helpers/test_helpers.go +++ b/x/gamm/pool-models/internal/test_helpers/test_helpers.go @@ -10,8 +10,8 @@ import ( tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) // CfmmCommonTestSuite is the common test suite struct of Constant Function Market Maker, diff --git a/x/gamm/pool-models/stableswap/amm.go b/x/gamm/pool-models/stableswap/amm.go index 7872d5d02fe..47356e3e27e 100644 --- a/x/gamm/pool-models/stableswap/amm.go +++ b/x/gamm/pool-models/stableswap/amm.go @@ -5,8 +5,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/cfmm_common" - types "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/internal/cfmm_common" + types "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var ( diff --git a/x/gamm/pool-models/stableswap/amm_test.go b/x/gamm/pool-models/stableswap/amm_test.go index 881de9fcc41..e77f83d5ec8 100644 --- a/x/gamm/pool-models/stableswap/amm_test.go +++ b/x/gamm/pool-models/stableswap/amm_test.go @@ -7,7 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/test_helpers" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/internal/test_helpers" ) type StableSwapTestSuite struct { diff --git a/x/gamm/pool-models/stableswap/codec.go b/x/gamm/pool-models/stableswap/codec.go index 168d535d33b..2d1a01f57d8 100644 --- a/x/gamm/pool-models/stableswap/codec.go +++ b/x/gamm/pool-models/stableswap/codec.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" - types "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + types "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) // RegisterLegacyAminoCodec registers the necessary x/gamm interfaces and concrete types diff --git a/x/gamm/pool-models/stableswap/msgs.go b/x/gamm/pool-models/stableswap/msgs.go index 4661693164d..2182d825723 100644 --- a/x/gamm/pool-models/stableswap/msgs.go +++ b/x/gamm/pool-models/stableswap/msgs.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) const ( diff --git a/x/gamm/pool-models/stableswap/msgs_test.go b/x/gamm/pool-models/stableswap/msgs_test.go index 250483dc3de..301aa5ffa50 100644 --- a/x/gamm/pool-models/stableswap/msgs_test.go +++ b/x/gamm/pool-models/stableswap/msgs_test.go @@ -8,8 +8,8 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" - appParams "github.com/osmosis-labs/osmosis/v7/app/params" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + appParams "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func TestMsgCreateStableswapPool(t *testing.T) { diff --git a/x/gamm/pool-models/stableswap/pool.go b/x/gamm/pool-models/stableswap/pool.go index 8ab7e1f962a..82eaba14aa9 100644 --- a/x/gamm/pool-models/stableswap/pool.go +++ b/x/gamm/pool-models/stableswap/pool.go @@ -9,8 +9,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/internal/cfmm_common" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/internal/cfmm_common" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var _ types.PoolI = &Pool{} diff --git a/x/gamm/pool-models/stableswap/pool_params.go b/x/gamm/pool-models/stableswap/pool_params.go index 7927e6604f8..6d5289c028e 100644 --- a/x/gamm/pool-models/stableswap/pool_params.go +++ b/x/gamm/pool-models/stableswap/pool_params.go @@ -3,7 +3,7 @@ package stableswap import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func (params PoolParams) Validate() error { diff --git a/x/gamm/pool-models/stableswap/stableswap_pool.pb.go b/x/gamm/pool-models/stableswap/stableswap_pool.pb.go index a2fdd1ab03f..ff197c18690 100644 --- a/x/gamm/pool-models/stableswap/stableswap_pool.pb.go +++ b/x/gamm/pool-models/stableswap/stableswap_pool.pb.go @@ -136,47 +136,47 @@ func init() { } var fileDescriptor_ae0f054436f9999a = []byte{ - // 632 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0xc1, 0x6e, 0xd3, 0x40, - 0x10, 0x8d, 0xdb, 0xb4, 0x29, 0x5b, 0x1a, 0x84, 0x29, 0xc2, 0x6d, 0x85, 0x37, 0x5a, 0x09, 0x14, - 0x21, 0x62, 0x53, 0x90, 0x40, 0xf4, 0x04, 0x01, 0x15, 0x21, 0x21, 0x51, 0xcc, 0x89, 0x0a, 0x29, - 0x5a, 0xdb, 0x1b, 0x77, 0x85, 0x9d, 0x35, 0xde, 0x75, 0x69, 0x2f, 0x9c, 0x39, 0x72, 0xe4, 0xd8, - 0x13, 0x07, 0xce, 0x7c, 0x44, 0xc5, 0xa9, 0x47, 0xc4, 0xc1, 0xa0, 0xf6, 0x0f, 0xf2, 0x05, 0x68, - 0xd7, 0xeb, 0x26, 0x29, 0x55, 0x55, 0x89, 0x53, 0x76, 0x66, 0xde, 0xbc, 0x99, 0x79, 0x33, 0x31, - 0x78, 0xc8, 0x78, 0xc2, 0x38, 0xe5, 0x6e, 0x84, 0x93, 0xc4, 0x4d, 0x19, 0x8b, 0x3b, 0x09, 0x0b, - 0x49, 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 0x7f, - 0xfb, 0x0d, 0xdb, 0xe7, 0xd8, 0xb9, 0x4c, 0xe0, 0xde, 0x82, 0x2c, 0xf1, 0xa2, 0xaa, 0x60, 0xbe, - 0x04, 0x4d, 0x1e, 0xe0, 0x98, 0x0e, 0xa2, 0x5e, 0x1f, 0x07, 0x82, 0x65, 0x56, 0xa3, 0x35, 0xdd, - 0xae, 0x77, 0xdb, 0xba, 0xeb, 0xd6, 0x3f, 0x62, 0x4f, 0xc2, 0x91, 0xb7, 0xa0, 0x1d, 0xeb, 0xca, - 0x36, 0x37, 0xc1, 0xb5, 0x49, 0xc4, 0x48, 0xf5, 0x39, 0xa5, 0x3a, 0x1a, 0x16, 0xd0, 0xd6, 0xac, - 0xa7, 0x03, 0x91, 0x77, 0x75, 0x82, 0xb3, 0xd2, 0x7e, 0xed, 0xf2, 0xa7, 0x3d, 0x58, 0xfb, 0xb2, - 0x07, 0x6b, 0x3f, 0xbe, 0x77, 0x66, 0xe4, 0x56, 0x9e, 0x77, 0x37, 0xf7, 0x0f, 0x6d, 0xe3, 0xe0, - 0xd0, 0x36, 0xfe, 0x1c, 0xda, 0xc6, 0xe7, 0x23, 0xbb, 0x76, 0x70, 0x64, 0xd7, 0x7e, 0x1e, 0xd9, - 0xb5, 0xcd, 0x47, 0x63, 0x92, 0xe8, 0x83, 0xeb, 0xc4, 0xd8, 0xe7, 0x95, 0xe1, 0x6e, 0x3f, 0x70, - 0x77, 0xce, 0xfa, 0x86, 0xf9, 0xb3, 0xea, 0x6f, 0x7d, 0xef, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, - 0x44, 0x51, 0xea, 0xde, 0xf1, 0x04, 0x00, 0x00, + // 634 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0xc1, 0x6e, 0xd3, 0x4c, + 0x10, 0x8e, 0xdb, 0xb4, 0xe9, 0xbf, 0xfd, 0x1b, 0x84, 0x29, 0xc2, 0x6d, 0x85, 0x37, 0x5a, 0x09, + 0x14, 0x21, 0x62, 0xb7, 0x20, 0x21, 0xd1, 0x5b, 0x03, 0x2a, 0x42, 0x42, 0xa2, 0x98, 0x13, 0x05, + 0x29, 0x5a, 0xdb, 0x1b, 0x77, 0x85, 0x9d, 0x35, 0xde, 0x75, 0x69, 0x2f, 0x9c, 0x39, 0x72, 0xe4, + 0xd8, 0x13, 0x07, 0xce, 0x3c, 0x44, 0xc5, 0xa9, 0x47, 0xc4, 0xc1, 0xa0, 0xf6, 0x0d, 0xf2, 0x04, + 0x68, 0xd7, 0xeb, 0x26, 0x29, 0x55, 0x55, 0x89, 0x53, 0x76, 0x66, 0xbe, 0xf9, 0x66, 0xe6, 0x9b, + 0x89, 0xc1, 0x43, 0xc6, 0x13, 0xc6, 0x29, 0x77, 0x23, 0x9c, 0x24, 0x6e, 0xca, 0x58, 0xdc, 0x49, + 0x58, 0x48, 0x62, 0xee, 0x72, 0x81, 0xfd, 0x98, 0xf0, 0xf7, 0x38, 0x1d, 0x7b, 0xf6, 0x24, 0xc2, + 0x49, 0x33, 0x26, 0x98, 0x79, 0x47, 0xa7, 0x3a, 0x32, 0xd5, 0x91, 0x81, 0x32, 0xd3, 0x19, 0xc1, + 0x9d, 0xdd, 0x35, 0x9f, 0x08, 0xbc, 0xb6, 0xbc, 0x14, 0x28, 0x70, 0x4f, 0x65, 0xba, 0xa5, 0x51, + 0xd2, 0x2c, 0x2f, 0x46, 0x2c, 0x62, 0xa5, 0x5f, 0xbe, 0xb4, 0xd7, 0x8e, 0x18, 0x8b, 0x62, 0xe2, + 0x2a, 0xcb, 0xcf, 0xfb, 0x6e, 0x98, 0x67, 0x58, 0x50, 0x36, 0xd0, 0x71, 0x78, 0x36, 0x2e, 0x68, + 0x42, 0xb8, 0xc0, 0x49, 0x5a, 0x11, 0x94, 0x45, 0x5c, 0x9c, 0x8b, 0x1d, 0x57, 0xb7, 0xa1, 0x8c, + 0x33, 0x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0xf0, 0xd8, 0x36, + 0x8e, 0x8e, 0x6d, 0xe3, 0xf7, 0xb1, 0x6d, 0x7c, 0x3a, 0xb1, 0x6b, 0x47, 0x27, 0x76, 0xed, 0xc7, + 0x89, 0x5d, 0xdb, 0xde, 0x18, 0x93, 0x44, 0x1f, 0x5c, 0x27, 0xc6, 0x3e, 0xaf, 0x0c, 0x77, 0x77, + 0x6d, 0xd5, 0xdd, 0xbb, 0xe8, 0x23, 0xe6, 0xcf, 0xaa, 0xff, 0xf5, 0xfd, 0x3f, 0x01, 0x00, 0x00, + 0xff, 0xff, 0xfa, 0x42, 0xbe, 0x54, 0xf2, 0x04, 0x00, 0x00, } func (m *PoolParams) Marshal() (dAtA []byte, err error) { diff --git a/x/gamm/pool-models/stableswap/tx.pb.go b/x/gamm/pool-models/stableswap/tx.pb.go index 40a2b7f36f3..f666bb53c64 100644 --- a/x/gamm/pool-models/stableswap/tx.pb.go +++ b/x/gamm/pool-models/stableswap/tx.pb.go @@ -256,44 +256,44 @@ func init() { } var fileDescriptor_46b7c8a0f24de97c = []byte{ - // 583 bytes of a gzipped FileDescriptorProto + // 584 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x94, 0x4d, 0x6f, 0xd3, 0x3e, - 0x1c, 0xc7, 0x9b, 0xb6, 0xea, 0x5f, 0x7f, 0x57, 0x80, 0x88, 0xaa, 0x51, 0x8a, 0x94, 0x94, 0x70, - 0xe9, 0x80, 0xc6, 0xac, 0x48, 0x20, 0x38, 0x41, 0x8a, 0x86, 0x26, 0xa8, 0xb4, 0xa5, 0xe2, 0xb2, - 0x4b, 0xe5, 0x34, 0x5e, 0x30, 0x24, 0x71, 0x88, 0xdd, 0x6e, 0x3d, 0x72, 0xe7, 0xc0, 0xcb, 0x40, - 0xbc, 0x90, 0x69, 0xc7, 0x1d, 0x39, 0x05, 0xd4, 0xbe, 0x83, 0xde, 0xb8, 0x21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0xed, 0x23, 0x9f, 0x84, 0xde, 0x2e, 0xea, 0x73, 0x1a, 0xb3, 0x75, + 0x06, 0xbc, 0xe4, 0xba, 0xb1, 0xca, 0x55, 0x3d, 0x00, 0x77, 0x98, 0x74, 0xe8, 0x1d, 0x4a, 0x8b, + 0x74, 0x18, 0x05, 0xab, 0x2e, 0x3a, 0x3e, 0x4d, 0xf4, 0x5a, 0x26, 0xbe, 0x38, 0x8a, 0xe7, 0x79, + 0xc3, 0xbe, 0xcd, 0xce, 0xa5, 0x68, 0x3c, 0x01, 0x5b, 0x57, 0xd6, 0x31, 0x6b, 0x4d, 0xeb, 0xef, + 0x06, 0xc8, 0x77, 0x98, 0xa7, 0xfe, 0x50, 0x40, 0xf9, 0xc2, 0x13, 0xdd, 0x5e, 0xe7, 0x44, 0xae, + 0x18, 0x44, 0xf5, 0xcd, 0x0d, 0x88, 0xcc, 0xa7, 0x79, 0xa2, 0x00, 0xed, 0x8a, 0x29, 0x75, 0xd6, + 0xf4, 0xbb, 0x5c, 0xae, 0xfa, 0xee, 0x46, 0xe5, 0x66, 0x85, 0x58, 0x1f, 0x4e, 0xc7, 0x9a, 0x72, + 0x36, 0xd6, 0x94, 0x3f, 0x63, 0x4d, 0xf9, 0x3e, 0xd1, 0x72, 0x67, 0x13, 0x2d, 0xf7, 0x6b, 0xa2, + 0xe5, 0xde, 0xef, 0x2c, 0xfd, 0x66, 0x99, 0x75, 0xc3, 0x47, 0x0e, 0x9b, 0xbd, 0xc0, 0x61, 0x73, + 0x1b, 0x1e, 0x5f, 0x76, 0x77, 0x39, 0xc5, 0xf4, 0xb2, 0x7a, 0xf6, 0x2f, 0x00, 0x00, 0xff, 0xff, + 0xdb, 0xb6, 0x17, 0x10, 0x79, 0x05, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/gamm/pool-models/stableswap/util_test.go b/x/gamm/pool-models/stableswap/util_test.go index d1dbaa82702..eba4517ad31 100644 --- a/x/gamm/pool-models/stableswap/util_test.go +++ b/x/gamm/pool-models/stableswap/util_test.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func createTestPool(t *testing.T, poolLiquidity sdk.Coins, swapFee, exitFee sdk.Dec) types.PoolI { diff --git a/x/gamm/simulation/sim_msgs.go b/x/gamm/simulation/sim_msgs.go index 29841a1c087..bb6fe0dc672 100644 --- a/x/gamm/simulation/sim_msgs.go +++ b/x/gamm/simulation/sim_msgs.go @@ -6,11 +6,11 @@ import ( "github.com/cosmos/cosmos-sdk/server/rosetta/lib/errors" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - balancertypes "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + balancertypes "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) func CurrySimMsgJoinPool(k keeper.Keeper) func(sim *simulation.SimCtx, ctx sdk.Context) (*gammtypes.MsgJoinPool, error) { diff --git a/x/gamm/twap/hook_listener.go b/x/gamm/twap/hook_listener.go index 4b84676b3d4..2a5163577d4 100644 --- a/x/gamm/twap/hook_listener.go +++ b/x/gamm/twap/hook_listener.go @@ -3,7 +3,7 @@ package twap import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var _ types.GammHooks = &gammhook{} diff --git a/x/gamm/twap/module.go b/x/gamm/twap/module.go index 9dae3925b85..e15b401601f 100644 --- a/x/gamm/twap/module.go +++ b/x/gamm/twap/module.go @@ -16,9 +16,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/osmosis-labs/osmosis/v7/x/gamm/keeper" - twaptypes "github.com/osmosis-labs/osmosis/v7/x/gamm/twap/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + twaptypes "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var ( diff --git a/x/gamm/types/genesis.pb.go b/x/gamm/types/genesis.pb.go index be2e2adf324..29f5c0a0f7a 100644 --- a/x/gamm/types/genesis.pb.go +++ b/x/gamm/types/genesis.pb.go @@ -143,32 +143,33 @@ func init() { } var fileDescriptor_5a324eb7f1dd793e = []byte{ - // 400 bytes of a gzipped FileDescriptorProto + // 401 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x92, 0xcf, 0xaa, 0xd3, 0x40, 0x18, 0xc5, 0x33, 0xde, 0x7b, 0x0b, 0xe6, 0x8a, 0x7f, 0x42, 0x17, 0xb9, 0x17, 0x49, 0x4b, 0x56, - 0xd9, 0x74, 0x86, 0x5b, 0x11, 0xa1, 0x3b, 0x53, 0x50, 0x0a, 0x22, 0x25, 0xee, 0xdc, 0x84, 0x49, - 0x9c, 0xc6, 0x60, 0x32, 0x5f, 0xc8, 0x4c, 0x4b, 0xf3, 0x16, 0x82, 0x7b, 0x1f, 0x40, 0xb7, 0x3e, - 0x44, 0x71, 0xd5, 0xa5, 0xab, 0x2a, 0xed, 0x1b, 0xf8, 0x04, 0x32, 0x7f, 0x22, 0x82, 0x77, 0x95, - 0x7c, 0xf3, 0xfd, 0xce, 0xe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bb, 0x17, 0x8a, 0x11, 0x36, 0xd9, 0x10, 0x9b, 0x5e, + 0x70, 0xdf, 0x0b, 0x7e, 0xc2, 0xbb, 0xf8, 0xf6, 0xb7, 0xaf, 0x93, 0x8b, 0x25, 0x40, 0xf5, 0x3c, + 0x31, 0xb4, 0x17, 0xb9, 0xf7, 0x39, 0xdb, 0xca, 0x54, 0xe7, 0xe3, 0xeb, 0x3a, 0x63, 0xad, 0x7f, + 0x6b, 0x8c, 0xa2, 0xf3, 0xe4, 0xae, 0x3a, 0x57, 0xec, 0x2b, 0x7d, 0xea, 0xcd, 0xdd, 0x41, 0xa3, + 0x1b, 0xf1, 0xcf, 0xc6, 0x28, 0xba, 0x9c, 0x3d, 0xc4, 0xff, 0xfb, 0x4a, 0xd8, 0xb4, 0x16, 0x9f, + 0xab, 0xeb, 0x27, 0x56, 0x11, 0xbf, 0xd8, 0x1d, 0x03, 0xb4, 0x3f, 0x06, 0xe8, 0xe7, 0x31, 0x40, + 0x1f, 0x4e, 0x81, 0xb3, 0x3f, 0x05, 0xce, 0xf7, 0x53, 0xe0, 0xbc, 0xb9, 0xf9, 0xab, 0x02, 0xeb, + 0x37, 0xa9, 0x68, 0x26, 0xfa, 0x81, 0x6c, 0xa6, 0x37, 0x64, 0x6b, 0x7e, 0x16, 0x5d, 0x48, 0x36, + 0xd0, 0x37, 0x7a, 0xf4, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x03, 0xb5, 0xea, 0x6a, 0x49, 0x02, 0x00, + 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { diff --git a/x/gamm/types/msgs_test.go b/x/gamm/types/msgs_test.go index 9643f354b5e..3cfee6629dc 100644 --- a/x/gamm/types/msgs_test.go +++ b/x/gamm/types/msgs_test.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" - appParams "github.com/osmosis-labs/osmosis/v7/app/params" + appParams "github.com/osmosis-labs/osmosis/v10/app/params" ) func TestMsgSwapExactAmountIn(t *testing.T) { diff --git a/x/gamm/types/params.go b/x/gamm/types/params.go index 72dfd3d46f4..db3d72166b3 100644 --- a/x/gamm/types/params.go +++ b/x/gamm/types/params.go @@ -3,7 +3,7 @@ package types import ( "fmt" - appparams "github.com/osmosis-labs/osmosis/v7/app/params" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" diff --git a/x/gamm/types/query.pb.go b/x/gamm/types/query.pb.go index d723db2e7d0..8178f3cf7b6 100644 --- a/x/gamm/types/query.pb.go +++ b/x/gamm/types/query.pb.go @@ -997,90 +997,90 @@ func init() { func init() { proto.RegisterFile("osmosis/gamm/v1beta1/query.proto", fileDescriptor_d9a717df9ca609ef) } var fileDescriptor_d9a717df9ca609ef = []byte{ - // 1321 bytes of a gzipped FileDescriptorProto + // 1322 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x97, 0xcd, 0x6f, 0x1b, 0x45, 0x14, 0xc0, 0xb3, 0xa9, 0x93, 0xc6, 0x13, 0x9a, 0x26, 0xd3, 0xb4, 0x75, 0x37, 0xad, 0xb7, 0x0c, - 0xa2, 0x09, 0x6d, 0xb2, 0x4b, 0xda, 0x54, 0x48, 0x15, 0x50, 0x6a, 0x9a, 0xb4, 0xae, 0xa0, 0x0d, - 0x5b, 0x04, 0x02, 0x0e, 0xd6, 0x26, 0x59, 0xdc, 0x55, 0xed, 0x9d, 0x8d, 0x67, 0xb6, 0x69, 0x84, - 0x2a, 0x24, 0x84, 0x38, 0x71, 0x40, 0x2a, 0xdc, 0x2a, 0x95, 0x03, 0x07, 0xc4, 0x99, 0x7f, 0x01, - 0xa9, 0x42, 0x42, 0x2a, 0xe2, 0x82, 0x38, 0x18, 0xd4, 0x72, 0xe0, 0xec, 0x7f, 0x00, 0x34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f1, 0xe4, 0xe3, 0xf3, 0xdd, 0x08, 0x76, 0x59, 0x91, 0xf4, 0xa5, 0xc1, 0x9c, 0x00, 0x7f, 0x59, + 0xe2, 0x5f, 0xc2, 0xaf, 0x64, 0xe3, 0x27, 0xe0, 0x2e, 0xd0, 0x5a, 0x6c, 0xdb, 0x09, 0xca, 0xae, + 0x08, 0x06, 0xef, 0x52, 0xd9, 0xf3, 0xf1, 0xcf, 0x1a, 0xd2, 0x77, 0xa9, 0xe7, 0x66, 0xc8, 0xf1, + 0x00, 0x6c, 0xc9, 0x66, 0xd1, 0xf5, 0xa4, 0xef, 0xfe, 0x10, 0x93, 0x15, 0x59, 0xd2, 0x6b, 0xf8, + 0xd5, 0x7f, 0x51, 0x12, 0x0d, 0x79, 0xe9, 0xfa, 0xe3, 0xa7, 0x45, 0xed, 0xc9, 0xd3, 0xa2, 0xf6, + 0xc7, 0xd3, 0xa2, 0xf6, 0xc5, 0xb3, 0xe2, 0xd0, 0x93, 0x67, 0xc5, 0xa1, 0x5f, 0x9f, 0x15, 0x87, + 0xde, 0x3f, 0x9b, 0x7a, 0xf0, 0x20, 0xc7, 0x42, 0xd5, 0x59, 0x67, 0x71, 0xc2, 0xbb, 0x8b, 0x67, + 0xad, 0x7b, 0x2a, 0xad, 0x7c, 0xfe, 0xd6, 0x47, 0xe5, 0xff, 0x78, 0xe7, 0xff, 0x09, 0x00, 0x00, + 0xff, 0xff, 0x35, 0x7c, 0xb0, 0x19, 0x56, 0x11, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/gamm/types/tx.pb.go b/x/gamm/types/tx.pb.go index 75e649d559d..901f7672f57 100644 --- a/x/gamm/types/tx.pb.go +++ b/x/gamm/types/tx.pb.go @@ -969,77 +969,78 @@ func init() { func init() { proto.RegisterFile("osmosis/gamm/v1beta1/tx.proto", fileDescriptor_cfc8fd3ac7df3247) } var fileDescriptor_cfc8fd3ac7df3247 = []byte{ - // 1119 bytes of a gzipped FileDescriptorProto + // 1121 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x58, 0x4b, 0x6f, 0x1b, 0x45, 0x1c, 0xcf, 0xd8, 0x6e, 0x1e, 0x93, 0xe6, 0xb5, 0x4d, 0x1a, 0x67, 0xdb, 0xda, 0xe9, 0x80, 0x20, - 0xa5, 0xea, 0x2e, 0x4d, 0x25, 0x8a, 0xb8, 0x00, 0x86, 0x20, 0x8c, 0xb0, 0x5c, 0x6d, 0x2f, 0x15, - 0x17, 0x6b, 0x1d, 0xaf, 0xdc, 0x55, 0xb3, 0x33, 0x96, 0x67, 0x36, 0xb8, 0x42, 0x02, 0x89, 0xc7, - 0x1d, 0x84, 0x78, 0x7c, 0x02, 0xc4, 0x57, 0xe0, 0x00, 0x07, 0xb8, 0xf4, 0xd8, 0x1b, 0x94, 0x83, - 0x85, 0x92, 0x6f, 0xe0, 0x4f, 0x80, 0x76, 0x67, 0xf6, 0xe9, 0xdd, 0xd8, 0x9b, 0xd8, 0xc9, 0x29, - 0xf1, 0xce, 0xff, 0xfd, 0xff, 0xcd, 0xef, 0xff, 0xdf, 0x85, 0x37, 0x08, 0xb5, 0x08, 0x35, 0xa9, - 0xda, 0xd6, 0x2d, 0x4b, 0x3d, 0xbc, 0xdb, 0x34, 0x98, 0x7e, 0x57, 0x65, 0x3d, 0xa5, 0xd3, 0x25, - 0x8c, 0x48, 0xeb, 0xe2, 0x58, 0x71, 0x8e, 0x15, 0x71, 0x2c, 0xaf, 0xb7, 0x49, 0x9b, 0xb8, 0x02, - 0xaa, 0xf3, 0x1f, 0x97, 0x95, 0x4b, 0xfb, 0xae, 0xb0, 0xda, 0xd4, 0xa9, 0xe1, 0x5b, 0xda, 0x27, - 0x26, 0xe6, 0xe7, 0xe8, 0xf7, 0x1c, 0x5c, 0xac, 0xd1, 0xf6, 0x47, 0xc4, 0xc4, 0x0f, 0x08, 0x39, - 0x90, 0x6e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d, 0x46, 0xdb, 0x4e, 0x24, - 0x7b, 0x3d, 0x7d, 0x9f, 0x79, 0xe1, 0x64, 0x41, 0xce, 0x1e, 0x9c, 0xed, 0x3a, 0xd1, 0x53, 0x81, - 0xe0, 0x57, 0x95, 0x24, 0xb6, 0x53, 0x86, 0xb2, 0xad, 0x14, 0x9c, 0x3a, 0x69, 0x42, 0x39, 0x72, - 0x15, 0x1c, 0x30, 0x9d, 0xed, 0x2a, 0x48, 0x9f, 0xc3, 0xf5, 0xa4, 0x8e, 0x17, 0x0b, 0x6e, 0x3a, - 0xb5, 0xcc, 0x38, 0xbd, 0x96, 0x8e, 0x22, 0xa4, 0xad, 0x85, 0x40, 0xc4, 0x73, 0x44, 0xdf, 0x03, - 0x78, 0x3d, 0xa9, 0xb2, 0x61, 0xbe, 0x09, 0x8c, 0x4d, 0x86, 0x6f, 0xe2, 0xf6, 0x90, 0xb6, 0xec, - 0x05, 0x26, 0xa2, 0xfa, 0x0a, 0x40, 0x29, 0x68, 0x44, 0xdd, 0x66, 0xa7, 0xc0, 0xdd, 0x3b, 0xde, - 0x55, 0x34, 0xf1, 0xd8, 0xb0, 0xbb, 0x2c, 0xda, 0xc2, 0x51, 0xf7, 0x22, 0x07, 0x37, 0x86, 0x6b, - 0x53, 0xb7, 0x59, 0x16, 0xd8, 0x7d, 0x10, 0x83, 0xdd, 0xce, 0x28, 0xd8, 0x79, 0xd9, 0xc6, 0x70, - 0xf7, 0x19, 0xbc, 0x92, 0x30, 0x35, 0x04, 0x9f, 0x7d, 0x9c, 0xb9, 0x15, 0x72, 0xea, 0x20, 0x42, - 0xda, 0x6a, 0x30, 0x87, 0x04, 0xad, 0x45, 0x88, 0xa5, 0x30, 0x0a, 0xf5, 0xe3, 0x10, 0xcb, 0x77, - 0x00, 0xde, 0x48, 0xac, 0xad, 0x0f, 0xbc, 0x8e, 0xc7, 0x1b, 0xc1, 0xa5, 0x00, 0x67, 0x23, 0xef, - 0x98, 0x39, 0x8f, 0x65, 0x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, 0xe5, 0x71, 0x31, + 0xa3, 0x83, 0xcf, 0x42, 0x35, 0x99, 0x86, 0xd4, 0xf8, 0x09, 0x25, 0x98, 0xe7, 0xe3, 0x23, 0x94, + 0x24, 0x9b, 0x48, 0x5b, 0xf1, 0xf6, 0x84, 0x80, 0x50, 0x7e, 0x01, 0xf0, 0x66, 0x6a, 0x11, 0x2f, + 0x74, 0x8b, 0x41, 0xbf, 0xe6, 0x23, 0xfd, 0x7d, 0xe0, 0x9c, 0x9e, 0xe9, 0x4e, 0x67, 0xea, 0xef, + 0xbb, 0x03, 0x3c, 0xc4, 0xef, 0xec, 0x46, 0xbf, 0x57, 0x5e, 0x8b, 0x01, 0x33, 0x89, 0x86, 0x12, + 0x6b, 0x55, 0x98, 0xf4, 0xc6, 0x97, 0x42, 0x37, 0x97, 0x5e, 0x06, 0xdd, 0xa0, 0x1f, 0xa3, 0x18, + 0x8a, 0x36, 0xea, 0x02, 0x09, 0xe2, 0xb7, 0x3c, 0x2c, 0x8a, 0xbd, 0x2b, 0x16, 0xd7, 0x04, 0xf9, + 0x21, 0x61, 0x7f, 0xca, 0x67, 0xdc, 0x9f, 0x92, 0x16, 0xe1, 0xc2, 0x64, 0x17, 0xe1, 0xb4, 0xbd, + 0xe6, 0xd2, 0x4b, 0xda, 0x6b, 0x7e, 0x06, 0x70, 0x33, 0xad, 0x55, 0x17, 0xbb, 0xdb, 0xfc, 0x9d, + 0x83, 0x72, 0x28, 0xb2, 0x30, 0x41, 0x4e, 0x92, 0x86, 0x22, 0x23, 0x3c, 0x3f, 0x86, 0x11, 0xee, + 0x50, 0x84, 0x8f, 0x82, 0x10, 0x45, 0x14, 0xce, 0x47, 0x11, 0x09, 0x26, 0x91, 0xb6, 0x2c, 0xc0, + 0x15, 0x50, 0xc4, 0x4f, 0x00, 0xa2, 0xf4, 0x2a, 0x86, 0x39, 0x22, 0x0e, 0x7c, 0x30, 0x51, 0xe0, + 0xef, 0xfe, 0x3e, 0x03, 0xf3, 0x35, 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25, 0x8d, 0xc6, 0xb4, 0xfb, + 0x19, 0xf4, 0xee, 0x8b, 0x00, 0x00, 0x00, 0xff, 0xff, 0x26, 0x3c, 0x5b, 0xdf, 0x73, 0x15, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/incentives/client/cli/cli_test.go b/x/incentives/client/cli/cli_test.go index 71930765188..21f6e6d5fe6 100644 --- a/x/incentives/client/cli/cli_test.go +++ b/x/incentives/client/cli/cli_test.go @@ -9,15 +9,15 @@ import ( tmcli "github.com/tendermint/tendermint/libs/cli" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app" - gammtestutil "github.com/osmosis-labs/osmosis/v7/x/gamm/client/testutil" - "github.com/osmosis-labs/osmosis/v7/x/incentives/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptestutil "github.com/osmosis-labs/osmosis/v7/x/lockup/client/testutil" + "github.com/osmosis-labs/osmosis/v10/app" + gammtestutil "github.com/osmosis-labs/osmosis/v10/x/gamm/client/testutil" + "github.com/osmosis-labs/osmosis/v10/x/incentives/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptestutil "github.com/osmosis-labs/osmosis/v10/x/lockup/client/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" diff --git a/x/incentives/client/cli/query.go b/x/incentives/client/cli/query.go index 27a0afa89c8..6f33f7ed9bc 100644 --- a/x/incentives/client/cli/query.go +++ b/x/incentives/client/cli/query.go @@ -8,8 +8,8 @@ import ( "github.com/spf13/cobra" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/incentives/client/cli/tx.go b/x/incentives/client/cli/tx.go index 9d8b52a2094..8ea79478110 100644 --- a/x/incentives/client/cli/tx.go +++ b/x/incentives/client/cli/tx.go @@ -8,8 +8,8 @@ import ( "github.com/spf13/cobra" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/incentives/keeper/bench_test.go b/x/incentives/keeper/bench_test.go index 2ff1bc2c9a2..81ba4b48a48 100644 --- a/x/incentives/keeper/bench_test.go +++ b/x/incentives/keeper/bench_test.go @@ -9,9 +9,9 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/incentives/keeper/distribute.go b/x/incentives/keeper/distribute.go index cad4970aac8..f25b233426c 100644 --- a/x/incentives/keeper/distribute.go +++ b/x/incentives/keeper/distribute.go @@ -6,8 +6,8 @@ import ( db "github.com/tendermint/tm-db" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/keeper/distribute_test.go b/x/incentives/keeper/distribute_test.go index 59077e2fbf3..54745eb7026 100644 --- a/x/incentives/keeper/distribute_test.go +++ b/x/incentives/keeper/distribute_test.go @@ -6,8 +6,8 @@ import ( "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/keeper/export_test.go b/x/incentives/keeper/export_test.go index 124ed6b2948..ac465da4fe9 100644 --- a/x/incentives/keeper/export_test.go +++ b/x/incentives/keeper/export_test.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" ) // AddGaugeRefByKey appends the provided gauge ID into an array associated with the provided key. diff --git a/x/incentives/keeper/gauge.go b/x/incentives/keeper/gauge.go index 0f1348d6a11..412ef436f69 100644 --- a/x/incentives/keeper/gauge.go +++ b/x/incentives/keeper/gauge.go @@ -10,9 +10,9 @@ import ( "github.com/gogo/protobuf/proto" db "github.com/tendermint/tm-db" - epochtypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + epochtypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/keeper/gauge_test.go b/x/incentives/keeper/gauge_test.go index e46fb22cbc7..45579973715 100644 --- a/x/incentives/keeper/gauge_test.go +++ b/x/incentives/keeper/gauge_test.go @@ -5,8 +5,8 @@ import ( "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/keeper/genesis.go b/x/incentives/keeper/genesis.go index c38b690955b..16b140667d7 100644 --- a/x/incentives/keeper/genesis.go +++ b/x/incentives/keeper/genesis.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" ) // InitGenesis initializes the incentives module's state from a provided genesis state. diff --git a/x/incentives/keeper/genesis_test.go b/x/incentives/keeper/genesis_test.go index f48c3ed9fda..ea6a4b02ef6 100644 --- a/x/incentives/keeper/genesis_test.go +++ b/x/incentives/keeper/genesis_test.go @@ -9,10 +9,10 @@ import ( "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - osmoapp "github.com/osmosis-labs/osmosis/v7/app" + osmoapp "github.com/osmosis-labs/osmosis/v10/app" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) // TestIncentivesExportGenesis tests export genesis command for the incentives module. diff --git a/x/incentives/keeper/grpc_query.go b/x/incentives/keeper/grpc_query.go index 106152cc0f3..becb8c53cd0 100644 --- a/x/incentives/keeper/grpc_query.go +++ b/x/incentives/keeper/grpc_query.go @@ -12,8 +12,8 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) var _ types.QueryServer = Querier{} diff --git a/x/incentives/keeper/grpc_query_test.go b/x/incentives/keeper/grpc_query_test.go index b458329e839..bd05e32bc54 100644 --- a/x/incentives/keeper/grpc_query_test.go +++ b/x/incentives/keeper/grpc_query_test.go @@ -8,9 +8,9 @@ import ( query "github.com/cosmos/cosmos-sdk/types/query" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - pooltypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + pooltypes "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) var _ = suite.TestingSuite(nil) diff --git a/x/incentives/keeper/hooks.go b/x/incentives/keeper/hooks.go index d51d1447d50..0584fd52124 100644 --- a/x/incentives/keeper/hooks.go +++ b/x/incentives/keeper/hooks.go @@ -1,9 +1,9 @@ package keeper import ( - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/keeper/iterator.go b/x/incentives/keeper/iterator.go index ad95a0f1159..66fd09685f5 100644 --- a/x/incentives/keeper/iterator.go +++ b/x/incentives/keeper/iterator.go @@ -3,8 +3,8 @@ package keeper import ( "time" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/incentives/keeper/keeper.go b/x/incentives/keeper/keeper.go index 439e78f68fd..09c80d185a5 100644 --- a/x/incentives/keeper/keeper.go +++ b/x/incentives/keeper/keeper.go @@ -6,7 +6,7 @@ import ( "github.com/tendermint/tendermint/libs/log" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/incentives/keeper/keeper_test.go b/x/incentives/keeper/keeper_test.go index 3b4d80b81b1..a20a5f8f313 100644 --- a/x/incentives/keeper/keeper_test.go +++ b/x/incentives/keeper/keeper_test.go @@ -6,8 +6,8 @@ import ( "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - "github.com/osmosis-labs/osmosis/v7/x/incentives/keeper" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/x/incentives/keeper" ) type KeeperTestSuite struct { diff --git a/x/incentives/keeper/msg_server.go b/x/incentives/keeper/msg_server.go index c83f5418b90..bfcffaf99e0 100644 --- a/x/incentives/keeper/msg_server.go +++ b/x/incentives/keeper/msg_server.go @@ -3,8 +3,8 @@ package keeper import ( "context" - "github.com/osmosis-labs/osmosis/v7/x/gamm/utils" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/utils" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/incentives/keeper/params.go b/x/incentives/keeper/params.go index 5975d785943..23b94c7e4a3 100644 --- a/x/incentives/keeper/params.go +++ b/x/incentives/keeper/params.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/keeper/store.go b/x/incentives/keeper/store.go index c96b074955f..d325b760b29 100644 --- a/x/incentives/keeper/store.go +++ b/x/incentives/keeper/store.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/keeper/suite_test.go b/x/incentives/keeper/suite_test.go index 5d71fd2a61c..793a47a9837 100644 --- a/x/incentives/keeper/suite_test.go +++ b/x/incentives/keeper/suite_test.go @@ -5,8 +5,8 @@ import ( "math/rand" "time" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/keeper/utils.go b/x/incentives/keeper/utils.go index 79efff15d48..9fd45f1af59 100644 --- a/x/incentives/keeper/utils.go +++ b/x/incentives/keeper/utils.go @@ -3,7 +3,7 @@ package keeper import ( "time" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/keeper/utils_test.go b/x/incentives/keeper/utils_test.go index c316e73724b..a2f5bfcd7d0 100644 --- a/x/incentives/keeper/utils_test.go +++ b/x/incentives/keeper/utils_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/module.go b/x/incentives/module.go index 02824adc959..62b50e7ca52 100644 --- a/x/incentives/module.go +++ b/x/incentives/module.go @@ -19,11 +19,11 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/osmosis-labs/osmosis/v7/x/incentives/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/incentives/keeper" - "github.com/osmosis-labs/osmosis/v7/x/incentives/simulation" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/client/rest" + "github.com/osmosis-labs/osmosis/v10/x/incentives/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/incentives/keeper" + "github.com/osmosis-labs/osmosis/v10/x/incentives/simulation" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/client/rest" ) var ( diff --git a/x/incentives/simulation/genesis.go b/x/incentives/simulation/genesis.go index a28a185b97d..d875dc5933f 100644 --- a/x/incentives/simulation/genesis.go +++ b/x/incentives/simulation/genesis.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" ) // Simulation parameter constants. diff --git a/x/incentives/simulation/operations.go b/x/incentives/simulation/operations.go index f1e656150eb..950cca38197 100644 --- a/x/incentives/simulation/operations.go +++ b/x/incentives/simulation/operations.go @@ -4,13 +4,13 @@ import ( "math/rand" "time" - osmo_simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" + osmo_simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/osmosis-labs/osmosis/v7/x/incentives/keeper" - "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/incentives/keeper" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/codec" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" diff --git a/x/incentives/types/expected_keepers.go b/x/incentives/types/expected_keepers.go index ddc26781e8a..e377908df79 100644 --- a/x/incentives/types/expected_keepers.go +++ b/x/incentives/types/expected_keepers.go @@ -3,8 +3,8 @@ package types import ( time "time" - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/types/gauge.go b/x/incentives/types/gauge.go index c1dd1b0193d..bb0f97d087c 100644 --- a/x/incentives/types/gauge.go +++ b/x/incentives/types/gauge.go @@ -3,7 +3,7 @@ package types import ( time "time" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/types/gauge.pb.go b/x/incentives/types/gauge.pb.go index 36e74c0af84..820d03b2610 100644 --- a/x/incentives/types/gauge.pb.go +++ b/x/incentives/types/gauge.pb.go @@ -11,7 +11,7 @@ import ( proto "github.com/gogo/protobuf/proto" _ "github.com/gogo/protobuf/types" github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" - types "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + types "github.com/osmosis-labs/osmosis/v10/x/lockup/types" io "io" math "math" math_bits "math/bits" @@ -203,40 +203,40 @@ func init() { proto.RegisterFile("osmosis/incentives/gauge.proto", fileDescripto var fileDescriptor_c0304e2bb0159901 = []byte{ // 545 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0xcf, 0x6a, 0xdb, 0x30, - 0x1c, 0xc7, 0xe3, 0x34, 0xe9, 0x3a, 0x25, 0x1d, 0x8b, 0xe8, 0xc0, 0x09, 0xcc, 0xc9, 0x32, 0x06, - 0xb9, 0x54, 0x5a, 0x3b, 0xc6, 0x60, 0xc7, 0x74, 0x63, 0x14, 0x06, 0xed, 0x42, 0x0f, 0x63, 0x17, - 0x23, 0xdb, 0x8a, 0x2b, 0x62, 0xfb, 0x67, 0x2c, 0x39, 0x34, 0x6f, 0xb0, 0x63, 0xd9, 0x69, 0xcf, - 0xb0, 0x27, 0xe9, 0xb1, 0xc7, 0x9d, 0xda, 0x91, 0xbc, 0xc1, 0x9e, 0x60, 0x58, 0xb2, 0x49, 0xc8, - 0xae, 0x3d, 0xc9, 0xfa, 0x7d, 0x7f, 0xff, 0xbe, 0x1f, 0x64, 0xe4, 0x80, 0x8c, 0x41, 0x0a, 0x49, - 0x45, 0xe2, 0xf3, 0x44, 0x89, 0x39, 0x97, 0x34, 0x64, 0x79, 0xc8, 0x49, 0x9a, 0x81, 0x02, 0x8c, - 0x4b, 0x9d, 0xac, 0xf5, 0xde, 0x41, 0x08, 0x21, 0x68, 0x99, 0x16, 0x5f, 0x26, 0xb3, 0xe7, 0x84, - 0x00, 0x61, 0xc4, 0xa9, 0xbe, 0x79, 0xf9, 0x94, 0x06, 0x79, 0xc6, 0x94, 0x80, 0xa4, 0xd4, 0xfb, - 0xdb, 0xba, 0x12, 0x31, 0x97, 0x8a, 0xc5, 0x69, 0xd5, 0xc0, 0xd7, 0xb3, 0xa8, 0xc7, 0x24, 0xa7, - 0xf3, 0x23, 0x8f, 0x2b, 0x76, 0x44, 0x7d, 0x10, 0x55, 0x83, 0x6e, 0xb5, 0x6a, 0x04, 0xfe, 0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, 0xbd, 0xc0, 0x03, 0x00, 0x00, } diff --git a/x/incentives/types/genesis.pb.go b/x/incentives/types/genesis.pb.go index 0661e2378f7..e9870f5d8a4 100644 --- a/x/incentives/types/genesis.pb.go +++ b/x/incentives/types/genesis.pb.go @@ -110,29 +110,29 @@ func init() { func init() { proto.RegisterFile("osmosis/incentives/genesis.proto", fileDescriptor_a288ccc95d977d2d) } var fileDescriptor_a288ccc95d977d2d = []byte{ - // 339 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0xb1, 0x4e, 0xc3, 0x30, - 0x10, 0x86, 0x93, 0xb6, 0xea, 0x90, 0xc2, 0x80, 0xc5, 0x90, 0x76, 0x70, 0xa2, 0x48, 0x48, 0x5d, - 0xb0, 0xa5, 0x22, 0x54, 0xc4, 0x58, 0x21, 0x55, 0x4c, 0xa0, 0xb2, 0xb1, 0x54, 0x4e, 0x6b, 0x8c, - 0x45, 0x12, 0x57, 0x3d, 0xa7, 0xa2, 0x6f, 0xc1, 0x84, 0x78, 0xa4, 0x8e, 0x1d, 0x99, 0x0a, 0x6a, - 0xdf, 0x80, 0x27, 0x40, 0x71, 0x62, 0x81, 0xd4, 0x6e, 0x3e, 0xff, 0xdf, 0xfd, 0xf7, 0xdf, 0x79, - 0xa1, 0x82, 0x54, 0x81, 0x04, 0x2a, 0xb3, 0x09, 0xcf, 0xb4, 0x5c, 0x70, 0xa0, 0x82, 0x67, 0x1c, - 0x24, 0x90, 0xd9, 0x5c, 0x69, 0x85, 0x50, 0x45, 0x90, 0x3f, 0xa2, 0x73, 0x2a, 0x94, 0x50, 0x46, - 0xa6, 0xc5, 0xab, 0x24, 0x3b, 0x58, 0x28, 0x25, 0x12, 0x4e, 0x4d, 0x15, 0xe7, 0x4f, 0x74, 0x9a, - 0xcf, 0x99, 0x96, 0x2a, 0xab, 0xf4, 0xe0, 0xc0, 0xac, 0x19, 0x9b, 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c, 0xe2, 0xa6, 0xd9, 0xe0, 0xe2, 0x37, 0x00, 0x00, 0xff, 0xff, 0x51, 0x99, 0x95, 0x16, 0x1f, - 0x02, 0x00, 0x00, + // 342 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0xb1, 0x4e, 0xfb, 0x30, + 0x10, 0xc6, 0x93, 0xb6, 0xea, 0x90, 0xfe, 0xff, 0x03, 0x16, 0x43, 0xda, 0xc1, 0x89, 0x22, 0x21, + 0x75, 0xc1, 0x86, 0x22, 0x01, 0x62, 0xac, 0x90, 0x2a, 0xb6, 0xaa, 0x6c, 0x2c, 0x95, 0xd3, 0x1a, + 0x63, 0x91, 0xc4, 0x55, 0xcf, 0xa9, 0xe8, 0x5b, 0x30, 0x21, 0x1e, 0xa9, 0x63, 0x47, 0xa6, 0x82, + 0xda, 0x37, 0xe0, 0x09, 0x50, 0x9c, 0x58, 0x20, 0xb5, 0x9b, 0xcf, 0xdf, 0xef, 0xbe, 0xfb, 0xee, + 0xbc, 0x50, 0x41, 0xaa, 0x40, 0x02, 0x95, 0xd9, 0x84, 0x67, 0x5a, 0x2e, 0x38, 0x50, 0xc1, 0x33, + 0x0e, 0x12, 0xc8, 0x6c, 0xae, 0xb4, 0x42, 0xa8, 0x22, 0xc8, 0x2f, 0xd1, 0x39, 0x16, 0x4a, 0x28, + 0x23, 0xd3, 0xe2, 0x55, 0x92, 0x1d, 0x2c, 0x94, 0x12, 0x09, 0xa7, 0xa6, 0x8a, 0xf3, 0x47, 0x3a, + 0xcd, 0xe7, 0x4c, 0x4b, 0x95, 0x55, 0x7a, 0x70, 0x60, 0xd6, 0x8c, 0xcd, 0x59, 0x0a, 0xd6, 0xe0, + 0x50, 0x18, 0x96, 0x0b, 0x5e, 0xea, 0xd1, 0x5b, 0xcd, 0xfb, 0x37, 0x28, 0xc3, 0xdd, 0x6b, 0xa6, + 0x39, 0xba, 0xf6, 0x9a, 0xa5, 0x81, 0xef, 0x86, 0x6e, 0xb7, 0xd5, 0xeb, 0x90, 0xfd, 0xb0, 0x64, + 0x68, 0x88, 0x7e, 0x63, 0xb5, 0x09, 0x9c, 0x51, 0xc5, 0xa3, 0x2b, 0xaf, 0x69, 0x9c, 0xc1, 0xaf, + 0x85, 0xf5, 0x6e, 0xab, 0xd7, 0x3e, 0xd4, 0x39, 0x28, 0x08, 0xdb, 0x58, 0xe2, 0x48, 0x79, 0x28, + 0x51, 0x93, 0x67, 0x16, 0x27, 0x7c, 0x6c, 0xf7, 0x03, 0xbf, 0x5e, 0x99, 0x94, 0x17, 0x20, 0xf6, + 0x02, 0xe4, 0xb6, 0x22, 0xfa, 0x27, 0x85, 0xc9, 0xf7, 0x26, 0x68, 0x2f, 0x59, 0x9a, 0xdc, 0x44, + 0xfb, 0x16, 0xd1, 0xfb, 0x67, 0xe0, 0x8e, 0x8e, 0xac, 0x60, 0x1b, 0x01, 0x45, 0xde, 0xff, 0x84, + 0x81, 0x1e, 0x9b, 0xf9, 0x63, 0x39, 0xf5, 0x1b, 0xa1, 0xdb, 0x6d, 0x8c, 0x5a, 0xc5, 0xa7, 0x09, + 0x78, 0x37, 0xed, 0x0f, 0x57, 0x5b, 0xec, 0xae, 0xb7, 0xd8, 0xfd, 0xda, 0x62, 0xf7, 0x75, 0x87, + 0x9d, 0xf5, 0x0e, 0x3b, 0x1f, 0x3b, 0xec, 0x3c, 0x5c, 0x0a, 0xa9, 0x9f, 0xf2, 0x98, 0x4c, 0x54, + 0x4a, 0xab, 0x0d, 0x4f, 0x13, 0x16, 0x83, 0x2d, 0xe8, 0xe2, 0xfc, 0x8c, 0xbe, 0xfc, 0x3d, 0xb8, + 0x5e, 0xce, 0x38, 0xc4, 0x4d, 0xb3, 0xc2, 0xc5, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x50, 0xb4, + 0xd0, 0x4a, 0x20, 0x02, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { diff --git a/x/incentives/types/msgs.go b/x/incentives/types/msgs.go index a9b61de5dfd..4873cb9f174 100644 --- a/x/incentives/types/msgs.go +++ b/x/incentives/types/msgs.go @@ -4,7 +4,7 @@ import ( "errors" "time" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/types/msgs_test.go b/x/incentives/types/msgs_test.go index 4ef99c55b71..cc906cd5ac5 100644 --- a/x/incentives/types/msgs_test.go +++ b/x/incentives/types/msgs_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/ed25519" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/incentives/types/params.go b/x/incentives/types/params.go index b9e5a8fa145..c5956b0bd8e 100644 --- a/x/incentives/types/params.go +++ b/x/incentives/types/params.go @@ -1,7 +1,7 @@ package types import ( - epochtypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + epochtypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) diff --git a/x/incentives/types/params.pb.go b/x/incentives/types/params.pb.go index ba4e8aed481..d0ffe0e001a 100644 --- a/x/incentives/types/params.pb.go +++ b/x/incentives/types/params.pb.go @@ -77,7 +77,7 @@ func init() { func init() { proto.RegisterFile("osmosis/incentives/params.proto", fileDescriptor_1cc8b460d089f845) } var fileDescriptor_1cc8b460d089f845 = []byte{ - // 206 bytes of a gzipped FileDescriptorProto + // 207 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcf, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0xcf, 0xcc, 0x4b, 0x4e, 0xcd, 0x2b, 0xc9, 0x2c, 0x4b, 0x2d, 0xd6, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x82, 0x2a, 0xd0, @@ -85,12 +85,12 @@ var fileDescriptor_1cc8b460d089f845 = []byte{ 0x89, 0x5c, 0x6c, 0x01, 0x60, 0x9d, 0x42, 0xe1, 0x5c, 0x62, 0x29, 0x99, 0xc5, 0x25, 0x45, 0xf1, 0xa9, 0x05, 0xf9, 0xc9, 0x19, 0xf1, 0x99, 0x29, 0x20, 0x8d, 0x69, 0x99, 0xa9, 0x45, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x4e, 0x8a, 0x9f, 0xee, 0xc9, 0xcb, 0x56, 0x26, 0xe6, 0xe6, 0x58, 0x29, - 0x61, 0x57, 0xa7, 0x14, 0x24, 0x02, 0x96, 0x70, 0x05, 0x89, 0x7b, 0xc2, 0x85, 0x9d, 0xfc, 0x4f, + 0x61, 0x57, 0xa7, 0x14, 0x24, 0x02, 0x96, 0x70, 0x05, 0x89, 0x7b, 0xc2, 0x85, 0x9d, 0x02, 0x4e, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, - 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0xca, 0x34, 0x3d, 0xb3, 0x24, 0xa3, 0x34, + 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0xca, 0x2c, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x1f, 0xea, 0x62, 0xdd, 0x9c, 0xc4, 0xa4, 0x62, 0x18, 0x47, 0xbf, - 0xcc, 0x5c, 0xbf, 0x02, 0xd9, 0x93, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0xa7, 0x1b, - 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xe2, 0x27, 0x6e, 0x20, 0x07, 0x01, 0x00, 0x00, + 0xcc, 0xd0, 0x40, 0xbf, 0x02, 0xd9, 0x97, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0xb7, + 0x1b, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xd8, 0xad, 0x8e, 0x18, 0x08, 0x01, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { diff --git a/x/incentives/types/query.pb.go b/x/incentives/types/query.pb.go index 846c7f939a3..30394a462c8 100644 --- a/x/incentives/types/query.pb.go +++ b/x/incentives/types/query.pb.go @@ -14,7 +14,7 @@ import ( proto "github.com/gogo/protobuf/proto" _ "github.com/gogo/protobuf/types" github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" - _ "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + _ "github.com/osmosis-labs/osmosis/v10/x/lockup/types" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" @@ -1019,76 +1019,77 @@ func init() { func init() { proto.RegisterFile("osmosis/incentives/query.proto", fileDescriptor_8124258a89427f98) } var fileDescriptor_8124258a89427f98 = []byte{ - // 1103 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x96, 0x4d, 0x6f, 0x1b, 0x45, - 0x18, 0xc7, 0x33, 0x4e, 0x52, 0x9a, 0x87, 0x36, 0x34, 0x43, 0x28, 0x89, 0xdb, 0xae, 0xcd, 0xaa, - 0x4d, 0xdd, 0x94, 0xec, 0xc6, 0x76, 0x93, 0x20, 0xde, 0x24, 0x8c, 0x4b, 0xa9, 0x04, 0xa2, 0xac, - 0x40, 0x48, 0x48, 0x68, 0xb5, 0xf6, 0x0e, 0xdb, 0x55, 0xec, 0x1d, 0xd7, 0xb3, 0x9b, 0x60, 0x45, - 0xb9, 0x00, 0xe7, 0x0a, 0x44, 0x54, 0x71, 0xe8, 0x27, 0xe0, 0x08, 0x12, 0x37, 0x38, 0x70, 0xea, - 0xb1, 0x12, 0x17, 0x4e, 0x29, 0x4a, 0xf8, 0x04, 0xfd, 0x04, 0x68, 0x67, 0x66, 0xfd, 0xba, 0x5e, - 0x3b, 0x88, 0x46, 0x39, 0x39, 0x93, 0xe7, 0xed, 0xf7, 0x3c, 0x1e, 0xcf, 0xff, 0x01, 0x85, 0xb2, - 0x3a, 0x65, 0x2e, 0xd3, 0x5d, 0xaf, 0x4a, 0x3c, 0xdf, 0xdd, 0x22, 0x4c, 0xbf, 0x17, 0x90, 0x66, - 0x4b, 0x6b, 0x34, 0xa9, 0x4f, 0x31, 0x96, 0x76, 0xad, 0x63, 0x4f, 0xcf, 0x3b, 0xd4, 0xa1, 0xdc, - 0xac, 0x87, 0x7f, 0x09, 0xcf, 0xf4, 0x45, 0x87, 0x52, 0xa7, 0x46, 0x74, 0xab, 0xe1, 0xea, 0x96, - 0xe7, 0x51, 0xdf, 0xf2, 0x5d, 0xea, 0x31, 0x69, 0x55, 0xa4, 0x95, 0x9f, 0x2a, 0xc1, 0x97, 0xba, - 0x1d, 0x34, 0xb9, 0x43, 0x64, 0xaf, 0xf2, 0x42, 0x7a, 0xc5, 0x62, 0x44, 0xdf, 0xca, 0x57, 0x88, - 0x6f, 0xe5, 0xf5, 0x2a, 0x75, 0x23, 0xfb, 0x72, 0xb7, 0x9d, 0x03, 0xb6, 0xbd, 0x1a, 0x96, 0xe3, - 0x7a, 0x3d, 0xb9, 0x62, 0x7a, 0x72, 0xac, 0xc0, 0x21, 0xd2, 0xbe, 0x18, 0xd9, 0x6b, 0xb4, 0xba, - 0x19, 0x34, 0xf8, 0x87, 0x30, 0xa9, 0x59, 0x50, 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 0x5d, - 0xbb, 0x7f, 0xb6, 0x85, 0xa3, 0x84, 0x48, 0xec, 0xb7, 0x38, 0xf6, 0x06, 0x5e, 0x3b, 0x02, 0x76, - 0xd7, 0x7c, 0xf7, 0x10, 0x40, 0x47, 0x7b, 0x70, 0xec, 0x0f, 0x73, 0x40, 0x10, 0xd3, 0x4b, 0xa3, - 0xdc, 0x24, 0xdc, 0x06, 0x87, 0xcb, 0x63, 0x3d, 0x09, 0xae, 0x29, 0xe2, 0x4c, 0xc2, 0x7c, 0x7d, - 0x87, 0x0b, 0xe9, 0x2e, 0xfe, 0x19, 0xc1, 0xdc, 0x80, 0xe4, 0xc4, 0x8f, 0x34, 0x51, 0xc0, 0xe2, - 0x47, 0x9a, 0xac, 0x68, 0xea, 0x3a, 0xa7, 0x5e, 0xc5, 0x5a, 0x12, 0xf5, 0xa0, 0x60, 0x95, 0x3e, - 0x7a, 0x74, 0xa0, 0xa0, 0xc7, 0x07, 0x0a, 0xfa, 0xfb, 0x40, 0x41, 0xdf, 0x1d, 0x2a, 0x13, 0x8f, - 0x0f, 0x95, 0x89, 0xbf, 0x0e, 0x95, 0x89, 0xcf, 0xd7, 0xba, 0x84, 0x59, 0xe6, 0x5c, 0xa9, 0x59, - 0x15, 0xd6, 0x2e, 0xb0, 0xb5, 0xa1, 0x7f, 0xd5, 0x5d, 0x85, 0x6b, 0x75, 0xe5, 0x14, 0x97, 0xcd, - 0xe2, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x54, 0x04, 0x4d, 0xb2, 0x89, 0x10, 0x00, 0x00, + // 1105 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x96, 0x4f, 0x6f, 0x1b, 0xc5, + 0x1b, 0xc7, 0x33, 0x4e, 0xdc, 0x5f, 0xf3, 0xfc, 0xda, 0xd0, 0x0c, 0xa1, 0x24, 0x6e, 0xbb, 0x36, + 0xab, 0x36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0xab, 0xc4, 0x2c, 0x71, + 0xcc, 0x55, 0x7c, 0x3d, 0x09, 0x73, 0x40, 0xae, 0xf0, 0x6f, 0x43, 0xe2, 0xdf, 0x99, 0x6c, 0x61, + 0x7c, 0xed, 0xc1, 0xd9, 0x16, 0x8f, 0x12, 0x22, 0xb1, 0xdf, 0xe2, 0xd8, 0xb7, 0xf0, 0xcd, 0x23, + 0x60, 0xf7, 0xcc, 0x77, 0x0f, 0x01, 0x74, 0xb5, 0x07, 0xc7, 0xfe, 0x30, 0x87, 0x04, 0x31, 0xb3, + 0x3c, 0xce, 0x4d, 0xc2, 0xdd, 0xe2, 0x70, 0x05, 0xac, 0x27, 0xc1, 0xb5, 0x44, 0x9c, 0x49, 0x98, + 0xaf, 0xef, 0x70, 0x21, 0xdd, 0xc5, 0x3f, 0x21, 0x98, 0x1f, 0x92, 0x9c, 0xf8, 0x91, 0x26, 0x0a, + 0x58, 0xfc, 0x48, 0x93, 0x15, 0x4d, 0x5d, 0xe7, 0xd4, 0x6b, 0x58, 0x4b, 0xa2, 0x1e, 0x16, 0xac, + 0xf2, 0xc6, 0xe3, 0x03, 0x05, 0x3d, 0x39, 0x50, 0xd0, 0x5f, 0x07, 0x0a, 0xfa, 0xf6, 0x50, 0x99, + 0x7a, 0x72, 0xa8, 0x4c, 0xfd, 0x79, 0xa8, 0x4c, 0x7d, 0xb6, 0xde, 0x23, 0xcc, 0x32, 0xe7, 0x6a, + 0xdd, 0xaa, 0xb2, 0x4e, 0x81, 0xad, 0xc2, 0x9a, 0xfe, 0x65, 0x6f, 0x19, 0x2e, 0xd6, 0xd5, 0x53, + 0x5c, 0x37, 0x4b, 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, 0x42, 0x98, 0x1e, 0x3a, 0x8a, 0x10, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/incentives/types/tx.pb.go b/x/incentives/types/tx.pb.go index 740c33d7bb7..186516a7e94 100644 --- a/x/incentives/types/tx.pb.go +++ b/x/incentives/types/tx.pb.go @@ -13,7 +13,7 @@ import ( proto "github.com/gogo/protobuf/proto" _ "github.com/gogo/protobuf/types" github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" - types "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + types "github.com/osmosis-labs/osmosis/v10/x/lockup/types" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" @@ -278,45 +278,45 @@ func init() { func init() { proto.RegisterFile("osmosis/incentives/tx.proto", fileDescriptor_8ea120e22291556e) } var fileDescriptor_8ea120e22291556e = []byte{ - // 596 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0xcd, 0x6e, 0xd3, 0x4c, - 0x14, 0xcd, 0x7c, 0x49, 0xff, 0x26, 0xed, 0xa7, 0x62, 0x15, 0x70, 0x03, 0xb2, 0x53, 0x2f, 0x90, - 0x41, 0xea, 0x0c, 0x2d, 0x42, 0x48, 0xec, 0x48, 0x84, 0x50, 0x17, 0x51, 0x8b, 0x15, 0x09, 0xa9, - 0x12, 0xb2, 0xc6, 0xf6, 0xe0, 0x8e, 0x1a, 0x7b, 0x2c, 0xcf, 0x38, 0x6d, 0xde, 0xa2, 0x12, 0x6f, - 0xc1, 0x1b, 0xb0, 0x63, 0xd9, 0x65, 0x97, 0xac, 0x52, 0x94, 0xbc, 0x41, 0x9f, 0x00, 0x79, 0x6c, - 0x37, 0x89, 0xf8, 0xe9, 0x86, 0xd5, 0x64, 0xe6, 0x9c, 0x7b, 0xe6, 0xce, 0x39, 0x37, 0x86, 0x8f, - 0xb8, 0x88, 0xb8, 0x60, 0x02, 0xb3, 0xd8, 0xa7, 0xb1, 0x64, 0x43, 0x2a, 0xb0, 0x3c, 0x47, 0x49, - 0xca, 0x25, 0xd7, 0xb4, 0x12, 0x44, 0x33, 0xb0, 0xb5, 0x15, 0xf2, 0x90, 0x2b, 0x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d, 0x6a, 0xff, 0x1b, 0x80, 0xf5, - 0x9e, 0x08, 0xb5, 0x8f, 0xb0, 0x39, 0x3f, 0x88, 0x16, 0xfa, 0xf5, 0x2f, 0x84, 0x16, 0x7d, 0x69, - 0x3d, 0xbb, 0x9b, 0x53, 0x5d, 0xa3, 0x1d, 0x43, 0x38, 0xe7, 0xdb, 0xce, 0x1f, 0x2a, 0x67, 0x94, - 0xd6, 0xd3, 0x3b, 0x29, 0x95, 0x76, 0xe7, 0xf0, 0x72, 0x62, 0x80, 0xab, 0x89, 0x01, 0x7e, 0x4c, - 0x0c, 0x70, 0x31, 0x35, 0x6a, 0x57, 0x53, 0xa3, 0xf6, 0x7d, 0x6a, 0xd4, 0x8e, 0x5f, 0xce, 0x19, - 0x55, 0xca, 0xed, 0x0e, 0x88, 0x27, 0xaa, 0x0d, 0x1e, 0xbe, 0xc2, 0xe7, 0x0b, 0x5f, 0x90, 0xdc, - 0x3b, 0x6f, 0x59, 0x0d, 0xdc, 0x8b, 0x9f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0xba, 0xf8, - 0x64, 0x04, 0x00, 0x00, + // 595 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0xcf, 0x6e, 0xd3, 0x30, + 0x1c, 0xae, 0x69, 0xf7, 0xcf, 0xdd, 0xd0, 0x88, 0x06, 0x64, 0x05, 0x25, 0x5d, 0x0e, 0x28, 0x20, + 0xcd, 0xde, 0x86, 0xc4, 0x81, 0x1b, 0x9d, 0x10, 0xda, 0xa1, 0xa2, 0x44, 0x95, 0x90, 0x26, 0xa1, + 0xc8, 0x49, 0x4c, 0x66, 0xad, 0x89, 0xa3, 0xd8, 0xe9, 0xd6, 0xb7, 0x98, 0xc4, 0x5b, 0xf0, 0x06, + 0xdc, 0x38, 0xee, 0xb8, 0x23, 0xa7, 0x0e, 0xb5, 0x6f, 0xb0,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x00, 0x37, 0xba, 0x22, 0x7c, 0x13, 0x04, 0x7d, 0x5e, 0xc4, 0x75, + 0x9b, 0x05, 0xf8, 0x77, 0x16, 0xdb, 0x70, 0x55, 0xcd, 0x84, 0xcb, 0x02, 0x15, 0x5b, 0xc3, 0x59, + 0x51, 0xfb, 0xa3, 0x40, 0xa3, 0x70, 0x25, 0xa5, 0x67, 0x24, 0x0d, 0x84, 0x5e, 0xff, 0xff, 0xee, + 0x56, 0xda, 0xd6, 0x63, 0xf8, 0x70, 0xa1, 0xf5, 0xea, 0x51, 0x07, 0xdf, 0x01, 0xac, 0x77, 0x45, + 0xa8, 0x7d, 0x82, 0xcd, 0xf9, 0x41, 0xb4, 0xd0, 0xef, 0x7f, 0x21, 0xb4, 0xe8, 0x4b, 0xeb, 0xc5, + 0xdd, 0x9c, 0xea, 0x1a, 0xed, 0x18, 0xc2, 0x39, 0xdf, 0x76, 0xfe, 0x52, 0x39, 0xa3, 0xb4, 0x9e, + 0xdf, 0x49, 0xa9, 0xb4, 0x3b, 0xbd, 0xcb, 0x89, 0x01, 0xae, 0x26, 0x06, 0xf8, 0x39, 0x31, 0xc0, + 0xc5, 0xd4, 0xa8, 0x5d, 0x4d, 0x8d, 0xda, 0x8f, 0xa9, 0x51, 0x3b, 0x7e, 0x35, 0x67, 0x54, 0x29, + 0xb7, 0x3b, 0x20, 0x9e, 0xa8, 0x36, 0x78, 0xb8, 0xbf, 0x87, 0xcf, 0x17, 0x3e, 0x21, 0xb9, 0x79, + 0xde, 0xb2, 0x9a, 0xb8, 0x97, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0x7b, 0x05, 0x85, 0x94, 0x65, + 0x04, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/lockup/abci.go b/x/lockup/abci.go index 3c530bd0fb2..d70b6d0e6ed 100644 --- a/x/lockup/abci.go +++ b/x/lockup/abci.go @@ -3,7 +3,7 @@ package lockup import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" + "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/client/cli/cli_test.go b/x/lockup/client/cli/cli_test.go index cfea64c0362..06ef8156ece 100644 --- a/x/lockup/client/cli/cli_test.go +++ b/x/lockup/client/cli/cli_test.go @@ -9,11 +9,11 @@ import ( "github.com/stretchr/testify/suite" tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/lockup/client/cli" - lockuptestutil "github.com/osmosis-labs/osmosis/v7/x/lockup/client/testutil" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/lockup/client/cli" + lockuptestutil "github.com/osmosis-labs/osmosis/v10/x/lockup/client/testutil" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" diff --git a/x/lockup/client/cli/query.go b/x/lockup/client/cli/query.go index 81fea436d16..6fb84f38554 100644 --- a/x/lockup/client/cli/query.go +++ b/x/lockup/client/cli/query.go @@ -16,7 +16,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) // GetQueryCmd returns the cli query commands for this module. diff --git a/x/lockup/client/cli/tx.go b/x/lockup/client/cli/tx.go index b6ff1ea510a..7f95e309842 100644 --- a/x/lockup/client/cli/tx.go +++ b/x/lockup/client/cli/tx.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/lockup/client/rest/query.go b/x/lockup/client/rest/query.go index 10f7acecd0c..d67352e8f05 100644 --- a/x/lockup/client/rest/query.go +++ b/x/lockup/client/rest/query.go @@ -8,7 +8,7 @@ import ( "github.com/gorilla/mux" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/lockup/client/rest/tx.go b/x/lockup/client/rest/tx.go index 6111bc7b430..d2b4327a8ef 100644 --- a/x/lockup/client/rest/tx.go +++ b/x/lockup/client/rest/tx.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" diff --git a/x/lockup/client/testutil/test_helpers.go b/x/lockup/client/testutil/test_helpers.go index 48e03eecaa2..80f573316f6 100644 --- a/x/lockup/client/testutil/test_helpers.go +++ b/x/lockup/client/testutil/test_helpers.go @@ -3,7 +3,7 @@ package testutil import ( "fmt" - lockupcli "github.com/osmosis-labs/osmosis/v7/x/lockup/client/cli" + lockupcli "github.com/osmosis-labs/osmosis/v10/x/lockup/client/cli" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/lockup/keeper/admin_keeper.go b/x/lockup/keeper/admin_keeper.go index 0fc3a77bd37..4aa956ec4b8 100644 --- a/x/lockup/keeper/admin_keeper.go +++ b/x/lockup/keeper/admin_keeper.go @@ -2,7 +2,7 @@ package keeper import ( "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/keeper/admin_keeper_test.go b/x/lockup/keeper/admin_keeper_test.go index 9d4d6a083bf..84a4af63362 100644 --- a/x/lockup/keeper/admin_keeper_test.go +++ b/x/lockup/keeper/admin_keeper_test.go @@ -3,7 +3,7 @@ package keeper_test import ( "time" - "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" + "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/keeper/bench_test.go b/x/lockup/keeper/bench_test.go index 6eb99b14b54..99a1008282d 100644 --- a/x/lockup/keeper/bench_test.go +++ b/x/lockup/keeper/bench_test.go @@ -9,8 +9,8 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/osmosis-labs/osmosis/v7/app" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/app" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/lockup/keeper/export_test.go b/x/lockup/keeper/export_test.go index 9b31939f4f4..816e925fbec 100644 --- a/x/lockup/keeper/export_test.go +++ b/x/lockup/keeper/export_test.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/keeper/genesis.go b/x/lockup/keeper/genesis.go index 43367c17223..b37f220e3e4 100644 --- a/x/lockup/keeper/genesis.go +++ b/x/lockup/keeper/genesis.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/keeper/genesis_test.go b/x/lockup/keeper/genesis_test.go index 6048046befb..7a5d4adc0e8 100644 --- a/x/lockup/keeper/genesis_test.go +++ b/x/lockup/keeper/genesis_test.go @@ -8,9 +8,9 @@ import ( "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - osmoapp "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/lockup" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + osmoapp "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/lockup" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/lockup/keeper/grpc_query.go b/x/lockup/keeper/grpc_query.go index 607d9e325cd..8d516dfa10b 100644 --- a/x/lockup/keeper/grpc_query.go +++ b/x/lockup/keeper/grpc_query.go @@ -8,7 +8,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) var _ types.QueryServer = Querier{} diff --git a/x/lockup/keeper/grpc_query_test.go b/x/lockup/keeper/grpc_query_test.go index 31d1658d1f8..a0aeb1ecf04 100644 --- a/x/lockup/keeper/grpc_query_test.go +++ b/x/lockup/keeper/grpc_query_test.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) func (suite *KeeperTestSuite) LockTokens(addr sdk.AccAddress, coins sdk.Coins, duration time.Duration) { diff --git a/x/lockup/keeper/invariants.go b/x/lockup/keeper/invariants.go index e8d1a94f23f..2aea79b4798 100644 --- a/x/lockup/keeper/invariants.go +++ b/x/lockup/keeper/invariants.go @@ -8,7 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) // RegisterInvariants registers all governance invariants. diff --git a/x/lockup/keeper/iterator.go b/x/lockup/keeper/iterator.go index e1196d71d81..750e117e4ed 100644 --- a/x/lockup/keeper/iterator.go +++ b/x/lockup/keeper/iterator.go @@ -5,7 +5,7 @@ import ( db "github.com/tendermint/tm-db" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/lockup/keeper/keeper.go b/x/lockup/keeper/keeper.go index 931280c0190..57785528c80 100644 --- a/x/lockup/keeper/keeper.go +++ b/x/lockup/keeper/keeper.go @@ -5,7 +5,7 @@ import ( "github.com/tendermint/tendermint/libs/log" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/lockup/keeper/keeper_test.go b/x/lockup/keeper/keeper_test.go index 84a93c922d4..1775e98d712 100644 --- a/x/lockup/keeper/keeper_test.go +++ b/x/lockup/keeper/keeper_test.go @@ -7,9 +7,9 @@ import ( "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" ) type KeeperTestSuite struct { diff --git a/x/lockup/keeper/lock.go b/x/lockup/keeper/lock.go index fc4305b031d..457ff1dc1c1 100644 --- a/x/lockup/keeper/lock.go +++ b/x/lockup/keeper/lock.go @@ -10,8 +10,8 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/store" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/store" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) // WithdrawAllMaturedLocks withdraws every lock thats in the process of unlocking, and has finished unlocking by diff --git a/x/lockup/keeper/lock_refs.go b/x/lockup/keeper/lock_refs.go index 68af9947b66..9526332585a 100644 --- a/x/lockup/keeper/lock_refs.go +++ b/x/lockup/keeper/lock_refs.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/keeper/lock_test.go b/x/lockup/keeper/lock_test.go index 109031a7c10..00f935cfbe0 100644 --- a/x/lockup/keeper/lock_test.go +++ b/x/lockup/keeper/lock_test.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/lockup/keeper/migration.go b/x/lockup/keeper/migration.go index b79f00f0516..c07276475d8 100644 --- a/x/lockup/keeper/migration.go +++ b/x/lockup/keeper/migration.go @@ -4,7 +4,7 @@ import ( "strconv" "time" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/keeper/migration_test.go b/x/lockup/keeper/migration_test.go index c79e40e9833..af329e9ae62 100644 --- a/x/lockup/keeper/migration_test.go +++ b/x/lockup/keeper/migration_test.go @@ -5,7 +5,7 @@ import ( "math/rand" "time" - "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" + "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/keeper/msg_server.go b/x/lockup/keeper/msg_server.go index ce123cff367..7263a2ae917 100644 --- a/x/lockup/keeper/msg_server.go +++ b/x/lockup/keeper/msg_server.go @@ -4,8 +4,8 @@ import ( "context" "fmt" - "github.com/osmosis-labs/osmosis/v7/x/gamm/utils" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/utils" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/lockup/keeper/msg_server_test.go b/x/lockup/keeper/msg_server_test.go index 0f389d3478a..7536a7b49b0 100644 --- a/x/lockup/keeper/msg_server_test.go +++ b/x/lockup/keeper/msg_server_test.go @@ -3,8 +3,8 @@ package keeper_test import ( "time" - "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/lockup/keeper/store.go b/x/lockup/keeper/store.go index 31285c841bb..dcbb8e24793 100644 --- a/x/lockup/keeper/store.go +++ b/x/lockup/keeper/store.go @@ -6,7 +6,7 @@ import ( "time" "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/lockup/keeper/synthetic_lock.go b/x/lockup/keeper/synthetic_lock.go index a97b6bc830a..12571061884 100644 --- a/x/lockup/keeper/synthetic_lock.go +++ b/x/lockup/keeper/synthetic_lock.go @@ -8,7 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) // A synthetic lock object is a lock obejct used for the superfluid module. diff --git a/x/lockup/keeper/synthetic_lock_test.go b/x/lockup/keeper/synthetic_lock_test.go index 09a296a7a98..4e59d095590 100644 --- a/x/lockup/keeper/synthetic_lock_test.go +++ b/x/lockup/keeper/synthetic_lock_test.go @@ -3,7 +3,7 @@ package keeper_test import ( "time" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/keeper/utils.go b/x/lockup/keeper/utils.go index e3ec5037d77..b103ba57c40 100644 --- a/x/lockup/keeper/utils.go +++ b/x/lockup/keeper/utils.go @@ -4,7 +4,7 @@ import ( "bytes" "time" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/keeper/utils_test.go b/x/lockup/keeper/utils_test.go index ba95bc4ccab..3d1f7da42eb 100644 --- a/x/lockup/keeper/utils_test.go +++ b/x/lockup/keeper/utils_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/lockup/module.go b/x/lockup/module.go index f5665e27540..5d52e901c96 100644 --- a/x/lockup/module.go +++ b/x/lockup/module.go @@ -17,13 +17,13 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" - "github.com/osmosis-labs/osmosis/v7/x/lockup/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/lockup/client/rest" - "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" + simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/lockup/client/rest" + "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" - locksimulation "github.com/osmosis-labs/osmosis/v7/x/lockup/simulation" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + locksimulation "github.com/osmosis-labs/osmosis/v10/x/lockup/simulation" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) var ( diff --git a/x/lockup/simulation/operations.go b/x/lockup/simulation/operations.go index 7056a595a96..edc74968b3e 100644 --- a/x/lockup/simulation/operations.go +++ b/x/lockup/simulation/operations.go @@ -6,10 +6,10 @@ import ( legacysimulationtype "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" - "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/lockup/types/genesis.pb.go b/x/lockup/types/genesis.pb.go index c108a1cdcd0..87d169348ae 100644 --- a/x/lockup/types/genesis.pb.go +++ b/x/lockup/types/genesis.pb.go @@ -91,7 +91,7 @@ func init() { func init() { proto.RegisterFile("osmosis/lockup/genesis.proto", fileDescriptor_648db7c6ebb608b0) } var fileDescriptor_648db7c6ebb608b0 = []byte{ - // 261 bytes of a gzipped FileDescriptorProto + // 262 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xc9, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0xcf, 0xc9, 0x4f, 0xce, 0x2e, 0x2d, 0xd0, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x83, 0xca, 0xea, 0x41, 0x64, 0xa5, @@ -103,12 +103,12 @@ var fileDescriptor_648db7c6ebb608b0 = []byte{ 0x06, 0xbd, 0x80, 0xd4, 0xa2, 0xcc, 0xfc, 0x14, 0x90, 0x62, 0x27, 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, 0x20, 0xca, 0x85, 0x7c, 0xb8, 0xf8, 0x8b, 0x2b, 0xf3, 0x4a, 0x32, 0x52, 0x4b, 0x32, 0x93, 0xe3, 0x21, 0x26, 0x30, 0x83, 0x4d, 0x90, 0x45, 0x37, 0x21, 0x18, 0xa6, 0x0c, 0xc9, 0x10, 0xbe, - 0x62, 0x64, 0xc1, 0x62, 0x27, 0xef, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, + 0x62, 0x64, 0xc1, 0x62, 0x27, 0x9f, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, - 0x32, 0x4c, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x87, 0x1a, 0xac, 0x9b, - 0x93, 0x98, 0x54, 0x0c, 0xe3, 0xe8, 0x97, 0x99, 0xeb, 0x57, 0xc0, 0x82, 0xa2, 0xa4, 0xb2, 0x20, - 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0x18, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf1, 0x7b, 0x29, - 0xfd, 0x6d, 0x01, 0x00, 0x00, + 0x32, 0x4a, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x87, 0x1a, 0xac, 0x9b, + 0x93, 0x98, 0x54, 0x0c, 0xe3, 0xe8, 0x97, 0x19, 0x1a, 0xe8, 0x57, 0xc0, 0xc2, 0xa2, 0xa4, 0xb2, + 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0x1a, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xed, 0xc1, + 0x2b, 0xff, 0x6e, 0x01, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { diff --git a/x/lockup/types/lock.pb.go b/x/lockup/types/lock.pb.go index baa790d8b96..e07414cbe8a 100644 --- a/x/lockup/types/lock.pb.go +++ b/x/lockup/types/lock.pb.go @@ -319,42 +319,42 @@ func init() { proto.RegisterFile("osmosis/lockup/lock.proto", fileDescriptor_7e9 var fileDescriptor_7e9d7527a237b489 = []byte{ // 595 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xbf, 0x6f, 0xd3, 0x40, - 0x14, 0xb6, 0x9d, 0xa4, 0xb4, 0x57, 0x92, 0x46, 0xa7, 0x0e, 0x69, 0x00, 0x3b, 0xf2, 0x80, 0x22, - 0xd4, 0xda, 0xa4, 0x0c, 0x48, 0x8c, 0x6e, 0x18, 0x22, 0x18, 0xc0, 0x54, 0x0c, 0x2c, 0x91, 0x7f, - 0x1c, 0xce, 0x29, 0xb6, 0xcf, 0xf8, 0x47, 0xc1, 0xff, 0x01, 0x63, 0x47, 0x90, 0xd8, 0xd8, 0xf8, - 0x4b, 0x3a, 0x76, 0x64, 0x4a, 0x51, 0x22, 0x16, 0xc6, 0xfe, 0x05, 0xe8, 0xee, 0x7c, 0x49, 0x5a, - 0x84, 0xd4, 0x01, 0xa6, 0xf3, 0xbb, 0xef, 0xbd, 0xef, 0xbd, 0xfb, 0xde, 0x27, 0x83, 0x3d, 0x92, - 0x45, 0x24, 0xc3, 0x99, 0x19, 0x12, 0x6f, 0x5a, 0x24, 0xec, 0x30, 0x92, 0x94, 0xe4, 0x04, 0xb6, - 0x2a, 0xc8, 0xe0, 0x50, 0x77, 0x37, 0x20, 0x01, 0x61, 0x90, 0x49, 0xbf, 0x78, 0x56, 0x57, 0x0d, - 0x08, 0x09, 0x42, 0x64, 0xb2, 0xc8, 0x2d, 0xde, 0x9a, 0x7e, 0x91, 0x3a, 0x39, 0x26, 0x71, 0x85, - 0x6b, 0xd7, 0xf1, 0x1c, 0x47, 0x28, 0xcb, 0x9d, 0x28, 0x11, 0x04, 0x1e, 0xeb, 0x63, 0xba, 0x4e, - 0x86, 0xcc, 0x93, 0x81, 0x8b, 0x72, 0x67, 0x60, 0x7a, 0x04, 0x57, 0x04, 0xfa, 0x4f, 0x05, 0x80, - 0x17, 0x28, 0xc5, 0xc4, 0x7f, 0x4e, 0xbc, 0x29, 0x6c, 0x01, 0x65, 0x34, 0xec, 0xc8, 0x3d, 0xb9, - 0x5f, 0xb7, 0x95, 0xd1, 0x10, 0xde, 0x07, 0x0d, 0xf2, 0x3e, 0x46, 0x69, 0x47, 0xe9, 0xc9, 0xfd, - 0x2d, 0xab, 0x7d, 0x39, 0xd3, 0x6e, 0x97, 0x4e, 0x14, 0x3e, 0xd1, 0xd9, 0xb5, 0x6e, 0x73, 0x18, - 0x4e, 0xc0, 0xa6, 0x98, 0xac, 0x53, 0xeb, 0xc9, 0xfd, 0xed, 0xc3, 0x3d, 0x83, 0x8f, 0x66, 0x88, - 0xd1, 0x8c, 0x61, 0x95, 0x60, 0x0d, 0xce, 0x66, 0x9a, 0xf4, 0x6b, 0xa6, 0x41, 0x51, 0xb2, 0x4f, - 0x22, 0x9c, 0xa3, 0x28, 0xc9, 0xcb, 0xcb, 0x99, 0xb6, 0xc3, 0x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, 0xe4, 0x96, 0x4a, 0x7f, 0x93, 0xfe, 0x35, 0xd8, 0x5e, 0xda, 0xeb, 0x0e, + 0xda, 0x3f, 0xac, 0x58, 0x5b, 0x9c, 0x75, 0x59, 0xca, 0xc5, 0x5f, 0x51, 0xe9, 0x5f, 0x14, 0xd0, + 0x78, 0x55, 0xc6, 0xf9, 0x04, 0xe5, 0xd8, 0x63, 0x36, 0x3c, 0x00, 0xb0, 0x88, 0x7d, 0x94, 0x86, + 0x25, 0x8e, 0x83, 0x31, 0x53, 0x09, 0xfb, 0x95, 0x2d, 0x5b, 0x2b, 0x84, 0xe6, 0x8e, 0x7c, 0xa8, + 0x81, 0x9d, 0x8c, 0x96, 0x8f, 0xd7, 0x75, 0x00, 0xec, 0x6a, 0x28, 0xc4, 0x58, 0x7a, 0x66, 0xe3, + 0x1f, 0x79, 0x66, 0xdd, 0xf1, 0xb5, 0xff, 0xe9, 0xf8, 0x27, 0x7d, 0xd0, 0xb8, 0x61, 0x00, 0xd8, + 0x04, 0xc0, 0x2a, 0x05, 0x77, 0x4b, 0x82, 0x00, 0x6c, 0x5a, 0x25, 0x1d, 0xaa, 0x25, 0x77, 0x6a, + 0x1f, 0xbf, 0xaa, 0x92, 0x75, 0x72, 0x31, 0x57, 0xe5, 0xcb, 0xb9, 0x2a, 0xff, 0x98, 0xab, 0xf2, + 0xf9, 0x42, 0x95, 0x2e, 0x17, 0xaa, 0xf4, 0x7d, 0xa1, 0x4a, 0x6f, 0x06, 0x6b, 0xc6, 0xad, 0x5c, + 0x76, 0x18, 0x3a, 0x6e, 0x26, 0x02, 0xf3, 0xac, 0x7f, 0x64, 0x7e, 0x10, 0xff, 0x2b, 0x66, 0x64, + 0x77, 0x93, 0x3d, 0xe8, 0xe9, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7d, 0xd6, 0xd2, 0x8b, 0xce, 0x04, 0x00, 0x00, } diff --git a/x/lockup/types/query.pb.go b/x/lockup/types/query.pb.go index 13802e3665b..aa1af9d8989 100644 --- a/x/lockup/types/query.pb.go +++ b/x/lockup/types/query.pb.go @@ -1566,97 +1566,97 @@ func init() { func init() { proto.RegisterFile("osmosis/lockup/query.proto", fileDescriptor_e906fda01cffd91a) } var fileDescriptor_e906fda01cffd91a = []byte{ - // 1427 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x58, 0xcd, 0x6f, 0x1b, 0xc5, - 0x1b, 0xce, 0xb4, 0x4d, 0x7f, 0xbf, 0xbe, 0xa5, 0x1f, 0x1a, 0xda, 0x92, 0x6c, 0x5b, 0x3b, 0xdd, - 0xb6, 0xc1, 0x40, 0xbc, 0xdb, 0x24, 0x55, 0x52, 0xaa, 0xb4, 0x49, 0x1d, 0x13, 0x14, 0x30, 0xd0, - 0xba, 0x85, 0x8a, 0x2f, 0x59, 0x6b, 0x7b, 0xeb, 0xae, 0x62, 0xef, 0xb8, 0xde, 0x75, 0xc1, 0x54, - 0xa5, 0xa2, 0xe5, 0xc8, 0xa1, 0x88, 0x0b, 0xe2, 0x80, 0x80, 0x1b, 0x1c, 0x10, 0x17, 0x0e, 0x15, - 0x77, 0x54, 0x81, 0x84, 0x2a, 0x71, 0x41, 0x1c, 0x52, 0x94, 0xf0, 0x17, 0xe4, 0xc4, 0x11, 0xed, - 0xcc, 0xec, 0xc6, 0xbb, 0xde, 0x5d, 0xef, 0xda, 0x24, 0xca, 0xc9, 0x1f, 0xf3, 0xce, 0xfb, 0x3e, - 0xcf, 0x33, 0xef, 0xce, 0xcc, 0xb3, 0x20, 0x10, 0xa3, 0x46, 0x0c, 0xcd, 0x90, 0xab, 0xa4, 0xb4, - 0xd4, 0xac, 0xcb, 0x37, 0x9a, 0x6a, 0xa3, 0x25, 0xd5, 0x1b, 0xc4, 0x24, 0x78, 0x2f, 0x1f, 0x93, - 0xd8, 0x98, 0x70, 0xa0, 0x42, 0x2a, 0x84, 0x0e, 0xc9, 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x0f, 0x42, 0xef, 0x36, - 0x38, 0xcd, 0xba, 0x61, 0x11, 0xe1, 0x24, 0xda, 0xd8, 0xfc, 0x86, 0xe0, 0x70, 0xc8, 0x2d, 0x07, - 0x87, 0x77, 0x9d, 0xaf, 0xd3, 0x11, 0x26, 0x63, 0xcd, 0x89, 0x4a, 0xc8, 0xd3, 0xaa, 0x55, 0x9a, - 0xa6, 0x60, 0xdf, 0xe1, 0x82, 0x37, 0x7d, 0x87, 0x4a, 0xf8, 0xa6, 0xef, 0x25, 0x91, 0x8e, 0x18, - 0xdd, 0xe3, 0xa6, 0xdf, 0x81, 0xfb, 0xd3, 0x6d, 0xf0, 0x5c, 0x8c, 0xbb, 0x39, 0xce, 0xc4, 0x10, - 0x39, 0xe8, 0x00, 0x98, 0xef, 0x2b, 0x07, 0x67, 0xfe, 0x26, 0x65, 0x7e, 0x19, 0x5f, 0xea, 0x6d, - 0xe1, 0xc2, 0x4e, 0x83, 0xd5, 0xf5, 0x77, 0x70, 0x81, 0x57, 0x70, 0x3c, 0x1d, 0x83, 0x84, 0x6b, - 0x87, 0x3a, 0x13, 0x7f, 0x22, 0xa7, 0x9c, 0xa3, 0x94, 0x17, 0x70, 0xb6, 0x47, 0xca, 0xae, 0xdd, - 0x35, 0xf3, 0xf2, 0xc3, 0x95, 0x04, 0x7a, 0xb4, 0x92, 0x40, 0x7f, 0xad, 0x24, 0xd0, 0xfd, 0xd5, - 0xc4, 0xc0, 0xa3, 0xd5, 0xc4, 0xc0, 0x1f, 0xab, 0x89, 0x81, 0xb7, 0xc6, 0xdb, 0x5e, 0xdc, 0xf0, - 0x4a, 0xe9, 0xaa, 0x52, 0x34, 0x9c, 0xb2, 0x37, 0xa7, 0xe5, 0xf7, 0xed, 0xda, 0xf4, 0x3d, 0x4e, - 0x71, 0x27, 0x35, 0x41, 0x93, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x62, 0xa3, 0x5a, 0xf4, 0x43, - 0x1b, 0x00, 0x00, + // 1426 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x58, 0xcf, 0x6f, 0x1b, 0x45, + 0x14, 0xce, 0xb4, 0x4d, 0xa1, 0xaf, 0xf4, 0x87, 0x86, 0xb6, 0x24, 0xdb, 0xd6, 0x4e, 0xb7, 0x6d, + 0x30, 0x10, 0xef, 0x26, 0x6e, 0xd5, 0x96, 0x2a, 0x6d, 0x52, 0xc7, 0x04, 0x05, 0x19, 0x68, 0xdd, + 0x42, 0xc5, 0x2f, 0x59, 0x6b, 0x7b, 0xeb, 0xae, 0x62, 0xef, 0xb8, 0xde, 0x75, 0xc1, 0x54, 0xa5, + 0xa2, 0xe5, 0xc8, 0xa1, 0x88, 0x0b, 0xe2, 0x80, 0x80, 0x1b, 0x1c, 0x10, 0x17, 0x0e, 0x15, 0x77, + 0x54, 0x81, 0x84, 0x2a, 0x71, 0x41, 0x1c, 0x52, 0x94, 0xf0, 0x17, 0xe4, 0xc4, 0x11, 0xed, 0xcc, + 0xec, 0xc6, 0xbb, 0xde, 0x5d, 0xef, 0xda, 0x24, 0xca, 0xc9, 0x3f, 0xe6, 0xcd, 0x7b, 0xdf, 0xf7, + 0xcd, 0xdb, 0x99, 0xf9, 0x16, 0x04, 0x62, 0xd4, 0x89, 0xa1, 0x19, 0x72, 0x8d, 0x94, 0x17, 0x5b, + 0x0d, 0xf9, 0x46, 0x4b, 0x6d, 0xb6, 0xa5, 0x46, 0x93, 0x98, 0x04, 0xef, 0xe6, 0x63, 0x12, 0x1b, + 0x13, 0xf6, 0x55, 0x49, 0x95, 0xd0, 0x21, 0xd9, 0xfa, 0xc6, 0xa2, 0x84, 0x44, 0x99, 0x86, 0xc9, + 0x25, 0xc5, 0x50, 0xe5, 0x9b, 0x53, 0x25, 0xd5, 0x54, 0xa6, 0xe4, 0x32, 0xd1, 0x74, 0x3e, 0x7e, + 0xa8, 0x4a, 0x48, 0xb5, 0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ef, 0xeb, 0x6a, 0x73, 0x04, + 0x8d, 0xa1, 0xd4, 0x8e, 0xec, 0xde, 0xd5, 0xa5, 0xe4, 0x53, 0x6d, 0xa5, 0x5e, 0x3b, 0x2b, 0xd2, + 0xbf, 0xc5, 0x02, 0x1b, 0x16, 0xef, 0x21, 0x48, 0x04, 0x65, 0xda, 0x38, 0x3a, 0xf3, 0x70, 0xc8, + 0x05, 0x42, 0xd3, 0xab, 0x7d, 0xb1, 0xb9, 0x8b, 0x3c, 0xba, 0xac, 0x25, 0xda, 0x38, 0x32, 0x73, + 0x30, 0xca, 0x31, 0xb0, 0xee, 0xe8, 0x8b, 0xc9, 0x1d, 0x10, 0xfc, 0x92, 0x6c, 0x1c, 0x8b, 0xaf, + 0x90, 0xb3, 0x26, 0x0c, 0xc1, 0x45, 0xc5, 0x30, 0xaf, 0x68, 0x75, 0x35, 0x26, 0x13, 0xfc, 0x26, + 0xec, 0x70, 0xb6, 0x8a, 0x91, 0x2d, 0x63, 0x28, 0xb5, 0x33, 0x23, 0x48, 0x6c, 0xaf, 0x90, 0xec, + 0xbd, 0x42, 0xba, 0x62, 0x47, 0x64, 0x0f, 0x59, 0x80, 0x57, 0x97, 0x92, 0x7b, 0x59, 0x2e, 0x67, + 0xaa, 0x78, 0xff, 0x71, 0x12, 0x15, 0xd6, 0x52, 0x89, 0x57, 0x9d, 0xa5, 0xf6, 0xe2, 0xe3, 0x22, + 0x9d, 0x82, 0x61, 0xab, 0x05, 0x6c, 0x91, 0x04, 0xc9, 0xbd, 0x4b, 0x4a, 0x17, 0xd5, 0xa6, 0x46, + 0x2a, 0xd6, 0xe4, 0xec, 0x36, 0xab, 0x68, 0x81, 0x85, 0x8b, 0x3f, 0x20, 0x98, 0xf0, 0xcd, 0xfc, + 0x1a, 0x59, 0xeb, 0xaa, 0xd7, 0xf5, 0x5a, 0x7b, 0xb3, 0x28, 0x51, 0x85, 0x74, 0x44, 0xbc, 0x03, + 0x2a, 0xf3, 0x2d, 0x82, 0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x55, 0x6b, 0x34, 0x4d, 0xd1, + 0xbe, 0xc3, 0x05, 0x6f, 0xfa, 0x0e, 0x95, 0xf0, 0x4d, 0xdf, 0x4b, 0x22, 0x1d, 0x31, 0xba, 0xcf, + 0x4d, 0xbf, 0x0b, 0xf7, 0x67, 0x5b, 0xe0, 0x85, 0x18, 0x77, 0x73, 0x9c, 0x8d, 0x21, 0x72, 0xd0, + 0x01, 0x30, 0x37, 0x50, 0x0e, 0xce, 0xfc, 0x2d, 0xca, 0xfc, 0x32, 0xbe, 0xd4, 0xdf, 0xc2, 0x85, + 0x9d, 0x06, 0x2b, 0x6b, 0xef, 0xe0, 0x02, 0xaf, 0xe0, 0xf8, 0x74, 0x0c, 0x12, 0xae, 0x1d, 0xea, + 0x4c, 0xfc, 0x89, 0x9c, 0x72, 0x9e, 0x52, 0x9e, 0xc7, 0xb9, 0x3e, 0x29, 0xbb, 0x76, 0xd7, 0x6c, + 0xfe, 0xe1, 0x72, 0x02, 0x3d, 0x5a, 0x4e, 0xa0, 0xbf, 0x97, 0x13, 0xe8, 0xfe, 0x4a, 0x62, 0xe8, + 0xd1, 0x4a, 0x62, 0xe8, 0xcf, 0x95, 0xc4, 0xd0, 0xdb, 0x99, 0x8e, 0x17, 0x37, 0xbc, 0x52, 0xba, + 0xa6, 0x94, 0x0c, 0xa7, 0xec, 0xcd, 0xa9, 0x49, 0xf9, 0x03, 0xbb, 0x38, 0x7d, 0x91, 0x53, 0xda, + 0x4e, 0x5d, 0xd0, 0x89, 0xff, 0x02, 0x00, 0x00, 0xff, 0xff, 0xcb, 0x70, 0x24, 0x96, 0x44, 0x1b, + 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/lockup/types/tx.pb.go b/x/lockup/types/tx.pb.go index 68e7bc70548..774447792f5 100644 --- a/x/lockup/types/tx.pb.go +++ b/x/lockup/types/tx.pb.go @@ -453,44 +453,44 @@ func init() { func init() { proto.RegisterFile("osmosis/lockup/tx.proto", fileDescriptor_bcdad5af0d24735f) } var fileDescriptor_bcdad5af0d24735f = []byte{ - // 590 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x54, 0xcd, 0x6e, 0xd3, 0x4c, - 0x14, 0x8d, 0x9d, 0xaf, 0x5f, 0xcb, 0xa5, 0xa4, 0xd4, 0x2a, 0x6a, 0x62, 0x81, 0x1d, 0x2c, 0xa0, - 0x41, 0x6a, 0x3d, 0xa4, 0x05, 0x21, 0xb1, 0x40, 0x22, 0x84, 0x45, 0x05, 0x91, 0x90, 0x55, 0x24, - 0xc4, 0x02, 0xc9, 0x76, 0x86, 0xa9, 0x15, 0xc7, 0x63, 0x65, 0xec, 0x92, 0xec, 0x79, 0x00, 0x96, - 0x3c, 0x03, 0x0b, 0x36, 0xbc, 0x44, 0x97, 0x5d, 0xb2, 0x4a, 0x51, 0xb2, 0x63, 0xd9, 0x35, 0x0b, - 0xe4, 0x71, 0xc6, 0xca, 0x9f, 0x48, 0x84, 0x04, 0xab, 0xc9, 0xcc, 0xb9, 0xf7, 0xdc, 0x7b, 0x4e, - 0x4e, 0x02, 0xdb, 0x94, 0xb5, 0x29, 0xf3, 0x18, 0xf2, 0xa9, 0xdb, 0x8a, 0x43, 0x14, 0x75, 0xcd, - 0xb0, 0x43, 0x23, 0xaa, 0x14, 0x46, 0x80, 0x99, 0x02, 0xea, 0x16, 0xa1, 0x84, 0x72, 0x08, 0x25, - 0x9f, 0xd2, 0x2a, 0x55, 0x23, 0x94, 0x12, 0x1f, 0x23, 0x7e, 0x73, 0xe2, 0x77, 0xa8, 0x19, 0x77, - 0xec, 0xc8, 0xa3, 0x81, 0xc0, 0x5d, 0x4e, 0x83, 0x1c, 0x9b, 0x61, 0x74, 0x52, 0x75, 0x70, 0x64, - 0x57, 0x91, 0x4b, 0x3d, 0x81, 0x97, 0xa6, 0xc6, 0x27, 0x47, 0x0a, 0x19, 0x1f, 0x64, 0x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a0, 0x49, 0xdf, 0x07, 0x9a, 0xf4, 0x71, 0xa8, 0xe5, 0xce, - 0x86, 0x5a, 0xee, 0xdb, 0x50, 0xcb, 0xbd, 0xa9, 0x8e, 0x65, 0x7d, 0x44, 0xb6, 0xe7, 0xdb, 0x0e, - 0x13, 0x17, 0x74, 0xf2, 0x10, 0x75, 0xb3, 0x3f, 0xfa, 0x24, 0xfa, 0xce, 0xff, 0x3c, 0x50, 0x07, - 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0xba, 0x65, 0x88, 0x8d, 0x07, 0x06, 0x00, 0x00, + // 589 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x54, 0xbf, 0x6f, 0xd3, 0x40, + 0x18, 0x8d, 0x1d, 0x4a, 0xcb, 0x51, 0x52, 0x6a, 0x15, 0x35, 0xb1, 0xc0, 0x0e, 0x16, 0xd0, 0x20, + 0xb5, 0x77, 0x4d, 0x0a, 0x0b, 0x03, 0x12, 0x21, 0x0c, 0x95, 0x1a, 0x09, 0x59, 0x45, 0x42, 0x0c, + 0x48, 0xb6, 0x73, 0x5c, 0xad, 0x38, 0x3e, 0x2b, 0x67, 0x97, 0x64, 0xe7, 0x0f, 0x60, 0xe4, 0x6f, + 0x60, 0x60, 0xe1, 0x9f, 0xe8, 0xd8, 0x91, 0x29, 0x45, 0xc9, 0xc6, 0xd8, 0x99, 0x01, 0xf9, 0xec, + 0xb3, 0xf2, 0x4b, 0x24, 0x42, 0xa2, 0xd3, 0xe5, 0xee, 0x7d, 0xdf, 0xfb, 0xbe, 0xf7, 0xf2, 0x12, + 0xb0, 0x4d, 0x59, 0x87, 0x32, 0x97, 0x21, 0x8f, 0x3a, 0xed, 0x28, 0x40, 0x61, 0x0f, 0x06, 0x5d, + 0x1a, 0x52, 0xa5, 0x90, 0x02, 0x30, 0x01, 0xd4, 0x2d, 0x42, 0x09, 0xe5, 0x10, 0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a9, 0xbb, 0xcb, 0x54, 0x65, 0x83, + 0xde, 0x83, 0xc2, 0x54, 0x26, 0xef, 0x2f, 0xec, 0x57, 0x1f, 0x2f, 0x2c, 0xc9, 0xf8, 0xdf, 0x82, + 0xf5, 0x89, 0x2c, 0xe8, 0x73, 0x5a, 0xc7, 0x0b, 0xd4, 0x9d, 0x05, 0x05, 0x82, 0xb9, 0x7e, 0x74, + 0x36, 0xd4, 0xa4, 0xf3, 0xa1, 0x26, 0xfd, 0x1c, 0x6a, 0xd2, 0xe7, 0x91, 0x96, 0x3b, 0x1f, 0x69, + 0xb9, 0x1f, 0x23, 0x2d, 0xf7, 0xae, 0x36, 0x96, 0xf5, 0x94, 0x6c, 0xcf, 0xb3, 0x6c, 0x26, 0x2e, + 0xe8, 0xb4, 0xba, 0x8f, 0x7a, 0xd9, 0x3f, 0x7d, 0x9c, 0x7d, 0xfb, 0x3a, 0x4f, 0xd4, 0xc1, 0x9f, + 0x00, 0x00, 0x00, 0xff, 0xff, 0xeb, 0xf8, 0x55, 0x1e, 0x08, 0x06, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/mint/client/cli/cli_test.go b/x/mint/client/cli/cli_test.go index f4e926ddd81..d9703eb8933 100644 --- a/x/mint/client/cli/cli_test.go +++ b/x/mint/client/cli/cli_test.go @@ -10,8 +10,8 @@ import ( "github.com/stretchr/testify/suite" tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/mint/client/cli" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/mint/client/cli" "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" diff --git a/x/mint/client/cli/query.go b/x/mint/client/cli/query.go index 26c94d6f9ac..368faff7cc4 100644 --- a/x/mint/client/cli/query.go +++ b/x/mint/client/cli/query.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/mint/client/rest/grpc_query_test.go b/x/mint/client/rest/grpc_query_test.go index b7aa537000a..9f8470cafe7 100644 --- a/x/mint/client/rest/grpc_query_test.go +++ b/x/mint/client/rest/grpc_query_test.go @@ -13,8 +13,8 @@ import ( "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/app" + minttypes "github.com/osmosis-labs/osmosis/v10/x/mint/types" "github.com/cosmos/cosmos-sdk/testutil/network" ) diff --git a/x/mint/client/rest/query.go b/x/mint/client/rest/query.go index cab71e70587..6d52375f8a4 100644 --- a/x/mint/client/rest/query.go +++ b/x/mint/client/rest/query.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" diff --git a/x/mint/keeper/export_test.go b/x/mint/keeper/export_test.go index 67dd378ed54..888411f125f 100644 --- a/x/mint/keeper/export_test.go +++ b/x/mint/keeper/export_test.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" ) type ( diff --git a/x/mint/keeper/genesis.go b/x/mint/keeper/genesis.go index 5633e9fcadf..875ad788626 100644 --- a/x/mint/keeper/genesis.go +++ b/x/mint/keeper/genesis.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" ) const developerVestingAmount = 225_000_000_000_000 diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index 72a29ba8b9c..dce0c939a66 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -7,9 +7,9 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/mint/keeper" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" ) var customGenesis = types.NewGenesisState( diff --git a/x/mint/keeper/grpc_query.go b/x/mint/keeper/grpc_query.go index 45b965152b3..00991239fa0 100644 --- a/x/mint/keeper/grpc_query.go +++ b/x/mint/keeper/grpc_query.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" ) var _ types.QueryServer = Querier{} diff --git a/x/mint/keeper/grpc_query_test.go b/x/mint/keeper/grpc_query_test.go index 9f0d8d080ca..a53e74b8c0c 100644 --- a/x/mint/keeper/grpc_query_test.go +++ b/x/mint/keeper/grpc_query_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" ) func TestMintGRPCQueryTestSuite(t *testing.T) { diff --git a/x/mint/keeper/hooks.go b/x/mint/keeper/hooks.go index 9c3e520e7fd..6fb37f37692 100644 --- a/x/mint/keeper/hooks.go +++ b/x/mint/keeper/hooks.go @@ -3,8 +3,8 @@ package keeper import ( "fmt" - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index 071e0124eb8..283e2cc6a6f 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -8,10 +8,10 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - osmoapp "github.com/osmosis-labs/osmosis/v7/app" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + osmoapp "github.com/osmosis-labs/osmosis/v10/app" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/keeper" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index f010155c8e7..93dab130363 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -6,8 +6,8 @@ import ( "github.com/tendermint/tendermint/libs/log" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" - poolincentivestypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" + poolincentivestypes "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 73baaa8c384..12eb528e3b1 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -16,12 +16,12 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" - poolincentivestypes "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/keeper" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" + poolincentivestypes "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) type KeeperTestSuite struct { diff --git a/x/mint/module.go b/x/mint/module.go index 89eeb0ecb1e..e371d3a17d1 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -18,11 +18,11 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/osmosis-labs/osmosis/v7/x/mint/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/mint/client/rest" - "github.com/osmosis-labs/osmosis/v7/x/mint/keeper" - "github.com/osmosis-labs/osmosis/v7/x/mint/simulation" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/mint/client/rest" + "github.com/osmosis-labs/osmosis/v10/x/mint/keeper" + "github.com/osmosis-labs/osmosis/v10/x/mint/simulation" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" ) var ( diff --git a/x/mint/simulation/decoder.go b/x/mint/simulation/decoder.go index 33a752a5dc9..81a136f4ccd 100644 --- a/x/mint/simulation/decoder.go +++ b/x/mint/simulation/decoder.go @@ -4,7 +4,7 @@ import ( "bytes" "fmt" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/kv" diff --git a/x/mint/simulation/decoder_test.go b/x/mint/simulation/decoder_test.go index 23e5adfde66..e10979f35ba 100644 --- a/x/mint/simulation/decoder_test.go +++ b/x/mint/simulation/decoder_test.go @@ -6,9 +6,9 @@ import ( "github.com/stretchr/testify/require" - simapp "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/mint/simulation" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + simapp "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/mint/simulation" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/kv" diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index b750d55821c..3656ad635b7 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -5,7 +5,7 @@ package simulation import ( "math/rand" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" diff --git a/x/mint/simulation/genesis_test.go b/x/mint/simulation/genesis_test.go index 130760e45c8..41c9bf358a8 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/x/mint/simulation" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/simulation" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" diff --git a/x/mint/types/expected_keepers.go b/x/mint/types/expected_keepers.go index 29f1c7d3a78..4db66e45456 100644 --- a/x/mint/types/expected_keepers.go +++ b/x/mint/types/expected_keepers.go @@ -1,7 +1,7 @@ package types // noalias import ( - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" diff --git a/x/mint/types/genesis.pb.go b/x/mint/types/genesis.pb.go index f93c2d59a1d..260ff0b4280 100644 --- a/x/mint/types/genesis.pb.go +++ b/x/mint/types/genesis.pb.go @@ -97,7 +97,7 @@ func init() { } var fileDescriptor_12e6a5511ad3feeb = []byte{ - // 282 bytes of a gzipped FileDescriptorProto + // 283 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xca, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0xcf, 0xcd, 0xcc, 0x2b, 0xd1, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, @@ -110,12 +110,12 @@ var fileDescriptor_12e6a5511ad3feeb = []byte{ 0xc5, 0x25, 0x5e, 0x94, 0x9a, 0x52, 0x9a, 0x5c, 0x92, 0x99, 0x9f, 0x17, 0x5f, 0x5c, 0x92, 0x58, 0x54, 0x92, 0x9a, 0x12, 0x9f, 0x5a, 0x90, 0x9f, 0x9c, 0x21, 0xc1, 0xac, 0xc0, 0xa8, 0xc1, 0xec, 0xa4, 0xf4, 0xe9, 0x9e, 0xbc, 0x5c, 0x65, 0x62, 0x6e, 0x8e, 0x95, 0x12, 0x0e, 0x85, 0x4a, 0x41, - 0xa2, 0x70, 0x99, 0x60, 0x88, 0x84, 0x2b, 0x48, 0xdc, 0xc9, 0xf3, 0xc4, 0x23, 0x39, 0xc6, 0x0b, + 0xa2, 0x70, 0x99, 0x60, 0x88, 0x84, 0x2b, 0x48, 0xdc, 0xc9, 0xeb, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, - 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xf4, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, - 0xf5, 0xa1, 0x6e, 0xd5, 0xcd, 0x49, 0x4c, 0x2a, 0x86, 0x71, 0xf4, 0xcb, 0xcc, 0xf5, 0x2b, 0x20, - 0x81, 0x57, 0x52, 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x0e, 0x36, 0x63, 0x40, 0x00, 0x00, 0x00, - 0xff, 0xff, 0xa2, 0xcc, 0xdf, 0xaf, 0xa9, 0x01, 0x00, 0x00, + 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0x0c, 0xd2, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, + 0xf5, 0xa1, 0x6e, 0xd5, 0xcd, 0x49, 0x4c, 0x2a, 0x86, 0x71, 0xf4, 0xcb, 0x0c, 0x0d, 0xf4, 0x2b, + 0x20, 0xa1, 0x57, 0x52, 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x0e, 0x37, 0x63, 0x40, 0x00, 0x00, + 0x00, 0xff, 0xff, 0x4c, 0xe3, 0x63, 0xd9, 0xaa, 0x01, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { diff --git a/x/mint/types/mint.pb.go b/x/mint/types/mint.pb.go index 954fdc0fc56..a2a03bfdc93 100644 --- a/x/mint/types/mint.pb.go +++ b/x/mint/types/mint.pb.go @@ -278,53 +278,53 @@ func init() { proto.RegisterFile("osmosis/mint/v1beta1/mint.proto", fileDescript var fileDescriptor_ccb38f8335e0f45b = []byte{ // 768 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0xcd, 0x6e, 0xf3, 0x44, - 0x14, 0x8d, 0x49, 0x49, 0xe9, 0x54, 0x6d, 0x8a, 0x55, 0x1a, 0x53, 0x44, 0xdc, 0x5a, 0x2d, 0x0a, - 0x12, 0x8d, 0xd5, 0x76, 0x81, 0xd4, 0x0d, 0x10, 0x85, 0x42, 0x90, 0x90, 0xc2, 0xb0, 0xa8, 0xd4, - 0x8d, 0xe5, 0xd8, 0x53, 0x77, 0xd4, 0x78, 0xc6, 0xcc, 0x4c, 0x12, 0xb2, 0xe1, 0x05, 0xd8, 0xb0, - 0xec, 0x12, 0xde, 0xa6, 0xcb, 0xb2, 0x43, 0x2c, 0x22, 0xd4, 0xbe, 0x41, 0x5e, 0x80, 0x4f, 0xf3, - 0xe3, 0xa4, 0x75, 0x1b, 0xe9, 0x8b, 0xbe, 0x55, 0x3c, 0xe7, 0x9e, 0x9c, 0x73, 0x7d, 0xe7, 0xde, - 0x6b, 0xe0, 0x52, 0x9e, 0x52, 0x8e, 0xb9, 0x9f, 0x62, 0x22, 0xfc, 0xe1, 0x71, 0x0f, 0x89, 0xf0, - 0x58, 0x1d, 0x9a, 0x19, 0xa3, 0x82, 0xda, 0xdb, 0x86, 0xd0, 0x54, 0x98, 0x21, 0xec, 0x6e, 0x27, - 0x34, 0xa1, 0x8a, 0xe0, 0xcb, 0x27, 0xcd, 0xdd, 0x75, 0x13, 0x4a, 0x93, 0x3e, 0xf2, 0xd5, 0xa9, - 0x37, 0xb8, 0xf2, 0x05, 0x4e, 0x11, 0x17, 0x61, 0x9a, 0x19, 0xc2, 0xc7, 0x45, 0x42, 0x48, 0xc6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54, 0x33, 0x4a, 0xfb, 0x01, 0x26, 0x11, 0x22, 0x02, 0x0f, - 0x11, 0x37, 0x6f, 0xf6, 0xfd, 0xd2, 0x1e, 0x3b, 0xda, 0xa3, 0x20, 0xe7, 0xc1, 0x4d, 0x89, 0x74, - 0x66, 0x80, 0x3d, 0x02, 0x1f, 0xc6, 0x68, 0x88, 0xfa, 0x34, 0x43, 0x2c, 0x60, 0x68, 0x14, 0xb2, - 0x98, 0x3b, 0x65, 0x65, 0xfa, 0xc3, 0xd2, 0xa6, 0x8e, 0x36, 0x7d, 0x21, 0xe8, 0xc1, 0xad, 0x19, - 0x06, 0x35, 0x64, 0x13, 0xb0, 0x19, 0xd1, 0x34, 0x1d, 0x10, 0x2c, 0xc6, 0x81, 0x4c, 0xca, 0x59, - 0x51, 0xae, 0xdf, 0x2d, 0xed, 0xfa, 0x91, 0x76, 0x7d, 0xae, 0xe6, 0xc1, 0x8d, 0x19, 0xd0, 0x95, - 0xe7, 0xff, 0x2b, 0xa0, 0xd2, 0x0d, 0x59, 0x98, 0x72, 0xfb, 0x53, 0x00, 0xe4, 0xec, 0x05, 0x31, - 0x22, 0x34, 0xd5, 0xb7, 0x08, 0xd7, 0x24, 0xd2, 0x96, 0x80, 0xfd, 0xbb, 0x05, 0x9c, 0x04, 0x11, - 0xc4, 0x31, 0x0f, 0x5e, 0xcc, 0x85, 0xbe, 0x8f, 0x9f, 0x96, 0x4e, 0xd2, 0xd5, 0x49, 0x2e, 0xd2, - 0xf5, 0xe0, 0x8e, 0x09, 0x7d, 0xfb, 0x7c, 0x4c, 0xec, 0xf3, 0x7c, 0x38, 0x71, 0x2c, 0xef, 0xec, - 0x0a, 0x23, 0x66, 0xee, 0xe7, 0x93, 0xe2, 0xb8, 0xcd, 0x19, 0xf9, 0xb8, 0x75, 0x66, 0x88, 0xdd, - 0x03, 0xbb, 0x0c, 0xc5, 0x83, 0x48, 0x76, 0x71, 0x90, 0x21, 0x86, 0x69, 0x1c, 0x60, 0xa2,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x72, 0x11, 0xde, 0x60, 0x92, 0x98, 0x14, 0xbf, 0x5a, 0xda, 0xd5, 0xbc, 0x90, 0x91, 0xf1, + 0x60, 0x2e, 0x68, 0xff, 0x04, 0xaa, 0x19, 0xa5, 0xfd, 0x00, 0x93, 0x08, 0x11, 0x81, 0x87, 0x88, + 0x9b, 0x37, 0xfb, 0x6e, 0x69, 0x8f, 0x2d, 0xed, 0x51, 0x90, 0xf3, 0xe0, 0xba, 0x44, 0x3a, 0x33, + 0xc0, 0x1e, 0x81, 0x0f, 0x63, 0x34, 0x44, 0x7d, 0x9a, 0x21, 0x16, 0x30, 0x34, 0x0a, 0x59, 0xcc, + 0x9d, 0xb2, 0x32, 0x3d, 0x5f, 0xda, 0xd4, 0xd1, 0xa6, 0x2f, 0x04, 0x3d, 0xb8, 0x31, 0xc3, 0xa0, + 0x86, 0x6c, 0x02, 0xd6, 0x23, 0x9a, 0xa6, 0x03, 0x82, 0xc5, 0x38, 0x90, 0x49, 0x39, 0x2b, 0xca, + 0xf5, 0xdb, 0xa5, 0x5d, 0x3f, 0xd2, 0xae, 0xcf, 0xd5, 0x3c, 0xb8, 0x36, 0x03, 0xba, 0xf2, 0xfc, + 0x6f, 0x05, 0x54, 0xba, 0x21, 0x0b, 0x53, 0x6e, 0x7f, 0x0a, 0x80, 0x9c, 0xbd, 0x20, 0x46, 0x84, + 0xa6, 0xfa, 0x16, 0xe1, 0x1b, 0x89, 0xb4, 0x25, 0x60, 0xff, 0x6a, 0x01, 0x27, 0x41, 0x04, 0x71, + 0xcc, 0x83, 0x17, 0x73, 0xa1, 0xef, 0xe3, 0x87, 0xa5, 0x93, 0x74, 0x75, 0x92, 0x8b, 0x74, 0x3d, + 0xb8, 0x65, 0x42, 0xdf, 0x3c, 0x1f, 0x13, 0xfb, 0x2c, 0x1f, 0x4e, 0x1c, 0xcb, 0x3b, 0xbb, 0xc2, + 0x88, 0x99, 0xfb, 0xf9, 0xa4, 0x38, 0x6e, 0x73, 0x46, 0x3e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, + 0x9e, 0x56, 0xf4, 0x47, 0xc9, 0x53, 0x8d, 0x71, 0xba, 0x72, 0xfb, 0xbb, 0x5b, 0x6a, 0x9d, 0xdf, + 0x3d, 0xd4, 0xad, 0xfb, 0x87, 0xba, 0xf5, 0xcf, 0x43, 0xdd, 0xfa, 0xed, 0xb1, 0x5e, 0xba, 0x7f, + 0xac, 0x97, 0xfe, 0x7a, 0xac, 0x97, 0x2e, 0x0f, 0x9f, 0x74, 0x85, 0x29, 0xd6, 0x41, 0x3f, 0xec, + 0xf1, 0xfc, 0xe0, 0x0f, 0x8f, 0x0e, 0xfd, 0x9f, 0xf5, 0x17, 0x55, 0xf5, 0x48, 0xaf, 0xa2, 0xbe, + 0x61, 0x27, 0xff, 0x05, 0x00, 0x00, 0xff, 0xff, 0xae, 0x9c, 0x03, 0xa2, 0x6e, 0x07, 0x00, 0x00, } func (m *Minter) Marshal() (dAtA []byte, err error) { diff --git a/x/mint/types/minter_test.go b/x/mint/types/minter_test.go index 4df3dc8e31e..b83829d29bf 100644 --- a/x/mint/types/minter_test.go +++ b/x/mint/types/minter_test.go @@ -4,7 +4,7 @@ import ( "math/rand" "testing" - "github.com/osmosis-labs/osmosis/v7/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" diff --git a/x/mint/types/params.go b/x/mint/types/params.go index 19dc168260b..6631b9927eb 100644 --- a/x/mint/types/params.go +++ b/x/mint/types/params.go @@ -7,7 +7,7 @@ import ( yaml "gopkg.in/yaml.v2" - epochtypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + epochtypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" diff --git a/x/mint/types/query.pb.go b/x/mint/types/query.pb.go index d394f9f53d7..ad109b6d370 100644 --- a/x/mint/types/query.pb.go +++ b/x/mint/types/query.pb.go @@ -202,31 +202,31 @@ func init() { proto.RegisterFile("osmosis/mint/v1beta1/query.proto", fileDescrip var fileDescriptor_cd2f42111e753fbb = []byte{ // 394 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc8, 0x2f, 0xce, 0xcd, - 0x2f, 0xce, 0x2c, 0xd6, 0xcf, 0xcd, 0xcc, 0x2b, 0xd1, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, - 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x81, 0xaa, - 0xd0, 0x03, 0xa9, 0xd0, 0x83, 0xaa, 0x90, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x2b, 0xd0, 0x07, - 0xb1, 0x20, 0x6a, 0xa5, 0x64, 0xd2, 0xf3, 0xf3, 0xd3, 0x73, 0x52, 0xf5, 0x13, 0x0b, 0x32, 0xf5, - 0x13, 0xf3, 0xf2, 0xf2, 0x4b, 0x12, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0xa1, 0xb2, 0xf2, 0x58, 0xed, - 0x02, 0x1b, 0x0b, 0x56, 0xa0, 0x24, 0xc2, 0x25, 0x14, 0x08, 0xb2, 0x39, 0x20, 0xb1, 0x28, 0x31, - 0xb7, 0x38, 0x28, 0xb5, 0xb0, 0x34, 0xb5, 0xb8, 0x44, 0x29, 0x90, 0x4b, 0x18, 0x45, 0xb4, 0xb8, - 0x20, 0x3f, 0xaf, 0x38, 0x55, 0xc8, 0x8a, 0x8b, 0xad, 0x00, 0x2c, 0x22, 0xc1, 0xa8, 0xc0, 0xa8, - 0xc1, 0x6d, 0x24, 0xa3, 0x87, 0xcd, 0xa1, 0x7a, 0x10, 0x5d, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, - 0x04, 0x41, 0x75, 0x28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x1c, 0xc3, 0x8d, 0xc7, 0x72, - 0x0c, 0x51, 0xfa, 0x48, 0xb1, 0x01, 0x35, 0x4b, 0x37, 0x27, 0x31, 0xa9, 0x18, 0x6e, 0x70, 0x99, - 0xb9, 0x7e, 0x05, 0xc4, 0x74, 0x70, 0xd4, 0x24, 0xb1, 0x81, 0xd3, 0xa3, 0x31, 0x20, 0x00, 0x00, - 0xff, 0xff, 0x6d, 0x21, 0x17, 0x68, 0x1e, 0x03, 0x00, 0x00, + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x92, 0xc1, 0x4e, 0xea, 0x40, + 0x14, 0x86, 0x5b, 0x72, 0x2f, 0x8b, 0xb9, 0x37, 0xc1, 0x8c, 0x2c, 0x4c, 0xad, 0x85, 0x34, 0x86, + 0xe0, 0x82, 0x19, 0x8a, 0x3b, 0x97, 0x44, 0x37, 0xae, 0x80, 0x9d, 0x6e, 0x4c, 0x5b, 0x27, 0xa5, + 0x91, 0x76, 0x4a, 0x67, 0x20, 0xb2, 0xd5, 0x17, 0x30, 0xf1, 0x25, 0x7c, 0x04, 0x1f, 0x81, 0x25, + 0x89, 0x1b, 0xe3, 0x82, 0x18, 0xf0, 0x41, 0x4c, 0xa7, 0x23, 0x11, 0x9c, 0x18, 0x5d, 0xb5, 0x99, + 0xf3, 0x9f, 0xff, 0xff, 0xe6, 0x9c, 0x01, 0x55, 0xca, 0x22, 0xca, 0x42, 0x86, 0xa3, 0x30, 0xe6, + 0x78, 0xec, 0x78, 0x84, 0xbb, 0x0e, 0x1e, 0x8e, 0x48, 0x3a, 0x41, 0x49, 0x4a, 0x39, 0x85, 0x65, + 0xa9, 0x40, 0x99, 0x02, 0x49, 0x85, 0x51, 0x0e, 0x68, 0x40, 0x85, 0x00, 0x67, 0x7f, 0xb9, 0xd6, + 0x30, 0x03, 0x4a, 0x83, 0x01, 0xc1, 0x6e, 0x12, 0x62, 0x37, 0x8e, 0x29, 0x77,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40, 0x24, 0x00, 0xeb, 0xb0, 0xa6, 0x06, 0xdc, 0xdc, 0x40, 0xfb, 0x74, + 0xba, 0xb0, 0xf4, 0xd9, 0xc2, 0xd2, 0x5f, 0x17, 0x96, 0x7e, 0xb7, 0xb4, 0xb4, 0xd9, 0xd2, 0xd2, + 0x9e, 0x97, 0x96, 0x76, 0xde, 0xfc, 0xb4, 0x0d, 0xe9, 0xd5, 0x18, 0xb8, 0x1e, 0x5b, 0x19, 0x8f, + 0x9d, 0x26, 0xbe, 0xce, 0xed, 0xc5, 0x6e, 0xbc, 0xa2, 0x78, 0x90, 0x87, 0xef, 0x01, 0x00, 0x00, + 0xff, 0xff, 0x80, 0xf4, 0x7f, 0xd2, 0x1f, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/pool-incentives/client/cli/cli_test.go b/x/pool-incentives/client/cli/cli_test.go index a2f38150a08..4de704adcf2 100644 --- a/x/pool-incentives/client/cli/cli_test.go +++ b/x/pool-incentives/client/cli/cli_test.go @@ -4,9 +4,9 @@ import ( "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" diff --git a/x/pool-incentives/client/cli/query.go b/x/pool-incentives/client/cli/query.go index f4c9bb56ea0..e4418f13e89 100644 --- a/x/pool-incentives/client/cli/query.go +++ b/x/pool-incentives/client/cli/query.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/pool-incentives/client/cli/tx.go b/x/pool-incentives/client/cli/tx.go index 06a231cad26..f3ea1a7f3d2 100644 --- a/x/pool-incentives/client/cli/tx.go +++ b/x/pool-incentives/client/cli/tx.go @@ -12,8 +12,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/client/cli" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) func NewTxCmd() *cobra.Command { diff --git a/x/pool-incentives/client/proposal_handler.go b/x/pool-incentives/client/proposal_handler.go index f70f5d1071d..6f90c30e2d9 100644 --- a/x/pool-incentives/client/proposal_handler.go +++ b/x/pool-incentives/client/proposal_handler.go @@ -1,8 +1,8 @@ package client import ( - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/client/rest" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/client/rest" govclient "github.com/cosmos/cosmos-sdk/x/gov/client" ) diff --git a/x/pool-incentives/client/rest/tx.go b/x/pool-incentives/client/rest/tx.go index 2b12eebdc23..8dc1b95d3d4 100644 --- a/x/pool-incentives/client/rest/tx.go +++ b/x/pool-incentives/client/rest/tx.go @@ -10,7 +10,7 @@ import ( govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) type UpdatePoolIncentivesRequest struct { diff --git a/x/pool-incentives/handler.go b/x/pool-incentives/handler.go index 3177660db70..9b12bf7efcd 100644 --- a/x/pool-incentives/handler.go +++ b/x/pool-incentives/handler.go @@ -5,8 +5,8 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/keeper" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/keeper" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) func NewPoolIncentivesProposalHandler(k keeper.Keeper) govtypes.Handler { diff --git a/x/pool-incentives/keeper/distr.go b/x/pool-incentives/keeper/distr.go index 828fcd9388a..0e5e9f96372 100644 --- a/x/pool-incentives/keeper/distr.go +++ b/x/pool-incentives/keeper/distr.go @@ -4,7 +4,7 @@ import ( "fmt" "sort" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/pool-incentives/keeper/distr_test.go b/x/pool-incentives/keeper/distr_test.go index 9596a9123d8..f3f3b56cf8f 100644 --- a/x/pool-incentives/keeper/distr_test.go +++ b/x/pool-incentives/keeper/distr_test.go @@ -3,8 +3,8 @@ package keeper_test import ( abci "github.com/tendermint/tendermint/abci/types" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + minttypes "github.com/osmosis-labs/osmosis/v10/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" diff --git a/x/pool-incentives/keeper/geneis_test.go b/x/pool-incentives/keeper/geneis_test.go index 3577ea9af03..5468664f50b 100644 --- a/x/pool-incentives/keeper/geneis_test.go +++ b/x/pool-incentives/keeper/geneis_test.go @@ -9,11 +9,11 @@ import ( "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - pool_incentives "github.com/osmosis-labs/osmosis/v7/x/pool-incentives" + pool_incentives "github.com/osmosis-labs/osmosis/v10/x/pool-incentives" - simapp "github.com/osmosis-labs/osmosis/v7/app" + simapp "github.com/osmosis-labs/osmosis/v10/app" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) var ( diff --git a/x/pool-incentives/keeper/genesis.go b/x/pool-incentives/keeper/genesis.go index d2e4d0fa77b..cb2249f87c9 100644 --- a/x/pool-incentives/keeper/genesis.go +++ b/x/pool-incentives/keeper/genesis.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) func (k Keeper) InitGenesis(ctx sdk.Context, genState *types.GenesisState) { diff --git a/x/pool-incentives/keeper/gov.go b/x/pool-incentives/keeper/gov.go index 8d3aa985c7b..a3bdb911212 100644 --- a/x/pool-incentives/keeper/gov.go +++ b/x/pool-incentives/keeper/gov.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) func (k Keeper) HandleReplacePoolIncentivesProposal(ctx sdk.Context, p *types.ReplacePoolIncentivesProposal) error { diff --git a/x/pool-incentives/keeper/grpc_query.go b/x/pool-incentives/keeper/grpc_query.go index 164324277dc..d756067c749 100644 --- a/x/pool-incentives/keeper/grpc_query.go +++ b/x/pool-incentives/keeper/grpc_query.go @@ -9,8 +9,8 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" - incentivetypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + incentivetypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) var _ types.QueryServer = Querier{} diff --git a/x/pool-incentives/keeper/grpc_query_test.go b/x/pool-incentives/keeper/grpc_query_test.go index 502f935f890..991e6878689 100644 --- a/x/pool-incentives/keeper/grpc_query_test.go +++ b/x/pool-incentives/keeper/grpc_query_test.go @@ -6,9 +6,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) var ( diff --git a/x/pool-incentives/keeper/hooks.go b/x/pool-incentives/keeper/hooks.go index 60fd8e97254..c2b49cdf488 100644 --- a/x/pool-incentives/keeper/hooks.go +++ b/x/pool-incentives/keeper/hooks.go @@ -3,8 +3,8 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + minttypes "github.com/osmosis-labs/osmosis/v10/x/mint/types" ) type Hooks struct { diff --git a/x/pool-incentives/keeper/keeper.go b/x/pool-incentives/keeper/keeper.go index b3b259df095..9643e820750 100644 --- a/x/pool-incentives/keeper/keeper.go +++ b/x/pool-incentives/keeper/keeper.go @@ -6,10 +6,10 @@ import ( "github.com/tendermint/tendermint/libs/log" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/pool-incentives/keeper/keeper_test.go b/x/pool-incentives/keeper/keeper_test.go index f0bad5d41d0..6804e6dc5e3 100644 --- a/x/pool-incentives/keeper/keeper_test.go +++ b/x/pool-incentives/keeper/keeper_test.go @@ -5,9 +5,9 @@ import ( "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) type KeeperTestSuite struct { diff --git a/x/pool-incentives/keeper/params.go b/x/pool-incentives/keeper/params.go index 1ff9ef0bf2c..6cab081375f 100644 --- a/x/pool-incentives/keeper/params.go +++ b/x/pool-incentives/keeper/params.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { diff --git a/x/pool-incentives/module.go b/x/pool-incentives/module.go index c1b849a964f..29f6ddac163 100644 --- a/x/pool-incentives/module.go +++ b/x/pool-incentives/module.go @@ -19,9 +19,9 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/simulation" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/keeper" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/keeper" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) var ( diff --git a/x/pool-incentives/types/expected_keepers.go b/x/pool-incentives/types/expected_keepers.go index ffdf807a0bc..df25e7215d1 100644 --- a/x/pool-incentives/types/expected_keepers.go +++ b/x/pool-incentives/types/expected_keepers.go @@ -7,9 +7,9 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) type AccountKeeper interface { diff --git a/x/pool-incentives/types/genesis.pb.go b/x/pool-incentives/types/genesis.pb.go index 8eac2a3e833..41190f66231 100644 --- a/x/pool-incentives/types/genesis.pb.go +++ b/x/pool-incentives/types/genesis.pb.go @@ -101,26 +101,26 @@ var fileDescriptor_cc1f078212600632 = []byte{ // 351 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x91, 0xcf, 0x4e, 0xfa, 0x40, 0x10, 0xc7, 0xbb, 0xf0, 0x0b, 0xc9, 0xaf, 0x78, 0xa1, 0xf1, 0x00, 0x1c, 0xb6, 0xa4, 0x89, 0x06, - 0x0f, 0xec, 0x0a, 0x1e, 0x4c, 0x38, 0x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 0xd6, 0x3a, 0x36, + 0xd1, 0x2e, 0x36, 0x1b, 0xf9, 0xe2, 0xfd, 0x28, 0x6b, 0xf2, 0x7f, 0xf6, 0x43, 0x3d, 0xac, 0xb7, + 0x18, 0x6d, 0xb6, 0x18, 0x7d, 0x6d, 0x31, 0x7a, 0x4d, 0xb0, 0xb6, 0x49, 0xb0, 0xf6, 0x91, 0x60, + 0xed, 0xf1, 0xda, 0x15, 0xea, 0x69, 0x61, 0x13, 0x07, 0x7c, 0x5a, 0x2c, 0xed, 0x79, 0xcc, 0x96, + 0x65, 0x41, 0x97, 0x83, 0x3e, 0x7d, 0x39, 0x78, 0x16, 0xb5, 0x0a, 0xb9, 0xb4, 0x6b, 0xd9, 0x8f, + 0xb8, 0xfc, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x73, 0x02, 0xfa, 0x34, 0x43, 0x02, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { diff --git a/x/pool-incentives/types/genesis_test.go b/x/pool-incentives/types/genesis_test.go index a97248f50fc..e0d53904c8e 100644 --- a/x/pool-incentives/types/genesis_test.go +++ b/x/pool-incentives/types/genesis_test.go @@ -5,7 +5,7 @@ import ( "time" proto "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/pool-incentives/types/gov.pb.go b/x/pool-incentives/types/gov.pb.go index 9674aeeee1e..c68123a16c8 100644 --- a/x/pool-incentives/types/gov.pb.go +++ b/x/pool-incentives/types/gov.pb.go @@ -123,7 +123,7 @@ func init() { } var fileDescriptor_96caede426ba9516 = []byte{ - // 302 bytes of a gzipped FileDescriptorProto + // 303 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0xcc, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0xc8, 0xcf, 0xcf, 0xd1, 0xcd, 0xcc, 0x4b, 0x4e, 0xcd, 0x2b, 0xc9, 0x2c, 0x4b, 0x2d, 0xd6, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0xcf, 0x2f, 0xd3, @@ -137,12 +137,12 @@ var fileDescriptor_96caede426ba9516 = []byte{ 0x2f, 0x4a, 0x29, 0x96, 0x60, 0x56, 0x60, 0xd6, 0xe0, 0x36, 0xd2, 0xd6, 0xc3, 0xef, 0x27, 0x3d, 0x97, 0xcc, 0xe2, 0x92, 0xa2, 0x20, 0xb0, 0x1e, 0x27, 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, 0x60, 0x26, 0x58, 0xf1, 0x74, 0x2c, 0x90, 0x67, 0x98, 0xb1, 0x40, 0x9e, 0xe1, 0xc5, 0x02, 0x79, 0x46, - 0xa5, 0x8d, 0x8c, 0x5c, 0x32, 0xa1, 0x05, 0x29, 0x89, 0x25, 0x43, 0xc7, 0xcd, 0x4e, 0x21, 0x27, + 0xa5, 0x8d, 0x8c, 0x5c, 0x32, 0xa1, 0x05, 0x29, 0x89, 0x25, 0x43, 0xc7, 0xcd, 0x4e, 0xa1, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, - 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0x65, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, + 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0x65, 0x9d, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x0f, 0xb5, 0x4d, 0x37, 0x27, 0x31, 0xa9, 0x18, 0xc6, 0xd1, 0x2f, - 0x33, 0xd7, 0xaf, 0xc0, 0x88, 0xd1, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, 0x70, 0x2c, 0x1a, - 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x51, 0xf7, 0x55, 0x7d, 0x5a, 0x02, 0x00, 0x00, + 0x33, 0x34, 0xd0, 0xaf, 0xc0, 0x88, 0xd2, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, 0x70, 0x34, + 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x6c, 0x07, 0xb6, 0xec, 0x5b, 0x02, 0x00, 0x00, } func (this *ReplacePoolIncentivesProposal) Equal(that interface{}) bool { diff --git a/x/pool-incentives/types/gov_test.go b/x/pool-incentives/types/gov_test.go index 267c939cf4b..7be521dc659 100644 --- a/x/pool-incentives/types/gov_test.go +++ b/x/pool-incentives/types/gov_test.go @@ -4,7 +4,7 @@ import ( "testing" proto "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/pool-incentives/types/incentives.pb.go b/x/pool-incentives/types/incentives.pb.go index d58272fdcac..10611062f02 100644 --- a/x/pool-incentives/types/incentives.pb.go +++ b/x/pool-incentives/types/incentives.pb.go @@ -221,37 +221,37 @@ func init() { } var fileDescriptor_a8153bad03e553d1 = []byte{ - // 465 bytes of a gzipped FileDescriptorProto + // 466 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x52, 0x41, 0x6b, 0xd4, 0x40, 0x18, 0xcd, 0xd4, 0x65, 0x6b, 0x67, 0x0b, 0x62, 0xaa, 0xb8, 0xed, 0x21, 0x29, 0x01, 0xa5, 0x20, - 0x3b, 0x63, 0xf5, 0x20, 0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, + 0xbf, 0xa5, 0xdb, 0x3d, 0x25, 0xff, 0x5f, 0x1b, 0xd1, 0x29, 0x03, 0xad, 0xf1, 0x3b, 0x55, 0xa2, + 0xa0, 0x71, 0xf0, 0xbe, 0x22, 0xdc, 0x6b, 0xd1, 0x36, 0xc1, 0x77, 0x13, 0xb6, 0x48, 0xf8, 0x54, + 0xc4, 0xba, 0x42, 0xc7, 0xdf, 0xdb, 0x94, 0xee, 0xbd, 0x3a, 0x54, 0xc3, 0x78, 0xc1, 0xb6, 0x3e, + 0x4e, 0x62, 0xfb, 0x15, 0xee, 0x9a, 0xc2, 0x5b, 0xba, 0x30, 0xb9, 0x5d, 0xe1, 0xc0, 0xa8, 0x47, + 0x9d, 0x3f, 0x17, 0x2e, 0xf2, 0xdf, 0x5f, 0xae, 0x1c, 0x74, 0xb5, 0x72, 0xd0, 0xef, 0x95, 0x83, + 0xbe, 0xad, 0x1d, 0xeb, 0x6a, 0xed, 0x58, 0x3f, 0xd6, 0x8e, 0xf5, 0xf1, 0x45, 0xcb, 0xcf, 0xb4, + 0x1d, 0xa4, 0x2c, 0x94, 0x0d, 0xa0, 0xcb, 0xe1, 0x31, 0xfd, 0x7c, 0xe3, 0x4f, 0xd7, 0x83, 0xc2, + 0xae, 0x5e, 0xfb, 0xf3, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xa6, 0x78, 0x74, 0x71, 0x11, 0x03, + 0x00, 0x00, } func (this *DistrRecord) Equal(that interface{}) bool { diff --git a/x/pool-incentives/types/incentives_test.go b/x/pool-incentives/types/incentives_test.go index b5abe93790d..7bf3044d84a 100644 --- a/x/pool-incentives/types/incentives_test.go +++ b/x/pool-incentives/types/incentives_test.go @@ -5,7 +5,7 @@ import ( "time" proto "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/pool-incentives/types/query.pb.go b/x/pool-incentives/types/query.pb.go index b498ea13ce7..b0b5004c46d 100644 --- a/x/pool-incentives/types/query.pb.go +++ b/x/pool-incentives/types/query.pb.go @@ -11,7 +11,7 @@ import ( proto "github.com/gogo/protobuf/proto" _ "github.com/gogo/protobuf/types" github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" - types1 "github.com/osmosis-labs/osmosis/v7/x/incentives/types" + types1 "github.com/osmosis-labs/osmosis/v10/x/incentives/types" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" @@ -671,62 +671,62 @@ var fileDescriptor_302873ecccbc7636 = []byte{ // 923 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0x41, 0x6f, 0x1b, 0x45, 0x14, 0xce, 0x34, 0x21, 0x4d, 0x26, 0x12, 0xd4, 0x93, 0x40, 0x9c, 0x15, 0xac, 0xc3, 0xd0, 0x42, - 0xaa, 0x28, 0xbb, 0xad, 0xdd, 0x16, 0x29, 0x04, 0x90, 0xdc, 0x20, 0x14, 0x89, 0x43, 0x58, 0x21, - 0x21, 0xc1, 0xc1, 0x5a, 0x7b, 0x27, 0x9b, 0x11, 0xeb, 0x1d, 0xd7, 0xb3, 0x0e, 0x0d, 0xa8, 0x97, + 0xaa, 0x28, 0xbb, 0x89, 0xdd, 0xf6, 0xd0, 0x06, 0x90, 0xdc, 0x20, 0x14, 0x89, 0x43, 0x58, 0x09, + 0x21, 0xc1, 0xc1, 0x5a, 0x67, 0x27, 0x9b, 0x11, 0xeb, 0x1d, 0xd7, 0xb3, 0x0e, 0x0d, 0xa8, 0x97, 0x4a, 0xdc, 0x41, 0x5c, 0x38, 0x23, 0x7a, 0xe6, 0xc4, 0x3f, 0xe0, 0xd0, 0x1b, 0x95, 0xb8, 0x70, - 0xc1, 0xa0, 0x84, 0x03, 0x67, 0xff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xe0, 0xf3, 0xe8, + 0xb8, 0xdb, 0xb4, 0x0e, 0x45, 0x4b, 0xe3, 0x6f, 0x05, 0x6e, 0x53, 0xa6, 0xcd, 0x4e, 0x76, 0xb6, + 0xed, 0xc7, 0xb9, 0x96, 0xd1, 0x69, 0x9b, 0xc9, 0xe6, 0xbc, 0xfa, 0x95, 0xaa, 0xfd, 0x17, 0x00, + 0x00, 0xff, 0xff, 0xd0, 0x94, 0x3e, 0x10, 0xb4, 0x0b, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/pool-incentives/types/query_test.go b/x/pool-incentives/types/query_test.go index 4de277cf43c..aef8101cc3b 100644 --- a/x/pool-incentives/types/query_test.go +++ b/x/pool-incentives/types/query_test.go @@ -5,7 +5,7 @@ import ( "time" proto "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" "github.com/stretchr/testify/require" ) diff --git a/x/pool-incentives/types/record_test.go b/x/pool-incentives/types/record_test.go index a49cb927e1c..bc1af2c5615 100644 --- a/x/pool-incentives/types/record_test.go +++ b/x/pool-incentives/types/record_test.go @@ -7,7 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/pool-incentives/types" + "github.com/osmosis-labs/osmosis/v10/x/pool-incentives/types" ) func TestDistrRecord(t *testing.T) { diff --git a/x/superfluid/abci.go b/x/superfluid/abci.go index 04e246c7eb8..af8f538df7a 100644 --- a/x/superfluid/abci.go +++ b/x/superfluid/abci.go @@ -1,8 +1,8 @@ package superfluid import ( - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/client/cli/query.go b/x/superfluid/client/cli/query.go index e120cb6bf59..4e21adaca70 100644 --- a/x/superfluid/client/cli/query.go +++ b/x/superfluid/client/cli/query.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/superfluid/client/cli/tx.go b/x/superfluid/client/cli/tx.go index 23771849537..0e5017dd3b6 100644 --- a/x/superfluid/client/cli/tx.go +++ b/x/superfluid/client/cli/tx.go @@ -5,7 +5,7 @@ import ( "strconv" "strings" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" diff --git a/x/superfluid/client/proposal_handler.go b/x/superfluid/client/proposal_handler.go index e6e306acd74..4100f550391 100644 --- a/x/superfluid/client/proposal_handler.go +++ b/x/superfluid/client/proposal_handler.go @@ -1,8 +1,8 @@ package client import ( - "github.com/osmosis-labs/osmosis/v7/x/superfluid/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/client/rest" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/client/rest" govclient "github.com/cosmos/cosmos-sdk/x/gov/client" ) diff --git a/x/superfluid/keeper/distribution_test.go b/x/superfluid/keeper/distribution_test.go index 1e77f51c8ed..3ff4cf71375 100644 --- a/x/superfluid/keeper/distribution_test.go +++ b/x/superfluid/keeper/distribution_test.go @@ -1,8 +1,8 @@ package keeper_test import ( - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" diff --git a/x/superfluid/keeper/edge_case_test.go b/x/superfluid/keeper/edge_case_test.go index a03a17883f3..28e897f5540 100644 --- a/x/superfluid/keeper/edge_case_test.go +++ b/x/superfluid/keeper/edge_case_test.go @@ -7,7 +7,7 @@ import ( evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) func (suite *KeeperTestSuite) TestSuperfluidDelegatedValidatorJailed() { diff --git a/x/superfluid/keeper/epoch.go b/x/superfluid/keeper/epoch.go index a1146131c63..47e7023c76f 100644 --- a/x/superfluid/keeper/epoch.go +++ b/x/superfluid/keeper/epoch.go @@ -7,11 +7,11 @@ import ( distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, _ int64) { diff --git a/x/superfluid/keeper/genesis.go b/x/superfluid/keeper/genesis.go index 0bc8427ed8e..1a016b69360 100644 --- a/x/superfluid/keeper/genesis.go +++ b/x/superfluid/keeper/genesis.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) // InitGenesis initializes the capability module's state from a provided genesis diff --git a/x/superfluid/keeper/genesis_test.go b/x/superfluid/keeper/genesis_test.go index dde164a99a8..08f42a054c0 100644 --- a/x/superfluid/keeper/genesis_test.go +++ b/x/superfluid/keeper/genesis_test.go @@ -8,9 +8,9 @@ import ( "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - simapp "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/superfluid" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + simapp "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/superfluid" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/keeper/gov/gov.go b/x/superfluid/keeper/gov/gov.go index 9a2f6f12717..1799e6197f2 100644 --- a/x/superfluid/keeper/gov/gov.go +++ b/x/superfluid/keeper/gov/gov.go @@ -3,8 +3,8 @@ package gov import ( "fmt" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/keeper/gov/gov_test.go b/x/superfluid/keeper/gov/gov_test.go index 90f88eaf9ce..38022941ea1 100644 --- a/x/superfluid/keeper/gov/gov_test.go +++ b/x/superfluid/keeper/gov/gov_test.go @@ -7,10 +7,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper/gov" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + minttypes "github.com/osmosis-labs/osmosis/v10/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper/gov" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) func (suite *KeeperTestSuite) createGammPool(denoms []string) uint64 { diff --git a/x/superfluid/keeper/gov/suite_test.go b/x/superfluid/keeper/gov/suite_test.go index f9946e68a42..efd571759f2 100644 --- a/x/superfluid/keeper/gov/suite_test.go +++ b/x/superfluid/keeper/gov/suite_test.go @@ -9,8 +9,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/app" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" ) type KeeperTestSuite struct { diff --git a/x/superfluid/keeper/grpc_query.go b/x/superfluid/keeper/grpc_query.go index 117b3741441..845878bd6a8 100644 --- a/x/superfluid/keeper/grpc_query.go +++ b/x/superfluid/keeper/grpc_query.go @@ -11,10 +11,10 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - appparams "github.com/osmosis-labs/osmosis/v7/app/params" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) var _ types.QueryServer = Querier{} diff --git a/x/superfluid/keeper/grpc_query_test.go b/x/superfluid/keeper/grpc_query_test.go index cd9f6aabe5a..75de6d3fe31 100644 --- a/x/superfluid/keeper/grpc_query_test.go +++ b/x/superfluid/keeper/grpc_query_test.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) func (suite *KeeperTestSuite) TestGRPCParams() { diff --git a/x/superfluid/keeper/hooks.go b/x/superfluid/keeper/hooks.go index 6848da25228..7310854aab0 100644 --- a/x/superfluid/keeper/hooks.go +++ b/x/superfluid/keeper/hooks.go @@ -4,8 +4,8 @@ import ( "fmt" "time" - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/keeper/intermediary_account.go b/x/superfluid/keeper/intermediary_account.go index f859fb6d344..4c7a770063d 100644 --- a/x/superfluid/keeper/intermediary_account.go +++ b/x/superfluid/keeper/intermediary_account.go @@ -2,8 +2,8 @@ package keeper import ( "github.com/gogo/protobuf/proto" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/superfluid/keeper/intermediary_account_test.go b/x/superfluid/keeper/intermediary_account_test.go index 29cbe67a3c0..32c96a87b2c 100644 --- a/x/superfluid/keeper/intermediary_account_test.go +++ b/x/superfluid/keeper/intermediary_account_test.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) func (suite *KeeperTestSuite) TestIntermediaryAccountCreation() { diff --git a/x/superfluid/keeper/invariants.go b/x/superfluid/keeper/invariants.go index 52ff07e4162..c4ffa289729 100644 --- a/x/superfluid/keeper/invariants.go +++ b/x/superfluid/keeper/invariants.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) const totalSuperfluidDelegationInvariantName = "total-superfluid-delegation-invariant-name" diff --git a/x/superfluid/keeper/keeper.go b/x/superfluid/keeper/keeper.go index 0dfc0a84fa8..a54027fd148 100644 --- a/x/superfluid/keeper/keeper.go +++ b/x/superfluid/keeper/keeper.go @@ -5,7 +5,7 @@ import ( "github.com/tendermint/tendermint/libs/log" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/superfluid/keeper/keeper_test.go b/x/superfluid/keeper/keeper_test.go index fa5a73d1fc8..03a8244cada 100644 --- a/x/superfluid/keeper/keeper_test.go +++ b/x/superfluid/keeper/keeper_test.go @@ -10,14 +10,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - epochtypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - minttypes "github.com/osmosis-labs/osmosis/v7/x/mint/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + epochtypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + minttypes "github.com/osmosis-labs/osmosis/v10/x/mint/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) type KeeperTestSuite struct { diff --git a/x/superfluid/keeper/msg_server.go b/x/superfluid/keeper/msg_server.go index 63d64c53286..514541539a2 100644 --- a/x/superfluid/keeper/msg_server.go +++ b/x/superfluid/keeper/msg_server.go @@ -9,11 +9,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - v8constants "github.com/osmosis-labs/osmosis/v7/app/upgrades/v8/constants" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + v8constants "github.com/osmosis-labs/osmosis/v10/app/upgrades/v8/constants" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) type msgServer struct { diff --git a/x/superfluid/keeper/msg_server_test.go b/x/superfluid/keeper/msg_server_test.go index 9075204317b..bdfbfa4ba92 100644 --- a/x/superfluid/keeper/msg_server_test.go +++ b/x/superfluid/keeper/msg_server_test.go @@ -6,10 +6,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - lockupkeeper "github.com/osmosis-labs/osmosis/v7/x/lockup/keeper" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + lockupkeeper "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) func (suite *KeeperTestSuite) TestMsgSuperfluidDelegate() { diff --git a/x/superfluid/keeper/params.go b/x/superfluid/keeper/params.go index 4b79f4d1d74..f53ef272d4c 100644 --- a/x/superfluid/keeper/params.go +++ b/x/superfluid/keeper/params.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/keeper/slash.go b/x/superfluid/keeper/slash.go index 35a04049e4f..a8490348a0c 100644 --- a/x/superfluid/keeper/slash.go +++ b/x/superfluid/keeper/slash.go @@ -3,8 +3,8 @@ package keeper import ( "time" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/keeper/slash_test.go b/x/superfluid/keeper/slash_test.go index bbe302047a1..aebf7f7682a 100644 --- a/x/superfluid/keeper/slash_test.go +++ b/x/superfluid/keeper/slash_test.go @@ -1,8 +1,8 @@ package keeper_test import ( - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" diff --git a/x/superfluid/keeper/stake.go b/x/superfluid/keeper/stake.go index 1cf129f9d29..ef8cd53b7e9 100644 --- a/x/superfluid/keeper/stake.go +++ b/x/superfluid/keeper/stake.go @@ -3,9 +3,9 @@ package keeper import ( "fmt" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" diff --git a/x/superfluid/keeper/stake_test.go b/x/superfluid/keeper/stake_test.go index f72ce71624f..ad1b52b6fac 100644 --- a/x/superfluid/keeper/stake_test.go +++ b/x/superfluid/keeper/stake_test.go @@ -5,9 +5,9 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" diff --git a/x/superfluid/keeper/superfluid_asset.go b/x/superfluid/keeper/superfluid_asset.go index d0d263b0a85..de2b6afce86 100644 --- a/x/superfluid/keeper/superfluid_asset.go +++ b/x/superfluid/keeper/superfluid_asset.go @@ -1,8 +1,8 @@ package keeper import ( - "github.com/osmosis-labs/osmosis/v7/osmoutils" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/keeper/superfluid_asset_store.go b/x/superfluid/keeper/superfluid_asset_store.go index 41d6cf47546..7fd3a0d9fba 100644 --- a/x/superfluid/keeper/superfluid_asset_store.go +++ b/x/superfluid/keeper/superfluid_asset_store.go @@ -4,7 +4,7 @@ package keeper import ( "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/superfluid/keeper/superfluid_asset_test.go b/x/superfluid/keeper/superfluid_asset_test.go index 34410196c31..2abd131f1bc 100644 --- a/x/superfluid/keeper/superfluid_asset_test.go +++ b/x/superfluid/keeper/superfluid_asset_test.go @@ -1,7 +1,7 @@ package keeper_test import ( - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/keeper/synthetic_lock_wrapper.go b/x/superfluid/keeper/synthetic_lock_wrapper.go index 4d99ca38661..b67dce964fd 100644 --- a/x/superfluid/keeper/synthetic_lock_wrapper.go +++ b/x/superfluid/keeper/synthetic_lock_wrapper.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/keeper/twap_price.go b/x/superfluid/keeper/twap_price.go index cdeb09b8f08..f16466a7861 100644 --- a/x/superfluid/keeper/twap_price.go +++ b/x/superfluid/keeper/twap_price.go @@ -2,8 +2,8 @@ package keeper import ( "github.com/gogo/protobuf/proto" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/superfluid/keeper/twap_price_test.go b/x/superfluid/keeper/twap_price_test.go index b5c6bf81f7a..2bb60643015 100644 --- a/x/superfluid/keeper/twap_price_test.go +++ b/x/superfluid/keeper/twap_price_test.go @@ -1,7 +1,7 @@ package keeper_test import ( - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/superfluid/keeper/unpool.go b/x/superfluid/keeper/unpool.go index 412916b58c3..68a5cdb2522 100644 --- a/x/superfluid/keeper/unpool.go +++ b/x/superfluid/keeper/unpool.go @@ -5,10 +5,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) // Returns a list of newly created lockIDs, or an error. diff --git a/x/superfluid/keeper/unpool_test.go b/x/superfluid/keeper/unpool_test.go index a919f5bc52b..f0a8300a023 100644 --- a/x/superfluid/keeper/unpool_test.go +++ b/x/superfluid/keeper/unpool_test.go @@ -8,10 +8,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/osmosis-labs/osmosis/v7/x/gamm/pool-models/balancer" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) var ( diff --git a/x/superfluid/module.go b/x/superfluid/module.go index 54ae2b9373c..5dceac95650 100644 --- a/x/superfluid/module.go +++ b/x/superfluid/module.go @@ -19,11 +19,11 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/osmosis-labs/osmosis/v7/x/mint/client/rest" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/simulation" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/mint/client/rest" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/simulation" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) var ( diff --git a/x/superfluid/proposal_handler.go b/x/superfluid/proposal_handler.go index 1c383becf0c..1aa75470e3d 100644 --- a/x/superfluid/proposal_handler.go +++ b/x/superfluid/proposal_handler.go @@ -5,9 +5,9 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper/gov" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper/gov" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) func NewSuperfluidProposalHandler(k keeper.Keeper, ek types.EpochKeeper) govtypes.Handler { diff --git a/x/superfluid/simulation/genesis.go b/x/superfluid/simulation/genesis.go index 8dae576a113..c0ae52e0c6c 100644 --- a/x/superfluid/simulation/genesis.go +++ b/x/superfluid/simulation/genesis.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" diff --git a/x/superfluid/simulation/operations.go b/x/superfluid/simulation/operations.go index 1061a688bb8..b363776dcec 100644 --- a/x/superfluid/simulation/operations.go +++ b/x/superfluid/simulation/operations.go @@ -3,13 +3,13 @@ package simulation import ( "math/rand" - osmo_simulation "github.com/osmosis-labs/osmosis/v7/simulation/types" + osmo_simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" "github.com/cosmos/cosmos-sdk/baseapp" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" "github.com/cosmos/cosmos-sdk/codec" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" diff --git a/x/superfluid/simulation/proposals.go b/x/superfluid/simulation/proposals.go index eecb67e3cc3..fc11740a3dd 100644 --- a/x/superfluid/simulation/proposals.go +++ b/x/superfluid/simulation/proposals.go @@ -7,9 +7,9 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/keeper" - "github.com/osmosis-labs/osmosis/v7/x/superfluid/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/keeper" + "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" ) const ( diff --git a/x/superfluid/types/expected_keepers.go b/x/superfluid/types/expected_keepers.go index 4baf773e6df..5f919d5a295 100644 --- a/x/superfluid/types/expected_keepers.go +++ b/x/superfluid/types/expected_keepers.go @@ -7,10 +7,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - incentivestypes "github.com/osmosis-labs/osmosis/v7/x/incentives/types" - lockuptypes "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) // LockupKeeper defines the expected interface needed to retrieve locks. diff --git a/x/superfluid/types/genesis.pb.go b/x/superfluid/types/genesis.pb.go index adbf10eed44..40d5532774e 100644 --- a/x/superfluid/types/genesis.pb.go +++ b/x/superfluid/types/genesis.pb.go @@ -113,31 +113,31 @@ func init() { func init() { proto.RegisterFile("osmosis/superfluid/genesis.proto", fileDescriptor_d5256ebb7c83fff3) } var fileDescriptor_d5256ebb7c83fff3 = []byte{ - // 384 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x41, 0x4f, 0xe2, 0x50, - 0x10, 0xc7, 0xdb, 0x85, 0xe5, 0x50, 0xf6, 0xb0, 0xdb, 0xb0, 0x49, 0xc5, 0x58, 0x88, 0x5c, 0xb8, - 0xd8, 0x46, 0x8c, 0xc1, 0x2b, 0x18, 0x63, 0x48, 0x34, 0x18, 0x48, 0x3c, 0x78, 0x69, 0x1e, 0xe5, - 0x59, 0x5f, 0x6c, 0x3b, 0xb5, 0xf3, 0x4a, 0xe0, 0x03, 0x78, 0xe7, 0x63, 0x71, 0xe4, 0xe8, 0xc9, - 0x18, 0xf8, 0x22, 0xa6, 0xed, 0xb3, 0xa0, 0x54, 0x6f, 0xd3, 0xce, 0xef, 0x3f, 0xbf, 0x79, 0xc9, - 0x28, 0x75, 0x40, 0x0f, 0x90, 0xa1, 0x89, 0x51, 0x40, 0xc3, 0x7b, 0x37, 0x62, 0x63, 0xd3, 0xa1, - 0x3e, 0x45, 0x86, 0x46, 0x10, 0x02, 0x07, 0x55, 0x15, 0x84, 0xb1, 0x21, 0xaa, 0x15, 0x07, 0x1c, - 0x48, 0xda, 0x66, 0x5c, 0xa5, 0x64, 0xb5, 0x91, 0x33, 0x6b, 0x53, 0x0a, 0xa8, 0x96, 0x03, 0x05, - 0x24, 0x24, 0x9e, 0xf0, 0x1d, 0xce, 0x8b, 0xca, 0x9f, 0xcb, 0x74, 0x83, 0x21, 0x27, 0x9c, 0xaa, - 0x67, 0x4a, 0x29, 0x05, 0x34, 0xb9, 0x2e, 0x37, 0xcb, 0xad, 0xaa, 0xb1, 0xbb, 0x91, 0x71, 0x93, - 0x10, 0xdd, 0xe2, 0xe2, 0xb5, 0x26, 0x0d, 0x04, 0xaf, 0xde, 0x2a, 0xff, 0x36, 0x88, 0x45, 0x10, - 0x29, 0x47, 0xed, 0x57, 0xbd, 0xd0, 0x2c, 0xb7, 0x1a, 0x79, 0x43, 0x86, 0x59, 0xd9, 0x89, 0x59, - 0x31, 0xed, 0x2f, 0x7e, 0xfe, 0x8d, 0xea, 0x54, 0xd9, 0x8f, 0xd3, 0x16, 0x7d, 0x8a, 0xd8, 0x84, - 0xb8, 0xd4, 0xe7, 0x96, 0x17, 0xb9, 0x9c, 0x05, 0x2e, 0xa3, 0x21, 0x6a, 0x85, 0xc4, 0xd0, 0xca, - 0x33, 0xf4, 0xd1, 0x83, 0x8b, 0x2c, 0x75, 0x9d, 0x85, 0x06, 0xd4, 0x86, 0x70, 0x2c, 0x84, 0x7b, - 0xf0, 0x0d, 0x85, 0xaa, 0xab, 0xfc, 0x67, 0x3e, 0xa7, 0xa1, 0x47, 0xc7, 0x8c, 0x84, 0x33, 0x8b, - 0xd8, 0x36, 0x44, 0x3e, 0x47, 0xad, 0x98, 0x38, 0x8f, 0x7f, 0x7e, 0x55, 0x6f, 0x2b, 0xda, 0x49, - 0x93, 0x42, 0x59, 0x61, 0xbb, 0x2d, 0x54, 0x9f, 0x65, 0xa5, 0x16, 0x37, 0xbe, 0xd8, 0x2c, 0x1b, - 0x7c, 0x9f, 0xda, 0x9c, 0x81, 0x8f, 0xda, 0xef, 0x44, 0xdc, 0xce, 0x13, 0x5f, 0x81, 0xfd, 0xd8, - 0xcb, 0x93, 0x9e, 0x67, 0x79, 0xa1, 0x3f, 0xd8, 0xb2, 0xec, 0x30, 0xd8, 0xed, 0x2f, 0x56, 0xba, - 0xbc, 0x5c, 0xe9, 0xf2, 0xdb, 0x4a, 0x97, 0xe7, 0x6b, 0x5d, 0x5a, 0xae, 0x75, 0xe9, 0x65, 0xad, - 0x4b, 0x77, 0xa7, 0x0e, 0xe3, 0x0f, 0xd1, 0xc8, 0xb0, 0xc1, 0x33, 0xc5, 0x06, 0x47, 0x2e, 0x19, - 0xe1, 0xc7, 0x87, 0x39, 0x69, 0x9b, 0xd3, 0xed, 0x53, 0xe3, 0xb3, 0x80, 0xe2, 0xa8, 0x94, 0x9c, - 0xda, 0xc9, 0x7b, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7e, 0x30, 0xda, 0x43, 0xfe, 0x02, 0x00, 0x00, + // 382 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x31, 0x4f, 0xc2, 0x40, + 0x14, 0xc7, 0x5b, 0x41, 0x86, 0xe2, 0xa0, 0x0d, 0x26, 0x15, 0x63, 0x21, 0xb2, 0xb0, 0xd8, 0x0a, + 0x26, 0xea, 0x0a, 0xc6, 0x18, 0x12, 0x8d, 0x04, 0x12, 0x07, 0x97, 0xe6, 0x28, 0x67, 0xbd, 0xd8, + 0xf6, 0xea, 0xbd, 0x2b, 0x81, 0x0f, 0xe0, 0xce, 0xc7, 0x62, 0x64, 0x74, 0x32, 0x06, 0xbe, 0x88, + 0x69, 0x7b, 0x16, 0x94, 0xea, 0xf6, 0xda, 0xf7, 0xfb, 0xbf, 0xdf, 0xbb, 0xe4, 0x29, 0x55, 0x0a, + 0x1e, 0x05, 0x02, 0x26, 0x84, 0x01, 0x66, 0x4f, 0x6e, 0x48, 0x86, 0xa6, 0x83, 0x7d, 0x0c, 0x04, + 0x8c, 0x80, 0x51, 0x4e, 0x55, 0x55, 0x10, 0xc6, 0x8a, 0x28, 0x97, 0x1c, 0xea, 0xd0, 0xb8, 0x6d, + 0x46, 0x55, 0x42, 0x96, 0x6b, 0x19, 0xb3, 0x56, 0xa5, 0x80, 0x2a, 0x19, 0x50, 0x80, 0x18, 0xf2, + 0x84, 0xef, 0x78, 0x9a, 0x57, 0x76, 0x6e, 0x92, 0x0d, 0xfa, 0x1c, 0x71, 0xac, 0x5e, 0x2a, 0x85, + 0x04, 0xd0, 0xe4, 0xaa, 0x5c, 0x2f, 0x36, 0xcb, 0xc6, 0xe6, 0x46, 0x46, 0x37, 0x26, 0xda, 0xf9, + 0xd9, 0x47, 0x45, 0xea, 0x09, 0x5e, 0x7d, 0x50, 0xf6, 0x56, 0x88, 0x85, 0x00, 0x30, 0x07, 0x6d, + 0xab, 0x9a, 0xab, 0x17, 0x9b, 0xb5, 0xac, 0x21, 0xfd, 0xb4, 0x6c, 0x45, 0xac, 0x98, 0xb6, 0x0b, + 0x3f, 0x7f, 0x83, 0x3a, 0x56, 0x0e, 0xa3, 0xb4, 0x85, 0x5f, 0x43, 0x32, 0x42, 0x2e, 0xf6, 0xb9, + 0xe5, 0x85, 0x2e, 0x27, 0x81, 0x4b, 0x30, 0x03, 0x2d, 0x17, 0x1b, 0x9a, 0x59, 0x86, 0x7b, 0xf0, + 0xe8, 0x75, 0x9a, 0xba, 0x4b, 0x43, 0x3d, 0x6c, 0x53, 0x36, 0x14, 0xc2, 0x03, 0xfa, 0x07, 0x05, + 0xaa, 0xab, 0xec, 0x13, 0x9f, 0x63, 0xe6, 0xe1, 0x21, 0x41, 0x6c, 0x62, 0x21, 0xdb, 0xa6, 0xa1, + 0xcf, 0x41, 0xcb, 0xc7, 0xce, 0xc6, 0xff, 0xaf, 0xea, 0xac, 0x45, 0x5b, 0x49, 0x52, 0x28, 0x4b, + 0x64, 0xb3, 0x05, 0xea, 0x9b, 0xac, 0x54, 0xa2, 0xc6, 0x2f, 0x9b, 0x65, 0x53, 0xdf, 0xc7, 0x36, + 0x27, 0xd4, 0x07, 0x6d, 0x3b, 0x16, 0x5f, 0x64, 0x89, 0x6f, 0xa9, 0xfd, 0xd2, 0xc9, 0x92, 0x5e, + 0xa5, 0x79, 0xa1, 0x3f, 0x5a, 0xb3, 0x6c, 0x30, 0xd0, 0xee, 0xce, 0x16, 0xba, 0x3c, 0x5f, 0xe8, + 0xf2, 0xe7, 0x42, 0x97, 0xa7, 0x4b, 0x5d, 0x9a, 0x2f, 0x75, 0xe9, 0x7d, 0xa9, 0x4b, 0x8f, 0xe7, + 0x0e, 0xe1, 0xcf, 0xe1, 0xc0, 0xb0, 0xa9, 0x67, 0x8a, 0x0d, 0x4e, 0x5c, 0x34, 0x80, 0xef, 0x0f, + 0x73, 0xd4, 0x38, 0x35, 0xc7, 0xeb, 0xb7, 0xc6, 0x27, 0x01, 0x86, 0x41, 0x21, 0xbe, 0xb5, 0xb3, + 0xaf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x05, 0x7b, 0x37, 0x83, 0xff, 0x02, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { diff --git a/x/superfluid/types/gov.go b/x/superfluid/types/gov.go index 8f93b45cade..3f7ae19b68e 100644 --- a/x/superfluid/types/gov.go +++ b/x/superfluid/types/gov.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) diff --git a/x/superfluid/types/gov.pb.go b/x/superfluid/types/gov.pb.go index d9fda1d2177..f6ec16f0d3f 100644 --- a/x/superfluid/types/gov.pb.go +++ b/x/superfluid/types/gov.pb.go @@ -113,7 +113,7 @@ func init() { } var fileDescriptor_2e37d6a8d0e42294 = []byte{ - // 311 bytes of a gzipped FileDescriptorProto + // 312 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc9, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0x2e, 0x2d, 0x48, 0x2d, 0x4a, 0xcb, 0x29, 0xcd, 0x4c, 0xd1, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0xcf, 0x2f, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, @@ -128,12 +128,12 @@ var fileDescriptor_2e37d6a8d0e42294 = []byte{ 0x58, 0x20, 0xcf, 0x30, 0x63, 0x81, 0x3c, 0xc3, 0x8b, 0x05, 0xf2, 0x8c, 0x4a, 0xf3, 0x18, 0xb9, 0xe4, 0x82, 0x52, 0x73, 0xf3, 0xcb, 0x52, 0xa9, 0xee, 0x56, 0x33, 0x2e, 0x71, 0x84, 0xa3, 0xe2, 0xc1, 0xb6, 0xc7, 0xa7, 0xa4, 0xe6, 0xe5, 0xe7, 0x42, 0x1c, 0xcf, 0x19, 0x24, 0x5a, 0x8c, 0x6a, - 0xa5, 0x0b, 0x58, 0x12, 0xd5, 0x81, 0x4e, 0xfe, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, + 0xa5, 0x0b, 0x58, 0x12, 0xd5, 0x81, 0x4e, 0x01, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, - 0xc7, 0x10, 0x65, 0x9a, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x0f, 0x0d, - 0x05, 0xdd, 0x9c, 0xc4, 0xa4, 0x62, 0x18, 0x47, 0xbf, 0xcc, 0x5c, 0xbf, 0x02, 0x39, 0x96, 0x4a, - 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0x31, 0x64, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xd0, - 0x71, 0x2d, 0x41, 0x20, 0x02, 0x00, 0x00, + 0xc7, 0x10, 0x65, 0x96, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x0f, 0x0d, + 0x05, 0xdd, 0x9c, 0xc4, 0xa4, 0x62, 0x18, 0x47, 0xbf, 0xcc, 0xd0, 0x40, 0xbf, 0x02, 0x39, 0x9a, + 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0x51, 0x64, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, + 0xab, 0x02, 0x5b, 0xb2, 0x21, 0x02, 0x00, 0x00, } func (this *SetSuperfluidAssetsProposal) Equal(that interface{}) bool { diff --git a/x/superfluid/types/params.pb.go b/x/superfluid/types/params.pb.go index 3ae9297731b..e15df3ae152 100644 --- a/x/superfluid/types/params.pb.go +++ b/x/superfluid/types/params.pb.go @@ -74,7 +74,7 @@ func init() { func init() { proto.RegisterFile("osmosis/superfluid/params.proto", fileDescriptor_0985261dfaf2a82e) } var fileDescriptor_0985261dfaf2a82e = []byte{ - // 259 bytes of a gzipped FileDescriptorProto + // 260 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcf, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0x2e, 0x2d, 0x48, 0x2d, 0x4a, 0xcb, 0x29, 0xcd, 0x4c, 0xd1, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x82, 0x2a, 0xd0, @@ -86,12 +86,12 @@ var fileDescriptor_0985261dfaf2a82e = []byte{ 0x7b, 0xf2, 0x0c, 0xb7, 0xee, 0xc9, 0xab, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x27, 0x83, 0x5d, 0x01, 0xa5, 0x74, 0x8b, 0x53, 0xb2, 0xf5, 0x4b, 0x2a, 0x0b, 0x52, 0x8b, 0xf5, 0x5c, 0x52, 0x93, 0x3f, 0xdd, 0x93, 0x97, 0xaa, 0x4c, 0xcc, 0xcd, 0xb1, 0x52, 0xc2, - 0x62, 0xa4, 0x52, 0x90, 0x20, 0x54, 0x34, 0x28, 0xb3, 0x38, 0xdb, 0x0d, 0x2c, 0xe6, 0xe4, 0x7f, + 0x62, 0xa4, 0x52, 0x90, 0x20, 0x54, 0x34, 0x28, 0xb3, 0x38, 0xdb, 0x0d, 0x2c, 0xe6, 0x14, 0x70, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, - 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0xa6, 0x48, 0x56, 0x42, 0xfd, 0xad, - 0x9b, 0x93, 0x98, 0x54, 0x0c, 0xe3, 0xe8, 0x97, 0x99, 0xeb, 0x57, 0x20, 0x07, 0x15, 0xd8, 0x15, - 0x49, 0x6c, 0x60, 0x0f, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x13, 0x35, 0x9c, 0x41, 0x4d, - 0x01, 0x00, 0x00, + 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x66, 0x48, 0x56, 0x42, 0xfd, 0xad, + 0x9b, 0x93, 0x98, 0x54, 0x0c, 0xe3, 0xe8, 0x97, 0x19, 0x1a, 0xe8, 0x57, 0x20, 0x87, 0x15, 0xd8, + 0x19, 0x49, 0x6c, 0x60, 0x1f, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xe5, 0x20, 0x36, 0xb0, + 0x4e, 0x01, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { diff --git a/x/superfluid/types/query.pb.go b/x/superfluid/types/query.pb.go index 197451f98ac..f456fcf1142 100644 --- a/x/superfluid/types/query.pb.go +++ b/x/superfluid/types/query.pb.go @@ -14,7 +14,7 @@ import ( grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" _ "github.com/gogo/protobuf/types" - types1 "github.com/osmosis-labs/osmosis/v7/x/lockup/types" + types1 "github.com/osmosis-labs/osmosis/v10/x/lockup/types" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" @@ -1386,111 +1386,111 @@ func init() { func init() { proto.RegisterFile("osmosis/superfluid/query.proto", fileDescriptor_e3d9448e4ed3943f) } var fileDescriptor_e3d9448e4ed3943f = []byte{ - // 1660 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x59, 0x4b, 0x6c, 0xd4, 0xc6, - 0x1b, 0xcf, 0x24, 0x21, 0x81, 0x0f, 0x09, 0x92,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x85, 0xcf, 0x13, 0xd1, 0x03, - 0xca, 0x15, 0xbd, 0xe4, 0x97, 0x61, 0x21, 0x22, 0x29, 0x7f, 0x8f, 0x60, 0x20, 0xd1, 0x94, 0xc8, - 0xc5, 0x35, 0xd8, 0xaa, 0x8b, 0x77, 0xa2, 0x38, 0x26, 0xd2, 0x8b, 0x23, 0x21, 0x78, 0xa2, 0x5c, - 0x02, 0x65, 0xf8, 0x72, 0x03, 0x88, 0x76, 0x06, 0x62, 0x24, 0x13, 0x04, 0xf7, 0xaa, 0x01, 0xc5, - 0x39, 0x18, 0xbc, 0xe0, 0xd8, 0x36, 0x29, 0xba, 0x24, 0xce, 0xb8, 0x1f, 0xb4, 0x3e, 0xe8, 0xf6, - 0x46, 0x8b, 0x97, 0x0a, 0xc4, 0x52, 0xd1, 0xe5, 0x3d, 0xce, 0x18, 0xf2, 0xfb, 0x30, 0x94, 0x2e, - 0x2f, 0x22, 0x31, 0x0f, 0xdd, 0xc2, 0x79, 0x11, 0xf2, 0xcd, 0x05, 0xa2, 0xe0, 0x6b, 0x91, 0x07, - 0xe1, 0xd0, 0x82, 0xe3, 0xea, 0x56, 0x28, 0x32, 0x4d, 0x2c, 0x52, 0xe2, 0x43, 0xda, 0xef, 0xd7, - 0xfb, 0x08, 0xe4, 0x34, 0x2e, 0xe1, 0xdc, 0x1d, 0x04, 0xbd, 0xae, 0xc7, 0xa6, 0x19, 0x21, 0x95, - 0xd7, 0xe9, 0xd4, 0xa2, 0x17, 0xf9, 0x5f, 0x1e, 0x0d, 0x0c, 0x97, 0x4c, 0xf7, 0x46, 0x6d, 0x59, - 0x29, 0x3a, 0x65, 0x55, 0x4c, 0x4b, 0xfe, 0xe7, 0x18, 0x35, 0x56, 0x54, 0x6f, 0xd6, 0x50, 0x65, - 0xc6, 0x76, 0xff, 0x7c, 0x34, 0x30, 0x58, 0xd7, 0xcb, 0xd6, 0x69, 0x99, 0x2b, 0x0c, 0xc1, 0x45, - 0x75, 0xcb, 0x85, 0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ytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x59, 0x4b, 0x6c, 0xd4, 0x46, + 0x1f, 0xcf, 0x24, 0x21, 0x81, 0x3f, 0x12, 0x24, 0x03, 0x7c, 0x09, 0x06, 0x36, 0xe0, 0x84, 0x24, + 0x5f, 0x00, 0x9b, 0x84, 0x0f, 0xc8, 0x07, 0x05, 0xb1, 0x21, 0x40, 0x23, 0x25, 0x0d, 0x5d, 0x92, + 0x20, 0xf5, 0x21, 0xcb, 0x59, 0x0f, 0x8b, 0x15, 0xaf, 0xbd, 0xd9, 0xf1, 0xa6, 0xac, 0x10, 0xaa, + 0x44, 0x55, 0xa9, 0xa8, 0x87, 0x56, 0xe2, 0xd4, 0x53, 0x7b, 0xa5, 0x87, 0x5e, 0x7b, 0xe9, 0xa5, + 0xea, 0x05, 0xa9, 0xaa, 0x84, 0xd4, 0x4b, 0xd5, 0x03, 0x54, 0xd0, 0x63, 0x7b, 0xe9, 0xb1, 0xbd, + 0x54, 0x9e, 0x19, 0x3f, 0x36, 0xeb, 0xc7, 0x26, 0x50, 0xe8, 0x29, 0x6b, 0xff, 0x9f, 0xbf, 0xff, + 0x6b, 0xe6, 0xef, 0x40, 0xce, 0xa1, 0x65, 0x87, 0x9a, 0x54, 0xa5, 0xb5, 0x0a, 0xa9, 0xde, 0xb0, + 0x6a, 0xa6, 0xa1, 0xae, 0xd6, 0x48, 0xb5, 0xae, 0x54, 0xaa, 0x8e, 0xeb, 0x60, 0x2c, 0xe8, 0x4a, + 0x48, 0x97, 0x76, 0x97, 0x9c, 0x92, 0xc3, 0xc8, 0xaa, 0xf7, 0x8b, 0x73, 0x4a, 0xb9, 0x22, 0x63, + 0x55, 0x97, 0x75, 0x4a, 0xd4, 0xb5, 0xf1, 0x65, 0xe2, 0xea, 0xe3, 0x6a, 0xd1, 0x31, 0x6d, 0x41, + 0xdf, 0x5f, 0x72, 0x9c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, 0x81, + 0xfd, 0xb5, 0xf1, 0xe3, 0xea, 0xad, 0xa8, 0x17, 0xec, 0x56, 0xbc, 0xdc, 0xc5, 0xfe, 0x93, 0x74, + 0xe2, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0x6d, 0x59, 0xf2, 0xe9, 0xc7, 0x1b, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/superfluid/types/superfluid.pb.go b/x/superfluid/types/superfluid.pb.go index 3e2afc2e9cf..9a0cba469ac 100644 --- a/x/superfluid/types/superfluid.pb.go +++ b/x/superfluid/types/superfluid.pb.go @@ -404,51 +404,51 @@ func init() { } var fileDescriptor_79d3c29d82dbb734 = []byte{ - // 694 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x4f, 0x4f, 0xd4, 0x40, - 0x14, 0xdf, 0xb2, 0x2b, 0xb0, 0x83, 0xd1, 0xa5, 0x10, 0x5c, 0x36, 0xa1, 0x8b, 0x25, 0x91, 0x0d, - 0x84, 0x36, 0x60, 0x8c, 0x09, 0xb7, 0x05, 0x34, 0x21, 0x41, 0x20, 0x45, 0x63, 0xc2, 0x65, 0x33, - 0xed, 0x0c, 0xdd, 0xc9, 0x4e, 0x3b, 0xa5, 0x33, 0xad, 0xee, 0xcd, 0x23, 0x47, 0x3f, 0x02, 0x89, - 0x37, 0x3f, 0x84, 0x67, 0x8e, 0x1c, 0x8d, 0x07, 0x34, 0x70, 0xf1, 0xcc, 0x27, 0x30, 0x9d, 0x76, - 0xbb, 0x15, 0x30, 0xea, 0xa9, 0x33, 0xef, 0xf7, 0xde, 0xef, 0xfd, 0xde, 0x9f, 0x0e, 0x58, 0x60, - 0xdc, 0x63, 0x9c, 0x70, 0x93, 0x47, 0x01, 0x0e, 0x8f, 0x68, 0x44, 0x50, 0xe1, 0x68, 0x04, 0x21, - 0x13, 0x4c, 0x55, 0x33, 0x27,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0x1e, 0x7b, 0x71, 0x1c, 0x91, - 0x18, 0x52, 0xec, 0x8b, 0x57, 0x11, 0x15, 0x24, 0xa0, 0x04, 0x87, 0x16, 0x76, 0x58, 0x88, 0xd4, - 0xc7, 0xe0, 0x3e, 0x0e, 0x98, 0xd3, 0xed, 0xf8, 0x91, 0x67, 0xe3, 0x50, 0x66, 0x2d, 0x5b, 0x13, - 0xd2, 0xb6, 0x2b, 0x4d, 0x43, 0x45, 0x23, 0x45, 0x45, 0x0e, 0x00, 0x5e, 0x4e, 0x26, 0x13, 0x57, - 0x37, 0x36, 0xcf, 0x2e, 0x9a, 0xa5, 0x6f, 0x17, 0xcd, 0x27, 0x2e, 0x11, 0xdd, 0xc8, 0x36, 0x1c, - 0xe6, 0x99, 0xd9, 0x28, 0xd2, 0xcf, 0x0a, 0x47, 0x3d, 0x33, 0xe9, 0x25, 0x37, 0xb6, 0xb0, 0x73, - 0x7d, 0xd1, 0x9c, 0xec, 0x43, 0x8f, 0xae, 0xeb, 0x43, 0x26, 0xdd, 0x2a, 0xd0, 0xea, 0xd7, 0x23, - 0xa0, 0x31, 0x6c, 0xd7, 0x16, 0xa6, 0xd8, 0x95, 0x8b, 0x90, 0x89, 0x5f, 0x06, 0x93, 0x28, 0xb5, - 0xb1, 0x50, 0xf6, 0x06, 0x73, 0x9e, 0xf5, 0xad, 0x96, 0x03, 0xed, 0xd4, 0x9e, 0x38, 0xc7, 0x90, - 0x12, 0xf4, 0x9b, 0x73, 0x5a, 0x52, 0x2d, 0x07, 0x06, 0xce, 0xef, 0x72, 0x66, 0xc2, 0xfc, 0x0e, - 0xf4, 0x92, 0xd1, 0xc8, 0x22, 0x27, 0xd6, 0x66, 0x8d, 0xb4, 0x16, 0x23, 0xd9, 0x2e, 0x23, 0xdb, - 0x2e, 0x63, 0x93, 0x11, 0x7f, 0xc3, 0x4c, 0xea, 0xff, 0xfc, 0xbd, 0xb9, 0xf8, 0x0f, 0xf5, 0x27, - 0x01, 0xb9, 0x4a,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70, 0x31, 0xe3, 0xe7, 0xe6, 0xfb, 0xe2, 0xfb, - 0x27, 0x1b, 0x6d, 0x8f, 0xca, 0x07, 0xe7, 0xe9, 0xaf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xc1, 0xfb, - 0xa8, 0x75, 0x22, 0x05, 0x00, 0x00, + // 696 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x4f, 0x4f, 0xd4, 0x4e, + 0x18, 0xde, 0xb2, 0xfb, 0x03, 0x76, 0xf8, 0x45, 0x97, 0x42, 0x70, 0xd9, 0x84, 0x2e, 0x96, 0x44, + 0x36, 0x10, 0x5a, 0x17, 0x13, 0x0f, 0xdc, 0x16, 0xd0, 0x84, 0x04, 0x91, 0x14, 0x8d, 0x09, 0x97, + 0xcd, 0xb4, 0x33, 0x74, 0x27, 0x3b, 0xed, 0x94, 0xce, 0xb4, 0xba, 0x37, 0x8f, 0x1c, 0xfd, 0x08, + 0x24, 0xde, 0xfc, 0x10, 0x9e, 0x39, 0x72, 0x34, 0x1e, 0xd0, 0xc0, 0xc5, 0x33, 0x9f, 0xc0, 0x74, + 0xda, 0xed, 0x56, 0xc0, 0xa8, 0xa7, 0xce, 0xbc, 0xcf, 0xfb, 0x3e, 0xef, 0xf3, 0xfe, 0xe9, 0x80, + 0x25, 0xc6, 0x3d, 0xc6, 0x09, 0x37, 0x79, 0x14, 0xe0, 0xf0, 0x88, 0x46, 0x04, 0x15, 0x8e, 0x46, + 0x10, 0x32, 0xc1, 0x54, 0x35, 0x73, 0x32, 0x46, 0x48, 0x63, 0xd6, 0x65, 0x2e, 0x93, 0xb0, 0x99, + 0x9c, 0x52, 0xcf, 0x86, 0xe6, 0x32, 0xe6, 0x52, 0x6c, 0xca, 0x9b, 0x1d, 0x1d, 0x99, 0x28, 0x0a, + 0xa1, 0x20, 0xcc, 0xcf, 0xf0, 0xe6, 0x4d, 0x5c,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a0, 0x1f, 0x83, 0xa5, 0x5d, 0xe6, 0xf4, 0x77, 0xee, 0x5a, 0xcf, + 0x2d, 0xe6, 0xfb, 0xd8, 0x49, 0xf4, 0xaa, 0x0f, 0xc0, 0x04, 0x65, 0x4e, 0x3f, 0x59, 0x3b, 0x45, + 0xae, 0xdd, 0x38, 0x95, 0x51, 0x6a, 0x1b, 0xcc, 0x92, 0x42, 0x64, 0x17, 0xa6, 0xa1, 0x59, 0xaf, + 0x67, 0xc8, 0x6d, 0x56, 0x7d, 0x05, 0xcc, 0xbd, 0xf6, 0x03, 0xc6, 0xe8, 0x9b, 0x1e, 0x11, 0x98, + 0x12, 0x2e, 0x30, 0xda, 0x67, 0x8c, 0x72, 0xb5, 0x06, 0xca, 0x04, 0x25, 0x43, 0x2d, 0xb7, 0x2a, + 0x56, 0x72, 0x5c, 0x39, 0x04, 0x33, 0x77, 0xfc, 0x6d, 0xea, 0x02, 0x98, 0xbf, 0xc3, 0xbc, 0x07, + 0x05, 0x89, 0x71, 0xad, 0xa4, 0x6a, 0xc5, 0x45, 0xca, 0xe1, 0xdd, 0xfd, 0x83, 0x1e, 0x0c, 0x71, + 0x4d, 0x69, 0x54, 0x4e, 0x3e, 0x6a, 0xa5, 0xcd, 0xfd, 0xb3, 0x4b, 0x4d, 0x39, 0xbf, 0xd4, 0x94, + 0xef, 0x97, 0x9a, 0xf2, 0xe1, 0x4a, 0x2b, 0x9d, 0x5f, 0x69, 0xa5, 0x2f, 0x57, 0x5a, 0xe9, 0xf0, + 0x69, 0xa1, 0xab, 0xd9, 0xff, 0xbf, 0x46, 0xa1, 0xcd, 0x87, 0x17, 0x33, 0x6e, 0x3f, 0x36, 0xdf, + 0x15, 0x1f, 0x40, 0xd9, 0x69, 0x7b, 0x5c, 0xbe, 0x38, 0x4f, 0x7e, 0x06, 0x00, 0x00, 0xff, 0xff, + 0xd3, 0xa7, 0xdf, 0xd8, 0x23, 0x05, 0x00, 0x00, } func (this *SuperfluidAsset) Equal(that interface{}) bool { diff --git a/x/superfluid/types/tx.pb.go b/x/superfluid/types/tx.pb.go index 2e00a381f2d..2932c083bb7 100644 --- a/x/superfluid/types/tx.pb.go +++ b/x/superfluid/types/tx.pb.go @@ -530,45 +530,45 @@ func init() { func init() { proto.RegisterFile("osmosis/superfluid/tx.proto", fileDescriptor_55b645f187d22814) } var fileDescriptor_55b645f187d22814 = []byte{ - // 607 bytes of a gzipped FileDescriptorProto + // 608 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x55, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0x8e, 0x93, 0x90, 0xc2, 0xa0, 0x16, 0x61, 0xb5, 0xaa, 0x63, 0xc0, 0x0e, 0x06, 0xa1, 0xa0, - 0x52, 0x6f, 0xd3, 0xf2, 0x27, 0x6e, 0x0d, 0xb9, 0x04, 0x35, 0x02, 0x19, 0x55, 0x48, 0x48, 0x28, - 0xb2, 0xb3, 0x5b, 0xd7, 0x8a, 0xe3, 0x8d, 0xbc, 0x4e, 0x94, 0x8a, 0x07, 0xe0, 0xca, 0x73, 0xf0, - 0x22, 0xf4, 0xd8, 0x23, 0xa7, 0x80, 0x92, 0x37, 0xa8, 0x78, 0x00, 0xe4, 0xdf, 0x50, 0xb0, 0x43, - 0x22, 0xe0, 0xe4, 0x9d, 0x99, 0x6f, 0xbf, 0xf9, 0x46, 0x33, 0xe3, 0x85, 0x1b, 0x94, 0xf5, 0x28, - 0xb3, 0x18, 0x62, 0x83, 0x3e, 0x71, 0x8f, 0xec, 0x81, 0x85, 0x91, 0x37, 0x52, 0xfb, 0x2e, 0xf5, - 0x28, 0xcf, 0x47, 0x41, 0x75, 0x16, 0x14, 0xd7, 0x4d, 0x6a, 0xd2, 0x20, 0x8c, 0xfc, 0x53, 0x88, - 0x14, 0x25, 0x93, 0x52, 0xd3, 0x26, 0x28, 0xb0, 0x8c, 0xc1, 0x11, 0xc2, 0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0xdb, 0xfd, 0x51, 0x04, 0x85, 0x0e, + 0x33, 0x79, 0x07, 0xf0, 0x69, 0xed, 0x53, 0xff, 0xfc, 0x19, 0xa8, 0xa9, 0x6b, 0x21, 0x36, 0x96, + 0x86, 0x26, 0x1a, 0xc7, 0x60, 0x23, 0x75, 0x7d, 0xb6, 0xff, 0x4a, 0x35, 0x07, 0x8b, 0x7b, 0x2b, + 0x80, 0xb3, 0x32, 0x27, 0x6b, 0xb3, 0x4c, 0xe6, 0x18, 0xbc, 0x54, 0xe6, 0xdf, 0x37, 0x86, 0xff, + 0xc8, 0x81, 0x4a, 0xf6, 0xba, 0xd4, 0x33, 0x28, 0x33, 0x6f, 0x88, 0x2f, 0x56, 0xbd, 0x91, 0x28, + 0xf9, 0x00, 0x36, 0xd3, 0xc7, 0xf6, 0x59, 0x06, 0x65, 0x2a, 0x5a, 0x7c, 0xbe, 0x0a, 0x3a, 0x4e, + 0xde, 0x3c, 0x3a, 0x9f, 0x4a, 0xdc, 0xc5, 0x54, 0xe2, 0xbe, 0x4f, 0x25, 0xee, 0xd3, 0x4c, 0xca, + 0x5d, 0xcc, 0xa4, 0xdc, 0xd7, 0x99, 0x94, 0x7b, 0xb7, 0xff, 0xcb, 0x52, 0x47, 0xcc, 0x3b, 0x44, + 0x37, 0x58, 0x6c, 0x40, 0xaf, 0x51, 0x87, 0xe3, 0x2b, 0x2f, 0x97, 0xbf, 0xe8, 0x46, 0x29, 0x78, + 0x2e, 0xf6, 0x7e, 0x06, 0x00, 0x00, 0xff, 0xff, 0x43, 0xb4, 0xc4, 0x07, 0xdc, 0x06, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/tokenfactory/client/cli/query.go b/x/tokenfactory/client/cli/query.go index c07a0e8c212..470b0bf5d3b 100644 --- a/x/tokenfactory/client/cli/query.go +++ b/x/tokenfactory/client/cli/query.go @@ -13,7 +13,7 @@ import ( // "github.com/cosmos/cosmos-sdk/client/flags" // sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) // GetQueryCmd returns the cli query commands for this module diff --git a/x/tokenfactory/client/cli/tx.go b/x/tokenfactory/client/cli/tx.go index a1c22e8c118..c649af4bbbb 100644 --- a/x/tokenfactory/client/cli/tx.go +++ b/x/tokenfactory/client/cli/tx.go @@ -11,7 +11,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" // "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) // GetTxCmd returns the transaction commands for this module diff --git a/x/tokenfactory/keeper/admins.go b/x/tokenfactory/keeper/admins.go index 3a62d2304ed..48ec2814a06 100644 --- a/x/tokenfactory/keeper/admins.go +++ b/x/tokenfactory/keeper/admins.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) // GetAuthorityMetadata returns the authority metadata for a specific denom diff --git a/x/tokenfactory/keeper/admins_test.go b/x/tokenfactory/keeper/admins_test.go index 958d52643a2..6f687c86537 100644 --- a/x/tokenfactory/keeper/admins_test.go +++ b/x/tokenfactory/keeper/admins_test.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) func (suite *KeeperTestSuite) TestAdminMsgs() { diff --git a/x/tokenfactory/keeper/bankactions.go b/x/tokenfactory/keeper/bankactions.go index bf23d1c273b..39b569aef80 100644 --- a/x/tokenfactory/keeper/bankactions.go +++ b/x/tokenfactory/keeper/bankactions.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) func (k Keeper) mintTo(ctx sdk.Context, amount sdk.Coin, mintTo string) error { diff --git a/x/tokenfactory/keeper/createdenom.go b/x/tokenfactory/keeper/createdenom.go index 89658322d58..7add23564cb 100644 --- a/x/tokenfactory/keeper/createdenom.go +++ b/x/tokenfactory/keeper/createdenom.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) // ConvertToBaseToken converts a fee amount in a whitelisted fee token to the base fee token amount diff --git a/x/tokenfactory/keeper/createdenom_test.go b/x/tokenfactory/keeper/createdenom_test.go index 64179a3972b..876c9375329 100644 --- a/x/tokenfactory/keeper/createdenom_test.go +++ b/x/tokenfactory/keeper/createdenom_test.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) func (suite *KeeperTestSuite) TestMsgCreateDenom() { diff --git a/x/tokenfactory/keeper/genesis.go b/x/tokenfactory/keeper/genesis.go index c87cfa94743..4ab32c0a010 100644 --- a/x/tokenfactory/keeper/genesis.go +++ b/x/tokenfactory/keeper/genesis.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) // InitGenesis initializes the tokenfactory module's state from a provided genesis diff --git a/x/tokenfactory/keeper/genesis_test.go b/x/tokenfactory/keeper/genesis_test.go index 2e99a6c0a11..0eb7f08a13c 100644 --- a/x/tokenfactory/keeper/genesis_test.go +++ b/x/tokenfactory/keeper/genesis_test.go @@ -5,7 +5,7 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) func (suite *KeeperTestSuite) TestGenesis() { diff --git a/x/tokenfactory/keeper/grpc_query.go b/x/tokenfactory/keeper/grpc_query.go index 87bb2dd6412..f2efef6465f 100644 --- a/x/tokenfactory/keeper/grpc_query.go +++ b/x/tokenfactory/keeper/grpc_query.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) var _ types.QueryServer = Keeper{} diff --git a/x/tokenfactory/keeper/keeper.go b/x/tokenfactory/keeper/keeper.go index b4798b2d631..9b885a3b4a7 100644 --- a/x/tokenfactory/keeper/keeper.go +++ b/x/tokenfactory/keeper/keeper.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" diff --git a/x/tokenfactory/keeper/keeper_test.go b/x/tokenfactory/keeper/keeper_test.go index 587fa7d030e..0689769ebc4 100644 --- a/x/tokenfactory/keeper/keeper_test.go +++ b/x/tokenfactory/keeper/keeper_test.go @@ -6,9 +6,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/keeper" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) type KeeperTestSuite struct { diff --git a/x/tokenfactory/keeper/msg_server.go b/x/tokenfactory/keeper/msg_server.go index f211dbfa82c..9403654f828 100644 --- a/x/tokenfactory/keeper/msg_server.go +++ b/x/tokenfactory/keeper/msg_server.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) type msgServer struct { diff --git a/x/tokenfactory/keeper/params.go b/x/tokenfactory/keeper/params.go index ad99bf757c3..472d6cf91c2 100644 --- a/x/tokenfactory/keeper/params.go +++ b/x/tokenfactory/keeper/params.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index 68a0207310e..67aee24683a 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -15,9 +15,9 @@ import ( "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/keeper" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) var ( diff --git a/x/tokenfactory/types/authorityMetadata.pb.go b/x/tokenfactory/types/authorityMetadata.pb.go index 484a1cd1fa9..86353fe3e6b 100644 --- a/x/tokenfactory/types/authorityMetadata.pb.go +++ b/x/tokenfactory/types/authorityMetadata.pb.go @@ -81,7 +81,7 @@ func init() { } var fileDescriptor_99435de88ae175f7 = []byte{ - // 238 bytes of a gzipped FileDescriptorProto + // 239 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0xc9, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0xc9, 0xcf, 0x4e, 0xcd, 0x4b, 0x4b, 0x4c, 0x2e, 0xc9, 0x2f, 0xaa, 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x2c, 0x2d, 0xc9, 0xc8, 0x2f, 0xca, @@ -91,12 +91,12 @@ var fileDescriptor_99435de88ae175f7 = []byte{ 0xa7, 0xc2, 0x2d, 0x48, 0xce, 0xcf, 0xcc, 0x83, 0xc8, 0x2b, 0xb9, 0x71, 0x89, 0xb9, 0xa4, 0xe6, 0xe5, 0xe7, 0x3a, 0xa2, 0xdb, 0x29, 0xa4, 0xc6, 0xc5, 0x9a, 0x98, 0x92, 0x9b, 0x99, 0x27, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0xe9, 0x24, 0xf0, 0xe9, 0x9e, 0x3c, 0x4f, 0x65, 0x62, 0x6e, 0x8e, 0x95, - 0x12, 0x58, 0x58, 0x29, 0x08, 0x22, 0x6d, 0xc5, 0xf2, 0x62, 0x81, 0x3c, 0xa3, 0x53, 0xe0, 0x89, + 0x12, 0x58, 0x58, 0x29, 0x08, 0x22, 0x6d, 0xc5, 0xf2, 0x62, 0x81, 0x3c, 0xa3, 0x53, 0xd0, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, - 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0x99, 0xa7, 0x67, 0x96, 0x64, 0x94, 0x26, + 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0x59, 0xa4, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x43, 0x3d, 0xa0, 0x9b, 0x93, 0x98, 0x54, 0x0c, 0xe3, 0xe8, 0x97, - 0x99, 0xeb, 0x57, 0xa0, 0x06, 0x44, 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, 0xd8, 0x85, 0xc6, - 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3b, 0xcc, 0xc4, 0x2f, 0x2d, 0x01, 0x00, 0x00, + 0x19, 0x1a, 0xe8, 0x57, 0xa0, 0x86, 0x44, 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, 0xd8, 0x89, + 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x15, 0x09, 0x62, 0x7b, 0x2e, 0x01, 0x00, 0x00, } func (this *DenomAuthorityMetadata) Equal(that interface{}) bool { diff --git a/x/tokenfactory/types/denoms_test.go b/x/tokenfactory/types/denoms_test.go index 31234344753..cf7c817d371 100644 --- a/x/tokenfactory/types/denoms_test.go +++ b/x/tokenfactory/types/denoms_test.go @@ -5,8 +5,8 @@ import ( "github.com/stretchr/testify/require" - appparams "github.com/osmosis-labs/osmosis/v7/app/params" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) func TestDecomposeDenoms(t *testing.T) { diff --git a/x/tokenfactory/types/genesis.pb.go b/x/tokenfactory/types/genesis.pb.go index 9e7458096ba..109e99fe2e8 100644 --- a/x/tokenfactory/types/genesis.pb.go +++ b/x/tokenfactory/types/genesis.pb.go @@ -142,7 +142,7 @@ func init() { } var fileDescriptor_5749c3f71850298b = []byte{ - // 364 bytes of a gzipped FileDescriptorProto + // 365 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0xca, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0xc9, 0xcf, 0x4e, 0xcd, 0x4b, 0x4b, 0x4c, 0x2e, 0xc9, 0x2f, 0xaa, 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, @@ -160,12 +160,12 @@ var fileDescriptor_5749c3f71850298b = []byte{ 0xe0, 0xd3, 0x3d, 0x79, 0x1e, 0x88, 0x49, 0x60, 0x61, 0xa5, 0x20, 0x88, 0xb4, 0x50, 0x1b, 0x23, 0x97, 0x10, 0x3c, 0x18, 0xe3, 0x73, 0xa1, 0xe1, 0x28, 0xc1, 0x04, 0xf6, 0xbb, 0x09, 0x7e, 0xf7, 0x82, 0x6d, 0x72, 0x44, 0x8f, 0x03, 0x27, 0x45, 0xa8, 0xcb, 0x25, 0x21, 0xf6, 0x61, 0x9a, 0xae, - 0x14, 0x24, 0x88, 0x11, 0x73, 0x56, 0x2c, 0x2f, 0x16, 0xc8, 0x33, 0x3a, 0x05, 0x9e, 0x78, 0x24, + 0x14, 0x24, 0x88, 0x11, 0x73, 0x56, 0x2c, 0x2f, 0x16, 0xc8, 0x33, 0x3a, 0x05, 0x9d, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, - 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x79, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, - 0x72, 0x7e, 0xae, 0x3e, 0xd4, 0x55, 0xba, 0x39, 0x89, 0x49, 0xc5, 0x30, 0x8e, 0x7e, 0x99, 0xb9, - 0x7e, 0x05, 0x6a, 0x84, 0x97, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x23, 0xda, 0x18, 0x10, - 0x00, 0x00, 0xff, 0xff, 0xa8, 0x21, 0x20, 0xd8, 0xab, 0x02, 0x00, 0x00, + 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x45, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, + 0x72, 0x7e, 0xae, 0x3e, 0xd4, 0x55, 0xba, 0x39, 0x89, 0x49, 0xc5, 0x30, 0x8e, 0x7e, 0x99, 0xa1, + 0x81, 0x7e, 0x05, 0x6a, 0x8c, 0x97, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x63, 0xda, 0x18, + 0x10, 0x00, 0x00, 0xff, 0xff, 0x06, 0x2f, 0x93, 0x12, 0xac, 0x02, 0x00, 0x00, } func (this *GenesisDenom) Equal(that interface{}) bool { diff --git a/x/tokenfactory/types/genesis_test.go b/x/tokenfactory/types/genesis_test.go index 6b6e3bf86f3..e14dd592763 100644 --- a/x/tokenfactory/types/genesis_test.go +++ b/x/tokenfactory/types/genesis_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/osmosis-labs/osmosis/v7/x/tokenfactory/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) func TestGenesisState_Validate(t *testing.T) { diff --git a/x/tokenfactory/types/params.go b/x/tokenfactory/types/params.go index 30c3c741204..9c42c5fd823 100644 --- a/x/tokenfactory/types/params.go +++ b/x/tokenfactory/types/params.go @@ -3,7 +3,7 @@ package types import ( "fmt" - appparams "github.com/osmosis-labs/osmosis/v7/app/params" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" diff --git a/x/tokenfactory/types/params.pb.go b/x/tokenfactory/types/params.pb.go index 6755f175e5e..05fd46c8f75 100644 --- a/x/tokenfactory/types/params.pb.go +++ b/x/tokenfactory/types/params.pb.go @@ -81,26 +81,26 @@ func init() { var fileDescriptor_cc8299d306f3ff47 = []byte{ // 309 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0xcc, 0x2f, 0xce, 0xcd, - 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0xc9, 0xcf, 0x4e, 0xcd, 0x4b, 0x4b, 0x4c, 0x2e, 0xc9, 0x2f, 0xaa, - 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x81, 0x2a, 0xd5, 0x43, 0x56, 0xaa, 0x07, 0x55, 0x2a, - 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xa8, 0x0f, 0x62, 0x41, 0xf4, 0x48, 0x99, 0xe0, 0x35, - 0x3e, 0xb1, 0xb4, 0x24, 0x23, 0xbf, 0x28, 0xb3, 0xa4, 0xd2, 0x37, 0xb5, 0x24, 0x31, 0x25, 0xb1, - 0x24, 0x11, 0xaa, 0x4b, 0x32, 0x19, 0xac, 0x2d, 0x1e, 0x62, 0x1c, 0x84, 0x03, 0x95, 0x92, 0x83, - 0xf0, 0xf4, 0x93, 0x12, 0x8b, 0x53, 0xe1, 0xe6, 0x24, 0xe7, 0x67, 0xe6, 0x41, 0xe4, 0x95, 0x16, - 0x32, 0x72, 0xb1, 0x05, 0x80, 0x5d, 0x2d, 0x34, 0x8d, 0x91, 0x4b, 0x28, 0x25, 0x35, 0x2f, 0x3f, - 0x37, 0x3e, 0xb9, 0x28, 0x35, 0xb1, 0x24, 0x33, 0x3f, 0x2f, 0x3e, 0x2d, 0x35, 0x55, 0x82, 0x51, - 0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 0xbc, 0xd7, 0x77, 0xb7, 0x9f, + 0x48, 0x3d, 0x5b, 0x86, 0x2c, 0xc2, 0xd4, 0x0e, 0x68, 0x9f, 0x81, 0x8a, 0xe7, 0x5c, 0x97, 0xb9, + 0x50, 0x86, 0xa6, 0x26, 0x47, 0x06, 0x30, 0xb2, 0xf9, 0x3b, 0x21, 0x86, 0x93, 0x75, 0x45, 0xc9, + 0xa6, 0xa2, 0xe4, 0xa3, 0xa2, 0xe4, 0xa9, 0xa6, 0xce, 0xa6, 0xa6, 0xce, 0x5b, 0x4d, 0x9d, 0x87, + 0x9b, 0x03, 0xaa, 0xbd, 0xdc, 0x60, 0x01, 0xa1, 0xda, 0x0b, 0xbe, 0xf2, 0x2f, 0xf8, 0xe3, 0xcf, + 0x63, 0x9a, 0x5e, 0x61, 0xcb, 0xac, 0x7f, 0xf5, 0x15, 0x00, 0x00, 0xff, 0xff, 0xb0, 0x4f, 0x79, + 0xa2, 0xd0, 0x01, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { diff --git a/x/tokenfactory/types/query.pb.go b/x/tokenfactory/types/query.pb.go index a8eb09754b1..70f59238689 100644 --- a/x/tokenfactory/types/query.pb.go +++ b/x/tokenfactory/types/query.pb.go @@ -311,43 +311,43 @@ func init() { } var fileDescriptor_6f22013ad0f72e3f = []byte{ - // 573 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0x4d, 0x6b, 0x13, 0x4f, - 0x18, 0xcf, 0xfc, 0xff, 0x6d, 0xa4, 0xe3, 0x0b, 0x66, 0x2c, 0xa2, 0xa1, 0x6e, 0x74, 0x2c, 0x25, - 0x95, 0xba, 0x63, 0x6a, 0xa1, 0x60, 0x15, 0xcd, 0x56, 0xf4, 0xa0, 0x05, 0xbb, 0x37, 0xbd, 0x84, - 0x49, 0x3a, 0xdd, 0x2e, 0x66, 0x77, 0xb6, 0x3b, 0x93, 0x62, 0x28, 0xbd, 0x78, 0xf0, 0x2c, 0x78, - 0xf4, 0x3b, 0xf8, 0x39, 0x7a, 0x2c, 0xf4, 0xe2, 0x69, 0x91, 0xa4, 0xf8, 0x01, 0xf2, 0x09, 0x64, - 0x67, 0x26, 0xb1, 0x75, 0xe3, 0x12, 0xf5, 0x94, 0x65, 0x9e, 0xdf, 0xf3, 0x7b, 0x79, 0x9e, 0x87, - 0xc0, 0x2a, 0x17, 0x01, 0x17, 0xbe, 0x20, 0x92, 0xbf, 0x65, 0xe1, 0x36, 0x6d, 0x49, 0x1e, 0x77, - 0xc9, 0x5e, 0xad, 0xc9, 0x24, 0xad, 0x91, 0xdd, 0x0e, 0x8b, 0xbb, 0x76, 0x14, 0x73, 0xc9, 0xd1, - 0x9c, 0x41, 0xda, 0xa7, 0x91, 0xb6, 0x41, 0x96, 0x67, 0x3d, 0xee, 0x71, 0x05, 0x24, 0xe9, 0x97, - 0xee, 0x29, 0xcf, 0x79, 0x9c, 0x7b, 0x6d, 0x46, 0x68, 0xe4, 0x13, 0x1a, 0x86, 0x5c, 0x52, 0xe9, - 0xf3, 0x50, 0x98, 0xea, 0x9d, 0x96, 0xa2, 0x24, 0x4d, 0x2a, 0x98, 0x96, 0x1a, 0x09, 0x47, 0xd4, - 0xf3, 0x43, 0x05, 0x36, 0xd8, 0x95, 0x5c, 0x9f, 0xb4, 0x23, 0x77, 0x78, 0xec, 0xcb, 0xee, 0x06, - 0x93, 0x74, 0x8b, 0x4a, 0x6a, 0xba, 0x16, 0x73, 0xbb, 0x22, 0x1a, 0xd3, 0xc0, 0x98, 0xc1, 0xb3, - 0x10, 0x6d, 0xa6, 0x16, 0x5e, 0xa9, 0x47, 0x97, 0xed, 0x76, 0x98, 0x90, 0xf8, 0x35, 0xbc, 0x72, - 0xe6, 0x55, 0x44, 0x3c, 0x14, 0x0c, 0x39, 0xb0, 0xa8, 0x9b, 0xaf, 0x81, 0x9b, 0xa0, 0x7a, 0x7e, - 0x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e, 0x5b, 0x40, 0xf3, 0x64, 0x82, 0xcb, 0x45, 0xdf, - 0x01, 0xbc, 0x3a, 0x7e, 0x29, 0xe8, 0xc9, 0x04, 0xda, 0xb9, 0x97, 0x57, 0xae, 0xff, 0x03, 0x83, - 0x49, 0xf3, 0x5c, 0xa5, 0xa9, 0xa3, 0xc7, 0xf9, 0x69, 0xf4, 0xd4, 0xc9, 0xbe, 0xfa, 0x3d, 0x20, - 0xd9, 0x03, 0x42, 0xc7, 0x00, 0x96, 0x32, 0x9b, 0x45, 0x6b, 0x93, 0x3a, 0x1c, 0x73, 0x5e, 0xe5, - 0x87, 0x7f, 0xd7, 0x6c, 0x92, 0xad, 0xab, 0x64, 0x8f, 0xd0, 0xda, 0x24, 0xc9, 0x1a, 0xdb, 0x31, - 0x0f, 0x1a, 0xe6, 0x52, 0xc9, 0xbe, 0xf9, 0x38, 0x70, 0x36, 0x0f, 0x7b, 0x16, 0x38, 0xea, 0x59, - 0xe0, 0x5b, 0xcf, 0x02, 0x1f, 0xfb, 0x56, 0xe1, 0xa8, 0x6f, 0x15, 0xbe, 0xf6, 0xad, 0xc2, 0x9b, - 0x55, 0xcf, 0x97, 0x3b, 0x9d, 0xa6, 0xdd, 0xe2, 0xc1, 0x50, 0xe0, 0x6e, 0x9b, 0x36, 0xc5, 0x48, - 0x6d, 0x6f, 0x95, 0xbc, 0x3b, 0x2b, 0x29, 0xbb, 0x11, 0x13, 0xcd, 0xa2, 0xfa, 0x33, 0xbb, 0xff, - 0x23, 0x00, 0x00, 0xff, 0xff, 0x10, 0x82, 0xc8, 0x64, 0xd7, 0x05, 0x00, 0x00, + // 572 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0x4f, 0x6b, 0x13, 0x41, + 0x14, 0xcf, 0x68, 0x1b, 0xe9, 0xf8, 0x07, 0x33, 0x16, 0xd1, 0x50, 0x37, 0x3a, 0x96,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 0x95, 0x7a, 0x74, 0xd9, 0x4e, 0x87, 0x09, 0x89, 0xdf, 0xc0, 0x2b, 0xa7, 0x5e, + 0x45, 0xc4, 0x43, 0xc1, 0x90, 0x03, 0x8b, 0xba, 0xf9, 0x1a, 0xb8, 0x09, 0xaa, 0xe7, 0x57, 0xe6, + 0xed, 0xbc, 0xe1, 0xd8, 0xba, 0xdb, 0x99, 0x3a, 0x48, 0x2a, 0x05, 0xd7, 0x74, 0xe2, 0x97, 0x10, + 0x2b, 0xea, 0xa7, 0x2c, 0xe4, 0x41, 0xfd, 0xf7, 0x00, 0xc6, 0x00, 0x5a, 0x80, 0xd3, 0x9b, 0x29, + 0x40, 0x09, 0xcd, 0x38, 0x97, 0x07, 0x49, 0xe5, 0x42, 0x97, 0x06, 0xed, 0x07, 0x58, 0x3d, 0x63, + 0x57, 0x97, 0xf1, 0x57, 0x00, 0x6f, 0xe7, 0xd2, 0x19, 0xe7, 0x1f, 0x01, 0x44, 0xa3, 0x69, 0x35, + 0x02, 0x53, 0x36, 0x31, 0x56, 0xf3, 0x63, 0x8c, 0xa7, 0x76, 0x6e, 0xa5, 0xb1, 0x06, 0x49, 0xe5, + 0xba, 0xf6, 0x95, 0x65, 0xc7, 0x6e, 0x29, 0xb3, 0x20, 0xbc, 0x01, 0x6f, 0xfc, 0xf2, 0x2b, 0x9e, + 0xc5, 0x3c, 0x58, 0x8f, 0x19, 0x95, 0x3c, 0x1e, 0x26, 0x5f, 0x82, 0xe7, 0x5a, 0xfa, 0xc5, 0x64, + 0x47, 0x83, 0xa4, 0x72, 0x49, 0x6b, 0x98, 0x02, 0x76, 0x87, 0x10, 0xfc, 0x02, 0x5a, 0x7f, 0xa2, + 0x33, 0xc9, 0x17, 0x61, 0x51, 0x8d, 0x2a, 0xdd, 0xd9, 0xd9, 0xea, 0x8c, 0x53, 0x1a, 0x24, 0x95, + 0x8b, 0x27, 0x46, 0x29, 0xb0, 0x6b, 0x00, 0x2b, 0xc7, 0x53, 0x70, 0x5a, 0xb1, 0xa1, 0x2f, 0x00, + 0x16, 0xf5, 0xf6, 0xd0, 0x72, 0xfe, 0x70, 0xb2, 0xc7, 0x53, 0xae, 0xfd, 0x45, 0x87, 0x36, 0x89, + 0x97, 0x3e, 0x1c, 0x1d, 0x7f, 0x3e, 0xb3, 0x80, 0xe6, 0xc9, 0x04, 0x97, 0x8b, 0x7e, 0x00, 0x78, + 0x75, 0xfc, 0x52, 0xd0, 0x93, 0x09, 0xb4, 0x73, 0x2f, 0xaf, 0x5c, 0xff, 0x0f, 0x06, 0x93, 0xe6, + 0xb9, 0x4a, 0x53, 0x47, 0x8f, 0xf3, 0xd3, 0xe8, 0xa9, 0x93, 0x3d, 0xf5, 0xbb, 0x4f, 0xb2, 0x07, + 0x84, 0x8e, 0x00, 0x2c, 0x65, 0x36, 0x8b, 0xd6, 0x26, 0x75, 0x38, 0xe6, 0xbc, 0xca, 0x0f, 0xff, + 0xad, 0xd9, 0x24, 0x5b, 0x57, 0xc9, 0x1e, 0xa1, 0xb5, 0x49, 0x92, 0x35, 0xb6, 0x62, 0x1e, 0x34, + 0xcc, 0xa5, 0x92, 0x3d, 0xf3, 0xb1, 0xef, 0xb8, 0x07, 0x3d, 0x0b, 0x1c, 0xf6, 0x2c, 0xf0, 0xbd, + 0x67, 0x81, 0x4f, 0x7d, 0xab, 0x70, 0xd8, 0xb7, 0x0a, 0xdf, 0xfa, 0x56, 0xe1, 0xed, 0x7d, 0xcf, + 0x97, 0xdb, 0x9d, 0xa6, 0xdd, 0xe2, 0xc1, 0x50, 0xe0, 0x6e, 0x9b, 0x36, 0xc5, 0x48, 0x6d, 0xb7, + 0xb6, 0x4c, 0xde, 0x9f, 0xd6, 0x94, 0xdd, 0x88, 0x89, 0x66, 0x51, 0xfd, 0x9b, 0xdd, 0xfb, 0x19, + 0x00, 0x00, 0xff, 0xff, 0x1b, 0xfc, 0x95, 0xd7, 0xd8, 0x05, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/tokenfactory/types/tx.pb.go b/x/tokenfactory/types/tx.pb.go index e3088cd3959..0f3a637ada6 100644 --- a/x/tokenfactory/types/tx.pb.go +++ b/x/tokenfactory/types/tx.pb.go @@ -436,36 +436,36 @@ var fileDescriptor_283b6c9a90a846b4 = []byte{ // 513 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x94, 0x4d, 0x6e, 0xd3, 0x40, 0x14, 0xc7, 0x63, 0x02, 0xa1, 0x9d, 0x52, 0xd2, 0x9a, 0x52, 0x05, 0x0b, 0xd9, 0x68, 0xa4, 0x22, - 0x90, 0xe8, 0x8c, 0x52, 0x90, 0x2a, 0xb1, 0xc3, 0x65, 0xc1, 0x26, 0x0b, 0x2c, 0x56, 0xa8, 0x52, - 0x35, 0x4e, 0x06, 0xd7, 0x22, 0x9e, 0x09, 0x9e, 0x49, 0xd3, 0x6c, 0x38, 0x03, 0x2b, 0xae, 0xc0, - 0x55, 0xba, 0xec, 0x92, 0x95, 0x85, 0x92, 0x1b, 0xf8, 0x04, 0x68, 0x3e, 0x92, 0x38, 0x20, 0xd1, - 0x64, 0xc5, 0x2e, 0xf1, 0xfb, 0xbd, 0xff, 0xfb, 0xf8, 0x3f, 0x1b, 0x1c, 0x70, 0x91, 0x71, 0x91, - 0x0a, 0x2c, 0xf9, 0x67, 0xca, 0x3e, 0x91, 0xae, 0xe4, 0xf9, 0x18, 0x5f, 0xb4, 0x63, 0x2a, 0x49, - 0x1b, 0xcb, 0x4b, 0x34, 0xc8, 0xb9, 0xe4, 0xee, 0x63, 0x8b, 0xa1, 0x2a, 0x86, 0x2c, 0xe6, 0xed, - 0x25, 0x3c, 0xe1, 0x1a, 0xc4, 0xea, 0x97, 0xc9, 0xf1, 0xfc, 0xae, 0x4e, 0xc2, 0x31, 0x11, 0x74, - 0xae, 0xd8, 0xe5, 0x29, 0x33, 0x71, 0xd8, 0x07, 0xf7, 0x3b, 0x22, 0x39, 0xc9, 0x29, 0x91, 0xf4, - 0x2d, 0x65, 0x3c, 0x73, 0x9f, 0x83, 0x86, 0xa0, 0xac, 0x47, 0xf3, 0x96, 0xf3, 0xc4, 0x79, 0xb6, - 0x19, 0xee, 0x96, 0x45, 0xb0, 0x3d, 0x26, 0x59, 0xff, 0x35, 0x34, 0xcf, 0x61, 0x64, 0x01, 0x17, - 0x83, 0x0d, 0x31, 0x8c, 0x7b, 0x2a, 0xad, 0x75, 0x4b, 0xc3, 0x0f, 0xca, 0x22, 0x68, 0x5a, 0xd8, - 0x46, 0x60, 0x34, 0x87, 0xe0, 0x29, 0xd8, 0x5f, 0xae, 0x16, 0x51, 0x31, 0xe0, 0x4c, 0x50, 0x37, - 0x04, 0x4d, 0x46, 0x47, 0x67, 0x7a, 0xb2, 0x33, 0xa3, 0x68, 0xca, 0x7b, 0x65, 0x11, 0xec, 0x1b, - 0xc5, 0x3f, 0x00, 0x18, 0x6d, 0x33, 0x3a, 0xfa, 0xa0, 0x1e, 0x68, 0x2d, 0xf8, 0x15, 0xdc, 0xed, - 0x88, 0xa4, 0x93, 0x32, 0xb9, 0xce, 0x10, 0xef, 0x40, 0x83, 0x64, 0x7c, 0xc8, 0xa4, 0x1e, 0x61, - 0xeb, 0xe8, 0x11, 0x32, 0x2b, 0x43, 0x6a, 0x65, 0xb3, 0xed, 0xa2, 0x13, 0x9e, 0xb2, 0xf0, 0xe1, - 0x55, 0x11, 0xd4, 0x16, 0x4a, 0x26, 0x0d, 0x46, 0x36, 0x1f, 0xee, 0x82, 0xa6, 0xad, 0x3f, 0x1b, - 0xcb, 0xb6, 0x14, 0x0e, 0x73, 0xf6, 0x3f, 0x5b, 0x52, 0xf5, 0xe7, 0x2d, 0x7d, 0x77, 0x8c, 0xe5, - 0xe7, 0x84, 0x25, 0xf4, 0x4d, 0x2f, 0x4b, 0xd7, 0x6a, 0xed, 0x29, 0xb8, 0x53, 0xf5, 0x7b, 0xa7, - 0x2c, 0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 0xeb, 0x83, 0x3a, 0xb8, 0x36, 0x5b, 0x61, 0xde, 0xe1, 0x4a, 0x58, + 0x55, 0x5d, 0xdf, 0xc6, 0xf5, 0xea, 0x0a, 0x5b, 0x41, 0xbd, 0xea, 0xb4, 0x5e, 0x57, 0xc5, 0xe5, + 0x15, 0xd6, 0xb5, 0xa0, 0x57, 0x59, 0xd7, 0xbf, 0x4e, 0x85, 0xd1, 0xe5, 0xc4, 0x77, 0xae, 0x26, + 0xbe, 0xf3, 0x7b, 0xe2, 0x3b, 0xdf, 0xa7, 0x7e, 0xed, 0x6a, 0xea, 0xd7, 0x7e, 0x4d, 0xfd, 0xda, + 0xa7, 0x37, 0x49, 0x2a, 0xcf, 0x86, 0x31, 0xea, 0xf2, 0x0c, 0x5b, 0xe5, 0xc3, 0x3e, 0x89, 0xc5, + 0xec, 0x0f, 0x3e, 0x6f, 0xbf, 0xc4, 0x17, 0xcb, 0x5f, 0x40, 0x39, 0x1e, 0x50, 0x11, 0x37, 0xf4, + 0x97, 0xea, 0xd5, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x37, 0x11, 0x83, 0x05, 0x26, 0x05, 0x00, 0x00, } diff --git a/x/txfees/client/cli/query.go b/x/txfees/client/cli/query.go index 1190f93a149..c6b61e119a9 100644 --- a/x/txfees/client/cli/query.go +++ b/x/txfees/client/cli/query.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/txfees/client/cli/tx.go b/x/txfees/client/cli/tx.go index 476b1701491..641ae9d98ae 100644 --- a/x/txfees/client/cli/tx.go +++ b/x/txfees/client/cli/tx.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/client/cli" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) func NewTxCmd() *cobra.Command { diff --git a/x/txfees/handler.go b/x/txfees/handler.go index 2eb01c9052b..4ea5e538877 100644 --- a/x/txfees/handler.go +++ b/x/txfees/handler.go @@ -5,8 +5,8 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/osmosis-labs/osmosis/v7/x/txfees/keeper" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) func NewUpdateFeeTokenProposalHandler(k keeper.Keeper) govtypes.Handler { diff --git a/x/txfees/keeper/feedecorator.go b/x/txfees/keeper/feedecorator.go index 1f4cb51ee1c..caa93cfee9a 100644 --- a/x/txfees/keeper/feedecorator.go +++ b/x/txfees/keeper/feedecorator.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/osmosis-labs/osmosis/v7/x/txfees/keeper/txfee_filters" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper/txfee_filters" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) diff --git a/x/txfees/keeper/feedecorator_test.go b/x/txfees/keeper/feedecorator_test.go index 5faddf95259..1838a2c303d 100644 --- a/x/txfees/keeper/feedecorator_test.go +++ b/x/txfees/keeper/feedecorator_test.go @@ -9,8 +9,8 @@ import ( authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" - "github.com/osmosis-labs/osmosis/v7/x/txfees/keeper" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) func (suite *KeeperTestSuite) TestFeeDecorator() { diff --git a/x/txfees/keeper/feetokens.go b/x/txfees/keeper/feetokens.go index f1da6a3765f..0f532e3f139 100644 --- a/x/txfees/keeper/feetokens.go +++ b/x/txfees/keeper/feetokens.go @@ -2,7 +2,7 @@ package keeper import ( "github.com/gogo/protobuf/proto" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/txfees/keeper/feetokens_test.go b/x/txfees/keeper/feetokens_test.go index 1dd945f1c00..74c296de67c 100644 --- a/x/txfees/keeper/feetokens_test.go +++ b/x/txfees/keeper/feetokens_test.go @@ -1,7 +1,7 @@ package keeper_test import ( - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/txfees/keeper/genesis.go b/x/txfees/keeper/genesis.go index 858b6a3235a..9cd9cf00782 100644 --- a/x/txfees/keeper/genesis.go +++ b/x/txfees/keeper/genesis.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/txfees/keeper/gov.go b/x/txfees/keeper/gov.go index 8d2550b4843..38dcd27cc07 100644 --- a/x/txfees/keeper/gov.go +++ b/x/txfees/keeper/gov.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) func (k Keeper) HandleUpdateFeeTokenProposal(ctx sdk.Context, p *types.UpdateFeeTokenProposal) error { diff --git a/x/txfees/keeper/grpc_query.go b/x/txfees/keeper/grpc_query.go index e2a017a710e..9a6626591c3 100644 --- a/x/txfees/keeper/grpc_query.go +++ b/x/txfees/keeper/grpc_query.go @@ -8,7 +8,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) var _ types.QueryServer = Querier{} diff --git a/x/txfees/keeper/hooks.go b/x/txfees/keeper/hooks.go index 6cb662b36a7..33721062fc9 100644 --- a/x/txfees/keeper/hooks.go +++ b/x/txfees/keeper/hooks.go @@ -3,9 +3,9 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/osmoutils" - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" - txfeestypes "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/osmoutils" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + txfeestypes "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) func (k Keeper) BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) {} diff --git a/x/txfees/keeper/hooks_test.go b/x/txfees/keeper/hooks_test.go index 6b5f97b1ef8..e868b8022c9 100644 --- a/x/txfees/keeper/hooks_test.go +++ b/x/txfees/keeper/hooks_test.go @@ -7,8 +7,8 @@ import ( "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) var defaultPooledAssetAmount = int64(500) diff --git a/x/txfees/keeper/keeper.go b/x/txfees/keeper/keeper.go index 1c60dd2add8..54a14d51897 100644 --- a/x/txfees/keeper/keeper.go +++ b/x/txfees/keeper/keeper.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) type Keeper struct { diff --git a/x/txfees/keeper/keeper_test.go b/x/txfees/keeper/keeper_test.go index 52f7420ec51..72acced6e3f 100644 --- a/x/txfees/keeper/keeper_test.go +++ b/x/txfees/keeper/keeper_test.go @@ -8,10 +8,10 @@ import ( "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" - osmosisapp "github.com/osmosis-labs/osmosis/v7/app" + osmosisapp "github.com/osmosis-labs/osmosis/v10/app" - "github.com/osmosis-labs/osmosis/v7/app/apptesting" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) type KeeperTestSuite struct { diff --git a/x/txfees/keeper/txfee_filters/arb_tx.go b/x/txfees/keeper/txfee_filters/arb_tx.go index 03a7fb80b10..800bfb62e62 100644 --- a/x/txfees/keeper/txfee_filters/arb_tx.go +++ b/x/txfees/keeper/txfee_filters/arb_tx.go @@ -1,7 +1,7 @@ package txfee_filters import ( - gammtypes "github.com/osmosis-labs/osmosis/v7/x/gamm/types" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/txfees/module.go b/x/txfees/module.go index 5949982b711..e898172259f 100644 --- a/x/txfees/module.go +++ b/x/txfees/module.go @@ -16,9 +16,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/osmosis-labs/osmosis/v7/x/txfees/client/cli" - "github.com/osmosis-labs/osmosis/v7/x/txfees/keeper" - "github.com/osmosis-labs/osmosis/v7/x/txfees/types" + "github.com/osmosis-labs/osmosis/v10/x/txfees/client/cli" + "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper" + "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) var ( diff --git a/x/txfees/module_test.go b/x/txfees/module_test.go index af76b0eec12..e1e2a880060 100644 --- a/x/txfees/module_test.go +++ b/x/txfees/module_test.go @@ -7,7 +7,7 @@ import ( abcitypes "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - simapp "github.com/osmosis-labs/osmosis/v7/app" + simapp "github.com/osmosis-labs/osmosis/v10/app" ) func TestSetBaseDenomOnInitBlock(t *testing.T) { diff --git a/x/txfees/types/expected_keepers.go b/x/txfees/types/expected_keepers.go index c8a3d2df789..9e2ae585cd8 100644 --- a/x/txfees/types/expected_keepers.go +++ b/x/txfees/types/expected_keepers.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - epochstypes "github.com/osmosis-labs/osmosis/v7/x/epochs/types" + epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) // SpotPriceCalculator defines the contract that must be fulfilled by a spot price calculator diff --git a/x/txfees/types/feetoken.pb.go b/x/txfees/types/feetoken.pb.go index e532700ac28..2d910c87b38 100644 --- a/x/txfees/types/feetoken.pb.go +++ b/x/txfees/types/feetoken.pb.go @@ -88,7 +88,7 @@ func init() { } var fileDescriptor_c50689857adfcfe0 = []byte{ - // 235 bytes of a gzipped FileDescriptorProto + // 236 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xcd, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0xa9, 0x48, 0x4b, 0x4d, 0x2d, 0xd6, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4b, 0x4d, 0x2d, 0xc9, 0xcf, 0x4e, 0xcd, 0xd3, 0x2b, 0x28, 0xca, 0x2f, @@ -98,12 +98,12 @@ var fileDescriptor_c50689857adfcfe0 = []byte{ 0x38, 0x9d, 0x04, 0x3e, 0xdd, 0x93, 0xe7, 0xa9, 0x4c, 0xcc, 0xcd, 0xb1, 0x52, 0x02, 0x0b, 0x2b, 0x05, 0x41, 0xa4, 0x85, 0xb4, 0xb8, 0xd8, 0x0a, 0xf2, 0xf3, 0x73, 0x3c, 0x5d, 0x24, 0x98, 0x14, 0x18, 0x35, 0x58, 0x9c, 0x84, 0x3e, 0xdd, 0x93, 0xe7, 0x83, 0x28, 0x04, 0x89, 0xc7, 0x67, 0xa6, - 0x28, 0x05, 0x41, 0x55, 0x58, 0xb1, 0xbc, 0x58, 0x20, 0xcf, 0xe8, 0xe4, 0x7d, 0xe2, 0x91, 0x1c, + 0x28, 0x05, 0x41, 0x55, 0x58, 0xb1, 0xbc, 0x58, 0x20, 0xcf, 0xe8, 0xe4, 0x73, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, - 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x86, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, - 0xf9, 0xb9, 0xfa, 0x50, 0x87, 0xeb, 0xe6, 0x24, 0x26, 0x15, 0xc3, 0x38, 0xfa, 0x65, 0xe6, 0xfa, - 0x15, 0x30, 0x1f, 0x97, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x5d, 0x6e, 0x0c, 0x08, 0x00, - 0x00, 0xff, 0xff, 0x6f, 0x91, 0x61, 0xbb, 0x10, 0x01, 0x00, 0x00, + 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x46, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, + 0xf9, 0xb9, 0xfa, 0x50, 0x87, 0xeb, 0xe6, 0x24, 0x26, 0x15, 0xc3, 0x38, 0xfa, 0x65, 0x86, 0x06, + 0xfa, 0x15, 0x30, 0x2f, 0x97, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x9d, 0x6e, 0x0c, 0x08, + 0x00, 0x00, 0xff, 0xff, 0x94, 0x93, 0x95, 0xe8, 0x11, 0x01, 0x00, 0x00, } func (this *FeeToken) Equal(that interface{}) bool { diff --git a/x/txfees/types/genesis.pb.go b/x/txfees/types/genesis.pb.go index 141fe5bb96e..3b13e04ea9c 100644 --- a/x/txfees/types/genesis.pb.go +++ b/x/txfees/types/genesis.pb.go @@ -85,7 +85,7 @@ func init() { } var fileDescriptor_4423c18e3d020b37 = []byte{ - // 235 bytes of a gzipped FileDescriptorProto + // 236 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc9, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0xa9, 0x48, 0x4b, 0x4d, 0x2d, 0xd6, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, @@ -95,12 +95,12 @@ var fileDescriptor_4423c18e3d020b37 = []byte{ 0x24, 0x55, 0x48, 0x86, 0x8b, 0x33, 0x29, 0xb1, 0x38, 0x35, 0x25, 0x35, 0x2f, 0x3f, 0x57, 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x08, 0x21, 0x20, 0xe4, 0xc2, 0xc5, 0x09, 0xd3, 0x5f, 0x2c, 0xc1, 0xa4, 0xc0, 0xac, 0xc1, 0x6d, 0xa4, 0xa0, 0x87, 0xdd, 0x59, 0x7a, 0x6e, 0xa9, 0xa9, 0x21, 0x20, - 0x85, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x21, 0x34, 0x3a, 0x79, 0x9f, 0x78, 0x24, 0xc7, + 0x85, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x21, 0x34, 0x3a, 0xf9, 0x9c, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, 0x2c, - 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x61, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, - 0x7e, 0xae, 0x3e, 0xd4, 0x58, 0xdd, 0x9c, 0xc4, 0xa4, 0x62, 0x18, 0x47, 0xbf, 0xcc, 0x5c, 0xbf, - 0x02, 0xe6, 0xa3, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, 0xb0, 0x3f, 0x8c, 0x01, 0x01, 0x00, - 0x00, 0xff, 0xff, 0xdd, 0x30, 0x73, 0x62, 0x44, 0x01, 0x00, 0x00, + 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x51, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, + 0x7e, 0xae, 0x3e, 0xd4, 0x58, 0xdd, 0x9c, 0xc4, 0xa4, 0x62, 0x18, 0x47, 0xbf, 0xcc, 0xd0, 0x40, + 0xbf, 0x02, 0xe6, 0xa5, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, 0xb0, 0x47, 0x8c, 0x01, 0x01, + 0x00, 0x00, 0xff, 0xff, 0x95, 0x53, 0x23, 0xcd, 0x45, 0x01, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { diff --git a/x/txfees/types/gov.pb.go b/x/txfees/types/gov.pb.go index 34add7f87d3..0cff1a6cc96 100644 --- a/x/txfees/types/gov.pb.go +++ b/x/txfees/types/gov.pb.go @@ -73,7 +73,7 @@ func init() { func init() { proto.RegisterFile("osmosis/txfees/v1beta1/gov.proto", fileDescriptor_2c4a51bafc82863d) } var fileDescriptor_2c4a51bafc82863d = []byte{ - // 311 bytes of a gzipped FileDescriptorProto + // 312 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc8, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0xa9, 0x48, 0x4b, 0x4d, 0x2d, 0xd6, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0xcf, 0x2f, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x83, 0xaa, @@ -88,12 +88,12 @@ var fileDescriptor_2c4a51bafc82863d = []byte{ 0x98, 0x73, 0x24, 0x98, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0x14, 0xf4, 0xb0, 0x7b, 0x52, 0x0f, 0xe6, 0x3a, 0x27, 0x89, 0x13, 0xf7, 0xe4, 0x19, 0x3e, 0xdd, 0x93, 0x17, 0x80, 0x18, 0x9e, 0x96, 0x9a, 0x1a, 0x0f, 0x36, 0x40, 0x29, 0x08, 0x6e, 0x96, 0x15, 0x4f, 0xc7, 0x02, 0x79, 0x86, 0x19, 0x0b, - 0xe4, 0x19, 0x5e, 0x2c, 0x90, 0x67, 0x74, 0xf2, 0x3e, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, + 0xe4, 0x19, 0x5e, 0x2c, 0x90, 0x67, 0x74, 0xf2, 0x39, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, - 0x39, 0x86, 0x28, 0xc3, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0xa8, - 0xbd, 0xba, 0x39, 0x89, 0x49, 0xc5, 0x30, 0x8e, 0x7e, 0x99, 0xb9, 0x7e, 0x05, 0x2c, 0x00, 0x4b, - 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0xc1, 0x66, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x40, - 0x95, 0x3f, 0xf6, 0xaf, 0x01, 0x00, 0x00, + 0x39, 0x86, 0x28, 0xa3, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0xa8, + 0xbd, 0xba, 0x39, 0x89, 0x49, 0xc5, 0x30, 0x8e, 0x7e, 0x99, 0xa1, 0x81, 0x7e, 0x05, 0x2c, 0x04, + 0x4b, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0xe1, 0x66, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, + 0xc9, 0xf0, 0x09, 0x43, 0xb0, 0x01, 0x00, 0x00, } func (this *UpdateFeeTokenProposal) Equal(that interface{}) bool { diff --git a/x/txfees/types/query.pb.go b/x/txfees/types/query.pb.go index 7b45155d0e0..9beef390b32 100644 --- a/x/txfees/types/query.pb.go +++ b/x/txfees/types/query.pb.go @@ -389,44 +389,44 @@ func init() { var fileDescriptor_6cbc1b48c44dfdd6 = []byte{ // 611 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0x41, 0x6b, 0x13, 0x4f, - 0x18, 0xc6, 0x33, 0xfd, 0xff, 0x53, 0xc8, 0x54, 0x8a, 0x0e, 0xb6, 0x8d, 0xab, 0x6c, 0xc2, 0xa0, - 0xa5, 0x54, 0xb2, 0x63, 0x12, 0x45, 0xf0, 0x66, 0x0c, 0x05, 0x11, 0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0xfd, 0x43, 0x8c, 0x3d, 0x57, 0x80, 0x33, 0x9d, 0x73, - 0x23, 0x99, 0x39, 0xa9, 0x51, 0x3b, 0xe3, 0xc5, 0xbb, 0x4b, 0x9f, 0xd3, 0x38, 0xad, 0x0c, 0xc9, - 0x17, 0x84, 0x33, 0x13, 0xca, 0x48, 0x61, 0x1e, 0x49, 0x33, 0x31, 0x35, 0xac, 0xab, 0xca, 0xa3, - 0xb0, 0x74, 0xf7, 0xc3, 0x8f, 0x3f, 0x9f, 0x56, 0xee, 0x12, 0xca, 0xe6, 0xdf, 0x0f, 0x0d, 0x26, - 0xf9, 0x8e, 0xf0, 0xfa, 0x79, 0x82, 0x48, 0xe9, 0x9f, 0xed, 0x66, 0x52, 0x6b, 0x94, 0x97, 0xda, - 0xa3, 0x73, 0x96, 0x55, 0xce, 0x02, 0xb9, 0x3f, 0x2f, 0x67, 0x82, 0x92, 0xe3, 0xf5, 0xa3, 0xf7, - 0x4b, 0xbe, 0x22, 0xbc, 0x36, 0x05, 0x00, 0x61, 0x8b, 0x3b, 0x9f, 0xa3, 0xcd, 0x78, 0x70, 0xf5, - 0x0d, 0x3a, 0xe7, 0x23, 0x95, 0x93, 0x91, 0xc2, 0xbc, 0x9c, 0x2a, 0x99, 0xa3, 0x39, 0x63, 0xef, - 0xd4, 0xe3, 0x7b, 0x75, 0xe6, 0x13, 0x92, 0x16, 0x9c, 0xf9, 0x45, 0x14, 0x17, 0x9c, 0xf9, 0x25, - 0x40, 0x17, 0x9f, 0x79, 0x82, 0x68, 0xe5, 0xc5, 0xe9, 0xd0, 0x44, 0x67, 0x43, 0x13, 0xfd, 0x1e, - 0x9a, 0xe8, 0xe3, 0xc8, 0x4c, 0x9d, 0x8d, 0xcc, 0xd4, 0xcf, 0x91, 0x99, 0x3a, 0x28, 0x4e, 0x5d, - 0x76, 0xed, 0x53, 0x68, 0xb9, 0x9e, 0x98, 0x98, 0x1e, 0x3f, 0x66, 0x27, 0xb1, 0xb3, 0xba, 0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x7c, 0xaf, 0xce, 0x7c, 0x42, 0xd2, 0x82, 0x33, 0xbf, 0x8c, 0xe2, 0x82, 0x33, 0xbf, 0x02, + 0xe8, 0xe2, 0x33, 0x4f, 0x10, 0xad, 0xbc, 0x38, 0x1b, 0x9a, 0xe8, 0x7c, 0x68, 0xa2, 0xdf, 0x43, + 0x13, 0x7d, 0x1c, 0x99, 0xa9, 0xf3, 0x91, 0x99, 0xfa, 0x39, 0x32, 0x53, 0x87, 0xa5, 0xa9, 0xcb, + 0xae, 0x7d, 0x0a, 0x2d, 0xd7, 0x13, 0x13, 0xd3, 0x93, 0xe2, 0x1e, 0x3b, 0x8d, 0xad, 0xd5, 0xe5, + 0xf7, 0x56, 0xd5, 0x47, 0xb6, 0xfc, 0x37, 0x00, 0x00, 0xff, 0xff, 0xb3, 0xd1, 0x75, 0xfb, 0x1d, 0x06, 0x00, 0x00, } From 8fe3fa79249fca8ee223e1150a15311bab71b4e8 Mon Sep 17 00:00:00 2001 From: Roman Date: Mon, 18 Jul 2022 13:33:16 -0400 Subject: [PATCH 093/376] chore(deps): upgrade cosmos-sdk fork to v0.45.0x-osmo-v11.rc1 tag (#2041) * chore(deps): upgrade cosmos-sdk fork to v0.45.0x-osmo-v11.rc0 tag * updates * update tag --- go.mod | 10 +++++----- go.sum | 15 +++++++++------ wasmbinding/test/custom_query_test.go | 2 +- wasmbinding/test/store_run_test.go | 2 +- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/go.mod b/go.mod index c0e14c9b56f..8f5b9549135 100644 --- a/go.mod +++ b/go.mod @@ -51,7 +51,7 @@ require ( github.com/OpenPeeDeeP/depguard v1.1.0 // indirect github.com/Workiva/go-datastructures v1.0.53 // indirect github.com/alexkohler/prealloc v1.0.0 // indirect - github.com/armon/go-metrics v0.3.10 // indirect + github.com/armon/go-metrics v0.3.11 // indirect github.com/ashanbrown/forbidigo v1.3.0 // indirect github.com/ashanbrown/makezero v1.1.1 // indirect github.com/beorn7/perks v1.0.1 // indirect @@ -61,7 +61,7 @@ require ( github.com/bombsimon/wsl/v3 v3.3.0 // indirect github.com/breml/bidichk v0.2.3 // indirect github.com/breml/errchkjson v0.3.0 // indirect - github.com/btcsuite/btcd v0.22.0-beta // indirect + github.com/btcsuite/btcd v0.22.1 // indirect github.com/butuzov/ireturn v0.1.1 // indirect github.com/cenkalti/backoff/v4 v4.1.3 // indirect github.com/cespare/xxhash v1.1.0 // indirect @@ -202,7 +202,7 @@ require ( github.com/polyfloyd/go-errorlint v1.0.0 // indirect github.com/prometheus/client_golang v1.12.2 github.com/prometheus/client_model v0.2.0 // indirect - github.com/prometheus/common v0.33.0 // indirect + github.com/prometheus/common v0.34.0 // indirect github.com/prometheus/procfs v0.7.3 // indirect github.com/quasilyte/go-ruleguard v0.3.16-0.20220213074421-6aa060fab41a // indirect github.com/quasilyte/gogrep v0.0.0-20220120141003-628d8b3623b5 // indirect @@ -278,8 +278,8 @@ require ( replace ( // branch: v0.27.0.rc3-osmo, current tag: v0.27.0.rc3-osmo github.com/CosmWasm/wasmd => github.com/osmosis-labs/wasmd v0.27.0-rc2.0.20220517191021-59051aa18d58 - // Our cosmos-sdk branch is: https://github.com/osmosis-labs/cosmos-sdk v0.45.0x-osmo-v7 - github.com/cosmos/cosmos-sdk => github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220620200611-3e46ff7501a1 + // Our cosmos-sdk branch is: https://github.com/osmosis-labs/cosmos-sdk osmosis-main, current tag: v0.45.0x-osmo-v11.rc1 + github.com/cosmos/cosmos-sdk => github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220714223138-b81ad24550fa // Use Osmosis fast iavl github.com/cosmos/iavl => github.com/osmosis-labs/iavl v0.17.3-osmo-v7 // use cosmos-compatible protobufs diff --git a/go.sum b/go.sum index 976dfb6b888..c5945e03aec 100644 --- a/go.sum +++ b/go.sum @@ -159,8 +159,9 @@ github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hC github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-metrics v0.3.9/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc= -github.com/armon/go-metrics v0.3.10 h1:FR+drcQStOe+32sYyJYyZ7FIdgoGGBnwLl+flodp8Uo= github.com/armon/go-metrics v0.3.10/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc= +github.com/armon/go-metrics v0.3.11 h1:/q4zqTAH+/mtFjimfc0SC7yuuxZshlS4TaCeBm+7sZ0= +github.com/armon/go-metrics v0.3.11/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= @@ -203,8 +204,10 @@ github.com/btcsuite/btcd v0.0.0-20190115013929-ed77733ec07d/go.mod h1:d3C0AkH6BR github.com/btcsuite/btcd v0.0.0-20190315201642-aa6e0f35703c/go.mod h1:DrZx5ec/dmnfpw9KyYoQyYo7d0KEvTkk/5M/vbZjAr8= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= github.com/btcsuite/btcd v0.21.0-beta/go.mod h1:ZSWyehm27aAuS9bvkATT+Xte3hjHZ+MRgMY/8NJ7K94= -github.com/btcsuite/btcd v0.22.0-beta h1:LTDpDKUM5EeOFBPM8IXpinEcmZ6FWfNZbE3lfrfdnWo= github.com/btcsuite/btcd v0.22.0-beta/go.mod h1:9n5ntfhhHQBIhUvlhDvD3Qg6fRUj4jkN0VB8L8svzOA= +github.com/btcsuite/btcd v0.22.1 h1:CnwP9LM/M9xuRrGSCGeMVs9iv09uMqwsVX7EeIpgV2c= +github.com/btcsuite/btcd v0.22.1/go.mod h1:wqgTSL29+50LRkmOVknEdmt8ZojIzhuWvgu/iptuN7Y= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U= github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= github.com/btcsuite/btcutil v0.0.0-20180706230648-ab6388e0c60a/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= github.com/btcsuite/btcutil v0.0.0-20190207003914-4c204d697803/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= @@ -1044,8 +1047,8 @@ github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4 github.com/ory/dockertest v3.3.5+incompatible/go.mod h1:1vX4m9wsvi00u5bseYwXaSnhNrne+V0E6LAcBILJdPs= github.com/ory/dockertest/v3 v3.9.1 h1:v4dkG+dlu76goxMiTT2j8zV7s4oPPEppKT8K8p2f1kY= github.com/ory/dockertest/v3 v3.9.1/go.mod h1:42Ir9hmvaAPm0Mgibk6mBPi7SFvTXxEcnztDYOJ//uM= -github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220620200611-3e46ff7501a1 h1:DGOm5SJcKVmgUVN8of2u4jj3vxEhAYs/+e+XqsxcrnQ= -github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220620200611-3e46ff7501a1/go.mod h1:pMiEr6WR7drhXAXK1FOdAKPazWCi7b+WOyWOF4O0OXY= +github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220714223138-b81ad24550fa h1:XN0dDQx8Lq3+/eCNRlT/rjUTcpDavLFfTYiVwvmFhL0= +github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220714223138-b81ad24550fa/go.mod h1:uUkGXyCWol+CHoaMxZA0nKglvlN5uHBCMbMSsZoGSAs= github.com/osmosis-labs/iavl v0.17.3-osmo-v7 h1:6KcADC/WhL7yDmNQxUIJt2XmzNt4FfRmq9gRke45w74= github.com/osmosis-labs/iavl v0.17.3-osmo-v7/go.mod h1:lJEOIlsd3sVO0JDyXWIXa9/Ur5FBscP26zJx0KxHjto= github.com/osmosis-labs/wasmd v0.27.0-rc2.0.20220517191021-59051aa18d58 h1:15l3Iss2oCGCeJRi2g3CuCnqmEjpAr3Le7cDnoN/LS0= @@ -1129,8 +1132,8 @@ github.com/prometheus/common v0.15.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16 github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= github.com/prometheus/common v0.30.0/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= -github.com/prometheus/common v0.33.0 h1:rHgav/0a6+uYgGdNt3jwz8FNSesO/Hsang3O0T9A5SE= -github.com/prometheus/common v0.33.0/go.mod h1:gB3sOl7P0TvJabZpLY5uQMpUqRCPPCyRLCZYc7JZTNE= +github.com/prometheus/common v0.34.0 h1:RBmGO9d/FVjqHT0yUGQwBJhkwKV+wPCn7KGpvfab0uE= +github.com/prometheus/common v0.34.0/go.mod h1:gB3sOl7P0TvJabZpLY5uQMpUqRCPPCyRLCZYc7JZTNE= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= diff --git a/wasmbinding/test/custom_query_test.go b/wasmbinding/test/custom_query_test.go index 270be30583f..0d6cf4c5889 100644 --- a/wasmbinding/test/custom_query_test.go +++ b/wasmbinding/test/custom_query_test.go @@ -308,7 +308,7 @@ func storeReflectCode(t *testing.T, ctx sdk.Context, osmosis *app.OsmosisApp, ad }) // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, src) + storedProposal, err := govKeeper.SubmitProposal(ctx, src, false) require.NoError(t, err) // and proposal execute diff --git a/wasmbinding/test/store_run_test.go b/wasmbinding/test/store_run_test.go index 25602540656..1df4a457ed5 100644 --- a/wasmbinding/test/store_run_test.go +++ b/wasmbinding/test/store_run_test.go @@ -44,7 +44,7 @@ func storeCodeViaProposal(t *testing.T, ctx sdk.Context, osmosis *app.OsmosisApp }) // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, src) + storedProposal, err := govKeeper.SubmitProposal(ctx, src, false) require.NoError(t, err) // and proposal execute From 17ebcc81f128eaf610e9a94cf7b8e47fcb680d02 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Mon, 18 Jul 2022 17:44:16 -0500 Subject: [PATCH 094/376] simulator: add gamm and tokenfactory messages (#2091) * initial push * Update simulation/types/account.go Co-authored-by: Dev Ojha * lint * switch to RandomGenesisState * no need for balance * Update x/tokenfactory/simulation/sim_msgs.go Co-authored-by: Dev Ojha * Fix merge conflict * Update x/gamm/simulation/sim_msgs.go Co-authored-by: Dev Ojha * switch to univ2 verbiage * Update x/gamm/simulation/sim_msgs.go Co-authored-by: Dev Ojha * address Dev comment * Fix merge conflict * name fix 2 * spelling * add mint token factory denom * update path from v7 to v10 * cap join pool to total pool liquidity * remove test logs * check if wallet has enough for pool creation fee * Reduce token factory complexity * Fix compilation issue * Fix second error * Some more updates * Fix lint * Move kludge to helper, fix lint * Fix build * Add log fix discussed in call Co-authored-by: Dev Ojha Co-authored-by: Dev Ojha --- osmoutils/coin_helper.go | 15 +++ osmoutils/iter_helper.go | 14 +++ simulation/types/account.go | 70 ++++++++++-- simulation/types/action.go | 3 + simulation/types/manager.go | 4 +- simulation/types/randutil.go | 8 +- simulation/types/txbuilder.go | 5 +- tests/simulator/sim_test.go | 2 +- x/gamm/module.go | 13 ++- x/gamm/simulation/sim_msgs.go | 154 ++++++++++++++++++++++---- x/tokenfactory/module.go | 23 ++++ x/tokenfactory/simulation/sim_msgs.go | 51 +++++++++ 12 files changed, 324 insertions(+), 38 deletions(-) create mode 100644 osmoutils/iter_helper.go create mode 100644 x/tokenfactory/simulation/sim_msgs.go diff --git a/osmoutils/coin_helper.go b/osmoutils/coin_helper.go index 77680435e68..07c802c162f 100644 --- a/osmoutils/coin_helper.go +++ b/osmoutils/coin_helper.go @@ -10,3 +10,18 @@ func CoinsDenoms(coins sdk.Coins) []string { } return denoms } + +// MinCoins returns the minimum of each denom between both coins. +// For now it assumes they have the same denoms. +// TODO: Replace with method in SDK once we update our version +func MinCoins(coinsA sdk.Coins, coinsB sdk.Coins) sdk.Coins { + resCoins := sdk.Coins{} + for i, coin := range coinsA { + if coinsB[i].Amount.GT(coin.Amount) { + resCoins = append(resCoins, coin) + } else { + resCoins = append(resCoins, coinsB[i]) + } + } + return resCoins +} diff --git a/osmoutils/iter_helper.go b/osmoutils/iter_helper.go new file mode 100644 index 00000000000..2f8a48abd03 --- /dev/null +++ b/osmoutils/iter_helper.go @@ -0,0 +1,14 @@ +package osmoutils + +import "github.com/cosmos/cosmos-sdk/store" + +func GatherAllKeysFromStore(storeObj store.KVStore) []string { + iterator := storeObj.Iterator(nil, nil) + defer iterator.Close() + + keys := []string{} + for ; iterator.Valid(); iterator.Next() { + keys = append(keys, string(iterator.Key())) + } + return keys +} diff --git a/simulation/types/account.go b/simulation/types/account.go index 670c345f12f..1719f56fad7 100644 --- a/simulation/types/account.go +++ b/simulation/types/account.go @@ -92,7 +92,61 @@ func (sim *SimCtx) SelAddrWithDenoms(ctx sdk.Context, denoms []string) (simulati return acc, sdk.Coins{}, false } balance := sim.RandCoinSubset(ctx, acc.Address, denoms) - return acc, balance, true + return acc, balance.Sort(), true +} + +// SelAddrWithDenom attempts to find an address with the provided denom. This function +// returns (account, randSubsetCoins, found), so if found = false, then no such address exists. +// randSubsetCoins is a random subset of the provided denoms, if the account is found. +// TODO: Write unit test +func (sim *SimCtx) SelAddrWithDenom(ctx sdk.Context, denom string) (simulation.Account, sdk.Coin, bool) { + acc, subsetCoins, found := sim.SelAddrWithDenoms(ctx, []string{denom}) + if !found { + return acc, sdk.Coin{}, found + } + return acc, subsetCoins[0], found +} + +// GetRandSubsetOfKDenoms returns a random subset of coins of k unique denoms from the provided account +// TODO: Write unit test +func (sim *SimCtx) GetRandSubsetOfKDenoms(ctx sdk.Context, acc simulation.Account, k int) (sdk.Coins, bool) { + // get all spendable coins from provided account + coins := sim.BankKeeper().SpendableCoins(ctx, acc.Address) + // ensure account coins are greater than or equal to the requested subset length + if len(coins) < k { + return sdk.Coins{}, false + } + // randomly remove a denom from the coins array until we reach desired length + r := sim.GetSeededRand("select random seed") + + for len(coins) != k { + index := r.Intn(len(coins) - 1) + coins = RemoveIndex(coins, index) + } + // append random amount less than or equal to existing amount to new subset array + subset := sdk.Coins{} + for _, c := range coins { + amt, err := simulation.RandPositiveInt(r, c.Amount) + if err != nil { + return sdk.Coins{}, false + } + subset = append(subset, sdk.NewCoin(c.Denom, amt)) + } + + // return nothing if the coin struct length is less than requested (sanity check) + if len(subset) < k { + return sdk.Coins{}, false + } + + return subset.Sort(), true +} + +// RandomSimAccountWithKDenoms returns an account that possesses k unique denoms +func (sim *SimCtx) RandomSimAccountWithKDenoms(ctx sdk.Context, k int) (simulation.Account, bool) { + accHasBal := func(acc simulation.Account) bool { + return len(sim.BankKeeper().SpendableCoins(ctx, acc.Address)) >= k + } + return sim.RandomSimAccountWithConstraint(accHasBal) } // RandGeometricCoin uniformly samples a denom from the addr's balances. @@ -125,10 +179,7 @@ func (sim *SimCtx) RandCoinSubset(ctx sdk.Context, addr sdk.AccAddress, denoms [ subsetCoins := sdk.Coins{} for _, denom := range denoms { bal := sim.BankKeeper().GetBalance(ctx, addr, denom) - amt, err := sim.RandPositiveInt(bal.Amount) - if err != nil { - panic(err) - } + amt := sim.RandPositiveInt(bal.Amount) subsetCoins = subsetCoins.Add(sdk.NewCoin(bal.Denom, amt)) } return subsetCoins @@ -157,10 +208,7 @@ func (sim *SimCtx) RandomFees(ctx sdk.Context, spendableCoins sdk.Coins) (sdk.Co return nil, fmt.Errorf("no coins found for random fees") } - amt, err := sim.RandPositiveInt(randCoin.Amount) - if err != nil { - return nil, err - } + amt := sim.RandPositiveInt(randCoin.Amount) // Create a random fee and verify the fees are within the account's spendable // balance. @@ -168,3 +216,7 @@ func (sim *SimCtx) RandomFees(ctx sdk.Context, spendableCoins sdk.Coins) (sdk.Co return fees, nil } + +func RemoveIndex(s sdk.Coins, index int) sdk.Coins { + return append(s[:index], s[index+1:]...) +} diff --git a/simulation/types/action.go b/simulation/types/action.go index 0d1830556f6..b95a7b11a69 100644 --- a/simulation/types/action.go +++ b/simulation/types/action.go @@ -77,6 +77,9 @@ func NewCurriedMsgBasedAction[K interface{}, M sdk.Msg](actionName string, k K, return NewMsgBasedAction(actionName, msgGenerator) } +// TODO: make API in simulator action collection interface +// to add a 'modulename' to many actions + type msgBasedAction struct { name string weight Weight diff --git a/simulation/types/manager.go b/simulation/types/manager.go index b45f4ee9be6..f79d8d15bcb 100644 --- a/simulation/types/manager.go +++ b/simulation/types/manager.go @@ -26,7 +26,7 @@ type AppModuleSimulationV2 interface { type AppModuleSimulationV2WithRandGenesis interface { AppModuleSimulationV2 // TODO: Come back and improve SimulationState interface - RandomGenesisState(*module.SimulationState, *SimCtx) + GenerateGenesisState(*module.SimulationState, *SimCtx) } // SimulationManager defines a simulation manager that provides the high level utility @@ -141,7 +141,7 @@ func (m Manager) GenerateGenesisStates(simState *module.SimulationState, sim *Si if simModule, ok := m.Modules[moduleName]; ok { // if we define a random genesis function use it, otherwise use default genesis if mod, ok := simModule.(AppModuleSimulationV2WithRandGenesis); ok { - mod.RandomGenesisState(simState, sim) + mod.GenerateGenesisState(simState, sim) } else { simState.GenState[simModule.Name()] = simModule.DefaultGenesis(simState.Cdc) } diff --git a/simulation/types/randutil.go b/simulation/types/randutil.go index b6f21364ac7..18138b37524 100644 --- a/simulation/types/randutil.go +++ b/simulation/types/randutil.go @@ -32,9 +32,13 @@ func (sim *SimCtx) RandStringOfLength(n int) string { } // RandPositiveInt get a rand positive sdk.Int -func (sim *SimCtx) RandPositiveInt(max sdk.Int) (sdk.Int, error) { +func (sim *SimCtx) RandPositiveInt(max sdk.Int) sdk.Int { r := sim.GetSeededRand("random bounded positive int") - return sdkrand.RandPositiveInt(r, max) + v, err := sdkrand.RandPositiveInt(r, max) + if err != nil { + panic(err) + } + return v } // RandomAmount generates a random amount diff --git a/simulation/types/txbuilder.go b/simulation/types/txbuilder.go index a59a94cff79..112bf87b9a5 100644 --- a/simulation/types/txbuilder.go +++ b/simulation/types/txbuilder.go @@ -61,7 +61,10 @@ func (sim *SimCtx) deliverTx(tx sdk.Tx, msg sdk.Msg, msgName string) (simulation return simulation.NoOpMsg(msgName, msgName, fmt.Sprintf("unable to deliver tx. \nreason: %v\n results: %v\n msg: %s\n tx: %s", err, results, msg, tx)), nil, err } - return simulation.NewOperationMsg(msg, true, "", nil), nil, nil + opMsg := simulation.NewOperationMsg(msg, true, "", nil) + opMsg.Route = msgName + opMsg.Name = msgName + return opMsg, nil, nil } // GenTx generates a signed mock transaction. diff --git a/tests/simulator/sim_test.go b/tests/simulator/sim_test.go index 97b1212deef..1e344cecb63 100644 --- a/tests/simulator/sim_test.go +++ b/tests/simulator/sim_test.go @@ -40,7 +40,7 @@ func TestFullAppSimulation(t *testing.T) { // -Enabled=true -NumBlocks=1000 -BlockSize=200 \ // -Period=1 -Commit=true -Seed=57 -v -timeout 24h sdkSimapp.FlagEnabledValue = true - sdkSimapp.FlagNumBlocksValue = 100 + sdkSimapp.FlagNumBlocksValue = 200 sdkSimapp.FlagBlockSizeValue = 25 sdkSimapp.FlagCommitValue = true sdkSimapp.FlagVerboseValue = true diff --git a/x/gamm/module.go b/x/gamm/module.go index a5352f99272..4c20a91f3bb 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -158,10 +158,19 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val func (AppModule) ConsensusVersion() uint64 { return 1 } // **** simulation implementation **** +// GenerateGenesisState creates a randomized GenState of the gamm module. +func (am AppModule) GenerateGenesisState(simState *module.SimulationState, s *simulation.SimCtx) { + DefaultGen := types.DefaultGenesis() + // change the pool creation fee denom from uosmo to stake + DefaultGen.Params.PoolCreationFee = sdk.NewCoins(gammsimulation.PoolCreationFee) + DefaultGenJson := simState.Cdc.MustMarshalJSON(DefaultGen) + simState.GenState[types.ModuleName] = DefaultGenJson +} func (am AppModule) Actions() []simulation.Action { return []simulation.Action{ - simulation.NewMsgBasedAction("MsgJoinPool", gammsimulation.CurrySimMsgJoinPool(am.keeper)), - simulation.NewCurriedMsgBasedAction("Msg create univ2 pool", am.keeper, gammsimulation.RandomCreateUniv2PoolMsg), + simulation.NewCurriedMsgBasedAction("MsgJoinPool", am.keeper, gammsimulation.RandomJoinPoolMsg), + simulation.NewCurriedMsgBasedAction("MsgExitPool", am.keeper, gammsimulation.RandomExitPoolMsg), + simulation.NewCurriedMsgBasedAction("CreateUniV2Msg", am.keeper, gammsimulation.RandomCreateUniV2Msg), } } diff --git a/x/gamm/simulation/sim_msgs.go b/x/gamm/simulation/sim_msgs.go index bb6fe0dc672..ed871f28652 100644 --- a/x/gamm/simulation/sim_msgs.go +++ b/x/gamm/simulation/sim_msgs.go @@ -1,52 +1,164 @@ package gammsimulation import ( + "errors" "fmt" - "github.com/cosmos/cosmos-sdk/server/rosetta/lib/errors" sdk "github.com/cosmos/cosmos-sdk/types" + legacysimulationtype "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/osmosis-labs/osmosis/v10/osmoutils" simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" balancertypes "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" - gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) -func CurrySimMsgJoinPool(k keeper.Keeper) func(sim *simulation.SimCtx, ctx sdk.Context) (*gammtypes.MsgJoinPool, error) { - return func(sim *simulation.SimCtx, ctx sdk.Context) (*gammtypes.MsgJoinPool, error) { - return RandomJoinPoolMsg(k, sim, ctx) - } -} +var ( + PoolCreationFee = sdk.NewInt64Coin("stake", 10_000_000) +) -func RandomJoinPoolMsg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*gammtypes.MsgJoinPool, error) { - // Get pool +// RandomJoinPoolMsg pseudo-randomly selects an existing pool ID, attempts to find an account with the +// respective underlying token denoms, and attempts to execute a join pool transaction +func RandomJoinPoolMsg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgJoinPool, error) { + // get random pool pool_id := simulation.RandLTBound(sim, k.GetNextPoolNumber(ctx)) pool, err := k.GetPoolAndPoke(ctx, pool_id) if err != nil { - return &gammtypes.MsgJoinPool{}, err + return &types.MsgJoinPool{}, err } - // Get address that has all denoms in the pool + // get address that has all denoms from the randomly selected pool poolDenoms := osmoutils.CoinsDenoms(pool.GetTotalPoolLiquidity(ctx)) - sender, tokenInMaxs, senderExists := sim.SelAddrWithDenoms(ctx, poolDenoms) + sender, tokenIn, senderExists := sim.SelAddrWithDenoms(ctx, poolDenoms) if !senderExists { - return &gammtypes.MsgJoinPool{}, fmt.Errorf("no sender with denoms %s exists", poolDenoms) + return &types.MsgJoinPool{}, fmt.Errorf("no sender with denoms %s exists", poolDenoms) + } + // cap joining pool to double the pool liquidity + tokenIn = osmoutils.MinCoins(tokenIn, pool.GetTotalPoolLiquidity(ctx)) + + // TODO: Fix API so this is a one liner, pool.CalcJoinPoolNoSwapShares() + minShareOutAmt, err := deriveRealMinShareOutAmt(ctx, tokenIn, pool) + if err != nil { + return &types.MsgJoinPool{}, err } + // TODO: Make FuzzTokenSubset API, token_in_maxs := sim.FuzzTokensSubset(sender, poolDenoms) // TODO: Add some slippage tolerance - minShareOutAmt, _, _ := pool.CalcJoinPoolShares(ctx, tokenInMaxs, pool.GetSwapFee(ctx)) // TODO: Make MinShareOutAmt fuzz API: minShareOutAmt = sim.FuzzEqualInt(share_out_amount) - return &gammtypes.MsgJoinPool{ + return &types.MsgJoinPool{ Sender: sender.Address.String(), PoolId: pool_id, ShareOutAmount: minShareOutAmt, - TokenInMaxs: tokenInMaxs, + TokenInMaxs: tokenIn, + }, nil +} + +// TODO: Fix CalcJoinPoolShares API so we don't have to do this +func deriveRealMinShareOutAmt(ctx sdk.Context, tokenIn sdk.Coins, pool types.PoolI) (sdk.Int, error) { + minShareOutAmt, _, err := pool.CalcJoinPoolShares(ctx, tokenIn, pool.GetSwapFee(ctx)) + if err != nil { + return sdk.Int{}, err + } + + totalSharesAmount := pool.GetTotalShares() + // shareRatio is the desired number of shares, divided by the total number of + // shares currently in the pool. It is intended to be used in scenarios where you want + shareRatio := minShareOutAmt.ToDec().QuoInt(totalSharesAmount) + if shareRatio.LTE(sdk.ZeroDec()) { + return sdk.Int{}, fmt.Errorf("share ratio is zero or negative") + } + + poolLiquidity := pool.GetTotalPoolLiquidity(ctx) + neededLpLiquidity := sdk.Coins{} + + for _, coin := range poolLiquidity { + // (coin.Amt * shareRatio).Ceil() + neededAmt := coin.Amount.ToDec().Mul(shareRatio).Ceil().RoundInt() + if neededAmt.LTE(sdk.ZeroInt()) { + return sdk.Int{}, fmt.Errorf("Too few shares out wanted") + } + neededCoin := sdk.Coin{Denom: coin.Denom, Amount: neededAmt} + neededLpLiquidity = neededLpLiquidity.Add(neededCoin) + } + + if tokenIn.Len() != 0 { + if !(neededLpLiquidity.DenomsSubsetOf(tokenIn) && tokenIn.IsAllGTE(neededLpLiquidity)) { + return sdk.Int{}, fmt.Errorf("TokenInMaxs is less than the needed LP liquidity to this JoinPoolNoSwap,"+ + " upperbound: %v, needed %v", tokenIn, neededLpLiquidity) + } else if !(tokenIn.DenomsSubsetOf(neededLpLiquidity)) { + return sdk.Int{}, fmt.Errorf("TokenInMaxs includes tokens that are not part of the target pool,"+ + " input tokens: %v, pool tokens %v", tokenIn, neededLpLiquidity) + } + } + + return minShareOutAmt, nil +} + +// RandomExitPoolMsg pseudo-randomly selects an existing pool ID, attempts to find an account with the +// respective unbonded gamm shares, and attempts to execute an exit pool transaction +func RandomExitPoolMsg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgExitPool, error) { + // select a pseudo-random pool ID, max bound by the upcoming pool ID + pool_id := simulation.RandLTBound(sim, k.GetNextPoolNumber(ctx)) + pool, err := k.GetPoolAndPoke(ctx, pool_id) + if err != nil { + return &types.MsgExitPool{}, err + } + // select an address that has gamm shares of the selected pool + gammDenom := types.GetPoolShareDenom(pool_id) + sender, gammShares, senderExists := sim.SelAddrWithDenom(ctx, gammDenom) + if !senderExists { + return &types.MsgExitPool{}, fmt.Errorf("no sender with denom %s exists", gammDenom) + } + // calculate the minimum number of tokens received from input of gamm shares + tokenOutMins, _ := pool.CalcExitPoolCoinsFromShares(ctx, gammShares.Amount, pool.GetExitFee(ctx)) + return &types.MsgExitPool{ + Sender: sender.Address.String(), + PoolId: pool_id, + ShareInAmount: gammShares.Amount, + TokenOutMins: tokenOutMins, + }, nil +} + +// RandomCreatePoolMsg attempts to find an account with two or more distinct denoms and attempts to send a +// create pool message composed of those denoms +func RandomCreateUniV2Msg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*balancertypes.MsgCreateBalancerPool, error) { + var poolAssets []balancertypes.PoolAsset + // find an address with two or more distinct denoms in their wallet + sender, senderExists := sim.RandomSimAccountWithConstraint(createPoolRestriction(k, sim, ctx)) + if !senderExists { + return &balancertypes.MsgCreateBalancerPool{}, errors.New("no sender with two different denoms & pool creation fee exists") + } + poolCoins, _ := sim.GetRandSubsetOfKDenoms(ctx, sender, 2) + if poolCoins.Add(PoolCreationFee).IsAnyGT(sim.BankKeeper().SpendableCoins(ctx, sender.Address)) { + return &balancertypes.MsgCreateBalancerPool{}, errors.New("chose an account / creation amount that didn't pass fee bar") + } + + // TODO: pseudo-randomly generate swap and exit fees + poolParams := &balancertypes.PoolParams{ + SwapFee: sdk.NewDecWithPrec(1, 2), + ExitFee: sdk.ZeroDec(), + } + + // from the above selected account, determine the token type and respective weight needed to make the pool + for i := 0; i < len(poolCoins); i++ { + poolAssets = append(poolAssets, balancertypes.PoolAsset{ + Weight: sdk.OneInt(), + Token: poolCoins[i], + }) + } + return &balancertypes.MsgCreateBalancerPool{ + Sender: sender.Address.String(), + PoolParams: poolParams, + PoolAssets: poolAssets, }, nil } -func RandomCreateUniv2PoolMsg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*balancertypes.MsgCreateBalancerPool, error) { - // 1) Select two denoms, ideally with some frequency weighting based on distribution amongst addrs - // 2) Select sender with both denoms + creation fee - // 3) Create pool - return nil, errors.ErrNotImplemented +func createPoolRestriction(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) simulation.SimAccountConstraint { + return func(acc legacysimulationtype.Account) bool { + accCoins := sim.BankKeeper().SpendableCoins(ctx, acc.Address) + hasTwoCoins := len(accCoins) >= 2 + hasPoolCreationFee := accCoins.AmountOf("stake").GT(PoolCreationFee.Amount) + return hasTwoCoins && hasPoolCreationFee + } } diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index 67aee24683a..b9b350a43c8 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -15,6 +15,9 @@ import ( "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" + simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + tokenfactorysimulation "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/simulation" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/client/cli" "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" @@ -170,3 +173,23 @@ func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } + +// ___________________________________________________________________________ + +// AppModuleSimulationV2 functions + +// GenerateGenesisState creates a randomized GenState of the tokenfactory module. +func (am AppModule) GenerateGenesisState(simState *module.SimulationState, s *simulation.SimCtx) { + tfDefaultGen := types.DefaultGenesis() + tfDefaultGen.Params.DenomCreationFee = sdk.NewCoins(sdk.NewInt64Coin("stake", 10_000_000)) + tfDefaultGenJson := simState.Cdc.MustMarshalJSON(tfDefaultGen) + simState.GenState[types.ModuleName] = tfDefaultGenJson +} + +// WeightedOperations returns the all the lockup module operations with their respective weights. +func (am AppModule) Actions() []simulation.Action { + return []simulation.Action{ + simulation.NewCurriedMsgBasedAction("create token factory token", am.keeper, tokenfactorysimulation.RandomMsgCreateDenom), + simulation.NewCurriedMsgBasedAction("mint token factory token", am.keeper, tokenfactorysimulation.RandomMsgMintDenom), + } +} diff --git a/x/tokenfactory/simulation/sim_msgs.go b/x/tokenfactory/simulation/sim_msgs.go new file mode 100644 index 00000000000..3398aa9c13e --- /dev/null +++ b/x/tokenfactory/simulation/sim_msgs.go @@ -0,0 +1,51 @@ +package simulation + +import ( + "errors" + + legacysimulationtype "github.com/cosmos/cosmos-sdk/types/simulation" + + "github.com/osmosis-labs/osmosis/v10/osmoutils" + simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" + "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// RandomMsgCreateDenom creates a random tokenfactory denom that is no greater than 44 alphanumeric characters +func RandomMsgCreateDenom(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgCreateDenom, error) { + return &types.MsgCreateDenom{ + Sender: sim.RandomSimAccount().Address.String(), + Subdenom: sim.RandStringOfLength(types.MaxSubdenomLength), + }, nil +} + +func RandomMsgMintDenom(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgMint, error) { + acc, senderExists := sim.RandomSimAccountWithConstraint(accountCreatedTokenFactoryDenom(k, ctx)) + if !senderExists { + return nil, errors.New("no addr has created a tokenfactory coin") + } + // Pick denom + store := k.GetCreatorPrefixStore(ctx, acc.Address.String()) + denoms := osmoutils.GatherAllKeysFromStore(store) + denom := simulation.RandSelect(sim, denoms...) + + // TODO: Replace with an improved rand exponential coin + mintAmount := sim.RandPositiveInt(sdk.NewIntFromUint64(1000_000000)) + return &types.MsgMint{ + Sender: acc.Address.String(), + Amount: sdk.NewCoin(denom, mintAmount), + }, nil +} + +// TODO: We are going to need to index the owner of an account as well, rather than creator +// to simulate admin changes +func accountCreatedTokenFactoryDenom(k keeper.Keeper, ctx sdk.Context) simulation.SimAccountConstraint { + return func(acc legacysimulationtype.Account) bool { + store := k.GetCreatorPrefixStore(ctx, acc.Address.String()) + iterator := store.Iterator(nil, nil) + defer iterator.Close() + return iterator.Valid() + } +} From e5ffb813c624772051b636f3634aac6dabb2a409 Mon Sep 17 00:00:00 2001 From: Sishir Giri Date: Mon, 18 Jul 2022 15:45:43 -0700 Subject: [PATCH 095/376] refactor(x/mint, x/gamm errors): move errors in mint and gamm keeper to errors.go (#2067) * moved mint errors * errors formatted * rom and bez feedback * rebased * addressed all comments --- x/gamm/pool-models/balancer/amm.go | 4 +-- x/gamm/pool-models/balancer/export_test.go | 6 ++-- x/gamm/pool-models/balancer/pool.go | 32 +++++++++++----------- x/gamm/types/errors.go | 1 + x/mint/keeper/export_test.go | 4 --- x/mint/keeper/keeper.go | 14 +++------- x/mint/keeper/keeper_test.go | 12 ++++---- x/mint/types/errors.go | 11 ++++++++ 8 files changed, 43 insertions(+), 41 deletions(-) create mode 100644 x/mint/types/errors.go diff --git a/x/gamm/pool-models/balancer/amm.go b/x/gamm/pool-models/balancer/amm.go index d24714d5a2c..150a8595d2a 100644 --- a/x/gamm/pool-models/balancer/amm.go +++ b/x/gamm/pool-models/balancer/amm.go @@ -151,7 +151,7 @@ func getPoolAssetsByDenom(poolAssets []PoolAsset) (map[string]PoolAsset, error) for _, poolAsset := range poolAssets { _, ok := poolAssetsByDenom[poolAsset.Token.Denom] if ok { - return nil, fmt.Errorf(errMsgFormatRepeatingPoolAssetsNotAllowed, poolAsset.Token.Denom) + return nil, fmt.Errorf(formatRepeatingPoolAssetsNotAllowedErrFormat, poolAsset.Token.Denom) } poolAssetsByDenom[poolAsset.Token.Denom] = poolAsset @@ -174,7 +174,7 @@ func updateIntermediaryPoolAssetsLiquidity(liquidity sdk.Coins, poolAssetsByDeno for _, coin := range liquidity { poolAsset, ok := poolAssetsByDenom[coin.Denom] if !ok { - return fmt.Errorf(errMsgFormatFailedInterimLiquidityUpdate, coin.Denom) + return fmt.Errorf(failedInterimLiquidityUpdateErrFormat, coin.Denom) } poolAsset.Token.Amount = poolAssetsByDenom[coin.Denom].Token.Amount.Add(coin.Amount) diff --git a/x/gamm/pool-models/balancer/export_test.go b/x/gamm/pool-models/balancer/export_test.go index 75677b7e559..5f65f9c2c0e 100644 --- a/x/gamm/pool-models/balancer/export_test.go +++ b/x/gamm/pool-models/balancer/export_test.go @@ -3,12 +3,12 @@ package balancer import sdk "github.com/cosmos/cosmos-sdk/types" const ( - ErrMsgFormatRepeatingPoolAssetsNotAllowed = errMsgFormatRepeatingPoolAssetsNotAllowed - ErrMsgFormatNoPoolAssetFound = errMsgFormatNoPoolAssetFound + ErrMsgFormatRepeatingPoolAssetsNotAllowed = formatRepeatingPoolAssetsNotAllowedErrFormat + ErrMsgFormatNoPoolAssetFound = formatNoPoolAssetFoundErrFormat ) var ( - ErrMsgFormatFailedInterimLiquidityUpdate = errMsgFormatFailedInterimLiquidityUpdate + ErrMsgFormatFailedInterimLiquidityUpdate = failedInterimLiquidityUpdateErrFormat CalcPoolSharesOutGivenSingleAssetIn = calcPoolSharesOutGivenSingleAssetIn CalcSingleAssetInGivenPoolSharesOut = calcSingleAssetInGivenPoolSharesOut diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index f0c887b7bd8..51e82bd64d6 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -17,14 +17,14 @@ import ( //nolint:deadcode const ( - errMsgFormatSharesAmountNotPositive = "shares amount must be positive, was %d" - errMsgFormatTokenAmountNotPositive = "token amount must be positive, was %d" - errMsgFormatTokensLargerThanMax = "%d resulted tokens is larger than the max amount of %d" - errMsgFormatSharesLargerThanMax = "%d resulted shares is larger than the max amount of %d" - errMsgFormatFailedInterimLiquidityUpdate = "failed to update interim liquidity - pool asset %s does not exist" - errMsgFormatRepeatingPoolAssetsNotAllowed = "repeating pool assets not allowed, found %s" - errMsgFormatNoPoolAssetFound = "can't find the PoolAsset (%s)" - errMsgFormatInvalidInputDenoms = "input denoms must already exist in the pool (%s)" + nonPostiveSharesAmountErrFormat = "shares amount must be positive, was %d" + nonPostiveTokenAmountErrFormat = "token amount must be positive, was %d" + sharesLargerThanMaxErrFormat = "%d resulted shares is larger than the max amount of %d" + invalidInputDenomsErrFormat = "input denoms must already exist in the pool (%s)" + + failedInterimLiquidityUpdateErrFormat = "failed to update interim liquidity - pool asset %s does not exist" + formatRepeatingPoolAssetsNotAllowedErrFormat = "repeating pool assets not allowed, found %s" + formatNoPoolAssetFoundErrFormat = "can't find the PoolAsset (%s)" ) var ( @@ -223,7 +223,7 @@ func (p Pool) getPoolAssetAndIndex(denom string) (int, PoolAsset, error) { } if len(p.PoolAssets) == 0 { - return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) + return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(formatNoPoolAssetFoundErrFormat, denom)) } i := sort.Search(len(p.PoolAssets), func(i int) bool { @@ -234,11 +234,11 @@ func (p Pool) getPoolAssetAndIndex(denom string) (int, PoolAsset, error) { }) if i < 0 || i >= len(p.PoolAssets) { - return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) + return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(formatNoPoolAssetFoundErrFormat, denom)) } if p.PoolAssets[i].Token.Denom != denom { - return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(errMsgFormatNoPoolAssetFound, denom)) + return -1, PoolAsset{}, sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, fmt.Sprintf(formatNoPoolAssetFoundErrFormat, denom)) } return i, p.PoolAssets[i], nil @@ -692,7 +692,7 @@ func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee s for _, coin := range tokensIn { _, ok := poolAssetsByDenom[coin.Denom] if !ok { - return sdk.ZeroInt(), sdk.NewCoins(), fmt.Errorf(errMsgFormatInvalidInputDenoms, coin.Denom) + return sdk.ZeroInt(), sdk.NewCoins(), sdkerrors.Wrapf(types.ErrDenomAlreadyInPool, invalidInputDenomsErrFormat, coin.Denom) } } @@ -827,7 +827,7 @@ func (p *Pool) CalcTokenInShareAmountOut( ).Ceil().TruncateInt() if !tokenInAmount.IsPositive() { - return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatTokenAmountNotPositive, tokenInAmount.Int64()) + return sdk.Int{}, sdkerrors.Wrapf(types.ErrNotPositiveRequireAmount, nonPostiveTokenAmountErrFormat, tokenInAmount.Int64()) } return tokenInAmount, nil @@ -854,7 +854,7 @@ func (p *Pool) JoinPoolTokenInMaxShareAmountOut( ).TruncateInt() if !tokenInAmount.IsPositive() { - return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatTokenAmountNotPositive, tokenInAmount.Int64()) + return sdk.Int{}, sdkerrors.Wrapf(types.ErrNotPositiveRequireAmount, nonPostiveTokenAmountErrFormat, tokenInAmount.Int64()) } poolAssetIn.Token.Amount = poolAssetIn.Token.Amount.Add(tokenInAmount) @@ -886,11 +886,11 @@ func (p *Pool) ExitSwapExactAmountOut( ).TruncateInt() if !sharesIn.IsPositive() { - return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatSharesAmountNotPositive, sharesIn.Int64()) + return sdk.Int{}, sdkerrors.Wrapf(types.ErrNotPositiveRequireAmount, nonPostiveSharesAmountErrFormat, sharesIn.Int64()) } if sharesIn.GT(shareInMaxAmount) { - return sdk.Int{}, sdkerrors.Wrapf(types.ErrLimitMaxAmount, errMsgFormatSharesLargerThanMax, sharesIn.Int64(), shareInMaxAmount.Uint64()) + return sdk.Int{}, sdkerrors.Wrapf(types.ErrLimitMaxAmount, sharesLargerThanMaxErrFormat, sharesIn.Int64(), shareInMaxAmount.Uint64()) } if err := p.exitPool(ctx, sdk.NewCoins(tokenOut), sharesIn); err != nil { diff --git a/x/gamm/types/errors.go b/x/gamm/types/errors.go index faa26df35dc..dcf6dc70cdf 100644 --- a/x/gamm/types/errors.go +++ b/x/gamm/types/errors.go @@ -15,6 +15,7 @@ var ( ErrAlreadyInvalidPool = sdkerrors.Register(ModuleName, 9, "destruction on already invalid pool") ErrInvalidPool = sdkerrors.Register(ModuleName, 10, "attempting to create an invalid pool") ErrDenomNotFoundInPool = sdkerrors.Register(ModuleName, 11, "denom does not exist in pool") + ErrDenomAlreadyInPool = sdkerrors.Register(ModuleName, 12, "denom already exists in the pool") ErrEmptyRoutes = sdkerrors.Register(ModuleName, 21, "routes not defined") ErrEmptyPoolAssets = sdkerrors.Register(ModuleName, 22, "PoolAssets not defined") diff --git a/x/mint/keeper/export_test.go b/x/mint/keeper/export_test.go index 888411f125f..6c27f1aebbb 100644 --- a/x/mint/keeper/export_test.go +++ b/x/mint/keeper/export_test.go @@ -15,10 +15,6 @@ const ( ) var ( - ErrAmountCannotBeNilOrZero = errAmountCannotBeNilOrZero - ErrDevVestingModuleAccountAlreadyCreated = errDevVestingModuleAccountAlreadyCreated - ErrDevVestingModuleAccountNotCreated = errDevVestingModuleAccountNotCreated - GetProportions = getProportions ) diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index 93dab130363..cdcde523f81 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -1,7 +1,6 @@ package keeper import ( - "errors" "fmt" "github.com/tendermint/tendermint/libs/log" @@ -11,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) @@ -36,12 +36,6 @@ func (e invalidRatioError) Error() string { return fmt.Sprintf("mint allocation ratio (%s) is greater than 1", e.ActualRatio) } -var ( - errAmountCannotBeNilOrZero = errors.New("amount cannot be nil or zero") - errDevVestingModuleAccountAlreadyCreated = fmt.Errorf("%s module account already exists", types.DeveloperVestingModuleAcctName) - errDevVestingModuleAccountNotCreated = fmt.Errorf("%s module account does not exist", types.DeveloperVestingModuleAcctName) -) - // NewKeeper creates a new mint Keeper instance. func NewKeeper( cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace, @@ -79,7 +73,7 @@ func NewKeeper( // queries. The method returns an error if current height in ctx is greater than the v7 upgrade height. func (k Keeper) SetInitialSupplyOffsetDuringMigration(ctx sdk.Context) error { if !k.accountKeeper.HasAccount(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) { - return errDevVestingModuleAccountNotCreated + return sdkerrors.Wrapf(types.ErrModuleDoesnotExist, "%s vesting module account doesnot exist", types.DeveloperVestingModuleAcctName) } moduleAccBalance := k.bankKeeper.GetBalance(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), k.GetParams(ctx).MintDenom) @@ -96,10 +90,10 @@ func (k Keeper) SetInitialSupplyOffsetDuringMigration(ctx sdk.Context) error { // - developer vesting module account is already created prior to calling this method. func (k Keeper) CreateDeveloperVestingModuleAccount(ctx sdk.Context, amount sdk.Coin) error { if amount.IsNil() || amount.Amount.IsZero() { - return errAmountCannotBeNilOrZero + return sdkerrors.Wrap(types.ErrAmountNilOrZero, "amount cannot be nil or zero") } if k.accountKeeper.HasAccount(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) { - return errDevVestingModuleAccountAlreadyCreated + return sdkerrors.Wrapf(types.ErrModuleAccountAlreadyExist, "%s vesting module account already exist", types.DeveloperVestingModuleAcctName) } moduleAcc := authtypes.NewEmptyModuleAccount( diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 12eb528e3b1..ecde05b23c7 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -315,18 +315,18 @@ func (suite *KeeperTestSuite) TestCreateDeveloperVestingModuleAccount() { }, "nil amount": { blockHeight: 0, - expectedError: keeper.ErrAmountCannotBeNilOrZero, + expectedError: sdkerrors.Wrap(types.ErrAmountNilOrZero, "amount cannot be nil or zero"), }, "zero amount": { blockHeight: 0, amount: sdk.NewCoin("stake", sdk.NewInt(0)), - expectedError: keeper.ErrAmountCannotBeNilOrZero, + expectedError: sdkerrors.Wrap(types.ErrAmountNilOrZero, "amount cannot be nil or zero"), }, "module account is already created": { blockHeight: 0, amount: sdk.NewCoin("stake", sdk.NewInt(keeper.DeveloperVestingAmount)), isDeveloperModuleAccountCreated: true, - expectedError: keeper.ErrDevVestingModuleAccountAlreadyCreated, + expectedError: sdkerrors.Wrapf(types.ErrModuleAccountAlreadyExist, "%s vesting module account already exist", types.DeveloperVestingModuleAcctName), }, } @@ -340,7 +340,7 @@ func (suite *KeeperTestSuite) TestCreateDeveloperVestingModuleAccount() { if tc.expectedError != nil { suite.Error(actualError) - suite.Equal(actualError, tc.expectedError) + suite.ErrorIs(actualError, tc.expectedError) return } suite.NoError(actualError) @@ -361,7 +361,7 @@ func (suite *KeeperTestSuite) TestSetInitialSupplyOffsetDuringMigration() { }, "dev vesting module account does not exist": { blockHeight: 1, - expectedError: keeper.ErrDevVestingModuleAccountNotCreated, + expectedError: sdkerrors.Wrapf(types.ErrModuleDoesnotExist, "%s vesting module account doesnot exist", types.DeveloperVestingModuleAcctName), }, } @@ -380,7 +380,7 @@ func (suite *KeeperTestSuite) TestSetInitialSupplyOffsetDuringMigration() { if tc.expectedError != nil { suite.Error(actualError) - suite.Equal(actualError, tc.expectedError) + suite.ErrorIs(actualError, tc.expectedError) suite.Equal(supplyWithOffsetBefore.Amount, bankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount) suite.Equal(supplyOffsetBefore, bankKeeper.GetSupplyOffset(ctx, sdk.DefaultBondDenom)) diff --git a/x/mint/types/errors.go b/x/mint/types/errors.go new file mode 100644 index 00000000000..6f721cb74a7 --- /dev/null +++ b/x/mint/types/errors.go @@ -0,0 +1,11 @@ +package types + +import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +var ( + ErrAmountNilOrZero = sdkerrors.Register(ModuleName, 2, "amount cannot be nil or zero") + ErrModuleAccountAlreadyExist = sdkerrors.Register(ModuleName, 3, "module account already exists") + ErrModuleDoesnotExist = sdkerrors.Register(ModuleName, 4, "module account does not exist") +) From dcc44d9fe4c82933065b480e9855d173c3c6a271 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Mon, 18 Jul 2022 20:09:43 -0500 Subject: [PATCH 096/376] simulator: API changes (#2126) * rename to simtypes * simulation/types package to simulation/simtypes * gammsimulation and locksimulation to simulation * Rename currying API * Rename interface names * missed a file --- app/app.go | 6 +++--- app/modules.go | 10 +++++----- simulation/executor/mock_tendermint.go | 2 +- simulation/executor/operation.go | 2 +- simulation/executor/params.go | 2 +- simulation/executor/simulate.go | 2 +- simulation/executor/simulate_dev.go | 2 +- simulation/executor/util.go | 2 +- simulation/{types => simtypes}/account.go | 2 +- simulation/{types => simtypes}/action.go | 9 ++++----- simulation/{types => simtypes}/app.go | 2 +- .../{types => simtypes}/genesis_config.go | 2 +- .../{types => simtypes}/init_functions.go | 2 +- simulation/{types => simtypes}/legacy.go | 2 +- simulation/{types => simtypes}/manager.go | 20 +++++++++---------- .../{types => simtypes}/randmanager_test.go | 2 +- .../{types => simtypes}/random/sdkrand.go | 0 simulation/{types => simtypes}/randutil.go | 4 ++-- simulation/{types => simtypes}/simctx.go | 2 +- .../transitionmatrix/transition_matrix.go | 0 simulation/{types => simtypes}/txbuilder.go | 2 +- simulation/{types => simtypes}/weight.go | 2 +- tests/simulator/sim_test.go | 8 ++++---- tests/simulator/state.go | 8 ++++---- x/gamm/module.go | 18 ++++++++--------- x/gamm/simulation/sim_msgs.go | 14 ++++++------- x/incentives/simulation/operations.go | 6 +++--- x/lockup/module.go | 16 +++++++-------- x/lockup/simulation/operations.go | 16 +++++++-------- x/superfluid/simulation/operations.go | 8 ++++---- x/tokenfactory/module.go | 14 ++++++------- x/tokenfactory/simulation/sim_msgs.go | 10 +++++----- 32 files changed, 98 insertions(+), 99 deletions(-) rename simulation/{types => simtypes}/account.go (99%) rename simulation/{types => simtypes}/action.go (90%) rename simulation/{types => simtypes}/app.go (97%) rename simulation/{types => simtypes}/genesis_config.go (99%) rename simulation/{types => simtypes}/init_functions.go (98%) rename simulation/{types => simtypes}/legacy.go (99%) rename simulation/{types => simtypes}/manager.go (91%) rename simulation/{types => simtypes}/randmanager_test.go (99%) rename simulation/{types => simtypes}/random/sdkrand.go (100%) rename simulation/{types => simtypes}/randutil.go (96%) rename simulation/{types => simtypes}/simctx.go (99%) rename simulation/{types => simtypes}/transitionmatrix/transition_matrix.go (100%) rename simulation/{types => simtypes}/txbuilder.go (99%) rename simulation/{types => simtypes}/weight.go (88%) diff --git a/app/app.go b/app/app.go index cc3db5234ec..cdff0cfe18d 100644 --- a/app/app.go +++ b/app/app.go @@ -52,7 +52,7 @@ import ( v8 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v8" v9 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v9" _ "github.com/osmosis-labs/osmosis/v10/client/docs/statik" - simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" ) const appName = "OsmosisApp" @@ -128,7 +128,7 @@ type OsmosisApp struct { invCheckPeriod uint mm *module.Manager - sm *simulation.Manager + sm *simtypes.Manager configurator module.Configurator } @@ -361,7 +361,7 @@ func (app *OsmosisApp) InterfaceRegistry() types.InterfaceRegistry { } // SimulationManager implements the SimulationApp interface. -func (app *OsmosisApp) SimulationManager() *simulation.Manager { +func (app *OsmosisApp) SimulationManager() *simtypes.Manager { return app.sm } diff --git a/app/modules.go b/app/modules.go index b3ed20189ce..5a6562f4a36 100644 --- a/app/modules.go +++ b/app/modules.go @@ -43,7 +43,7 @@ import ( appparams "github.com/osmosis-labs/osmosis/v10/app/params" _ "github.com/osmosis-labs/osmosis/v10/client/docs/statik" "github.com/osmosis-labs/osmosis/v10/osmoutils/partialord" - simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" "github.com/osmosis-labs/osmosis/v10/x/epochs" epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "github.com/osmosis-labs/osmosis/v10/x/gamm" @@ -214,13 +214,13 @@ func createSimulationManager( app *OsmosisApp, encodingConfig appparams.EncodingConfig, skipGenesisInvariants bool, -) *simulation.Manager { +) *simtypes.Manager { appCodec := encodingConfig.Marshaler overrideModules := map[string]module.AppModuleSimulation{ authtypes.ModuleName: auth.NewAppModule(appCodec, *app.AccountKeeper, authsims.RandomGenesisAccounts), } - simulationManager := simulation.NewSimulationManager(*app.mm, overrideModules) + simulationManager := simtypes.NewSimulationManager(*app.mm, overrideModules) return &simulationManager } @@ -234,10 +234,10 @@ func (app *OsmosisApp) ModuleAccountAddrs() map[string]bool { return modAccAddrs } -func (app *OsmosisApp) GetAccountKeeper() simulation.AccountKeeper { +func (app *OsmosisApp) GetAccountKeeper() simtypes.AccountKeeper { return app.AppKeepers.AccountKeeper } -func (app *OsmosisApp) GetBankKeeper() simulation.BankKeeper { +func (app *OsmosisApp) GetBankKeeper() simtypes.BankKeeper { return app.AppKeepers.BankKeeper } diff --git a/simulation/executor/mock_tendermint.go b/simulation/executor/mock_tendermint.go index 33f463f1f23..2d4b46c841f 100644 --- a/simulation/executor/mock_tendermint.go +++ b/simulation/executor/mock_tendermint.go @@ -14,7 +14,7 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "golang.org/x/exp/maps" - markov "github.com/osmosis-labs/osmosis/v10/simulation/types/transitionmatrix" + markov "github.com/osmosis-labs/osmosis/v10/simulation/simtypes/transitionmatrix" ) type mockValidator struct { diff --git a/simulation/executor/operation.go b/simulation/executor/operation.go index 89e61d57744..353ff0b2c7c 100644 --- a/simulation/executor/operation.go +++ b/simulation/executor/operation.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/simulation" - simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" ) // entry kinds for use within OperationEntry diff --git a/simulation/executor/params.go b/simulation/executor/params.go index e3011aef7ff..2cfc3106c9b 100644 --- a/simulation/executor/params.go +++ b/simulation/executor/params.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/simulation" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - markov "github.com/osmosis-labs/osmosis/v10/simulation/types/transitionmatrix" + markov "github.com/osmosis-labs/osmosis/v10/simulation/simtypes/transitionmatrix" ) const ( diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index 0cfb9354cfd..2ea3de66ca1 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -19,7 +19,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/simulation" - simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" ) const AverageBlockTime = 6 * time.Second diff --git a/simulation/executor/simulate_dev.go b/simulation/executor/simulate_dev.go index 8d1faab0e4a..06b93d1c7d1 100644 --- a/simulation/executor/simulate_dev.go +++ b/simulation/executor/simulate_dev.go @@ -10,7 +10,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" ) type simState struct { diff --git a/simulation/executor/util.go b/simulation/executor/util.go index 85654166bbb..401b34421be 100644 --- a/simulation/executor/util.go +++ b/simulation/executor/util.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" ) func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) { diff --git a/simulation/types/account.go b/simulation/simtypes/account.go similarity index 99% rename from simulation/types/account.go rename to simulation/simtypes/account.go index 1719f56fad7..45c5b8c1555 100644 --- a/simulation/types/account.go +++ b/simulation/simtypes/account.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "errors" diff --git a/simulation/types/action.go b/simulation/simtypes/action.go similarity index 90% rename from simulation/types/action.go rename to simulation/simtypes/action.go index b95a7b11a69..f747f12a2e7 100644 --- a/simulation/types/action.go +++ b/simulation/simtypes/action.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "fmt" @@ -54,7 +54,7 @@ func actionsFromWeightedOperations(moduleName string, ops legacysimexec.Weighted var _ Action = msgBasedAction{} -func NewMsgBasedAction[M sdk.Msg](actionName string, msgGenerator func(sim *SimCtx, ctx sdk.Context) (M, error)) Action { +func NewKeeperlessMsgBasedAction[M sdk.Msg](actionName string, msgGenerator func(sim *SimCtx, ctx sdk.Context) (M, error)) Action { wrappedMsgGen := func(sim *SimCtx, ctx sdk.Context) (sdk.Msg, error) { return msgGenerator(sim, ctx) } @@ -65,16 +65,15 @@ func NewMsgBasedAction[M sdk.Msg](actionName string, msgGenerator func(sim *SimC return msgBasedAction{name: actionName, weight: Normal, msgGenerator: wrappedMsgGen} } -// TODO: Decide if I want NewMsgBasedAction to auto-curry func CurryMsgGenerator[K interface{}, M sdk.Msg](k K, f func(K, *SimCtx, sdk.Context) (M, error)) func(*SimCtx, sdk.Context) (M, error) { return func(sim *SimCtx, ctx sdk.Context) (M, error) { return f(k, sim, ctx) } } -func NewCurriedMsgBasedAction[K interface{}, M sdk.Msg](actionName string, k K, f func(K, *SimCtx, sdk.Context) (M, error)) Action { +func NewMsgBasedAction[K interface{}, M sdk.Msg](actionName string, k K, f func(K, *SimCtx, sdk.Context) (M, error)) Action { msgGenerator := CurryMsgGenerator(k, f) - return NewMsgBasedAction(actionName, msgGenerator) + return NewKeeperlessMsgBasedAction(actionName, msgGenerator) } // TODO: make API in simulator action collection interface diff --git a/simulation/types/app.go b/simulation/simtypes/app.go similarity index 97% rename from simulation/types/app.go rename to simulation/simtypes/app.go index e5a8e845bfc..852bddc5644 100644 --- a/simulation/types/app.go +++ b/simulation/simtypes/app.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "github.com/cosmos/cosmos-sdk/baseapp" diff --git a/simulation/types/genesis_config.go b/simulation/simtypes/genesis_config.go similarity index 99% rename from simulation/types/genesis_config.go rename to simulation/simtypes/genesis_config.go index 3790f0acb0f..aa2d5ed8d82 100644 --- a/simulation/types/genesis_config.go +++ b/simulation/simtypes/genesis_config.go @@ -1,4 +1,4 @@ -package simulation +package simtypes // SimulationState is the input parameters used on each of the module's randomized // GenesisState generator function diff --git a/simulation/types/init_functions.go b/simulation/simtypes/init_functions.go similarity index 98% rename from simulation/types/init_functions.go rename to simulation/simtypes/init_functions.go index b7009744d12..685052a5de4 100644 --- a/simulation/types/init_functions.go +++ b/simulation/simtypes/init_functions.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "math/rand" diff --git a/simulation/types/legacy.go b/simulation/simtypes/legacy.go similarity index 99% rename from simulation/types/legacy.go rename to simulation/simtypes/legacy.go index 3afee2e3970..bdf0638788c 100644 --- a/simulation/types/legacy.go +++ b/simulation/simtypes/legacy.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "math/rand" diff --git a/simulation/types/manager.go b/simulation/simtypes/manager.go similarity index 91% rename from simulation/types/manager.go rename to simulation/simtypes/manager.go index f79d8d15bcb..75b22c72971 100644 --- a/simulation/types/manager.go +++ b/simulation/simtypes/manager.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "encoding/json" @@ -16,24 +16,24 @@ import ( // AppModuleSimulation defines the standard functions that every module should expose // for the SDK blockchain simulator -type AppModuleSimulationV2 interface { +type AppModuleSimulation interface { module.AppModule Actions() []Action // PropertyTests() } -type AppModuleSimulationV2WithRandGenesis interface { - AppModuleSimulationV2 +type AppModuleSimulationGenesis interface { + AppModuleSimulation // TODO: Come back and improve SimulationState interface - GenerateGenesisState(*module.SimulationState, *SimCtx) + SimulatorGenesisState(*module.SimulationState, *SimCtx) } // SimulationManager defines a simulation manager that provides the high level utility // for managing and executing simulation functionalities for a group of modules type Manager struct { moduleManager module.Manager - Modules map[string]AppModuleSimulationV2 // map of all non-legacy app modules; + Modules map[string]AppModuleSimulation // map of all non-legacy app modules; legacyModules map[string]module.AppModuleSimulation // legacy app modules } @@ -42,7 +42,7 @@ func NewSimulationManager(manager module.Manager, overrideModules map[string]mod panic("manager.OrderInitGenesis is unset, needs to be set prior to creating simulation manager") } - simModules := map[string]AppModuleSimulationV2{} + simModules := map[string]AppModuleSimulation{} legacySimModules := map[string]module.AppModuleSimulation{} appModuleNamesSorted := maps.Keys(manager.Modules) sort.Strings(appModuleNamesSorted) @@ -55,7 +55,7 @@ func NewSimulationManager(manager module.Manager, overrideModules map[string]mod legacySimModules[moduleName] = simModule } else { appModule := manager.Modules[moduleName] - if simModule, ok := appModule.(AppModuleSimulationV2); ok { + if simModule, ok := appModule.(AppModuleSimulation); ok { simModules[moduleName] = simModule } else if simModule, ok := appModule.(module.AppModuleSimulation); ok { legacySimModules[moduleName] = simModule @@ -140,8 +140,8 @@ func (m Manager) GenerateGenesisStates(simState *module.SimulationState, sim *Si for _, moduleName := range m.moduleManager.OrderInitGenesis { if simModule, ok := m.Modules[moduleName]; ok { // if we define a random genesis function use it, otherwise use default genesis - if mod, ok := simModule.(AppModuleSimulationV2WithRandGenesis); ok { - mod.GenerateGenesisState(simState, sim) + if mod, ok := simModule.(AppModuleSimulationGenesis); ok { + mod.SimulatorGenesisState(simState, sim) } else { simState.GenState[simModule.Name()] = simModule.DefaultGenesis(simState.Cdc) } diff --git a/simulation/types/randmanager_test.go b/simulation/simtypes/randmanager_test.go similarity index 99% rename from simulation/types/randmanager_test.go rename to simulation/simtypes/randmanager_test.go index 4e7fa116d47..26488adf600 100644 --- a/simulation/types/randmanager_test.go +++ b/simulation/simtypes/randmanager_test.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "math/rand" diff --git a/simulation/types/random/sdkrand.go b/simulation/simtypes/random/sdkrand.go similarity index 100% rename from simulation/types/random/sdkrand.go rename to simulation/simtypes/random/sdkrand.go diff --git a/simulation/types/randutil.go b/simulation/simtypes/randutil.go similarity index 96% rename from simulation/types/randutil.go rename to simulation/simtypes/randutil.go index 18138b37524..53e21e11284 100644 --- a/simulation/types/randutil.go +++ b/simulation/simtypes/randutil.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "time" @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "golang.org/x/exp/constraints" - sdkrand "github.com/osmosis-labs/osmosis/v10/simulation/types/random" + sdkrand "github.com/osmosis-labs/osmosis/v10/simulation/simtypes/random" ) func RandLTBound[T constraints.Integer](sim *SimCtx, upperbound T) T { diff --git a/simulation/types/simctx.go b/simulation/simtypes/simctx.go similarity index 99% rename from simulation/types/simctx.go rename to simulation/simtypes/simctx.go index fb3b8c1ee4c..b6fed16ad98 100644 --- a/simulation/types/simctx.go +++ b/simulation/simtypes/simctx.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "crypto/sha256" diff --git a/simulation/types/transitionmatrix/transition_matrix.go b/simulation/simtypes/transitionmatrix/transition_matrix.go similarity index 100% rename from simulation/types/transitionmatrix/transition_matrix.go rename to simulation/simtypes/transitionmatrix/transition_matrix.go diff --git a/simulation/types/txbuilder.go b/simulation/simtypes/txbuilder.go similarity index 99% rename from simulation/types/txbuilder.go rename to simulation/simtypes/txbuilder.go index 112bf87b9a5..b4e68ddb736 100644 --- a/simulation/types/txbuilder.go +++ b/simulation/simtypes/txbuilder.go @@ -1,4 +1,4 @@ -package simulation +package simtypes import ( "errors" diff --git a/simulation/types/weight.go b/simulation/simtypes/weight.go similarity index 88% rename from simulation/types/weight.go rename to simulation/simtypes/weight.go index bd5f2e1f1b9..48a90443f01 100644 --- a/simulation/types/weight.go +++ b/simulation/simtypes/weight.go @@ -1,4 +1,4 @@ -package simulation +package simtypes type Weight int64 diff --git a/tests/simulator/sim_test.go b/tests/simulator/sim_test.go index 1e344cecb63..42949681fb1 100644 --- a/tests/simulator/sim_test.go +++ b/tests/simulator/sim_test.go @@ -16,10 +16,10 @@ import ( sdkSimapp "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/store" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/types/simulation" osmosim "github.com/osmosis-labs/osmosis/v10/simulation/executor" - simtypes "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" ) // Profile with: @@ -90,7 +90,7 @@ func fullAppSimulation(tb testing.TB, is_testing bool) { fauxMerkleModeOpt) initFns := simtypes.InitFunctions{ - RandomAccountFn: simtypes.WrapRandAccFnForResampling(simulation2.RandomAccounts, osmosis.ModuleAccountAddrs()), + RandomAccountFn: simtypes.WrapRandAccFnForResampling(simulation.RandomAccounts, osmosis.ModuleAccountAddrs()), AppInitialStateFn: AppStateFn(osmosis.AppCodec(), osmosis.SimulationManager()), } @@ -176,7 +176,7 @@ func TestAppStateDeterminism(t *testing.T) { ) initFns := simtypes.InitFunctions{ - RandomAccountFn: simtypes.WrapRandAccFnForResampling(simulation2.RandomAccounts, osmosis.ModuleAccountAddrs()), + RandomAccountFn: simtypes.WrapRandAccFnForResampling(simulation.RandomAccounts, osmosis.ModuleAccountAddrs()), AppInitialStateFn: AppStateFn(osmosis.AppCodec(), osmosis.SimulationManager()), } diff --git a/tests/simulator/state.go b/tests/simulator/state.go index a6b6cc46183..f53b733c712 100644 --- a/tests/simulator/state.go +++ b/tests/simulator/state.go @@ -8,7 +8,7 @@ import ( "time" "github.com/osmosis-labs/osmosis/v10/app" - simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + osmosimtypes "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" "github.com/cosmos/cosmos-sdk/codec" sdksimapp "github.com/cosmos/cosmos-sdk/simapp" @@ -24,7 +24,7 @@ import ( // AppStateFn returns the initial application state using a genesis or the simulation parameters. // It panics if the user provides files for both of them. // If a file is not given for the genesis or the sim params, it creates a randomized one. -func AppStateFn(cdc codec.JSONCodec, simManager *simulation.Manager) simtypes.AppStateFn { +func AppStateFn(cdc codec.JSONCodec, simManager *osmosimtypes.Manager) simtypes.AppStateFn { return func(r *rand.Rand, accs []simtypes.Account, config simtypes.Config, ) (appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time) { if sdksimapp.FlagGenesisTimeValue == 0 { @@ -138,7 +138,7 @@ func AppStateFn(cdc codec.JSONCodec, simManager *simulation.Manager) simtypes.Ap // AppStateRandomizedFn creates calls each module's GenesisState generator function // and creates the simulation params. func AppStateRandomizedFn( - simManager *simulation.Manager, r *rand.Rand, cdc codec.JSONCodec, + simManager *osmosimtypes.Manager, r *rand.Rand, cdc codec.JSONCodec, accs []simtypes.Account, genesisTimestamp time.Time, appParams simtypes.AppParams, ) (json.RawMessage, []simtypes.Account) { numAccs := int64(len(accs)) @@ -180,7 +180,7 @@ func AppStateRandomizedFn( GenTimestamp: genesisTimestamp, } - simManager.GenerateGenesisStates(simState, &simulation.SimCtx{}) + simManager.GenerateGenesisStates(simState, &osmosimtypes.SimCtx{}) appState, err := json.Marshal(genesisState) if err != nil { diff --git a/x/gamm/module.go b/x/gamm/module.go index 4c20a91f3bb..21c215ea2b2 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -16,11 +16,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" "github.com/osmosis-labs/osmosis/v10/x/gamm/client/cli" "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" - gammsimulation "github.com/osmosis-labs/osmosis/v10/x/gamm/simulation" + simulation "github.com/osmosis-labs/osmosis/v10/x/gamm/simulation" "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) @@ -159,18 +159,18 @@ func (AppModule) ConsensusVersion() uint64 { return 1 } // **** simulation implementation **** // GenerateGenesisState creates a randomized GenState of the gamm module. -func (am AppModule) GenerateGenesisState(simState *module.SimulationState, s *simulation.SimCtx) { +func (am AppModule) SimulatorGenesisState(simState *module.SimulationState, s *simtypes.SimCtx) { DefaultGen := types.DefaultGenesis() // change the pool creation fee denom from uosmo to stake - DefaultGen.Params.PoolCreationFee = sdk.NewCoins(gammsimulation.PoolCreationFee) + DefaultGen.Params.PoolCreationFee = sdk.NewCoins(simulation.PoolCreationFee) DefaultGenJson := simState.Cdc.MustMarshalJSON(DefaultGen) simState.GenState[types.ModuleName] = DefaultGenJson } -func (am AppModule) Actions() []simulation.Action { - return []simulation.Action{ - simulation.NewCurriedMsgBasedAction("MsgJoinPool", am.keeper, gammsimulation.RandomJoinPoolMsg), - simulation.NewCurriedMsgBasedAction("MsgExitPool", am.keeper, gammsimulation.RandomExitPoolMsg), - simulation.NewCurriedMsgBasedAction("CreateUniV2Msg", am.keeper, gammsimulation.RandomCreateUniV2Msg), +func (am AppModule) Actions() []simtypes.Action { + return []simtypes.Action{ + simtypes.NewMsgBasedAction("MsgJoinPool", am.keeper, simulation.RandomJoinPoolMsg), + simtypes.NewMsgBasedAction("MsgExitPool", am.keeper, simulation.RandomExitPoolMsg), + simtypes.NewMsgBasedAction("CreateUniV2Msg", am.keeper, simulation.RandomCreateUniV2Msg), } } diff --git a/x/gamm/simulation/sim_msgs.go b/x/gamm/simulation/sim_msgs.go index ed871f28652..d26a6fa5948 100644 --- a/x/gamm/simulation/sim_msgs.go +++ b/x/gamm/simulation/sim_msgs.go @@ -9,7 +9,7 @@ import ( legacysimulationtype "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/osmosis-labs/osmosis/v10/osmoutils" - simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" balancertypes "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" "github.com/osmosis-labs/osmosis/v10/x/gamm/types" @@ -21,9 +21,9 @@ var ( // RandomJoinPoolMsg pseudo-randomly selects an existing pool ID, attempts to find an account with the // respective underlying token denoms, and attempts to execute a join pool transaction -func RandomJoinPoolMsg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgJoinPool, error) { +func RandomJoinPoolMsg(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgJoinPool, error) { // get random pool - pool_id := simulation.RandLTBound(sim, k.GetNextPoolNumber(ctx)) + pool_id := simtypes.RandLTBound(sim, k.GetNextPoolNumber(ctx)) pool, err := k.GetPoolAndPoke(ctx, pool_id) if err != nil { return &types.MsgJoinPool{}, err @@ -97,9 +97,9 @@ func deriveRealMinShareOutAmt(ctx sdk.Context, tokenIn sdk.Coins, pool types.Poo // RandomExitPoolMsg pseudo-randomly selects an existing pool ID, attempts to find an account with the // respective unbonded gamm shares, and attempts to execute an exit pool transaction -func RandomExitPoolMsg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgExitPool, error) { +func RandomExitPoolMsg(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgExitPool, error) { // select a pseudo-random pool ID, max bound by the upcoming pool ID - pool_id := simulation.RandLTBound(sim, k.GetNextPoolNumber(ctx)) + pool_id := simtypes.RandLTBound(sim, k.GetNextPoolNumber(ctx)) pool, err := k.GetPoolAndPoke(ctx, pool_id) if err != nil { return &types.MsgExitPool{}, err @@ -122,7 +122,7 @@ func RandomExitPoolMsg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) // RandomCreatePoolMsg attempts to find an account with two or more distinct denoms and attempts to send a // create pool message composed of those denoms -func RandomCreateUniV2Msg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*balancertypes.MsgCreateBalancerPool, error) { +func RandomCreateUniV2Msg(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*balancertypes.MsgCreateBalancerPool, error) { var poolAssets []balancertypes.PoolAsset // find an address with two or more distinct denoms in their wallet sender, senderExists := sim.RandomSimAccountWithConstraint(createPoolRestriction(k, sim, ctx)) @@ -154,7 +154,7 @@ func RandomCreateUniV2Msg(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Conte }, nil } -func createPoolRestriction(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) simulation.SimAccountConstraint { +func createPoolRestriction(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) simtypes.SimAccountConstraint { return func(acc legacysimulationtype.Account) bool { accCoins := sim.BankKeeper().SpendableCoins(ctx, acc.Address) hasTwoCoins := len(accCoins) >= 2 diff --git a/x/incentives/simulation/operations.go b/x/incentives/simulation/operations.go index 950cca38197..10b281f4a09 100644 --- a/x/incentives/simulation/operations.go +++ b/x/incentives/simulation/operations.go @@ -4,7 +4,7 @@ import ( "math/rand" "time" - osmo_simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + osmosimtypes "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" "github.com/cosmos/cosmos-sdk/baseapp" @@ -142,7 +142,7 @@ func SimulateMsgCreateGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankK } txGen := simappparams.MakeTestEncodingConfig().TxConfig - return osmo_simulation.GenAndDeliverTxWithRandFees( + return osmosimtypes.GenAndDeliverTxWithRandFees( r, app, txGen, &msg, rewards, ctx, simAccount, ak, bk, types.ModuleName) } } @@ -175,7 +175,7 @@ func SimulateMsgAddToGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankKe } txGen := simappparams.MakeTestEncodingConfig().TxConfig - return osmo_simulation.GenAndDeliverTxWithRandFees( + return osmosimtypes.GenAndDeliverTxWithRandFees( r, app, txGen, &msg, rewards, ctx, simAccount, ak, bk, types.ModuleName, ) } diff --git a/x/lockup/module.go b/x/lockup/module.go index 5d52e901c96..139c30cd864 100644 --- a/x/lockup/module.go +++ b/x/lockup/module.go @@ -17,12 +17,12 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" "github.com/osmosis-labs/osmosis/v10/x/lockup/client/cli" "github.com/osmosis-labs/osmosis/v10/x/lockup/client/rest" "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" - locksimulation "github.com/osmosis-labs/osmosis/v10/x/lockup/simulation" + simulation "github.com/osmosis-labs/osmosis/v10/x/lockup/simulation" "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) @@ -183,13 +183,13 @@ func (AppModule) ConsensusVersion() uint64 { return 1 } // ___________________________________________________________________________ -// AppModuleSimulationV2 functions +// AppModuleSimulation functions // WeightedOperations returns the all the lockup module operations with their respective weights. -func (am AppModule) Actions() []simulation.Action { - return []simulation.Action{ - simulation.NewCurriedMsgBasedAction("lock tokens", am.keeper, locksimulation.RandomMsgLockTokens), - simulation.NewCurriedMsgBasedAction("unlock all tokens", am.keeper, locksimulation.RandomMsgBeginUnlockingAll), - simulation.NewCurriedMsgBasedAction("unlock lock", am.keeper, locksimulation.RandomMsgBeginUnlocking), +func (am AppModule) Actions() []simtypes.Action { + return []simtypes.Action{ + simtypes.NewMsgBasedAction("lock tokens", am.keeper, simulation.RandomMsgLockTokens), + simtypes.NewMsgBasedAction("unlock all tokens", am.keeper, simulation.RandomMsgBeginUnlockingAll), + simtypes.NewMsgBasedAction("unlock lock", am.keeper, simulation.RandomMsgBeginUnlocking), } } diff --git a/x/lockup/simulation/operations.go b/x/lockup/simulation/operations.go index edc74968b3e..a09c61c54a6 100644 --- a/x/lockup/simulation/operations.go +++ b/x/lockup/simulation/operations.go @@ -7,20 +7,20 @@ import ( legacysimulationtype "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/osmosis-labs/osmosis/v10/osmoutils" - simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" "github.com/osmosis-labs/osmosis/v10/x/lockup/keeper" "github.com/osmosis-labs/osmosis/v10/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" ) -func RandomMsgLockTokens(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgLockTokens, error) { +func RandomMsgLockTokens(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgLockTokens, error) { sender, err := sim.RandomSimAccountWithBalance(ctx) if err != nil { return nil, err } lockCoin := sim.RandExponentialCoin(ctx, sender.Address) - duration := simulation.RandSelect(sim, time.Minute, time.Hour, time.Hour*24) + duration := simtypes.RandSelect(sim, time.Minute, time.Hour, time.Hour*24) return &types.MsgLockTokens{ Owner: sender.Address.String(), Duration: duration, @@ -28,14 +28,14 @@ func RandomMsgLockTokens(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Contex }, nil } -func RandomMsgBeginUnlockingAll(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgBeginUnlockingAll, error) { +func RandomMsgBeginUnlockingAll(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgBeginUnlockingAll, error) { sender := sim.RandomSimAccount() return &types.MsgBeginUnlockingAll{ Owner: sender.Address.String(), }, nil } -func RandomMsgBeginUnlocking(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgBeginUnlocking, error) { +func RandomMsgBeginUnlocking(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgBeginUnlocking, error) { sender, senderExists := sim.RandomSimAccountWithConstraint(accountHasLockConstraint(k, ctx)) if !senderExists { return nil, errors.New("no addr has created a lock") @@ -49,14 +49,14 @@ func RandomMsgBeginUnlocking(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Co var notUnlockingFilter = func(l types.PeriodLock) bool { return !l.IsUnlocking() } -func accountHasLockConstraint(k keeper.Keeper, ctx sdk.Context) simulation.SimAccountConstraint { +func accountHasLockConstraint(k keeper.Keeper, ctx sdk.Context) simtypes.SimAccountConstraint { return func(acc legacysimulationtype.Account) bool { return len(osmoutils.Filter(notUnlockingFilter, k.GetAccountPeriodLocks(ctx, acc.Address))) != 0 } } -func randLock(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context, addr sdk.AccAddress) types.PeriodLock { +func randLock(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context, addr sdk.AccAddress) types.PeriodLock { locks := k.GetAccountPeriodLocks(ctx, addr) notUnlockingLocks := osmoutils.Filter(notUnlockingFilter, locks) - return simulation.RandSelect(sim, notUnlockingLocks...) + return simtypes.RandSelect(sim, notUnlockingLocks...) } diff --git a/x/superfluid/simulation/operations.go b/x/superfluid/simulation/operations.go index b363776dcec..c37205ce7f8 100644 --- a/x/superfluid/simulation/operations.go +++ b/x/superfluid/simulation/operations.go @@ -3,7 +3,7 @@ package simulation import ( "math/rand" - osmo_simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + osmosimtypes "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" "github.com/cosmos/cosmos-sdk/baseapp" @@ -114,7 +114,7 @@ func SimulateMsgSuperfluidDelegate(ak stakingtypes.AccountKeeper, bk stakingtype } txGen := simappparams.MakeTestEncodingConfig().TxConfig - return osmo_simulation.GenAndDeliverTxWithRandFees( + return osmosimtypes.GenAndDeliverTxWithRandFees( r, app, txGen, &msg, nil, ctx, simAccount, ak, bk, types.ModuleName) } } @@ -140,7 +140,7 @@ func SimulateMsgSuperfluidUndelegate(ak stakingtypes.AccountKeeper, bk stakingty } txGen := simappparams.MakeTestEncodingConfig().TxConfig - return osmo_simulation.GenAndDeliverTxWithRandFees( + return osmosimtypes.GenAndDeliverTxWithRandFees( r, app, txGen, &msg, nil, ctx, simAccount, ak, bk, types.ModuleName) } } @@ -176,7 +176,7 @@ func SimulateMsgSuperfluidUndelegate(ak stakingtypes.AccountKeeper, bk stakingty // } // txGen := simappparams.MakeTestEncodingConfig().TxConfig -// return osmo_simulation.GenAndDeliverTxWithRandFees( +// return osmosimtypes.GenAndDeliverTxWithRandFees( // r, app, txGen, &msg, nil, ctx, simAccount, ak, bk, types.ModuleName) // } // } diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index b9b350a43c8..bc27f218531 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -15,8 +15,8 @@ import ( "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" - simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" - tokenfactorysimulation "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/simulation" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" + simulation "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/simulation" "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/client/cli" "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" @@ -179,7 +179,7 @@ func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Valid // AppModuleSimulationV2 functions // GenerateGenesisState creates a randomized GenState of the tokenfactory module. -func (am AppModule) GenerateGenesisState(simState *module.SimulationState, s *simulation.SimCtx) { +func (am AppModule) SimulatorGenesisState(simState *module.SimulationState, s *simtypes.SimCtx) { tfDefaultGen := types.DefaultGenesis() tfDefaultGen.Params.DenomCreationFee = sdk.NewCoins(sdk.NewInt64Coin("stake", 10_000_000)) tfDefaultGenJson := simState.Cdc.MustMarshalJSON(tfDefaultGen) @@ -187,9 +187,9 @@ func (am AppModule) GenerateGenesisState(simState *module.SimulationState, s *si } // WeightedOperations returns the all the lockup module operations with their respective weights. -func (am AppModule) Actions() []simulation.Action { - return []simulation.Action{ - simulation.NewCurriedMsgBasedAction("create token factory token", am.keeper, tokenfactorysimulation.RandomMsgCreateDenom), - simulation.NewCurriedMsgBasedAction("mint token factory token", am.keeper, tokenfactorysimulation.RandomMsgMintDenom), +func (am AppModule) Actions() []simtypes.Action { + return []simtypes.Action{ + simtypes.NewMsgBasedAction("create token factory token", am.keeper, simulation.RandomMsgCreateDenom), + simtypes.NewMsgBasedAction("mint token factory token", am.keeper, simulation.RandomMsgMintDenom), } } diff --git a/x/tokenfactory/simulation/sim_msgs.go b/x/tokenfactory/simulation/sim_msgs.go index 3398aa9c13e..e7563d9a278 100644 --- a/x/tokenfactory/simulation/sim_msgs.go +++ b/x/tokenfactory/simulation/sim_msgs.go @@ -6,7 +6,7 @@ import ( legacysimulationtype "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/osmosis-labs/osmosis/v10/osmoutils" - simulation "github.com/osmosis-labs/osmosis/v10/simulation/types" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/keeper" "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" @@ -14,14 +14,14 @@ import ( ) // RandomMsgCreateDenom creates a random tokenfactory denom that is no greater than 44 alphanumeric characters -func RandomMsgCreateDenom(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgCreateDenom, error) { +func RandomMsgCreateDenom(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgCreateDenom, error) { return &types.MsgCreateDenom{ Sender: sim.RandomSimAccount().Address.String(), Subdenom: sim.RandStringOfLength(types.MaxSubdenomLength), }, nil } -func RandomMsgMintDenom(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context) (*types.MsgMint, error) { +func RandomMsgMintDenom(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgMint, error) { acc, senderExists := sim.RandomSimAccountWithConstraint(accountCreatedTokenFactoryDenom(k, ctx)) if !senderExists { return nil, errors.New("no addr has created a tokenfactory coin") @@ -29,7 +29,7 @@ func RandomMsgMintDenom(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context // Pick denom store := k.GetCreatorPrefixStore(ctx, acc.Address.String()) denoms := osmoutils.GatherAllKeysFromStore(store) - denom := simulation.RandSelect(sim, denoms...) + denom := simtypes.RandSelect(sim, denoms...) // TODO: Replace with an improved rand exponential coin mintAmount := sim.RandPositiveInt(sdk.NewIntFromUint64(1000_000000)) @@ -41,7 +41,7 @@ func RandomMsgMintDenom(k keeper.Keeper, sim *simulation.SimCtx, ctx sdk.Context // TODO: We are going to need to index the owner of an account as well, rather than creator // to simulate admin changes -func accountCreatedTokenFactoryDenom(k keeper.Keeper, ctx sdk.Context) simulation.SimAccountConstraint { +func accountCreatedTokenFactoryDenom(k keeper.Keeper, ctx sdk.Context) simtypes.SimAccountConstraint { return func(acc legacysimulationtype.Account) bool { store := k.GetCreatorPrefixStore(ctx, acc.Address.String()) iterator := store.Iterator(nil, nil) From 6d20105f0842a0baa330829898dba01d4c459ee5 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Mon, 18 Jul 2022 20:59:56 -0500 Subject: [PATCH 097/376] Remove cdc arg from SimulateFromSeed, suppress committed KVStore logs (#2132) * Remove cdc arg from SimulateFromSeed, suppress committed KVStore logs * move simlogger to simtypes Co-authored-by: Adam Tucker Co-authored-by: Adam Tucker --- simulation/executor/simulate.go | 74 ++++++++++++------------- simulation/simtypes/simlogger/logger.go | 35 ++++++++++++ tests/simulator/sim_test.go | 6 +- 3 files changed, 73 insertions(+), 42 deletions(-) create mode 100644 simulation/simtypes/simlogger/logger.go diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index 2ea3de66ca1..b7f626a24b7 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -15,7 +15,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/simulation" @@ -24,39 +23,6 @@ import ( const AverageBlockTime = 6 * time.Second -// initialize the chain for the simulation -func initChain( - r *rand.Rand, - params Params, - accounts []simulation.Account, - app simtypes.App, - appStateFn simulation.AppStateFn, - config *simulation.Config, - cdc codec.JSONCodec, -) (mockValidators, time.Time, []simulation.Account) { - // TODO: Cleanup the whole config dependency with appStateFn - appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, *config) - consensusParams := randomConsensusParams(r, appState, cdc) - req := abci.RequestInitChain{ - AppStateBytes: appState, - ChainId: chainID, - ConsensusParams: consensusParams, - Time: genesisTimestamp, - } - // Valid app version can only be zero on app initialization. - req.ConsensusParams.Version.AppVersion = 0 - res := app.GetBaseApp().InitChain(req) - validators := newMockValidators(r, res.Validators, params) - - // update config - config.ChainID = chainID - if config.InitialBlockHeight == 0 { - config.InitialBlockHeight = 1 - } - - return validators, genesisTimestamp, accounts -} - // SimulateFromSeedLegacy tests an application by running the provided // operations, testing the provided invariants, but using the provided config.Seed. // TODO: Restore SimulateFromSeedLegacy by adding a wrapper that can take in @@ -94,13 +60,12 @@ func SimulateFromSeed( initFunctions simtypes.InitFunctions, actions []simtypes.Action, config simulation.Config, - cdc codec.JSONCodec, ) (stopEarly bool, err error) { // in case we have to end early, don't os.Exit so that we can run cleanup code. // TODO: Understand exit pattern, this is so screwed up. Then delete ^ // Encapsulate the bizarre initialization logic that must be cleaned. - simCtx, simState, simParams, err := cursedInitializationLogic(tb, w, app, initFunctions, &config, cdc) + simCtx, simState, simParams, err := cursedInitializationLogic(tb, w, app, initFunctions, &config) if err != nil { return true, err } @@ -150,8 +115,7 @@ func cursedInitializationLogic( w io.Writer, app simtypes.App, initFunctions simtypes.InitFunctions, - config *simulation.Config, - cdc codec.JSONCodec) (*simtypes.SimCtx, *simState, Params, error) { + config *simulation.Config) (*simtypes.SimCtx, *simState, Params, error) { fmt.Fprintf(w, "Starting SimulateFromSeed with randomness created with seed %d\n", int(config.Seed)) r := rand.New(rand.NewSource(config.Seed)) @@ -163,7 +127,7 @@ func cursedInitializationLogic( return nil, nil, simParams, fmt.Errorf("must have greater than zero genesis accounts") } - validators, genesisTimestamp, accs := initChain(r, simParams, accs, app, initFunctions.AppInitialStateFn, config, cdc) + validators, genesisTimestamp, accs := initChain(r, simParams, accs, app, initFunctions.AppInitialStateFn, config) fmt.Printf( "Starting the simulation from time %v (unixtime %v)\n", @@ -186,6 +150,38 @@ func cursedInitializationLogic( return simCtx, simState, simParams, nil } +// initialize the chain for the simulation +func initChain( + r *rand.Rand, + params Params, + accounts []simulation.Account, + app simtypes.App, + appStateFn simulation.AppStateFn, + config *simulation.Config, +) (mockValidators, time.Time, []simulation.Account) { + // TODO: Cleanup the whole config dependency with appStateFn + appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, *config) + consensusParams := randomConsensusParams(r, appState, app.AppCodec()) + req := abci.RequestInitChain{ + AppStateBytes: appState, + ChainId: chainID, + ConsensusParams: consensusParams, + Time: genesisTimestamp, + } + // Valid app version can only be zero on app initialization. + req.ConsensusParams.Version.AppVersion = 0 + res := app.GetBaseApp().InitChain(req) + validators := newMockValidators(r, res.Validators, params) + + // update config + config.ChainID = chainID + if config.InitialBlockHeight == 0 { + config.InitialBlockHeight = 1 + } + + return validators, genesisTimestamp, accounts +} + //nolint:deadcode,unused func printPanicRecoveryError(recoveryError interface{}) { errStackTrace := string(debug.Stack()) diff --git a/simulation/simtypes/simlogger/logger.go b/simulation/simtypes/simlogger/logger.go new file mode 100644 index 00000000000..7537556ad64 --- /dev/null +++ b/simulation/simtypes/simlogger/logger.go @@ -0,0 +1,35 @@ +// This package is a hack. It is meant to solve temporary logging pains in simulation. +// Every issue this package fixes needs a longer term fix in our stack, to not get into full node logs. +package simlogger + +import ( + "strings" + + "github.com/tendermint/tendermint/libs/log" +) + +type simLogger struct { + logger log.Logger +} + +func (s *simLogger) Debug(msg string, keyvals ...interface{}) { + // Suppress this log + if strings.Contains(msg, "committed KVStore") { + return + } + s.logger.Debug(msg, keyvals...) +} +func (s *simLogger) Info(msg string, keyvals ...interface{}) { + s.logger.Info(msg, keyvals) +} +func (s *simLogger) Error(msg string, keyvals ...interface{}) { + s.logger.Error(msg, keyvals) +} + +func (s *simLogger) With(keyvals ...interface{}) log.Logger { + return s.logger.With(keyvals...) +} + +func NewSimLogger(logger log.Logger) log.Logger { + return &simLogger{logger} +} diff --git a/tests/simulator/sim_test.go b/tests/simulator/sim_test.go index 42949681fb1..f80f58ed297 100644 --- a/tests/simulator/sim_test.go +++ b/tests/simulator/sim_test.go @@ -20,6 +20,7 @@ import ( osmosim "github.com/osmosis-labs/osmosis/v10/simulation/executor" "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" + "github.com/osmosis-labs/osmosis/v10/simulation/simtypes/simlogger" ) // Profile with: @@ -54,6 +55,7 @@ func fullAppSimulation(tb testing.TB, is_testing bool) { if err != nil { tb.Fatalf("simulation setup failed: %s", err.Error()) } + logger = simlogger.NewSimLogger(logger) // This file is needed to provide the correct path // to reflect.wasm test file needed for wasmd simulation testing. config.ParamsFile = "params.json" @@ -102,7 +104,6 @@ func fullAppSimulation(tb testing.TB, is_testing bool) { initFns, osmosis.SimulationManager().Actions(config.Seed, osmosis.AppCodec()), // Run all registered operations config, - osmosis.AppCodec(), ) if simErr != nil { @@ -148,7 +149,7 @@ func TestAppStateDeterminism(t *testing.T) { for j := 0; j < numTimesToRunPerSeed; j++ { var logger log.Logger - logger = log.TestingLogger() + logger = simlogger.NewSimLogger(log.TestingLogger()) // if sdkSimapp.FlagVerboseValue { // logger = log.TestingLogger() // } else { @@ -188,7 +189,6 @@ func TestAppStateDeterminism(t *testing.T) { initFns, osmosis.SimulationManager().Actions(config.Seed, osmosis.AppCodec()), // Run all registered operations config, - osmosis.AppCodec(), ) require.NoError(t, simErr) From eaefb31338eb0fcea48c7db69474ab1a3dfa814e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Jul 2022 21:08:24 -0500 Subject: [PATCH 098/376] chore(deps): bump github.com/golangci/golangci-lint (#2134) Bumps [github.com/golangci/golangci-lint](https://github.com/golangci/golangci-lint) from 1.46.2 to 1.47.0. - [Release notes](https://github.com/golangci/golangci-lint/releases) - [Changelog](https://github.com/golangci/golangci-lint/blob/master/CHANGELOG.md) - [Commits](https://github.com/golangci/golangci-lint/compare/v1.46.2...v1.47.0) --- updated-dependencies: - dependency-name: github.com/golangci/golangci-lint dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 61 +++++++++++---------- go.sum | 166 ++++++++++++++++++++++++--------------------------------- 2 files changed, 103 insertions(+), 124 deletions(-) diff --git a/go.mod b/go.mod index 8f5b9549135..148cf09f1a9 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/cosmos/ibc-go/v3 v3.0.0 github.com/gogo/protobuf v1.3.3 github.com/golang/protobuf v1.5.2 - github.com/golangci/golangci-lint v1.46.2 + github.com/golangci/golangci-lint v1.47.0 github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/ory/dockertest/v3 v3.9.1 @@ -32,19 +32,27 @@ require ( mvdan.cc/gofumpt v0.3.1 ) +require ( + github.com/alingse/asasalint v0.0.10 // indirect + github.com/sivchari/nosnakecase v1.5.0 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.7.0 // indirect + go.uber.org/zap v1.19.1 // indirect +) + require ( 4d63.com/gochecknoglobals v0.1.0 // indirect filippo.io/edwards25519 v1.0.0-beta.2 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect - github.com/Antonboom/errname v0.1.6 // indirect + github.com/Antonboom/errname v0.1.7 // indirect github.com/Antonboom/nilnil v0.1.1 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/BurntSushi/toml v1.1.0 // indirect github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect github.com/CosmWasm/wasmvm v1.0.0 github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 // indirect - github.com/GaijinEntertainment/go-exhaustruct/v2 v2.1.0 // indirect + github.com/GaijinEntertainment/go-exhaustruct/v2 v2.2.0 // indirect github.com/Masterminds/semver v1.5.0 // indirect github.com/Microsoft/go-winio v0.5.2 // indirect github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect @@ -75,7 +83,7 @@ require ( github.com/cosmos/gorocksdb v1.2.0 // indirect github.com/cosmos/ledger-cosmos-go v0.11.1 // indirect github.com/cosmos/ledger-go v0.9.2 // indirect - github.com/daixiang0/gci v0.3.3 // indirect + github.com/daixiang0/gci v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/denis-tingaikin/go-header v0.4.3 // indirect @@ -93,9 +101,9 @@ require ( github.com/fatih/color v1.13.0 // indirect github.com/fatih/structtag v1.2.0 // indirect github.com/felixge/httpsnoop v1.0.1 // indirect - github.com/firefart/nonamedreturns v1.0.1 // indirect + github.com/firefart/nonamedreturns v1.0.4 // indirect github.com/fsnotify/fsnotify v1.5.4 // indirect - github.com/fzipp/gocyclo v0.5.1 // indirect + github.com/fzipp/gocyclo v0.6.0 // indirect github.com/go-critic/go-critic v0.6.3 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.0 // indirect @@ -144,7 +152,7 @@ require ( github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hashicorp/go-version v1.4.0 // indirect + github.com/hashicorp/go-version v1.6.0 // indirect github.com/hashicorp/golang-lru v0.5.4 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87 // indirect @@ -158,20 +166,20 @@ require ( github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af // indirect github.com/jmhodges/levigo v1.0.0 // indirect github.com/julz/importas v0.1.0 // indirect - github.com/kisielk/errcheck v1.6.0 // indirect + github.com/kisielk/errcheck v1.6.1 // indirect github.com/kisielk/gotool v1.0.0 // indirect github.com/klauspost/compress v1.13.6 // indirect - github.com/kulti/thelper v0.6.2 // indirect - github.com/kunwardeep/paralleltest v1.0.3 // indirect + github.com/kulti/thelper v0.6.3 // indirect + github.com/kunwardeep/paralleltest v1.0.6 // indirect github.com/kyoh86/exportloopref v0.1.8 // indirect github.com/ldez/gomoddirectives v0.2.3 // indirect github.com/ldez/tagliatelle v0.3.1 // indirect github.com/leonklingele/grouper v1.1.0 // indirect - github.com/lib/pq v1.10.4 // indirect + github.com/lib/pq v1.10.6 // indirect github.com/libp2p/go-buffer-pool v0.0.2 // indirect github.com/lufeee/execinquery v1.2.1 // indirect github.com/magiconair/properties v1.8.6 // indirect - github.com/maratori/testpackage v1.0.1 // indirect + github.com/maratori/testpackage v1.1.0 // indirect github.com/matoous/godox v0.0.0-20210227103229-6504466cf951 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-isatty v0.0.14 // indirect @@ -188,14 +196,14 @@ require ( github.com/mtibben/percent v0.2.1 // indirect github.com/nakabonne/nestif v0.3.1 // indirect github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 // indirect - github.com/nishanths/exhaustive v0.7.11 // indirect + github.com/nishanths/exhaustive v0.8.1 // indirect github.com/nishanths/predeclared v0.2.2 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.0.2 // indirect github.com/opencontainers/runc v1.1.2 // indirect github.com/pelletier/go-toml v1.9.5 // indirect - github.com/pelletier/go-toml/v2 v2.0.1 // indirect + github.com/pelletier/go-toml/v2 v2.0.2 // indirect github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d // indirect github.com/pmezard/go-difflib v1.0.0 // indirect @@ -217,11 +225,11 @@ require ( github.com/ryanrolds/sqlclosecheck v0.3.0 // indirect github.com/sanposhiho/wastedassign/v2 v2.0.6 // indirect github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa // indirect - github.com/securego/gosec/v2 v2.11.0 // indirect + github.com/securego/gosec/v2 v2.12.0 // indirect github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c // indirect github.com/sirupsen/logrus v1.8.1 // indirect github.com/sivchari/containedctx v1.0.2 // indirect - github.com/sivchari/tenv v1.5.0 // indirect + github.com/sivchari/tenv v1.6.0 // indirect github.com/sonatard/noctx v0.0.1 // indirect github.com/sourcegraph/go-diff v0.6.1 // indirect github.com/spf13/afero v1.8.2 // indirect @@ -229,7 +237,7 @@ require ( github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect github.com/stbenjam/no-sprintf-host-port v0.1.1 // indirect github.com/stretchr/objx v0.4.0 // indirect - github.com/subosito/gotenv v1.3.0 // indirect + github.com/subosito/gotenv v1.4.0 // indirect github.com/sylvia7788/contextcheck v1.0.4 // indirect github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca github.com/tdakkota/asciicheck v0.1.1 // indirect @@ -238,11 +246,11 @@ require ( github.com/tendermint/go-amino v0.16.0 // indirect github.com/tetafro/godot v1.4.11 // indirect github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144 // indirect - github.com/tomarrell/wrapcheck/v2 v2.6.1 // indirect + github.com/tomarrell/wrapcheck/v2 v2.6.2 // indirect github.com/tommy-muehle/go-mnd/v2 v2.5.0 // indirect github.com/ultraware/funlen v0.0.3 // indirect github.com/ultraware/whitespace v0.0.5 // indirect - github.com/uudashr/gocognit v1.0.5 // indirect + github.com/uudashr/gocognit v1.0.6 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect @@ -251,24 +259,23 @@ require ( github.com/zimmski/go-tool v0.0.0-20150119110811-2dfdc9ac8439 // indirect github.com/zimmski/osutil v0.0.0-20190128123334-0d0b3ca231ac // indirect github.com/zondax/hid v0.9.0 // indirect - gitlab.com/bosi/decorder v0.2.1 // indirect + gitlab.com/bosi/decorder v0.2.2 // indirect go.etcd.io/bbolt v1.3.6 // indirect go.opencensus.io v0.23.0 // indirect - golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect + golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e // indirect - golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect + golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect - golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect + golang.org/x/sys v0.0.0-20220702020025-31831981b65f // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect - golang.org/x/tools v0.1.11-0.20220316014157-77aa08bb151a // indirect - golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df // indirect + golang.org/x/tools v0.1.11 // indirect google.golang.org/protobuf v1.28.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect - gopkg.in/ini.v1 v1.66.4 // indirect + gopkg.in/ini.v1 v1.66.6 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - honnef.co/go/tools v0.3.1 // indirect + honnef.co/go/tools v0.3.2 // indirect mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed // indirect mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b // indirect mvdan.cc/unparam v0.0.0-20211214103731-d0ef000c54e5 // indirect diff --git a/go.sum b/go.sum index c5945e03aec..a2fcf17be47 100644 --- a/go.sum +++ b/go.sum @@ -32,16 +32,12 @@ cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+Y cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW4= cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= cloud.google.com/go v0.99.0/go.mod h1:w0Xx2nLzqWJPuozYQX+hFfCSI8WioryfRDzkoI/Y2ZA= -cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w99A= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/compute v0.1.0/go.mod h1:GAesmwr110a34z04OlxYkATPBEfVhkymfTBXtfbBFow= -cloud.google.com/go/compute v1.3.0/go.mod h1:cCZiE1NHEtai4wiufUhW8I8S1JKkAnhnQJWM7YD99wM= -cloud.google.com/go/compute v1.5.0/go.mod h1:9SMHyhJlzhlkJqrPAc839t2BZFTSk6Jdj6mkzQJeu0M= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= @@ -66,8 +62,8 @@ github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMb github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= github.com/99designs/keyring v1.2.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o= github.com/99designs/keyring v1.2.1/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA= -github.com/Antonboom/errname v0.1.6 h1:LzIJZlyLOCSu51o3/t2n9Ck7PcoP9wdbrdaW6J8fX24= -github.com/Antonboom/errname v0.1.6/go.mod h1:7lz79JAnuoMNDAWE9MeeIr1/c/VpSUWatBv2FH9NYpI= +github.com/Antonboom/errname v0.1.7 h1:mBBDKvEYwPl4WFFNwec1CZO096G6vzK9vvDQzAwkako= +github.com/Antonboom/errname v0.1.7/go.mod h1:g0ONh16msHIPgJSGsecu1G/dcF2hlYR/0SddnIAGavU= github.com/Antonboom/nilnil v0.1.1 h1:PHhrh5ANKFWRBh7TdYmyyq2gyT2lotnvFvvFbylF81Q= github.com/Antonboom/nilnil v0.1.1/go.mod h1:L1jBqoWM7AOeTD+tSquifKSesRHs4ZdaxvZR+xdJEaI= github.com/Azure/azure-pipeline-go v0.2.1/go.mod h1:UGSo8XybXnIGZ3epmeBw7Jdz+HiUVpqIlpz/HKHylF4= @@ -103,8 +99,8 @@ github.com/DataDog/zstd v1.4.1/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 h1:sHglBQTwgx+rWPdisA5ynNEsoARbiCBOyGcJM4/OzsM= github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24/go.mod h1:4UJr5HIiMZrwgkSPdsjy2uOQExX/WEILpIrO9UPGuXs= -github.com/GaijinEntertainment/go-exhaustruct/v2 v2.1.0 h1:LAPPhJ4KR5Z8aKVZF5S48csJkxL5RMKmE/98fMs1u5M= -github.com/GaijinEntertainment/go-exhaustruct/v2 v2.1.0/go.mod h1:LGOGuvEgCfCQsy3JF2tRmpGDpzA53iZfyGEWSPwQ6/4= +github.com/GaijinEntertainment/go-exhaustruct/v2 v2.2.0 h1:V9xVvhKbLt7unNEGAruK1xXglyc668Pq3Xx0MNTNqpo= +github.com/GaijinEntertainment/go-exhaustruct/v2 v2.2.0/go.mod h1:n/vLeA7V+QY84iYAGwMkkUUp9ooeuftMEvaDrSVch+Q= github.com/HdrHistogram/hdrhistogram-go v1.1.0/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo= github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= @@ -148,6 +144,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alexkohler/prealloc v1.0.0 h1:Hbq0/3fJPQhNkN0dR95AVrr6R7tou91y0uHG5pOcUuw= github.com/alexkohler/prealloc v1.0.0/go.mod h1:VetnK3dIgFBBKmg0YnD9F9x6Icjd+9cvfHR56wJVlKE= +github.com/alingse/asasalint v0.0.10 h1:qqGPDTV0ff0tWHN/nnIlSdjlU/EwRPaUY4SfpE1rnms= +github.com/alingse/asasalint v0.0.10/go.mod h1:nCaoMhw7a9kSJObvQyVzNTPBDbNpdocqrSP7t/cW5+I= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= @@ -180,6 +178,7 @@ github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZw github.com/aws/aws-sdk-go-v2 v1.9.1/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.8.1/go.mod h1:CM+19rL1+4dFWnOQKwDc7H1KwXTz+h61oUSHyhV0b3o= github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= +github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= @@ -312,8 +311,8 @@ github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cyphar/filepath-securejoin v0.2.2/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4= github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= -github.com/daixiang0/gci v0.3.3 h1:55xJKH7Gl9Vk6oQ1cMkwrDWjAkT1D+D1G9kNmRcAIY4= -github.com/daixiang0/gci v0.3.3/go.mod h1:1Xr2bxnQbDxCqqulUOv8qpGqkgRw9RSCGGjEC2LjF8o= +github.com/daixiang0/gci v0.4.2 h1:PyT/Y4a265wDhPCZo2ip/YH33M4zEuFA3nDMdAvcKSA= +github.com/daixiang0/gci v0.4.2/go.mod h1:d0f+IJhr9loBtIq+ebwhRoTt1LGbPH96ih8bKlsRT9E= github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -391,8 +390,8 @@ github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4 github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94= github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/firefart/nonamedreturns v1.0.1 h1:fSvcq6ZpK/uBAgJEGMvzErlzyM4NELLqqdTofVjVNag= -github.com/firefart/nonamedreturns v1.0.1/go.mod h1:D3dpIBojGGNh5UfElmwPu73SwDCm+VKhHYqwlNOk2uQ= +github.com/firefart/nonamedreturns v1.0.4 h1:abzI1p7mAEPYuR4A+VLKn4eNDOycjYo2phmY9sfv40Y= +github.com/firefart/nonamedreturns v1.0.4/go.mod h1:TDhe/tjI1BXo48CmYbUduTV7BdIga8MAO/xbKdcVsGI= github.com/fjl/memsize v0.0.0-20180418122429-ca190fb6ffbc/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= @@ -408,8 +407,8 @@ github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5 github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/fullstorydev/grpcurl v1.6.0/go.mod h1:ZQ+ayqbKMJNhzLmbpCiurTVlaK2M/3nqZCxaQ2Ze/sM= -github.com/fzipp/gocyclo v0.5.1 h1:L66amyuYogbxl0j2U+vGqJXusPF2IkduvXLnYD5TFgw= -github.com/fzipp/gocyclo v0.5.1/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA= +github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo= +github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= @@ -542,8 +541,8 @@ github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe h1:6RGUuS7EGotKx6 github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe/go.mod h1:gjqyPShc/m8pEMpk0a3SeagVb0kaqvhscv+i9jI5ZhQ= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a h1:iR3fYXUjHCR97qWS8ch1y9zPNsgXThGwjKPrYfqMPks= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= -github.com/golangci/golangci-lint v1.46.2 h1:o90t/Xa6dhJbvy8Bz2RpzUXqrkigp19DLStMolTZbyo= -github.com/golangci/golangci-lint v1.46.2/go.mod h1:3DkdHnxn9eoTTrpT2gB0TEv8KSziuoqe9FitgQLHvAY= +github.com/golangci/golangci-lint v1.47.0 h1:h2s+ZGGF63fdzUtac+VYUHPsEO0ADTqHouI7Vase+FY= +github.com/golangci/golangci-lint v1.47.0/go.mod h1:3TZhfF5KolbIkXYjUFvER6G9CoxzLEaafr/u/QI1S5A= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 h1:MfyDlzVjl1hoaPzPD4Gpb/QgoRfSBR0jdhwGyAWwMSA= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0/go.mod h1:66R6K6P6VWk9I95jvqGxkqJxVWGFy9XlDwLwVz1RCFg= github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca h1:kNY3/svz5T29MYHubXix4aDDuE3RWHkPvopM/EDv/MA= @@ -573,7 +572,6 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= @@ -617,10 +615,8 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM= -github.com/googleapis/gax-go/v2 v2.2.0/go.mod h1:as02EH8zWkzwUoLbBaFeQ+arQaj/OthfcblKl4IGNaM= -github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99EXz9pXxye9YM= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= -github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo= +github.com/gookit/color v1.5.1/go.mod h1:wZFzea4X8qN6vHOSP2apMb4/+w/orMznEzYsIHPaqKM= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gordonklaus/ineffassign v0.0.0-20200309095847-7953dde2c7bf/go.mod h1:cuNKsD1zp2v6XfE/orVX2QE1LC+i254ceGcVeDT3pTU= github.com/gordonklaus/ineffassign v0.0.0-20210914165742-4cc7213b9bc8 h1:PVRE9d4AQKmbelZ7emNig1+NT27DUmKZn5qXxfio54U= @@ -692,7 +688,6 @@ github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/S github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v0.16.2/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v1.0.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= -github.com/hashicorp/go-hclog v1.2.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= @@ -711,8 +706,8 @@ github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1 github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.4.0 h1:aAQzgqIrRKRa7w75CKpbBxYsmUoPjzVm1W59ca1L0J4= -github.com/hashicorp/go-version v1.4.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= +github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= @@ -730,7 +725,6 @@ github.com/hashicorp/memberlist v0.3.0/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOn github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/hashicorp/serf v0.9.5/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk= github.com/hashicorp/serf v0.9.6/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= -github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87 h1:uUjLpLt6bVvZ72SQc/B4dXcPBw4Vgd7soowdRl52qEM= github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87/go.mod h1:XGsKKeXxeRr95aEOgipvluMPlgjr7dGlk9ZTWOjcUcg= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= @@ -802,8 +796,8 @@ github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q github.com/karalabe/usb v0.0.0-20190919080040-51dc0efba356/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/errcheck v1.6.0 h1:YTDO4pNy7AUN/021p+JGHycQyYNIyMoenM1YDVK6RlY= -github.com/kisielk/errcheck v1.6.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/errcheck v1.6.1 h1:cErYo+J4SmEjdXZrVXGwLJCE2sB06s23LpkcyWNrT+s= +github.com/kisielk/errcheck v1.6.1/go.mod h1:nXw/i/MfnvRHqXa7XXmQMUB0oNFGuBrNI8d8NLy0LPw= github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= @@ -826,10 +820,10 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kulti/thelper v0.6.2 h1:K4xulKkwOCnT1CDms6Ex3uG1dvSMUUQe9zxgYQgbRXs= -github.com/kulti/thelper v0.6.2/go.mod h1:DsqKShOvP40epevkFrvIwkCMNYxMeTNjdWL4dqWHZ6I= -github.com/kunwardeep/paralleltest v1.0.3 h1:UdKIkImEAXjR1chUWLn+PNXqWUGs//7tzMeWuP7NhmI= -github.com/kunwardeep/paralleltest v1.0.3/go.mod h1:vLydzomDFpk7yu5UX02RmP0H8QfRPOV/oFhWN85Mjb4= +github.com/kulti/thelper v0.6.3 h1:ElhKf+AlItIu+xGnI990no4cE2+XaSu1ULymV2Yulxs= +github.com/kulti/thelper v0.6.3/go.mod h1:DsqKShOvP40epevkFrvIwkCMNYxMeTNjdWL4dqWHZ6I= +github.com/kunwardeep/paralleltest v1.0.6 h1:FCKYMF1OF2+RveWlABsdnmsvJrei5aoyZoaGS+Ugg8g= +github.com/kunwardeep/paralleltest v1.0.6/go.mod h1:Y0Y0XISdZM5IKm3TREQMZ6iteqn1YuwCsJO/0kL9Zes= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/kyoh86/exportloopref v0.1.8 h1:5Ry/at+eFdkX9Vsdw3qU4YkvGtzuVfzT4X7S77LoN/M= github.com/kyoh86/exportloopref v0.1.8/go.mod h1:1tUcJeiioIs7VWe5gcOObrux3lb66+sBqGZrRkMwPgg= @@ -846,8 +840,9 @@ github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.9.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/lib/pq v1.10.4 h1:SO9z7FRPzA03QhHKJrH5BXA6HU1rS4V2nIVrrNC1iYk= github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lib/pq v1.10.6 h1:jbk+ZieJ0D7EVGJYpL9QTz7/YW6UHbmdnZWYyK5cdBs= +github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/libp2p/go-buffer-pool v0.0.2 h1:QNK2iAFa8gjAe1SPz6mHSMuCcjs+X1wlHzeOSqcmlfs= github.com/libp2p/go-buffer-pool v0.0.2/go.mod h1:MvaB6xw5vOrDl8rYZGLFdKAuk/hRoRZd1Vi32+RXyFM= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= @@ -861,8 +856,8 @@ github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czP github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= -github.com/maratori/testpackage v1.0.1 h1:QtJ5ZjqapShm0w5DosRjg0PRlSdAdlx+W6cCKoALdbQ= -github.com/maratori/testpackage v1.0.1/go.mod h1:ddKdw+XG0Phzhx8BFDTKgpWP4i7MpApTE5fXSKAqwDU= +github.com/maratori/testpackage v1.1.0 h1:GJY4wlzQhuBusMF1oahQCBtUV/AQ/k69IZ68vxaac2Q= +github.com/maratori/testpackage v1.1.0/go.mod h1:PeAhzU8qkCwdGEMTEupsHJNlQu2gZopMC6RjbhmHeDc= github.com/matoous/godox v0.0.0-20210227103229-6504466cf951 h1:pWxk9e//NbPwfxat7RXkts09K+dEBJWakUWwICVqYbA= github.com/matoous/godox v0.0.0-20210227103229-6504466cf951/go.mod h1:1BELzlh859Sh1c6+90blK8lbYy0kwQf1bYlBhBysy1s= github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE= @@ -981,8 +976,8 @@ github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 h1:4kuARK6Y6Fx github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354/go.mod h1:KSVJerMDfblTH7p5MZaTt+8zaT2iEk3AkVb9PQdZuE8= github.com/neilotoole/errgroup v0.1.5/go.mod h1:Q2nLGf+594h0CLBs/Mbg6qOr7GtqDK7C2S41udRnToE= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/nishanths/exhaustive v0.7.11 h1:xV/WU3Vdwh5BUH4N06JNUznb6d5zhRPOnlgCrpNYNKA= -github.com/nishanths/exhaustive v0.7.11/go.mod h1:gX+MP7DWMKJmNa1HfMozK+u04hQd3na9i0hyqf3/dOI= +github.com/nishanths/exhaustive v0.8.1 h1:0QKNascWv9qIHY7zRoZSxeRr6kuk5aAT3YXLTiDmjTo= +github.com/nishanths/exhaustive v0.8.1/go.mod h1:qj+zJJUgJ76tR92+25+03oYUhzF4R7/2Wk7fGTfCHmg= github.com/nishanths/predeclared v0.0.0-20190419143655-18a43bb90ffc/go.mod h1:62PewwiQTlm/7Rj+cxVYqZvDIUc+JjZq6GHAC1fsObQ= github.com/nishanths/predeclared v0.2.2 h1:V2EPdZPliZymNAn79T8RkNApBjMmVKh5XRpLm/w98Vk= github.com/nishanths/predeclared v0.2.2/go.mod h1:RROzoN6TnGQupbC+lqggsOlcgysk3LMK/HI84Mp280c= @@ -1007,17 +1002,17 @@ github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9k github.com/onsi/ginkgo v1.16.2/go.mod h1:CObGmKUOKaSC0RjmoAK7tKyn4Azo5P2IWuoMnvwxz1E= github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= -github.com/onsi/ginkgo/v2 v2.0.0/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= -github.com/onsi/ginkgo/v2 v2.1.3 h1:e/3Cwtogj0HA+25nMP1jCMDIf8RtRYbGwGGuBIFztkc= github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= +github.com/onsi/ginkgo/v2 v2.1.4 h1:GNapqRSid3zijZ9H77KrgVG4/8KqiyRsxcSxe+7ApXY= +github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU= github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.13.0/go.mod h1:lRk9szgn8TxENtWd0Tp4c3wjlRfMTMH27I+3Je41yGY= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= -github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE= -github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs= +github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw= +github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= @@ -1069,10 +1064,8 @@ github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/9 github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/pelletier/go-toml/v2 v2.0.0-beta.8/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= -github.com/pelletier/go-toml/v2 v2.0.0/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= -github.com/pelletier/go-toml/v2 v2.0.1 h1:8e3L2cCQzLFi2CR4g7vGFuFxX7Jl1kKX8gW+iV0GUKU= -github.com/pelletier/go-toml/v2 v2.0.1/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= +github.com/pelletier/go-toml/v2 v2.0.2 h1:+jQXlF3scKIcSEKkdHzXhCTDLPFi5r1wnK6yPS+49Gw= +github.com/pelletier/go-toml/v2 v2.0.2/go.mod h1:MovirKjgVRESsAvNZlAjtFwV867yGuwRkXbG66OzopI= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/performancecopilot/speed/v4 v4.0.0/go.mod h1:qxrSyuDGrTOWfV+uKRFhfxw6h/4HXRGUiZiufxo49BM= github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= @@ -1197,7 +1190,6 @@ github.com/ryanrolds/sqlclosecheck v0.3.0 h1:AZx+Bixh8zdUBxUA1NxbxVAS78vTPq4rCb8 github.com/ryanrolds/sqlclosecheck v0.3.0/go.mod h1:1gREqxyTGR3lVtpngyFo3hZAgk0KCtEdgEkHwDbigdA= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sagikazarmark/crypt v0.4.0/go.mod h1:ALv2SRj7GxYV4HO9elxH9nS6M9gW+xDNxqmyJ6RfDFM= -github.com/sagikazarmark/crypt v0.5.0/go.mod h1:l+nzl7KWh51rpzp2h7t4MZWyiEWdhNpOAnclKvg+mdA= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= github.com/sanposhiho/wastedassign/v2 v2.0.6 h1:+6/hQIHKNJAUixEj6EmOngGIisyeI+T3335lYTyxRoA= github.com/sanposhiho/wastedassign/v2 v2.0.6/go.mod h1:KyZ0MWTwxxBmfwn33zh3k1dmsbF2ud9pAAGfoLfjhtI= @@ -1206,8 +1198,8 @@ github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa/go.mod h1:F7 github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo= github.com/seccomp/libseccomp-golang v0.9.2-0.20210429002308-3879420cc921/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= -github.com/securego/gosec/v2 v2.11.0 h1:+PDkpzR41OI2jrw1q6AdXZCbsNGNGT7pQjal0H0cArI= -github.com/securego/gosec/v2 v2.11.0/go.mod h1:SX8bptShuG8reGC0XS09+a4H2BoWSJi+fscA+Pulbpo= +github.com/securego/gosec/v2 v2.12.0 h1:CQWdW7ATFpvLSohMVsajscfyHJ5rsGmEXmsNcsDNmAg= +github.com/securego/gosec/v2 v2.12.0/go.mod h1:iTpT+eKTw59bSgklBHlSnH5O2tNygHMDxfvMubA4i7I= github.com/segmentio/fasthash v1.0.3/go.mod h1:waKX8l2N8yckOgmSsXJi7x1ZfdKZ4x7KRMzBtS3oedY= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c h1:W65qqJCIOVP4jpqPQ0YvHYKwcMEMVWIzWC5iNQQfBTU= @@ -1225,8 +1217,10 @@ github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sivchari/containedctx v1.0.2 h1:0hLQKpgC53OVF1VT7CeoFHk9YKstur1XOgfYIc1yrHI= github.com/sivchari/containedctx v1.0.2/go.mod h1:PwZOeqm4/DLoJOqMSIJs3aKqXRX4YO+uXww087KZ7Bw= -github.com/sivchari/tenv v1.5.0 h1:wxW0mFpKI6DIb3s6m1jCDYvkWXCskrimXMuGd0K/kSQ= -github.com/sivchari/tenv v1.5.0/go.mod h1:64yStXKSOxDfX47NlhVwND4dHwfZDdbp2Lyl018Icvg= +github.com/sivchari/nosnakecase v1.5.0 h1:ZBvAu1H3uteN0KQ0IsLpIFOwYgPEhKLyv2ahrVkub6M= +github.com/sivchari/nosnakecase v1.5.0/go.mod h1:CwDzrzPea40/GB6uynrNLiorAlgFRvRbFSgJx2Gs+QY= +github.com/sivchari/tenv v1.6.0 h1:FyE4WysxLwYljKqWhTfOMjgKjBSnmzzg7lWOmpDiAcc= +github.com/sivchari/tenv v1.6.0/go.mod h1:64yStXKSOxDfX47NlhVwND4dHwfZDdbp2Lyl018Icvg= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPHbB5mVY2iO9KV3pTt/QbIkGaO8gQ2WrDbP4= @@ -1267,7 +1261,6 @@ github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/y github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/spf13/viper v1.10.1/go.mod h1:IGlFPqhNAPKRxohIzWpI5QEy4kuI7tcl5WvR+8qy1rU= -github.com/spf13/viper v1.11.0/go.mod h1:djo0X/bA5+tYVoCn+C7cAYJGcVn/qYLFTG8gdUsX7Zk= github.com/spf13/viper v1.12.0 h1:CZ7eSOd3kZoaYDLbXnmzgQI5RlciuXBMA+18HwHRfZQ= github.com/spf13/viper v1.12.0/go.mod h1:b6COn30jlNxbm/V2IqWiNWkJ+vZNiMNksliPCiuKtSI= github.com/ssgreg/nlreturn/v2 v2.2.1 h1:X4XDI7jstt3ySqGU86YGAURbxw3oTDPK9sPEi6YEwQ0= @@ -1295,11 +1288,12 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/subosito/gotenv v1.3.0 h1:mjC+YW8QpAdXibNi+vNWgzmgBH4+5l5dCXv8cNysBLI= -github.com/subosito/gotenv v1.3.0/go.mod h1:YzJjq/33h7nrwdY+iHMhEOEEbW0ovIz0tB6t6PwAXzs= +github.com/subosito/gotenv v1.4.0 h1:yAzM1+SmVcz5R4tXGsNMu1jUl2aOJXoiWUCEwwnGrvs= +github.com/subosito/gotenv v1.4.0/go.mod h1:mZd6rFysKEcUhUHXJk0C/08wAgyDBFuwEYL7vWWGaGo= github.com/sylvia7788/contextcheck v1.0.4 h1:MsiVqROAdr0efZc/fOCt0c235qm9XJqHtWwM+2h2B04= github.com/sylvia7788/contextcheck v1.0.4/go.mod h1:vuPKJMQ7MQ91ZTqfdyreNKwZjyUg6KO+IebVyQDedZQ= github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= @@ -1334,11 +1328,12 @@ github.com/tidwall/sjson v1.1.4/go.mod h1:wXpKXu8CtDjKAZ+3DrKY5ROCorDFahq8l0tey/ github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144 h1:kl4KhGNsJIbDHS9/4U9yQo1UcPQM0kOMJHn29EoH/Ro= github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= github.com/tinylib/msgp v1.1.5/go.mod h1:eQsjooMTnV42mHu917E26IogZ2930nFyBQdofk10Udg= +github.com/tj/assert v0.0.3 h1:Df/BlaZ20mq6kuai7f5z2TvPFiwC3xaWJSDQNiIS3Rk= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20200427203606-3cfed13b9966/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/tomarrell/wrapcheck/v2 v2.6.1 h1:Cf4a/iwuMp9s7kKrh74GTgijRVim0wEpKjgAsT7Wctw= -github.com/tomarrell/wrapcheck/v2 v2.6.1/go.mod h1:Eo+Opt6pyMW1b6cNllOcDSSoHO0aTJ+iF6BfCUbHltA= +github.com/tomarrell/wrapcheck/v2 v2.6.2 h1:3dI6YNcrJTQ/CJQ6M/DUkc0gnqYSIk6o0rChn9E/D0M= +github.com/tomarrell/wrapcheck/v2 v2.6.2/go.mod h1:ao7l5p0aOlUNJKI0qVwB4Yjlqutd0IvAB9Rdwyilxvg= github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce/go.mod h1:o8v6yHRoik09Xen7gje4m9ERNah1d1PPsVq1VEx9vE4= github.com/tommy-muehle/go-mnd/v2 v2.5.0 h1:iAj0a8e6+dXSL7Liq0aXPox36FiN1dBbjA6lt9fl65s= github.com/tommy-muehle/go-mnd/v2 v2.5.0/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= @@ -1359,8 +1354,8 @@ github.com/ultraware/whitespace v0.0.5 h1:hh+/cpIcopyMYbZNVov9iSxvJU3OYQg78Sfaqz github.com/ultraware/whitespace v0.0.5/go.mod h1:aVMh/gQve5Maj9hQ/hg+F75lr/X5A89uZnzAmWSineA= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/uudashr/gocognit v1.0.5 h1:rrSex7oHr3/pPLQ0xoWq108XMU8s678FJcQ+aSfOHa4= -github.com/uudashr/gocognit v1.0.5/go.mod h1:wgYz0mitoKOTysqxTDMOUXg+Jb5SvtihkfmugIZYpEA= +github.com/uudashr/gocognit v1.0.6 h1:2Cgi6MweCsdB6kpcVQp7EW4U23iBFQWfTXiWlyp842Y= +github.com/uudashr/gocognit v1.0.6/go.mod h1:nAIUuVBnYU7pcninia3BHOvQkpQCeO76Uscky5BOwcY= github.com/viki-org/dnscache v0.0.0-20130720023526-c70c1f23c5d8/go.mod h1:dniwbG03GafCjFohMDmz6Zc6oCuiqgH6tGNyXTkHzXE= github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= @@ -1399,8 +1394,8 @@ github.com/zimmski/osutil v0.0.0-20190128123334-0d0b3ca231ac h1:uiFRlKzyIzHeLOth github.com/zimmski/osutil v0.0.0-20190128123334-0d0b3ca231ac/go.mod h1:wJ9WGevuM/rw8aB2pQPFMUgXZWeaouI0ueFamR0DUPE= github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8= github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= -gitlab.com/bosi/decorder v0.2.1 h1:ehqZe8hI4w7O4b1vgsDZw1YU1PE7iJXrQWFMsocbQ1w= -gitlab.com/bosi/decorder v0.2.1/go.mod h1:6C/nhLSbF6qZbYD8bRmISBwc6vcWdNsiIBkRvjJFrH0= +gitlab.com/bosi/decorder v0.2.2 h1:LRfb3lP6mZWjUzpMOCLTVjcnl/SqZWBWmKNqQvMocQs= +gitlab.com/bosi/decorder v0.2.2/go.mod h1:9K1RB5+VPNQYtXtTDAzd2OEftsZb1oV0IrJrzChSdGE= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= @@ -1411,13 +1406,10 @@ go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mI go.etcd.io/etcd v0.0.0-20200513171258-e048e166ab9c/go.mod h1:xCI7ZzBfRuGgBXyXO6yfWfDmlWd35khcWpUa4L0xI/k= go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/api/v3 v3.5.1/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= -go.etcd.io/etcd/api/v3 v3.5.2/go.mod h1:5GB2vv4A4AOn3yk7MftYGHkUfGtDHnEraIjym4dYz5A= go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/pkg/v3 v3.5.1/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= -go.etcd.io/etcd/client/pkg/v3 v3.5.2/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= go.etcd.io/etcd/client/v2 v2.305.1/go.mod h1:pMEacxZW7o8pg4CrFE7pquyCJJzZvkvdD2RibOCCCGs= -go.etcd.io/etcd/client/v2 v2.305.2/go.mod h1:2D7ZejHVMIfog1221iLSYlQRzrtECw3kz4I4VAQm3qI= go.etcd.io/etcd/client/v3 v3.5.0/go.mod h1:AIKXXVX/DQXtfTEqBryiLTUXwON+GuvO6Z7lLS/oTh0= go.mozilla.org/mozlog v0.0.0-20170222151521-4bb13139d403/go.mod h1:jHoPAGnDrCy6kaI2tAze5Prf0Nr0w/oNkROt2lw3n3o= go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= @@ -1435,17 +1427,21 @@ go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.11-0.20210813005559-691160354723 h1:sHOAIxRGBp443oHZIPB+HsUGaksVCXVQENPxwTfQdH4= go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.4.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/multierr v1.7.0 h1:zaiO/rmgFjbmCXdSYJWQcdvOCsthmdaHfr3Gm2Kx4Ec= go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= +go.uber.org/zap v1.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI= go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180501155221-613d6eafa307/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= @@ -1478,9 +1474,8 @@ golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20210915214749-c084706c2272/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20220313003712-b769efc7c000/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA= -golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e h1:T8NU3HyQ8ClP4SEE+KbFlg6n0NhuTsN4MyznaarGsZM= +golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -1529,8 +1524,9 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1597,8 +1593,6 @@ golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211208012354-db4efeb81f4b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 h1:NWy5+hlRbC7HK+PmcXVUmW1IMyFce7to56IUvhUFm7Y= golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -1619,8 +1613,6 @@ golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20211005180243-6b3c2da341f1/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= -golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= -golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1741,14 +1733,11 @@ golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220702020025-31831981b65f h1:xdsejrW/0Wf2diT5CPp3XmKUNbr7Xvw8kYilQ+6qjRY= +golang.org/x/sys v0.0.0-20220702020025-31831981b65f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -1827,7 +1816,6 @@ golang.org/x/tools v0.0.0-20200324003944-a576cf524670/go.mod h1:Sl4aGygMT6LrqrWc golang.org/x/tools v0.0.0-20200329025819-fd4102a86c65/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200414032229-332987a829c3/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200422022333-3d57cf2e726e/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200426102838-f3a5411a4c3b/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -1873,15 +1861,12 @@ golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.9-0.20211228192929-ee1ca4ffc4da/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= -golang.org/x/tools v0.1.11-0.20220316014157-77aa08bb151a h1:ofrrl6c6NG5/IOSx/R1cyiQxxjqlur0h/TvbUhkH0II= -golang.org/x/tools v0.1.11-0.20220316014157-77aa08bb151a/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= +golang.org/x/tools v0.1.11 h1:loJ25fNOEhSXfHrpoGj91eCUThwdNX6u24rO1xnNteY= +golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df h1:5Pf6pFKu98ODmgnpvkJ3kFUOQGGLIzLIkbzUHp47618= -golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0= gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= @@ -1920,10 +1905,6 @@ google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdr google.golang.org/api v0.59.0/go.mod h1:sT2boj7M9YJxZzgeZqXogmhfmRWDtPzT31xkieUbuZU= google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I= google.golang.org/api v0.63.0/go.mod h1:gs4ij2ffTRXwuzzgJl/56BdwJaA194ijkfn++9tDuPo= -google.golang.org/api v0.67.0/go.mod h1:ShHKP8E60yPsKNw/w8w+VYaj9H6buA5UqDp8dhbQZ6g= -google.golang.org/api v0.70.0/go.mod h1:Bs4ZM2HGifEvXwd50TtW70ovgJffJYw2oRCOFU/SkfA= -google.golang.org/api v0.71.0/go.mod h1:4PyU6e6JogV1f9eA4voyrTY2batOLdgZ5qZ5HOCc4j8= -google.golang.org/api v0.74.0/go.mod h1:ZpfMZOVRMywNyvJFeqL9HRWBgAuRfSjJFpe9QtRRyDs= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -2006,15 +1987,6 @@ google.golang.org/genproto v0.0.0-20211028162531-8db9c33dc351/go.mod h1:5CzLGKJ6 google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20211221195035-429b39de9b1c/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20220126215142-9970aeb2e350/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20220207164111-0872dc986b00/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20220218161850-94dd64e39d7c/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= -google.golang.org/genproto v0.0.0-20220222213610-43724f9ea8cf/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= -google.golang.org/genproto v0.0.0-20220304144024-325a89244dc8/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= -google.golang.org/genproto v0.0.0-20220310185008-1973136f34c6/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= -google.golang.org/genproto v0.0.0-20220324131243-acbaeb5b85eb/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= -google.golang.org/genproto v0.0.0-20220407144326-9054f6ed7bac/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd h1:e0TwkXOdbnH/1x5rc5MZ/VYyiZ4v+RdVfrGMqEwT68I= google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= google.golang.org/grpc v1.33.2 h1:EQyQC3sa8M+p6Ulc8yy9SWSS2GVwyRc83gAbG8lrl4o= @@ -2051,8 +2023,8 @@ gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMy gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/ini.v1 v1.66.4 h1:SsAcf+mM7mRZo2nJNGt8mZCjG8ZRaNGMURJw7BsIST4= -gopkg.in/ini.v1 v1.66.4/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.66.6 h1:LATuAqN/shcYAOkv3wl2L4rkaKqkcgTBQjOyYDvcPKI= +gopkg.in/ini.v1 v1.66.6/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= gopkg.in/olebedev/go-duktape.v3 v3.0.0-20200619000410-60c24ae608a6/go.mod h1:uAJfkITjFhyEEuUfm7bsmCZRbW5WRq8s9EY8HZ6hCns= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= @@ -2086,8 +2058,8 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.3.1 h1:1kJlrWJLkaGXgcaeosRXViwviqjI7nkBvU2+sZW0AYc= -honnef.co/go/tools v0.3.1/go.mod h1:vlRD9XErLMGT+mDuofSr0mMMquscM/1nQqtRSsh6m70= +honnef.co/go/tools v0.3.2 h1:ytYb4rOqyp1TSa2EPvNVwtPQJctSELKaMyLfqNP4+34= +honnef.co/go/tools v0.3.2/go.mod h1:jzwdWgg7Jdq75wlfblQxO4neNaFFSvgc1tD5Wv8U0Yw= mvdan.cc/gofumpt v0.3.1 h1:avhhrOmv0IuvQVK7fvwV91oFSGAk5/6Po8GXTzICeu8= mvdan.cc/gofumpt v0.3.1/go.mod h1:w3ymliuxvzVx8DAutBnVyDqYb1Niy/yCJt/lk821YCE= mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed h1:WX1yoOaKQfddO/mLzdV4wptyWgoH/6hwLs7QHTixo0I= From 6d162fa1bd3f7ed5ffb007cf3a174a1ecbbbe5fd Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Mon, 18 Jul 2022 19:21:16 -0700 Subject: [PATCH 099/376] fix IsActive test (#2136) --- x/gamm/pool-models/balancer/pool_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go index f96943d7510..cab4a06952f 100644 --- a/x/gamm/pool-models/balancer/pool_test.go +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -1196,7 +1196,7 @@ func TestBalancerPoolPokeTokenWeights(t *testing.T) { // This test (currently trivially) checks to make sure that `IsActive` returns true for balancer pools. // This is mainly to make sure that if IsActive is ever used as an emergency switch, it is not accidentally left off for any (or all) pools. // TODO: create a test with mocks to make sure IsActive works as intended when flipped for specific pools/all pools -func (suite *BalancerTestSuite) TestIsActive(t *testing.T) { +func TestIsActive(t *testing.T) { tests := map[string]struct { expectedIsActive bool }{ @@ -1207,7 +1207,7 @@ func (suite *BalancerTestSuite) TestIsActive(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { - ctx := suite.CreateTestContext() + ctx := sdk.Context{} // Initialize a pool pool, err := balancer.NewBalancerPool(defaultPoolId, defaultBalancerPoolParams, dummyPoolAssets, defaultFutureGovernor, defaultCurBlockTime) From 8efe39411f3df9d48a7235fcc57ce12133149115 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Mon, 18 Jul 2022 22:41:37 -0500 Subject: [PATCH 100/376] Speedup mint keeper tests (20x locally) (#2137) * Speedup mint keeper tests (20x locally) * driveby, fix 20 line code duplication --- x/mint/keeper/genesis_test.go | 7 --- x/mint/keeper/grpc_query_test.go | 7 --- x/mint/keeper/hooks_test.go | 78 ++++++-------------------------- x/mint/keeper/keeper_test.go | 3 ++ 4 files changed, 17 insertions(+), 78 deletions(-) diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index dce0c939a66..078d0ca623c 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -1,11 +1,8 @@ package keeper_test import ( - "testing" - sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/stretchr/testify/suite" "github.com/osmosis-labs/osmosis/v10/osmoutils" "github.com/osmosis-labs/osmosis/v10/x/mint/keeper" @@ -39,10 +36,6 @@ var customGenesis = types.NewGenesisState( 2), // minting reward distribution start epoch 3) // halven started epoch -func TestMintGenesisTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - // TestMintInitGenesis tests that genesis is initialized correctly // with different parameters and state. func (suite *KeeperTestSuite) TestMintInitGenesis() { diff --git a/x/mint/keeper/grpc_query_test.go b/x/mint/keeper/grpc_query_test.go index a53e74b8c0c..19be91c22b6 100644 --- a/x/mint/keeper/grpc_query_test.go +++ b/x/mint/keeper/grpc_query_test.go @@ -2,17 +2,10 @@ package keeper_test import ( gocontext "context" - "testing" - - "github.com/stretchr/testify/suite" "github.com/osmosis-labs/osmosis/v10/x/mint/types" ) -func TestMintGRPCQueryTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - func (suite *KeeperTestSuite) TestGRPCParams() { _, _, queryClient := suite.App, suite.Ctx, suite.queryClient diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index 283e2cc6a6f..e262e9d3c63 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -1,35 +1,25 @@ package keeper_test import ( - "testing" "time" - "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" osmoapp "github.com/osmosis-labs/osmosis/v10/app" - lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" "github.com/osmosis-labs/osmosis/v10/x/mint/keeper" "github.com/osmosis-labs/osmosis/v10/x/mint/types" - "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" ) -func TestMintHooksTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { - app := osmoapp.Setup(false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + app := suite.App + ctx := suite.Ctx header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - setupGaugeForLPIncentives(suite, app, ctx) - params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) @@ -115,21 +105,19 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { } func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmpty() { - app := osmoapp.Setup(false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + app := suite.App + ctx := suite.Ctx header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - setupGaugeForLPIncentives(suite, app, ctx) - params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) height := int64(1) lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) - // correct rewards - for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { + + checkDistribution := func(height int64) { devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) devRewardsModuleOrigin := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) @@ -153,6 +141,11 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp suite.Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) } + // correct rewards + for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { + checkDistribution(height) + } + app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) @@ -160,34 +153,13 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp suite.Equal(lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { - devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) - devRewardsModuleOrigin := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) - - app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) - app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - - mintParams := app.MintKeeper.GetParams(ctx) - mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking.Add(mintParams.DistributionProportions.DeveloperRewards)) - suite.NoError(err) - expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) - - // check community pool balance increase - feePoolNew := app.DistrKeeper.GetFeePool(ctx) - suite.Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, expectedRewards.String()) - - // test that the dev rewards module account balance decreased by the correct amount - devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.NoError(err) - suite.Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) + checkDistribution(height) } } func (suite *KeeperTestSuite) TestEndOfEpochNoDistributionWhenIsNotYetStartTime() { - app := osmoapp.Setup(false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + app := suite.App + ctx := suite.Ctx mintParams := app.MintKeeper.GetParams(ctx) mintParams.MintingRewardsDistributionStartEpoch = 4 @@ -196,8 +168,6 @@ func (suite *KeeperTestSuite) TestEndOfEpochNoDistributionWhenIsNotYetStartTime( header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - setupGaugeForLPIncentives(suite, app, ctx) - params := app.IncentivesKeeper.GetParams(ctx) futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) @@ -436,23 +406,3 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete suite.Equal(mainnetThirdenedProvisions, expectedThirdenedProvisions.String()) suite.Equal(expectedThirdenedProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions) } - -func setupGaugeForLPIncentives(suite *KeeperTestSuite, app *osmoapp.OsmosisApp, ctx sdk.Context) { - addr := sdk.AccAddress([]byte("addr1---------------")) - coins := sdk.Coins{sdk.NewInt64Coin("stake", 10000)} - err := simapp.FundAccount(app.BankKeeper, ctx, addr, coins) - suite.NoError(err) - distrTo := lockuptypes.QueryCondition{ - LockQueryType: lockuptypes.ByDuration, - Denom: "lptoken", - Duration: time.Second, - } - - // mints coins so supply exists on chain - mintLPtokens := sdk.Coins{sdk.NewInt64Coin(distrTo.Denom, 200)} - err = simapp.FundAccount(app.BankKeeper, ctx, addr, mintLPtokens) - suite.NoError(err) - - _, err = app.IncentivesKeeper.CreateGauge(ctx, true, addr, coins, distrTo, time.Now(), 1) - suite.NoError(err) -} diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index ecde05b23c7..4075748cc7c 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -44,6 +44,9 @@ func (suite *KeeperTestSuite) SetupTest() { suite.Setup() suite.queryClient = types.NewQueryClient(suite.QueryHelper) + params := suite.App.MintKeeper.GetParams(suite.Ctx) + params.ReductionPeriodInEpochs = 10 + suite.App.MintKeeper.SetParams(suite.Ctx, params) } // setupDeveloperVestingModuleAccountTest sets up test cases that utilize developer vesting From 1d8653dbd9028710f86c08704dadeeb3a3d66641 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 19 Jul 2022 00:21:08 -0400 Subject: [PATCH 101/376] refactor(x/mint): introduce distributeDeveloperRewards methods; unit tests (2/2) (#2073) * refactor(x/mint): introduce distributeDeveloperRewards methods; unit tests * clean up * Apply suggestions from code review * comment formatting * minimize diff * reuse address * allow minting to empty address and tests * empty address clean up * more clean up --- x/mint/keeper/export_test.go | 6 +++-- x/mint/keeper/keeper.go | 36 ++++++++++++++++++++------ x/mint/keeper/keeper_test.go | 50 +++++++++++++++++++++++++++++++++--- 3 files changed, 78 insertions(+), 14 deletions(-) diff --git a/x/mint/keeper/export_test.go b/x/mint/keeper/export_test.go index 6c27f1aebbb..2bd23cf73c2 100644 --- a/x/mint/keeper/export_test.go +++ b/x/mint/keeper/export_test.go @@ -7,11 +7,13 @@ import ( ) type ( - ErrInvalidRatio = invalidRatioError + ErrInvalidRatio = invalidRatioError + ErrInsufficientDevVestingBalance = insufficientDevVestingBalanceError ) const ( - DeveloperVestingAmount = developerVestingAmount + EmptyWeightedAddressReceiver = emptyWeightedAddressReceiver + DeveloperVestingAmount = developerVestingAmount ) var ( diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index cdcde523f81..e0e8579459a 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -36,6 +36,17 @@ func (e invalidRatioError) Error() string { return fmt.Sprintf("mint allocation ratio (%s) is greater than 1", e.ActualRatio) } +type insufficientDevVestingBalanceError struct { + ActualBalance sdk.Int + AttemptedDistribution sdk.Int +} + +func (e insufficientDevVestingBalanceError) Error() string { + return fmt.Sprintf("developer vesting balance (%s) is smaller than requested distribution of (%s)", e.ActualBalance, e.AttemptedDistribution) +} + +const emptyWeightedAddressReceiver = "" + // NewKeeper creates a new mint Keeper instance. func NewKeeper( cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace, @@ -249,27 +260,35 @@ func (k Keeper) distributeToModule(ctx sdk.Context, recipientModule string, mint // - the balance of mint module is less than totalMintedCoin * developerRewardsProportion. // CONTRACT: // - weights in developerRewardsReceivers add up to 1. -// - addresses in developerRewardsReceivers are valid. +// - addresses in developerRewardsReceivers are valid or empty string. func (k Keeper) distributeDeveloperRewards(ctx sdk.Context, totalMintedCoin sdk.Coin, developerRewardsProportion sdk.Dec, developerRewardsReceivers []types.WeightedAddress) (sdk.Int, error) { devRewardCoin, err := getProportions(ctx, totalMintedCoin, developerRewardsProportion) if err != nil { return sdk.Int{}, err } + + developerRewardsModuleAccountAddress := k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName) + developerAccountBalance := k.bankKeeper.GetBalance(ctx, developerRewardsModuleAccountAddress, totalMintedCoin.Denom) + if developerAccountBalance.Amount.LT(devRewardCoin.Amount) { + return sdk.Int{}, insufficientDevVestingBalanceError{ActualBalance: developerAccountBalance.Amount, AttemptedDistribution: devRewardCoin.Amount} + } + devRewardCoins := sdk.NewCoins(devRewardCoin) - // This is supposed to come from the developer vesting module address, not the mint module address - // we over-allocated to the mint module address earlier though, so we burn it right here. + // TODO: https://github.com/osmosis-labs/osmosis/issues/2025 + // Avoid over-allocating from the mint module address and have to later burn it here: if err := k.bankKeeper.BurnCoins(ctx, types.ModuleName, devRewardCoins); err != nil { return sdk.Int{}, err } // Take the current balance of the developer rewards pool and remove it from the supply offset // We re-introduce the new supply at the end, in order to avoid any rounding discrepancies. - developerAccountBalance := k.bankKeeper.GetBalance(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), totalMintedCoin.Denom) k.bankKeeper.AddSupplyOffset(ctx, totalMintedCoin.Denom, developerAccountBalance.Amount) + // If no developer rewards receivers provided, fund the community pool from + // the developer vesting module account. if len(developerRewardsReceivers) == 0 { - // fund community pool when rewards address is empty - if err := k.distrKeeper.FundCommunityPool(ctx, devRewardCoins, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)); err != nil { + err = k.distrKeeper.FundCommunityPool(ctx, devRewardCoins, developerRewardsModuleAccountAddress) + if err != nil { return sdk.Int{}, err } } else { @@ -280,7 +299,8 @@ func (k Keeper) distributeDeveloperRewards(ctx sdk.Context, totalMintedCoin sdk. return sdk.Int{}, err } devRewardPortionCoins := sdk.NewCoins(devPortionCoin) - if w.Address == "" { + // fund community pool when rewards address is empty. + if w.Address == emptyWeightedAddressReceiver { err := k.distrKeeper.FundCommunityPool(ctx, devRewardPortionCoins, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) if err != nil { @@ -302,7 +322,7 @@ func (k Keeper) distributeDeveloperRewards(ctx sdk.Context, totalMintedCoin sdk. } // Take the new balance of the developer rewards pool and add it back to the supply offset deduction - developerAccountBalance = k.bankKeeper.GetBalance(ctx, k.accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), totalMintedCoin.Denom) + developerAccountBalance = k.bankKeeper.GetBalance(ctx, developerRewardsModuleAccountAddress, totalMintedCoin.Denom) k.bankKeeper.AddSupplyOffset(ctx, totalMintedCoin.Denom, developerAccountBalance.Amount.Neg()) return devRewardCoin.Amount, nil diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 4075748cc7c..1eb27fc2056 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -7,11 +7,11 @@ import ( "github.com/cosmos/btcutil/bech32" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/distribution" distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -669,7 +669,35 @@ func (suite *KeeperTestSuite) TestDistributeDeveloperRewards() { Weight: sdk.NewDec(1), }, }, - expectedError: sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, fmt.Sprintf("%s is smaller than %s", validPreMintCoin, sdk.NewCoin(sdk.DefaultBondDenom, validPreMintAmountAddOne))), + expectedError: keeper.ErrInsufficientDevVestingBalance{ActualBalance: validPreMintCoin.Amount, AttemptedDistribution: validPreMintAmountAddOne}, + }, + "valid case with 1 empty string weighted address - distributes to community pool": { + preMintCoin: validPreMintCoin, + + mintedCoin: validPreMintCoin, + proportion: sdk.NewDecWithPrec(153, 3), + recepientAddresses: []types.WeightedAddress{ + { + Address: keeper.EmptyWeightedAddressReceiver, + Weight: sdk.NewDec(1), + }, + }, + }, + "valid case with 2 addresses - empty string (distributes to community pool) and regular address (distributes to the address)": { + preMintCoin: validPreMintCoin, + + mintedCoin: validPreMintCoin, + proportion: sdk.NewDecWithPrec(153, 3), + recepientAddresses: []types.WeightedAddress{ + { + Address: keeper.EmptyWeightedAddressReceiver, + Weight: sdk.NewDec(1), + }, + { + Address: testAddressOne.String(), + Weight: sdk.NewDec(1), + }, + }, }, } for name, tc := range tests { @@ -694,6 +722,10 @@ func (suite *KeeperTestSuite) TestDistributeDeveloperRewards() { oldCommunityPoolBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(distributiontypes.ModuleName), tc.mintedCoin.Denom).Amount oldDeveloperRewardsBalanceAmounts := make([]sdk.Int, len(tc.recepientAddresses)) for i, weightedAddress := range tc.recepientAddresses { + if weightedAddress.Address == keeper.EmptyWeightedAddressReceiver { + continue + } + // No error check to be able to test invalid addresses. address, _ := sdk.AccAddressFromBech32(weightedAddress.Address) oldDeveloperRewardsBalanceAmounts[i] = bankKeeper.GetBalance(ctx, address, tc.mintedCoin.Denom).Amount @@ -742,12 +774,20 @@ func (suite *KeeperTestSuite) TestDistributeDeveloperRewards() { // TODO: these should be equal, slightly off due to known rounding issues: https://github.com/osmosis-labs/osmosis/issues/1917 // suite.Equal(oldDeveloperVestingModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) + expectedDistributedCommunityPool := sdk.NewInt(0) + for i, weightedAddress := range tc.recepientAddresses { + // TODO: truncation should not occur: https://github.com/osmosis-labs/osmosis/issues/1917 + expectedAllocation := expectedDistributed.ToDec().Mul(tc.recepientAddresses[i].Weight).TruncateInt() + + if weightedAddress.Address == keeper.EmptyWeightedAddressReceiver { + expectedDistributedCommunityPool = expectedDistributedCommunityPool.Add(expectedAllocation) + continue + } + address, err := sdk.AccAddressFromBech32(weightedAddress.Address) suite.NoError(err) - // TODO: truncation should not occur: https://github.com/osmosis-labs/osmosis/issues/1917 - expectedAllocation := expectedDistributed.ToDec().Mul(tc.recepientAddresses[i].Weight).TruncateInt() actualDeveloperRewardsBalanceAmounts := bankKeeper.GetBalance(ctx, address, tc.mintedCoin.Denom).Amount // Edge case. See testcases with this flag set to true for details. @@ -758,6 +798,8 @@ func (suite *KeeperTestSuite) TestDistributeDeveloperRewards() { suite.Equal(oldDeveloperRewardsBalanceAmounts[i].Add(expectedAllocation).Int64(), actualDeveloperRewardsBalanceAmounts.Int64()) } + + suite.Equal(oldCommunityPoolBalanceAmount.Add(expectedDistributedCommunityPool).Int64(), actualCommunityPoolModuleBalanceAmount.Int64()) }) }) } From 69126dd7e13eb0cf62d5a9bd39174114c3661112 Mon Sep 17 00:00:00 2001 From: Xiangan He <76530366+xBalbinus@users.noreply.github.com> Date: Tue, 19 Jul 2022 09:33:21 -0400 Subject: [PATCH 102/376] Contributing.md e2e testing additions (#2120) * contributing.md e2e testing additions * superlinter fixes * Update CONTRIBUTING.md Co-authored-by: Roman * Update CONTRIBUTING.md Co-authored-by: Roman * Update CONTRIBUTING.md Co-authored-by: Roman Co-authored-by: Roman --- CONTRIBUTING.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8be1c8f2290..bf75d7beb35 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -317,6 +317,26 @@ func TestGetPoolAssetsByDenom(t *testing.T) { } ``` +## Debug testing e2e locally + +The e2e package defines an integration testing suite used for full end-to-end testing functionality. This package is decoupled from depending on the Osmosis codebase. It initializes the chains for testing via Docker files. + +As a result, the test suite may provide the desired Osmosis version to Docker containers during the initialization. This design allows for the opportunity of testing chain upgrades in the future by providing an older Osmosis version to the container, performing the chain upgrade, and running the latest test suite. + +The file `e2e_setup_test.go` defines the testing suite and contains the core bootstrapping logic that creates a testing environment via Docker containers. A testing network is created dynamically by providing the desirable number of validator configurations. + +The file `e2e_test.go` contains the actual end-to-end integration tests that utilize the testing suite. + + +Additionally, there is an ability to disable certain components of the e2e suite. This can be done by setting the environment variables. See the [E2E test docs](https://github.com/osmosis-labs/osmosis/blob/main/tests/e2e/README.md) or more details. + +To get started: +- Run `make test-e2e` +- Inspect the logs of the docker containers and see if something it’s there +- `docker ps -a #` to list all docker containers +- Note the container id of the one you want to see the logs +- And then run `docker logs ` to debug via container logs + ## Working with the SDK ### Updating dependencies for builds From ce51825f200e09078ec605d3a1c9165ee737a6c6 Mon Sep 17 00:00:00 2001 From: Xiangan He <76530366+xBalbinus@users.noreply.github.com> Date: Tue, 19 Jul 2022 11:25:29 -0400 Subject: [PATCH 103/376] Package Godocs improvements and additions (#2064) * ante, app, cmd, osmomath package doc additions * wasmbindings, epochs, and gamm doc additions * modules, proto godocs additions * proto godocs additions * make proto-gen * godocs in all module.go; package godocs * sync w main * godocs naming conventions followed * Update ante/sendblock.go Co-authored-by: Roman * Update app/apptesting/gamm.go Co-authored-by: Roman * Update app/apptesting/gamm.go Co-authored-by: Roman * Update app/apptesting/gamm.go Co-authored-by: Roman * Update app/keepers/keys.go Co-authored-by: Roman * Update app/keepers/keys.go Co-authored-by: Roman * Update app/modules.go Co-authored-by: Roman * Update app/params/config.go Co-authored-by: Roman * Update cmd/osmosisd/cmd/init.go Co-authored-by: Roman * Update app/apptesting/test_suite.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update app/apptesting/test_suite.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update app/forks.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update cmd/osmosisd/cmd/genesis.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update cmd/osmosisd/cmd/testnet.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update proto/osmosis/gamm/pool-models/balancer/tx/tx.proto Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update app/keepers/keys.go Co-authored-by: Roman * Update osmomath/decimal.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update proto/osmosis/pool-incentives/v1beta1/query.proto Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update wasmbinding/message_plugin.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update wasmbinding/message_plugin.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * Update osmomath/decimal.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> * docs clarifications * make all * indirect fix Co-authored-by: Roman Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> --- ante/sendblock.go | 4 ++++ app/app.go | 1 + app/apptesting/gamm.go | 5 ++++- app/apptesting/test_suite.go | 11 +++++++++++ app/config.go | 1 + app/forks.go | 2 +- app/keepers/keepers.go | 3 +++ app/keepers/keys.go | 5 +++++ app/modules.go | 1 + app/params/config.go | 2 ++ cmd/osmosisd/cmd/balances_from_state_export.go | 3 +++ cmd/osmosisd/cmd/forceprune.go | 5 ++++- cmd/osmosisd/cmd/genesis.go | 1 + cmd/osmosisd/cmd/init.go | 2 ++ cmd/osmosisd/cmd/root.go | 5 +++++ cmd/osmosisd/cmd/testnet.go | 5 +++-- go.mod | 2 +- osmomath/decimal.go | 13 +++++++++---- osmomath/int.go | 4 ++++ osmomath/sigfig_round.go | 1 + proto/osmosis/gamm/pool-models/balancer/tx/tx.proto | 1 + proto/osmosis/gamm/pool-models/stableswap/tx.proto | 6 ++++-- proto/osmosis/pool-incentives/v1beta1/query.proto | 7 ++++++- proto/osmosis/txfees/v1beta1/query.proto | 5 ++++- wasmbinding/message_plugin.go | 12 ++++++++++++ wasmbinding/queries.go | 4 ++++ wasmbinding/query_plugin.go | 1 + x/epochs/keeper/epoch.go | 1 + x/epochs/keeper/genesis.go | 2 +- x/epochs/keeper/grpc_query.go | 1 + x/epochs/keeper/hooks.go | 2 ++ x/epochs/keeper/keeper.go | 1 + x/epochs/module.go | 13 +++++++++++++ x/epochs/types/doc.go | 4 ++++ x/epochs/types/genesis.go | 1 + x/gamm/keeper/grpc_query.go | 10 ++++++++++ x/gamm/keeper/msg_server.go | 4 ++++ x/gamm/module.go | 9 +++++++++ x/gamm/pool-models/balancer/tx.pb.go | 1 + x/gamm/pool-models/stableswap/tx.pb.go | 6 ++++-- x/incentives/module.go | 8 ++++++++ x/lockup/keeper/iterator.go | 11 ++++++++++- x/lockup/module.go | 11 +++++++++++ x/mint/module.go | 9 +++++++++ x/pool-incentives/module.go | 10 ++++++++++ x/pool-incentives/spec/README.md | 2 +- x/pool-incentives/types/query.pb.go | 10 ++++++++++ x/superfluid/module.go | 7 +++++++ x/tokenfactory/module.go | 8 ++++++++ x/txfees/module.go | 9 +++++++++ x/txfees/types/query.pb.go | 10 ++++++++-- 51 files changed, 241 insertions(+), 21 deletions(-) create mode 100644 x/epochs/types/doc.go diff --git a/ante/sendblock.go b/ante/sendblock.go index c34faba4d38..9c01049423e 100644 --- a/ante/sendblock.go +++ b/ante/sendblock.go @@ -14,12 +14,14 @@ type SendBlockOptions struct { PermittedOnlySendTo map[string]string } +// NewSendBlockOptions returns options for sending new blocks. func NewSendBlockOptions(appOpts servertypes.AppOptions) SendBlockOptions { return SendBlockOptions{ PermittedOnlySendTo: parsePermittedOnlySendTo(appOpts), } } +// parsePermittedOnlySendTo parses the mapping PermittedOnlySendTo. func parsePermittedOnlySendTo(opts servertypes.AppOptions) map[string]string { valueInterface := opts.Get("permitted-only-send-to") if valueInterface == nil { @@ -32,12 +34,14 @@ type SendBlockDecorator struct { Options SendBlockOptions } +// NewSendBlockDecorator are a part of auth module AnteDecorators that are recursively chained together into a single AntiHandler. func NewSendBlockDecorator(options SendBlockOptions) *SendBlockDecorator { return &SendBlockDecorator{ Options: options, // TODO: hydrate from configuration } } +// AnteHandle is used for performing basic validity checks on a transaction such that it can be thrown out of the mempool. func (decorator *SendBlockDecorator) AnteHandle( ctx sdk.Context, tx sdk.Tx, diff --git a/app/app.go b/app/app.go index cdff0cfe18d..815acd94cd1 100644 --- a/app/app.go +++ b/app/app.go @@ -132,6 +132,7 @@ type OsmosisApp struct { configurator module.Configurator } +// init sets DefaultNodeHome to default osmosisd install location. func init() { userHomeDir, err := os.UserHomeDir() if err != nil { diff --git a/app/apptesting/gamm.go b/app/apptesting/gamm.go index 87a43c74f84..f269249be34 100644 --- a/app/apptesting/gamm.go +++ b/app/apptesting/gamm.go @@ -14,7 +14,7 @@ var DefaultAcctFunds sdk.Coins = sdk.NewCoins( sdk.NewCoin("baz", sdk.NewInt(10000000)), ) -// Returns a Univ2 pool with the initial liquidity being the provided balances +// PrepareUni2PoolWithAssets returns a Univ2 pool with the initial liquidity being the provided balances. func (s *KeeperTestHelper) PrepareUni2PoolWithAssets(asset1, asset2 sdk.Coin) uint64 { return s.PrepareBalancerPoolWithPoolAsset( []balancer.PoolAsset{ @@ -30,6 +30,7 @@ func (s *KeeperTestHelper) PrepareUni2PoolWithAssets(asset1, asset2 sdk.Coin) ui ) } +// PrepareBalancerPool returns a Balancer pool's pool-ID with pool params set in PrepareBalancerPoolWithPoolParams. func (s *KeeperTestHelper) PrepareBalancerPool() uint64 { poolId := s.PrepareBalancerPoolWithPoolParams(balancer.PoolParams{ SwapFee: sdk.NewDec(0), @@ -51,6 +52,7 @@ func (s *KeeperTestHelper) PrepareBalancerPool() uint64 { return poolId } +// PrepareBalancerPoolWithPoolParams sets up a Balancer pool with poolParams. func (s *KeeperTestHelper) PrepareBalancerPoolWithPoolParams(poolParams balancer.PoolParams) uint64 { // Mint some assets to the account. s.FundAcc(s.TestAccs[0], DefaultAcctFunds) @@ -75,6 +77,7 @@ func (s *KeeperTestHelper) PrepareBalancerPoolWithPoolParams(poolParams balancer return poolId } +// PrepareBalancerPoolWithPoolAsset sets up a Balancer pool with an array of assets. func (s *KeeperTestHelper) PrepareBalancerPoolWithPoolAsset(assets []balancer.PoolAsset) uint64 { s.Require().Len(assets, 2) diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index 4cb5a7c7d34..9f7a6ecf6eb 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -39,6 +39,7 @@ type KeeperTestHelper struct { TestAccs []sdk.AccAddress } +// Setup sets up basic environment for suite (App, Ctx, and test accounts) func (s *KeeperTestHelper) Setup() { s.App = app.Setup(false) s.Ctx = s.App.BaseApp.NewContext(false, tmtypes.Header{Height: 1, ChainID: "osmosis-1", Time: time.Now().UTC()}) @@ -50,6 +51,7 @@ func (s *KeeperTestHelper) Setup() { s.TestAccs = CreateRandomAccounts(3) } +// CreateTestContext creates a test context. func (s *KeeperTestHelper) CreateTestContext() sdk.Context { db := dbm.NewMemDB() logger := log.NewNopLogger() @@ -59,11 +61,13 @@ func (s *KeeperTestHelper) CreateTestContext() sdk.Context { return sdk.NewContext(ms, tmtypes.Header{}, false, logger) } +// FundAcc funds target address with specified amount. func (s *KeeperTestHelper) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) { err := simapp.FundAccount(s.App.BankKeeper, s.Ctx, acc, amounts) s.Require().NoError(err) } +// SetupValidator sets up a validator and returns the ValAddress. func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sdk.ValAddress { valPub := secp256k1.GenPrivKey().PubKey() valAddr := sdk.ValAddress(valPub.Address()) @@ -98,10 +102,12 @@ func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sd return valAddr } +// SetupTokenFactory sets up a token module account for the TokenFactoryKeeper. func (s *KeeperTestHelper) SetupTokenFactory() { s.App.TokenFactoryKeeper.CreateModuleAccount(s.Ctx) } +// BeginNewBlock starts a new block. func (s *KeeperTestHelper) BeginNewBlock(executeNextEpoch bool) { var valAddr []byte @@ -120,6 +126,7 @@ func (s *KeeperTestHelper) BeginNewBlock(executeNextEpoch bool) { s.BeginNewBlockWithProposer(executeNextEpoch, valAddr) } +// BeginNewBlockWithProposer begins a new block with a proposer. func (s *KeeperTestHelper) BeginNewBlockWithProposer(executeNextEpoch bool, proposer sdk.ValAddress) { validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, proposer) s.Assert().True(found) @@ -152,11 +159,13 @@ func (s *KeeperTestHelper) BeginNewBlockWithProposer(executeNextEpoch bool, prop s.App.BeginBlocker(s.Ctx, reqBeginBlock) } +// EndBlock ends the block. func (s *KeeperTestHelper) EndBlock() { reqEndBlock := abci.RequestEndBlock{Height: s.Ctx.BlockHeight()} s.App.EndBlocker(s.Ctx, reqEndBlock) } +// AllocateRewardsToValidator allocates reward tokens to a distribution module then allocates rewards to the validator address. func (s *KeeperTestHelper) AllocateRewardsToValidator(valAddr sdk.ValAddress, rewardAmt sdk.Int) { validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) s.Require().True(found) @@ -250,6 +259,7 @@ func (s *KeeperTestHelper) SwapAndSetSpotPrice(poolId uint64, fromAsset sdk.Coin return spotPrice } +// LockTokens funds an account, locks tokens and returns a lockID. func (s *KeeperTestHelper) LockTokens(addr sdk.AccAddress, coins sdk.Coins, duration time.Duration) (lockID uint64) { msgServer := lockupkeeper.NewMsgServerImpl(s.App.LockupKeeper) s.FundAcc(addr, coins) @@ -260,6 +270,7 @@ func (s *KeeperTestHelper) LockTokens(addr sdk.AccAddress, coins sdk.Coins, dura return msgResponse.ID } +// BuildTx builds a transaction. func (s *KeeperTestHelper) BuildTx( txBuilder client.TxBuilder, msgs []sdk.Msg, diff --git a/app/config.go b/app/config.go index fd27d842870..95fe40f5557 100644 --- a/app/config.go +++ b/app/config.go @@ -47,6 +47,7 @@ func DefaultConfig() network.Config { } } +// NewAppConstructor returns a new Osmosis app given encoding type configs. func NewAppConstructor(encodingCfg params.EncodingConfig) network.AppConstructor { return func(val network.Validator) servertypes.Application { return NewOsmosisApp( diff --git a/app/forks.go b/app/forks.go index d8268170f0a..e3ca6b4b842 100644 --- a/app/forks.go +++ b/app/forks.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// BeginBlockForks is intended to be ran in. +// BeginBlockForks is intended to be ran in a chain upgrade. func BeginBlockForks(ctx sdk.Context, app *OsmosisApp) { for _, fork := range Forks { if ctx.BlockHeight() == fork.UpgradeHeight { diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index cbd1b94e616..90121bd8fd4 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -118,6 +118,7 @@ type AppKeepers struct { memKeys map[string]*sdk.MemoryStoreKey } +// InitNormalKeepers initializes all 'normal' keepers (account, app, bank, auth, staking, distribution, slashing, transfer, gamm, IBC router, pool incentives, governance, mint, txfees keepers). func (appKeepers *AppKeepers) InitNormalKeepers( appCodec codec.Codec, bApp *baseapp.BaseApp, @@ -367,6 +368,7 @@ func (appKeepers *AppKeepers) InitNormalKeepers( appKeepers.GovKeeper = &govKeeper } +// InitSpecialKeepers initiates special keepers (crisis appkeeper, upgradekeeper, params keeper) func (appKeepers *AppKeepers) InitSpecialKeepers( appCodec codec.Codec, bApp *baseapp.BaseApp, @@ -433,6 +435,7 @@ func (appKeepers *AppKeepers) initParamsKeeper(appCodec codec.BinaryCodec, legac return paramsKeeper } +// SetupHooks sets up hooks for modules. func (appKeepers *AppKeepers) SetupHooks() { // For every module that has hooks set on it, // you must check InitNormalKeepers to ensure that its not passed by de-reference diff --git a/app/keepers/keys.go b/app/keepers/keys.go index 556a0314280..350f50a7279 100644 --- a/app/keepers/keys.go +++ b/app/keepers/keys.go @@ -6,6 +6,7 @@ import ( paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" ) +// GenerateKeys generates new keys (KV Store, Transient store, and memory store). func (appKeepers *AppKeepers) GenerateKeys() { // Define what keys will be used in the cosmos-sdk key/value store. // Cosmos-SDK modules each have a "key" that allows the application to reference what they've stored on the chain. @@ -18,19 +19,23 @@ func (appKeepers *AppKeepers) GenerateKeys() { appKeepers.memKeys = sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) } +// GetSubspace gets existing substore from keeper. func (appKeepers *AppKeepers) GetSubspace(moduleName string) paramstypes.Subspace { subspace, _ := appKeepers.ParamsKeeper.GetSubspace(moduleName) return subspace } +// GetKVStoreKey gets KV Store keys. func (appKeepers *AppKeepers) GetKVStoreKey() map[string]*sdk.KVStoreKey { return appKeepers.keys } +// GetTransientStoreKey gets Transient Store keys. func (appKeepers *AppKeepers) GetTransientStoreKey() map[string]*sdk.TransientStoreKey { return appKeepers.tkeys } +// GetMemoryStoreKey get memory Store keys. func (appKeepers *AppKeepers) GetMemoryStoreKey() map[string]*sdk.MemoryStoreKey { return appKeepers.memKeys } diff --git a/app/modules.go b/app/modules.go index 5a6562f4a36..ba9e72149ea 100644 --- a/app/modules.go +++ b/app/modules.go @@ -162,6 +162,7 @@ func orderBeginBlockers(allModuleNames []string) []string { return ord.TotalOrdering() } +// OrderEndBlockers returns EndBlockers (crisis, govtypes, staking) with no relative order. func OrderEndBlockers(allModuleNames []string) []string { ord := partialord.NewPartialOrdering(allModuleNames) // only Osmosis modules with endblock code are: crisis, govtypes, staking diff --git a/app/params/config.go b/app/params/config.go index 8b952c2849a..3da0e06560a 100644 --- a/app/params/config.go +++ b/app/params/config.go @@ -36,6 +36,7 @@ func init() { RegisterDenoms() } +// RegisterDenoms registers token denoms. func RegisterDenoms() { err := sdk.RegisterDenom(HumanCoinUnit, sdk.OneDec()) if err != nil { @@ -47,6 +48,7 @@ func RegisterDenoms() { } } +// SetAddressPrefixes builds the Config with Bech32 addressPrefix and publKeyPrefix for accounts, validators, and consensus nodes and verifies that addreeses have correct format. func SetAddressPrefixes() { config := sdk.GetConfig() config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub) diff --git a/cmd/osmosisd/cmd/balances_from_state_export.go b/cmd/osmosisd/cmd/balances_from_state_export.go index cfdfc50d679..d955a3243fe 100644 --- a/cmd/osmosisd/cmd/balances_from_state_export.go +++ b/cmd/osmosisd/cmd/balances_from_state_export.go @@ -43,6 +43,7 @@ type DerivedAccount struct { TotalBalances sdk.Coins `json:"total_balances"` } +// newDerivedAccount returns a new derived account. func newDerivedAccount(address string) DerivedAccount { return DerivedAccount{ Address: address, @@ -53,6 +54,7 @@ func newDerivedAccount(address string) DerivedAccount { } } +// underlyingCoins returns liquidity pool's underlying coin balances. func underlyingCoins(originCoins sdk.Coins, pools map[string]gammtypes.PoolI) sdk.Coins { balances := sdk.Coins{} convertAgain := false @@ -115,6 +117,7 @@ func underlyingCoinsForSelectPools( return balancesByPool } +// getGenStateFromPath returns a JSON genState message from inputted path. func getGenStateFromPath(genesisFilePath string) (map[string]json.RawMessage, error) { genState := make(map[string]json.RawMessage) diff --git a/cmd/osmosisd/cmd/forceprune.go b/cmd/osmosisd/cmd/forceprune.go index 0ac1424180c..eb032e915a3 100644 --- a/cmd/osmosisd/cmd/forceprune.go +++ b/cmd/osmosisd/cmd/forceprune.go @@ -30,7 +30,7 @@ const ( defaultMinHeight = "1000" ) -// get cmd to convert any bech32 address to an osmo prefix. +// forceprune gets cmd to convert any bech32 address to an osmo prefix. func forceprune() *cobra.Command { cmd := &cobra.Command{ Use: "forceprune", @@ -94,6 +94,7 @@ func forceprune() *cobra.Command { return cmd } +// pruneBlockStoreAndGetHeights prunes blockstore and returns the startHeight and currentHeight. func pruneBlockStoreAndGetHeights(dbPath string, fullHeight int64) ( startHeight int64, currentHeight int64, err error, ) { @@ -131,6 +132,7 @@ func pruneBlockStoreAndGetHeights(dbPath string, fullHeight int64) ( return startHeight, currentHeight, nil } +// compactBlockStore compacts block storage. func compactBlockStore(dbPath string) (err error) { compactOpts := opt.Options{ DisableSeeksCompaction: true, @@ -151,6 +153,7 @@ func compactBlockStore(dbPath string) (err error) { return nil } +// forcepruneStateStore prunes and compacts state storage. func forcepruneStateStore(dbPath string, startHeight, currentHeight, minHeight, fullHeight int64) error { opts := opt.Options{ DisableSeeksCompaction: true, diff --git a/cmd/osmosisd/cmd/genesis.go b/cmd/osmosisd/cmd/genesis.go index 5fe5c764ae1..c8119d9e0b5 100644 --- a/cmd/osmosisd/cmd/genesis.go +++ b/cmd/osmosisd/cmd/genesis.go @@ -34,6 +34,7 @@ import ( ) //nolint:ineffassign +// PrepareGenesisCmd returns prepare-genesis cobra Command. func PrepareGenesisCmd(defaultNodeHome string, mbm module.BasicManager) *cobra.Command { cmd := &cobra.Command{ Use: "prepare-genesis", diff --git a/cmd/osmosisd/cmd/init.go b/cmd/osmosisd/cmd/init.go index 2369f6a8883..24d16d363c4 100644 --- a/cmd/osmosisd/cmd/init.go +++ b/cmd/osmosisd/cmd/init.go @@ -44,6 +44,7 @@ type printInfo struct { AppMessage json.RawMessage `json:"app_message" yaml:"app_message"` } +// newPrintInfo initializes a printInfo struct. func newPrintInfo(moniker, chainID, nodeID, genTxsDir string, appMessage json.RawMessage) printInfo { return printInfo{ Moniker: moniker, @@ -54,6 +55,7 @@ func newPrintInfo(moniker, chainID, nodeID, genTxsDir string, appMessage json.Ra } } +// displayInfo displays printInfo in JSON format. func displayInfo(info printInfo) error { out, err := json.MarshalIndent(info, "", " ") if err != nil { diff --git a/cmd/osmosisd/cmd/root.go b/cmd/osmosisd/cmd/root.go index 62a6ff7f247..b1dae87cbec 100644 --- a/cmd/osmosisd/cmd/root.go +++ b/cmd/osmosisd/cmd/root.go @@ -135,6 +135,7 @@ min-gas-price-for-high-gas-tx = ".0025" return OsmosisAppTemplate, OsmosisAppCfg } +// initRootCmd initializes root commands when creating a new root command for simd. func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { cfg := sdk.GetConfig() cfg.Seal() @@ -179,6 +180,7 @@ func addModuleInitFlags(startCmd *cobra.Command) { wasm.AddModuleInitFlags(startCmd) } +// queryCommand adds transaction and account querying commands. func queryCommand() *cobra.Command { cmd := &cobra.Command{ Use: "query", @@ -203,6 +205,7 @@ func queryCommand() *cobra.Command { return cmd } +// txCommand adds transaction signing, encoding / decoding, and broadcasting commands. func txCommand() *cobra.Command { cmd := &cobra.Command{ Use: "tx", @@ -229,6 +232,7 @@ func txCommand() *cobra.Command { return cmd } +// newApp initializes and returns a new Osmosis app. func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application { var cache sdk.MultiStorePersistentCache @@ -282,6 +286,7 @@ func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts serverty ) } +// createOsmosisAppAndExport creates and exports the new Osmosis app, returns the state of the new Osmosis app for a genesis file. func createOsmosisAppAndExport( logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string, appOpts servertypes.AppOptions, diff --git a/cmd/osmosisd/cmd/testnet.go b/cmd/osmosisd/cmd/testnet.go index 78b8b805ec0..81aaacc8086 100644 --- a/cmd/osmosisd/cmd/testnet.go +++ b/cmd/osmosisd/cmd/testnet.go @@ -45,7 +45,7 @@ var ( emptyMnemonic = "" ) -// get cmd to initialize all files for tendermint testnet and application. +// testnetCmd gets the cmd to initialize all files for tendermint testnet and application. func testnetCmd(mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command { cmd := &cobra.Command{ Use: "testnet", @@ -105,7 +105,7 @@ Example: const nodeDirPerm = 0o755 -// Initialize the testnet. +// InitTestnet initializes the testnet. func InitTestnet( clientCtx client.Context, cmd *cobra.Command, @@ -270,6 +270,7 @@ func InitTestnet( return nil } +// initGenFiles initializes genesis files for testnet. func initGenFiles( clientCtx client.Context, mbm module.BasicManager, genesisParams GenesisParams, chainID string, genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, diff --git a/go.mod b/go.mod index 148cf09f1a9..fe15d4903b3 100644 --- a/go.mod +++ b/go.mod @@ -79,7 +79,7 @@ require ( github.com/coinbase/rosetta-sdk-go v0.7.0 // indirect github.com/confio/ics23/go v0.7.0 // indirect github.com/containerd/continuity v0.3.0 // indirect - github.com/cosmos/btcutil v1.0.4 + github.com/cosmos/btcutil v1.0.4 // indirect github.com/cosmos/gorocksdb v1.2.0 // indirect github.com/cosmos/ledger-cosmos-go v0.11.1 // indirect github.com/cosmos/ledger-go v0.9.2 // indirect diff --git a/osmomath/decimal.go b/osmomath/decimal.go index b082fad37f4..49243a773c1 100644 --- a/osmomath/decimal.go +++ b/osmomath/decimal.go @@ -422,6 +422,7 @@ func (d BigDec) Format(s fmt.State, verb rune) { } } +// String returns a BigDec as a string. func (d BigDec) String() string { if d.i == nil { return d.i.String() @@ -535,6 +536,7 @@ func chopPrecisionAndRound(d *big.Int) *big.Int { } } +// chopPrecisionAndRoundUp removes a Precision amount of rightmost digits and rounds up. func chopPrecisionAndRoundUp(d *big.Int) *big.Int { // remove the negative and add it back when returning if d.Sign() == -1 { @@ -761,7 +763,7 @@ func (d *BigDec) UnmarshalAmino(bz []byte) error { return d.Unmarshal(bz) } // helpers -// test if two decimal arrays are equal +// DecsEqual tests if two decimal arrays are equal func DecsEqual(d1s, d2s []BigDec) bool { if len(d1s) != len(d2s) { return false @@ -775,7 +777,7 @@ func DecsEqual(d1s, d2s []BigDec) bool { return true } -// minimum decimal between two +// MinDec gets minimum decimal between two func MinDec(d1, d2 BigDec) BigDec { if d1.LT(d2) { return d1 @@ -783,7 +785,7 @@ func MinDec(d1, d2 BigDec) BigDec { return d2 } -// maximum decimal between two +// MaxDec gets maximum decimal between two func MaxDec(d1, d2 BigDec) BigDec { if d1.LT(d2) { return d2 @@ -791,11 +793,14 @@ func MaxDec(d1, d2 BigDec) BigDec { return d1 } -// intended to be used with require/assert: require.True(DecEq(...)) +// DecEq returns true if two given decimals are equal. +// Intended to be used with require/assert: require.True(t, DecEq(...)) func DecEq(t *testing.T, exp, got BigDec) (*testing.T, bool, string, string, string) { return t, exp.Equal(got), "expected:\t%v\ngot:\t\t%v", exp.String(), got.String() } +// DecApproxEq returns true if the differences between two given decimals are smaller than the tolerance range. +// Intended to be used with require/assert: require.True(t, DecEq(...)) func DecApproxEq(t *testing.T, d1 BigDec, d2 BigDec, tol BigDec) (*testing.T, bool, string, string, string) { diff := d1.Sub(d2).Abs() return t, diff.LTE(tol), "expected |d1 - d2| <:\t%v\ngot |d1 - d2| = \t\t%v", tol.String(), diff.String() diff --git a/osmomath/int.go b/osmomath/int.go index ab407a56dfd..9d4f5e6501b 100644 --- a/osmomath/int.go +++ b/osmomath/int.go @@ -16,12 +16,16 @@ func newIntegerFromString(s string) (*big.Int, bool) { func equal(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == 0 } +// Greater than func gt(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == 1 } +// Greater than or equal to func gte(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) >= 0 } +// Less than func lt(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == -1 } +// Less than or equal to func lte(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) <= 0 } func add(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Add(i, i2) } diff --git a/osmomath/sigfig_round.go b/osmomath/sigfig_round.go index cd8621bd18c..d0287b3ac9e 100644 --- a/osmomath/sigfig_round.go +++ b/osmomath/sigfig_round.go @@ -4,6 +4,7 @@ import sdk "github.com/cosmos/cosmos-sdk/types" var pointOne = sdk.OneDec().QuoInt64(10) +// SigFigRound rounds to a specified significant figure. func SigFigRound(d sdk.Dec, tenToSigFig sdk.Int) sdk.Dec { // for d > .1, we do round(d * 10^sigfig) / 10^sigfig // for k, where 10^k*d > .1 && 10^{k-1}*d < .1, we do: diff --git a/proto/osmosis/gamm/pool-models/balancer/tx/tx.proto b/proto/osmosis/gamm/pool-models/balancer/tx/tx.proto index edcaa7714e9..2af4a15a30e 100644 --- a/proto/osmosis/gamm/pool-models/balancer/tx/tx.proto +++ b/proto/osmosis/gamm/pool-models/balancer/tx/tx.proto @@ -25,6 +25,7 @@ message MsgCreateBalancerPool { [ (gogoproto.moretags) = "yaml:\"future_pool_governor\"" ]; } +// Returns the poolID message MsgCreateBalancerPoolResponse { uint64 pool_id = 1 [ (gogoproto.customname) = "PoolID" ]; } diff --git a/proto/osmosis/gamm/pool-models/stableswap/tx.proto b/proto/osmosis/gamm/pool-models/stableswap/tx.proto index eb53c86cd48..f5c88a7f62d 100644 --- a/proto/osmosis/gamm/pool-models/stableswap/tx.proto +++ b/proto/osmosis/gamm/pool-models/stableswap/tx.proto @@ -14,6 +14,7 @@ service Msg { returns (MsgStableSwapAdjustScalingFactorsResponse); } +// ===================== MsgCreatePool message MsgCreateStableswapPool { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; @@ -28,13 +29,14 @@ message MsgCreateStableswapPool { [ (gogoproto.moretags) = "yaml:\"future_pool_governor\"" ]; } +// Returns a poolID with custom poolName. message MsgCreateStableswapPoolResponse { uint64 pool_id = 1 [ (gogoproto.customname) = "PoolID" ]; } +// Sender must be the pool's scaling_factor_governor in order for the tx to +// succeed. Adjusts stableswap scaling factors. message MsgStableSwapAdjustScalingFactors { - // Sender must be the pool's scaling_factor_governor in order for the tx to - // succeed string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; uint64 pool_id = 2 [ (gogoproto.customname) = "PoolID" ]; diff --git a/proto/osmosis/pool-incentives/v1beta1/query.proto b/proto/osmosis/pool-incentives/v1beta1/query.proto index 0c10931c51b..e252a5643f8 100644 --- a/proto/osmosis/pool-incentives/v1beta1/query.proto +++ b/proto/osmosis/pool-incentives/v1beta1/query.proto @@ -15,27 +15,32 @@ service Query { option (google.api.http).get = "/osmosis/pool-incentives/v1beta1/gauge-ids/{pool_id}"; } - + // DistrInfo returns the pool's matching gauge ids and weights. rpc DistrInfo(QueryDistrInfoRequest) returns (QueryDistrInfoResponse) { option (google.api.http).get = "/osmosis/pool-incentives/v1beta1/distr_info"; } + // Params returns pool incentives params. rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { option (google.api.http).get = "/osmosis/pool-incentives/v1beta1/params"; } + // LockableDurations returns lock durations for pools. rpc LockableDurations(QueryLockableDurationsRequest) returns (QueryLockableDurationsResponse) { option (google.api.http).get = "/osmosis/pool-incentives/v1beta1/lockable_durations"; } + // IncentivizedPools returns currently incentivized pools rpc IncentivizedPools(QueryIncentivizedPoolsRequest) returns (QueryIncentivizedPoolsResponse) { option (google.api.http).get = "/osmosis/pool-incentives/v1beta1/incentivized_pools"; } + + // ExternalIncentiveGauges returns external incentive gauges. rpc ExternalIncentiveGauges(QueryExternalIncentiveGaugesRequest) returns (QueryExternalIncentiveGaugesResponse) { option (google.api.http).get = diff --git a/proto/osmosis/txfees/v1beta1/query.proto b/proto/osmosis/txfees/v1beta1/query.proto index 38ab374a9c8..9856877f631 100644 --- a/proto/osmosis/txfees/v1beta1/query.proto +++ b/proto/osmosis/txfees/v1beta1/query.proto @@ -11,23 +11,26 @@ option go_package = "github.com/osmosis-labs/osmosis/v10/x/txfees/types"; service Query { // FeeTokens returns a list of all the whitelisted fee tokens and their - // corresponding pools It does not include the BaseDenom, which has its own + // corresponding pools. It does not include the BaseDenom, which has its own // query endpoint rpc FeeTokens(QueryFeeTokensRequest) returns (QueryFeeTokensResponse) { option (google.api.http).get = "/osmosis/txfees/v1beta1/fee_tokens"; } + // DenomSpotPrice returns all spot prices by each registered token denom. rpc DenomSpotPrice(QueryDenomSpotPriceRequest) returns (QueryDenomSpotPriceResponse) { option (google.api.http).get = "/osmosis/txfees/v1beta1/spot_price_by_denom"; } + // Returns the poolID for a specified denom input. rpc DenomPoolId(QueryDenomPoolIdRequest) returns (QueryDenomPoolIdResponse) { option (google.api.http).get = "/osmosis/txfees/v1beta1/denom_pool_id/{denom}"; } + // Returns a list of all base denom tokens and their corresponding pools. rpc BaseDenom(QueryBaseDenomRequest) returns (QueryBaseDenomResponse) { option (google.api.http).get = "/osmosis/txfees/v1beta1/base_denom"; } diff --git a/wasmbinding/message_plugin.go b/wasmbinding/message_plugin.go index 7590b5a98cb..c55d9f1c388 100644 --- a/wasmbinding/message_plugin.go +++ b/wasmbinding/message_plugin.go @@ -17,6 +17,7 @@ import ( tokenfactorytypes "github.com/osmosis-labs/osmosis/v10/x/tokenfactory/types" ) +// CustomMessageDecorator returns decorator for custom CosmWasm bindings messages func CustomMessageDecorator(gammKeeper *gammkeeper.Keeper, bank *bankkeeper.BaseKeeper, tokenFactory *tokenfactorykeeper.Keeper) func(wasmkeeper.Messenger) wasmkeeper.Messenger { return func(old wasmkeeper.Messenger) wasmkeeper.Messenger { return &CustomMessenger{ @@ -37,6 +38,7 @@ type CustomMessenger struct { var _ wasmkeeper.Messenger = (*CustomMessenger)(nil) +// DispatchMsg executes on the contractMsg. func (m *CustomMessenger) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Event, [][]byte, error) { if msg.Custom != nil { // only handle the happy path where this is really creating / minting / swapping ... @@ -64,6 +66,7 @@ func (m *CustomMessenger) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddre return m.wrapped.DispatchMsg(ctx, contractAddr, contractIBCPortID, msg) } +// createDenom creates a new token denom func (m *CustomMessenger) createDenom(ctx sdk.Context, contractAddr sdk.AccAddress, createDenom *bindings.CreateDenom) ([]sdk.Event, [][]byte, error) { err := PerformCreateDenom(m.tokenFactory, m.bank, ctx, contractAddr, createDenom) if err != nil { @@ -72,6 +75,7 @@ func (m *CustomMessenger) createDenom(ctx sdk.Context, contractAddr sdk.AccAddre return nil, nil, nil } +// PerformCreateDenom is used with createDenom to create a token denom; validates the msgCreateDenom. func PerformCreateDenom(f *tokenfactorykeeper.Keeper, b *bankkeeper.BaseKeeper, ctx sdk.Context, contractAddr sdk.AccAddress, createDenom *bindings.CreateDenom) error { if createDenom == nil { return wasmvmtypes.InvalidRequest{Err: "create denom null create denom"} @@ -96,6 +100,7 @@ func PerformCreateDenom(f *tokenfactorykeeper.Keeper, b *bankkeeper.BaseKeeper, return nil } +// mintTokens mints tokens of a specified denom to an address. func (m *CustomMessenger) mintTokens(ctx sdk.Context, contractAddr sdk.AccAddress, mint *bindings.MintTokens) ([]sdk.Event, [][]byte, error) { err := PerformMint(m.tokenFactory, m.bank, ctx, contractAddr, mint) if err != nil { @@ -104,6 +109,7 @@ func (m *CustomMessenger) mintTokens(ctx sdk.Context, contractAddr sdk.AccAddres return nil, nil, nil } +// PerformMint used with mintTokens to validate the mint message and mint through token factory. func PerformMint(f *tokenfactorykeeper.Keeper, b *bankkeeper.BaseKeeper, ctx sdk.Context, contractAddr sdk.AccAddress, mint *bindings.MintTokens) error { if mint == nil { return wasmvmtypes.InvalidRequest{Err: "mint token null mint"} @@ -132,6 +138,7 @@ func PerformMint(f *tokenfactorykeeper.Keeper, b *bankkeeper.BaseKeeper, ctx sdk return nil } +// changeAdmin changes the admin. func (m *CustomMessenger) changeAdmin(ctx sdk.Context, contractAddr sdk.AccAddress, changeAdmin *bindings.ChangeAdmin) ([]sdk.Event, [][]byte, error) { err := ChangeAdmin(m.tokenFactory, ctx, contractAddr, changeAdmin) if err != nil { @@ -140,6 +147,7 @@ func (m *CustomMessenger) changeAdmin(ctx sdk.Context, contractAddr sdk.AccAddre return nil, nil, nil } +// ChangeAdmin is used with changeAdmin to validate changeAdmin messages and to dispatch. func ChangeAdmin(f *tokenfactorykeeper.Keeper, ctx sdk.Context, contractAddr sdk.AccAddress, changeAdmin *bindings.ChangeAdmin) error { if changeAdmin == nil { return wasmvmtypes.InvalidRequest{Err: "changeAdmin is nil"} @@ -162,6 +170,7 @@ func ChangeAdmin(f *tokenfactorykeeper.Keeper, ctx sdk.Context, contractAddr sdk return nil } +// burnTokens burns tokens. func (m *CustomMessenger) burnTokens(ctx sdk.Context, contractAddr sdk.AccAddress, burn *bindings.BurnTokens) ([]sdk.Event, [][]byte, error) { err := PerformBurn(m.tokenFactory, ctx, contractAddr, burn) if err != nil { @@ -170,6 +179,7 @@ func (m *CustomMessenger) burnTokens(ctx sdk.Context, contractAddr sdk.AccAddres return nil, nil, nil } +// PerformBurn performs token burning after validating tokenBurn message. func PerformBurn(f *tokenfactorykeeper.Keeper, ctx sdk.Context, contractAddr sdk.AccAddress, burn *bindings.BurnTokens) error { if burn == nil { return wasmvmtypes.InvalidRequest{Err: "burn token null mint"} @@ -193,6 +203,7 @@ func PerformBurn(f *tokenfactorykeeper.Keeper, ctx sdk.Context, contractAddr sdk return nil } +// swapTokens swaps one denom for another. func (m *CustomMessenger) swapTokens(ctx sdk.Context, contractAddr sdk.AccAddress, swap *bindings.SwapMsg) ([]sdk.Event, [][]byte, error) { _, err := PerformSwap(m.gammKeeper, ctx, contractAddr, swap) if err != nil { @@ -275,6 +286,7 @@ func GetFullDenom(contract string, subDenom string) (string, error) { return fullDenom, nil } +// parseAddress parses address from bech32 string and verifies its format. func parseAddress(addr string) (sdk.AccAddress, error) { parsed, err := sdk.AccAddressFromBech32(addr) if err != nil { diff --git a/wasmbinding/queries.go b/wasmbinding/queries.go index 6665fc24bd5..11696b7e93c 100644 --- a/wasmbinding/queries.go +++ b/wasmbinding/queries.go @@ -26,6 +26,7 @@ func NewQueryPlugin(gk *gammkeeper.Keeper, tfk *tokenfactorykeeper.Keeper) *Quer } } +// GetDenomAdmin is a query to get denom admin. func (qp QueryPlugin) GetDenomAdmin(ctx sdk.Context, denom string) (*bindings.DenomAdminResponse, error) { metadata, err := qp.tokenFactoryKeeper.GetAuthorityMetadata(ctx, denom) if err != nil { @@ -35,6 +36,7 @@ func (qp QueryPlugin) GetDenomAdmin(ctx sdk.Context, denom string) (*bindings.De return &bindings.DenomAdminResponse{Admin: metadata.Admin}, nil } +// GetPoolState is a query to get pool liquidity and amount of each denoms' pool shares. func (qp QueryPlugin) GetPoolState(ctx sdk.Context, poolID uint64) (*bindings.PoolAssets, error) { poolData, err := qp.gammKeeper.GetPoolAndPoke(ctx, poolID) if err != nil { @@ -50,6 +52,7 @@ func (qp QueryPlugin) GetPoolState(ctx sdk.Context, poolID uint64) (*bindings.Po }, nil } +// GetSpotPrice is a query to get spot price of denoms. func (qp QueryPlugin) GetSpotPrice(ctx sdk.Context, spotPrice *bindings.SpotPrice) (*sdk.Dec, error) { if spotPrice == nil { return nil, wasmvmtypes.InvalidRequest{Err: "gamm spot price null"} @@ -77,6 +80,7 @@ func (qp QueryPlugin) GetSpotPrice(ctx sdk.Context, spotPrice *bindings.SpotPric return &price, nil } +// EstimateSwap validates each denom (in / out) and performs a swap. func (qp QueryPlugin) EstimateSwap(ctx sdk.Context, estimateSwap *bindings.EstimateSwap) (*bindings.SwapAmount, error) { if estimateSwap == nil { return nil, wasmvmtypes.InvalidRequest{Err: "gamm estimate swap null"} diff --git a/wasmbinding/query_plugin.go b/wasmbinding/query_plugin.go index 1f44dc87b9e..8a684d6c1c0 100644 --- a/wasmbinding/query_plugin.go +++ b/wasmbinding/query_plugin.go @@ -11,6 +11,7 @@ import ( "github.com/osmosis-labs/osmosis/v10/wasmbinding/bindings" ) +// CustomQuerier dispatches custom CosmWasm bindings queries. func CustomQuerier(qp *QueryPlugin) func(ctx sdk.Context, request json.RawMessage) ([]byte, error) { return func(ctx sdk.Context, request json.RawMessage) ([]byte, error) { var contractQuery bindings.OsmosisQuery diff --git a/x/epochs/keeper/epoch.go b/x/epochs/keeper/epoch.go index 9dcf262910c..a705b375a6c 100644 --- a/x/epochs/keeper/epoch.go +++ b/x/epochs/keeper/epoch.go @@ -88,6 +88,7 @@ func (k Keeper) IterateEpochInfo(ctx sdk.Context, fn func(index int64, epochInfo } } +// AllEpochInfos iterate through epochs to return all epochs info. func (k Keeper) AllEpochInfos(ctx sdk.Context) []types.EpochInfo { epochs := []types.EpochInfo{} k.IterateEpochInfo(ctx, func(index int64, epochInfo types.EpochInfo) (stop bool) { diff --git a/x/epochs/keeper/genesis.go b/x/epochs/keeper/genesis.go index ddbbe18f118..b3d44bd7a54 100644 --- a/x/epochs/keeper/genesis.go +++ b/x/epochs/keeper/genesis.go @@ -6,8 +6,8 @@ import ( "github.com/osmosis-labs/osmosis/v10/x/epochs/types" ) +// InitGenesis sets epoch info from genesis func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { - // set epoch info from genesis for _, epoch := range genState.Epochs { err := k.AddEpochInfo(ctx, epoch) if err != nil { diff --git a/x/epochs/keeper/grpc_query.go b/x/epochs/keeper/grpc_query.go index 66734c4f17e..27e62dbb9ff 100644 --- a/x/epochs/keeper/grpc_query.go +++ b/x/epochs/keeper/grpc_query.go @@ -19,6 +19,7 @@ type Querier struct { Keeper } +// NewQuerier initializes new querier. func NewQuerier(k Keeper) Querier { return Querier{Keeper: k} } diff --git a/x/epochs/keeper/hooks.go b/x/epochs/keeper/hooks.go index 059a2bd1411..46a57b0bf54 100644 --- a/x/epochs/keeper/hooks.go +++ b/x/epochs/keeper/hooks.go @@ -4,10 +4,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// AfterEpochEnd gets called at the end of the epoch, end of epoch is the timestamp of first block produced after epoch duration. func (k Keeper) AfterEpochEnd(ctx sdk.Context, identifier string, epochNumber int64) { k.hooks.AfterEpochEnd(ctx, identifier, epochNumber) } +// BeforeEpochStart new epoch is next block of epoch end block func (k Keeper) BeforeEpochStart(ctx sdk.Context, identifier string, epochNumber int64) { k.hooks.BeforeEpochStart(ctx, identifier, epochNumber) } diff --git a/x/epochs/keeper/keeper.go b/x/epochs/keeper/keeper.go index 4c56599eda3..02f128df719 100644 --- a/x/epochs/keeper/keeper.go +++ b/x/epochs/keeper/keeper.go @@ -18,6 +18,7 @@ type ( } ) +// NewKeeper returns a new keeper by codec and storeKey inputs. func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey) *Keeper { return &Keeper{ cdc: cdc, diff --git a/x/epochs/module.go b/x/epochs/module.go index f32d5d3c788..de6c17ee220 100644 --- a/x/epochs/module.go +++ b/x/epochs/module.go @@ -1,3 +1,15 @@ +/* +Often in the SDK, we would like to run certain code every-so often. The +purpose of `epochs` module is to allow other modules to set that they +would like to be signaled once every period. So another module can +specify it wants to execute code once a week, starting at UTC-time = x. +`epochs` creates a generalized epoch interface to other modules so that +they can easily be signalled upon such events. + - Contains functionality for querying epoch. + - Events for BeginBlock and EndBlock. + - Initialization for epoch-related infos. +*/ + package epochs import ( @@ -45,6 +57,7 @@ func (AppModuleBasic) Name() string { return types.ModuleName } +// RegisterLegacyAminoCodec registers the module's Amino codec that properly handles protobuf types with Any's. func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} // RegisterInterfaces registers the module's interface types. diff --git a/x/epochs/types/doc.go b/x/epochs/types/doc.go new file mode 100644 index 00000000000..c1b138dfb61 --- /dev/null +++ b/x/epochs/types/doc.go @@ -0,0 +1,4 @@ +/* +Package types translates gRPC into RESTful JSON APIs. +*/ +package types diff --git a/x/epochs/types/genesis.go b/x/epochs/types/genesis.go index 8fb660d5d8f..98b42b28e19 100644 --- a/x/epochs/types/genesis.go +++ b/x/epochs/types/genesis.go @@ -38,6 +38,7 @@ func (gs GenesisState) Validate() error { return nil } +// Validate also validates epoch info. func (epoch EpochInfo) Validate() error { if epoch.Identifier == "" { return errors.New("epoch identifier should NOT be empty") diff --git a/x/gamm/keeper/grpc_query.go b/x/gamm/keeper/grpc_query.go index a404369e698..52527ec9bda 100644 --- a/x/gamm/keeper/grpc_query.go +++ b/x/gamm/keeper/grpc_query.go @@ -44,6 +44,7 @@ func NewQuerier(k Keeper) Querier { return Querier{Keeper: k} } +// Pool checks if a pool exists and their respective poolWeights. func (q Querier) Pool( ctx context.Context, req *types.QueryPoolRequest, @@ -67,6 +68,7 @@ func (q Querier) Pool( return &types.QueryPoolResponse{Pool: any}, nil } +// Pools checks existence of multiple pools and their poolWeights func (q Querier) Pools( ctx context.Context, req *types.QueryPoolsRequest, @@ -116,6 +118,7 @@ func (q Querier) Pools( }, nil } +// NumPools returns total number of pools. func (q Querier) NumPools(ctx context.Context, _ *types.QueryNumPoolsRequest) (*types.QueryNumPoolsResponse, error) { sdkCtx := sdk.UnwrapSDKContext(ctx) @@ -124,6 +127,7 @@ func (q Querier) NumPools(ctx context.Context, _ *types.QueryNumPoolsRequest) (* }, nil } +// PoolParams queries a specified pool for its params. func (q Querier) PoolParams(ctx context.Context, req *types.QueryPoolParamsRequest) (*types.QueryPoolParamsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -153,6 +157,7 @@ func (q Querier) PoolParams(ctx context.Context, req *types.QueryPoolParamsReque } } +// TotalPoolLiquidity returns total liquidity in pool. func (q Querier) TotalPoolLiquidity(ctx context.Context, req *types.QueryTotalPoolLiquidityRequest) (*types.QueryTotalPoolLiquidityResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -170,6 +175,7 @@ func (q Querier) TotalPoolLiquidity(ctx context.Context, req *types.QueryTotalPo }, nil } +// TotalShares returns total pool shares. func (q Querier) TotalShares(ctx context.Context, req *types.QueryTotalSharesRequest) (*types.QueryTotalSharesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -189,6 +195,7 @@ func (q Querier) TotalShares(ctx context.Context, req *types.QueryTotalSharesReq }, nil } +// SpotPrice returns target pool asset prices on base and quote assets. func (q Querier) SpotPrice(ctx context.Context, req *types.QuerySpotPriceRequest) (*types.QuerySpotPriceResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -219,6 +226,7 @@ func (q Querier) SpotPrice(ctx context.Context, req *types.QuerySpotPriceRequest }, nil } +// TotalLiquidity returns total liquidity across all pools. func (q Querier) TotalLiquidity(ctx context.Context, _ *types.QueryTotalLiquidityRequest) (*types.QueryTotalLiquidityResponse, error) { sdkCtx := sdk.UnwrapSDKContext(ctx) @@ -227,6 +235,7 @@ func (q Querier) TotalLiquidity(ctx context.Context, _ *types.QueryTotalLiquidit }, nil } +// EstimateSwapExactAmountIn estimates input token amount for a swap. func (q Querier) EstimateSwapExactAmountIn(ctx context.Context, req *types.QuerySwapExactAmountInRequest) (*types.QuerySwapExactAmountInResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") @@ -266,6 +275,7 @@ func (q Querier) EstimateSwapExactAmountIn(ctx context.Context, req *types.Query }, nil } +// EstimateSwapExactAmountOut estimates token output amount for a swap. func (q Querier) EstimateSwapExactAmountOut(ctx context.Context, req *types.QuerySwapExactAmountOutRequest) (*types.QuerySwapExactAmountOutResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") diff --git a/x/gamm/keeper/msg_server.go b/x/gamm/keeper/msg_server.go index 5e3ce495e61..9c44f97bdd1 100644 --- a/x/gamm/keeper/msg_server.go +++ b/x/gamm/keeper/msg_server.go @@ -38,6 +38,7 @@ var ( // _ stableswap.MsgServer = msgServer{} ) +// CreateBalancerPool is a create balancer pool message. func (server msgServer) CreateBalancerPool(goCtx context.Context, msg *balancer.MsgCreateBalancerPool) (*balancer.MsgCreateBalancerPoolResponse, error) { poolId, err := server.CreatePool(goCtx, msg) return &balancer.MsgCreateBalancerPoolResponse{PoolID: poolId}, err @@ -61,6 +62,9 @@ func (server msgServer) CreateBalancerPool(goCtx context.Context, msg *balancer. // return &stableswap.MsgStableSwapAdjustScalingFactorsResponse{}, nil // } +// CreatePool attempts to create a pool returning the newly created pool ID or an error upon failure. +// The pool creation fee is used to fund the community pool. +// It will create a dedicated module account for the pool and sends the initial liquidity to the created module account. func (server msgServer) CreatePool(goCtx context.Context, msg types.CreatePoolMsg) (poolId uint64, err error) { ctx := sdk.UnwrapSDKContext(goCtx) diff --git a/x/gamm/module.go b/x/gamm/module.go index 21c215ea2b2..1c46041a41f 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -1,3 +1,12 @@ +/* +Package gamm contains a variety of generalized automated market maker +functionality which provides the logic to create and interact with +liquidity pools on the Osmosis DEX. + - Has pool creation, join pool, and exit pool logic + - Token swap logic + - GAMM pool queries +*/ + package gamm import ( diff --git a/x/gamm/pool-models/balancer/tx.pb.go b/x/gamm/pool-models/balancer/tx.pb.go index dd2f853aa3c..c07d60eba65 100644 --- a/x/gamm/pool-models/balancer/tx.pb.go +++ b/x/gamm/pool-models/balancer/tx.pb.go @@ -97,6 +97,7 @@ func (m *MsgCreateBalancerPool) GetFuturePoolGovernor() string { return "" } +// Returns the poolID type MsgCreateBalancerPoolResponse struct { PoolID uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` } diff --git a/x/gamm/pool-models/stableswap/tx.pb.go b/x/gamm/pool-models/stableswap/tx.pb.go index f666bb53c64..be09836c83f 100644 --- a/x/gamm/pool-models/stableswap/tx.pb.go +++ b/x/gamm/pool-models/stableswap/tx.pb.go @@ -30,6 +30,7 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// ===================== MsgCreatePool type MsgCreateStableswapPool struct { Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` PoolParams *PoolParams `protobuf:"bytes,2,opt,name=pool_params,json=poolParams,proto3" json:"pool_params,omitempty" yaml:"pool_params"` @@ -98,6 +99,7 @@ func (m *MsgCreateStableswapPool) GetFuturePoolGovernor() string { return "" } +// Returns a poolID with custom poolName. type MsgCreateStableswapPoolResponse struct { PoolID uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` } @@ -142,9 +144,9 @@ func (m *MsgCreateStableswapPoolResponse) GetPoolID() uint64 { return 0 } +// Sender must be the pool's scaling_factor_governor in order for the tx to +// succeed. Adjusts stableswap scaling factors. type MsgStableSwapAdjustScalingFactors struct { - // Sender must be the pool's scaling_factor_governor in order for the tx to - // succeed Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` PoolID uint64 `protobuf:"varint,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` ScalingFactors []uint64 `protobuf:"varint,3,rep,packed,name=scaling_factors,json=scalingFactors,proto3" json:"scaling_factors,omitempty" yaml:"stableswap_scaling_factor"` diff --git a/x/incentives/module.go b/x/incentives/module.go index 62b50e7ca52..edc66cfea10 100644 --- a/x/incentives/module.go +++ b/x/incentives/module.go @@ -1,3 +1,11 @@ +/* +Incentives module provides general interface to give yield to stakers. The yield to be given +to stakers are stored in gauges and is distributed on epoch basis +to the stakers who meet specific conditions. + - Gauge queries, gauge creation and add tokens to gauge + - Upcoming-gauges related queries + - Gauge infos and gauge queues +*/ package incentives import ( diff --git a/x/lockup/keeper/iterator.go b/x/lockup/keeper/iterator.go index 750e117e4ed..fe8d0fa2663 100644 --- a/x/lockup/keeper/iterator.go +++ b/x/lockup/keeper/iterator.go @@ -18,6 +18,7 @@ func unlockingPrefix(isUnlocking bool) []byte { return types.KeyPrefixNotUnlocking } +// iteratorAfterTime iterates through keys between that use prefix, and have a time. func (k Keeper) iteratorAfterTime(ctx sdk.Context, prefix []byte, time time.Time) sdk.Iterator { store := ctx.KVStore(k.storeKey) timeKey := getTimeKey(time) @@ -27,7 +28,7 @@ func (k Keeper) iteratorAfterTime(ctx sdk.Context, prefix []byte, time time.Time return store.Iterator(storetypes.PrefixEndBytes(key), storetypes.PrefixEndBytes(prefix)) } -// iterate through keys between that use prefix, and have a time LTE max time. +// iteratorBeforeTime iterates through keys between that use prefix, and have a time LTE max time. func (k Keeper) iteratorBeforeTime(ctx sdk.Context, prefix []byte, maxTime time.Time) sdk.Iterator { store := ctx.KVStore(k.storeKey) timeKey := getTimeKey(maxTime) @@ -37,6 +38,7 @@ func (k Keeper) iteratorBeforeTime(ctx sdk.Context, prefix []byte, maxTime time. return store.Iterator(prefix, storetypes.PrefixEndBytes(key)) } +// iteratorDuration iterates over a domain of keys for a specified duration. func (k Keeper) iteratorDuration(ctx sdk.Context, prefix []byte, duration time.Duration) sdk.Iterator { durationKey := getDurationKey(duration) key := combineKeys(prefix, durationKey) @@ -44,6 +46,7 @@ func (k Keeper) iteratorDuration(ctx sdk.Context, prefix []byte, duration time.D return sdk.KVStorePrefixIterator(store, key) } +// iteratorLongerDuration iterates over a domain of keys for longer than a specified duration. func (k Keeper) iteratorLongerDuration(ctx sdk.Context, prefix []byte, duration time.Duration) sdk.Iterator { store := ctx.KVStore(k.storeKey) durationKey := getDurationKey(duration) @@ -52,6 +55,7 @@ func (k Keeper) iteratorLongerDuration(ctx sdk.Context, prefix []byte, duration return store.Iterator(key, storetypes.PrefixEndBytes(prefix)) } +// iteratorShorterDuration iterates over a domain of keys for shorter than a specified duration. func (k Keeper) iteratorShorterDuration(ctx sdk.Context, prefix []byte, duration time.Duration) sdk.Iterator { store := ctx.KVStore(k.storeKey) durationKey := getDurationKey(duration) @@ -60,6 +64,7 @@ func (k Keeper) iteratorShorterDuration(ctx sdk.Context, prefix []byte, duration return store.Iterator(prefix, key) } +// iterator iterates over a domain of keys. func (k Keeper) iterator(ctx sdk.Context, prefix []byte) sdk.Iterator { store := ctx.KVStore(k.storeKey) return sdk.KVStorePrefixIterator(store, prefix) @@ -173,6 +178,7 @@ func (k Keeper) AccountLockIteratorDurationDenom(ctx sdk.Context, isUnlocking bo return k.iteratorDuration(ctx, combineKeys(unlockingPrefix, types.KeyPrefixAccountDenomLockDuration, addr, []byte(denom)), duration) } +// getLocksFromIterator returns an array of single lock unit by period defined by the x/lockup module. func (k Keeper) getLocksFromIterator(ctx sdk.Context, iterator db.Iterator) []types.PeriodLock { locks := []types.PeriodLock{} defer iterator.Close() @@ -187,6 +193,7 @@ func (k Keeper) getLocksFromIterator(ctx sdk.Context, iterator db.Iterator) []ty return locks } +// unlockFromIterator gets locks from the iterator, then unlocks all matured locks. Returns locks unlocked and sum of coins unlocked. func (k Keeper) unlockFromIterator(ctx sdk.Context, iterator db.Iterator) ([]types.PeriodLock, sdk.Coins) { // Note: this function is only used for an account // and this has no conflicts with synthetic lockups @@ -204,6 +211,7 @@ func (k Keeper) unlockFromIterator(ctx sdk.Context, iterator db.Iterator) ([]typ return locks, coins } +// beginUnlockFromIterator starts unlocking coins from NotUnlocking queue. func (k Keeper) beginUnlockFromIterator(ctx sdk.Context, iterator db.Iterator) ([]types.PeriodLock, error) { // Note: this function is only used for an account // and this has no conflicts with synthetic lockups @@ -218,6 +226,7 @@ func (k Keeper) beginUnlockFromIterator(ctx sdk.Context, iterator db.Iterator) ( return locks, nil } +// getCoinsFromIterator gets coins from locks using the iterator. func (k Keeper) getCoinsFromIterator(ctx sdk.Context, iterator db.Iterator) sdk.Coins { return k.getCoinsFromLocks(k.getLocksFromIterator(ctx, iterator)) } diff --git a/x/lockup/module.go b/x/lockup/module.go index 139c30cd864..217b92c4320 100644 --- a/x/lockup/module.go +++ b/x/lockup/module.go @@ -1,3 +1,14 @@ +/* +Lockup module provides an interface for users to lock tokens +(also known as bonding) into the module to get incentives. +After tokens have been added to a specific pool and turned into LP shares +through the GAMM module, users can then lock these LP shares with +a specific duration in order to begin earing rewards. + - Lock and unlock token message handling + - Lock token infos and LP shares balance queries + - Pool locked denom balance queries +*/ + package lockup import ( diff --git a/x/mint/module.go b/x/mint/module.go index e371d3a17d1..5fb3059737c 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -1,3 +1,12 @@ +/* +The `mint` module is responsible for creating tokens in a +flexible way to reward validators, incentivize providing pool +liquidity, provide funds for Osmosis governance, +and pay developers to maintain and improve Osmosis. + - Denom minting; reduction and reserve ratio settings + - Token distribution proportions + - Epoch start distribution settings +*/ package mint import ( diff --git a/x/pool-incentives/module.go b/x/pool-incentives/module.go index 29f6ddac163..8892b8ac2e0 100644 --- a/x/pool-incentives/module.go +++ b/x/pool-incentives/module.go @@ -1,3 +1,13 @@ +/* +The `pool-incentives` module automatically creates individual gauges +in the `incentives` module for every lock duration +that exists in that pool. The `pool-incentives` module also takes +the `pool_incentives` distributed from the `gov` module +and distributes it to the various incentivized gauges. + - Handles governance proposals impacting pool incentives. + - Pool distribution and lockup infos queries. + - Distributes incentives to LPs. +*/ package pool_incentives import ( diff --git a/x/pool-incentives/spec/README.md b/x/pool-incentives/spec/README.md index dd8cd501560..9dabfc087bd 100644 --- a/x/pool-incentives/spec/README.md +++ b/x/pool-incentives/spec/README.md @@ -1,6 +1,6 @@ # Pool Incentives -The `pool-incentives` module is separate but related to the `incentives` module. When a pool is created using the `GAMM` module, the `pool-incentives` module automatically creates individual gauges in the `incentives` module for every lock duration that exists in that pool. The `pool-incentives` module also takes takes the `pool_incentives` distributed from the `gov` module and distributes it to the various incentivized gauges. +The `pool-incentives` module is separate but related to the `incentives` module. When a pool is created using the `GAMM` module, the `pool-incentives` module automatically creates individual gauges in the `incentives` module for every lock duration that exists in that pool. The `pool-incentives` module also takes the `pool_incentives` distributed from the `gov` module and distributes it to the various incentivized gauges. ## Abstract The `pool-incentives` module is separate but related to the `incentives` module. When a pool is created using the `GAMM` module, the `pool-incentives` module automatically creates individual gauges in the `incentives` module for every lock duration that exists in that pool. The `pool-incentives` module also takes takes the `pool_incentives` distributed from the `gov` module and distributes it to the various incentivized gauges. diff --git a/x/pool-incentives/types/query.pb.go b/x/pool-incentives/types/query.pb.go index b0b5004c46d..ac45cf44c41 100644 --- a/x/pool-incentives/types/query.pb.go +++ b/x/pool-incentives/types/query.pb.go @@ -743,10 +743,15 @@ const _ = grpc.SupportPackageIsVersion4 type QueryClient interface { // GaugeIds takes the pool id and returns the matching gauge ids and durations GaugeIds(ctx context.Context, in *QueryGaugeIdsRequest, opts ...grpc.CallOption) (*QueryGaugeIdsResponse, error) + // DistrInfo returns the pool's matching gauge ids and weights. DistrInfo(ctx context.Context, in *QueryDistrInfoRequest, opts ...grpc.CallOption) (*QueryDistrInfoResponse, error) + // Params returns pool incentives params. Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + // LockableDurations returns lock durations for pools. LockableDurations(ctx context.Context, in *QueryLockableDurationsRequest, opts ...grpc.CallOption) (*QueryLockableDurationsResponse, error) + // IncentivizedPools returns currently incentivized pools IncentivizedPools(ctx context.Context, in *QueryIncentivizedPoolsRequest, opts ...grpc.CallOption) (*QueryIncentivizedPoolsResponse, error) + // ExternalIncentiveGauges returns external incentive gauges. ExternalIncentiveGauges(ctx context.Context, in *QueryExternalIncentiveGaugesRequest, opts ...grpc.CallOption) (*QueryExternalIncentiveGaugesResponse, error) } @@ -816,10 +821,15 @@ func (c *queryClient) ExternalIncentiveGauges(ctx context.Context, in *QueryExte type QueryServer interface { // GaugeIds takes the pool id and returns the matching gauge ids and durations GaugeIds(context.Context, *QueryGaugeIdsRequest) (*QueryGaugeIdsResponse, error) + // DistrInfo returns the pool's matching gauge ids and weights. DistrInfo(context.Context, *QueryDistrInfoRequest) (*QueryDistrInfoResponse, error) + // Params returns pool incentives params. Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + // LockableDurations returns lock durations for pools. LockableDurations(context.Context, *QueryLockableDurationsRequest) (*QueryLockableDurationsResponse, error) + // IncentivizedPools returns currently incentivized pools IncentivizedPools(context.Context, *QueryIncentivizedPoolsRequest) (*QueryIncentivizedPoolsResponse, error) + // ExternalIncentiveGauges returns external incentive gauges. ExternalIncentiveGauges(context.Context, *QueryExternalIncentiveGaugesRequest) (*QueryExternalIncentiveGaugesResponse, error) } diff --git a/x/superfluid/module.go b/x/superfluid/module.go index 5dceac95650..434a155a49f 100644 --- a/x/superfluid/module.go +++ b/x/superfluid/module.go @@ -1,3 +1,10 @@ +/* +The superfluid module handles all logic in relation to +the superfluid staking feature on Osmosis. Namely: +- Methods to lock funds and mint synthetic osmo for staking +- Daily minting and burning of the purpose of adjusting synthetic osmo lockups. +- Staking reward distribution via the intermediary account. +*/ package superfluid import ( diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index bc27f218531..fa03c848b44 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -1,3 +1,11 @@ +/* +The tokenfactory module allows any account to create a new token with +the name `factory/{creator address}/{subdenom}`. + +- Mint and burn user denom to and form any account +- Create a transfer of their denom between any two accounts +- Change the admin. In the future, more admin capabilities may be added. +*/ package tokenfactory import ( diff --git a/x/txfees/module.go b/x/txfees/module.go index e898172259f..c52aebce8b7 100644 --- a/x/txfees/module.go +++ b/x/txfees/module.go @@ -1,3 +1,12 @@ +/* +The txfees modules allows nodes to easily support many +tokens for usage as txfees, while letting node operators +only specify their tx fee parameters for a single "base" asset. + +- Adds a whitelist of tokens that can be used as fees on the chain. +- Any token not on this list cannot be provided as a tx fee. +- Adds a new SDK message for creating governance proposals for adding new TxFee denoms. +*/ package txfees import ( diff --git a/x/txfees/types/query.pb.go b/x/txfees/types/query.pb.go index 9beef390b32..7da1377e8be 100644 --- a/x/txfees/types/query.pb.go +++ b/x/txfees/types/query.pb.go @@ -443,11 +443,14 @@ const _ = grpc.SupportPackageIsVersion4 // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { // FeeTokens returns a list of all the whitelisted fee tokens and their - // corresponding pools It does not include the BaseDenom, which has its own + // corresponding pools. It does not include the BaseDenom, which has its own // query endpoint FeeTokens(ctx context.Context, in *QueryFeeTokensRequest, opts ...grpc.CallOption) (*QueryFeeTokensResponse, error) + // DenomSpotPrice returns all spot prices by each registered token denom. DenomSpotPrice(ctx context.Context, in *QueryDenomSpotPriceRequest, opts ...grpc.CallOption) (*QueryDenomSpotPriceResponse, error) + // Returns the poolID for a specified denom input. DenomPoolId(ctx context.Context, in *QueryDenomPoolIdRequest, opts ...grpc.CallOption) (*QueryDenomPoolIdResponse, error) + // Returns a list of all base denom tokens and their corresponding pools. BaseDenom(ctx context.Context, in *QueryBaseDenomRequest, opts ...grpc.CallOption) (*QueryBaseDenomResponse, error) } @@ -498,11 +501,14 @@ func (c *queryClient) BaseDenom(ctx context.Context, in *QueryBaseDenomRequest, // QueryServer is the server API for Query service. type QueryServer interface { // FeeTokens returns a list of all the whitelisted fee tokens and their - // corresponding pools It does not include the BaseDenom, which has its own + // corresponding pools. It does not include the BaseDenom, which has its own // query endpoint FeeTokens(context.Context, *QueryFeeTokensRequest) (*QueryFeeTokensResponse, error) + // DenomSpotPrice returns all spot prices by each registered token denom. DenomSpotPrice(context.Context, *QueryDenomSpotPriceRequest) (*QueryDenomSpotPriceResponse, error) + // Returns the poolID for a specified denom input. DenomPoolId(context.Context, *QueryDenomPoolIdRequest) (*QueryDenomPoolIdResponse, error) + // Returns a list of all base denom tokens and their corresponding pools. BaseDenom(context.Context, *QueryBaseDenomRequest) (*QueryBaseDenomResponse, error) } From 47a2366c5eeee474de9e1cb4777fab0ccfbb9592 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 19 Jul 2022 14:08:14 -0400 Subject: [PATCH 104/376] e2e: enable state-sync tests (final MVP) (#2125) * progress * snapshot passes with no upgrade enabled * remove tm test config * permissions * make state sync test work with upgrades * comments * lint * comments * update init image and README * remove obsolete var * Update tests/e2e/e2e_test.go Co-authored-by: Adam Tucker * snapshot height from config Co-authored-by: Adam Tucker --- tests/e2e/README.md | 3 + tests/e2e/configurer/base.go | 4 +- tests/e2e/configurer/chain/chain.go | 33 +++++++++ tests/e2e/configurer/chain/node.go | 22 +++++- tests/e2e/configurer/chain/queries.go | 17 +++++ tests/e2e/configurer/factory.go | 8 ++- tests/e2e/containers/config.go | 2 +- tests/e2e/e2e_setup_test.go | 17 +++-- tests/e2e/e2e_test.go | 98 +++++++++++++++++++++++++++ tests/e2e/initialization/init.go | 8 ++- tests/e2e/initialization/init_test.go | 2 +- tests/e2e/initialization/node.go | 3 +- tests/e2e/initialization/node/main.go | 10 ++- 13 files changed, 208 insertions(+), 19 deletions(-) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index efe054035fa..d34b339f52b 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -161,6 +161,8 @@ tests require IBC logic. - `OSMOSIS_E2E_SKIP_IBC` - when true, skips the IBC tests tests. +- `OSMOSIS_E2E_SKIP_STATE_SYNC` - when true, skips the state sync tests. + - `OSMOSIS_E2E_SKIP_CLEANUP` - when true, avoids cleaning up the e2e Docker containers. @@ -191,6 +193,7 @@ This debug configuration helps to run e2e tests locally and skip the desired tes "OSMOSIS_E2E_SKIP_IBC": "true", "OSMOSIS_E2E_SKIP_UPGRADE": "true", "OSMOSIS_E2E_SKIP_CLEANUP": "true", + "OSMOSIS_E2E_SKIP_STATE_SYNC": "true", "OSMOSIS_E2E_UPGRADE_VERSION": "v10", "OSMOSIS_E2E_FORK_HEIGHT": "4713065" # this is v10 fork height. } diff --git a/tests/e2e/configurer/base.go b/tests/e2e/configurer/base.go index 0503df2953c..14f2eef8a5c 100644 --- a/tests/e2e/configurer/base.go +++ b/tests/e2e/configurer/base.go @@ -178,8 +178,8 @@ func (bc *baseConfigurer) initializeChainConfigFromInitChain(initializedChain *i chainConfig.ChainMeta = initializedChain.ChainMeta chainConfig.NodeConfigs = make([]*chain.NodeConfig, 0, len(initializedChain.Nodes)) setupTime := time.Now() - for _, validator := range initializedChain.Nodes { - conf := chain.NewNodeConfig(bc.t, validator, chainConfig.Id, bc.containerManager).WithSetupTime(setupTime) + for i, validator := range initializedChain.Nodes { + conf := chain.NewNodeConfig(bc.t, validator, chainConfig.ValidatorInitConfigs[i], chainConfig.Id, bc.containerManager).WithSetupTime(setupTime) chainConfig.NodeConfigs = append(chainConfig.NodeConfigs, conf) } } diff --git a/tests/e2e/configurer/chain/chain.go b/tests/e2e/configurer/chain/chain.go index d4b4b13fbff..53cc493ebb0 100644 --- a/tests/e2e/configurer/chain/chain.go +++ b/tests/e2e/configurer/chain/chain.go @@ -50,6 +50,29 @@ func New(t *testing.T, containerManager *containers.Manager, id string, initVali } } +// CreateNode returns new initialized NodeConfig. +func (c *Config) CreateNode(initNode *initialization.Node) *NodeConfig { + nodeConfig := &NodeConfig{ + Node: *initNode, + chainId: c.Id, + containerManager: c.containerManager, + t: c.t, + } + c.NodeConfigs = append(c.NodeConfigs, nodeConfig) + return nodeConfig +} + +// RemoveNode removes node and stops it from running. +func (c *Config) RemoveNode(nodeName string) error { + for i, node := range c.NodeConfigs { + if node.Name == nodeName { + c.NodeConfigs = append(c.NodeConfigs[:i], c.NodeConfigs[i+1:]...) + return node.Stop() + } + } + return fmt.Errorf("node %s not found", nodeName) +} + // WaitUntilHeight waits for all validators to reach the specified height at the minimum. // returns error, if any. func (c *Config) WaitUntilHeight(height int64) error { @@ -118,6 +141,16 @@ func (c *Config) GetDefaultNode() (*NodeConfig, error) { return c.getNodeAtIndex(defaultNodeIndex) } +// GetPersistentPeers returns persistent peers from every node +// associated with a chain. +func (c *Config) GetPersistentPeers() []string { + peers := make([]string, len(c.NodeConfigs)) + for i, node := range c.NodeConfigs { + peers[i] = node.PeerId + } + return peers +} + func (c *Config) getNodeAtIndex(nodeIndex int) (*NodeConfig, error) { if nodeIndex > len(c.NodeConfigs) { return nil, fmt.Errorf("node index (%d) is greter than the number of nodes available (%d)", nodeIndex, len(c.NodeConfigs)) diff --git a/tests/e2e/configurer/chain/node.go b/tests/e2e/configurer/chain/node.go index 2c76a6ef51e..10b4cc99001 100644 --- a/tests/e2e/configurer/chain/node.go +++ b/tests/e2e/configurer/chain/node.go @@ -20,6 +20,7 @@ type NodeConfig struct { initialization.Node OperatorAddress string + SnapshotInterval uint64 chainId string rpcClient *rpchttp.HTTP t *testing.T @@ -30,9 +31,10 @@ type NodeConfig struct { } // NewNodeConfig returens new initialized NodeConfig. -func NewNodeConfig(t *testing.T, initNode *initialization.Node, chainId string, containerManager *containers.Manager) *NodeConfig { +func NewNodeConfig(t *testing.T, initNode *initialization.Node, initConfig *initialization.NodeConfig, chainId string, containerManager *containers.Manager) *NodeConfig { return &NodeConfig{ Node: *initNode, + SnapshotInterval: initConfig.SnapshotInterval, chainId: chainId, containerManager: containerManager, t: t, @@ -44,7 +46,7 @@ func NewNodeConfig(t *testing.T, initNode *initialization.Node, chainId string, // The node configuration must be already added to the chain config prior to calling this // method. func (n *NodeConfig) Run() error { - n.t.Logf("starting %s validator container: %s", n.chainId, n.Name) + n.t.Logf("starting node container: %s", n.Name) resource, err := n.containerManager.RunNodeResource(n.chainId, n.Name, n.ConfigDir) if err != nil { return err @@ -63,7 +65,7 @@ func (n *NodeConfig) Run() error { return false } - n.t.Logf("started %s node container: %s", resource.Container.Name[1:], resource.Container.ID) + n.t.Logf("started node container: %s", n.Name) return true }, 5*time.Minute, @@ -80,6 +82,16 @@ func (n *NodeConfig) Run() error { return nil } +// Stop stops the node from running and removes its container. +func (n *NodeConfig) Stop() error { + n.t.Logf("stopping node container: %s", n.Name) + if err := n.containerManager.RemoveNodeResource(n.Name); err != nil { + return err + } + n.t.Logf("stopped node container: %s", n.Name) + return nil +} + // WaitUntil waits until node reaches doneCondition. Return nil // if reached, error otherwise. func (n *NodeConfig) WaitUntil(doneCondition func(syncInfo coretypes.SyncInfo) bool) error { @@ -118,6 +130,10 @@ func (n *NodeConfig) extractOperatorAddressIfValidator() error { return nil } +func (n *NodeConfig) GetHostPort(portId string) (string, error) { + return n.containerManager.GetHostPort(n.Name, portId) +} + func (n *NodeConfig) WithSetupTime(t time.Time) *NodeConfig { n.setupTime = t return n diff --git a/tests/e2e/configurer/chain/queries.go b/tests/e2e/configurer/chain/queries.go index 49f3472ce02..0a86a124201 100644 --- a/tests/e2e/configurer/chain/queries.go +++ b/tests/e2e/configurer/chain/queries.go @@ -2,6 +2,7 @@ package chain import ( "context" + "encoding/json" "fmt" "io" "net/http" @@ -13,6 +14,7 @@ import ( govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" + tmabcitypes "github.com/tendermint/tendermint/abci/types" "github.com/osmosis-labs/osmosis/v10/tests/e2e/util" superfluidtypes "github.com/osmosis-labs/osmosis/v10/x/superfluid/types" @@ -112,3 +114,18 @@ func (n *NodeConfig) QueryCurrentHeight() (int64, error) { } return status.SyncInfo.LatestBlockHeight, nil } + +// QueryListSnapshots gets all snapshots currently created for a node. +func (n *NodeConfig) QueryListSnapshots() ([]*tmabcitypes.Snapshot, error) { + abciResponse, err := n.rpcClient.ABCIQuery(context.Background(), "/app/snapshots", nil) + if err != nil { + return nil, err + } + + var listSnapshots tmabcitypes.ResponseListSnapshots + if err := json.Unmarshal(abciResponse.Response.Value, &listSnapshots); err != nil { + return nil, err + } + + return listSnapshots.Snapshots, nil +} diff --git a/tests/e2e/configurer/factory.go b/tests/e2e/configurer/factory.go index 92c52bb8e4b..35d528cc56a 100644 --- a/tests/e2e/configurer/factory.go +++ b/tests/e2e/configurer/factory.go @@ -28,12 +28,14 @@ var ( // the configurations below. validatorConfigsChainA = []*initialization.NodeConfig{ { - Name: "prune-default-snapshot", + // this is a node that is used to state-sync from so its snapshot-interval + // is frequent. + Name: "prune-default-snapshot-state-sync-from", Pruning: "default", PruningKeepRecent: "0", PruningInterval: "0", - SnapshotInterval: 1500, - SnapshotKeepRecent: 2, + SnapshotInterval: 25, + SnapshotKeepRecent: 10, IsValidator: true, }, { diff --git a/tests/e2e/containers/config.go b/tests/e2e/containers/config.go index 03c51ec9fce..12b1d9fdea9 100644 --- a/tests/e2e/containers/config.go +++ b/tests/e2e/containers/config.go @@ -27,7 +27,7 @@ const ( previousVersionOsmoTag = "v10.0.0-debug" // Pre-upgrade repo/tag for osmosis initialization (this should be one version below upgradeVersion) previousVersionInitRepository = "osmolabs/osmosis-e2e-init-chain" - previousVersionInitTag = "v10.0.0-e2e-v2" + previousVersionInitTag = "v10.0.0-e2e-v4" // Hermes repo/version for relayer relayerRepository = "osmolabs/hermes" relayerTag = "0.13.0" diff --git a/tests/e2e/e2e_setup_test.go b/tests/e2e/e2e_setup_test.go index 8d4417b866b..954e0a61e6d 100644 --- a/tests/e2e/e2e_setup_test.go +++ b/tests/e2e/e2e_setup_test.go @@ -16,6 +16,8 @@ const ( skipUpgradeEnv = "OSMOSIS_E2E_SKIP_UPGRADE" // Environment variable name to skip the IBC tests skipIBCEnv = "OSMOSIS_E2E_SKIP_IBC" + // Environment variable name to skip state sync testing + skipStateSyncEnv = "OSMOSIS_E2E_SKIP_STATE_SYNC" // Environment variable name to determine if this upgrade is a fork forkHeightEnv = "OSMOSIS_E2E_FORK_HEIGHT" // Environment variable name to skip cleaning up Docker resources in teardown @@ -27,10 +29,11 @@ const ( type IntegrationTestSuite struct { suite.Suite - configurer configurer.Configurer - skipUpgrade bool - skipIBC bool - forkHeight int + configurer configurer.Configurer + skipUpgrade bool + skipIBC bool + skipStateSync bool + forkHeight int } func TestIntegrationTestSuite(t *testing.T) { @@ -72,6 +75,12 @@ func (s *IntegrationTestSuite) SetupSuite() { s.T().Log(fmt.Sprintf("%s was true, skipping IBC tests", skipIBCEnv)) } + if str := os.Getenv("OSMOSIS_E2E_SKIP_STATE_SYNC"); len(str) > 0 { + s.skipStateSync, err = strconv.ParseBool(str) + s.Require().NoError(err) + s.T().Log("skipping state sync testing") + } + if str := os.Getenv(upgradeVersionEnv); len(str) > 0 { upgradeSettings.Version = str s.T().Log(fmt.Sprintf("upgrade version set to %s", upgradeSettings.Version)) diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index 6b8df0bfc1c..a653430283b 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -2,9 +2,13 @@ package e2e import ( "fmt" + "os" + "path/filepath" "strconv" "time" + coretypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) @@ -110,3 +114,97 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { "superfluid delegation vote overwrite not working as expected", ) } + +func (s *IntegrationTestSuite) TestStateSync() { + if s.skipStateSync { + s.T().Skip() + } + + chain := s.configurer.GetChainConfig(0) + runningNode, err := chain.GetDefaultNode() + s.Require().NoError(err) + + persistenrPeers := chain.GetPersistentPeers() + + stateSyncHostPort := fmt.Sprintf("%s:26657", runningNode.Name) + stateSyncRPCServers := []string{stateSyncHostPort, stateSyncHostPort} + + // get trust height and trust hash. + trustHeight, err := runningNode.QueryCurrentHeight() + s.Require().NoError(err) + + trustHash, err := runningNode.QueryHashFromBlock(trustHeight) + s.Require().NoError(err) + + stateSynchingNodeConfig := &initialization.NodeConfig{ + Name: "state-sync", + Pruning: "default", + PruningKeepRecent: "0", + PruningInterval: "0", + SnapshotInterval: 1500, + SnapshotKeepRecent: 2, + } + + tempDir, err := os.MkdirTemp("", "osmosis-e2e-statesync-") + s.Require().NoError(err) + + // configure genesis and config files for the state-synchin node. + nodeInit, err := initialization.InitSingleNode( + chain.Id, + tempDir, + filepath.Join(runningNode.ConfigDir, "config", "genesis.json"), + stateSynchingNodeConfig, + time.Duration(chain.VotingPeriod), + trustHeight, + trustHash, + stateSyncRPCServers, + persistenrPeers, + ) + s.Require().NoError(err) + + stateSynchingNode := chain.CreateNode(nodeInit) + + // ensure that the running node has snapshots at a height > trustHeight. + hasSnapshotsAvailable := func(syncInfo coretypes.SyncInfo) bool { + snapshotHeight := runningNode.SnapshotInterval + if uint64(syncInfo.LatestBlockHeight) < snapshotHeight { + s.T().Logf("snapshot height is not reached yet, current (%d), need (%d)", syncInfo.LatestBlockHeight, snapshotHeight) + return false + } + + snapshots, err := runningNode.QueryListSnapshots() + s.Require().NoError(err) + + for _, snapshot := range snapshots { + if snapshot.Height > uint64(trustHeight) { + s.T().Log("found state sync snapshot after trust height") + return true + } + } + s.T().Log("state sync snashot after trust height is not found") + return false + } + runningNode.WaitUntil(hasSnapshotsAvailable) + + // start the state synchin node. + err = stateSynchingNode.Run() + s.NoError(err) + + // ensure that the state synching node cathes up to the running node. + s.Require().Eventually(func() bool { + stateSyncNodeHeight, err := stateSynchingNode.QueryCurrentHeight() + s.NoError(err) + + runningNodeHeight, err := runningNode.QueryCurrentHeight() + s.NoError(err) + + return stateSyncNodeHeight == runningNodeHeight + }, + 3*time.Minute, + 500*time.Millisecond, + ) + + // stop the state synching node. + err = chain.RemoveNode(stateSynchingNode.Name) + s.NoError(err) +} diff --git a/tests/e2e/initialization/init.go b/tests/e2e/initialization/init.go index 427dbdad3a5..1f7df7dc712 100644 --- a/tests/e2e/initialization/init.go +++ b/tests/e2e/initialization/init.go @@ -36,7 +36,7 @@ func InitChain(id, dataDir string, nodeConfigs []*NodeConfig, votingPeriod time. for _, node := range chain.nodes { if node.isValidator { - if err := node.initValidatorConfigs(chain, peers); err != nil { + if err := node.initNodeConfigs(peers); err != nil { return nil, err } } @@ -44,7 +44,7 @@ func InitChain(id, dataDir string, nodeConfigs []*NodeConfig, votingPeriod time. return chain.export(), nil } -func InitSingleNode(chainId, dataDir string, existingGenesisDir string, nodeConfig *NodeConfig, votingPeriod time.Duration, trustHeight int64, trustHash string, stateSyncRPCServers []string) (*Node, error) { +func InitSingleNode(chainId, dataDir string, existingGenesisDir string, nodeConfig *NodeConfig, votingPeriod time.Duration, trustHeight int64, trustHash string, stateSyncRPCServers []string, persistentPeers []string) (*Node, error) { if nodeConfig.IsValidator { return nil, errors.New("creating individual validator nodes after starting up chain is not currently supported") } @@ -67,6 +67,10 @@ func InitSingleNode(chainId, dataDir string, existingGenesisDir string, nodeConf return nil, err } + if err := newNode.initNodeConfigs(persistentPeers); err != nil { + return nil, err + } + if err := newNode.initStateSyncConfig(trustHeight, trustHash, stateSyncRPCServers); err != nil { return nil, err } diff --git a/tests/e2e/initialization/init_test.go b/tests/e2e/initialization/init_test.go index 4cb54ab2ad8..42af5f3b858 100644 --- a/tests/e2e/initialization/init_test.go +++ b/tests/e2e/initialization/init_test.go @@ -109,7 +109,7 @@ func TestSingleNodeInit(t *testing.T) { existingChain, err := initialization.InitChain(id, dataDir, existingChainNodeConfigs, time.Second*3, forkHeight) require.NoError(t, err) - actualNode, err := initialization.InitSingleNode(existingChain.ChainMeta.Id, dataDir, filepath.Join(existingChain.Nodes[0].ConfigDir, "config", "genesis.json"), expectedConfig, time.Second*3, 3, "testHash", []string{"some server"}) + actualNode, err := initialization.InitSingleNode(existingChain.ChainMeta.Id, dataDir, filepath.Join(existingChain.Nodes[0].ConfigDir, "config", "genesis.json"), expectedConfig, time.Second*3, 3, "testHash", []string{"some server"}, []string{"some server"}) require.NoError(t, err) validateNode(t, id, dataDir, expectedConfig, actualNode) diff --git a/tests/e2e/initialization/node.go b/tests/e2e/initialization/node.go index 68536e736a7..08299a9d0e7 100644 --- a/tests/e2e/initialization/node.go +++ b/tests/e2e/initialization/node.go @@ -289,7 +289,7 @@ func (n *internalNode) createMnemonic() (string, error) { return mnemonic, nil } -func (n *internalNode) initValidatorConfigs(c *internalChain, persistentPeers []string) error { +func (n *internalNode) initNodeConfigs(persistentPeers []string) error { tmCfgPath := filepath.Join(n.configDir(), "config", "config.toml") vpr := viper.New() @@ -310,7 +310,6 @@ func (n *internalNode) initValidatorConfigs(c *internalChain, persistentPeers [] valConfig.StateSync.Enable = false valConfig.LogLevel = "info" valConfig.P2P.PersistentPeers = strings.Join(persistentPeers, ",") - valConfig.Consensus = tmconfig.TestConsensusConfig() tmconfig.WriteConfigFile(tmCfgPath, valConfig) return nil diff --git a/tests/e2e/initialization/node/main.go b/tests/e2e/initialization/node/main.go index 14ea881783b..d29b60b3790 100644 --- a/tests/e2e/initialization/node/main.go +++ b/tests/e2e/initialization/node/main.go @@ -24,6 +24,8 @@ func main() { stateSyncRPCServersStr string + persistentPeersStr string + trustHeight int64 trustHash string @@ -35,6 +37,7 @@ func main() { flag.StringVar(&nodeConfigStr, "node-config", "", "serialized node config") flag.DurationVar(&votingPeriod, "voting-period", 30000000000, "voting period") flag.StringVar(&stateSyncRPCServersStr, "rpc-servers", "", "state sync RPC servers") + flag.StringVar(&persistentPeersStr, "peers", "", "state sync RPC servers") flag.Int64Var(&trustHeight, "trust-height", 0, "trust Height") flag.StringVar(&trustHash, "trust-hash", "", "trust hash") @@ -55,11 +58,16 @@ func main() { panic("rpc-servers is required, separated by commas") } + persistenrPeers := strings.Split(persistentPeersStr, ",") + if len(persistenrPeers) == 0 { + panic("persistent peers are required, separated by commas") + } + if err := os.MkdirAll(dataDir, 0o755); err != nil { panic(err) } - _, err = initialization.InitSingleNode(chainId, dataDir, existingGenesisDir, &nodeConfig, votingPeriod, trustHeight, trustHash, stateSyncRPCServers) + _, err = initialization.InitSingleNode(chainId, dataDir, existingGenesisDir, &nodeConfig, votingPeriod, trustHeight, trustHash, stateSyncRPCServers, persistenrPeers) if err != nil { panic(err) } From 3aecc23c75f62623c21578b07445a443f4edaea5 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Tue, 19 Jul 2022 15:00:38 -0500 Subject: [PATCH 105/376] Benchmark apptesting setup time (#2143) --- app/apptesting/bench_test.go | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 app/apptesting/bench_test.go diff --git a/app/apptesting/bench_test.go b/app/apptesting/bench_test.go new file mode 100644 index 00000000000..5a731014810 --- /dev/null +++ b/app/apptesting/bench_test.go @@ -0,0 +1,10 @@ +package apptesting + +import "testing" + +func BenchmarkSetup(b *testing.B) { + for i := 0; i < b.N; i++ { + s := new(KeeperTestHelper) + s.Setup() + } +} From edf78ae32b8bac5c6407f0ba3457cb40cd583f1d Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 19 Jul 2022 17:57:23 -0400 Subject: [PATCH 106/376] chore: Set MaxAgeNumBlocks in v11 Upgrade Handler (#2147) Closes: #2124 ## What is the purpose of the change Ref: #1638 Since the previous upgrade was a fork, the MaxAgeNumBlocks change was not applied during v10 upgrade. As a result, adding the exact same logic to the v11 handler. ## Testing and Verifying Covered by e2e upgrade tests. ## Documentation and Release Note - Does this pull request introduce a new feature or user-facing behavior changes? no - Is a relevant changelog entry added to the `Unreleased` section in `CHANGELOG.md`? no - How is the feature or change documented? not applicable --- CHANGELOG.md | 1 + app/upgrades/v11/upgrades.go | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 235e00b7588..53d1eb7ab17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased * [#2016](https://github.com/osmosis-labs/osmosis/pull/2016) Add fixed 10000 gas cost for each Balancer swap +* [$2147](https://github.com/osmosis-labs/osmosis/pull/2147) Set MaxAgeNumBlocks in v11 Upgrade Handler to two weeks. ### Breaking Changes diff --git a/app/upgrades/v11/upgrades.go b/app/upgrades/v11/upgrades.go index be6e5c21cba..25af86205cf 100644 --- a/app/upgrades/v11/upgrades.go +++ b/app/upgrades/v11/upgrades.go @@ -27,6 +27,18 @@ func CreateUpgradeHandler( return nil, err } + // Set the max_age_num_blocks in the evidence params to reflect the 14 day + // unbonding period. + // + // Ref: https://github.com/osmosis-labs/osmosis/issues/1160 + cp := bpm.GetConsensusParams(ctx) + if cp != nil && cp.Evidence != nil { + evParams := cp.Evidence + evParams.MaxAgeNumBlocks = 186_092 + + bpm.StoreConsensusParams(ctx, cp) + } + return mm.RunMigrations(ctx, configurator, fromVM) } } From 339c58fa0ff03ac249b3a00915f1f3f37807ddd5 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 19 Jul 2022 20:47:20 -0400 Subject: [PATCH 107/376] chore(changelog): add api breaking changelog entry from #1857 (#2157) Closes: #XXX ## What is the purpose of the change #1857 introduced an API break but a changelog entry wasn't added. This PR follows through with the entry --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 53d1eb7ab17..8c6bbe25e4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#1630](https://github.com/osmosis-labs/osmosis/pull/1630) Delete the v043_temp module, now that we're on an updated SDK version. * [#1667](https://github.com/osmosis-labs/osmosis/pull/1673) Move wasm-bindings code out of app package into its own root level package. * [#2013](https://github.com/osmosis-labs/osmosis/pull/2013) Make `SetParams`, `SetPool`, `SetTotalLiquidity`, and `SetDenomLiquidity` GAMM APIs private +*[#1857](https://github.com/osmosis-labs/osmosis/pull/1857) x/mint rename GetLastHalvenEpochNum to GetLastReductionEpochNum ### Features From a75b1f734603027002b44fd278220b32796d3db4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 20 Jul 2022 01:39:30 +0000 Subject: [PATCH 108/376] chore(deps): bump github.com/golangci/golangci-lint from 1.47.0 to 1.47.1 (#2163) Bumps [github.com/golangci/golangci-lint](https://github.com/golangci/golangci-lint) from 1.47.0 to 1.47.1.
Release notes

Sourced from github.com/golangci/golangci-lint's releases.

v1.47.1

Changelog

  • a91463cd build(deps): bump github.com/daixiang0/gci from 0.4.2 to 0.4.3 (#2992)
  • 4c8bdc70 build(deps): bump github.com/sivchari/tenv from 1.6.0 to 1.7.0 (#2988)
  • 4e60e8a8 gci: fix options display (#2989)
  • fd87bd1e gci: remove the use of stdin (#2984)
Changelog

Sourced from github.com/golangci/golangci-lint's changelog.

v1.47.1

  1. updated linters:
    • gci: from 0.4.2 to 0.4.3
    • gci: remove the use of stdin
    • gci: fix options display
    • tenv: from 1.6.0 to 1.7.0
    • unparam: bump to HEAD
Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=github.com/golangci/golangci-lint&package-manager=go_modules&previous-version=1.47.0&new-version=1.47.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
--- go.mod | 14 +++++++------- go.sum | 28 ++++++++++++---------------- 2 files changed, 19 insertions(+), 23 deletions(-) diff --git a/go.mod b/go.mod index fe15d4903b3..c1db08ff788 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/cosmos/ibc-go/v3 v3.0.0 github.com/gogo/protobuf v1.3.3 github.com/golang/protobuf v1.5.2 - github.com/golangci/golangci-lint v1.47.0 + github.com/golangci/golangci-lint v1.47.1 github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/ory/dockertest/v3 v3.9.1 @@ -79,11 +79,11 @@ require ( github.com/coinbase/rosetta-sdk-go v0.7.0 // indirect github.com/confio/ics23/go v0.7.0 // indirect github.com/containerd/continuity v0.3.0 // indirect - github.com/cosmos/btcutil v1.0.4 // indirect + github.com/cosmos/btcutil v1.0.4 github.com/cosmos/gorocksdb v1.2.0 // indirect github.com/cosmos/ledger-cosmos-go v0.11.1 // indirect github.com/cosmos/ledger-go v0.9.2 // indirect - github.com/daixiang0/gci v0.4.2 // indirect + github.com/daixiang0/gci v0.4.3 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/denis-tingaikin/go-header v0.4.3 // indirect @@ -229,7 +229,7 @@ require ( github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c // indirect github.com/sirupsen/logrus v1.8.1 // indirect github.com/sivchari/containedctx v1.0.2 // indirect - github.com/sivchari/tenv v1.6.0 // indirect + github.com/sivchari/tenv v1.7.0 // indirect github.com/sonatard/noctx v0.0.1 // indirect github.com/sourcegraph/go-diff v0.6.1 // indirect github.com/spf13/afero v1.8.2 // indirect @@ -263,14 +263,14 @@ require ( go.etcd.io/bbolt v1.3.6 // indirect go.opencensus.io v0.23.0 // indirect golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect - golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e // indirect + golang.org/x/exp/typeparams v0.0.0-20220613132600-b0d781184e0d // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect golang.org/x/sys v0.0.0-20220702020025-31831981b65f // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect - golang.org/x/tools v0.1.11 // indirect + golang.org/x/tools v0.1.12-0.20220628192153-7743d1d949f1 // indirect google.golang.org/protobuf v1.28.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/ini.v1 v1.66.6 // indirect @@ -278,7 +278,7 @@ require ( honnef.co/go/tools v0.3.2 // indirect mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed // indirect mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b // indirect - mvdan.cc/unparam v0.0.0-20211214103731-d0ef000c54e5 // indirect + mvdan.cc/unparam v0.0.0-20220706161116-678bad134442 // indirect nhooyr.io/websocket v1.8.6 // indirect ) diff --git a/go.sum b/go.sum index a2fcf17be47..2a4b4b59fb5 100644 --- a/go.sum +++ b/go.sum @@ -311,8 +311,8 @@ github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cyphar/filepath-securejoin v0.2.2/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4= github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= -github.com/daixiang0/gci v0.4.2 h1:PyT/Y4a265wDhPCZo2ip/YH33M4zEuFA3nDMdAvcKSA= -github.com/daixiang0/gci v0.4.2/go.mod h1:d0f+IJhr9loBtIq+ebwhRoTt1LGbPH96ih8bKlsRT9E= +github.com/daixiang0/gci v0.4.3 h1:wf7x0xRjQqTlA2dzHTI0A/xPyp7VcBatBG9nwGatwbQ= +github.com/daixiang0/gci v0.4.3/go.mod h1:EpVfrztufwVgQRXjnX4zuNinEpLj5OmMjtu/+MB0V0c= github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -541,8 +541,8 @@ github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe h1:6RGUuS7EGotKx6 github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe/go.mod h1:gjqyPShc/m8pEMpk0a3SeagVb0kaqvhscv+i9jI5ZhQ= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a h1:iR3fYXUjHCR97qWS8ch1y9zPNsgXThGwjKPrYfqMPks= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= -github.com/golangci/golangci-lint v1.47.0 h1:h2s+ZGGF63fdzUtac+VYUHPsEO0ADTqHouI7Vase+FY= -github.com/golangci/golangci-lint v1.47.0/go.mod h1:3TZhfF5KolbIkXYjUFvER6G9CoxzLEaafr/u/QI1S5A= +github.com/golangci/golangci-lint v1.47.1 h1:hbubHskV2Ppwz4ZZE2lc0/Pw9ZhqLuzm2dT7ZVpLA6Y= +github.com/golangci/golangci-lint v1.47.1/go.mod h1:lpS2pjBZtRyXewUcOY7yUL3K4KfpoWz072yRN8AuhHg= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 h1:MfyDlzVjl1hoaPzPD4Gpb/QgoRfSBR0jdhwGyAWwMSA= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0/go.mod h1:66R6K6P6VWk9I95jvqGxkqJxVWGFy9XlDwLwVz1RCFg= github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca h1:kNY3/svz5T29MYHubXix4aDDuE3RWHkPvopM/EDv/MA= @@ -1079,7 +1079,6 @@ github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0 github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -1172,7 +1171,6 @@ github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6So github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= -github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rs/cors v0.0.0-20160617231935-a62a804a8a00/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.2 h1:KCooALfAYGs415Cwu5ABvv9n9509fSiG5SQJn/AQo4U= @@ -1219,8 +1217,8 @@ github.com/sivchari/containedctx v1.0.2 h1:0hLQKpgC53OVF1VT7CeoFHk9YKstur1XOgfYI github.com/sivchari/containedctx v1.0.2/go.mod h1:PwZOeqm4/DLoJOqMSIJs3aKqXRX4YO+uXww087KZ7Bw= github.com/sivchari/nosnakecase v1.5.0 h1:ZBvAu1H3uteN0KQ0IsLpIFOwYgPEhKLyv2ahrVkub6M= github.com/sivchari/nosnakecase v1.5.0/go.mod h1:CwDzrzPea40/GB6uynrNLiorAlgFRvRbFSgJx2Gs+QY= -github.com/sivchari/tenv v1.6.0 h1:FyE4WysxLwYljKqWhTfOMjgKjBSnmzzg7lWOmpDiAcc= -github.com/sivchari/tenv v1.6.0/go.mod h1:64yStXKSOxDfX47NlhVwND4dHwfZDdbp2Lyl018Icvg= +github.com/sivchari/tenv v1.7.0 h1:d4laZMBK6jpe5PWepxlV9S+LC0yXqvYHiq8E6ceoVVE= +github.com/sivchari/tenv v1.7.0/go.mod h1:64yStXKSOxDfX47NlhVwND4dHwfZDdbp2Lyl018Icvg= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPHbB5mVY2iO9KV3pTt/QbIkGaO8gQ2WrDbP4= @@ -1328,7 +1326,6 @@ github.com/tidwall/sjson v1.1.4/go.mod h1:wXpKXu8CtDjKAZ+3DrKY5ROCorDFahq8l0tey/ github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144 h1:kl4KhGNsJIbDHS9/4U9yQo1UcPQM0kOMJHn29EoH/Ro= github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= github.com/tinylib/msgp v1.1.5/go.mod h1:eQsjooMTnV42mHu917E26IogZ2930nFyBQdofk10Udg= -github.com/tj/assert v0.0.3 h1:Df/BlaZ20mq6kuai7f5z2TvPFiwC3xaWJSDQNiIS3Rk= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20200427203606-3cfed13b9966/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= @@ -1493,8 +1490,8 @@ golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMk golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= golang.org/x/exp v0.0.0-20220613132600-b0d781184e0d h1:vtUKgx8dahOomfFzLREU8nSv25YHnTgLBn4rDnWZdU0= golang.org/x/exp v0.0.0-20220613132600-b0d781184e0d/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA= -golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e h1:qyrTQ++p1afMkO4DPEeLGq/3oTsdlvdH4vqZUBWzUKM= -golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= +golang.org/x/exp/typeparams v0.0.0-20220613132600-b0d781184e0d h1:+W8Qf4iJtMGKkyAygcKohjxTk4JPsL9DpzApJ22m5Ic= +golang.org/x/exp/typeparams v0.0.0-20220613132600-b0d781184e0d/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= @@ -1730,7 +1727,6 @@ golang.org/x/sys v0.0.0-20211116061358-0a5406a5449c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1857,12 +1853,12 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= -golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.9-0.20211228192929-ee1ca4ffc4da/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= -golang.org/x/tools v0.1.11 h1:loJ25fNOEhSXfHrpoGj91eCUThwdNX6u24rO1xnNteY= golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= +golang.org/x/tools v0.1.12-0.20220628192153-7743d1d949f1 h1:NHLFZ56qCjD+0hYY3kE5Wl40Z7q4Gn9Ln/7YU0lsGko= +golang.org/x/tools v0.1.12-0.20220628192153-7743d1d949f1/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -2066,8 +2062,8 @@ mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed h1:WX1yoOaKQfddO/mLzdV4wp mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed/go.mod h1:Xkxe497xwlCKkIaQYRfC7CSLworTXY9RMqwhhCm+8Nc= mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b h1:DxJ5nJdkhDlLok9K6qO+5290kphDJbHOQO1DFFFTeBo= mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b/go.mod h1:2odslEg/xrtNQqCYg2/jCoyKnw3vv5biOc3JnIcYfL4= -mvdan.cc/unparam v0.0.0-20211214103731-d0ef000c54e5 h1:Jh3LAeMt1eGpxomyu3jVkmVZWW2MxZ1qIIV2TZ/nRio= -mvdan.cc/unparam v0.0.0-20211214103731-d0ef000c54e5/go.mod h1:b8RRCBm0eeiWR8cfN88xeq2G5SG3VKGO+5UPWi5FSOY= +mvdan.cc/unparam v0.0.0-20220706161116-678bad134442 h1:seuXWbRB1qPrS3NQnHmFKLJLtskWyueeIzmLXghMGgk= +mvdan.cc/unparam v0.0.0-20220706161116-678bad134442/go.mod h1:F/Cxw/6mVrNKqrR2YjFf5CaW0Bw4RL8RfbEf4GRggJk= nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= nhooyr.io/websocket v1.8.6/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= pgregory.net/rapid v0.4.7/go.mod h1:UYpPVyjFHzYBGHIxLFoupi8vwk6rXNzRY9OMvVxFIOU= From 0c93a03d68a568f0379a6742861be19ed933f9fd Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 19 Jul 2022 21:43:49 -0400 Subject: [PATCH 109/376] chore(x/mint): use Require() for assertions in tests (#2161) --- x/mint/keeper/genesis_test.go | 12 ++-- x/mint/keeper/hooks_test.go | 58 +++++++++--------- x/mint/keeper/keeper_test.go | 112 +++++++++++++++++----------------- 3 files changed, 91 insertions(+), 91 deletions(-) diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index 078d0ca623c..a74f02cc555 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -118,25 +118,25 @@ func (suite *KeeperTestSuite) TestMintInitGenesis() { // Epoch provisions are set to genesis epoch provisions from params. actualEpochProvisions := mintKeeper.GetMinter(ctx).EpochProvisions - suite.Equal(tc.expectedEpochProvisions, actualEpochProvisions) + suite.Require().Equal(tc.expectedEpochProvisions, actualEpochProvisions) // Supply offset is applied to genesis supply. actualSupplyOffset := bankKeeper.GetSupplyOffset(ctx, tc.mintDenom) expectedSupplyOffset := tc.expectedSupplyOffsetDelta.Add(originalSupplyOffset) - suite.Equal(expectedSupplyOffset, actualSupplyOffset) + suite.Require().Equal(expectedSupplyOffset, actualSupplyOffset) // Supply with offset is as expected. actualSupplyWithOffset := bankKeeper.GetSupplyWithOffset(ctx, tc.mintDenom).Amount expectedSupplyWithOffset := tc.expectedSupplyWithOffsetDelta.Add(originalSupplyWithOffset.Amount) - suite.Equal(expectedSupplyWithOffset.Int64(), actualSupplyWithOffset.Int64()) + suite.Require().Equal(expectedSupplyWithOffset.Int64(), actualSupplyWithOffset.Int64()) // Developer vesting account has the desired amount of tokens. actualVestingCoins := bankKeeper.GetBalance(ctx, developerAccount, tc.mintDenom) expectedDeveloperVestingAmount := tc.expectedDeveloperVestingAmountDelta.Add(originalVestingCoins.Amount) - suite.Equal(expectedDeveloperVestingAmount.Int64(), actualVestingCoins.Amount.Int64()) + suite.Require().Equal(expectedDeveloperVestingAmount.Int64(), actualVestingCoins.Amount.Int64()) // Last halven epoch num is set to 0. - suite.Equal(tc.expectedHalvenStartedEpoch, mintKeeper.GetLastReductionEpochNum(ctx)) + suite.Require().Equal(tc.expectedHalvenStartedEpoch, mintKeeper.GetLastReductionEpochNum(ctx)) }) } } @@ -168,7 +168,7 @@ func (suite *KeeperTestSuite) TestMintExportGenesis() { actualGenesis := app.MintKeeper.ExportGenesis(ctx) // Assertions. - suite.Equal(tc.expectedGenesis, actualGenesis) + suite.Require().Equal(tc.expectedGenesis, actualGenesis) }) } } diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index e262e9d3c63..e26c959a26b 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -51,32 +51,32 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { mintParams = app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking) - suite.NoError(err) + suite.Require().NoError(err) expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) // ensure post-epoch supply with offset changed by exactly the minted coins amount // ensure post-epoch supply with offset changed by less than the minted coins amount (because of developer vesting account) postsupply := app.BankKeeper.GetSupply(ctx, mintParams.MintDenom) postsupplyWithOffset := app.BankKeeper.GetSupplyWithOffset(ctx, mintParams.MintDenom) - suite.False(postsupply.IsEqual(presupply.Add(mintedCoin))) - suite.True(postsupplyWithOffset.IsEqual(presupplyWithOffset.Add(mintedCoin))) + suite.Require().False(postsupply.IsEqual(presupply.Add(mintedCoin))) + suite.Require().True(postsupplyWithOffset.IsEqual(presupplyWithOffset.Add(mintedCoin))) // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) - suite.Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) + suite.Require().Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) expectedDevRewards, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.NoError(err) - suite.Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) + suite.Require().NoError(err) + suite.Require().Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) } app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) lastReductionPeriod = app.MintKeeper.GetLastReductionEpochNum(ctx) - suite.Equal(lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) + suite.Require().Equal(lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) @@ -89,18 +89,18 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { mintParams = app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking) - suite.NoError(err) + suite.Require().NoError(err) expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) - suite.Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) + suite.Require().Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) // test that the balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) expectedDevRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.NoError(err) - suite.Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) + suite.Require().NoError(err) + suite.Require().Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) } } @@ -127,18 +127,18 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp mintParams := app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking.Add(mintParams.DistributionProportions.DeveloperRewards)) - suite.NoError(err) + suite.Require().NoError(err) expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) // check community pool balance increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) - suite.Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) + suite.Require().Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) expectedDevRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.NoError(err) - suite.Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) + suite.Require().NoError(err) + suite.Require().Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) } // correct rewards @@ -150,7 +150,7 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) lastReductionPeriod = app.MintKeeper.GetLastReductionEpochNum(ctx) - suite.Equal(lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) + suite.Require().Equal(lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { checkDistribution(height) @@ -181,7 +181,7 @@ func (suite *KeeperTestSuite) TestEndOfEpochNoDistributionWhenIsNotYetStartTime( // check community pool balance not increase feePoolNew := app.DistrKeeper.GetFeePool(ctx) - suite.Equal(feePoolOrigin.CommunityPool, feePoolNew.CommunityPool, "height = %v", height) + suite.Require().Equal(feePoolOrigin.CommunityPool, feePoolNew.CommunityPool, "height = %v", height) } // Run through epochs mintParams.MintingRewardsDistributionStartEpoch // ensure tokens distributed @@ -192,7 +192,7 @@ func (suite *KeeperTestSuite) TestEndOfEpochNoDistributionWhenIsNotYetStartTime( // reduction period should be set to mintParams.MintingRewardsDistributionStartEpoch lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) - suite.Equal(lastReductionPeriod, mintParams.MintingRewardsDistributionStartEpoch) + suite.Require().Equal(lastReductionPeriod, mintParams.MintingRewardsDistributionStartEpoch) } // TODO: Remove after rounding errors are addressed and resolved. @@ -309,7 +309,7 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete for _, w := range mintParams.WeightedDeveloperRewardsReceivers { sumOfWeights = sumOfWeights.Add(w.Weight) } - suite.Equal(sdk.OneDec(), sumOfWeights) + suite.Require().Equal(sdk.OneDec(), sumOfWeights) // Test setup parameters are not identical with mainnet. // Therfore, we set them here to the desired mainnet values. @@ -323,10 +323,10 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete expectedSupply := sdk.NewDec(developerAccountBalance) supplyWithOffset := app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom) - suite.Equal(expectedSupplyWithOffset.TruncateInt64(), supplyWithOffset.Amount.Int64()) + suite.Require().Equal(expectedSupplyWithOffset.TruncateInt64(), supplyWithOffset.Amount.Int64()) supply := app.BankKeeper.GetSupply(ctx, mintDenom) - suite.Equal(expectedSupply.TruncateInt64(), supply.Amount.Int64()) + suite.Require().Equal(expectedSupply.TruncateInt64(), supply.Amount.Int64()) devRewardsDelta := sdk.ZeroDec() epochProvisionsDelta := genesisEpochProvisionsDec.Sub(genesisEpochProvisionsDec.TruncateInt().ToDec()).Mul(sdk.NewDec(reductionPeriodInEpochs)) @@ -370,14 +370,14 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete } expectedSupply = expectedSupply.Add(truncatedEpochProvisions).Sub(devRewards) - suite.Equal(expectedSupply.RoundInt(), app.BankKeeper.GetSupply(ctx, mintDenom).Amount) + suite.Require().Equal(expectedSupply.RoundInt(), app.BankKeeper.GetSupply(ctx, mintDenom).Amount) expectedSupplyWithOffset = expectedSupply.Sub(developerAccountBalance.Amount.ToDec()) - suite.Equal(expectedSupplyWithOffset.RoundInt(), app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount) + suite.Require().Equal(expectedSupplyWithOffset.RoundInt(), app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount) // Validate that the epoch provisions have not been reduced. - suite.Equal(mintingRewardsDistributionStartEpoch, app.MintKeeper.GetLastReductionEpochNum(ctx)) - suite.Equal(genesisEpochProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions.String()) + suite.Require().Equal(mintingRewardsDistributionStartEpoch, app.MintKeeper.GetLastReductionEpochNum(ctx)) + suite.Require().Equal(genesisEpochProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions.String()) } // Validate total supply. @@ -393,16 +393,16 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete actualTotalProvisionedSupply := app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount.ToDec() // 299_999_999_999_999.999999999999999705 == 299_999_999_997_380 + 2555 + 64.999999999999999705 - suite.Equal(expectedTotalProvisionedSupply, actualTotalProvisionedSupply.Add(devRewardsDelta).Add(epochProvisionsDelta)) + suite.Require().Equal(expectedTotalProvisionedSupply, actualTotalProvisionedSupply.Add(devRewardsDelta).Add(epochProvisionsDelta)) // This end of epoch should trigger thirdening. It will utilize the updated // (reduced) provisions. app.MintKeeper.AfterEpochEnd(ctx, epochIdentifier, thirdeningEpochNum) - suite.Equal(thirdeningEpochNum, app.MintKeeper.GetLastReductionEpochNum(ctx)) + suite.Require().Equal(thirdeningEpochNum, app.MintKeeper.GetLastReductionEpochNum(ctx)) expectedThirdenedProvisions := mintParams.ReductionFactor.Mul(genesisEpochProvisionsDec) // Sanity check with the actual value on mainnet. - suite.Equal(mainnetThirdenedProvisions, expectedThirdenedProvisions.String()) - suite.Equal(expectedThirdenedProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions) + suite.Require().Equal(mainnetThirdenedProvisions, expectedThirdenedProvisions.String()) + suite.Require().Equal(expectedThirdenedProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions) } diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 1eb27fc2056..6beac4e4c58 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -75,7 +75,7 @@ func (suite *KeeperTestSuite) setupDeveloperVestingModuleAccountTest(blockHeight // therefore, we should reset it to 0 to set up the environment truly w/o the module account. supplyOffset := bankKeeper.GetSupplyOffset(suite.Ctx, sdk.DefaultBondDenom) bankKeeper.AddSupplyOffset(suite.Ctx, sdk.DefaultBondDenom, supplyOffset.Mul(sdk.NewInt(-1))) - suite.Equal(sdk.ZeroInt(), bankKeeper.GetSupplyOffset(suite.Ctx, sdk.DefaultBondDenom)) + suite.Require().Equal(sdk.ZeroInt(), bankKeeper.GetSupplyOffset(suite.Ctx, sdk.DefaultBondDenom)) } } @@ -137,12 +137,12 @@ func (suite *KeeperTestSuite) TestGetProportions() { if tc.expectedError != nil { suite.Require().Equal(tc.expectedError, err) - suite.Equal(sdk.Coin{}, coin) + suite.Require().Equal(sdk.Coin{}, coin) return } - suite.NoError(err) - suite.Equal(tc.expectedCoin, coin) + suite.Require().NoError(err) + suite.Require().Equal(tc.expectedCoin, coin) }) } } @@ -215,32 +215,32 @@ func (suite *KeeperTestSuite) TestDistributeMintedCoin_ToDeveloperRewardsAddr() suite.FundAcc(gaugeCreator, mintLPtokens) gaugeId, err := intencentivesKeeper.CreateGauge(suite.Ctx, true, gaugeCreator, gaugeCoins, distrTo, time.Now(), 1) - suite.NoError(err) + suite.Require().NoError(err) err = poolincentivesKeeper.UpdateDistrRecords(suite.Ctx, poolincentivestypes.DistrRecord{ GaugeId: gaugeId, Weight: sdk.NewInt(100), }) - suite.NoError(err) + suite.Require().NoError(err) err = mintKeeper.MintCoins(suite.Ctx, sdk.NewCoins(tc.mintCoin)) - suite.NoError(err) + suite.Require().NoError(err) err = mintKeeper.DistributeMintedCoin(suite.Ctx, tc.mintCoin) - suite.NoError(err) + suite.Require().NoError(err) // check feePool feePool := distrKeeper.GetFeePool(suite.Ctx) feeCollector := accountKeeper.GetModuleAddress(authtypes.FeeCollectorName) - suite.Equal( + suite.Require().Equal( tc.mintCoin.Amount.ToDec().Mul(params.DistributionProportions.Staking).TruncateInt(), bankKeeper.GetAllBalances(suite.Ctx, feeCollector).AmountOf("stake")) if tc.weightedAddresses != nil { - suite.Equal( + suite.Require().Equal( tc.mintCoin.Amount.ToDec().Mul(params.DistributionProportions.CommunityPool), feePool.CommunityPool.AmountOf("stake")) } else { - suite.Equal( + suite.Require().Equal( // distribution go to community pool because nil dev reward addresses. tc.mintCoin.Amount.ToDec().Mul((params.DistributionProportions.DeveloperRewards).Add(params.DistributionProportions.CommunityPool)), feePool.CommunityPool.AmountOf("stake")) @@ -249,7 +249,7 @@ func (suite *KeeperTestSuite) TestDistributeMintedCoin_ToDeveloperRewardsAddr() // check devAddress balances for i, weightedAddress := range tc.weightedAddresses { devRewardsReceiver, _ := sdk.AccAddressFromBech32(weightedAddress.GetAddress()) - suite.Equal( + suite.Require().Equal( tc.mintCoin.Amount.ToDec().Mul(params.DistributionProportions.DeveloperRewards).Mul(params.WeightedDeveloperRewardsReceivers[i].Weight).TruncateInt(), bankKeeper.GetBalance(suite.Ctx, devRewardsReceiver, "stake").Amount) } @@ -268,9 +268,9 @@ func (suite *KeeperTestSuite) TestDistrAssetToCommunityPoolWhenNoDeveloperReward mintCoin := sdk.NewCoin("stake", sdk.NewInt(100000)) mintCoins := sdk.Coins{mintCoin} err := mintKeeper.MintCoins(suite.Ctx, mintCoins) - suite.NoError(err) + suite.Require().NoError(err) err = mintKeeper.DistributeMintedCoin(suite.Ctx, mintCoin) - suite.NoError(err) + suite.Require().NoError(err) distribution.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{}, *distrKeeper) @@ -280,26 +280,26 @@ func (suite *KeeperTestSuite) TestDistrAssetToCommunityPoolWhenNoDeveloperReward proportionToCommunity := params.DistributionProportions.PoolIncentives. Add(params.DistributionProportions.DeveloperRewards). Add(params.DistributionProportions.CommunityPool) - suite.Equal( + suite.Require().Equal( mintCoins[0].Amount.ToDec().Mul(params.DistributionProportions.Staking).TruncateInt(), bankKeeper.GetBalance(suite.Ctx, feeCollector, "stake").Amount) - suite.Equal( + suite.Require().Equal( mintCoins[0].Amount.ToDec().Mul(proportionToCommunity), feePool.CommunityPool.AmountOf("stake")) // Mint more and community pool should be increased err = mintKeeper.MintCoins(suite.Ctx, mintCoins) - suite.NoError(err) + suite.Require().NoError(err) err = mintKeeper.DistributeMintedCoin(suite.Ctx, mintCoin) - suite.NoError(err) + suite.Require().NoError(err) distribution.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{}, *distrKeeper) feePool = distrKeeper.GetFeePool(suite.Ctx) - suite.Equal( + suite.Require().Equal( mintCoins[0].Amount.ToDec().Mul(params.DistributionProportions.Staking).TruncateInt().Mul(sdk.NewInt(2)), bankKeeper.GetBalance(suite.Ctx, feeCollector, "stake").Amount) - suite.Equal( + suite.Require().Equal( mintCoins[0].Amount.ToDec().Mul(proportionToCommunity).Mul(sdk.NewDec(2)), feePool.CommunityPool.AmountOf("stake")) } @@ -342,11 +342,11 @@ func (suite *KeeperTestSuite) TestCreateDeveloperVestingModuleAccount() { actualError := mintKeeper.CreateDeveloperVestingModuleAccount(suite.Ctx, tc.amount) if tc.expectedError != nil { - suite.Error(actualError) - suite.ErrorIs(actualError, tc.expectedError) + suite.Require().Error(actualError) + suite.Require().ErrorIs(actualError, tc.expectedError) return } - suite.NoError(actualError) + suite.Require().NoError(actualError) }) } } @@ -382,16 +382,16 @@ func (suite *KeeperTestSuite) TestSetInitialSupplyOffsetDuringMigration() { actualError := mintKeeper.SetInitialSupplyOffsetDuringMigration(ctx) if tc.expectedError != nil { - suite.Error(actualError) - suite.ErrorIs(actualError, tc.expectedError) + suite.Require().Error(actualError) + suite.Require().ErrorIs(actualError, tc.expectedError) - suite.Equal(supplyWithOffsetBefore.Amount, bankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount) - suite.Equal(supplyOffsetBefore, bankKeeper.GetSupplyOffset(ctx, sdk.DefaultBondDenom)) + suite.Require().Equal(supplyWithOffsetBefore.Amount, bankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount) + suite.Require().Equal(supplyOffsetBefore, bankKeeper.GetSupplyOffset(ctx, sdk.DefaultBondDenom)) return } - suite.NoError(actualError) - suite.Equal(supplyWithOffsetBefore.Amount.Sub(sdk.NewInt(keeper.DeveloperVestingAmount)), bankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount) - suite.Equal(supplyOffsetBefore.Sub(sdk.NewInt(keeper.DeveloperVestingAmount)), bankKeeper.GetSupplyOffset(ctx, sdk.DefaultBondDenom)) + suite.Require().NoError(actualError) + suite.Require().Equal(supplyWithOffsetBefore.Amount.Sub(sdk.NewInt(keeper.DeveloperVestingAmount)), bankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount) + suite.Require().Equal(supplyOffsetBefore.Sub(sdk.NewInt(keeper.DeveloperVestingAmount)), bankKeeper.GetSupplyOffset(ctx, sdk.DefaultBondDenom)) }) } } @@ -475,7 +475,7 @@ func (suite *KeeperTestSuite) TestDistributeToModule() { ctx := suite.Ctx // Setup. - suite.NoError(mintKeeper.MintCoins(ctx, sdk.NewCoins(tc.preMintCoin))) + suite.Require().NoError(mintKeeper.MintCoins(ctx, sdk.NewCoins(tc.preMintCoin))) // TODO: Should not be truncated. Remove truncation after rounding errors are addressed and resolved. // Ref: https://github.com/osmosis-labs/osmosis/issues/1917 @@ -491,20 +491,20 @@ func (suite *KeeperTestSuite) TestDistributeToModule() { actualRecepientModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(tc.recepientModule), tc.mintedCoin.Denom).Amount if tc.expectedError { - suite.Error(err) - suite.Equal(actualDistributed, sdk.Int{}) + suite.Require().Error(err) + suite.Require().Equal(actualDistributed, sdk.Int{}) // Old balances should not change. - suite.Equal(oldMintModuleBalanceAmount.Int64(), actualMintModuleBalanceAmount.Int64()) - suite.Equal(oldRecepientModuleBalanceAmount.Int64(), actualRecepientModuleBalanceAmount.Int64()) + suite.Require().Equal(oldMintModuleBalanceAmount.Int64(), actualMintModuleBalanceAmount.Int64()) + suite.Require().Equal(oldRecepientModuleBalanceAmount.Int64(), actualRecepientModuleBalanceAmount.Int64()) return } - suite.NoError(err) - suite.Equal(expectedDistributed, actualDistributed) + suite.Require().NoError(err) + suite.Require().Equal(expectedDistributed, actualDistributed) // Updated balances. - suite.Equal(oldMintModuleBalanceAmount.Sub(actualDistributed).Int64(), actualMintModuleBalanceAmount.Int64()) - suite.Equal(oldRecepientModuleBalanceAmount.Add(actualDistributed).Int64(), actualRecepientModuleBalanceAmount.Int64()) + suite.Require().Equal(oldMintModuleBalanceAmount.Sub(actualDistributed).Int64(), actualMintModuleBalanceAmount.Int64()) + suite.Require().Equal(oldRecepientModuleBalanceAmount.Add(actualDistributed).Int64(), actualRecepientModuleBalanceAmount.Int64()) }) }) } @@ -711,7 +711,7 @@ func (suite *KeeperTestSuite) TestDistributeDeveloperRewards() { ctx := suite.Ctx // Setup. - suite.NoError(mintKeeper.MintCoins(ctx, sdk.NewCoins(tc.preMintCoin))) + suite.Require().NoError(mintKeeper.MintCoins(ctx, sdk.NewCoins(tc.preMintCoin))) // TODO: Should not be truncated. Remove truncation after rounding errors are addressed and resolved. // Ref: https://github.com/osmosis-labs/osmosis/issues/1917 @@ -740,39 +740,39 @@ func (suite *KeeperTestSuite) TestDistributeDeveloperRewards() { actualCommunityPoolModuleBalanceAmount := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(distributiontypes.ModuleName), tc.mintedCoin.Denom).Amount if tc.expectedError != nil { - suite.Error(err) - suite.Equal(tc.expectedError.Error(), err.Error()) - suite.Equal(actualDistributed, sdk.Int{}) + suite.Require().Error(err) + suite.Require().Equal(tc.expectedError.Error(), err.Error()) + suite.Require().Equal(actualDistributed, sdk.Int{}) // See testcases with this flag set to true for details. if tc.allowBalanceChange { return } // Old balances should not change. - suite.Equal(oldMintModuleBalanceAmount.Int64(), actualMintModuleBalance.Amount.Int64()) - suite.Equal(oldDeveloperVestingModuleBalanceAmount.Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) - suite.Equal(oldCommunityPoolBalanceAmount.Int64(), actualCommunityPoolModuleBalanceAmount.Int64()) + suite.Require().Equal(oldMintModuleBalanceAmount.Int64(), actualMintModuleBalance.Amount.Int64()) + suite.Require().Equal(oldDeveloperVestingModuleBalanceAmount.Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) + suite.Require().Equal(oldCommunityPoolBalanceAmount.Int64(), actualCommunityPoolModuleBalanceAmount.Int64()) return } - suite.NoError(err) - suite.Equal(expectedDistributed, actualDistributed) + suite.Require().NoError(err) + suite.Require().Equal(expectedDistributed, actualDistributed) // Updated balances. // Burn from mint module account. We over-allocate. // To be fixed: https://github.com/osmosis-labs/osmosis/issues/2025 - suite.Equal(oldMintModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualMintModuleBalance.Amount.Int64()) + suite.Require().Equal(oldMintModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualMintModuleBalance.Amount.Int64()) // Allocate to community pool when no addresses are provided. if len(tc.recepientAddresses) == 0 { - suite.Equal(oldDeveloperVestingModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) - suite.Equal(oldCommunityPoolBalanceAmount.Add(expectedDistributed).Int64(), actualCommunityPoolModuleBalanceAmount.Int64()) + suite.Require().Equal(oldDeveloperVestingModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) + suite.Require().Equal(oldCommunityPoolBalanceAmount.Add(expectedDistributed).Int64(), actualCommunityPoolModuleBalanceAmount.Int64()) return } // TODO: these should be equal, slightly off due to known rounding issues: https://github.com/osmosis-labs/osmosis/issues/1917 - // suite.Equal(oldDeveloperVestingModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) + // suite.Require().Equal(oldDeveloperVestingModuleBalanceAmount.Sub(expectedDistributed).Int64(), actualDeveloperVestingModuleBalanceAmount.Int64()) expectedDistributedCommunityPool := sdk.NewInt(0) @@ -786,20 +786,20 @@ func (suite *KeeperTestSuite) TestDistributeDeveloperRewards() { } address, err := sdk.AccAddressFromBech32(weightedAddress.Address) - suite.NoError(err) + suite.Require().NoError(err) actualDeveloperRewardsBalanceAmounts := bankKeeper.GetBalance(ctx, address, tc.mintedCoin.Denom).Amount // Edge case. See testcases with this flag set to true for details. if tc.expectSameAddresses { - suite.Equal(oldDeveloperRewardsBalanceAmounts[i].Add(expectedAllocation.Mul(sdk.NewInt(2))).Int64(), actualDeveloperRewardsBalanceAmounts.Int64()) + suite.Require().Equal(oldDeveloperRewardsBalanceAmounts[i].Add(expectedAllocation.Mul(sdk.NewInt(2))).Int64(), actualDeveloperRewardsBalanceAmounts.Int64()) return } - suite.Equal(oldDeveloperRewardsBalanceAmounts[i].Add(expectedAllocation).Int64(), actualDeveloperRewardsBalanceAmounts.Int64()) + suite.Require().Equal(oldDeveloperRewardsBalanceAmounts[i].Add(expectedAllocation).Int64(), actualDeveloperRewardsBalanceAmounts.Int64()) } - suite.Equal(oldCommunityPoolBalanceAmount.Add(expectedDistributedCommunityPool).Int64(), actualCommunityPoolModuleBalanceAmount.Int64()) + suite.Require().Equal(oldCommunityPoolBalanceAmount.Add(expectedDistributedCommunityPool).Int64(), actualCommunityPoolModuleBalanceAmount.Int64()) }) }) } From 84dce39240e19cb3c3f8c126de66bbe069998d78 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Tue, 19 Jul 2022 20:50:22 -0500 Subject: [PATCH 110/376] simulator: frequency management (#2156) * simulator weight management * Move action selection out of executor into types * linter changes * Update simulation/simtypes/weight.go Co-authored-by: Roman * change from Roman review Co-authored-by: Roman --- simulation/executor/operation.go | 32 ---------------- simulation/executor/simulate.go | 2 +- simulation/simtypes/action.go | 66 +++++++++++++++++++++++--------- simulation/simtypes/frequency.go | 40 +++++++++++++++++++ simulation/simtypes/weight.go | 11 ------ x/gamm/module.go | 2 +- 6 files changed, 89 insertions(+), 64 deletions(-) create mode 100644 simulation/simtypes/frequency.go delete mode 100644 simulation/simtypes/weight.go diff --git a/simulation/executor/operation.go b/simulation/executor/operation.go index 353ff0b2c7c..741efbe7a33 100644 --- a/simulation/executor/operation.go +++ b/simulation/executor/operation.go @@ -4,11 +4,8 @@ package simulation import ( "encoding/json" - "math/rand" "github.com/cosmos/cosmos-sdk/types/simulation" - - "github.com/osmosis-labs/osmosis/v10/simulation/simtypes" ) // entry kinds for use within OperationEntry @@ -91,32 +88,3 @@ func (simState *simState) queueOperations(futureOps []simulation.FutureOperation } } } - -func totalWeight(actions []simtypes.Action) int { - totalWeight := 0 - for _, action := range actions { - totalWeight += int(action.Weight()) - } - - return totalWeight -} - -type selectActionFn func(r *rand.Rand) simtypes.Action - -func getSelectActionFn(actions []simtypes.Action) selectActionFn { - totalOpWeight := totalWeight(actions) - - return func(r *rand.Rand) simtypes.Action { - x := r.Intn(totalOpWeight) - // TODO: Change to an accum list approach - for i := 0; i < len(actions); i++ { - if x <= int(actions[i].Weight()) { - return actions[i] - } - - x -= int(actions[i].Weight()) - } - // shouldn't happen - return actions[0] - } -} diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index b7f626a24b7..ee1c466717d 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -210,7 +210,7 @@ func createBlockSimulator(testingMode bool, w io.Writer, params Params, actions ) blockSimFn { lastBlockSizeState := 0 // state for [4 * uniform distribution] blocksize := 0 - selectAction := getSelectActionFn(actions) + selectAction := simtypes.GetSelectActionFn(actions) return func( simCtx *simtypes.SimCtx, ctx sdk.Context, header tmproto.Header, diff --git a/simulation/simtypes/action.go b/simulation/simtypes/action.go index f747f12a2e7..c7bee9d64ec 100644 --- a/simulation/simtypes/action.go +++ b/simulation/simtypes/action.go @@ -2,6 +2,7 @@ package simtypes import ( "fmt" + "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/simulation" @@ -11,29 +12,33 @@ import ( // Action represents a simulator action. // The details of this struct are internal, -// we currently plan on maintaining 3 constructors for it. -// * ActionFromWeightedOperation - for legacy simulator compatibility -// * ActionFromMsg - An easy API to go from creating a message via simctx to something simulator can deal with -// * ActionFromDependentMessages - API for defining a series of messages that depend on one another, and should satisfy -// some properties post-execution. +// we currently plan on maintaining 2 constructors for it. +// * weightedOperationAction - for legacy simulator compatibility +// * msgBasedAction - An easy API to go from creating a message via simctx to something simulator can deal with type Action interface { Name() string - // I envision this weight being provided from a config. + // I envision this frequency being provided from a config. // Module providers can optionally provide a default from an enum, // but this should not be the default. - // TODO: Maybe we make a "WithWeight" fn? - Weight() Weight + Frequency() Frequency Execute(*SimCtx, sdk.Context) ( OperationMsg simulation.OperationMsg, futureOps []simulation.FutureOperation, err error) + WithFrequency(w Frequency) Action } +type selectActionFn func(r *rand.Rand) Action + type weightedOperationAction struct { moduleName string + frequency Frequency op simulation.WeightedOperation } -func (a weightedOperationAction) Name() string { return fmt.Sprintf("%s: weighted_op", a.moduleName) } -func (a weightedOperationAction) Weight() Weight { return Weight(a.op.Weight()) } +func (a weightedOperationAction) WithFrequency(w Frequency) Action { a.frequency = w; return a } +func (a weightedOperationAction) Name() string { return fmt.Sprintf("%s: weighted_op", a.moduleName) } +func (a weightedOperationAction) Frequency() Frequency { + return Frequency(mapFrequencyFromInt(a.op.Weight())) +} func (a weightedOperationAction) Execute(sim *SimCtx, ctx sdk.Context) ( simulation.OperationMsg, []simulation.FutureOperation, error, ) { @@ -62,7 +67,7 @@ func NewKeeperlessMsgBasedAction[M sdk.Msg](actionName string, msgGenerator func // TODO: Also do we even want this? Isn't the goal to write simulation event hooks based on Name // var sampleMsg M // msgName := osmoutils.GetType(sampleMsg) - return msgBasedAction{name: actionName, weight: Normal, msgGenerator: wrappedMsgGen} + return msgBasedAction{name: actionName, frequency: Common, msgGenerator: wrappedMsgGen} } func CurryMsgGenerator[K interface{}, M sdk.Msg](k K, f func(K, *SimCtx, sdk.Context) (M, error)) func(*SimCtx, sdk.Context) (M, error) { @@ -81,17 +86,13 @@ func NewMsgBasedAction[K interface{}, M sdk.Msg](actionName string, k K, f func( type msgBasedAction struct { name string - weight Weight + frequency Frequency msgGenerator func(sim *SimCtx, ctx sdk.Context) (sdk.Msg, error) } -func (m msgBasedAction) WithWeight(weight Weight) msgBasedAction { - m.weight = weight - return m -} - -func (m msgBasedAction) Name() string { return m.name } -func (m msgBasedAction) Weight() Weight { return m.weight } +func (m msgBasedAction) WithFrequency(w Frequency) Action { m.frequency = w; return m } +func (m msgBasedAction) Name() string { return m.name } +func (m msgBasedAction) Frequency() Frequency { return m.frequency } func (m msgBasedAction) Execute(sim *SimCtx, ctx sdk.Context) ( OperationMsg simulation.OperationMsg, futureOps []simulation.FutureOperation, err error, ) { @@ -105,3 +106,30 @@ func (m msgBasedAction) Execute(sim *SimCtx, ctx sdk.Context) ( } return sim.deliverTx(tx, msg, m.name) } + +func totalFrequency(actions []Action) int { + totalFrequency := 0 + for _, action := range actions { + totalFrequency += mapFrequencyFromString(action.Frequency()) + } + + return totalFrequency +} + +func GetSelectActionFn(actions []Action) selectActionFn { + totalOpFrequency := totalFrequency(actions) + + return func(r *rand.Rand) Action { + x := r.Intn(totalOpFrequency) + // TODO: Change to an accum list approach + for i := 0; i < len(actions); i++ { + if x <= mapFrequencyFromString(actions[i].Frequency()) { + return actions[i] + } + + x -= mapFrequencyFromString(actions[i].Frequency()) + } + // shouldn't happen + return actions[0] + } +} diff --git a/simulation/simtypes/frequency.go b/simulation/simtypes/frequency.go new file mode 100644 index 00000000000..3884224a789 --- /dev/null +++ b/simulation/simtypes/frequency.go @@ -0,0 +1,40 @@ +package simtypes + +type Frequency string + +const ( + Rare = "Rare" + Infrequent = "Infrequent" + Common = "Common" + Frequent = "Frequent" +) + +func mapFrequencyFromInt(intFrequency int) string { + switch { + case intFrequency < 10: + return Rare + case intFrequency > 10 && intFrequency < 20: + return Infrequent + case intFrequency > 20 && intFrequency < 50: + return Common + case intFrequency > 50: + return Frequent + default: + return Common + } +} + +func mapFrequencyFromString(strFrequency Frequency) int { + switch strFrequency { + case Rare: + return 5 + case Infrequent: + return 15 + case Common: + return 35 + case Frequent: + return 65 + default: + return 35 + } +} diff --git a/simulation/simtypes/weight.go b/simulation/simtypes/weight.go deleted file mode 100644 index 48a90443f01..00000000000 --- a/simulation/simtypes/weight.go +++ /dev/null @@ -1,11 +0,0 @@ -package simtypes - -type Weight int64 - -const ( - Undefined Weight = 0 - Rare = 1 - Infrequent = 5 - Normal = 10 - Frequent = 20 -) diff --git a/x/gamm/module.go b/x/gamm/module.go index 1c46041a41f..1f5fba040b3 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -180,6 +180,6 @@ func (am AppModule) Actions() []simtypes.Action { return []simtypes.Action{ simtypes.NewMsgBasedAction("MsgJoinPool", am.keeper, simulation.RandomJoinPoolMsg), simtypes.NewMsgBasedAction("MsgExitPool", am.keeper, simulation.RandomExitPoolMsg), - simtypes.NewMsgBasedAction("CreateUniV2Msg", am.keeper, simulation.RandomCreateUniV2Msg), + simtypes.NewMsgBasedAction("CreateUniV2Msg", am.keeper, simulation.RandomCreateUniV2Msg).WithFrequency(simtypes.Rare), } } From 03504abd385c554c0562374c792ce5db47ec0e3f Mon Sep 17 00:00:00 2001 From: Roman Date: Wed, 20 Jul 2022 20:10:00 -0400 Subject: [PATCH 111/376] refactor(mint): remove unused context parameter from getProportions (#2162) Closes: #XXX ## What is the purpose of the change The context parameter in `getProportions` is unused. Removed the unused parameter. ## Documentation and Release Note - Does this pull request introduce a new feature or user-facing behavior changes? no - Is a relevant changelog entry added to the `Unreleased` section in `CHANGELOG.md`? no - How is the feature or change documented? not applicable --- x/mint/keeper/hooks_test.go | 12 ++++++------ x/mint/keeper/keeper.go | 8 ++++---- x/mint/keeper/keeper_test.go | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index e26c959a26b..65a70d9c1e2 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -50,7 +50,7 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { mintParams = app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking) + expectedRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.Staking) suite.Require().NoError(err) expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) @@ -67,7 +67,7 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewards, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) + expectedDevRewards, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.DeveloperRewards) suite.Require().NoError(err) suite.Require().Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) } @@ -88,7 +88,7 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { mintParams = app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking) + expectedRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.Staking) suite.Require().NoError(err) expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) @@ -98,7 +98,7 @@ func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { // test that the balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) + expectedDevRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.DeveloperRewards) suite.Require().NoError(err) suite.Require().Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) } @@ -126,7 +126,7 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp mintParams := app.MintKeeper.GetParams(ctx) mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.Staking.Add(mintParams.DistributionProportions.DeveloperRewards)) + expectedRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.Staking.Add(mintParams.DistributionProportions.DeveloperRewards)) suite.Require().NoError(err) expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) @@ -136,7 +136,7 @@ func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmp // test that the dev rewards module account balance decreased by the correct amount devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewardsCoin, err := keeper.GetProportions(ctx, mintedCoin, mintParams.DistributionProportions.DeveloperRewards) + expectedDevRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.DeveloperRewards) suite.Require().NoError(err) suite.Require().Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) } diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index e0e8579459a..c407e328341 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -236,7 +236,7 @@ func (k Keeper) DistributeMintedCoin(ctx sdk.Context, mintedCoin sdk.Coin) error // distributeToModule distributes mintedCoin multiplied by proportion to the recepientModule account. func (k Keeper) distributeToModule(ctx sdk.Context, recipientModule string, mintedCoin sdk.Coin, proportion sdk.Dec) (sdk.Int, error) { - distributionCoin, err := getProportions(ctx, mintedCoin, proportion) + distributionCoin, err := getProportions(mintedCoin, proportion) if err != nil { return sdk.Int{}, err } @@ -262,7 +262,7 @@ func (k Keeper) distributeToModule(ctx sdk.Context, recipientModule string, mint // - weights in developerRewardsReceivers add up to 1. // - addresses in developerRewardsReceivers are valid or empty string. func (k Keeper) distributeDeveloperRewards(ctx sdk.Context, totalMintedCoin sdk.Coin, developerRewardsProportion sdk.Dec, developerRewardsReceivers []types.WeightedAddress) (sdk.Int, error) { - devRewardCoin, err := getProportions(ctx, totalMintedCoin, developerRewardsProportion) + devRewardCoin, err := getProportions(totalMintedCoin, developerRewardsProportion) if err != nil { return sdk.Int{}, err } @@ -294,7 +294,7 @@ func (k Keeper) distributeDeveloperRewards(ctx sdk.Context, totalMintedCoin sdk. } else { // allocate developer rewards to addresses by weight for _, w := range developerRewardsReceivers { - devPortionCoin, err := getProportions(ctx, devRewardCoin, w.Weight) + devPortionCoin, err := getProportions(devRewardCoin, w.Weight) if err != nil { return sdk.Int{}, err } @@ -332,7 +332,7 @@ func (k Keeper) distributeDeveloperRewards(ctx sdk.Context, totalMintedCoin sdk. // allocation ratio. Returns error if ratio is greater than 1. // TODO: this currently rounds down and is the cause of rounding discrepancies. // To be fixed in: https://github.com/osmosis-labs/osmosis/issues/1917 -func getProportions(ctx sdk.Context, mintedCoin sdk.Coin, ratio sdk.Dec) (sdk.Coin, error) { +func getProportions(mintedCoin sdk.Coin, ratio sdk.Dec) (sdk.Coin, error) { if ratio.GT(sdk.OneDec()) { return sdk.Coin{}, invalidRatioError{ratio} } diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 6beac4e4c58..1e4f4085bd0 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -133,7 +133,7 @@ func (suite *KeeperTestSuite) TestGetProportions() { for _, tc := range tests { suite.Run(tc.name, func() { - coin, err := keeper.GetProportions(suite.Ctx, tc.mintedCoin, tc.ratio) + coin, err := keeper.GetProportions(tc.mintedCoin, tc.ratio) if tc.expectedError != nil { suite.Require().Equal(tc.expectedError, err) From 7160374fbab5c6ff7fef34ea92c7b2b2aa0278c2 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Wed, 20 Jul 2022 19:39:01 -0500 Subject: [PATCH 112/376] simulator: prevent locking zero tokens (#2172) * prevent locking zero tokens * change to Dev's suggestion * Update simulation/simtypes/action.go Co-authored-by: Dev Ojha * add acc fee check for tokenfactory creation * Update sim_msgs.go * Update sim_msgs.go * add RandomSimAccountWithMinCoins Co-authored-by: Dev Ojha --- simulation/simtypes/account.go | 11 +++++++++++ simulation/simtypes/action.go | 4 ++++ x/tokenfactory/simulation/sim_msgs.go | 6 +++++- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/simulation/simtypes/account.go b/simulation/simtypes/account.go index 45c5b8c1555..80c3d1c7931 100644 --- a/simulation/simtypes/account.go +++ b/simulation/simtypes/account.go @@ -39,6 +39,17 @@ func (sim *SimCtx) RandomSimAccountWithConstraint(f SimAccountConstraint) (simul return sim.randomSimAccount(filteredAddrs), true } +func (sim *SimCtx) RandomSimAccountWithMinCoins(ctx sdk.Context, denom string, amount int64) (simulation.Account, error) { + accHasMinCoins := func(acc simulation.Account) bool { + return sim.BankKeeper().GetBalance(ctx, acc.Address, denom).IsGTE(sdk.NewCoin(denom, sdk.NewInt(amount))) + } + acc, found := sim.RandomSimAccountWithConstraint(accHasMinCoins) + if !found { + return simulation.Account{}, errors.New("no address with min balance found.") + } + return acc, nil +} + func (sim *SimCtx) RandomExistingAddress() sdk.AccAddress { acc := sim.RandomSimAccount() return acc.Address diff --git a/simulation/simtypes/action.go b/simulation/simtypes/action.go index c7bee9d64ec..a0118e3a17d 100644 --- a/simulation/simtypes/action.go +++ b/simulation/simtypes/action.go @@ -100,6 +100,10 @@ func (m msgBasedAction) Execute(sim *SimCtx, ctx sdk.Context) ( if err != nil { return simulation.NoOpMsg(m.name, m.name, fmt.Sprintf("unable to build msg due to: %v", err)), nil, nil } + err = msg.ValidateBasic() + if err != nil { + return simulation.NoOpMsg(m.name, m.name, fmt.Sprintf("msg did not pass ValidateBasic: %v", err)), nil, nil + } tx, err := sim.txbuilder(ctx, msg, m.name) if err != nil { return simulation.NoOpMsg(m.name, m.name, fmt.Sprintf("unable to build tx due to: %v", err)), nil, err diff --git a/x/tokenfactory/simulation/sim_msgs.go b/x/tokenfactory/simulation/sim_msgs.go index e7563d9a278..3310362f9d7 100644 --- a/x/tokenfactory/simulation/sim_msgs.go +++ b/x/tokenfactory/simulation/sim_msgs.go @@ -15,8 +15,12 @@ import ( // RandomMsgCreateDenom creates a random tokenfactory denom that is no greater than 44 alphanumeric characters func RandomMsgCreateDenom(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgCreateDenom, error) { + acc, err := sim.RandomSimAccountWithMinCoins(ctx, "stake", 10_000_000) + if err != nil { + return nil, err + } return &types.MsgCreateDenom{ - Sender: sim.RandomSimAccount().Address.String(), + Sender: acc.Address.String(), Subdenom: sim.RandStringOfLength(types.MaxSubdenomLength), }, nil } From 4970f165f439ad43c8a188e056b4ad69f54aebb4 Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 21 Jul 2022 16:40:42 -0400 Subject: [PATCH 113/376] test(x/gamm): add liquidity event tests (#2141) * test(gamm): add liquidity events * Apply suggestions from code review * Update x/gamm/keeper/msg_server_test.go Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> Co-authored-by: Matt, Park <45252226+mattverse@users.noreply.github.com> --- x/gamm/keeper/internal/events/emit_test.go | 54 +++++++++++++++ x/gamm/keeper/msg_server.go | 4 -- x/gamm/keeper/msg_server_test.go | 76 +++++++++++++++++++++- x/gamm/keeper/pool_service_test.go | 19 ++++-- x/gamm/spec/README.md | 18 ++++- 5 files changed, 159 insertions(+), 12 deletions(-) diff --git a/x/gamm/keeper/internal/events/emit_test.go b/x/gamm/keeper/internal/events/emit_test.go index eac138c0e1a..6f17918a976 100644 --- a/x/gamm/keeper/internal/events/emit_test.go +++ b/x/gamm/keeper/internal/events/emit_test.go @@ -85,3 +85,57 @@ func (suite *GammEventsTestSuite) TestEmitSwapEvent() { }) } } + +func (suite *GammEventsTestSuite) TestEmitAddLiquidityEvent() { + testcases := map[string]struct { + ctx sdk.Context + testAccountAddr sdk.AccAddress + poolId uint64 + tokensIn sdk.Coins + }{ + "basic valid": { + ctx: suite.CreateTestContext(), + testAccountAddr: sdk.AccAddress([]byte(addressString)), + poolId: 1, + tokensIn: sdk.NewCoins(sdk.NewCoin(testDenomA, sdk.NewInt(1234))), + }, + "context with no event manager": { + ctx: sdk.Context{}, + }, + "valid with multiple tokens in": { + ctx: suite.CreateTestContext(), + testAccountAddr: sdk.AccAddress([]byte(addressString)), + poolId: 200, + tokensIn: sdk.NewCoins(sdk.NewCoin(testDenomA, sdk.NewInt(12)), sdk.NewCoin(testDenomB, sdk.NewInt(99))), + }, + } + + for name, tc := range testcases { + suite.Run(name, func() { + expectedEvents := sdk.Events{ + sdk.NewEvent( + types.TypeEvtPoolJoined, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeySender, tc.testAccountAddr.String()), + sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(tc.poolId, 10)), + sdk.NewAttribute(types.AttributeKeyTokensIn, tc.tokensIn.String()), + ), + } + + hasNoEventManager := tc.ctx.EventManager() == nil + + // System under test. + events.EmitAddLiquidityEvent(tc.ctx, tc.testAccountAddr, tc.poolId, tc.tokensIn) + + // Assertions + if hasNoEventManager { + // If there is no event manager on context, this is a no-op. + return + } + + eventManager := tc.ctx.EventManager() + actualEvents := eventManager.Events() + suite.Equal(expectedEvents, actualEvents) + }) + } +} diff --git a/x/gamm/keeper/msg_server.go b/x/gamm/keeper/msg_server.go index 9c44f97bdd1..e58ba23334d 100644 --- a/x/gamm/keeper/msg_server.go +++ b/x/gamm/keeper/msg_server.go @@ -118,10 +118,6 @@ func (server msgServer) JoinPool(goCtx context.Context, msg *types.MsgJoinPool) } ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.TypeEvtPoolJoined, - sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(msg.PoolId, 10)), - ), sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), diff --git a/x/gamm/keeper/msg_server_test.go b/x/gamm/keeper/msg_server_test.go index a52251162e2..1920adc8fd8 100644 --- a/x/gamm/keeper/msg_server_test.go +++ b/x/gamm/keeper/msg_server_test.go @@ -1,6 +1,8 @@ package keeper_test import ( + "testing" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" @@ -12,7 +14,9 @@ const ( doesNotExistDenom = "nodenom" ) -var _ = suite.TestingSuite(nil) +func TestMsgServerTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} // TestSwapExactAmountIn_Events tests that events are correctly emitted // when calling SwapExactAmountIn. @@ -213,6 +217,74 @@ func (suite *KeeperTestSuite) TestSwapExactAmountOut_Events() { } } +// TestJoinPool_Events tests that events are correctly emitted +// when calling JoinPool. +func (suite *KeeperTestSuite) TestJoinPool_Events() { + const ( + // Max positive int64. + tokenInMaxAmount = int64(^uint64(0) >> 1) + shareOut = 110 + ) + + testcases := map[string]struct { + poolId uint64 + shareOutAmount sdk.Int + tokenInMaxs sdk.Coins + expectError bool + expectedAddLiquidityEvents int + expectedMessageEvents int + }{ + "successful join": { + poolId: 1, + shareOutAmount: sdk.NewInt(shareOut), + tokenInMaxs: sdk.NewCoins( + sdk.NewCoin("foo", sdk.NewInt(tokenInMaxAmount)), + sdk.NewCoin("bar", sdk.NewInt(tokenInMaxAmount)), + sdk.NewCoin("baz", sdk.NewInt(tokenInMaxAmount)), + ), + expectedAddLiquidityEvents: 1, + expectedMessageEvents: 3, // 1 gamm + 2 tendermint. + }, + "tokenInMaxs do not match all tokens in pool - invalid join": { + poolId: 1, + shareOutAmount: sdk.NewInt(shareOut), + tokenInMaxs: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(tokenInMaxAmount))), + expectError: true, + }, + } + + for name, tc := range testcases { + suite.Run(name, func() { + suite.Setup() + ctx := suite.Ctx + + suite.PrepareBalancerPool() + suite.PrepareBalancerPool() + + msgServer := keeper.NewMsgServerImpl(suite.App.GAMMKeeper) + + // Reset event counts to 0 by creating a new manager. + ctx = ctx.WithEventManager(sdk.NewEventManager()) + suite.Require().Equal(0, len(ctx.EventManager().Events())) + + response, err := msgServer.JoinPool(sdk.WrapSDKContext(ctx), &types.MsgJoinPool{ + Sender: suite.TestAccs[0].String(), + PoolId: tc.poolId, + ShareOutAmount: tc.shareOutAmount, + TokenInMaxs: tc.tokenInMaxs, + }) + + if !tc.expectError { + suite.Require().NoError(err) + suite.Require().NotNil(response) + } + + assertEventEmitted(suite, ctx, types.TypeEvtPoolJoined, tc.expectedAddLiquidityEvents) + assertEventEmitted(suite, ctx, sdk.EventTypeMessage, tc.expectedMessageEvents) + }) + } +} + func assertEventEmitted(suite *KeeperTestSuite, ctx sdk.Context, eventTypeExpected string, numEventsExpected int) { allEvents := ctx.EventManager().Events() // filter out other events @@ -222,5 +294,5 @@ func assertEventEmitted(suite *KeeperTestSuite, ctx sdk.Context, eventTypeExpect actualEvents = append(actualEvents, event) } } - suite.Equal(numEventsExpected, len(actualEvents)) + suite.Require().Equal(numEventsExpected, len(actualEvents)) } diff --git a/x/gamm/keeper/pool_service_test.go b/x/gamm/keeper/pool_service_test.go index 9201d44d094..7ceaaeb09ba 100644 --- a/x/gamm/keeper/pool_service_test.go +++ b/x/gamm/keeper/pool_service_test.go @@ -377,6 +377,7 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { for _, test := range tests { suite.SetupTest() + ctx := suite.Ctx keeper := suite.App.GAMMKeeper // Mint some assets to the accounts. @@ -407,8 +408,12 @@ func (suite *KeeperTestSuite) TestJoinPoolNoSwap() { liquidity := suite.App.GAMMKeeper.GetTotalLiquidity(suite.Ctx) suite.Require().Equal("15000bar,15000foo", liquidity.String()) + + assertEventEmitted(suite, ctx, types.TypeEvtPoolJoined, 1) } else { suite.Require().Error(err, "test: %v", test.name) + + assertEventEmitted(suite, ctx, types.TypeEvtPoolJoined, 0) } } } @@ -566,6 +571,8 @@ func (suite *KeeperTestSuite) TestJoinPoolExitPool_InverseRelationship() { suite.SetupTest() suite.Run(tc.name, func() { + ctx := suite.Ctx + for _, acc := range suite.TestAccs { suite.FundAcc(acc, defaultAcctFunds) } @@ -576,17 +583,19 @@ func (suite *KeeperTestSuite) TestJoinPoolExitPool_InverseRelationship() { // test account is set on every test case iteration, we need to manually update address for pool creator tc.pool.Sender = createPoolAcc.String() - poolId, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, tc.pool) + poolId, err := suite.App.GAMMKeeper.CreatePool(ctx, tc.pool) suite.Require().NoError(err) - balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) + balanceBeforeJoin := suite.App.BankKeeper.GetAllBalances(ctx, joinPoolAcc) - _, _, err = suite.App.GAMMKeeper.JoinPoolNoSwap(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) + _, _, err = suite.App.GAMMKeeper.JoinPoolNoSwap(ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) suite.Require().NoError(err) - _, err = suite.App.GAMMKeeper.ExitPool(suite.Ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) + assertEventEmitted(suite, ctx, types.TypeEvtPoolJoined, 1) + + _, err = suite.App.GAMMKeeper.ExitPool(ctx, joinPoolAcc, poolId, tc.joinPoolShareAmt, sdk.Coins{}) - balanceAfterExit := suite.App.BankKeeper.GetAllBalances(suite.Ctx, joinPoolAcc) + balanceAfterExit := suite.App.BankKeeper.GetAllBalances(ctx, joinPoolAcc) deltaBalance, _ := balanceBeforeJoin.SafeSub(balanceAfterExit) // due to rounding, `balanceBeforeJoin` and `balanceAfterExit` have neglectable difference diff --git a/x/gamm/spec/README.md b/x/gamm/spec/README.md index a986d7f355a..1163a412d53 100644 --- a/x/gamm/spec/README.md +++ b/x/gamm/spec/README.md @@ -956,7 +956,7 @@ osmosisd tx gamm swap-exact-amount-out 1000000ibc/27394FB092D2ECCD56123C74F36E4C ## Events -There are 4 types of events that exist in GAMM: +There are 5 types of events that exist in GAMM: * `sdk.EventTypeMessage` - "message" * `types.TypeEvtPoolJoined` - "pool_joined" @@ -970,6 +970,22 @@ This event is emitted in the message server when any of the gamm messages finish TBD +### `types.TypeEvtPoolJoined` + +This event is emitted after one of `JoinPool` or `JoinPoolNoSwap` complete joining +the requested pool successfully. + +It consists of the following attributes: + +* `sdk.AttributeKeyModule` - "module" + * The value is the module's name - "gamm". +* `sdk.AttributeKeySender` + * The value is the address of the sender who created the swap message. +* `types.AttributeKeyPoolId` + * The value is the pool id of the pool where swap occurs. +* `types.AttributeKeyTokensIn` + * The value is the string representation of the tokens being swapped in. + ### `types.TypeEvtPoolExited` TBD From e1223ad3419053fc4d65ac43940e25dd23342df5 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Thu, 21 Jul 2022 20:25:27 -0500 Subject: [PATCH 114/376] chore(deps): bump sdk fork to v0.45.0x-osmo-v11-alpha.2 (#2185) * bump to v11-rc2 tag * use osmosis-main for fork * Update go.mod * Update go.mod --- go.mod | 4 ++-- go.sum | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index c1db08ff788..90d352d59a5 100644 --- a/go.mod +++ b/go.mod @@ -285,8 +285,8 @@ require ( replace ( // branch: v0.27.0.rc3-osmo, current tag: v0.27.0.rc3-osmo github.com/CosmWasm/wasmd => github.com/osmosis-labs/wasmd v0.27.0-rc2.0.20220517191021-59051aa18d58 - // Our cosmos-sdk branch is: https://github.com/osmosis-labs/cosmos-sdk osmosis-main, current tag: v0.45.0x-osmo-v11.rc1 - github.com/cosmos/cosmos-sdk => github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220714223138-b81ad24550fa + // Our cosmos-sdk branch is: https://github.com/osmosis-labs/cosmos-sdk, current tag: v0.45.0x-osmo-v11-alpha.2, current branch: osmosis-main + github.com/cosmos/cosmos-sdk => github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220721082708-0aca1df58871 // Use Osmosis fast iavl github.com/cosmos/iavl => github.com/osmosis-labs/iavl v0.17.3-osmo-v7 // use cosmos-compatible protobufs diff --git a/go.sum b/go.sum index 2a4b4b59fb5..03f473f5bef 100644 --- a/go.sum +++ b/go.sum @@ -1042,8 +1042,8 @@ github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4 github.com/ory/dockertest v3.3.5+incompatible/go.mod h1:1vX4m9wsvi00u5bseYwXaSnhNrne+V0E6LAcBILJdPs= github.com/ory/dockertest/v3 v3.9.1 h1:v4dkG+dlu76goxMiTT2j8zV7s4oPPEppKT8K8p2f1kY= github.com/ory/dockertest/v3 v3.9.1/go.mod h1:42Ir9hmvaAPm0Mgibk6mBPi7SFvTXxEcnztDYOJ//uM= -github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220714223138-b81ad24550fa h1:XN0dDQx8Lq3+/eCNRlT/rjUTcpDavLFfTYiVwvmFhL0= -github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220714223138-b81ad24550fa/go.mod h1:uUkGXyCWol+CHoaMxZA0nKglvlN5uHBCMbMSsZoGSAs= +github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220721082708-0aca1df58871 h1:VkQCYrUg8xpUOoDRP7pBcQi8ceqvxC75SBkDAKFFh3g= +github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220721082708-0aca1df58871/go.mod h1:uUkGXyCWol+CHoaMxZA0nKglvlN5uHBCMbMSsZoGSAs= github.com/osmosis-labs/iavl v0.17.3-osmo-v7 h1:6KcADC/WhL7yDmNQxUIJt2XmzNt4FfRmq9gRke45w74= github.com/osmosis-labs/iavl v0.17.3-osmo-v7/go.mod h1:lJEOIlsd3sVO0JDyXWIXa9/Ur5FBscP26zJx0KxHjto= github.com/osmosis-labs/wasmd v0.27.0-rc2.0.20220517191021-59051aa18d58 h1:15l3Iss2oCGCeJRi2g3CuCnqmEjpAr3Le7cDnoN/LS0= From e69e260ed878db03d9a5724458072a7fb96db69b Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Thu, 21 Jul 2022 22:39:50 -0500 Subject: [PATCH 115/376] TWAP proto, types package, and osmoutils (#2175) * Extract osmoutils, proto & types from main TWAP PR * Delete merge conflict * Add TestGetAllUniqueDenomPairs * Resolve more comments * Fix incorrect pool interface (but was a no-op) * Apply suggestions from code review Co-authored-by: Aleksandr Bezobchuk * apply review comment * Make NewTwapRecord return an error Co-authored-by: Aleksandr Bezobchuk --- osmoutils/iter_helper.go | 14 - osmoutils/slice_helper.go | 12 + osmoutils/store_helper.go | 97 ++ osmoutils/time_helper.go | 20 + .../gamm/twap/v1beta1/twap_record.proto | 63 ++ x/gamm/twap/types/expected_interfaces.go | 16 + x/gamm/twap/types/keys.go | 86 +- x/gamm/twap/types/keys_test.go | 92 ++ x/gamm/twap/types/twap_record.pb.go | 905 ++++++++++++++++++ x/gamm/twap/types/utils.go | 82 ++ x/gamm/twap/types/utils_test.go | 34 + 11 files changed, 1406 insertions(+), 15 deletions(-) delete mode 100644 osmoutils/iter_helper.go create mode 100644 osmoutils/store_helper.go create mode 100644 osmoutils/time_helper.go create mode 100644 proto/osmosis/gamm/twap/v1beta1/twap_record.proto create mode 100644 x/gamm/twap/types/expected_interfaces.go create mode 100644 x/gamm/twap/types/keys_test.go create mode 100644 x/gamm/twap/types/twap_record.pb.go create mode 100644 x/gamm/twap/types/utils.go create mode 100644 x/gamm/twap/types/utils_test.go diff --git a/osmoutils/iter_helper.go b/osmoutils/iter_helper.go deleted file mode 100644 index 2f8a48abd03..00000000000 --- a/osmoutils/iter_helper.go +++ /dev/null @@ -1,14 +0,0 @@ -package osmoutils - -import "github.com/cosmos/cosmos-sdk/store" - -func GatherAllKeysFromStore(storeObj store.KVStore) []string { - iterator := storeObj.Iterator(nil, nil) - defer iterator.Close() - - keys := []string{} - for ; iterator.Valid(); iterator.Next() { - keys = append(keys, string(iterator.Key())) - } - return keys -} diff --git a/osmoutils/slice_helper.go b/osmoutils/slice_helper.go index 1128789c19a..2dc10c87603 100644 --- a/osmoutils/slice_helper.go +++ b/osmoutils/slice_helper.go @@ -7,6 +7,7 @@ import ( ) // SortSlice sorts a slice of type T elements that implement constraints.Ordered. +// Mutates input slice s func SortSlice[T constraints.Ordered](s []T) { sort.Slice(s, func(i, j int) bool { return s[i] < s[j] @@ -22,3 +23,14 @@ func Filter[T interface{}](filter func(T) bool, s []T) []T { } return filteredSlice } + +// ReverseSlice returns a reversed copy of the input slice. +// Does not mutate argument. +func ReverseSlice[T any](s []T) []T { + newSlice := make([]T, len(s)) + maxIndex := len(s) - 1 + for i := 0; i < len(s); i++ { + newSlice[maxIndex-i] = s[i] + } + return newSlice +} diff --git a/osmoutils/store_helper.go b/osmoutils/store_helper.go new file mode 100644 index 00000000000..029900ec877 --- /dev/null +++ b/osmoutils/store_helper.go @@ -0,0 +1,97 @@ +package osmoutils + +import ( + "errors" + + "github.com/cosmos/cosmos-sdk/store" + "github.com/gogo/protobuf/proto" +) + +func GatherAllKeysFromStore(storeObj store.KVStore) []string { + iterator := storeObj.Iterator(nil, nil) + defer iterator.Close() + + keys := []string{} + for ; iterator.Valid(); iterator.Next() { + keys = append(keys, string(iterator.Key())) + } + return keys +} + +func GatherValuesFromStore[T any](storeObj store.KVStore, keyStart []byte, keyEnd []byte, parseValue func([]byte) (T, error)) ([]T, error) { + iterator := storeObj.Iterator(keyStart, keyEnd) + defer iterator.Close() + + values := []T{} + for ; iterator.Valid(); iterator.Next() { + val, err := parseValue(iterator.Value()) + if err != nil { + return nil, err + } + values = append(values, val) + } + return values, nil +} + +func GetValuesUntilDerivedStop[T any](storeObj store.KVStore, keyStart []byte, stopFn func([]byte) bool, parseValue func([]byte) (T, error)) ([]T, error) { + // SDK iterator is broken for nil end time, and non-nil start time + // https://github.com/cosmos/cosmos-sdk/issues/12661 + // hence we use []byte{0xff} + keyEnd := []byte{0xff} + return GetIterValuesWithStop(storeObj, keyStart, keyEnd, false, stopFn, parseValue) +} + +func GetIterValuesWithStop[T any]( + storeObj store.KVStore, + keyStart []byte, + keyEnd []byte, + reverse bool, + stopFn func([]byte) bool, + parseValue func([]byte) (T, error)) ([]T, error) { + var iter store.Iterator + if reverse { + iter = storeObj.ReverseIterator(keyStart, keyEnd) + } else { + iter = storeObj.Iterator(keyStart, keyEnd) + } + defer iter.Close() + + values := []T{} + for ; iter.Valid(); iter.Next() { + if stopFn(iter.Key()) { + break + } + val, err := parseValue(iter.Value()) + if err != nil { + return nil, err + } + values = append(values, val) + } + return values, nil +} + +func GetFirstValueAfterPrefix[T any](storeObj store.KVStore, keyStart []byte, parseValue func([]byte) (T, error)) (T, error) { + // SDK iterator is broken for nil end time, and non-nil start time + // https://github.com/cosmos/cosmos-sdk/issues/12661 + // hence we use []byte{0xff} + iterator := storeObj.Iterator(keyStart, []byte{0xff}) + defer iterator.Close() + + if !iterator.Valid() { + var blankValue T + return blankValue, errors.New("No values in iterator") + } + + return parseValue(iterator.Value()) +} + +// MustSet runs store.Set(key, proto.Marshal(value)) +// but panics on any error. +func MustSet(storeObj store.KVStore, key []byte, value proto.Message) { + bz, err := proto.Marshal(value) + if err != nil { + panic(err) + } + + storeObj.Set(key, bz) +} diff --git a/osmoutils/time_helper.go b/osmoutils/time_helper.go new file mode 100644 index 00000000000..05571fa73ea --- /dev/null +++ b/osmoutils/time_helper.go @@ -0,0 +1,20 @@ +package osmoutils + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func FormatTimeString(t time.Time) string { + return t.UTC().Round(0).Format(sdk.SortableTimeFormat) +} + +// Parses a string encoded using FormatTimeString back into a time.Time +func ParseTimeString(s string) (time.Time, error) { + t, err := time.Parse(sdk.SortableTimeFormat, s) + if err != nil { + return t, err + } + return t.UTC().Round(0), nil +} diff --git a/proto/osmosis/gamm/twap/v1beta1/twap_record.proto b/proto/osmosis/gamm/twap/v1beta1/twap_record.proto new file mode 100644 index 00000000000..b6685529668 --- /dev/null +++ b/proto/osmosis/gamm/twap/v1beta1/twap_record.proto @@ -0,0 +1,63 @@ +syntax = "proto3"; +package osmosis.gamm.twap.v1beta1; + +import "gogoproto/gogo.proto"; +import "google/protobuf/any.proto"; +import "cosmos_proto/cosmos.proto"; +import "cosmos/base/v1beta1/coin.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types"; + +// A TWAP record should be indexed in state by pool_id, (asset pair), timestamp +// The asset pair assets should be lexicographically sorted. +// Technically (pool_id, asset_0_denom, asset_1_denom, height) do not need to +// appear in the struct however we view this as the wrong performance tradeoff +// given SDK today. Would rather we optimize for readability and correctness, +// than an optimal state storage format. The system bottleneck is elsewhere for +// now. +message TwapRecord { + uint64 pool_id = 1; + // Lexicographically smaller denom of the pair + string asset0_denom = 2; + // Lexicographically larger denom of the pair + string asset1_denom = 3; + // height this record corresponds to, for debugging purposes + int64 height = 4 [ + (gogoproto.moretags) = "yaml:\"record_height\"", + (gogoproto.jsontag) = "record_height" + ]; + // This field should only exist until we have a global registry in the state + // machine, mapping prior block heights within {TIME RANGE} to times. + google.protobuf.Timestamp time = 5 [ + (gogoproto.nullable) = false, + (gogoproto.stdtime) = true, + (gogoproto.moretags) = "yaml:\"record_time\"" + ]; + + // We store the last spot prices in the struct, so that we can interpolate + // accumulator values for times between when accumulator records are stored. + string p0_last_spot_price = 6 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + string p1_last_spot_price = 7 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + + string p0_arithmetic_twap_accumulator = 8 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + string p1_arithmetic_twap_accumulator = 9 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + // string geometric_twap_accumulator = 7 [(gogoproto.customtype) = + // "github.com/cosmos/cosmos-sdk/types.Dec", + // (gogoproto.nullable) = false]; +} + +// GenesisState defines the gamm module's genesis state. +message GenesisState { repeated TwapRecord twaps = 1; } diff --git a/x/gamm/twap/types/expected_interfaces.go b/x/gamm/twap/types/expected_interfaces.go new file mode 100644 index 00000000000..0af93f75285 --- /dev/null +++ b/x/gamm/twap/types/expected_interfaces.go @@ -0,0 +1,16 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// AmmInterface is the functionality needed from a given pool ID, in order to maintain records and serve TWAPs. +type AmmInterface interface { + GetPoolDenoms(ctx sdk.Context, poolId uint64) (denoms []string, err error) + // CalculateSpotPrice returns the spot price of the quote asset in terms of the base asset, + // using the specified pool. + // E.g. if pool 1 traded 2 atom for 3 osmo, the quote asset was atom, and the base asset was osmo, + // this would return 1.5. (Meaning that 1 atom costs 1.5 osmo) + CalculateSpotPrice(ctx sdk.Context, + poolID uint64, + baseAssetDenom string, + quoteAssetDenom string) (price sdk.Dec, err error) +} diff --git a/x/gamm/twap/types/keys.go b/x/gamm/twap/types/keys.go index 5020db04d7c..32d683cf615 100644 --- a/x/gamm/twap/types/keys.go +++ b/x/gamm/twap/types/keys.go @@ -1,5 +1,17 @@ package types +import ( + "errors" + fmt "fmt" + "strings" + time "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/gogo/protobuf/proto" + + "github.com/osmosis-labs/osmosis/v10/osmoutils" +) + const ( ModuleName = "twap" @@ -8,6 +20,78 @@ const ( RouterKey = ModuleName QuerierRoute = ModuleName + // Contract: Coin denoms cannot contain this character + KeySeparator = "|" ) -var AlteredPoolIdsPrefix = []byte{0} +var ( + mostRecentTWAPsNoSeparator = "recent_twap" + historicalTWAPTimeIndexNoSeparator = "historical_time_index" + historicalTWAPPoolIndexNoSeparator = "historical_pool_index" + + mostRecentTWAPsPrefix = mostRecentTWAPsNoSeparator + KeySeparator + historicalTWAPTimeIndexPrefix = historicalTWAPTimeIndexNoSeparator + KeySeparator + historicalTWAPPoolIndexPrefix = historicalTWAPPoolIndexNoSeparator + KeySeparator +) + +// TODO: make utility command to automatically interlace separators + +func FormatMostRecentTWAPKey(poolId uint64, denom1, denom2 string) []byte { + return []byte(fmt.Sprintf("%s%d%s%s%s%s", mostRecentTWAPsPrefix, poolId, KeySeparator, denom1, KeySeparator, denom2)) +} + +// TODO: Replace historical management with ORM, we currently accept 2x write amplification right now. +func FormatHistoricalTimeIndexTWAPKey(accumulatorWriteTime time.Time, poolId uint64, denom1, denom2 string) []byte { + timeS := osmoutils.FormatTimeString(accumulatorWriteTime) + return []byte(fmt.Sprintf("%s%s%s%d%s%s%s%s", historicalTWAPTimeIndexPrefix, timeS, KeySeparator, poolId, KeySeparator, denom1, KeySeparator, denom2)) +} + +func FormatHistoricalPoolIndexTWAPKey(poolId uint64, accumulatorWriteTime time.Time, denom1, denom2 string) []byte { + timeS := osmoutils.FormatTimeString(accumulatorWriteTime) + return []byte(fmt.Sprintf("%s%d%s%s%s%s%s%s", historicalTWAPPoolIndexPrefix, poolId, KeySeparator, timeS, KeySeparator, denom1, KeySeparator, denom2)) +} + +func FormatHistoricalPoolIndexTimePrefix(poolId uint64, accumulatorWriteTime time.Time) []byte { + timeS := osmoutils.FormatTimeString(accumulatorWriteTime) + return []byte(fmt.Sprintf("%s%d%s%s%s", historicalTWAPPoolIndexPrefix, poolId, KeySeparator, timeS, KeySeparator)) +} + +func ParseTimeFromHistoricalTimeIndexKey(key []byte) time.Time { + keyS := string(key) + s := strings.Split(keyS, KeySeparator) + if len(s) != 5 || s[0] != historicalTWAPTimeIndexNoSeparator { + panic("Called ParseTimeFromHistoricalTimeIndexKey on incorrectly formatted key") + } + t, err := osmoutils.ParseTimeString(s[1]) + if err != nil { + panic("incorrectly formatted time string in key") + } + return t +} + +func ParseTimeFromHistoricalPoolIndexKey(key []byte) (time.Time, error) { + keyS := string(key) + s := strings.Split(keyS, KeySeparator) + if len(s) != 5 || s[0] != historicalTWAPPoolIndexNoSeparator { + return time.Time{}, fmt.Errorf("Called ParseTimeFromHistoricalPoolIndexKey on incorrectly formatted key: %v", s) + } + t, err := osmoutils.ParseTimeString(s[2]) + if err != nil { + return time.Time{}, fmt.Errorf("incorrectly formatted time string in key %s : %v", keyS, err) + } + return t, nil +} + +func GetAllMostRecentTwapsForPool(store sdk.KVStore, poolId uint64) ([]TwapRecord, error) { + startPrefix := fmt.Sprintf("%s%s%d%s", mostRecentTWAPsPrefix, KeySeparator, poolId, KeySeparator) + endPrefix := fmt.Sprintf("%s%s%d%s", mostRecentTWAPsPrefix, KeySeparator, poolId+1, KeySeparator) + return osmoutils.GatherValuesFromStore(store, []byte(startPrefix), []byte(endPrefix), ParseTwapFromBz) +} + +func ParseTwapFromBz(bz []byte) (twap TwapRecord, err error) { + if len(bz) == 0 { + return TwapRecord{}, errors.New("twap not found") + } + err = proto.Unmarshal(bz, &twap) + return twap, err +} diff --git a/x/gamm/twap/types/keys_test.go b/x/gamm/twap/types/keys_test.go new file mode 100644 index 00000000000..13fc334c5b0 --- /dev/null +++ b/x/gamm/twap/types/keys_test.go @@ -0,0 +1,92 @@ +package types + +import ( + "strings" + "testing" + time "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/require" +) + +func TestFormatMostRecentTWAPKey(t *testing.T) { + tests := map[string]struct { + poolId uint64 + denom1 string + denom2 string + want string + }{ + "standard": {poolId: 1, denom1: "B", denom2: "A", want: "recent_twap|1|B|A"}, + "standard2digit": {poolId: 10, denom1: "B", denom2: "A", want: "recent_twap|10|B|A"}, + "maxPoolId": {poolId: ^uint64(0), denom1: "B", denom2: "A", want: "recent_twap|18446744073709551615|B|A"}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + got := FormatMostRecentTWAPKey(tt.poolId, tt.denom1, tt.denom2) + require.Equal(t, tt.want, string(got)) + }) + } +} + +func TestFormatHistoricalTwapKeys(t *testing.T) { + // go playground default time + // 2009-11-10 23:00:00 +0000 UTC m=+0.000000001 + baseTime := time.Unix(1257894000, 0).UTC() + tests := map[string]struct { + poolId uint64 + time time.Time + denom1 string + denom2 string + wantPoolIndex string + wantTimeIndex string + }{ + "standard": {poolId: 1, time: baseTime, denom1: "B", denom2: "A", wantTimeIndex: "historical_time_index|2009-11-10T23:00:00.000000000|1|B|A", wantPoolIndex: "historical_pool_index|1|2009-11-10T23:00:00.000000000|B|A"}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + gotTimeKey := FormatHistoricalTimeIndexTWAPKey(tt.time, tt.poolId, tt.denom1, tt.denom2) + gotPoolKey := FormatHistoricalPoolIndexTWAPKey(tt.poolId, tt.time, tt.denom1, tt.denom2) + require.Equal(t, tt.wantTimeIndex, string(gotTimeKey)) + require.Equal(t, tt.wantPoolIndex, string(gotPoolKey)) + + parsedTime := ParseTimeFromHistoricalTimeIndexKey(gotTimeKey) + require.Equal(t, tt.time, parsedTime) + parsedTime, err := ParseTimeFromHistoricalPoolIndexKey(gotPoolKey) + require.Equal(t, tt.time, parsedTime) + require.NoError(t, err) + + poolIndexPrefix := FormatHistoricalPoolIndexTimePrefix(tt.poolId, tt.time) + require.True(t, strings.HasPrefix(string(gotPoolKey), string(poolIndexPrefix))) + }) + } +} + +func TestParseTwapFromBz(t *testing.T) { + baseTime := time.Unix(1257894000, 0).UTC() + tests := map[string]struct { + record TwapRecord + }{ + "standard": {TwapRecord{ + PoolId: 123, + Asset0Denom: "B", + Asset1Denom: "A", + Height: 1, + Time: baseTime, + P0LastSpotPrice: sdk.NewDecWithPrec(1, 5), + P1LastSpotPrice: sdk.NewDecWithPrec(2, 5), // inconsistent value + P0ArithmeticTwapAccumulator: sdk.ZeroDec(), + P1ArithmeticTwapAccumulator: sdk.ZeroDec(), + }}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + bz, err := proto.Marshal(&tt.record) + require.NoError(t, err) + record, err := ParseTwapFromBz(bz) + require.NoError(t, err) + + require.Equal(t, tt.record, record) + }) + } +} diff --git a/x/gamm/twap/types/twap_record.pb.go b/x/gamm/twap/types/twap_record.pb.go new file mode 100644 index 00000000000..c29041b23e0 --- /dev/null +++ b/x/gamm/twap/types/twap_record.pb.go @@ -0,0 +1,905 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: osmosis/gamm/twap/v1beta1/twap_record.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/codec/types" + _ "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" + _ "github.com/gogo/protobuf/types" + github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" + io "io" + math "math" + math_bits "math/bits" + time "time" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// A TWAP record should be indexed in state by pool_id, (asset pair), timestamp +// The asset pair assets should be lexicographically sorted. +// Technically (pool_id, asset_0_denom, asset_1_denom, height) do not need to +// appear in the struct however we view this as the wrong performance tradeoff +// given SDK today. Would rather we optimize for readability and correctness, +// than an optimal state storage format. The system bottleneck is elsewhere for +// now. +type TwapRecord struct { + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + // Lexicographically smaller denom of the pair + Asset0Denom string `protobuf:"bytes,2,opt,name=asset0_denom,json=asset0Denom,proto3" json:"asset0_denom,omitempty"` + // Lexicographically larger denom of the pair + Asset1Denom string `protobuf:"bytes,3,opt,name=asset1_denom,json=asset1Denom,proto3" json:"asset1_denom,omitempty"` + // height this record corresponds to, for debugging purposes + Height int64 `protobuf:"varint,4,opt,name=height,proto3" json:"record_height" yaml:"record_height"` + // This field should only exist until we have a global registry in the state + // machine, mapping prior block heights within {TIME RANGE} to times. + Time time.Time `protobuf:"bytes,5,opt,name=time,proto3,stdtime" json:"time" yaml:"record_time"` + // We store the last spot prices in the struct, so that we can interpolate + // accumulator values for times between when accumulator records are stored. + P0LastSpotPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=p0_last_spot_price,json=p0LastSpotPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"p0_last_spot_price"` + P1LastSpotPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=p1_last_spot_price,json=p1LastSpotPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"p1_last_spot_price"` + P0ArithmeticTwapAccumulator github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,8,opt,name=p0_arithmetic_twap_accumulator,json=p0ArithmeticTwapAccumulator,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"p0_arithmetic_twap_accumulator"` + P1ArithmeticTwapAccumulator github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,9,opt,name=p1_arithmetic_twap_accumulator,json=p1ArithmeticTwapAccumulator,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"p1_arithmetic_twap_accumulator"` +} + +func (m *TwapRecord) Reset() { *m = TwapRecord{} } +func (m *TwapRecord) String() string { return proto.CompactTextString(m) } +func (*TwapRecord) ProtoMessage() {} +func (*TwapRecord) Descriptor() ([]byte, []int) { + return fileDescriptor_a81e54bd4e35cf12, []int{0} +} +func (m *TwapRecord) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *TwapRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_TwapRecord.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 *TwapRecord) XXX_Merge(src proto.Message) { + xxx_messageInfo_TwapRecord.Merge(m, src) +} +func (m *TwapRecord) XXX_Size() int { + return m.Size() +} +func (m *TwapRecord) XXX_DiscardUnknown() { + xxx_messageInfo_TwapRecord.DiscardUnknown(m) +} + +var xxx_messageInfo_TwapRecord proto.InternalMessageInfo + +func (m *TwapRecord) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *TwapRecord) GetAsset0Denom() string { + if m != nil { + return m.Asset0Denom + } + return "" +} + +func (m *TwapRecord) GetAsset1Denom() string { + if m != nil { + return m.Asset1Denom + } + return "" +} + +func (m *TwapRecord) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *TwapRecord) GetTime() time.Time { + if m != nil { + return m.Time + } + return time.Time{} +} + +// GenesisState defines the gamm module's genesis state. +type GenesisState struct { + Twaps []*TwapRecord `protobuf:"bytes,1,rep,name=twaps,proto3" json:"twaps,omitempty"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_a81e54bd4e35cf12, []int{1} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.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 *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetTwaps() []*TwapRecord { + if m != nil { + return m.Twaps + } + return nil +} + +func init() { + proto.RegisterType((*TwapRecord)(nil), "osmosis.gamm.twap.v1beta1.TwapRecord") + proto.RegisterType((*GenesisState)(nil), "osmosis.gamm.twap.v1beta1.GenesisState") +} + +func init() { + proto.RegisterFile("osmosis/gamm/twap/v1beta1/twap_record.proto", fileDescriptor_a81e54bd4e35cf12) +} + +var fileDescriptor_a81e54bd4e35cf12 = []byte{ + // 535 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x93, 0x4f, 0x6f, 0xd3, 0x3e, + 0x18, 0xc7, 0x9b, 0x5f, 0xff, 0xec, 0x37, 0x77, 0x08, 0x29, 0x9a, 0x44, 0x56, 0xa4, 0xa4, 0x54, + 0x02, 0x15, 0xa1, 0x39, 0xc9, 0x10, 0x17, 0x38, 0xb5, 0x9a, 0x84, 0x10, 0x08, 0x50, 0xb6, 0x13, + 0x1c, 0x22, 0x27, 0x35, 0xa9, 0x45, 0x5c, 0x5b, 0xb1, 0xbb, 0xd1, 0x77, 0xb1, 0xd7, 0xc0, 0xab, + 0xd9, 0x71, 0x47, 0xc4, 0x21, 0xa0, 0xf6, 0xc6, 0x71, 0xaf, 0x00, 0xd9, 0x4e, 0xbb, 0x16, 0x34, + 0x0e, 0x3d, 0x25, 0x8f, 0x9f, 0xef, 0xf3, 0xf9, 0x3e, 0x8f, 0xf5, 0x18, 0x3c, 0x61, 0x82, 0x32, + 0x41, 0x84, 0x9f, 0x21, 0x4a, 0x7d, 0x79, 0x8e, 0xb8, 0x7f, 0x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 0xbe, 0xbb, 0x9c, 0xbb, 0xd6, 0xd5, 0xdc, + 0xb5, 0x7e, 0xce, 0x5d, 0xeb, 0x62, 0xe1, 0xd6, 0xae, 0x16, 0x6e, 0xed, 0xdb, 0xc2, 0xad, 0x7d, + 0x78, 0xb6, 0xd6, 0x6b, 0x45, 0x3c, 0xcc, 0x51, 0x22, 0x96, 0x81, 0x7f, 0x16, 0x06, 0xfe, 0x97, + 0xb5, 0xe7, 0xaf, 0xdb, 0x4f, 0x5a, 0x7a, 0xf7, 0x9e, 0xfe, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x31, + 0x20, 0x99, 0x21, 0x20, 0x04, 0x00, 0x00, +} + +func (m *TwapRecord) 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 *TwapRecord) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TwapRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.P1ArithmeticTwapAccumulator.Size() + i -= size + if _, err := m.P1ArithmeticTwapAccumulator.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTwapRecord(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x4a + { + size := m.P0ArithmeticTwapAccumulator.Size() + i -= size + if _, err := m.P0ArithmeticTwapAccumulator.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTwapRecord(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + { + size := m.P1LastSpotPrice.Size() + i -= size + if _, err := m.P1LastSpotPrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTwapRecord(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + { + size := m.P0LastSpotPrice.Size() + i -= size + if _, err := m.P0LastSpotPrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTwapRecord(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + n1, err1 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Time):]) + if err1 != nil { + return 0, err1 + } + i -= n1 + i = encodeVarintTwapRecord(dAtA, i, uint64(n1)) + i-- + dAtA[i] = 0x2a + if m.Height != 0 { + i = encodeVarintTwapRecord(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x20 + } + if len(m.Asset1Denom) > 0 { + i -= len(m.Asset1Denom) + copy(dAtA[i:], m.Asset1Denom) + i = encodeVarintTwapRecord(dAtA, i, uint64(len(m.Asset1Denom))) + i-- + dAtA[i] = 0x1a + } + if len(m.Asset0Denom) > 0 { + i -= len(m.Asset0Denom) + copy(dAtA[i:], m.Asset0Denom) + i = encodeVarintTwapRecord(dAtA, i, uint64(len(m.Asset0Denom))) + i-- + dAtA[i] = 0x12 + } + if m.PoolId != 0 { + i = encodeVarintTwapRecord(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *GenesisState) 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 *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Twaps) > 0 { + for iNdEx := len(m.Twaps) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Twaps[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTwapRecord(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintTwapRecord(dAtA []byte, offset int, v uint64) int { + offset -= sovTwapRecord(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *TwapRecord) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovTwapRecord(uint64(m.PoolId)) + } + l = len(m.Asset0Denom) + if l > 0 { + n += 1 + l + sovTwapRecord(uint64(l)) + } + l = len(m.Asset1Denom) + if l > 0 { + n += 1 + l + sovTwapRecord(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovTwapRecord(uint64(m.Height)) + } + l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Time) + n += 1 + l + sovTwapRecord(uint64(l)) + l = m.P0LastSpotPrice.Size() + n += 1 + l + sovTwapRecord(uint64(l)) + l = m.P1LastSpotPrice.Size() + n += 1 + l + sovTwapRecord(uint64(l)) + l = m.P0ArithmeticTwapAccumulator.Size() + n += 1 + l + sovTwapRecord(uint64(l)) + l = m.P1ArithmeticTwapAccumulator.Size() + n += 1 + l + sovTwapRecord(uint64(l)) + return n +} + +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Twaps) > 0 { + for _, e := range m.Twaps { + l = e.Size() + n += 1 + l + sovTwapRecord(uint64(l)) + } + } + return n +} + +func sovTwapRecord(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTwapRecord(x uint64) (n int) { + return sovTwapRecord(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *TwapRecord) 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 ErrIntOverflowTwapRecord + } + 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: TwapRecord: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TwapRecord: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Asset0Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + 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 ErrInvalidLengthTwapRecord + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTwapRecord + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Asset0Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Asset1Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + 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 ErrInvalidLengthTwapRecord + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTwapRecord + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Asset1Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTwapRecord + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTwapRecord + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field P0LastSpotPrice", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + 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 ErrInvalidLengthTwapRecord + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTwapRecord + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.P0LastSpotPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field P1LastSpotPrice", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + 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 ErrInvalidLengthTwapRecord + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTwapRecord + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.P1LastSpotPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field P0ArithmeticTwapAccumulator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + 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 ErrInvalidLengthTwapRecord + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTwapRecord + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.P0ArithmeticTwapAccumulator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field P1ArithmeticTwapAccumulator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + 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 ErrInvalidLengthTwapRecord + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTwapRecord + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.P1ArithmeticTwapAccumulator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTwapRecord(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTwapRecord + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GenesisState) 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 ErrIntOverflowTwapRecord + } + 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: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Twaps", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTwapRecord + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTwapRecord + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTwapRecord + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Twaps = append(m.Twaps, &TwapRecord{}) + if err := m.Twaps[len(m.Twaps)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTwapRecord(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTwapRecord + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTwapRecord(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTwapRecord + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTwapRecord + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTwapRecord + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTwapRecord + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTwapRecord + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTwapRecord + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTwapRecord = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTwapRecord = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTwapRecord = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/gamm/twap/types/utils.go b/x/gamm/twap/types/utils.go new file mode 100644 index 00000000000..ff62cc13f8b --- /dev/null +++ b/x/gamm/twap/types/utils.go @@ -0,0 +1,82 @@ +package types + +import ( + fmt "fmt" + "sort" + time "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/osmosis-labs/osmosis/v10/osmoutils" +) + +func NewTwapRecord(k AmmInterface, ctx sdk.Context, poolId uint64, denom0 string, denom1 string) (TwapRecord, error) { + if !(denom0 > denom1) { + return TwapRecord{}, fmt.Errorf("precondition denom0 > denom1 not satisfied. denom0 %s | denom1 %s", denom0, denom1) + } + sp0 := MustGetSpotPrice(k, ctx, poolId, denom0, denom1) + sp1 := MustGetSpotPrice(k, ctx, poolId, denom1, denom0) + return TwapRecord{ + PoolId: poolId, + Asset0Denom: denom0, + Asset1Denom: denom1, + Height: ctx.BlockHeight(), + Time: ctx.BlockTime(), + P0LastSpotPrice: sp0, + P1LastSpotPrice: sp1, + P0ArithmeticTwapAccumulator: sdk.ZeroDec(), + P1ArithmeticTwapAccumulator: sdk.ZeroDec(), + }, nil +} + +// mustGetSpotPrice returns the spot price for the given pool id, and denom0 in terms of denom1. +// Panics if the pool state is misconfigured, which will halt any tx that interacts with this. +func MustGetSpotPrice(k AmmInterface, ctx sdk.Context, poolId uint64, baseAssetDenom string, quoteAssetDenom string) sdk.Dec { + sp, err := k.CalculateSpotPrice(ctx, poolId, baseAssetDenom, quoteAssetDenom) + if err != nil { + panic(err) + } + return sp +} + +// GetAllUniqueDenomPairs returns all unique pairs of denoms, where for every pair +// (X, Y), X >= Y. +// The pair (X,Y) should only appear once in the list +// +// NOTE: Sorts the input denoms slice. +func GetAllUniqueDenomPairs(denoms []string) ([]string, []string) { + // get denoms in descending order + sort.Strings(denoms) + reverseDenoms := osmoutils.ReverseSlice(denoms) + + numPairs := len(denoms) * (len(denoms) - 1) / 2 + pairGT := make([]string, 0, numPairs) + pairLT := make([]string, 0, numPairs) + + for i := 0; i < len(reverseDenoms); i++ { + for j := i + 1; j < len(reverseDenoms); j++ { + pairGT = append(pairGT, reverseDenoms[i]) + pairLT = append(pairLT, reverseDenoms[j]) + } + } + // sanity check + for i := 0; i < numPairs; i++ { + if pairGT[i] == pairLT[i] { + panic("input had duplicated denom") + } + } + return pairGT, pairLT +} + +func SpotPriceTimesDuration(sp sdk.Dec, timeDelta time.Duration) sdk.Dec { + return sp.MulInt64(int64(timeDelta)) +} + +func AccumDiffDivDuration(accumDiff sdk.Dec, timeDelta time.Duration) sdk.Dec { + return accumDiff.QuoInt64(int64(timeDelta)) +} + +// TODO +func (g *GenesisState) Validate() error { + return nil +} diff --git a/x/gamm/twap/types/utils_test.go b/x/gamm/twap/types/utils_test.go new file mode 100644 index 00000000000..6d700d57dc0 --- /dev/null +++ b/x/gamm/twap/types/utils_test.go @@ -0,0 +1,34 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/osmosis-labs/osmosis/v10/osmoutils" +) + +func TestGetAllUniqueDenomPairs(t *testing.T) { + tests := map[string]struct { + denoms []string + wantedPairGT []string + wantedPairLT []string + panics bool + }{ + "basic": {[]string{"A", "B"}, []string{"B"}, []string{"A"}, false}, + "basicRev": {[]string{"B", "A"}, []string{"B"}, []string{"A"}, false}, + // AB > A + "prefixed": {[]string{"A", "AB"}, []string{"AB"}, []string{"A"}, false}, + "basic-3": {[]string{"A", "B", "C"}, []string{"C", "C", "B"}, []string{"B", "A", "A"}, false}, + "panics": {[]string{"A", "A"}, []string{}, []string{}, true}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + osmoutils.ConditionalPanic(t, tt.panics, func() { + pairGT, pairLT := GetAllUniqueDenomPairs(tt.denoms) + require.Equal(t, pairGT, tt.wantedPairGT) + require.Equal(t, pairLT, tt.wantedPairLT) + }) + }) + } +} From 8d86c7027591df852f9824215f40a171c4b53d0a Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Fri, 22 Jul 2022 08:52:22 -0500 Subject: [PATCH 116/376] fix: check coins are positive in lockup ValidateBasic (#2180) * add check to lockup validate basic * add table driven test for ValidateBasic * Update msgs_test.go --- x/lockup/types/msgs.go | 10 ++++ x/lockup/types/msgs_test.go | 104 ++++++++++++++++++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 x/lockup/types/msgs_test.go diff --git a/x/lockup/types/msgs.go b/x/lockup/types/msgs.go index fab3cac197f..bbbce794244 100644 --- a/x/lockup/types/msgs.go +++ b/x/lockup/types/msgs.go @@ -5,6 +5,7 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) // constants. @@ -29,6 +30,11 @@ func NewMsgLockTokens(owner sdk.AccAddress, duration time.Duration, coins sdk.Co func (m MsgLockTokens) Route() string { return RouterKey } func (m MsgLockTokens) Type() string { return TypeMsgLockTokens } func (m MsgLockTokens) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Owner) + if err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid owner address (%s)", err) + } + if m.Duration <= 0 { return fmt.Errorf("duration should be positive: %d < 0", m.Duration) } @@ -38,6 +44,10 @@ func (m MsgLockTokens) ValidateBasic() error { return fmt.Errorf("lockups can only have one denom per lock ID, got %v", m.Coins) } + if !m.Coins.IsAllPositive() { + return fmt.Errorf("cannot lock up a zero or negative amount") + } + return nil } diff --git a/x/lockup/types/msgs_test.go b/x/lockup/types/msgs_test.go new file mode 100644 index 00000000000..8dd16cb3fd1 --- /dev/null +++ b/x/lockup/types/msgs_test.go @@ -0,0 +1,104 @@ +package types + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + sdk "github.com/cosmos/cosmos-sdk/types" + + appParams "github.com/osmosis-labs/osmosis/v10/app/params" +) + +func TestMsgLockTokens(t *testing.T) { + appParams.SetAddressPrefixes() + pk1 := ed25519.GenPrivKey().PubKey() + addr1 := sdk.AccAddress(pk1.Address()).String() + invalidAddr := sdk.AccAddress("invalid") + + createMsg := func(after func(msg MsgLockTokens) MsgLockTokens) MsgLockTokens { + properMsg := MsgLockTokens{ + Owner: addr1, + Duration: time.Hour, + Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(100))), + } + + return after(properMsg) + } + + msg := createMsg(func(msg MsgLockTokens) MsgLockTokens { + // Do nothing + return msg + }) + + require.Equal(t, msg.Route(), RouterKey) + require.Equal(t, msg.Type(), "lock_tokens") + signers := msg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1) + + tests := []struct { + name string + msg MsgLockTokens + expectPass bool + }{ + { + name: "proper msg", + msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { + // Do nothing + return msg + }), + expectPass: true, + }, + { + name: "invalid owner", + msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { + msg.Owner = invalidAddr.String() + return msg + }), + expectPass: false, + }, + { + name: "invalid duration", + msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { + msg.Duration = -1 + return msg + }), + expectPass: false, + }, + { + name: "invalid coin length", + msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { + msg.Coins = sdk.NewCoins(sdk.NewCoin("test1", sdk.NewInt(100000)), sdk.NewCoin("test2", sdk.NewInt(100000))) + return msg + }), + expectPass: false, + }, + { + name: "zero token amount", + msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { + msg.Coins = sdk.NewCoins(sdk.NewCoin("test1", sdk.NewInt(0))) + return msg + }), + expectPass: false, + }, + } + + for _, test := range tests { + if test.expectPass { + require.NoError(t, test.msg.ValidateBasic(), "test: %v", test.name) + } else { + require.Error(t, test.msg.ValidateBasic(), "test: %v", test.name) + } + } +} + +// TODO: Complete table driven tests for the remaining messages + +// MsgBeginUnlockingAll + +// MsgBeginUnlocking + +// MsgExtendLockup From 9ec7c1bbf12ad52fcb04731e50041637dd6dc6d9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 22 Jul 2022 09:33:11 -0500 Subject: [PATCH 117/376] chore(deps): Bump github.com/golangci/golangci-lint (#2188) Bumps [github.com/golangci/golangci-lint](https://github.com/golangci/golangci-lint) from 1.47.1 to 1.47.2. - [Release notes](https://github.com/golangci/golangci-lint/releases) - [Changelog](https://github.com/golangci/golangci-lint/blob/master/CHANGELOG.md) - [Commits](https://github.com/golangci/golangci-lint/compare/v1.47.1...v1.47.2) --- updated-dependencies: - dependency-name: github.com/golangci/golangci-lint dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 90d352d59a5..6fba47841e0 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/cosmos/ibc-go/v3 v3.0.0 github.com/gogo/protobuf v1.3.3 github.com/golang/protobuf v1.5.2 - github.com/golangci/golangci-lint v1.47.1 + github.com/golangci/golangci-lint v1.47.2 github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/ory/dockertest/v3 v3.9.1 diff --git a/go.sum b/go.sum index 03f473f5bef..4d61864a186 100644 --- a/go.sum +++ b/go.sum @@ -541,8 +541,8 @@ github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe h1:6RGUuS7EGotKx6 github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe/go.mod h1:gjqyPShc/m8pEMpk0a3SeagVb0kaqvhscv+i9jI5ZhQ= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a h1:iR3fYXUjHCR97qWS8ch1y9zPNsgXThGwjKPrYfqMPks= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= -github.com/golangci/golangci-lint v1.47.1 h1:hbubHskV2Ppwz4ZZE2lc0/Pw9ZhqLuzm2dT7ZVpLA6Y= -github.com/golangci/golangci-lint v1.47.1/go.mod h1:lpS2pjBZtRyXewUcOY7yUL3K4KfpoWz072yRN8AuhHg= +github.com/golangci/golangci-lint v1.47.2 h1:qvMDVv49Hrx3PSEXZ0bD/yhwSbhsOihQjFYCKieegIw= +github.com/golangci/golangci-lint v1.47.2/go.mod h1:lpS2pjBZtRyXewUcOY7yUL3K4KfpoWz072yRN8AuhHg= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 h1:MfyDlzVjl1hoaPzPD4Gpb/QgoRfSBR0jdhwGyAWwMSA= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0/go.mod h1:66R6K6P6VWk9I95jvqGxkqJxVWGFy9XlDwLwVz1RCFg= github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca h1:kNY3/svz5T29MYHubXix4aDDuE3RWHkPvopM/EDv/MA= From 979cbd449274c660d8ed31b095664b8625b506bf Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 22 Jul 2022 11:49:15 -0500 Subject: [PATCH 118/376] Update dependabot.yml (#2189) --- .github/dependabot.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 1108256374b..7d2488faf47 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,7 +3,7 @@ updates: - package-ecosystem: gomod directory: "/" schedule: - interval: daily + interval: weekly ignore: - dependency-name: "github.com/tendermint/tendermint" update-types: ["version-update:semver-major", "version-update:semver-minor"] From dbb906fe5fd992237efa1784abd5ddeb8c48bd89 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 22 Jul 2022 14:44:04 -0500 Subject: [PATCH 119/376] Twap: Add twapkeeper wiring (#2193) * Twap: Add twapkeeper wiring * Add changelog entry --- CHANGELOG.md | 8 +++---- app/apptesting/gamm.go | 18 ++++++++++++++ app/apptesting/test_suite.go | 10 ++++++++ app/keepers/keepers.go | 11 +++++++++ app/keepers/keys.go | 4 +++- app/keepers/modules.go | 2 ++ app/modules.go | 6 ++++- app/upgrades/v11/constants.go | 6 ++++- x/gamm/keeper/pool.go | 7 ++++++ x/gamm/twap/abci.go | 13 ----------- x/gamm/twap/hook_listener.go | 31 ++++++++++++++++++++---- x/gamm/twap/keeper.go | 27 +++++++++++++++++---- x/gamm/twap/module.go | 44 ++++++++++++----------------------- x/gamm/twap/store.go | 9 +++---- 14 files changed, 135 insertions(+), 61 deletions(-) delete mode 100644 x/gamm/twap/abci.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c6bbe25e4d..d2687f58418 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,9 +42,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased -* [#2016](https://github.com/osmosis-labs/osmosis/pull/2016) Add fixed 10000 gas cost for each Balancer swap -* [$2147](https://github.com/osmosis-labs/osmosis/pull/2147) Set MaxAgeNumBlocks in v11 Upgrade Handler to two weeks. - ### Breaking Changes @@ -54,6 +51,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#1825](https://github.com/osmosis-labs/osmosis/pull/1825) Fixes Interchain Accounts (host side) by adding it to AppModuleBasics * [#1699](https://github.com/osmosis-labs/osmosis/pull/1699) Fixes bug in sig fig rounding on spot price queries for small values * [#1994](https://github.com/osmosis-labs/osmosis/pull/1994) Removed bech32ibc module +* [#2016](https://github.com/osmosis-labs/osmosis/pull/2016) Add fixed 10000 gas cost for each Balancer swap +* [#2147](https://github.com/osmosis-labs/osmosis/pull/2147) Set MaxAgeNumBlocks in v11 Upgrade Handler to two weeks. +* [#2193](https://github.com/osmosis-labs/osmosis/pull/2193) Add TwapKeeper to the Osmosis app #### Golang API breaks @@ -66,7 +66,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#1630](https://github.com/osmosis-labs/osmosis/pull/1630) Delete the v043_temp module, now that we're on an updated SDK version. * [#1667](https://github.com/osmosis-labs/osmosis/pull/1673) Move wasm-bindings code out of app package into its own root level package. * [#2013](https://github.com/osmosis-labs/osmosis/pull/2013) Make `SetParams`, `SetPool`, `SetTotalLiquidity`, and `SetDenomLiquidity` GAMM APIs private -*[#1857](https://github.com/osmosis-labs/osmosis/pull/1857) x/mint rename GetLastHalvenEpochNum to GetLastReductionEpochNum +* [#1857](https://github.com/osmosis-labs/osmosis/pull/1857) x/mint rename GetLastHalvenEpochNum to GetLastReductionEpochNum ### Features diff --git a/app/apptesting/gamm.go b/app/apptesting/gamm.go index f269249be34..a6de6def851 100644 --- a/app/apptesting/gamm.go +++ b/app/apptesting/gamm.go @@ -96,3 +96,21 @@ func (s *KeeperTestHelper) PrepareBalancerPoolWithPoolAsset(assets []balancer.Po s.NoError(err) return poolId } + +func (s *KeeperTestHelper) RunBasicSwap(poolId uint64) { + denoms, err := s.App.GAMMKeeper.GetPoolDenoms(s.Ctx, poolId) + s.Require().NoError(err) + + swapIn := sdk.NewCoins(sdk.NewCoin(denoms[0], sdk.NewInt(1000))) + s.FundAcc(s.TestAccs[0], swapIn) + + msg := gammtypes.MsgSwapExactAmountIn{ + Sender: string(s.TestAccs[0]), + Routes: []gammtypes.SwapAmountInRoute{{PoolId: poolId, TokenOutDenom: denoms[1]}}, + TokenIn: swapIn[0], + TokenOutMinAmount: sdk.ZeroInt(), + } + // TODO: switch to message + _, err = s.App.GAMMKeeper.SwapExactAmountIn(s.Ctx, s.TestAccs[0], poolId, msg.TokenIn, denoms[1], msg.TokenOutMinAmount) + s.Require().NoError(err) +} diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index 9f7a6ecf6eb..152a5a7d3c1 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -61,6 +61,16 @@ func (s *KeeperTestHelper) CreateTestContext() sdk.Context { return sdk.NewContext(ms, tmtypes.Header{}, false, logger) } +// CreateTestContext creates a test context. +func (s *KeeperTestHelper) Commit() { + oldHeight := s.Ctx.BlockHeight() + oldHeader := s.Ctx.BlockHeader() + s.App.Commit() + newHeader := tmtypes.Header{Height: oldHeight + 1, ChainID: oldHeader.ChainID, Time: time.Now().UTC()} + s.App.BeginBlock(abci.RequestBeginBlock{Header: newHeader}) + s.Ctx = s.App.GetBaseApp().NewContext(false, newHeader) +} + // FundAcc funds target address with specified amount. func (s *KeeperTestHelper) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) { err := simapp.FundAccount(s.App.BankKeeper, s.Ctx, acc, amounts) diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index 90121bd8fd4..aeecb95a0e5 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -52,6 +52,8 @@ import ( epochskeeper "github.com/osmosis-labs/osmosis/v10/x/epochs/keeper" epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" gammkeeper "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap" + twaptypes "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" incentiveskeeper "github.com/osmosis-labs/osmosis/v10/x/incentives/keeper" incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" @@ -98,6 +100,7 @@ type AppKeepers struct { TransferKeeper *ibctransferkeeper.Keeper EvidenceKeeper *evidencekeeper.Keeper GAMMKeeper *gammkeeper.Keeper + TwapKeeper *twap.Keeper LockupKeeper *lockupkeeper.Keeper EpochsKeeper *epochskeeper.Keeper IncentivesKeeper *incentiveskeeper.Keeper @@ -241,6 +244,12 @@ func (appKeepers *AppKeepers) InitNormalKeepers( appKeepers.AccountKeeper, appKeepers.BankKeeper, appKeepers.DistrKeeper) appKeepers.GAMMKeeper = &gammKeeper + appKeepers.TwapKeeper = twap.NewKeeper( + appKeepers.keys[twaptypes.StoreKey], + appKeepers.tkeys[twaptypes.TransientStoreKey], + appKeepers.GetSubspace(twaptypes.ModuleName), + appKeepers.GAMMKeeper) + appKeepers.LockupKeeper = lockupkeeper.NewKeeper( appCodec, appKeepers.keys[lockuptypes.StoreKey], @@ -454,6 +463,7 @@ func (appKeepers *AppKeepers) SetupHooks() { gammtypes.NewMultiGammHooks( // insert gamm hooks receivers here appKeepers.PoolIncentivesKeeper.Hooks(), + appKeepers.TwapKeeper.GammHooks(), ), ) @@ -512,6 +522,7 @@ func KVStoreKeys() []string { ibctransfertypes.StoreKey, capabilitytypes.StoreKey, gammtypes.StoreKey, + twaptypes.StoreKey, lockuptypes.StoreKey, incentivestypes.StoreKey, epochstypes.StoreKey, diff --git a/app/keepers/keys.go b/app/keepers/keys.go index 350f50a7279..c3dc16a6bd8 100644 --- a/app/keepers/keys.go +++ b/app/keepers/keys.go @@ -4,6 +4,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + + twaptypes "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" ) // GenerateKeys generates new keys (KV Store, Transient store, and memory store). @@ -13,7 +15,7 @@ func (appKeepers *AppKeepers) GenerateKeys() { appKeepers.keys = sdk.NewKVStoreKeys(KVStoreKeys()...) // Define transient store keys - appKeepers.tkeys = sdk.NewTransientStoreKeys(paramstypes.TStoreKey) + appKeepers.tkeys = sdk.NewTransientStoreKeys(paramstypes.TStoreKey, twaptypes.TransientStoreKey) // MemKeys are for information that is stored only in RAM. appKeepers.memKeys = sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) diff --git a/app/keepers/modules.go b/app/keepers/modules.go index cf6555b3252..07218549e7b 100644 --- a/app/keepers/modules.go +++ b/app/keepers/modules.go @@ -30,6 +30,7 @@ import ( _ "github.com/osmosis-labs/osmosis/v10/client/docs/statik" "github.com/osmosis-labs/osmosis/v10/x/epochs" "github.com/osmosis-labs/osmosis/v10/x/gamm" + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap" "github.com/osmosis-labs/osmosis/v10/x/incentives" "github.com/osmosis-labs/osmosis/v10/x/lockup" "github.com/osmosis-labs/osmosis/v10/x/mint" @@ -74,6 +75,7 @@ var AppModuleBasics = []module.AppModuleBasic{ transfer.AppModuleBasic{}, vesting.AppModuleBasic{}, gamm.AppModuleBasic{}, + twap.AppModuleBasic{}, txfees.AppModuleBasic{}, incentives.AppModuleBasic{}, lockup.AppModuleBasic{}, diff --git a/app/modules.go b/app/modules.go index ba9e72149ea..382131bbb71 100644 --- a/app/modules.go +++ b/app/modules.go @@ -47,6 +47,8 @@ import ( "github.com/osmosis-labs/osmosis/v10/x/epochs" epochstypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "github.com/osmosis-labs/osmosis/v10/x/gamm" + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap" + twaptypes "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" "github.com/osmosis-labs/osmosis/v10/x/incentives" incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" @@ -121,6 +123,7 @@ func appModules( params.NewAppModule(*app.ParamsKeeper), app.TransferModule, gamm.NewAppModule(appCodec, *app.GAMMKeeper, app.AccountKeeper, app.BankKeeper), + twap.NewAppModule(*app.TwapKeeper), txfees.NewAppModule(appCodec, *app.TxFeesKeeper), incentives.NewAppModule(appCodec, *app.IncentivesKeeper, app.AccountKeeper, app.BankKeeper, app.EpochsKeeper), lockup.NewAppModule(appCodec, *app.LockupKeeper, app.AccountKeeper, app.BankKeeper), @@ -165,7 +168,7 @@ func orderBeginBlockers(allModuleNames []string) []string { // OrderEndBlockers returns EndBlockers (crisis, govtypes, staking) with no relative order. func OrderEndBlockers(allModuleNames []string) []string { ord := partialord.NewPartialOrdering(allModuleNames) - // only Osmosis modules with endblock code are: crisis, govtypes, staking + // only Osmosis modules with endblock code are: twap, crisis, govtypes, staking // we don't care about the relative ordering between them. return ord.TotalOrdering() } @@ -190,6 +193,7 @@ func OrderInitGenesis(allModuleNames []string) []string { ibchost.ModuleName, icatypes.ModuleName, gammtypes.ModuleName, + twaptypes.ModuleName, txfeestypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, diff --git a/app/upgrades/v11/constants.go b/app/upgrades/v11/constants.go index fa9fa4455c7..6a1cc34ff4a 100644 --- a/app/upgrades/v11/constants.go +++ b/app/upgrades/v11/constants.go @@ -2,6 +2,7 @@ package v11 import ( "github.com/osmosis-labs/osmosis/v10/app/upgrades" + twaptypes "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" store "github.com/cosmos/cosmos-sdk/store/types" ) @@ -12,5 +13,8 @@ const UpgradeName = "v11" var Upgrade = upgrades.Upgrade{ UpgradeName: UpgradeName, CreateUpgradeHandler: CreateUpgradeHandler, - StoreUpgrades: store.StoreUpgrades{}, + StoreUpgrades: store.StoreUpgrades{ + Added: []string{twaptypes.StoreKey}, + Deleted: []string{}, // double check bech32ibc + }, } diff --git a/x/gamm/keeper/pool.go b/x/gamm/keeper/pool.go index 9617ffb3f03..dae14c7a654 100644 --- a/x/gamm/keeper/pool.go +++ b/x/gamm/keeper/pool.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/osmosis-labs/osmosis/v10/osmoutils" "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/stableswap" "github.com/osmosis-labs/osmosis/v10/x/gamm/types" @@ -197,6 +198,12 @@ func (k Keeper) DeletePool(ctx sdk.Context, poolId uint64) error { // return nil // } +func (k Keeper) GetPoolDenoms(ctx sdk.Context, poolId uint64) ([]string, error) { + pool, err := k.GetPoolAndPoke(ctx, poolId) + denoms := osmoutils.CoinsDenoms(pool.GetTotalPoolLiquidity(ctx)) + return denoms, err +} + // setNextPoolNumber sets next pool number. func (k Keeper) setNextPoolNumber(ctx sdk.Context, poolNumber uint64) { store := ctx.KVStore(k.storeKey) diff --git a/x/gamm/twap/abci.go b/x/gamm/twap/abci.go deleted file mode 100644 index 060da2b2525..00000000000 --- a/x/gamm/twap/abci.go +++ /dev/null @@ -1,13 +0,0 @@ -package twap - -import sdk "github.com/cosmos/cosmos-sdk/types" - -func (k twapkeeper) endBlockLogic(ctx sdk.Context) { - // TODO: Update TWAP entries - // step 1: Get all altered pool ids - changedPoolIds := k.getChangedPools(ctx) - if len(changedPoolIds) == 0 { - return - } - // 'altered pool ids' should be automatically cleared -} diff --git a/x/gamm/twap/hook_listener.go b/x/gamm/twap/hook_listener.go index 2a5163577d4..cad053ab64a 100644 --- a/x/gamm/twap/hook_listener.go +++ b/x/gamm/twap/hook_listener.go @@ -1,29 +1,52 @@ package twap import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + epochtypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) var _ types.GammHooks = &gammhook{} +var _ epochtypes.EpochHooks = &epochhook{} + +type epochhook struct { + k Keeper +} + +func (hook *epochhook) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) { + if epochIdentifier == hook.k.PruneEpochIdentifier(ctx) { + fmt.Println("restore logic in subsequent PR") + // hook.k.pruneOldTwaps(ctx) + } +} + +func (hook *epochhook) BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) {} type gammhook struct { - k twapkeeper + k Keeper +} + +func (k Keeper) GammHooks() types.GammHooks { + return &gammhook{k} } // AfterPoolCreated is called after CreatePool func (hook *gammhook) AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, poolId uint64) { - // TODO: Log pool creation to begin creating TWAPs for it + // err := hook.k.afterCreatePool(ctx, poolId) + // // Will halt pool creation + // if err != nil { + // panic(err) + // } } func (hook *gammhook) AfterSwap(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) { - // Log that this pool had a potential spot price change hook.k.trackChangedPool(ctx, poolId) } func (hook *gammhook) AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, enterCoins sdk.Coins, shareOutAmount sdk.Int) { - // Log that this pool had a potential spot price change hook.k.trackChangedPool(ctx, poolId) } diff --git a/x/gamm/twap/keeper.go b/x/gamm/twap/keeper.go index b3a189b2701..46ad1cccbe3 100644 --- a/x/gamm/twap/keeper.go +++ b/x/gamm/twap/keeper.go @@ -1,8 +1,27 @@ package twap -import sdk "github.com/cosmos/cosmos-sdk/types" +import ( + sdk "github.com/cosmos/cosmos-sdk/types" -type twapkeeper struct { - // storeKey sdk.StoreKey - transientKey sdk.TransientStoreKey + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" +) + +type Keeper struct { + storeKey sdk.StoreKey + transientKey *sdk.TransientStoreKey + + paramSpace paramtypes.Subspace + + ammkeeper types.AmmInterface +} + +func NewKeeper(storeKey sdk.StoreKey, transientKey *sdk.TransientStoreKey, paramSpace paramtypes.Subspace, ammKeeper types.AmmInterface) *Keeper { + return &Keeper{storeKey: storeKey, transientKey: transientKey, paramSpace: paramSpace, ammkeeper: ammKeeper} +} + +// TODO: make this read from a parameter, or hardcode it. +func (k *Keeper) PruneEpochIdentifier(ctx sdk.Context) string { + return "daily" } diff --git a/x/gamm/twap/module.go b/x/gamm/twap/module.go index e15b401601f..178c65219f5 100644 --- a/x/gamm/twap/module.go +++ b/x/gamm/twap/module.go @@ -1,7 +1,6 @@ package twap import ( - "context" "encoding/json" "fmt" @@ -16,9 +15,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/osmosis-labs/osmosis/v10/x/gamm/keeper" - twaptypes "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" - "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" ) var ( @@ -27,27 +24,24 @@ var ( ) type AppModuleBasic struct { - cdc codec.Codec } -func (AppModuleBasic) Name() string { return twaptypes.ModuleName } +func (AppModuleBasic) Name() string { return types.ModuleName } func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { } func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return json.RawMessage{} - // return cdc.MustMarshalJSON(types.DefaultGenesis()) + return cdc.MustMarshalJSON(&types.GenesisState{}) } // ValidateGenesis performs genesis state validation for the gamm module. func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - // var genState types.GenesisState - // if err := cdc.UnmarshalJSON(bz, &genState); err != nil { - // return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - // } - // return genState.Validate() - return nil + var genState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + return genState.Validate() } //--------------------------------------- @@ -56,7 +50,7 @@ func (b AppModuleBasic) RegisterRESTRoutes(ctx client.Context, r *mux.Router) { } func (b AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) //nolint:errcheck + // types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) //nolint:errcheck } func (b AppModuleBasic) GetTxCmd() *cobra.Command { @@ -76,23 +70,16 @@ func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) type AppModule struct { AppModuleBasic - ak types.AccountKeeper - bk types.BankKeeper - gk keeper.Keeper - tk twapkeeper + k Keeper } func (am AppModule) RegisterServices(cfg module.Configurator) { } -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, - accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, -) AppModule { +func NewAppModule(twapKeeper Keeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - gk: keeper, - ak: accountKeeper, - bk: bankKeeper, + AppModuleBasic: AppModuleBasic{}, + k: twapKeeper, } } @@ -128,10 +115,9 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw // BeginBlock performs a no-op. func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// EndBlock returns the end blocker for the gamm module. It returns no validator -// updates. +// EndBlock performs a no-op. func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - am.tk.endBlockLogic(ctx) + // am.k.endBlock(ctx) return []abci.ValidatorUpdate{} } diff --git a/x/gamm/twap/store.go b/x/gamm/twap/store.go index 171a678f897..5a95438881c 100644 --- a/x/gamm/twap/store.go +++ b/x/gamm/twap/store.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func (k twapkeeper) trackChangedPool(ctx sdk.Context, poolId uint64) { - store := ctx.TransientStore(&k.transientKey) +func (k Keeper) trackChangedPool(ctx sdk.Context, poolId uint64) { + store := ctx.TransientStore(k.transientKey) poolIdBz := make([]byte, 8) binary.LittleEndian.PutUint64(poolIdBz, poolId) // just has to not be empty, for store to work / not register as a delete. @@ -15,8 +15,9 @@ func (k twapkeeper) trackChangedPool(ctx sdk.Context, poolId uint64) { store.Set(poolIdBz, sentinelExistsValue) } -func (k twapkeeper) getChangedPools(ctx sdk.Context) []uint64 { - store := ctx.TransientStore(&k.transientKey) +//nolint:unused,deadcode +func (k Keeper) getChangedPools(ctx sdk.Context) []uint64 { + store := ctx.TransientStore(k.transientKey) iter := store.Iterator(nil, nil) defer iter.Close() From cbc6ad4b92121ff2d3462d65f6b878d6fad33258 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Fri, 22 Jul 2022 16:42:17 -0500 Subject: [PATCH 120/376] simulator: return accs with SpendableCoins (#2182) * change to spendable coins * implement Dev's suggestions * apply Roman suggestion --- simulation/simtypes/account.go | 22 +++++++++++++++++----- x/gamm/simulation/sim_msgs.go | 2 +- x/tokenfactory/module.go | 2 +- x/tokenfactory/simulation/sim_msgs.go | 7 ++++++- 4 files changed, 25 insertions(+), 8 deletions(-) diff --git a/simulation/simtypes/account.go b/simulation/simtypes/account.go index 80c3d1c7931..9b375bf52da 100644 --- a/simulation/simtypes/account.go +++ b/simulation/simtypes/account.go @@ -39,9 +39,10 @@ func (sim *SimCtx) RandomSimAccountWithConstraint(f SimAccountConstraint) (simul return sim.randomSimAccount(filteredAddrs), true } -func (sim *SimCtx) RandomSimAccountWithMinCoins(ctx sdk.Context, denom string, amount int64) (simulation.Account, error) { +func (sim *SimCtx) RandomSimAccountWithMinCoins(ctx sdk.Context, coins sdk.Coins) (simulation.Account, error) { accHasMinCoins := func(acc simulation.Account) bool { - return sim.BankKeeper().GetBalance(ctx, acc.Address, denom).IsGTE(sdk.NewCoin(denom, sdk.NewInt(amount))) + spendableCoins := sim.BankKeeper().SpendableCoins(ctx, acc.Address) + return spendableCoins.IsAllGTE(coins) && coins.DenomsSubsetOf(spendableCoins) } acc, found := sim.RandomSimAccountWithConstraint(accHasMinCoins) if !found { @@ -94,6 +95,13 @@ func (sim *SimCtx) SelAddrWithDenoms(ctx sdk.Context, denoms []string) (simulati if sim.BankKeeper().GetBalance(ctx, acc.Address, denom).Amount.IsZero() { return false } + // only return addr if it has spendable coins of requested denom + coins := sim.BankKeeper().SpendableCoins(ctx, acc.Address) + for _, coin := range coins { + if denom == coin.Denom { + return true + } + } } return true } @@ -189,9 +197,13 @@ func (sim *SimCtx) RandExponentialCoin(ctx sdk.Context, addr sdk.AccAddress) sdk func (sim *SimCtx) RandCoinSubset(ctx sdk.Context, addr sdk.AccAddress, denoms []string) sdk.Coins { subsetCoins := sdk.Coins{} for _, denom := range denoms { - bal := sim.BankKeeper().GetBalance(ctx, addr, denom) - amt := sim.RandPositiveInt(bal.Amount) - subsetCoins = subsetCoins.Add(sdk.NewCoin(bal.Denom, amt)) + coins := sim.BankKeeper().SpendableCoins(ctx, addr) + for _, coin := range coins { + if denom == coin.Denom { + amt := sim.RandPositiveInt(coin.Amount) + subsetCoins = subsetCoins.Add(sdk.NewCoin(coin.Denom, amt)) + } + } } return subsetCoins } diff --git a/x/gamm/simulation/sim_msgs.go b/x/gamm/simulation/sim_msgs.go index d26a6fa5948..9e227cacc6e 100644 --- a/x/gamm/simulation/sim_msgs.go +++ b/x/gamm/simulation/sim_msgs.go @@ -34,7 +34,7 @@ func RandomJoinPoolMsg(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) ( if !senderExists { return &types.MsgJoinPool{}, fmt.Errorf("no sender with denoms %s exists", poolDenoms) } - // cap joining pool to double the pool liquidity + // cap joining pool to the pool liquidity tokenIn = osmoutils.MinCoins(tokenIn, pool.GetTotalPoolLiquidity(ctx)) // TODO: Fix API so this is a one liner, pool.CalcJoinPoolNoSwapShares() diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index fa03c848b44..f339049d8be 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -189,7 +189,7 @@ func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Valid // GenerateGenesisState creates a randomized GenState of the tokenfactory module. func (am AppModule) SimulatorGenesisState(simState *module.SimulationState, s *simtypes.SimCtx) { tfDefaultGen := types.DefaultGenesis() - tfDefaultGen.Params.DenomCreationFee = sdk.NewCoins(sdk.NewInt64Coin("stake", 10_000_000)) + tfDefaultGen.Params.DenomCreationFee = simulation.TokenFactoryCreationFee tfDefaultGenJson := simState.Cdc.MustMarshalJSON(tfDefaultGen) simState.GenState[types.ModuleName] = tfDefaultGenJson } diff --git a/x/tokenfactory/simulation/sim_msgs.go b/x/tokenfactory/simulation/sim_msgs.go index 3310362f9d7..4fe4caa0281 100644 --- a/x/tokenfactory/simulation/sim_msgs.go +++ b/x/tokenfactory/simulation/sim_msgs.go @@ -13,9 +13,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +var ( + TokenFactoryCreationFee = sdk.NewCoins(sdk.NewInt64Coin("stake", 10_000_000)) +) + // RandomMsgCreateDenom creates a random tokenfactory denom that is no greater than 44 alphanumeric characters func RandomMsgCreateDenom(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgCreateDenom, error) { - acc, err := sim.RandomSimAccountWithMinCoins(ctx, "stake", 10_000_000) + minCoins := TokenFactoryCreationFee + acc, err := sim.RandomSimAccountWithMinCoins(ctx, minCoins) if err != nil { return nil, err } From e988d4008e50821c5b137945951e5e6a863c713b Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Fri, 22 Jul 2022 17:49:30 -0500 Subject: [PATCH 121/376] simulator: create an ActionWithMetadata struct (#2196) * add ActionWithMetadata struct * public module name --- simulation/executor/simulate.go | 5 +++-- simulation/simtypes/action.go | 8 ++++---- simulation/simtypes/manager.go | 30 ++++++++++++++++++++++++------ 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index ee1c466717d..fa3f6c19371 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -58,7 +58,7 @@ func SimulateFromSeed( w io.Writer, app simtypes.App, initFunctions simtypes.InitFunctions, - actions []simtypes.Action, + actions []simtypes.ActionsWithMetadata, config simulation.Config, ) (stopEarly bool, err error) { // in case we have to end early, don't os.Exit so that we can run cleanup code. @@ -205,7 +205,7 @@ type blockSimFn func(simCtx *simtypes.SimCtx, ctx sdk.Context, header tmproto.He // Returns a function to simulate blocks. Written like this to avoid constant // parameters being passed everytime, to minimize memory overhead. -func createBlockSimulator(testingMode bool, w io.Writer, params Params, actions []simtypes.Action, +func createBlockSimulator(testingMode bool, w io.Writer, params Params, actions []simtypes.ActionsWithMetadata, simState *simState, config simulation.Config, ) blockSimFn { lastBlockSizeState := 0 // state for [4 * uniform distribution] @@ -233,6 +233,7 @@ func createBlockSimulator(testingMode bool, w io.Writer, params Params, actions // Select and execute tx action := selectAction(actionSimCtx.GetSeededRand("action select")) opMsg, futureOps, err := action.Execute(actionSimCtx, ctx) + opMsg.Route = action.ModuleName cleanup() simState.logActionResult(header, i, config, blocksize, opMsg, err) diff --git a/simulation/simtypes/action.go b/simulation/simtypes/action.go index a0118e3a17d..762e77823d8 100644 --- a/simulation/simtypes/action.go +++ b/simulation/simtypes/action.go @@ -26,7 +26,7 @@ type Action interface { WithFrequency(w Frequency) Action } -type selectActionFn func(r *rand.Rand) Action +type selectActionFn func(r *rand.Rand) ActionsWithMetadata type weightedOperationAction struct { moduleName string @@ -111,7 +111,7 @@ func (m msgBasedAction) Execute(sim *SimCtx, ctx sdk.Context) ( return sim.deliverTx(tx, msg, m.name) } -func totalFrequency(actions []Action) int { +func totalFrequency(actions []ActionsWithMetadata) int { totalFrequency := 0 for _, action := range actions { totalFrequency += mapFrequencyFromString(action.Frequency()) @@ -120,10 +120,10 @@ func totalFrequency(actions []Action) int { return totalFrequency } -func GetSelectActionFn(actions []Action) selectActionFn { +func GetSelectActionFn(actions []ActionsWithMetadata) selectActionFn { totalOpFrequency := totalFrequency(actions) - return func(r *rand.Rand) Action { + return func(r *rand.Rand) ActionsWithMetadata { x := r.Intn(totalOpFrequency) // TODO: Change to an accum list approach for i := 0; i < len(actions); i++ { diff --git a/simulation/simtypes/manager.go b/simulation/simtypes/manager.go index 75b22c72971..8c37e5a5960 100644 --- a/simulation/simtypes/manager.go +++ b/simulation/simtypes/manager.go @@ -29,6 +29,15 @@ type AppModuleSimulationGenesis interface { SimulatorGenesisState(*module.SimulationState, *SimCtx) } +type SimulatorManagerI interface { + Actions() []ActionsWithMetadata +} + +type ActionsWithMetadata struct { + Action + ModuleName string +} + // SimulationManager defines a simulation manager that provides the high level utility // for managing and executing simulation functionalities for a group of modules type Manager struct { @@ -80,11 +89,10 @@ func loadAppParamsForWasm(path string) simulation.AppParams { return appParams } -func (m Manager) legacyActions(seed int64, cdc codec.JSONCodec) []Action { +func (m Manager) legacyActions(seed int64, cdc codec.JSONCodec) []ActionsWithMetadata { // We do not support the legacy simulator config format, and just (unfortunately) // hardcode this one filepath for wasm. // TODO: Clean this up / make a better plan - simState := module.SimulationState{ AppParams: loadAppParamsForWasm("params.json"), ParamChanges: []simulation.ParamChange{}, @@ -101,23 +109,33 @@ func (m Manager) legacyActions(seed int64, cdc codec.JSONCodec) []Action { } } // second pass generate actions - actions := []Action{} + actions := []ActionsWithMetadata{} for _, moduleName := range m.moduleManager.OrderInitGenesis { if simModule, ok := m.legacyModules[moduleName]; ok { weightedOps := simModule.WeightedOperations(simState) - actions = append(actions, actionsFromWeightedOperations(moduleName, weightedOps)...) + for _, action := range actionsFromWeightedOperations(moduleName, weightedOps) { + var actionWithMetaData ActionsWithMetadata + actionWithMetaData.Action = action + actionWithMetaData.ModuleName = moduleName + actions = append(actions, actionWithMetaData) + } } } return actions } // TODO: Can we use sim here instead? Perhaps by passing in the simulation module manager to the simulator. -func (m Manager) Actions(seed int64, cdc codec.JSONCodec) []Action { +func (m Manager) Actions(seed int64, cdc codec.JSONCodec) []ActionsWithMetadata { actions := m.legacyActions(seed, cdc) moduleKeys := maps.Keys(m.Modules) osmoutils.SortSlice(moduleKeys) for _, simModuleName := range moduleKeys { - actions = append(actions, m.Modules[simModuleName].Actions()...) + for _, action := range m.Modules[simModuleName].Actions() { + var actionWithMetaData ActionsWithMetadata + actionWithMetaData.Action = action + actionWithMetaData.ModuleName = simModuleName + actions = append(actions, actionWithMetaData) + } } return actions } From 3cdfbccd2957e78e8a62877b47941a8e1cee537d Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Sat, 23 Jul 2022 12:46:22 -0500 Subject: [PATCH 122/376] feat: speedup epoch distribution, superfluid component (#2214) * Speedup epoch distribution, superfluid component * changelog entries * lint Co-authored-by: Dev Ojha --- CHANGELOG.md | 3 ++- x/incentives/keeper/distribute.go | 35 +++++++++++++++++++++++-------- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2687f58418..70f47dada78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,7 +44,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking Changes - * [#1889](https://github.com/osmosis-labs/osmosis/pull/1825) Add proto responses to gamm LP messages: * MsgJoinPoolResponse: share_out_amount and token_in fields * MsgExitPoolResponse: token_out field @@ -85,6 +84,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [1931](https://github.com/osmosis-labs/osmosis/pull/1931) Add explicit check for input denoms to `CalcJoinPoolShares` * [2011](https://github.com/osmosis-labs/osmosis/pull/2011) Fix bug in TokenFactory initGenesis, relating to denom creation fee param. +### Improvements +* [#2214](https://github.com/osmosis-labs/osmosis/pull/2214) Speedup epoch distribution, superfluid component ## [v9.0.0 - Nitrogen](https://github.com/osmosis-labs/osmosis/releases/tag/v9.0.0) diff --git a/x/incentives/keeper/distribute.go b/x/incentives/keeper/distribute.go index f25b233426c..c6921364441 100644 --- a/x/incentives/keeper/distribute.go +++ b/x/incentives/keeper/distribute.go @@ -225,20 +225,37 @@ func (k Keeper) doDistributionSends(ctx sdk.Context, distrs *distributionInfo) e func (k Keeper) distributeSyntheticInternal( ctx sdk.Context, gauge types.Gauge, locks []lockuptypes.PeriodLock, distrInfo *distributionInfo, ) (sdk.Coins, error) { - denom := gauge.DistributeTo.Denom - - qualifiedLocks := make([]lockuptypes.PeriodLock, 0, len(locks)) + qualifiedLocks := k.lk.GetLocksLongerThanDurationDenom(ctx, gauge.DistributeTo.Denom, gauge.DistributeTo.Duration) + + // map from lockID to present index in resultant list + // to be state compatible with what we had before, we iterate over locks, to get qualified locks + // to be in the same order as what is present in locks. + // in a future release, we can just use qualified locks directly. + type lockIndexPair struct { + lock lockuptypes.PeriodLock + index int + } + qualifiedLocksMap := make(map[uint64]lockIndexPair, len(qualifiedLocks)) + for _, lock := range qualifiedLocks { + qualifiedLocksMap[lock.ID] = lockIndexPair{lock, -1} + } + curIndex := 0 for _, lock := range locks { - // see if this lock has a synthetic lockup. If so, err == nil, and we add to qualifiedLocks. - // otherwise it does not, and we continue. - _, err := k.lk.GetSyntheticLockup(ctx, lock.ID, denom) - if err != nil { + if v, ok := qualifiedLocksMap[lock.ID]; ok { + qualifiedLocksMap[lock.ID] = lockIndexPair{v.lock, curIndex} + curIndex += 1 + } + } + + sortedAndTrimmedQualifiedLocks := make([]lockuptypes.PeriodLock, curIndex) + for _, v := range qualifiedLocksMap { + if v.index < 0 { continue } - qualifiedLocks = append(qualifiedLocks, lock) + sortedAndTrimmedQualifiedLocks[v.index] = v.lock } - return k.distributeInternal(ctx, gauge, qualifiedLocks, distrInfo) + return k.distributeInternal(ctx, gauge, sortedAndTrimmedQualifiedLocks, distrInfo) } // distributeInternal runs the distribution logic for a gauge, and adds the sends to From 7f1d6175a864226e339c93951fd023e819ec96d3 Mon Sep 17 00:00:00 2001 From: Roman Date: Sat, 23 Jul 2022 16:58:15 -0400 Subject: [PATCH 123/376] feat(txfees/incentives): minimum base fee for a message (#2202) * feat(txfees/incentives): minimum base fee for a message * comment * typos * clean up * msg fees in dec and fixes in decorator * progress * tests * amounts * test suite fix * changelog * fix error msg * Update x/txfees/keeper/feedecorator.go Co-authored-by: Aleksandr Bezobchuk * Update x/txfees/keeper/feedecorator.go Co-authored-by: Aleksandr Bezobchuk * group vars Co-authored-by: Aleksandr Bezobchuk --- CHANGELOG.md | 1 + go.mod | 4 +- x/incentives/types/msgs.go | 22 ++++- x/txfees/keeper/feedecorator.go | 29 +++++-- x/txfees/keeper/feedecorator_test.go | 78 +++++++++++++++++ x/txfees/keeper/mocks/fee_tx_mock.go | 120 +++++++++++++++++++++++++++ x/txfees/types/msg_fee_extension.go | 11 +++ 7 files changed, 255 insertions(+), 10 deletions(-) create mode 100644 x/txfees/keeper/mocks/fee_tx_mock.go create mode 100644 x/txfees/types/msg_fee_extension.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 70f47dada78..1da79e1ab72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#1667](https://github.com/osmosis-labs/osmosis/pull/1673) Move wasm-bindings code out of app package into its own root level package. * [#2013](https://github.com/osmosis-labs/osmosis/pull/2013) Make `SetParams`, `SetPool`, `SetTotalLiquidity`, and `SetDenomLiquidity` GAMM APIs private * [#1857](https://github.com/osmosis-labs/osmosis/pull/1857) x/mint rename GetLastHalvenEpochNum to GetLastReductionEpochNum +* [#2202](https://github.com/osmosis-labs/osmosis/pull/2202) Minimum message fee for `CreateGauge`, `AddToGauge`; feedecorator `IsSufficientFee` API changes. ### Features diff --git a/go.mod b/go.mod index 6fba47841e0..7a741660236 100644 --- a/go.mod +++ b/go.mod @@ -34,13 +34,11 @@ require ( require ( github.com/alingse/asasalint v0.0.10 // indirect + github.com/golang/mock v1.6.0 // indirect github.com/sivchari/nosnakecase v1.5.0 // indirect go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.7.0 // indirect go.uber.org/zap v1.19.1 // indirect -) - -require ( 4d63.com/gochecknoglobals v0.1.0 // indirect filippo.io/edwards25519 v1.0.0-beta.2 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect diff --git a/x/incentives/types/msgs.go b/x/incentives/types/msgs.go index 4873cb9f174..8776c73be6f 100644 --- a/x/incentives/types/msgs.go +++ b/x/incentives/types/msgs.go @@ -5,6 +5,7 @@ import ( "time" lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + txfeestypes "github.com/osmosis-labs/osmosis/v10/x/txfees/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -12,9 +13,16 @@ import ( const ( TypeMsgCreateGauge = "create_gauge" TypeMsgAddToGauge = "add_to_gauge" + + createGaugeMinBaseFee = 50 * 1_000_000 + addToGaugeMinBaseFee = 25 * 1_000_000 ) -var _ sdk.Msg = &MsgCreateGauge{} +var ( + _ sdk.Msg = &MsgCreateGauge{} + _ txfeestypes.MsgMinFeeExtension = &MsgCreateGauge{} + _ txfeestypes.MsgMinFeeExtension = &MsgAddToGauge{} +) // NewMsgCreateGauge creates a message to create a gauge with the provided parameters. func NewMsgCreateGauge(isPerpetual bool, owner sdk.AccAddress, distributeTo lockuptypes.QueryCondition, coins sdk.Coins, startTime time.Time, numEpochsPaidOver uint64) *MsgCreateGauge { @@ -28,6 +36,12 @@ func NewMsgCreateGauge(isPerpetual bool, owner sdk.AccAddress, distributeTo lock } } +// GetRequiredMinBaseFee returns the minimum fee for the message +// denominated in base fee denom. +func (m MsgCreateGauge) GetRequiredMinBaseFee() sdk.Dec { + return sdk.NewDec(createGaugeMinBaseFee) +} + // Route takes a create gauge message, then returns the RouterKey used for slashing. func (m MsgCreateGauge) Route() string { return RouterKey } @@ -84,6 +98,12 @@ func NewMsgAddToGauge(owner sdk.AccAddress, gaugeId uint64, rewards sdk.Coins) * } } +// GetRequiredMinBaseFee returns the minimum fee for the message +// denominated in base fee denom. +func (m MsgAddToGauge) GetRequiredMinBaseFee() sdk.Dec { + return sdk.NewDec(addToGaugeMinBaseFee) +} + // Route takes an add to gauge message, then returns the RouterKey used for slashing. func (m MsgAddToGauge) Route() string { return RouterKey } diff --git a/x/txfees/keeper/feedecorator.go b/x/txfees/keeper/feedecorator.go index caa93cfee9a..06e9efd713b 100644 --- a/x/txfees/keeper/feedecorator.go +++ b/x/txfees/keeper/feedecorator.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/pkg/errors" "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper/txfee_filters" "github.com/osmosis-labs/osmosis/v10/x/txfees/types" @@ -82,7 +83,7 @@ func (mfd MempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b if len(feeCoins) != 1 { return ctx, sdkerrors.Wrapf(sdkerrors.ErrInsufficientFee, "no fee attached") } - err = mfd.TxFeesKeeper.IsSufficientFee(ctx, minBaseGasPrice, feeTx.GetGas(), feeCoins[0]) + err = mfd.TxFeesKeeper.IsSufficientFee(ctx, minBaseGasPrice, feeTx) if err != nil { return ctx, err } @@ -92,23 +93,39 @@ func (mfd MempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b return next(ctx, tx, simulate) } -// IsSufficientFee checks if the feeCoin provided (in any asset), is worth enough osmo at current spot prices -// to pay the gas cost of this tx. -func (k Keeper) IsSufficientFee(ctx sdk.Context, minBaseGasPrice sdk.Dec, gasRequested uint64, feeCoin sdk.Coin) error { +// IsSufficientFee checks if the fee provided (in any asset), is worth enough osmo at current spot prices +// to pay the maximum of: +// - gas cost of this tx +// - minimum fee associated with any of the messages in this tx. N.B.: not all messages have such a fee. +func (k Keeper) IsSufficientFee(ctx sdk.Context, minBaseGasPrice sdk.Dec, tx sdk.FeeTx) error { baseDenom, err := k.GetBaseDenom(ctx) if err != nil { return err } + feeCoins := tx.GetFee() + if len(feeCoins) != 1 { + return errors.Wrap(sdkerrors.ErrInsufficientFee, fmt.Sprintf("invalid number of fee tokens provided (%s); expected: 1, got: %d", feeCoins, len(feeCoins))) + } + feeCoin := feeCoins[0] // Determine the required fees by multiplying the required minimum gas // price by the gas limit, where fee = ceil(minGasPrice * gasLimit). - glDec := sdk.NewDec(int64(gasRequested)) - requiredBaseFee := sdk.NewCoin(baseDenom, minBaseGasPrice.Mul(glDec).Ceil().RoundInt()) + glDec := sdk.NewDec(int64(tx.GetGas())) + maxRequiredBaseFee := minBaseGasPrice.Mul(glDec).Ceil() + + for _, msg := range tx.GetMsgs() { + if feeMsg, ok := msg.(types.MsgMinFeeExtension); ok { + maxRequiredBaseFee = sdk.MaxDec(maxRequiredBaseFee, feeMsg.GetRequiredMinBaseFee()) + } + } + + requiredBaseFee := sdk.NewCoin(baseDenom, maxRequiredBaseFee.RoundInt()) convertedFee, err := k.ConvertToBaseToken(ctx, feeCoin) if err != nil { return err } + // check to ensure that the convertedFee should always be greater than or equal to the requireBaseFee if !(convertedFee.IsGTE(requiredBaseFee)) { return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFee, "insufficient fees; got: %s which converts to %s. required: %s", feeCoin, convertedFee, requiredBaseFee) diff --git a/x/txfees/keeper/feedecorator_test.go b/x/txfees/keeper/feedecorator_test.go index 1838a2c303d..4cb652c649c 100644 --- a/x/txfees/keeper/feedecorator_test.go +++ b/x/txfees/keeper/feedecorator_test.go @@ -8,8 +8,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + gomock "github.com/golang/mock/gomock" + gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" + incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper" + "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper/mocks" "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) @@ -240,3 +244,77 @@ func (suite *KeeperTestSuite) TestFeeDecorator() { }) } } + +func (suite *KeeperTestSuite) TestIsSufficientFee() { + suite.SetupTest(false) + ctrl := gomock.NewController(suite.T()) + defer ctrl.Finish() + + ctx := suite.Ctx + txfeesKeeper := suite.App.TxFeesKeeper + + createGaugeFee := incentivestypes.MsgCreateGauge{}.GetRequiredMinBaseFee().RoundInt64() + + testcases := map[string]struct { + txFee int64 + gasFee int64 + msg []sdk.Msg + + minGasFee int64 + expectError bool + }{ + "tx fee above gas fee and msg fee - no error": { + txFee: createGaugeFee + 1, + gasFee: createGaugeFee - 1, + msg: []sdk.Msg{&incentivestypes.MsgCreateGauge{}}, + }, + "tx fee above gas fee but below msg fee - error": { + txFee: createGaugeFee - 1, + minGasFee: createGaugeFee - 2, + msg: []sdk.Msg{&incentivestypes.MsgCreateGauge{}}, + + expectError: true, + }, + "tx fee above msg fee but below gas fee - error": { + txFee: createGaugeFee + 2, + minGasFee: createGaugeFee + 5, + msg: []sdk.Msg{&incentivestypes.MsgCreateGauge{}}, + + expectError: true, + }, + "tx fee above gas fee and msg 1 but below msg 2 fee - error": { + txFee: createGaugeFee - 1, + minGasFee: createGaugeFee - 3, + msg: []sdk.Msg{&incentivestypes.MsgAddToGauge{}, &incentivestypes.MsgCreateGauge{}}, + + expectError: true, + }, + "tx fee above gas fee and msg with no fee - success": { + txFee: createGaugeFee, + minGasFee: createGaugeFee - 3, + msg: []sdk.Msg{&gammtypes.MsgExitPool{}}, + }, + } + + for name, tc := range testcases { + suite.Run(name, func() { + minBaseGasPrice := sdk.NewDec(tc.minGasFee) + + txMock := mocks.NewMockFeeTx(ctrl) + + txMock.EXPECT().GetFee().Return(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(tc.txFee)))).AnyTimes() + txMock.EXPECT().GetGas().Return(uint64(1)).AnyTimes() // minBaseGasPrice = 1 * tc.MinGasFee, for easy comparison with msg fee. + txMock.EXPECT().GetMsgs().Return([]sdk.Msg{ + &incentivestypes.MsgCreateGauge{}, + }).AnyTimes() + + err := txfeesKeeper.IsSufficientFee(ctx, minBaseGasPrice, txMock) + + if tc.expectError { + suite.Require().Error(err) + } else { + suite.Require().NoError(err) + } + }) + } +} diff --git a/x/txfees/keeper/mocks/fee_tx_mock.go b/x/txfees/keeper/mocks/fee_tx_mock.go new file mode 100644 index 00000000000..4cd2451b530 --- /dev/null +++ b/x/txfees/keeper/mocks/fee_tx_mock.go @@ -0,0 +1,120 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: /root/workspace/cosmos-sdk/types/tx_msg.go + +// Package mock_types is a generated GoMock package. +package mocks + +import ( + reflect "reflect" + + types0 "github.com/cosmos/cosmos-sdk/types" + gomock "github.com/golang/mock/gomock" +) + + +// MockFeeTx is a mock of FeeTx interface. +type MockFeeTx struct { + ctrl *gomock.Controller + recorder *MockFeeTxMockRecorder +} + +// MockFeeTxMockRecorder is the mock recorder for MockFeeTx. +type MockFeeTxMockRecorder struct { + mock *MockFeeTx +} + +// NewMockFeeTx creates a new mock instance. +func NewMockFeeTx(ctrl *gomock.Controller) *MockFeeTx { + mock := &MockFeeTx{ctrl: ctrl} + mock.recorder = &MockFeeTxMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockFeeTx) EXPECT() *MockFeeTxMockRecorder { + return m.recorder +} + +// FeeGranter mocks base method. +func (m *MockFeeTx) FeeGranter() types0.AccAddress { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FeeGranter") + ret0, _ := ret[0].(types0.AccAddress) + return ret0 +} + +// FeeGranter indicates an expected call of FeeGranter. +func (mr *MockFeeTxMockRecorder) FeeGranter() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FeeGranter", reflect.TypeOf((*MockFeeTx)(nil).FeeGranter)) +} + +// FeePayer mocks base method. +func (m *MockFeeTx) FeePayer() types0.AccAddress { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FeePayer") + ret0, _ := ret[0].(types0.AccAddress) + return ret0 +} + +// FeePayer indicates an expected call of FeePayer. +func (mr *MockFeeTxMockRecorder) FeePayer() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FeePayer", reflect.TypeOf((*MockFeeTx)(nil).FeePayer)) +} + +// GetFee mocks base method. +func (m *MockFeeTx) GetFee() types0.Coins { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetFee") + ret0, _ := ret[0].(types0.Coins) + return ret0 +} + +// GetFee indicates an expected call of GetFee. +func (mr *MockFeeTxMockRecorder) GetFee() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFee", reflect.TypeOf((*MockFeeTx)(nil).GetFee)) +} + +// GetGas mocks base method. +func (m *MockFeeTx) GetGas() uint64 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetGas") + ret0, _ := ret[0].(uint64) + return ret0 +} + +// GetGas indicates an expected call of GetGas. +func (mr *MockFeeTxMockRecorder) GetGas() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGas", reflect.TypeOf((*MockFeeTx)(nil).GetGas)) +} + +// GetMsgs mocks base method. +func (m *MockFeeTx) GetMsgs() []types0.Msg { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetMsgs") + ret0, _ := ret[0].([]types0.Msg) + return ret0 +} + +// GetMsgs indicates an expected call of GetMsgs. +func (mr *MockFeeTxMockRecorder) GetMsgs() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMsgs", reflect.TypeOf((*MockFeeTx)(nil).GetMsgs)) +} + +// ValidateBasic mocks base method. +func (m *MockFeeTx) ValidateBasic() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ValidateBasic") + ret0, _ := ret[0].(error) + return ret0 +} + +// ValidateBasic indicates an expected call of ValidateBasic. +func (mr *MockFeeTxMockRecorder) ValidateBasic() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateBasic", reflect.TypeOf((*MockFeeTx)(nil).ValidateBasic)) +} diff --git a/x/txfees/types/msg_fee_extension.go b/x/txfees/types/msg_fee_extension.go new file mode 100644 index 00000000000..a7958c67010 --- /dev/null +++ b/x/txfees/types/msg_fee_extension.go @@ -0,0 +1,11 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// MsgMinFeeExtension is an extension of the messages that defines a minimum fee +// denominated in base denom. +type MsgMinFeeExtension interface { + // GetRequiredMinBaseFee returns minimum fee for a message denominated in the base + // fee denom. + GetRequiredMinBaseFee() sdk.Dec +} From 607baaed7eeb87d4bb902471d66f4b0403d4a6b4 Mon Sep 17 00:00:00 2001 From: Roman Date: Sun, 24 Jul 2022 14:26:29 -0400 Subject: [PATCH 124/376] Revert "feat(txfees/incentives): minimum base fee for a message (#2202)" (#2226) This reverts commit 7f1d6175a864226e339c93951fd023e819ec96d3. --- CHANGELOG.md | 1 - go.mod | 4 +- x/incentives/types/msgs.go | 22 +---- x/txfees/keeper/feedecorator.go | 29 ++----- x/txfees/keeper/feedecorator_test.go | 78 ----------------- x/txfees/keeper/mocks/fee_tx_mock.go | 120 --------------------------- x/txfees/types/msg_fee_extension.go | 11 --- 7 files changed, 10 insertions(+), 255 deletions(-) delete mode 100644 x/txfees/keeper/mocks/fee_tx_mock.go delete mode 100644 x/txfees/types/msg_fee_extension.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1da79e1ab72..70f47dada78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,7 +66,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#1667](https://github.com/osmosis-labs/osmosis/pull/1673) Move wasm-bindings code out of app package into its own root level package. * [#2013](https://github.com/osmosis-labs/osmosis/pull/2013) Make `SetParams`, `SetPool`, `SetTotalLiquidity`, and `SetDenomLiquidity` GAMM APIs private * [#1857](https://github.com/osmosis-labs/osmosis/pull/1857) x/mint rename GetLastHalvenEpochNum to GetLastReductionEpochNum -* [#2202](https://github.com/osmosis-labs/osmosis/pull/2202) Minimum message fee for `CreateGauge`, `AddToGauge`; feedecorator `IsSufficientFee` API changes. ### Features diff --git a/go.mod b/go.mod index 7a741660236..6fba47841e0 100644 --- a/go.mod +++ b/go.mod @@ -34,11 +34,13 @@ require ( require ( github.com/alingse/asasalint v0.0.10 // indirect - github.com/golang/mock v1.6.0 // indirect github.com/sivchari/nosnakecase v1.5.0 // indirect go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.7.0 // indirect go.uber.org/zap v1.19.1 // indirect +) + +require ( 4d63.com/gochecknoglobals v0.1.0 // indirect filippo.io/edwards25519 v1.0.0-beta.2 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect diff --git a/x/incentives/types/msgs.go b/x/incentives/types/msgs.go index 8776c73be6f..4873cb9f174 100644 --- a/x/incentives/types/msgs.go +++ b/x/incentives/types/msgs.go @@ -5,7 +5,6 @@ import ( "time" lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" - txfeestypes "github.com/osmosis-labs/osmosis/v10/x/txfees/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -13,16 +12,9 @@ import ( const ( TypeMsgCreateGauge = "create_gauge" TypeMsgAddToGauge = "add_to_gauge" - - createGaugeMinBaseFee = 50 * 1_000_000 - addToGaugeMinBaseFee = 25 * 1_000_000 ) -var ( - _ sdk.Msg = &MsgCreateGauge{} - _ txfeestypes.MsgMinFeeExtension = &MsgCreateGauge{} - _ txfeestypes.MsgMinFeeExtension = &MsgAddToGauge{} -) +var _ sdk.Msg = &MsgCreateGauge{} // NewMsgCreateGauge creates a message to create a gauge with the provided parameters. func NewMsgCreateGauge(isPerpetual bool, owner sdk.AccAddress, distributeTo lockuptypes.QueryCondition, coins sdk.Coins, startTime time.Time, numEpochsPaidOver uint64) *MsgCreateGauge { @@ -36,12 +28,6 @@ func NewMsgCreateGauge(isPerpetual bool, owner sdk.AccAddress, distributeTo lock } } -// GetRequiredMinBaseFee returns the minimum fee for the message -// denominated in base fee denom. -func (m MsgCreateGauge) GetRequiredMinBaseFee() sdk.Dec { - return sdk.NewDec(createGaugeMinBaseFee) -} - // Route takes a create gauge message, then returns the RouterKey used for slashing. func (m MsgCreateGauge) Route() string { return RouterKey } @@ -98,12 +84,6 @@ func NewMsgAddToGauge(owner sdk.AccAddress, gaugeId uint64, rewards sdk.Coins) * } } -// GetRequiredMinBaseFee returns the minimum fee for the message -// denominated in base fee denom. -func (m MsgAddToGauge) GetRequiredMinBaseFee() sdk.Dec { - return sdk.NewDec(addToGaugeMinBaseFee) -} - // Route takes an add to gauge message, then returns the RouterKey used for slashing. func (m MsgAddToGauge) Route() string { return RouterKey } diff --git a/x/txfees/keeper/feedecorator.go b/x/txfees/keeper/feedecorator.go index 06e9efd713b..caa93cfee9a 100644 --- a/x/txfees/keeper/feedecorator.go +++ b/x/txfees/keeper/feedecorator.go @@ -5,7 +5,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/pkg/errors" "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper/txfee_filters" "github.com/osmosis-labs/osmosis/v10/x/txfees/types" @@ -83,7 +82,7 @@ func (mfd MempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b if len(feeCoins) != 1 { return ctx, sdkerrors.Wrapf(sdkerrors.ErrInsufficientFee, "no fee attached") } - err = mfd.TxFeesKeeper.IsSufficientFee(ctx, minBaseGasPrice, feeTx) + err = mfd.TxFeesKeeper.IsSufficientFee(ctx, minBaseGasPrice, feeTx.GetGas(), feeCoins[0]) if err != nil { return ctx, err } @@ -93,39 +92,23 @@ func (mfd MempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b return next(ctx, tx, simulate) } -// IsSufficientFee checks if the fee provided (in any asset), is worth enough osmo at current spot prices -// to pay the maximum of: -// - gas cost of this tx -// - minimum fee associated with any of the messages in this tx. N.B.: not all messages have such a fee. -func (k Keeper) IsSufficientFee(ctx sdk.Context, minBaseGasPrice sdk.Dec, tx sdk.FeeTx) error { +// IsSufficientFee checks if the feeCoin provided (in any asset), is worth enough osmo at current spot prices +// to pay the gas cost of this tx. +func (k Keeper) IsSufficientFee(ctx sdk.Context, minBaseGasPrice sdk.Dec, gasRequested uint64, feeCoin sdk.Coin) error { baseDenom, err := k.GetBaseDenom(ctx) if err != nil { return err } - feeCoins := tx.GetFee() - if len(feeCoins) != 1 { - return errors.Wrap(sdkerrors.ErrInsufficientFee, fmt.Sprintf("invalid number of fee tokens provided (%s); expected: 1, got: %d", feeCoins, len(feeCoins))) - } - feeCoin := feeCoins[0] // Determine the required fees by multiplying the required minimum gas // price by the gas limit, where fee = ceil(minGasPrice * gasLimit). - glDec := sdk.NewDec(int64(tx.GetGas())) - maxRequiredBaseFee := minBaseGasPrice.Mul(glDec).Ceil() - - for _, msg := range tx.GetMsgs() { - if feeMsg, ok := msg.(types.MsgMinFeeExtension); ok { - maxRequiredBaseFee = sdk.MaxDec(maxRequiredBaseFee, feeMsg.GetRequiredMinBaseFee()) - } - } - - requiredBaseFee := sdk.NewCoin(baseDenom, maxRequiredBaseFee.RoundInt()) + glDec := sdk.NewDec(int64(gasRequested)) + requiredBaseFee := sdk.NewCoin(baseDenom, minBaseGasPrice.Mul(glDec).Ceil().RoundInt()) convertedFee, err := k.ConvertToBaseToken(ctx, feeCoin) if err != nil { return err } - // check to ensure that the convertedFee should always be greater than or equal to the requireBaseFee if !(convertedFee.IsGTE(requiredBaseFee)) { return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFee, "insufficient fees; got: %s which converts to %s. required: %s", feeCoin, convertedFee, requiredBaseFee) diff --git a/x/txfees/keeper/feedecorator_test.go b/x/txfees/keeper/feedecorator_test.go index 4cb652c649c..1838a2c303d 100644 --- a/x/txfees/keeper/feedecorator_test.go +++ b/x/txfees/keeper/feedecorator_test.go @@ -8,12 +8,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" - gomock "github.com/golang/mock/gomock" - gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" - incentivestypes "github.com/osmosis-labs/osmosis/v10/x/incentives/types" "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper" - "github.com/osmosis-labs/osmosis/v10/x/txfees/keeper/mocks" "github.com/osmosis-labs/osmosis/v10/x/txfees/types" ) @@ -244,77 +240,3 @@ func (suite *KeeperTestSuite) TestFeeDecorator() { }) } } - -func (suite *KeeperTestSuite) TestIsSufficientFee() { - suite.SetupTest(false) - ctrl := gomock.NewController(suite.T()) - defer ctrl.Finish() - - ctx := suite.Ctx - txfeesKeeper := suite.App.TxFeesKeeper - - createGaugeFee := incentivestypes.MsgCreateGauge{}.GetRequiredMinBaseFee().RoundInt64() - - testcases := map[string]struct { - txFee int64 - gasFee int64 - msg []sdk.Msg - - minGasFee int64 - expectError bool - }{ - "tx fee above gas fee and msg fee - no error": { - txFee: createGaugeFee + 1, - gasFee: createGaugeFee - 1, - msg: []sdk.Msg{&incentivestypes.MsgCreateGauge{}}, - }, - "tx fee above gas fee but below msg fee - error": { - txFee: createGaugeFee - 1, - minGasFee: createGaugeFee - 2, - msg: []sdk.Msg{&incentivestypes.MsgCreateGauge{}}, - - expectError: true, - }, - "tx fee above msg fee but below gas fee - error": { - txFee: createGaugeFee + 2, - minGasFee: createGaugeFee + 5, - msg: []sdk.Msg{&incentivestypes.MsgCreateGauge{}}, - - expectError: true, - }, - "tx fee above gas fee and msg 1 but below msg 2 fee - error": { - txFee: createGaugeFee - 1, - minGasFee: createGaugeFee - 3, - msg: []sdk.Msg{&incentivestypes.MsgAddToGauge{}, &incentivestypes.MsgCreateGauge{}}, - - expectError: true, - }, - "tx fee above gas fee and msg with no fee - success": { - txFee: createGaugeFee, - minGasFee: createGaugeFee - 3, - msg: []sdk.Msg{&gammtypes.MsgExitPool{}}, - }, - } - - for name, tc := range testcases { - suite.Run(name, func() { - minBaseGasPrice := sdk.NewDec(tc.minGasFee) - - txMock := mocks.NewMockFeeTx(ctrl) - - txMock.EXPECT().GetFee().Return(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(tc.txFee)))).AnyTimes() - txMock.EXPECT().GetGas().Return(uint64(1)).AnyTimes() // minBaseGasPrice = 1 * tc.MinGasFee, for easy comparison with msg fee. - txMock.EXPECT().GetMsgs().Return([]sdk.Msg{ - &incentivestypes.MsgCreateGauge{}, - }).AnyTimes() - - err := txfeesKeeper.IsSufficientFee(ctx, minBaseGasPrice, txMock) - - if tc.expectError { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - } - }) - } -} diff --git a/x/txfees/keeper/mocks/fee_tx_mock.go b/x/txfees/keeper/mocks/fee_tx_mock.go deleted file mode 100644 index 4cd2451b530..00000000000 --- a/x/txfees/keeper/mocks/fee_tx_mock.go +++ /dev/null @@ -1,120 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: /root/workspace/cosmos-sdk/types/tx_msg.go - -// Package mock_types is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - types0 "github.com/cosmos/cosmos-sdk/types" - gomock "github.com/golang/mock/gomock" -) - - -// MockFeeTx is a mock of FeeTx interface. -type MockFeeTx struct { - ctrl *gomock.Controller - recorder *MockFeeTxMockRecorder -} - -// MockFeeTxMockRecorder is the mock recorder for MockFeeTx. -type MockFeeTxMockRecorder struct { - mock *MockFeeTx -} - -// NewMockFeeTx creates a new mock instance. -func NewMockFeeTx(ctrl *gomock.Controller) *MockFeeTx { - mock := &MockFeeTx{ctrl: ctrl} - mock.recorder = &MockFeeTxMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFeeTx) EXPECT() *MockFeeTxMockRecorder { - return m.recorder -} - -// FeeGranter mocks base method. -func (m *MockFeeTx) FeeGranter() types0.AccAddress { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FeeGranter") - ret0, _ := ret[0].(types0.AccAddress) - return ret0 -} - -// FeeGranter indicates an expected call of FeeGranter. -func (mr *MockFeeTxMockRecorder) FeeGranter() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FeeGranter", reflect.TypeOf((*MockFeeTx)(nil).FeeGranter)) -} - -// FeePayer mocks base method. -func (m *MockFeeTx) FeePayer() types0.AccAddress { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FeePayer") - ret0, _ := ret[0].(types0.AccAddress) - return ret0 -} - -// FeePayer indicates an expected call of FeePayer. -func (mr *MockFeeTxMockRecorder) FeePayer() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FeePayer", reflect.TypeOf((*MockFeeTx)(nil).FeePayer)) -} - -// GetFee mocks base method. -func (m *MockFeeTx) GetFee() types0.Coins { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetFee") - ret0, _ := ret[0].(types0.Coins) - return ret0 -} - -// GetFee indicates an expected call of GetFee. -func (mr *MockFeeTxMockRecorder) GetFee() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFee", reflect.TypeOf((*MockFeeTx)(nil).GetFee)) -} - -// GetGas mocks base method. -func (m *MockFeeTx) GetGas() uint64 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetGas") - ret0, _ := ret[0].(uint64) - return ret0 -} - -// GetGas indicates an expected call of GetGas. -func (mr *MockFeeTxMockRecorder) GetGas() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGas", reflect.TypeOf((*MockFeeTx)(nil).GetGas)) -} - -// GetMsgs mocks base method. -func (m *MockFeeTx) GetMsgs() []types0.Msg { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMsgs") - ret0, _ := ret[0].([]types0.Msg) - return ret0 -} - -// GetMsgs indicates an expected call of GetMsgs. -func (mr *MockFeeTxMockRecorder) GetMsgs() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMsgs", reflect.TypeOf((*MockFeeTx)(nil).GetMsgs)) -} - -// ValidateBasic mocks base method. -func (m *MockFeeTx) ValidateBasic() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidateBasic") - ret0, _ := ret[0].(error) - return ret0 -} - -// ValidateBasic indicates an expected call of ValidateBasic. -func (mr *MockFeeTxMockRecorder) ValidateBasic() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateBasic", reflect.TypeOf((*MockFeeTx)(nil).ValidateBasic)) -} diff --git a/x/txfees/types/msg_fee_extension.go b/x/txfees/types/msg_fee_extension.go deleted file mode 100644 index a7958c67010..00000000000 --- a/x/txfees/types/msg_fee_extension.go +++ /dev/null @@ -1,11 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// MsgMinFeeExtension is an extension of the messages that defines a minimum fee -// denominated in base denom. -type MsgMinFeeExtension interface { - // GetRequiredMinBaseFee returns minimum fee for a message denominated in the base - // fee denom. - GetRequiredMinBaseFee() sdk.Dec -} From bc78aded942aba8f32d14843eaf805946a0b4d51 Mon Sep 17 00:00:00 2001 From: JeremyParish69 <95667791+JeremyParish69@users.noreply.github.com> Date: Mon, 25 Jul 2022 18:54:13 -0600 Subject: [PATCH 125/376] Update chain schema (#2235) * add params to chain schema "cosmos_sdk_version": "0.45", "tendermint_version": "0.34", "cosmwasm_version": "0.24", "cosmwasm_enabled": true * minor fix "cosmos_sdk_version": "0.45", "tendermint_version": "0.34", "cosmwasm_version": "0.24", "cosmwasm_enabled": true --- chain.schema.json | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/chain.schema.json b/chain.schema.json index 71a75536ef3..25644961668 100644 --- a/chain.schema.json +++ b/chain.schema.json @@ -7,6 +7,10 @@ "binaries": { "linux/amd64": "https://github.com/osmosis-labs/osmosis/releases/download/v10.0.0/osmosis-10.0.0-linux-amd64", "linux/arm64": "https://github.com/osmosis-labs/osmosis/releases/download/v10.0.0/osmosis-10.0.0-linux-arm64" - } + }, + "cosmos_sdk_version": "0.45", + "tendermint_version": "0.34", + "cosmwasm_version": "0.24", + "cosmwasm_enabled": true } -} \ No newline at end of file +} From cbfde1148a329dee2e1020748f8212d385c9e4cd Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 26 Jul 2022 12:28:06 -0400 Subject: [PATCH 126/376] feat(incentives)!: create gauge and add to gauge fee charge (#2227) * feat(incentives)!: create gauge and add to gauge fee charge * initialize txfees keeper before incentives * finish TestChargeFee * refactor to charge fee in message server * more tests * clean up * test balances * test create gauge fees (#2228) * test create gauge fees * add mod account to test * test create gauge fees * add mod account to test * move to msg server * merge * add comments * account keeper comment * fix TestCreateGaugeFee * apply appparams.BaseCoinUnit * remove txfees keeper from incentives and revert order * clean up * remove unused keepers fromm incentives keeper * Update x/incentives/keeper/gauge.go * Update x/incentives/keeper/gauge.go * clean up * fixture names * chargeFeeIfSufficientFeeDenomBalance test name * changelog * comment * finished tests (#2230) * finished tests * use keeper instead of math * remove unused tests * clean up * sim only allow accounts with enough to pay fee * lint * move fee to types and reuse in simulation (#2234) Co-authored-by: Adam Tucker Co-authored-by: Adam Tucker --- CHANGELOG.md | 1 + app/keepers/keepers.go | 1 + x/incentives/keeper/export_test.go | 9 +- x/incentives/keeper/gauge.go | 19 ++ x/incentives/keeper/gauge_test.go | 96 ++++++++++ x/incentives/keeper/keeper.go | 4 +- x/incentives/keeper/msg_server.go | 8 + x/incentives/keeper/msg_server_test.go | 243 +++++++++++++++++++++++++ x/incentives/simulation/operations.go | 6 +- x/incentives/types/expected_keepers.go | 6 + x/incentives/types/gauge.go | 7 + 11 files changed, 395 insertions(+), 5 deletions(-) create mode 100644 x/incentives/keeper/msg_server_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 70f47dada78..95766a487b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#2016](https://github.com/osmosis-labs/osmosis/pull/2016) Add fixed 10000 gas cost for each Balancer swap * [#2147](https://github.com/osmosis-labs/osmosis/pull/2147) Set MaxAgeNumBlocks in v11 Upgrade Handler to two weeks. * [#2193](https://github.com/osmosis-labs/osmosis/pull/2193) Add TwapKeeper to the Osmosis app +* [#2227](https://github.com/osmosis-labs/osmosis/pull/2227) Enable charging fee in base denom for `CreateGauge` and `AddToGauge`. #### Golang API breaks diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index aeecb95a0e5..3369228ba26 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -267,6 +267,7 @@ func (appKeepers *AppKeepers) InitNormalKeepers( appKeepers.BankKeeper, appKeepers.LockupKeeper, appKeepers.EpochsKeeper, + appKeepers.DistrKeeper, ) appKeepers.SuperfluidKeeper = superfluidkeeper.NewKeeper( diff --git a/x/incentives/keeper/export_test.go b/x/incentives/keeper/export_test.go index ac465da4fe9..9eeb06ac191 100644 --- a/x/incentives/keeper/export_test.go +++ b/x/incentives/keeper/export_test.go @@ -7,8 +7,8 @@ import ( ) // AddGaugeRefByKey appends the provided gauge ID into an array associated with the provided key. -func (k Keeper) AddGaugeRefByKey(ctx sdk.Context, key []byte, guageID uint64) error { - return k.addGaugeRefByKey(ctx, key, guageID) +func (k Keeper) AddGaugeRefByKey(ctx sdk.Context, key []byte, gaugeID uint64) error { + return k.addGaugeRefByKey(ctx, key, gaugeID) } // DeleteGaugeRefByKey removes the provided gauge ID from an array associated with the provided key. @@ -35,3 +35,8 @@ func (k Keeper) MoveUpcomingGaugeToActiveGauge(ctx sdk.Context, gauge types.Gaug func (k Keeper) MoveActiveGaugeToFinishedGauge(ctx sdk.Context, gauge types.Gauge) error { return k.moveActiveGaugeToFinishedGauge(ctx, gauge) } + +// ChargeFeeIfSufficientFeeDenomBalance see chargeFeeIfSufficientFeeDenomBalance spec. +func (k Keeper) ChargeFeeIfSufficientFeeDenomBalance(ctx sdk.Context, address sdk.AccAddress, fee sdk.Int, gaugeCoins sdk.Coins) error { + return k.chargeFeeIfSufficientFeeDenomBalance(ctx, address, fee, gaugeCoins) +} diff --git a/x/incentives/keeper/gauge.go b/x/incentives/keeper/gauge.go index 412ef436f69..8a8638bc243 100644 --- a/x/incentives/keeper/gauge.go +++ b/x/incentives/keeper/gauge.go @@ -7,9 +7,11 @@ import ( "strings" "time" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/gogo/protobuf/proto" db "github.com/tendermint/tm-db" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" epochtypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "github.com/osmosis-labs/osmosis/v10/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" @@ -278,3 +280,20 @@ func (k Keeper) GetEpochInfo(ctx sdk.Context) epochtypes.EpochInfo { params := k.GetParams(ctx) return k.ek.GetEpochInfo(ctx, params.DistrEpochIdentifier) } + +// chargeFeeIfSufficientFeeDenomBalance charges fee in the base denom on the address if the address has +// balance that is less than fee + amount of the coin from gaugeCoins that is of base denom. +// gaugeCoins might not have a coin of tx base denom. In that case, fee is only compared to balance. +// The fee is sent to the community pool. +// Returns nil on success, error otherwise. +func (k Keeper) chargeFeeIfSufficientFeeDenomBalance(ctx sdk.Context, address sdk.AccAddress, fee sdk.Int, gaugeCoins sdk.Coins) (err error) { + totalCost := gaugeCoins.AmountOf(appparams.BaseCoinUnit).Add(fee) + accountBalance := k.bk.GetBalance(ctx, address, appparams.BaseCoinUnit).Amount + if accountBalance.LT(totalCost) { + return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "account's balance of %s (%s) is less than the total cost of the message (%s)", appparams.BaseCoinUnit, accountBalance, totalCost) + } + if err := k.dk.FundCommunityPool(ctx, sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, fee)), address); err != nil { + return err + } + return nil +} diff --git a/x/incentives/keeper/gauge_test.go b/x/incentives/keeper/gauge_test.go index 45579973715..2e36c881846 100644 --- a/x/incentives/keeper/gauge_test.go +++ b/x/incentives/keeper/gauge_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/suite" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" "github.com/osmosis-labs/osmosis/v10/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" @@ -237,3 +238,98 @@ func (suite *KeeperTestSuite) TestGaugeOperations() { } } } + +func (suite *KeeperTestSuite) TestChargeFeeIfSufficientFeeDenomBalance() { + const baseFee = int64(100) + + testcases := map[string]struct { + accountBalanceToFund sdk.Coin + feeToCharge int64 + gaugeCoins sdk.Coins + + expectError bool + }{ + "fee + base denom gauge coin == acount balance, success": { + accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + feeToCharge: baseFee / 2, + gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + }, + "fee + base denom gauge coin < acount balance, success": { + accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + feeToCharge: baseFee/2 - 1, + gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + }, + "fee + base denom gauge coin > acount balance, error": { + accountBalanceToFund: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee)), + feeToCharge: baseFee/2 + 1, + gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + + expectError: true, + }, + "fee + base denom gauge coin < acount balance, custom values, success": { + accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(11793193112)), + feeToCharge: 55, + gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(328812))), + }, + "account funded with coins other than base denom, error": { + accountBalanceToFund: sdk.NewCoin("usdc", sdk.NewInt(baseFee)), + feeToCharge: baseFee, + gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + + expectError: true, + }, + "fee == account balance, no gauge coins, success": { + accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + feeToCharge: baseFee, + }, + "gauge coins == account balance, no fee, success": { + accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee))), + }, + "fee == account balance, gauge coins in denom other than base, success": { + accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + feeToCharge: baseFee, + gaugeCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdk.NewInt(baseFee*2))), + }, + "fee + gauge coins == account balance, multiple gauge coins, one in denom other than base, success": { + accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + feeToCharge: baseFee / 2, + gaugeCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdk.NewInt(baseFee*2)), sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + }, + } + + for name, tc := range testcases { + suite.Run(name, func() { + suite.SetupTest() + + testAccount := suite.TestAccs[0] + + ctx := suite.Ctx + incentivesKeepers := suite.App.IncentivesKeeper + bankKeeper := suite.App.BankKeeper + + // Pre-fund account. + suite.FundAcc(testAccount, sdk.NewCoins(tc.accountBalanceToFund)) + + oldBalanceAmount := bankKeeper.GetBalance(ctx, testAccount, appparams.DefaultBondDenom).Amount + + // System under test. + err := incentivesKeepers.ChargeFeeIfSufficientFeeDenomBalance(ctx, testAccount, sdk.NewInt(tc.feeToCharge), tc.gaugeCoins) + + // Assertions. + newBalanceAmount := bankKeeper.GetBalance(ctx, testAccount, appparams.DefaultBondDenom).Amount + if tc.expectError { + suite.Require().Error(err) + + // check account balance unchanged + suite.Require().Equal(oldBalanceAmount, newBalanceAmount) + } else { + suite.Require().NoError(err) + + // check account balance changed. + expectedNewBalanceAmount := oldBalanceAmount.Sub(sdk.NewInt(tc.feeToCharge)) + suite.Require().Equal(expectedNewBalanceAmount.String(), newBalanceAmount.String()) + } + }) + } +} diff --git a/x/incentives/keeper/keeper.go b/x/incentives/keeper/keeper.go index 09c80d185a5..d21abad3579 100644 --- a/x/incentives/keeper/keeper.go +++ b/x/incentives/keeper/keeper.go @@ -22,10 +22,11 @@ type Keeper struct { bk types.BankKeeper lk types.LockupKeeper ek types.EpochKeeper + dk types.DistrKeeper } // NewKeeper returns a new instance of the incentive module keeper struct. -func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey, paramSpace paramtypes.Subspace, bk types.BankKeeper, lk types.LockupKeeper, ek types.EpochKeeper) *Keeper { +func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey, paramSpace paramtypes.Subspace, bk types.BankKeeper, lk types.LockupKeeper, ek types.EpochKeeper, dk types.DistrKeeper) *Keeper { if !paramSpace.HasKeyTable() { paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) } @@ -37,6 +38,7 @@ func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey, paramSpace paramtypes.Sub bk: bk, lk: lk, ek: ek, + dk: dk, } } diff --git a/x/incentives/keeper/msg_server.go b/x/incentives/keeper/msg_server.go index bfcffaf99e0..c966ab5f4bb 100644 --- a/x/incentives/keeper/msg_server.go +++ b/x/incentives/keeper/msg_server.go @@ -33,6 +33,10 @@ func (server msgServer) CreateGauge(goCtx context.Context, msg *types.MsgCreateG return nil, err } + if err := server.keeper.chargeFeeIfSufficientFeeDenomBalance(ctx, owner, types.CreateGaugeFee, msg.Coins); err != nil { + return nil, err + } + gaugeID, err := server.keeper.CreateGauge(ctx, msg.IsPerpetual, owner, msg.Coins, msg.DistributeTo, msg.StartTime, msg.NumEpochsPaidOver) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) @@ -56,6 +60,10 @@ func (server msgServer) AddToGauge(goCtx context.Context, msg *types.MsgAddToGau if err != nil { return nil, err } + + if err := server.keeper.chargeFeeIfSufficientFeeDenomBalance(ctx, owner, types.AddToGaugeFee, msg.Rewards); err != nil { + return nil, err + } err = server.keeper.AddToGaugeRewards(ctx, owner, msg.Rewards, msg.GaugeId) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) diff --git a/x/incentives/keeper/msg_server_test.go b/x/incentives/keeper/msg_server_test.go new file mode 100644 index 00000000000..497a5d2d92b --- /dev/null +++ b/x/incentives/keeper/msg_server_test.go @@ -0,0 +1,243 @@ +package keeper_test + +import ( + "time" + + "github.com/stretchr/testify/suite" + + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + + appparams "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/x/incentives/keeper" + "github.com/osmosis-labs/osmosis/v10/x/incentives/types" + lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var _ = suite.TestingSuite(nil) + +func (suite *KeeperTestSuite) TestCreateGauge_Fee() { + tests := []struct { + name string + accountBalanceToFund sdk.Coins + gaugeAddition sdk.Coins + expectedEndBalance sdk.Coins + isPerpetual bool + isModuleAccount bool + expectErr bool + }{ + { + name: "user creates a non-perpetual gauge and fills gauge with all remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(60000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + }, + { + name: "user creates a non-perpetual gauge and fills gauge with some remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + }, + { + name: "user with multiple denoms creates a non-perpetual gauge and fills gauge with some remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + }, + { + name: "module account creates a perpetual gauge and fills gauge with some remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + isPerpetual: true, + isModuleAccount: true, + }, + { + name: "user with multiple denoms creates a perpetual gauge and fills gauge with some remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + isPerpetual: true, + }, + { + name: "user tries to create a non-perpetual gauge but does not have enough funds to pay for the create gauge fee", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(40000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + expectErr: true, + }, + { + name: "user tries to create a non-perpetual gauge but does not have the correct fee denom", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(60000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(10000000))), + expectErr: true, + }, + { + name: "one user tries to create a gauge, has enough funds to pay for the create gauge fee but not enough to fill the gauge", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(60000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(30000000))), + expectErr: true, + }, + } + + for _, tc := range tests { + suite.SetupTest() + + testAccountPubkey := secp256k1.GenPrivKeyFromSecret([]byte("acc")).PubKey() + testAccountAddress := sdk.AccAddress(testAccountPubkey.Address()) + + ctx := suite.Ctx + bankKeeper := suite.App.BankKeeper + accountKeeper := suite.App.AccountKeeper + msgServer := keeper.NewMsgServerImpl(suite.App.IncentivesKeeper) + + suite.FundAcc(testAccountAddress, tc.accountBalanceToFund) + + if tc.isModuleAccount { + modAcc := authtypes.NewModuleAccount(authtypes.NewBaseAccount(testAccountAddress, testAccountPubkey, 1, 0), + "module", + "permission", + ) + accountKeeper.SetModuleAccount(ctx, modAcc) + } + + suite.SetupManyLocks(1, defaultLiquidTokens, defaultLPTokens, defaultLockDuration) + distrTo := lockuptypes.QueryCondition{ + LockQueryType: lockuptypes.ByDuration, + Denom: defaultLPDenom, + Duration: defaultLockDuration, + } + + msg := &types.MsgCreateGauge{ + IsPerpetual: tc.isPerpetual, + Owner: testAccountAddress.String(), + DistributeTo: distrTo, + Coins: tc.gaugeAddition, + StartTime: time.Now(), + NumEpochsPaidOver: 1, + } + // System under test. + _, err := msgServer.CreateGauge(sdk.WrapSDKContext(ctx), msg) + + if tc.expectErr { + suite.Require().Error(err) + } else { + suite.Require().NoError(err) + } + + balanceAmount := bankKeeper.GetAllBalances(ctx, testAccountAddress) + + if tc.expectErr { + suite.Require().Equal(tc.accountBalanceToFund.String(), balanceAmount.String(), "test: %v", tc.name) + } else { + fee := sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, types.CreateGaugeFee)) + accountBalance := tc.accountBalanceToFund.Sub(tc.gaugeAddition) + finalAccountBalance := accountBalance.Sub(fee) + suite.Require().Equal(finalAccountBalance.String(), balanceAmount.String(), "test: %v", tc.name) + } + } +} + +func (suite *KeeperTestSuite) TestAddToGauge_Fee() { + + tests := []struct { + name string + accountBalanceToFund sdk.Coins + gaugeAddition sdk.Coins + nonexistentGauge bool + isPerpetual bool + isModuleAccount bool + expectErr bool + }{ + { + name: "user creates a non-perpetual gauge and fills gauge with all remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(35000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + }, + { + name: "user creates a non-perpetual gauge and fills gauge with some remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + }, + { + name: "user with multiple denoms creates a non-perpetual gauge and fills gauge with some remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + }, + { + name: "module account creates a perpetual gauge and fills gauge with some remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + isPerpetual: true, + isModuleAccount: true, + }, + { + name: "user with multiple denoms creates a perpetual gauge and fills gauge with some remaining tokens", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + isPerpetual: true, + }, + { + name: "user tries to create a non-perpetual gauge but does not have enough funds to pay for the create gauge fee", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(20000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + expectErr: true, + }, + { + name: "user tries to add to a non-perpetual gauge but does not have the correct fee denom", + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(60000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(10000000))), + expectErr: true, + }, + } + + for _, tc := range tests { + suite.SetupTest() + + testAccountPubkey := secp256k1.GenPrivKeyFromSecret([]byte("acc")).PubKey() + testAccountAddress := sdk.AccAddress(testAccountPubkey.Address()) + + ctx := suite.Ctx + bankKeeper := suite.App.BankKeeper + incentivesKeeper := suite.App.IncentivesKeeper + accountKeeper := suite.App.AccountKeeper + msgServer := keeper.NewMsgServerImpl(incentivesKeeper) + + suite.FundAcc(testAccountAddress, tc.accountBalanceToFund) + + if tc.isModuleAccount { + modAcc := authtypes.NewModuleAccount(authtypes.NewBaseAccount(testAccountAddress, testAccountPubkey, 1, 0), + "module", + "permission", + ) + accountKeeper.SetModuleAccount(ctx, modAcc) + } + + // System under test. + coins := sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(500000000))) + gaugeID, _, _, _ := suite.SetupNewGauge(true, coins) + if tc.nonexistentGauge { + gaugeID = incentivesKeeper.GetLastGaugeID(ctx) + 1 + } + msg := &types.MsgAddToGauge{ + Owner: testAccountAddress.String(), + GaugeId: gaugeID, + Rewards: tc.gaugeAddition, + } + + _, err := msgServer.AddToGauge(sdk.WrapSDKContext(ctx), msg) + + if tc.expectErr { + suite.Require().Error(err) + } else { + suite.Require().NoError(err) + } + + bal := bankKeeper.GetAllBalances(ctx, testAccountAddress) + + if tc.expectErr { + suite.Require().Equal(tc.accountBalanceToFund.String(), bal.String(), "test: %v", tc.name) + } else { + fee := sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, types.AddToGaugeFee)) + accountBalance := tc.accountBalanceToFund.Sub(tc.gaugeAddition) + finalAccountBalance := accountBalance.Sub(fee) + suite.Require().Equal(finalAccountBalance.String(), bal.String(), "test: %v", tc.name) + } + } +} diff --git a/x/incentives/simulation/operations.go b/x/incentives/simulation/operations.go index 10b281f4a09..81d4e0854c7 100644 --- a/x/incentives/simulation/operations.go +++ b/x/incentives/simulation/operations.go @@ -18,6 +18,8 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + appparams "github.com/osmosis-labs/osmosis/v10/app/params" ) // Simulation operation weights constants. @@ -115,7 +117,7 @@ func SimulateMsgCreateGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankK ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { simAccount, _ := simtypes.RandomAcc(r, accs) simCoins := bk.SpendableCoins(ctx, simAccount.Address) - if simCoins.Len() <= 0 { + if simCoins.Len() <= 0 || simCoins.AmountOf(appparams.BaseCoinUnit).LT(types.CreateGaugeFee) { return simtypes.NoOpMsg( types.ModuleName, types.TypeMsgCreateGauge, "Account have no coin"), nil, nil } @@ -154,7 +156,7 @@ func SimulateMsgAddToGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankKe ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { simAccount, _ := simtypes.RandomAcc(r, accs) simCoins := bk.SpendableCoins(ctx, simAccount.Address) - if simCoins.Len() <= 0 { + if simCoins.Len() <= 0 || simCoins.AmountOf(appparams.BaseCoinUnit).LT(types.AddToGaugeFee) { return simtypes.NoOpMsg( types.ModuleName, types.TypeMsgAddToGauge, "Account have no coin"), nil, nil } diff --git a/x/incentives/types/expected_keepers.go b/x/incentives/types/expected_keepers.go index e377908df79..5319039c3fd 100644 --- a/x/incentives/types/expected_keepers.go +++ b/x/incentives/types/expected_keepers.go @@ -12,6 +12,7 @@ import ( // BankKeeper defines the expected interface needed to retrieve account balances. type BankKeeper interface { GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin HasSupply(ctx sdk.Context, denom string) bool @@ -36,3 +37,8 @@ type LockupKeeper interface { type EpochKeeper interface { GetEpochInfo(ctx sdk.Context, identifier string) epochstypes.EpochInfo } + +// DistrKeeper defines the contract needed to be fulfilled for distribution keeper. +type DistrKeeper interface { + FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error +} diff --git a/x/incentives/types/gauge.go b/x/incentives/types/gauge.go index bb0f97d087c..ec3b112d31f 100644 --- a/x/incentives/types/gauge.go +++ b/x/incentives/types/gauge.go @@ -8,6 +8,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +var ( + // CreateGaugeFee is the fee required to create a new gauge. + CreateGaugeFee = sdk.NewInt(50 * 1_000_000) + // AddToGagugeFee is the fee required to add to gauge. + AddToGaugeFee = sdk.NewInt(25 * 1_000_000) +) + // NewGauge creates a new gauge struct given the required gauge parameters. func NewGauge(id uint64, isPerpetual bool, distrTo lockuptypes.QueryCondition, coins sdk.Coins, startTime time.Time, numEpochsPaidOver uint64, filledEpochs uint64, distrCoins sdk.Coins) Gauge { return Gauge{ From 882c8d53c6ae655e234540afa187e2e7332f43bc Mon Sep 17 00:00:00 2001 From: Xiangan He <76530366+xBalbinus@users.noreply.github.com> Date: Tue, 26 Jul 2022 14:54:31 -0400 Subject: [PATCH 127/376] docs: all module README.mds relocated into module root (#2171) * rebase to main * markdown lint fixes * doc lint fixes --- x/epochs/README.md | 178 ++- x/epochs/spec/README.md | 186 --- x/gamm/{spec => }/README.md | 0 x/incentives/{spec => }/README.md | 0 x/lockup/README.md | 1115 ++++++++++++++++- x/lockup/spec/README.md | 1109 ---------------- x/pool-incentives/{spec => }/README.md | 21 +- x/superfluid/{spec => }/README.md | 2 +- x/superfluid/{spec => }/superfluiddiagram.png | Bin x/txfees/README.md | 121 +- x/txfees/spec/README.md | 49 - 11 files changed, 1342 insertions(+), 1439 deletions(-) delete mode 100644 x/epochs/spec/README.md rename x/gamm/{spec => }/README.md (100%) rename x/incentives/{spec => }/README.md (100%) delete mode 100644 x/lockup/spec/README.md rename x/pool-incentives/{spec => }/README.md (92%) rename x/superfluid/{spec => }/README.md (99%) rename x/superfluid/{spec => }/superfluiddiagram.png (100%) delete mode 100644 x/txfees/spec/README.md diff --git a/x/epochs/README.md b/x/epochs/README.md index fb8a32a42a1..95726a791ba 100644 --- a/x/epochs/README.md +++ b/x/epochs/README.md @@ -1,4 +1,25 @@ -# x/epochs +# Epochs + +## Abstract + +Often in the SDK, we would like to run certain code every-so often. The +purpose of `epochs` module is to allow other modules to set that they +would like to be signaled once every period. So another module can +specify it wants to execute code once a week, starting at UTC-time = x. +`epochs` creates a generalized epoch interface to other modules so that +they can easily be signalled upon such events. + +## Contents + +1. **[Concept](#concepts)** +2. **[State](#state)** +3. **[Events](#events)** +4. **[Keeper](#keeper)** +5. **[Hooks](#hooks)** +6. **[Queries](#queries)** +7. **[Downtime Recovery](#downtime-recovery)** + +## Concepts The epochs module defines on-chain timers, that execute at fixed time intervals. Other SDK modules can then register logic to be executed at the timer ticks. @@ -8,3 +29,158 @@ Every timer has a unique identifier. Every epoch will have a start time, and an end time, where `end time = start time + timer interval`. On Osmosis mainnet, we only utilize one identifier, with a time interval of `one day`. +The timer will tick at the first block whose blocktime is greater than the timer end time, +and set the start as the prior timer end time. (Notably, its not set to the block time!) +This means that if the chain has been down for awhile, you will get one timer tick per block, +until the timer has caught up. + +## State + +The Epochs module keeps a single [`EpochInfo`](https://github.com/osmosis-labs/osmosis/blob/b4befe4f3eb97ebb477323234b910c4afafab9b7/proto/osmosis/epochs/genesis.proto#L12) per identifier. +This contains the current state of the timer with the corresponding identifier. +Its fields are modified at every timer tick. +EpochInfos are initialized as part of genesis initialization or upgrade logic, +and are only modified on begin blockers. + +## Events + +The `epochs` module emits the following events: + +### BeginBlocker + +| Type | Attribute Key | Attribute Value | +| --------------| ---------------| -----------------| +| epoch\_start | epoch\_number | {epoch\_number} | +| epoch\_start | start\_time | {start\_time} | + +### EndBlocker + +| Type | Attribute Key | Attribute Value | +| ------------| ---------------| -----------------| +| epoch\_end | epoch\_number | {epoch\_number} | + +## Keepers + +### Keeper functions + +Epochs keeper module provides utility functions to manage epochs. + +```go +// Keeper is the interface for lockup module keeper +type Keeper interface { + // GetEpochInfo returns epoch info by identifier + GetEpochInfo(ctx sdk.Context, identifier string) types.EpochInfo + // SetEpochInfo set epoch info + SetEpochInfo(ctx sdk.Context, epoch types.EpochInfo) + // DeleteEpochInfo delete epoch info + DeleteEpochInfo(ctx sdk.Context, identifier string) + // IterateEpochInfo iterate through epochs + IterateEpochInfo(ctx sdk.Context, fn func(index int64, epochInfo types.EpochInfo) (stop bool)) + // Get all epoch infos + AllEpochInfos(ctx sdk.Context) []types.EpochInfo +} +``` + +## Hooks + +```go + // the first block whose timestamp is after the duration is counted as the end of the epoch + AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) + // new epoch is next block of epoch end block + BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) +``` + +### How modules receive hooks + +On hook receiver function of other modules, they need to filter +`epochIdentifier` and only do executions for only specific +epochIdentifier. Filtering epochIdentifier could be in `Params` of other +modules so that they can be modified by governance. + +This is the standard dev UX of this: +```golang +func (k MyModuleKeeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) { + params := k.GetParams(ctx) + if epochIdentifier == params.DistrEpochIdentifier { + // my logic + } +} +``` + +### Panic isolation + +If a given epoch hook panics, its state update is reverted, but we keep +proceeding through the remaining hooks. This allows more advanced epoch +logic to be used, without concern over state machine halting, or halting +subsequent modules. + +This does mean that if there is behavior you expect from a prior epoch +hook, and that epoch hook reverted, your hook may also have an issue. So +do keep in mind "what if a prior hook didn't get executed" in the safety +checks you consider for a new epoch hook. + +## Queries + +Epochs module is providing below queries to check the module's state. + +```protobuf +service Query { + // EpochInfos provide running epochInfos + rpc EpochInfos(QueryEpochsInfoRequest) returns (QueryEpochsInfoResponse) {} + // CurrentEpoch provide current epoch of specified identifier + rpc CurrentEpoch(QueryCurrentEpochRequest) returns (QueryCurrentEpochResponse) {} +} +``` + +### Epoch Infos + +Query the currently running epochInfos + +```sh +osmosisd query epochs epoch-infos +``` +::: details Example + +An example output: + +```sh +epochs: +- current_epoch: "183" + current_epoch_start_height: "2438409" + current_epoch_start_time: "2021-12-18T17:16:09.898160996Z" + duration: 86400s + epoch_counting_started: true + identifier: day + start_time: "2021-06-18T17:00:00Z" +- current_epoch: "26" + current_epoch_start_height: "2424854" + current_epoch_start_time: "2021-12-17T17:02:07.229632445Z" + duration: 604800s + epoch_counting_started: true + identifier: week + start_time: "2021-06-18T17:00:00Z" +``` +::: + +### Current Epoch + + +Query the current epoch by the specified identifier + +```sh +osmosisd query epochs current-epoch [identifier] +``` + +::: details Example + +Query the current `day` epoch: + +```sh +osmosisd query epochs current-epoch day +``` + +Which in this example outputs: + +```sh +current_epoch: "183" +``` diff --git a/x/epochs/spec/README.md b/x/epochs/spec/README.md deleted file mode 100644 index 95726a791ba..00000000000 --- a/x/epochs/spec/README.md +++ /dev/null @@ -1,186 +0,0 @@ -# Epochs - -## Abstract - -Often in the SDK, we would like to run certain code every-so often. The -purpose of `epochs` module is to allow other modules to set that they -would like to be signaled once every period. So another module can -specify it wants to execute code once a week, starting at UTC-time = x. -`epochs` creates a generalized epoch interface to other modules so that -they can easily be signalled upon such events. - -## Contents - -1. **[Concept](#concepts)** -2. **[State](#state)** -3. **[Events](#events)** -4. **[Keeper](#keeper)** -5. **[Hooks](#hooks)** -6. **[Queries](#queries)** -7. **[Downtime Recovery](#downtime-recovery)** - -## Concepts - -The epochs module defines on-chain timers, that execute at fixed time intervals. -Other SDK modules can then register logic to be executed at the timer ticks. -We refer to the period in between two timer ticks as an "epoch". - -Every timer has a unique identifier. -Every epoch will have a start time, and an end time, where `end time = start time + timer interval`. -On Osmosis mainnet, we only utilize one identifier, with a time interval of `one day`. - -The timer will tick at the first block whose blocktime is greater than the timer end time, -and set the start as the prior timer end time. (Notably, its not set to the block time!) -This means that if the chain has been down for awhile, you will get one timer tick per block, -until the timer has caught up. - -## State - -The Epochs module keeps a single [`EpochInfo`](https://github.com/osmosis-labs/osmosis/blob/b4befe4f3eb97ebb477323234b910c4afafab9b7/proto/osmosis/epochs/genesis.proto#L12) per identifier. -This contains the current state of the timer with the corresponding identifier. -Its fields are modified at every timer tick. -EpochInfos are initialized as part of genesis initialization or upgrade logic, -and are only modified on begin blockers. - -## Events - -The `epochs` module emits the following events: - -### BeginBlocker - -| Type | Attribute Key | Attribute Value | -| --------------| ---------------| -----------------| -| epoch\_start | epoch\_number | {epoch\_number} | -| epoch\_start | start\_time | {start\_time} | - -### EndBlocker - -| Type | Attribute Key | Attribute Value | -| ------------| ---------------| -----------------| -| epoch\_end | epoch\_number | {epoch\_number} | - -## Keepers - -### Keeper functions - -Epochs keeper module provides utility functions to manage epochs. - -```go -// Keeper is the interface for lockup module keeper -type Keeper interface { - // GetEpochInfo returns epoch info by identifier - GetEpochInfo(ctx sdk.Context, identifier string) types.EpochInfo - // SetEpochInfo set epoch info - SetEpochInfo(ctx sdk.Context, epoch types.EpochInfo) - // DeleteEpochInfo delete epoch info - DeleteEpochInfo(ctx sdk.Context, identifier string) - // IterateEpochInfo iterate through epochs - IterateEpochInfo(ctx sdk.Context, fn func(index int64, epochInfo types.EpochInfo) (stop bool)) - // Get all epoch infos - AllEpochInfos(ctx sdk.Context) []types.EpochInfo -} -``` - -## Hooks - -```go - // the first block whose timestamp is after the duration is counted as the end of the epoch - AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) - // new epoch is next block of epoch end block - BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) -``` - -### How modules receive hooks - -On hook receiver function of other modules, they need to filter -`epochIdentifier` and only do executions for only specific -epochIdentifier. Filtering epochIdentifier could be in `Params` of other -modules so that they can be modified by governance. - -This is the standard dev UX of this: -```golang -func (k MyModuleKeeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) { - params := k.GetParams(ctx) - if epochIdentifier == params.DistrEpochIdentifier { - // my logic - } -} -``` - -### Panic isolation - -If a given epoch hook panics, its state update is reverted, but we keep -proceeding through the remaining hooks. This allows more advanced epoch -logic to be used, without concern over state machine halting, or halting -subsequent modules. - -This does mean that if there is behavior you expect from a prior epoch -hook, and that epoch hook reverted, your hook may also have an issue. So -do keep in mind "what if a prior hook didn't get executed" in the safety -checks you consider for a new epoch hook. - -## Queries - -Epochs module is providing below queries to check the module's state. - -```protobuf -service Query { - // EpochInfos provide running epochInfos - rpc EpochInfos(QueryEpochsInfoRequest) returns (QueryEpochsInfoResponse) {} - // CurrentEpoch provide current epoch of specified identifier - rpc CurrentEpoch(QueryCurrentEpochRequest) returns (QueryCurrentEpochResponse) {} -} -``` - -### Epoch Infos - -Query the currently running epochInfos - -```sh -osmosisd query epochs epoch-infos -``` -::: details Example - -An example output: - -```sh -epochs: -- current_epoch: "183" - current_epoch_start_height: "2438409" - current_epoch_start_time: "2021-12-18T17:16:09.898160996Z" - duration: 86400s - epoch_counting_started: true - identifier: day - start_time: "2021-06-18T17:00:00Z" -- current_epoch: "26" - current_epoch_start_height: "2424854" - current_epoch_start_time: "2021-12-17T17:02:07.229632445Z" - duration: 604800s - epoch_counting_started: true - identifier: week - start_time: "2021-06-18T17:00:00Z" -``` -::: - -### Current Epoch - - -Query the current epoch by the specified identifier - -```sh -osmosisd query epochs current-epoch [identifier] -``` - -::: details Example - -Query the current `day` epoch: - -```sh -osmosisd query epochs current-epoch day -``` - -Which in this example outputs: - -```sh -current_epoch: "183" -``` diff --git a/x/gamm/spec/README.md b/x/gamm/README.md similarity index 100% rename from x/gamm/spec/README.md rename to x/gamm/README.md diff --git a/x/incentives/spec/README.md b/x/incentives/README.md similarity index 100% rename from x/incentives/spec/README.md rename to x/incentives/README.md diff --git a/x/lockup/README.md b/x/lockup/README.md index dd3c7cc006b..1e91375de5d 100644 --- a/x/lockup/README.md +++ b/x/lockup/README.md @@ -1,7 +1,1116 @@ -Commands -======== +# Lockup -``` {.sh} +## Abstract + +Lockup module provides an interface for users to lock tokens (also known as bonding) into the module to get incentives. + +After tokens have been added to a specific pool and turned into LP shares through the GAMM module, users can then lock these LP shares with a specific duration in order to begin earing rewards. + +To unlock these LP shares, users must trigger the unlock timer and wait for the unlock period that was set initially to be completed. After the unlock period is over, users can turn LP shares back into their respective share of tokens. + +This module provides interfaces for other modules to iterate the locks efficiently and grpc query to check the status of locked coins. + +## Contents + +1. **[Concept](#concepts)** +2. **[State](#state)** +3. **[Messages](#messages)** +4. **[Events](#events)** +5. **[Keeper](#keeper)** +6. **[Hooks](#hooks)** +7. **[Queries](#queries)** +8. **[Transactions](#transactions)** +9. **[Params](#params)** +10. **[Endblocker](#endblocker)** + +## Concepts + +The purpose of `lockup` module is to provide the functionality to lock +tokens for specific period of time for LP token stakers to get +incentives. + +To unlock these LP shares, users must trigger the unlock timer and wait for the unlock period that was set initially to be completed. After the unlock period is over, users can turn LP shares back into their respective share of tokens. + +This module provides interfaces for other modules to iterate the locks efficiently and grpc query to check the status of locked coins. + +There are currently three incentivize lockup periods; `1 day` (24h), `1 week` (168h), and `2 weeks` (336h). When locking tokens in the 2 week period, the liquidity provider is effectively earning rewards for a combination of the 1 day, 1 week, and 2 week bonding periods. + +The 2 week period refers to how long it takes to unbond the LP shares. The liquidity provider can keep their LP shares bonded to the 2 week lockup period indefinitely. Unbonding is only required when the liquidity provider desires access to the underlying assets. + +If the liquidity provider begins the unbonding process for their 2 week bonded LP shares, they will earn rewards for all three bonding periods during the first day of unbonding. + +After the first day passes, they will only receive rewards for the 1 day and 1 week lockup periods. After seven days pass, they will only receive the 1 day rewards until the 2 weeks is complete and their LP shares are unlocked. The below chart is a visual example of what was just explained. + +
+

+ +

+ +
+
+ +## State + +### Locked coins management + +Locked coins are all stored in module account for `lockup` module which +is called `LockPool`. When user lock coins within `lockup` module, it's +moved from user account to `LockPool` and a record (`PeriodLock` struct) +is created. + +Once the period is over, user can withdraw it at anytime from +`LockPool`. User can withdraw by PeriodLock ID or withdraw all +`UnlockableCoins` at a time. + +### Period Lock + +A `PeriodLock` is a single unit of lock by period. It's a record of +locked coin at a specific time. It stores owner, duration, unlock time +and the amount of coins locked. + +``` {.go} +type PeriodLock struct { + ID uint64 + Owner sdk.AccAddress + Duration time.Duration + UnlockTime time.Time + Coins sdk.Coins +} +``` + +All locks are stored on the KVStore as value at +`{KeyPrefixPeriodLock}{ID}` key. + +### Period lock reference queues + +To provide time efficient queries, several reference queues are managed +by denom, unlock time, and duration. There are two big queues to store +the lock references. (`a_prefix_key`) + +1. Lock references that hasn't started with unlocking yet has prefix of + `KeyPrefixNotUnlocking`. +2. Lock references that has started unlocking already has prefix of + `KeyPrefixUnlocking`. +3. Lock references that has withdrawn, it's removed from the store. + +Regardless the lock has started unlocking or not, it stores below +references. (`b_prefix_key`) + +1. `{KeyPrefixLockDuration}{Duration}` +2. `{KeyPrefixAccountLockDuration}{Owner}{Duration}` +3. `{KeyPrefixDenomLockDuration}{Denom}{Duration}` +4. `{KeyPrefixAccountDenomLockDuration}{Owner}{Denom}{Duration}` + +If the lock is unlocking, it also stores the below referneces. + +1. `{KeyPrefixLockTimestamp}{LockEndTime}` +2. `{KeyPrefixAccountLockTimestamp}{Owner}{LockEndTime}` +3. `{KeyPrefixDenomLockTimestamp}{Denom}{LockEndTime}` +4. `{KeyPrefixAccountDenomLockTimestamp}{Owner}{Denom}{LockEndTime}` + +For end time keys, they are converted to sortable string by using +`sdk.FormatTimeBytes` function. + +**Note:** Additionally, for locks that hasn't started unlocking yet, it +stores accumulation store for efficient rewards distribution mechanism. + +For reference management, `addLockRefByKey` function is used a lot. Here +key is the prefix key to be used for iteration. It is combination of two +prefix keys.(`{a_prefix_key}{b_prefix_key}`) + +``` {.go} +// addLockRefByKey make a lockID iterable with the prefix `key` +func (k Keeper) addLockRefByKey(ctx sdk.Context, key []byte, lockID uint64) error { + store := ctx.KVStore(k.storeKey) + lockIDBz := sdk.Uint64ToBigEndian(lockID) + endKey := combineKeys(key, lockIDBz) + if store.Has(endKey) { + return fmt.Errorf("lock with same ID exist: %d", lockID) + } + store.Set(endKey, lockIDBz) + return nil +} +``` + +### Synthetic Lockup + +Synthetic Lockups are a concept that serve the following roles: + +- Add "restrictions" to an underlying PeriodLock, so that its bond + status must be managed by a module rather than a BeginUnlockMessage +- Allow issuing of a locked, "synthetic" denom type +- Allow distribution of rewards to locked synthetic denominations. + +The first goal can eventually be pushed into a new data structure, as it +doesn't really relate to the synthetic component. + +This is then used for superfluid staking. (Old docs below): + +The goal of synthetic lockup is to support the querying of locks by +denom especially for delegated staking. By combining native denom and +synthetic suffix, lockup supports querying with synthetic denom with +existing denom querying functions. + +Synthetic lockup is creating virtual lockup where new denom is +combination of original denom and synthetic suffix. At the time of +synthetic lockup creation and deletion, accumulation store is also being +updated and on querier side, they can query as freely as native lockup. + +Note: The staking, distribution, slashing, superfluid module would be +refactored to use lockup module and synthetic lockup. The following +changes for synthetic lockup on native lockup change could be defined as +per use case. For now we assume this change is made on hook receiver +side which manages synthetic lockup, e.g. use cases are when user start +/ pause superfluid staking on a lockup, redelegation event, unbonding +event etc. + +External modules are managing synthetic locks to use it on their own +logic implementation. (e.g. delegated staking and superfluid staking) + +A `SyntheticLock` is a single unit of synthetic lockup. Each synthetic +lockup has reference `PeriodLock` ID, synthetic suffix (`Suffix`) and +synthetic lock's removal time (`EndTime`). + +``` {.go} +type SyntheticLock struct { + LockId uint64 + Suffix string + EndTime time.Time +} +``` + +All synthetic locks are stored on the KVStore as value at +`{KeyPrefixPeriodLock}{LockID}{Suffix}` key. + +### Synthetic lock reference queues + +To provide time efficient queries, several reference queues are managed +by denom, unlock time, and duration. + +1. `{KeyPrefixDenomLockTimestamp}{SyntheticDenom}{LockEndTime}` +2. `{KeyPrefixDenomLockDuration}{SyntheticDenom}{Duration}` +3. `{KeyPrefixAccountDenomLockTimestamp}{Owner}{SyntheticDenom}{LockEndTime}` +4. `{KeyPrefixAccountDenomLockDuration}{Owner}{SyntheticDenom}{Duration}` + +SyntheticDenom is expressed as `{Denom}{Suffix}`. (Note: we can change +this to `{Prefix}{Denom}` as per discussion with Dev) + +For end time keys, they are converted to sortable string by using +`sdk.FormatTimeBytes` function. + +**Note:** To implement the auto removal of synthetic lockups that is +already finished, we manage a separate time basis queue at +`{KeyPrefixSyntheticLockTimestamp}{EndTime}{LockId}{Suffix}` + +## Messages + +### Lock Tokens + +`MsgLockTokens` can be submitted by any token holder via a +`MsgLockTokens` transaction. + +``` {.go} +type MsgLockTokens struct { + Owner sdk.AccAddress + Duration time.Duration + Coins sdk.Coins +} +``` + +**State modifications:** + +- Validate `Owner` has enough tokens +- Generate new `PeriodLock` record +- Save the record inside the keeper's time basis unlock queue +- Transfer the tokens from the `Owner` to lockup `ModuleAccount`. + +### Begin Unlock of all locks + +Once time is over, users can withdraw unlocked coins from lockup +`ModuleAccount`. + +``` {.go} +type MsgBeginUnlockingAll struct { + Owner string +} +``` + +**State modifications:** + +- Fetch all unlockable `PeriodLock`s that has not started unlocking + yet +- Set `PeriodLock`'s unlock time +- Remove lock references from `NotUnlocking` queue +- Add lock references to `Unlocking` queue + +### Begin unlock for a lock + +Once time is over, users can withdraw unlocked coins from lockup +`ModuleAccount`. + +``` {.go} +type MsgBeginUnlocking struct { + Owner string + ID uint64 +} +``` + +**State modifications:** + +- Check `PeriodLock` with `ID` specified by `MsgBeginUnlocking` is not + started unlocking yet +- Set `PeriodLock`'s unlock time +- Remove lock references from `NotUnlocking` queue +- Add lock references to `Unlocking` queue + +Note: If another module needs past `PeriodLock` item, it can log the +details themselves using the hooks. + +## Events + +The lockup module emits the following events: + +### Handlers + +#### MsgLockTokens + +| Type | Attribute Key | Attribute Value | +| --------------| ------------------| -----------------| +| lock\_tokens | period\_lock\_id | {periodLockID} | +| lock\_tokens | owner | {owner} | +| lock\_tokens | amount | {amount} | +| lock\_tokens | duration | {duration} | +| lock\_tokens | unlock\_time | {unlockTime} | +| message | action | lock\_tokens | +| message | sender | {owner} | +| transfer | recipient | {moduleAccount} | +| transfer | sender | {owner} | +| transfer | amount | {amount} | + +#### MsgBeginUnlocking + +| Type | Attribute Key | Attribute Value | +| ---------------| ------------------| ------------------| +| begin\_unlock | period\_lock\_id | {periodLockID} | +| begin\_unlock | owner | {owner} | +| begin\_unlock | amount | {amount} | +| begin\_unlock | duration | {duration} | +| begin\_unlock | unlock\_time | {unlockTime} | +| message | action | begin\_unlocking | +| message | sender | {owner} | + +#### MsgBeginUnlockingAll + +| Type | Attribute Key | Attribute Value | +| --------------------| ------------------| -----------------------| +| begin\_unlock\_all | owner | {owner} | +| begin\_unlock\_all | unlocked\_coins | {unlockedCoins} | +| begin\_unlock | period\_lock\_id | {periodLockID} | +| begin\_unlock | owner | {owner} | +| begin\_unlock | amount | {amount} | +| begin\_unlock | duration | {duration} | +| begin\_unlock | unlock\_time | {unlockTime} | +| message | action | begin\_unlocking\_all | +| message | sender | {owner} | + +### Endblocker + +#### Automatic withdraw when unlock time mature + +| Type | Attribute Key | Attribute Value | +| ----------------| ------------------| -----------------| +| message | action | unlock\_tokens | +| message | sender | {owner} | +| transfer\[\] | recipient | {owner} | +| transfer\[\] | sender | {moduleAccount} | +| transfer\[\] | amount | {unlockAmount} | +| unlock\[\] | period\_lock\_id | {owner} | +| unlock\[\] | owner | {lockID} | +| unlock\[\] | duration | {lockDuration} | +| unlock\[\] | unlock\_time | {unlockTime} | +| unlock\_tokens | owner | {owner} | +| unlock\_tokens | unlocked\_coins | {totalAmount} | + +## Keepers + +### Lockup Keeper + +Lockup keeper provides utility functions to store lock queues and query +locks. + +```go +// Keeper is the interface for lockup module keeper +type Keeper interface { + // GetModuleBalance Returns full balance of the module + GetModuleBalance(sdk.Context) sdk.Coins + // GetModuleLockedCoins Returns locked balance of the module + GetModuleLockedCoins(sdk.Context) sdk.Coins + // GetAccountUnlockableCoins Returns whole unlockable coins which are not withdrawn yet + GetAccountUnlockableCoins(sdk.Context, addr sdk.AccAddress) sdk.Coins + // GetAccountUnlockingCoins Returns whole unlocking coins + GetAccountUnlockingCoins(sdk.Context, addr sdk.AccAddress) sdk.Coins + // GetAccountLockedCoins Returns a locked coins that can't be withdrawn + GetAccountLockedCoins(sdk.Context, addr sdk.AccAddress) sdk.Coins + // GetAccountLockedPastTime Returns the total locks of an account whose unlock time is beyond timestamp + GetAccountLockedPastTime(sdk.Context, addr sdk.AccAddress, timestamp time.Time) []types.PeriodLock + // GetAccountUnlockedBeforeTime Returns the total unlocks of an account whose unlock time is before timestamp + GetAccountUnlockedBeforeTime(sdk.Context, addr sdk.AccAddress, timestamp time.Time) []types.PeriodLock + // GetAccountLockedPastTimeDenom is equal to GetAccountLockedPastTime but denom specific + GetAccountLockedPastTimeDenom(ctx sdk.Context, addr sdk.AccAddress, denom string, timestamp time.Time) []types.PeriodLock + + // GetAccountLockedLongerDuration Returns account locked with duration longer than specified + GetAccountLockedLongerDuration(sdk.Context, addr sdk.AccAddress, duration time.Duration) []types.PeriodLock + // GetAccountLockedLongerDurationDenom Returns account locked with duration longer than specified with specific denom + GetAccountLockedLongerDurationDenom(sdk.Context, addr sdk.AccAddress, denom string, duration time.Duration) []types.PeriodLock + // GetLocksPastTimeDenom Returns the locks whose unlock time is beyond timestamp + GetLocksPastTimeDenom(ctx sdk.Context, addr sdk.AccAddress, denom string, timestamp time.Time) []types.PeriodLock + // GetLocksLongerThanDurationDenom Returns the locks whose unlock duration is longer than duration + GetLocksLongerThanDurationDenom(ctx sdk.Context, addr sdk.AccAddress, denom string, duration time.Duration) []types.PeriodLock + // GetLockByID Returns lock from lockID + GetLockByID(sdk.Context, lockID uint64) (*types.PeriodLock, error) + // GetPeriodLocks Returns the period locks on pool + GetPeriodLocks(sdk.Context) ([]types.PeriodLock, error) + // UnlockAllUnlockableCoins Unlock all unlockable coins + UnlockAllUnlockableCoins(sdk.Context, account sdk.AccAddress) (sdk.Coins, error) + // LockTokens lock tokens from an account for specified duration + LockTokens(sdk.Context, owner sdk.AccAddress, coins sdk.Coins, duration time.Duration) (types.PeriodLock, error) + // AddTokensToLock locks more tokens into a lockup + AddTokensToLock(ctx sdk.Context, owner sdk.AccAddress, lockID uint64, coins sdk.Coins) (*types.PeriodLock, error) + // Lock is a utility to lock coins into module account + Lock(sdk.Context, lock types.PeriodLock) error + // Unlock is a utility to unlock coins from module account + Unlock(sdk.Context, lock types.PeriodLock) error + GetSyntheticLockup(ctx sdk.Context, lockID uint64, suffix string) (*types.SyntheticLock, error) + GetAllSyntheticLockupsByLockup(ctx sdk.Context, lockID uint64) []types.SyntheticLock + GetAllSyntheticLockups(ctx sdk.Context) []types.SyntheticLock + // CreateSyntheticLockup create synthetic lockup with lock id and denom suffix + CreateSyntheticLockup(ctx sdk.Context, lockID uint64, suffix string, unlockDuration time.Duration) error + // DeleteSyntheticLockup delete synthetic lockup with lock id and suffix + DeleteSyntheticLockup(ctx sdk.Context, lockID uint64, suffix string) error + DeleteAllMaturedSyntheticLocks(ctx sdk.Context) +``` + +### Lock Admin Keeper + +Lockup admin keeper provides god privilege functions to remove tokens +from locks and create new locks. + +```go +// AdminKeeper defines a god priviledge keeper functions to remove tokens from locks and create new locks +// For the governance system of token pools, we want a "ragequit" feature +// So governance changes will take 1 week to go into effect +// During that time, people can choose to "ragequit" which means they would leave the original pool +// and form a new pool with the old parameters but if they still had 2 months of lockup left, +// their liquidity still needs to be 2 month lockup-ed, just in the new pool +// And we need to replace their pool1 LP tokens with pool2 LP tokens with the same lock duration and end time + +type AdminKeeper interface { + Keeper + + // this unlock previous lockID and create a new lock with newCoins with same duration and endtime + Relock(sdk.Context, lockID uint64, newCoins sdk.Coins) error + // this unlock without time check with an admin priviledge + BreakLock(sdk.Context, lockID uint64) error +} +``` + +## Hooks + +In this section we describe the "hooks" that `lockup` module provide for +other modules. + +### Tokens Locked + +On lock/unlock events, lockup module execute hooks for other modules to +make following actions. + +``` go + OnTokenLocked(ctx sdk.Context, address sdk.AccAddress, lockID uint64, amount sdk.Coins, lockDuration time.Duration, unlockTime time.Time) + OnTokenUnlocked(ctx sdk.Context, address sdk.AccAddress, lockID uint64, amount sdk.Coins, lockDuration time.Duration, unlockTime time.Time) +``` + +## Parameters + +The lockup module contains the following parameters: + +| Key | Type | Example | +| ---------------------- | --------------- | ------- | + +Note: Currently no parameters are set for `lockup` module, we will need +to move lockable durations from incentives module to lockup module. + +## Endblocker + +### Withdraw tokens after unlock time mature + +Once time is over, endblocker withdraw coins from matured locks and +coins are sent from lockup `ModuleAccount`. + +**State modifications:** + +- Fetch all unlockable `PeriodLock`s that `Owner` has not withdrawn + yet +- Remove `PeriodLock` records from the state +- Transfer the tokens from lockup `ModuleAccount` to the + `MsgUnlockTokens.Owner`. + +### Remove synthetic locks after removal time mature + +For synthetic lockups, no coin movement is made, but lockup record and +reference queues are removed. + +**State modifications:** + +- Fetch all synthetic lockups that is matured +- Remove `SyntheticLock` records from the state along with reference + queues + +## Transactions + +### lock-tokens + +Bond tokens in a LP for a set duration + +```sh +osmosisd tx lockup lock-tokens [tokens] --duration --from --chain-id +``` + +::: details Example + +To lockup `15.527546134174465309gamm/pool/3` tokens for a `one day` bonding period from `WALLET_NAME` on the osmosis mainnet: + +```bash +osmosisd tx lockup lock-tokens 15527546134174465309gamm/pool/3 --duration="24h" --from WALLET_NAME --chain-id osmosis-1 +``` + +To lockup `25.527546134174465309gamm/pool/13` tokens for a `one week` bonding period from `WALLET_NAME` on the osmosis testnet: + +```bash +osmosisd tx lockup lock-tokens 25527546134174465309gamm/pool/13 --duration="168h" --from WALLET_NAME --chain-id osmo-test-4 +``` + +To lockup `35.527546134174465309 gamm/pool/197` tokens for a `two week` bonding period from `WALLET_NAME` on the osmosis mainnet: + +```bash +osmosisd tx lockup lock-tokens 35527546134174465309gamm/pool/197 --duration="336h" --from WALLET_NAME --chain-id osmosis-1 +``` +::: + + +### begin-unlock-by-id + +Begin the unbonding process for tokens given their unique lock ID + +```sh +osmosisd tx lockup begin-unlock-by-id [id] --from --chain-id +``` + +::: details Example + +To begin the unbonding time for all bonded tokens under id `75` from `WALLET_NAME` on the osmosis mainnet: + +```bash +osmosisd tx lockup begin-unlock-by-id 75 --from WALLET_NAME --chain-id osmosis-1 +``` +::: +::: warning Note +The ID corresponds to the unique ID given to your lockup transaction (explained more in lock-by-id section) +::: + +### begin-unlock-tokens + +Begin unbonding process for all bonded tokens in a wallet + +```sh +osmosisd tx lockup begin-unlock-tokens --from --chain-id +``` + +::: details Example + +To begin unbonding time for ALL pools and ALL bonded tokens in `WALLET_NAME` on the osmosis mainnet: + + +```bash +osmosisd tx lockup begin-unlock-tokens --from=WALLET_NAME --chain-id=osmosis-1 --yes +``` +::: + +## Queries + +In this section we describe the queries required on grpc server. + +``` protobuf +// Query defines the gRPC querier service. +service Query { + // Return full balance of the module + rpc ModuleBalance(ModuleBalanceRequest) returns (ModuleBalanceResponse); + // Return locked balance of the module + rpc ModuleLockedAmount(ModuleLockedAmountRequest) returns (ModuleLockedAmountResponse); + + // Returns unlockable coins which are not withdrawn yet + rpc AccountUnlockableCoins(AccountUnlockableCoinsRequest) returns (AccountUnlockableCoinsResponse); + // Returns unlocking coins + rpc AccountUnlockingCoins(AccountUnlockingCoinsRequest) returns (AccountUnlockingCoinsResponse) {} + // Return a locked coins that can't be withdrawn + rpc AccountLockedCoins(AccountLockedCoinsRequest) returns (AccountLockedCoinsResponse); + + // Returns locked records of an account with unlock time beyond timestamp + rpc AccountLockedPastTime(AccountLockedPastTimeRequest) returns (AccountLockedPastTimeResponse); + // Returns locked records of an account with unlock time beyond timestamp excluding tokens started unlocking + rpc AccountLockedPastTimeNotUnlockingOnly(AccountLockedPastTimeNotUnlockingOnlyRequest) returns (AccountLockedPastTimeNotUnlockingOnlyResponse) {} + // Returns unlocked records with unlock time before timestamp + rpc AccountUnlockedBeforeTime(AccountUnlockedBeforeTimeRequest) returns (AccountUnlockedBeforeTimeResponse); + + // Returns lock records by address, timestamp, denom + rpc AccountLockedPastTimeDenom(AccountLockedPastTimeDenomRequest) returns (AccountLockedPastTimeDenomResponse); + // Returns lock record by id + rpc LockedByID(LockedRequest) returns (LockedResponse); + + // Returns account locked records with longer duration + rpc AccountLockedLongerDuration(AccountLockedLongerDurationRequest) returns (AccountLockedLongerDurationResponse); + // Returns account locked records with longer duration excluding tokens started unlocking + rpc AccountLockedLongerDurationNotUnlockingOnly(AccountLockedLongerDurationNotUnlockingOnlyRequest) returns (AccountLockedLongerDurationNotUnlockingOnlyResponse) {} + // Returns account's locked records for a denom with longer duration + rpc AccountLockedLongerDurationDenom(AccountLockedLongerDurationDenomRequest) returns (AccountLockedLongerDurationDenomResponse); + + // Returns account locked records with a specific duration + rpc AccountLockedDuration(AccountLockedDurationRequest) returns (AccountLockedDurationResponse); +} +``` + +### account-locked-beforetime + +Query an account's unlocked records after a specified time (UNIX) has passed + +In other words, if an account unlocked all their bonded tokens the moment the query was executed, only the locks that would have completed their bond time requirement by the time the `TIMESTAMP` is reached will be returned. + +::: details Example + +In this example, the current UNIX time is `1639776682`, 2 days from now is approx `1639971082`, and 15 days from now is approx `1641094282`. + +An account's `ADDRESS` is locked in both the `1 day` and `1 week` gamm/pool/3. To query the `ADDRESS` with a timestamp 2 days from now `1639971082`: + +```bash +osmosisd query lockup account-locked-beforetime ADDRESS 1639971082 +``` + +In this example will output the `1 day` lock but not the `1 week` lock: + +```bash +locks: +- ID: "571839" + coins: + - amount: "15527546134174465309" + denom: gamm/pool/3 + duration: 24h + end_time: "2021-12-18T23:32:58.900715388Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` + +If querying the same `ADDRESS` with a timestamp 15 days from now `1641094282`: + +```bash +osmosisd query lockup account-locked-beforetime ADDRESS 1641094282 +``` + +In this example will output both the `1 day` and `1 week` lock: + +```bash +locks: +- ID: "572027" + coins: + - amount: "16120691802759484268" + denom: gamm/pool/3 + duration: 604800.000006193s + end_time: "0001-01-01T00:00:00Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +- ID: "571839" + coins: + - amount: "15527546134174465309" + denom: gamm/pool/3 + duration: 24h + end_time: "2021-12-18T23:32:58.900715388Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` +::: + + +### account-locked-coins + +Query an account's locked (bonded) LP tokens + +```sh +osmosisd query lockup account-locked-coins [address] +``` + +:::: details Example + +```bash +osmosisd query lockup account-locked-coins osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` + +An example output: + +```bash +coins: +- amount: "413553955105681228583" + denom: gamm/pool/1 +- amount: "32155370994266157441309" + denom: gamm/pool/10 +- amount: "220957857520769912023" + denom: gamm/pool/3 +- amount: "31648237936933949577" + denom: gamm/pool/42 +- amount: "14162624050980051053569" + denom: gamm/pool/5 +- amount: "1023186951315714985896914" + denom: gamm/pool/9 +``` +::: warning Note +All GAMM amounts listed are 10^18. Move the decimal place to the left 18 places to get the GAMM amount listed in the GUI. + +You may also specify a --height flag to see bonded LP tokens at a specified height (note: if running a pruned node, this may result in an error) +::: +:::: + +### account-locked-longer-duration + +Query an account's locked records that are greater than or equal to a specified lock duration + +```sh +osmosisd query lockup account-locked-longer-duration [address] [duration] +``` + +::: details Example + +Here is an example of querying an `ADDRESS` for all `1 day` or greater bonding periods: + +```bash +osmosisd query lockup account-locked-longer-duration osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 24h +``` + +An example output: + +```bash +locks: +- ID: "572027" + coins: + - amount: "16120691802759484268" + denom: gamm/pool/3 + duration: 604800.000006193s + end_time: "0001-01-01T00:00:00Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +- ID: "571839" + coins: + - amount: "15527546134174465309" + denom: gamm/pool/3 + duration: 24h + end_time: "2021-12-18T23:32:58.900715388Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` +::: + + +### account-locked-longer-duration-denom + +Query an account's locked records for a denom that is locked equal to or greater than the specified duration AND match a specified denom + +```sh +osmosisd query lockup account-locked-longer-duration-denom [address] [duration] [denom] +``` + +::: details Example + +Here is an example of an `ADDRESS` that is locked in both the `1 day` and `1 week` for both the gamm/pool/3 and gamm/pool/1, then queries the `ADDRESS` for all bonding periods equal to or greater than `1 day` for just the gamm/pool/3: + +```bash +osmosisd query lockup account-locked-longer-duration-denom osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 24h gamm/pool/3 +``` + +An example output: + +```bash +locks: +- ID: "571839" + coins: + - amount: "15527546134174465309" + denom: gamm/pool/3 + duration: 24h + end_time: "0001-01-01T00:00:00Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +- ID: "572027" + coins: + - amount: "16120691802759484268" + denom: gamm/pool/3 + duration: 604800.000006193s + end_time: "0001-01-01T00:00:00Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` + +As shown, the gamm/pool/3 is returned but not the gamm/pool/1 due to the denom filter. +::: + + +### account-locked-longer-duration-not-unlocking + +Query an account's locked records for a denom that is locked equal to or greater than the specified duration AND is not in the process of being unlocked + +```sh +osmosisd query lockup account-locked-longer-duration-not-unlocking [address] [duration] +``` + +::: details Example + +Here is an example of an `ADDRESS` that is locked in both the `1 day` and `1 week` gamm/pool/3, begins unlocking process for the `1 day` bond, and queries the `ADDRESS` for all bonding periods equal to or greater than `1 day` that are not unbonding: + +```bash +osmosisd query lockup account-locked-longer-duration-not-unlocking osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 24h +``` + +An example output: + +```bash +locks: +- ID: "571839" + coins: + - amount: "16120691802759484268" + denom: gamm/pool/3 + duration: 604800.000006193s + end_time: "0001-01-01T00:00:00Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` + +The `1 day` bond does not show since it is in the process of unbonding. +::: + + +### account-locked-pasttime + +Query the locked records of an account with the unlock time beyond timestamp (UNIX) + +```bash +osmosisd query lockup account-locked-pasttime [address] [timestamp] +``` + +::: details Example + +Here is an example of an account that is locked in both the `1 day` and `1 week` gamm/pool/3. In this example, the UNIX time is currently `1639776682` and queries an `ADDRESS` for UNIX time two days later from the current time (which in this example would be `1639971082`) + +```bash +osmosisd query lockup account-locked-pasttime osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 1639971082 +``` + +The example output: + +```bash +locks: +- ID: "572027" + coins: + - amount: "16120691802759484268" + denom: gamm/pool/3 + duration: 604800.000006193s + end_time: "0001-01-01T00:00:00Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` + +Note that the `1 day` lock ID did not display because, if the unbonding time began counting down from the time the command was executed, the bonding period would be complete before the two day window given by the UNIX timestamp input. +::: + + +### account-locked-pasttime-denom + +Query the locked records of an account with the unlock time beyond timestamp (unix) and filter by a specific denom + +```bash +osmosisd query lockup account-locked-pasttime-denom osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 [timestamp] [denom] +``` + +::: details Example + +Here is an example of an account that is locked in both the `1 day` and `1 week` gamm/pool/3 and `1 day` and `1 week` gamm/pool/1. In this example, the UNIX time is currently `1639776682` and queries an `ADDRESS` for UNIX time two days later from the current time (which in this example would be `1639971082`) and filters for gamm/pool/3 + +```bash +osmosisd query lockup account-locked-pasttime-denom osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 1639971082 gamm/pool/3 +``` + +The example output: + +```bash +locks: +- ID: "572027" + coins: + - amount: "16120691802759484268" + denom: gamm/pool/3 + duration: 604800.000006193s + end_time: "0001-01-01T00:00:00Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` + +Note that the `1 day` lock ID did not display because, if the unbonding time began counting down from the time the command was executed, the bonding period would be complete before the two day window given by the UNIX timestamp input. Additionally, neither of the `1 day` or `1 week` lock IDs for gamm/pool/1 showed due to the denom filter. +::: + + +### account-locked-pasttime-not-unlocking + +Query the locked records of an account with the unlock time beyond timestamp (unix) AND is not in the process of unlocking + +```sh +osmosisd query lockup account-locked-pasttime [address] [timestamp] +``` + +::: details Example + +Here is an example of an account that is locked in both the `1 day` and `1 week` gamm/pool/3. In this example, the UNIX time is currently `1639776682` and queries an `ADDRESS` for UNIX time two days later from the current time (which in this example would be `1639971082`) AND is not unlocking: + +```bash +osmosisd query lockup account-locked-pasttime osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 1639971082 +``` + +The example output: + +```bash +locks: +- ID: "572027" + coins: + - amount: "16120691802759484268" + denom: gamm/pool/3 + duration: 604800.000006193s + end_time: "0001-01-01T00:00:00Z" + owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` + +Note that the `1 day` lock ID did not display because, if the unbonding time began counting down from the time the command was executed, the bonding period would be complete before the two day window given by the UNIX timestamp input. Additionally, if ID 572027 were to begin the unlocking process, the query would have returned blank. +::: + + +### account-unlockable-coins + +Query an address's LP shares that have completed the unlocking period and are ready to be withdrawn + +```bash +osmosisd query lockup account-unlockable-coins ADDRESS +``` + + + +### account-unlocking-coins + +Query an address's LP shares that are currently unlocking + +```sh +osmosisd query lockup account-unlocking-coins [address] +``` + +::: details Example + +```bash +osmosisd query lockup account-unlocking-coins osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 +``` + +Example output: + +```bash +coins: +- amount: "15527546134174465309" + denom: gamm/pool/3 +``` +::: + + +### lock-by-id + +Query a lock record by its ID + +```sh +osmosisd query lockup lock-by-id [id] +``` + +::: details Example + +Every time a user bonds tokens to an LP, a unique lock ID is created for that transaction. + +Here is an example viewing the lock record for ID 9: + +```bash +osmosisd query lockup lock-by-id 9 +``` + +And its output: + +```bash +lock: + ID: "9" + coins: + - amount: "2449472670508255020346507" + denom: gamm/pool/2 + duration: 336h + end_time: "0001-01-01T00:00:00Z" + owner: osmo16r39ghhwqjcwxa8q3yswlz8jhzldygy66vlm82 +``` + +In summary, this shows wallet `osmo16r39ghhwqjcwxa8q3yswlz8jhzldygy66vlm82` bonded `2449472.670 gamm/pool/2` LP shares for a `2 week` locking period. +::: + + +### module-balance + +Query the balance of all LP shares (bonded and unbonded) + +```sh +osmosisd query lockup module-balance +``` + +::: details Example + +```bash +osmosisd query lockup module-balance +``` + +An example output: + +```bash +coins: +- amount: "118851922644152734549498647" + denom: gamm/pool/1 +- amount: "2165392672114512349039263626" + denom: gamm/pool/10 +- amount: "9346769826591025900804" + denom: gamm/pool/13 +- amount: "229347389639275840044722315" + denom: gamm/pool/15 +- amount: "81217698776012800247869" + denom: gamm/pool/183 +- amount: "284253336860259874753775" + denom: gamm/pool/197 +- amount: "664300804648059580124426710" + denom: gamm/pool/2 +- amount: "5087102794776326441530430" + denom: gamm/pool/22 +- amount: "178900843925960029029567880" + denom: gamm/pool/3 +- amount: "64845148811263846652326124" + denom: gamm/pool/4 +- amount: "177831279847453210600513" + denom: gamm/pool/42 +- amount: "18685913727862493301261661338" + denom: gamm/pool/5 +- amount: "23579028640963777558149250419" + denom: gamm/pool/6 +- amount: "1273329284855460149381904976" + denom: gamm/pool/7 +- amount: "625252103927082207683116933" + denom: gamm/pool/8 +- amount: "1148475247281090606949382402" + denom: gamm/pool/9 +``` +::: + + +### module-locked-amount + +Query the balance of all bonded LP shares + +```sh +osmosisd query lockup module-locked-amount +``` + +::: details Example + +```bash +osmosisd query lockup module-locked-amount +``` + +An example output: + +```bash + + "coins": + { + "denom": "gamm/pool/1", + "amount": "247321084020868094262821308" + }, + { + "denom": "gamm/pool/10", + "amount": "2866946821820635047398966697" + }, + { + "denom": "gamm/pool/13", + "amount": "9366580741745176812984" + }, + { + "denom": "gamm/pool/15", + "amount": "193294911294343602187680438" + }, + { + "denom": "gamm/pool/183", + "amount": "196722012808526595790871" + }, + { + "denom": "gamm/pool/197", + "amount": "1157025085661167198918241" + }, + { + "denom": "gamm/pool/2", + "amount": "633051132033131378888258047" + }, + { + "denom": "gamm/pool/22", + "amount": "3622601406125950733194696" + }, +... + +``` + +NOTE: This command seems to only work on gRPC and on CLI returns an EOF error. +::: + + + +### output-all-locks + +Output all locks into a json file + +```sh +osmosisd query lockup output-all-locks [max lock ID] +``` + +:::: details Example + +This example command outputs locks 1-1000 and saves to a json file: + +```bash +osmosisd query lockup output-all-locks 1000 +``` +::: warning Note +If a lockup has been completed, the lockup status will show as "0" (or successful) and no further information will be available. To get further information on a completed lock, run the lock-by-id query. +::: +:::: + + +### total-locked-of-denom + +Query locked amount for a specific denom in the duration provided + +```sh +osmosisd query lockup total-locked-of-denom [denom] --min-duration +``` + +:::: details Example + +This example command outputs the amount of `gamm/pool/2` LP shares that locked in the `2 week` bonding period: + +```bash +osmosisd query lockup total-locked-of-denom gamm/pool/2 --min-duration "336h" +``` + +Which, at the time of this writing outputs `14106985399822075248947045` which is equivalent to `14106985.3998 gamm/pool/2` + +NOTE: As of this writing, there is a bug that defaults the min duration to days instead of seconds. Ensure you specify the time in seconds to get the correct response. +::: + +## Commands + +```sh # 1 day 100stake lock-tokens command osmosisd tx lockup lock-tokens 200stake --duration="86400s" --from=validator --chain-id=testing --keyring-backend=test --yes diff --git a/x/lockup/spec/README.md b/x/lockup/spec/README.md deleted file mode 100644 index 41ff5246204..00000000000 --- a/x/lockup/spec/README.md +++ /dev/null @@ -1,1109 +0,0 @@ -# Lockup - -## Abstract - -Lockup module provides an interface for users to lock tokens (also known as bonding) into the module to get incentives. - -After tokens have been added to a specific pool and turned into LP shares through the GAMM module, users can then lock these LP shares with a specific duration in order to begin earing rewards. - -To unlock these LP shares, users must trigger the unlock timer and wait for the unlock period that was set initially to be completed. After the unlock period is over, users can turn LP shares back into their respective share of tokens. - -This module provides interfaces for other modules to iterate the locks efficiently and grpc query to check the status of locked coins. - -## Contents - -1. **[Concept](#concepts)** -2. **[State](#state)** -3. **[Messages](#messages)** -4. **[Events](#events)** -5. **[Keeper](#keeper)** -6. **[Hooks](#hooks)** -7. **[Queries](#queries)** -8. **[Transactions](#transactions)** -9. **[Params](#params)** -10. **[Endblocker](#endblocker)** - -## Concepts - -The purpose of `lockup` module is to provide the functionality to lock -tokens for specific period of time for LP token stakers to get -incentives. - -To unlock these LP shares, users must trigger the unlock timer and wait for the unlock period that was set initially to be completed. After the unlock period is over, users can turn LP shares back into their respective share of tokens. - -This module provides interfaces for other modules to iterate the locks efficiently and grpc query to check the status of locked coins. - -There are currently three incentivize lockup periods; `1 day` (24h), `1 week` (168h), and `2 weeks` (336h). When locking tokens in the 2 week period, the liquidity provider is effectively earning rewards for a combination of the 1 day, 1 week, and 2 week bonding periods. - -The 2 week period refers to how long it takes to unbond the LP shares. The liquidity provider can keep their LP shares bonded to the 2 week lockup period indefinitely. Unbonding is only required when the liquidity provider desires access to the underlying assets. - -If the liquidity provider begins the unbonding process for their 2 week bonded LP shares, they will earn rewards for all three bonding periods during the first day of unbonding. - -After the first day passes, they will only receive rewards for the 1 day and 1 week lockup periods. After seven days pass, they will only receive the 1 day rewards until the 2 weeks is complete and their LP shares are unlocked. The below chart is a visual example of what was just explained. - -
-

- -

- -
-
- -## State - -### Locked coins management - -Locked coins are all stored in module account for `lockup` module which -is called `LockPool`. When user lock coins within `lockup` module, it's -moved from user account to `LockPool` and a record (`PeriodLock` struct) -is created. - -Once the period is over, user can withdraw it at anytime from -`LockPool`. User can withdraw by PeriodLock ID or withdraw all -`UnlockableCoins` at a time. - -### Period Lock - -A `PeriodLock` is a single unit of lock by period. It's a record of -locked coin at a specific time. It stores owner, duration, unlock time -and the amount of coins locked. - -``` {.go} -type PeriodLock struct { - ID uint64 - Owner sdk.AccAddress - Duration time.Duration - UnlockTime time.Time - Coins sdk.Coins -} -``` - -All locks are stored on the KVStore as value at -`{KeyPrefixPeriodLock}{ID}` key. - -### Period lock reference queues - -To provide time efficient queries, several reference queues are managed -by denom, unlock time, and duration. There are two big queues to store -the lock references. (`a_prefix_key`) - -1. Lock references that hasn't started with unlocking yet has prefix of - `KeyPrefixNotUnlocking`. -2. Lock references that has started unlocking already has prefix of - `KeyPrefixUnlocking`. -3. Lock references that has withdrawn, it's removed from the store. - -Regardless the lock has started unlocking or not, it stores below -references. (`b_prefix_key`) - -1. `{KeyPrefixLockDuration}{Duration}` -2. `{KeyPrefixAccountLockDuration}{Owner}{Duration}` -3. `{KeyPrefixDenomLockDuration}{Denom}{Duration}` -4. `{KeyPrefixAccountDenomLockDuration}{Owner}{Denom}{Duration}` - -If the lock is unlocking, it also stores the below referneces. - -1. `{KeyPrefixLockTimestamp}{LockEndTime}` -2. `{KeyPrefixAccountLockTimestamp}{Owner}{LockEndTime}` -3. `{KeyPrefixDenomLockTimestamp}{Denom}{LockEndTime}` -4. `{KeyPrefixAccountDenomLockTimestamp}{Owner}{Denom}{LockEndTime}` - -For end time keys, they are converted to sortable string by using -`sdk.FormatTimeBytes` function. - -**Note:** Additionally, for locks that hasn't started unlocking yet, it -stores accumulation store for efficient rewards distribution mechanism. - -For reference management, `addLockRefByKey` function is used a lot. Here -key is the prefix key to be used for iteration. It is combination of two -prefix keys.(`{a_prefix_key}{b_prefix_key}`) - -``` {.go} -// addLockRefByKey make a lockID iterable with the prefix `key` -func (k Keeper) addLockRefByKey(ctx sdk.Context, key []byte, lockID uint64) error { - store := ctx.KVStore(k.storeKey) - lockIDBz := sdk.Uint64ToBigEndian(lockID) - endKey := combineKeys(key, lockIDBz) - if store.Has(endKey) { - return fmt.Errorf("lock with same ID exist: %d", lockID) - } - store.Set(endKey, lockIDBz) - return nil -} -``` - -### Synthetic Lockup - -Synthetic Lockups are a concept that serve the following roles: - -- Add "restrictions" to an underlying PeriodLock, so that its bond - status must be managed by a module rather than a BeginUnlockMessage -- Allow issuing of a locked, "synthetic" denom type -- Allow distribution of rewards to locked synthetic denominations. - -The first goal can eventually be pushed into a new data structure, as it -doesn't really relate to the synthetic component. - -This is then used for superfluid staking. (Old docs below): - -The goal of synthetic lockup is to support the querying of locks by -denom especially for delegated staking. By combining native denom and -synthetic suffix, lockup supports querying with synthetic denom with -existing denom querying functions. - -Synthetic lockup is creating virtual lockup where new denom is -combination of original denom and synthetic suffix. At the time of -synthetic lockup creation and deletion, accumulation store is also being -updated and on querier side, they can query as freely as native lockup. - -Note: The staking, distribution, slashing, superfluid module would be -refactored to use lockup module and synthetic lockup. The following -changes for synthetic lockup on native lockup change could be defined as -per use case. For now we assume this change is made on hook receiver -side which manages synthetic lockup, e.g. use cases are when user start -/ pause superfluid staking on a lockup, redelegation event, unbonding -event etc. - -External modules are managing synthetic locks to use it on their own -logic implementation. (e.g. delegated staking and superfluid staking) - -A `SyntheticLock` is a single unit of synthetic lockup. Each synthetic -lockup has reference `PeriodLock` ID, synthetic suffix (`Suffix`) and -synthetic lock's removal time (`EndTime`). - -``` {.go} -type SyntheticLock struct { - LockId uint64 - Suffix string - EndTime time.Time -} -``` - -All synthetic locks are stored on the KVStore as value at -`{KeyPrefixPeriodLock}{LockID}{Suffix}` key. - -### Synthetic lock reference queues - -To provide time efficient queries, several reference queues are managed -by denom, unlock time, and duration. - -1. `{KeyPrefixDenomLockTimestamp}{SyntheticDenom}{LockEndTime}` -2. `{KeyPrefixDenomLockDuration}{SyntheticDenom}{Duration}` -3. `{KeyPrefixAccountDenomLockTimestamp}{Owner}{SyntheticDenom}{LockEndTime}` -4. `{KeyPrefixAccountDenomLockDuration}{Owner}{SyntheticDenom}{Duration}` - -SyntheticDenom is expressed as `{Denom}{Suffix}`. (Note: we can change -this to `{Prefix}{Denom}` as per discussion with Dev) - -For end time keys, they are converted to sortable string by using -`sdk.FormatTimeBytes` function. - -**Note:** To implement the auto removal of synthetic lockups that is -already finished, we manage a separate time basis queue at -`{KeyPrefixSyntheticLockTimestamp}{EndTime}{LockId}{Suffix}` - -## Messages - -### Lock Tokens - -`MsgLockTokens` can be submitted by any token holder via a -`MsgLockTokens` transaction. - -``` {.go} -type MsgLockTokens struct { - Owner sdk.AccAddress - Duration time.Duration - Coins sdk.Coins -} -``` - -**State modifications:** - -- Validate `Owner` has enough tokens -- Generate new `PeriodLock` record -- Save the record inside the keeper's time basis unlock queue -- Transfer the tokens from the `Owner` to lockup `ModuleAccount`. - -### Begin Unlock of all locks - -Once time is over, users can withdraw unlocked coins from lockup -`ModuleAccount`. - -``` {.go} -type MsgBeginUnlockingAll struct { - Owner string -} -``` - -**State modifications:** - -- Fetch all unlockable `PeriodLock`s that has not started unlocking - yet -- Set `PeriodLock`'s unlock time -- Remove lock references from `NotUnlocking` queue -- Add lock references to `Unlocking` queue - -### Begin unlock for a lock - -Once time is over, users can withdraw unlocked coins from lockup -`ModuleAccount`. - -``` {.go} -type MsgBeginUnlocking struct { - Owner string - ID uint64 -} -``` - -**State modifications:** - -- Check `PeriodLock` with `ID` specified by `MsgBeginUnlocking` is not - started unlocking yet -- Set `PeriodLock`'s unlock time -- Remove lock references from `NotUnlocking` queue -- Add lock references to `Unlocking` queue - -Note: If another module needs past `PeriodLock` item, it can log the -details themselves using the hooks. - -## Events - -The lockup module emits the following events: - -### Handlers - -#### MsgLockTokens - -| Type | Attribute Key | Attribute Value | -| --------------| ------------------| -----------------| -| lock\_tokens | period\_lock\_id | {periodLockID} | -| lock\_tokens | owner | {owner} | -| lock\_tokens | amount | {amount} | -| lock\_tokens | duration | {duration} | -| lock\_tokens | unlock\_time | {unlockTime} | -| message | action | lock\_tokens | -| message | sender | {owner} | -| transfer | recipient | {moduleAccount} | -| transfer | sender | {owner} | -| transfer | amount | {amount} | - -#### MsgBeginUnlocking - -| Type | Attribute Key | Attribute Value | -| ---------------| ------------------| ------------------| -| begin\_unlock | period\_lock\_id | {periodLockID} | -| begin\_unlock | owner | {owner} | -| begin\_unlock | amount | {amount} | -| begin\_unlock | duration | {duration} | -| begin\_unlock | unlock\_time | {unlockTime} | -| message | action | begin\_unlocking | -| message | sender | {owner} | - -#### MsgBeginUnlockingAll - -| Type | Attribute Key | Attribute Value | -| --------------------| ------------------| -----------------------| -| begin\_unlock\_all | owner | {owner} | -| begin\_unlock\_all | unlocked\_coins | {unlockedCoins} | -| begin\_unlock | period\_lock\_id | {periodLockID} | -| begin\_unlock | owner | {owner} | -| begin\_unlock | amount | {amount} | -| begin\_unlock | duration | {duration} | -| begin\_unlock | unlock\_time | {unlockTime} | -| message | action | begin\_unlocking\_all | -| message | sender | {owner} | - -### Endblocker - -#### Automatic withdraw when unlock time mature - -| Type | Attribute Key | Attribute Value | -| ----------------| ------------------| -----------------| -| message | action | unlock\_tokens | -| message | sender | {owner} | -| transfer\[\] | recipient | {owner} | -| transfer\[\] | sender | {moduleAccount} | -| transfer\[\] | amount | {unlockAmount} | -| unlock\[\] | period\_lock\_id | {owner} | -| unlock\[\] | owner | {lockID} | -| unlock\[\] | duration | {lockDuration} | -| unlock\[\] | unlock\_time | {unlockTime} | -| unlock\_tokens | owner | {owner} | -| unlock\_tokens | unlocked\_coins | {totalAmount} | - -## Keepers - -### Lockup Keeper - -Lockup keeper provides utility functions to store lock queues and query -locks. - -```go -// Keeper is the interface for lockup module keeper -type Keeper interface { - // GetModuleBalance Returns full balance of the module - GetModuleBalance(sdk.Context) sdk.Coins - // GetModuleLockedCoins Returns locked balance of the module - GetModuleLockedCoins(sdk.Context) sdk.Coins - // GetAccountUnlockableCoins Returns whole unlockable coins which are not withdrawn yet - GetAccountUnlockableCoins(sdk.Context, addr sdk.AccAddress) sdk.Coins - // GetAccountUnlockingCoins Returns whole unlocking coins - GetAccountUnlockingCoins(sdk.Context, addr sdk.AccAddress) sdk.Coins - // GetAccountLockedCoins Returns a locked coins that can't be withdrawn - GetAccountLockedCoins(sdk.Context, addr sdk.AccAddress) sdk.Coins - // GetAccountLockedPastTime Returns the total locks of an account whose unlock time is beyond timestamp - GetAccountLockedPastTime(sdk.Context, addr sdk.AccAddress, timestamp time.Time) []types.PeriodLock - // GetAccountUnlockedBeforeTime Returns the total unlocks of an account whose unlock time is before timestamp - GetAccountUnlockedBeforeTime(sdk.Context, addr sdk.AccAddress, timestamp time.Time) []types.PeriodLock - // GetAccountLockedPastTimeDenom is equal to GetAccountLockedPastTime but denom specific - GetAccountLockedPastTimeDenom(ctx sdk.Context, addr sdk.AccAddress, denom string, timestamp time.Time) []types.PeriodLock - - // GetAccountLockedLongerDuration Returns account locked with duration longer than specified - GetAccountLockedLongerDuration(sdk.Context, addr sdk.AccAddress, duration time.Duration) []types.PeriodLock - // GetAccountLockedLongerDurationDenom Returns account locked with duration longer than specified with specific denom - GetAccountLockedLongerDurationDenom(sdk.Context, addr sdk.AccAddress, denom string, duration time.Duration) []types.PeriodLock - // GetLocksPastTimeDenom Returns the locks whose unlock time is beyond timestamp - GetLocksPastTimeDenom(ctx sdk.Context, addr sdk.AccAddress, denom string, timestamp time.Time) []types.PeriodLock - // GetLocksLongerThanDurationDenom Returns the locks whose unlock duration is longer than duration - GetLocksLongerThanDurationDenom(ctx sdk.Context, addr sdk.AccAddress, denom string, duration time.Duration) []types.PeriodLock - // GetLockByID Returns lock from lockID - GetLockByID(sdk.Context, lockID uint64) (*types.PeriodLock, error) - // GetPeriodLocks Returns the period locks on pool - GetPeriodLocks(sdk.Context) ([]types.PeriodLock, error) - // UnlockAllUnlockableCoins Unlock all unlockable coins - UnlockAllUnlockableCoins(sdk.Context, account sdk.AccAddress) (sdk.Coins, error) - // LockTokens lock tokens from an account for specified duration - LockTokens(sdk.Context, owner sdk.AccAddress, coins sdk.Coins, duration time.Duration) (types.PeriodLock, error) - // AddTokensToLock locks more tokens into a lockup - AddTokensToLock(ctx sdk.Context, owner sdk.AccAddress, lockID uint64, coins sdk.Coins) (*types.PeriodLock, error) - // Lock is a utility to lock coins into module account - Lock(sdk.Context, lock types.PeriodLock) error - // Unlock is a utility to unlock coins from module account - Unlock(sdk.Context, lock types.PeriodLock) error - GetSyntheticLockup(ctx sdk.Context, lockID uint64, suffix string) (*types.SyntheticLock, error) - GetAllSyntheticLockupsByLockup(ctx sdk.Context, lockID uint64) []types.SyntheticLock - GetAllSyntheticLockups(ctx sdk.Context) []types.SyntheticLock - // CreateSyntheticLockup create synthetic lockup with lock id and denom suffix - CreateSyntheticLockup(ctx sdk.Context, lockID uint64, suffix string, unlockDuration time.Duration) error - // DeleteSyntheticLockup delete synthetic lockup with lock id and suffix - DeleteSyntheticLockup(ctx sdk.Context, lockID uint64, suffix string) error - DeleteAllMaturedSyntheticLocks(ctx sdk.Context) -``` - -### Lock Admin Keeper - -Lockup admin keeper provides god privilege functions to remove tokens -from locks and create new locks. - -```go -// AdminKeeper defines a god priviledge keeper functions to remove tokens from locks and create new locks -// For the governance system of token pools, we want a "ragequit" feature -// So governance changes will take 1 week to go into effect -// During that time, people can choose to "ragequit" which means they would leave the original pool -// and form a new pool with the old parameters but if they still had 2 months of lockup left, -// their liquidity still needs to be 2 month lockup-ed, just in the new pool -// And we need to replace their pool1 LP tokens with pool2 LP tokens with the same lock duration and end time - -type AdminKeeper interface { - Keeper - - // this unlock previous lockID and create a new lock with newCoins with same duration and endtime - Relock(sdk.Context, lockID uint64, newCoins sdk.Coins) error - // this unlock without time check with an admin priviledge - BreakLock(sdk.Context, lockID uint64) error -} -``` - -## Hooks - -In this section we describe the "hooks" that `lockup` module provide for -other modules. - -### Tokens Locked - -On lock/unlock events, lockup module execute hooks for other modules to -make following actions. - -``` go - OnTokenLocked(ctx sdk.Context, address sdk.AccAddress, lockID uint64, amount sdk.Coins, lockDuration time.Duration, unlockTime time.Time) - OnTokenUnlocked(ctx sdk.Context, address sdk.AccAddress, lockID uint64, amount sdk.Coins, lockDuration time.Duration, unlockTime time.Time) -``` - -## Parameters - -The lockup module contains the following parameters: - -| Key | Type | Example | -| ---------------------- | --------------- | ------- | - -Note: Currently no parameters are set for `lockup` module, we will need -to move lockable durations from incentives module to lockup module. - -## Endblocker - -### Withdraw tokens after unlock time mature - -Once time is over, endblocker withdraw coins from matured locks and -coins are sent from lockup `ModuleAccount`. - -**State modifications:** - -- Fetch all unlockable `PeriodLock`s that `Owner` has not withdrawn - yet -- Remove `PeriodLock` records from the state -- Transfer the tokens from lockup `ModuleAccount` to the - `MsgUnlockTokens.Owner`. - -### Remove synthetic locks after removal time mature - -For synthetic lockups, no coin movement is made, but lockup record and -reference queues are removed. - -**State modifications:** - -- Fetch all synthetic lockups that is matured -- Remove `SyntheticLock` records from the state along with reference - queues - -## Transactions - -### lock-tokens - -Bond tokens in a LP for a set duration - -```sh -osmosisd tx lockup lock-tokens [tokens] --duration --from --chain-id -``` - -::: details Example - -To lockup `15.527546134174465309gamm/pool/3` tokens for a `one day` bonding period from `WALLET_NAME` on the osmosis mainnet: - -```bash -osmosisd tx lockup lock-tokens 15527546134174465309gamm/pool/3 --duration="24h" --from WALLET_NAME --chain-id osmosis-1 -``` - -To lockup `25.527546134174465309gamm/pool/13` tokens for a `one week` bonding period from `WALLET_NAME` on the osmosis testnet: - -```bash -osmosisd tx lockup lock-tokens 25527546134174465309gamm/pool/13 --duration="168h" --from WALLET_NAME --chain-id osmo-test-4 -``` - -To lockup `35.527546134174465309 gamm/pool/197` tokens for a `two week` bonding period from `WALLET_NAME` on the osmosis mainnet: - -```bash -osmosisd tx lockup lock-tokens 35527546134174465309gamm/pool/197 --duration="336h" --from WALLET_NAME --chain-id osmosis-1 -``` -::: - - -### begin-unlock-by-id - -Begin the unbonding process for tokens given their unique lock ID - -```sh -osmosisd tx lockup begin-unlock-by-id [id] --from --chain-id -``` - -::: details Example - -To begin the unbonding time for all bonded tokens under id `75` from `WALLET_NAME` on the osmosis mainnet: - -```bash -osmosisd tx lockup begin-unlock-by-id 75 --from WALLET_NAME --chain-id osmosis-1 -``` -::: -::: warning Note -The ID corresponds to the unique ID given to your lockup transaction (explained more in lock-by-id section) -::: - -### begin-unlock-tokens - -Begin unbonding process for all bonded tokens in a wallet - -```sh -osmosisd tx lockup begin-unlock-tokens --from --chain-id -``` - -::: details Example - -To begin unbonding time for ALL pools and ALL bonded tokens in `WALLET_NAME` on the osmosis mainnet: - - -```bash -osmosisd tx lockup begin-unlock-tokens --from=WALLET_NAME --chain-id=osmosis-1 --yes -``` -::: - -## Queries - -In this section we describe the queries required on grpc server. - -``` protobuf -// Query defines the gRPC querier service. -service Query { - // Return full balance of the module - rpc ModuleBalance(ModuleBalanceRequest) returns (ModuleBalanceResponse); - // Return locked balance of the module - rpc ModuleLockedAmount(ModuleLockedAmountRequest) returns (ModuleLockedAmountResponse); - - // Returns unlockable coins which are not withdrawn yet - rpc AccountUnlockableCoins(AccountUnlockableCoinsRequest) returns (AccountUnlockableCoinsResponse); - // Returns unlocking coins - rpc AccountUnlockingCoins(AccountUnlockingCoinsRequest) returns (AccountUnlockingCoinsResponse) {} - // Return a locked coins that can't be withdrawn - rpc AccountLockedCoins(AccountLockedCoinsRequest) returns (AccountLockedCoinsResponse); - - // Returns locked records of an account with unlock time beyond timestamp - rpc AccountLockedPastTime(AccountLockedPastTimeRequest) returns (AccountLockedPastTimeResponse); - // Returns locked records of an account with unlock time beyond timestamp excluding tokens started unlocking - rpc AccountLockedPastTimeNotUnlockingOnly(AccountLockedPastTimeNotUnlockingOnlyRequest) returns (AccountLockedPastTimeNotUnlockingOnlyResponse) {} - // Returns unlocked records with unlock time before timestamp - rpc AccountUnlockedBeforeTime(AccountUnlockedBeforeTimeRequest) returns (AccountUnlockedBeforeTimeResponse); - - // Returns lock records by address, timestamp, denom - rpc AccountLockedPastTimeDenom(AccountLockedPastTimeDenomRequest) returns (AccountLockedPastTimeDenomResponse); - // Returns lock record by id - rpc LockedByID(LockedRequest) returns (LockedResponse); - - // Returns account locked records with longer duration - rpc AccountLockedLongerDuration(AccountLockedLongerDurationRequest) returns (AccountLockedLongerDurationResponse); - // Returns account locked records with longer duration excluding tokens started unlocking - rpc AccountLockedLongerDurationNotUnlockingOnly(AccountLockedLongerDurationNotUnlockingOnlyRequest) returns (AccountLockedLongerDurationNotUnlockingOnlyResponse) {} - // Returns account's locked records for a denom with longer duration - rpc AccountLockedLongerDurationDenom(AccountLockedLongerDurationDenomRequest) returns (AccountLockedLongerDurationDenomResponse); - - // Returns account locked records with a specific duration - rpc AccountLockedDuration(AccountLockedDurationRequest) returns (AccountLockedDurationResponse); -} -``` - -### account-locked-beforetime - -Query an account's unlocked records after a specified time (UNIX) has passed - -In other words, if an account unlocked all their bonded tokens the moment the query was executed, only the locks that would have completed their bond time requirement by the time the `TIMESTAMP` is reached will be returned. - -::: details Example - -In this example, the current UNIX time is `1639776682`, 2 days from now is approx `1639971082`, and 15 days from now is approx `1641094282`. - -An account's `ADDRESS` is locked in both the `1 day` and `1 week` gamm/pool/3. To query the `ADDRESS` with a timestamp 2 days from now `1639971082`: - -```bash -osmosisd query lockup account-locked-beforetime ADDRESS 1639971082 -``` - -In this example will output the `1 day` lock but not the `1 week` lock: - -```bash -locks: -- ID: "571839" - coins: - - amount: "15527546134174465309" - denom: gamm/pool/3 - duration: 24h - end_time: "2021-12-18T23:32:58.900715388Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` - -If querying the same `ADDRESS` with a timestamp 15 days from now `1641094282`: - -```bash -osmosisd query lockup account-locked-beforetime ADDRESS 1641094282 -``` - -In this example will output both the `1 day` and `1 week` lock: - -```bash -locks: -- ID: "572027" - coins: - - amount: "16120691802759484268" - denom: gamm/pool/3 - duration: 604800.000006193s - end_time: "0001-01-01T00:00:00Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -- ID: "571839" - coins: - - amount: "15527546134174465309" - denom: gamm/pool/3 - duration: 24h - end_time: "2021-12-18T23:32:58.900715388Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` -::: - - -### account-locked-coins - -Query an account's locked (bonded) LP tokens - -```sh -osmosisd query lockup account-locked-coins [address] -``` - -:::: details Example - -```bash -osmosisd query lockup account-locked-coins osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` - -An example output: - -```bash -coins: -- amount: "413553955105681228583" - denom: gamm/pool/1 -- amount: "32155370994266157441309" - denom: gamm/pool/10 -- amount: "220957857520769912023" - denom: gamm/pool/3 -- amount: "31648237936933949577" - denom: gamm/pool/42 -- amount: "14162624050980051053569" - denom: gamm/pool/5 -- amount: "1023186951315714985896914" - denom: gamm/pool/9 -``` -::: warning Note -All GAMM amounts listed are 10^18. Move the decimal place to the left 18 places to get the GAMM amount listed in the GUI. - -You may also specify a --height flag to see bonded LP tokens at a specified height (note: if running a pruned node, this may result in an error) -::: -:::: - -### account-locked-longer-duration - -Query an account's locked records that are greater than or equal to a specified lock duration - -```sh -osmosisd query lockup account-locked-longer-duration [address] [duration] -``` - -::: details Example - -Here is an example of querying an `ADDRESS` for all `1 day` or greater bonding periods: - -```bash -osmosisd query lockup account-locked-longer-duration osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 24h -``` - -An example output: - -```bash -locks: -- ID: "572027" - coins: - - amount: "16120691802759484268" - denom: gamm/pool/3 - duration: 604800.000006193s - end_time: "0001-01-01T00:00:00Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -- ID: "571839" - coins: - - amount: "15527546134174465309" - denom: gamm/pool/3 - duration: 24h - end_time: "2021-12-18T23:32:58.900715388Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` -::: - - -### account-locked-longer-duration-denom - -Query an account's locked records for a denom that is locked equal to or greater than the specified duration AND match a specified denom - -```sh -osmosisd query lockup account-locked-longer-duration-denom [address] [duration] [denom] -``` - -::: details Example - -Here is an example of an `ADDRESS` that is locked in both the `1 day` and `1 week` for both the gamm/pool/3 and gamm/pool/1, then queries the `ADDRESS` for all bonding periods equal to or greater than `1 day` for just the gamm/pool/3: - -```bash -osmosisd query lockup account-locked-longer-duration-denom osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 24h gamm/pool/3 -``` - -An example output: - -```bash -locks: -- ID: "571839" - coins: - - amount: "15527546134174465309" - denom: gamm/pool/3 - duration: 24h - end_time: "0001-01-01T00:00:00Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -- ID: "572027" - coins: - - amount: "16120691802759484268" - denom: gamm/pool/3 - duration: 604800.000006193s - end_time: "0001-01-01T00:00:00Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` - -As shown, the gamm/pool/3 is returned but not the gamm/pool/1 due to the denom filter. -::: - - -### account-locked-longer-duration-not-unlocking - -Query an account's locked records for a denom that is locked equal to or greater than the specified duration AND is not in the process of being unlocked - -```sh -osmosisd query lockup account-locked-longer-duration-not-unlocking [address] [duration] -``` - -::: details Example - -Here is an example of an `ADDRESS` that is locked in both the `1 day` and `1 week` gamm/pool/3, begins unlocking process for the `1 day` bond, and queries the `ADDRESS` for all bonding periods equal to or greater than `1 day` that are not unbonding: - -```bash -osmosisd query lockup account-locked-longer-duration-not-unlocking osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 24h -``` - -An example output: - -```bash -locks: -- ID: "571839" - coins: - - amount: "16120691802759484268" - denom: gamm/pool/3 - duration: 604800.000006193s - end_time: "0001-01-01T00:00:00Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` - -The `1 day` bond does not show since it is in the process of unbonding. -::: - - -### account-locked-pasttime - -Query the locked records of an account with the unlock time beyond timestamp (UNIX) - -```bash -osmosisd query lockup account-locked-pasttime [address] [timestamp] -``` - -::: details Example - -Here is an example of an account that is locked in both the `1 day` and `1 week` gamm/pool/3. In this example, the UNIX time is currently `1639776682` and queries an `ADDRESS` for UNIX time two days later from the current time (which in this example would be `1639971082`) - -```bash -osmosisd query lockup account-locked-pasttime osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 1639971082 -``` - -The example output: - -```bash -locks: -- ID: "572027" - coins: - - amount: "16120691802759484268" - denom: gamm/pool/3 - duration: 604800.000006193s - end_time: "0001-01-01T00:00:00Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` - -Note that the `1 day` lock ID did not display because, if the unbonding time began counting down from the time the command was executed, the bonding period would be complete before the two day window given by the UNIX timestamp input. -::: - - -### account-locked-pasttime-denom - -Query the locked records of an account with the unlock time beyond timestamp (unix) and filter by a specific denom - -```bash -osmosisd query lockup account-locked-pasttime-denom osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 [timestamp] [denom] -``` - -::: details Example - -Here is an example of an account that is locked in both the `1 day` and `1 week` gamm/pool/3 and `1 day` and `1 week` gamm/pool/1. In this example, the UNIX time is currently `1639776682` and queries an `ADDRESS` for UNIX time two days later from the current time (which in this example would be `1639971082`) and filters for gamm/pool/3 - -```bash -osmosisd query lockup account-locked-pasttime-denom osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 1639971082 gamm/pool/3 -``` - -The example output: - -```bash -locks: -- ID: "572027" - coins: - - amount: "16120691802759484268" - denom: gamm/pool/3 - duration: 604800.000006193s - end_time: "0001-01-01T00:00:00Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` - -Note that the `1 day` lock ID did not display because, if the unbonding time began counting down from the time the command was executed, the bonding period would be complete before the two day window given by the UNIX timestamp input. Additionally, neither of the `1 day` or `1 week` lock IDs for gamm/pool/1 showed due to the denom filter. -::: - - -### account-locked-pasttime-not-unlocking - -Query the locked records of an account with the unlock time beyond timestamp (unix) AND is not in the process of unlocking - -```sh -osmosisd query lockup account-locked-pasttime [address] [timestamp] -``` - -::: details Example - -Here is an example of an account that is locked in both the `1 day` and `1 week` gamm/pool/3. In this example, the UNIX time is currently `1639776682` and queries an `ADDRESS` for UNIX time two days later from the current time (which in this example would be `1639971082`) AND is not unlocking: - -```bash -osmosisd query lockup account-locked-pasttime osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 1639971082 -``` - -The example output: - -```bash -locks: -- ID: "572027" - coins: - - amount: "16120691802759484268" - denom: gamm/pool/3 - duration: 604800.000006193s - end_time: "0001-01-01T00:00:00Z" - owner: osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` - -Note that the `1 day` lock ID did not display because, if the unbonding time began counting down from the time the command was executed, the bonding period would be complete before the two day window given by the UNIX timestamp input. Additionally, if ID 572027 were to begin the unlocking process, the query would have returned blank. -::: - - -### account-unlockable-coins - -Query an address's LP shares that have completed the unlocking period and are ready to be withdrawn - -```bash -osmosisd query lockup account-unlockable-coins ADDRESS -``` - - - -### account-unlocking-coins - -Query an address's LP shares that are currently unlocking - -```sh -osmosisd query lockup account-unlocking-coins [address] -``` - -::: details Example - -```bash -osmosisd query lockup account-unlocking-coins osmo1xqhlshlhs5g0acqgrkafdemvf5kz4pp4c2x259 -``` - -Example output: - -```bash -coins: -- amount: "15527546134174465309" - denom: gamm/pool/3 -``` -::: - - -### lock-by-id - -Query a lock record by its ID - -```sh -osmosisd query lockup lock-by-id [id] -``` - -::: details Example - -Every time a user bonds tokens to an LP, a unique lock ID is created for that transaction. - -Here is an example viewing the lock record for ID 9: - -```bash -osmosisd query lockup lock-by-id 9 -``` - -And its output: - -```bash -lock: - ID: "9" - coins: - - amount: "2449472670508255020346507" - denom: gamm/pool/2 - duration: 336h - end_time: "0001-01-01T00:00:00Z" - owner: osmo16r39ghhwqjcwxa8q3yswlz8jhzldygy66vlm82 -``` - -In summary, this shows wallet `osmo16r39ghhwqjcwxa8q3yswlz8jhzldygy66vlm82` bonded `2449472.670 gamm/pool/2` LP shares for a `2 week` locking period. -::: - - -### module-balance - -Query the balance of all LP shares (bonded and unbonded) - -```sh -osmosisd query lockup module-balance -``` - -::: details Example - -```bash -osmosisd query lockup module-balance -``` - -An example output: - -```bash -coins: -- amount: "118851922644152734549498647" - denom: gamm/pool/1 -- amount: "2165392672114512349039263626" - denom: gamm/pool/10 -- amount: "9346769826591025900804" - denom: gamm/pool/13 -- amount: "229347389639275840044722315" - denom: gamm/pool/15 -- amount: "81217698776012800247869" - denom: gamm/pool/183 -- amount: "284253336860259874753775" - denom: gamm/pool/197 -- amount: "664300804648059580124426710" - denom: gamm/pool/2 -- amount: "5087102794776326441530430" - denom: gamm/pool/22 -- amount: "178900843925960029029567880" - denom: gamm/pool/3 -- amount: "64845148811263846652326124" - denom: gamm/pool/4 -- amount: "177831279847453210600513" - denom: gamm/pool/42 -- amount: "18685913727862493301261661338" - denom: gamm/pool/5 -- amount: "23579028640963777558149250419" - denom: gamm/pool/6 -- amount: "1273329284855460149381904976" - denom: gamm/pool/7 -- amount: "625252103927082207683116933" - denom: gamm/pool/8 -- amount: "1148475247281090606949382402" - denom: gamm/pool/9 -``` -::: - - -### module-locked-amount - -Query the balance of all bonded LP shares - -```sh -osmosisd query lockup module-locked-amount -``` - -::: details Example - -```bash -osmosisd query lockup module-locked-amount -``` - -An example output: - -```bash - - "coins": - { - "denom": "gamm/pool/1", - "amount": "247321084020868094262821308" - }, - { - "denom": "gamm/pool/10", - "amount": "2866946821820635047398966697" - }, - { - "denom": "gamm/pool/13", - "amount": "9366580741745176812984" - }, - { - "denom": "gamm/pool/15", - "amount": "193294911294343602187680438" - }, - { - "denom": "gamm/pool/183", - "amount": "196722012808526595790871" - }, - { - "denom": "gamm/pool/197", - "amount": "1157025085661167198918241" - }, - { - "denom": "gamm/pool/2", - "amount": "633051132033131378888258047" - }, - { - "denom": "gamm/pool/22", - "amount": "3622601406125950733194696" - }, -... - -``` - -NOTE: This command seems to only work on gRPC and on CLI returns an EOF error. -::: - - - -### output-all-locks - -Output all locks into a json file - -```sh -osmosisd query lockup output-all-locks [max lock ID] -``` - -:::: details Example - -This example command outputs locks 1-1000 and saves to a json file: - -```bash -osmosisd query lockup output-all-locks 1000 -``` -::: warning Note -If a lockup has been completed, the lockup status will show as "0" (or successful) and no further information will be available. To get further information on a completed lock, run the lock-by-id query. -::: -:::: - - -### total-locked-of-denom - -Query locked amount for a specific denom in the duration provided - -```sh -osmosisd query lockup total-locked-of-denom [denom] --min-duration -``` - -:::: details Example - -This example command outputs the amount of `gamm/pool/2` LP shares that locked in the `2 week` bonding period: - -```bash -osmosisd query lockup total-locked-of-denom gamm/pool/2 --min-duration "336h" -``` - -Which, at the time of this writing outputs `14106985399822075248947045` which is equivalent to `14106985.3998 gamm/pool/2` - -NOTE: As of this writing, there is a bug that defaults the min duration to days instead of seconds. Ensure you specify the time in seconds to get the correct response. -::: \ No newline at end of file diff --git a/x/pool-incentives/spec/README.md b/x/pool-incentives/README.md similarity index 92% rename from x/pool-incentives/spec/README.md rename to x/pool-incentives/README.md index 9dabfc087bd..d3d211de08b 100644 --- a/x/pool-incentives/spec/README.md +++ b/x/pool-incentives/README.md @@ -1,9 +1,8 @@ # Pool Incentives -The `pool-incentives` module is separate but related to the `incentives` module. When a pool is created using the `GAMM` module, the `pool-incentives` module automatically creates individual gauges in the `incentives` module for every lock duration that exists in that pool. The `pool-incentives` module also takes the `pool_incentives` distributed from the `gov` module and distributes it to the various incentivized gauges. - ## Abstract -The `pool-incentives` module is separate but related to the `incentives` module. When a pool is created using the `GAMM` module, the `pool-incentives` module automatically creates individual gauges in the `incentives` module for every lock duration that exists in that pool. The `pool-incentives` module also takes takes the `pool_incentives` distributed from the `gov` module and distributes it to the various incentivized gauges. +The `pool-incentives` module is separate but related to the `incentives` module. When a pool is created using the `GAMM` module, the `pool-incentives` module automatically creates individual gauges in the `incentives` module for every lock duration that exists in that pool. +The `pool-incentives` module also takes the `pool_incentives` distributed from the `gov` module and distributes it to the various incentivized gauges. ## Contents @@ -28,7 +27,7 @@ selected gauges. ## State -#### Genesis states +### Genesis states ```go type GenesisState struct { @@ -86,7 +85,7 @@ type DistrRecord struct { `DistrRecord`. Governance can modify DistrInfo via `UpdatePoolIncentivesProposal` proposal. -#### UpdatePoolIncentivesProposal +### UpdatePoolIncentivesProposal ```go type UpdatePoolIncentivesProposal struct { @@ -211,7 +210,7 @@ osmosisd query poolincentives distr-info An example output: -``` +```bash - gauge_id: "1877" weight: "60707" - gauge_id: "1878" @@ -243,7 +242,7 @@ osmosisd query pool-incentives external-incentivized-gauges An example output: -``` +```bash - coins: - amount: "596400000" denom: ibc/0EF15DF2F02480ADE0BB6E85D9EBB5DAEA2836D3860E9F97F9AADE4F57A31AA0 @@ -298,7 +297,7 @@ osmosisd query poolincentives gauge-ids 1 An example output: -``` +```bash gauge_ids_with_duration: - duration: 86400s gauge_id: "1" @@ -329,7 +328,7 @@ osmosisd query poolincentives incentivized-pools An example output: -``` +```bash - gauge_id: "1897" lockable_duration: 86400s pool_id: "602" @@ -362,7 +361,7 @@ osmosisd query poolincentives lockable-durations An example output: -``` +```bash lockable_durations: - 86400s - 604800s @@ -388,7 +387,7 @@ osmosisd query poolincentives params An example output: -``` +```bash params: minted_denom: uosmo ``` diff --git a/x/superfluid/spec/README.md b/x/superfluid/README.md similarity index 99% rename from x/superfluid/spec/README.md rename to x/superfluid/README.md index 7bb4a692dea..5bcf8d1542e 100644 --- a/x/superfluid/spec/README.md +++ b/x/superfluid/README.md @@ -96,7 +96,7 @@ process is found below:

- +

diff --git a/x/superfluid/spec/superfluiddiagram.png b/x/superfluid/superfluiddiagram.png similarity index 100% rename from x/superfluid/spec/superfluiddiagram.png rename to x/superfluid/superfluiddiagram.png diff --git a/x/txfees/README.md b/x/txfees/README.md index da1c3489215..0cabc734672 100644 --- a/x/txfees/README.md +++ b/x/txfees/README.md @@ -1,90 +1,53 @@ # Txfees -The txfees modules allows nodes to easily support many tokens for usage -as txfees, while letting node operators only specify their tx fee -parameters for a single "base" asset. This is done by having this module -maintain an allow-list of token denoms which can be used as tx fees, -each with some associated metadata. Then this metadata is used in tandem -with a "Spot Price Calculator" provided to the module, to convert the -provided tx fees into their equivalent value in the base denomination. -Currently the only supported metadata & spot price calculator is using a -GAMM pool ID & the GAMM keeper. +The txfees modules allows nodes to easily support many tokens for usage as txfees, while letting node operators only specify their tx fee parameters for a single "base" asset. +This is done by having this module maintain an allow-list of token denoms which can be used as tx fees, each with some associated metadata. +Then this metadata is used in tandem with a "Spot Price Calculator" provided to the module, to convert the provided tx fees into their equivalent value in the base denomination. +Currently the only supported metadata & spot price calculator is using a GAMM pool ID & the GAMM keeper. ## State Changes -- Adds a whitelist of tokens that can be used as fees on the chain. - - Any token not on this list cannot be provided as a tx fee. - - Any fee that is paid with a token that is on this list but is +* Adds a whitelist of tokens that can be used as fees on the chain. + * Any token not on this list cannot be provided as a tx fee. + * Any fee that is paid with a token that is on this list but is not the base denom will be collected in a separate module account to be batched and swapped into the base denom at the end of each epoch. -- Adds a new SDK message for creating governance proposals for adding - new TxFee denoms. +* Adds a new SDK message for creating governance proposals for adding new TxFee denoms. ## Local Mempool Filters Added -- If you specify a min-tx-fee in the \$BASEDENOM then - - Your node will allow any tx w/ tx fee in the whitelist of fees, - and a sufficient osmo-equivalent price to enter your mempool - - Txs with valid non-basedenom tx fees will be routed to a - separate module account. At the end of each epoch, these - fees will be swapped into the basedenom token and - transferred to the primary tx fee module account to be - distributed to validators/delegators. - - The osmo-equivalent price for determining sufficiency is - rechecked after every block. (During the mempools RecheckTx) - - TODO: further consider if we want to take this tradeoff. - Allows someone who manipulates price for one block to flush - txs using that asset as fee from most of the networks' - mempools. - - The simple alternative is only check fee equivalency at a - txs entry into the mempool, which allows someone to - manipulate price down to have many txs enter the chain at - low cost. - - Another alternative is to use TWAP instead of Spot Price - once it is available on-chain - - The former concern isn't very worrisome as long as some - nodes have 0 min tx fees. -- A separate min-gas-fee can be set on every node for arbitrage txs. - Methods of detecting an arb tx atm - - does start token of a swap = final token of swap (definitionally - correct) - - does it have multiple swap messages, with different tx ins. If - so, we assume its an arb. - - This has false positives, but is intended to avoid the - obvious solution of splitting an arb into multiple messages. - - We record all denoms seen across all swaps, and see if any - duplicates. (TODO) - - Contains both JoinPool and ExitPool messages in one tx. - - Has some false positives. - - These false positives seem like they primarily will get hit - during batching of many distinct operations, not really in one - atomic action. -- A max wanted gas per any tx can be set to filter out attack txes. -- If tx wanted gas \> than predefined threshold of 1M, then separate - 'min-gas-price-for-high-gas-tx' option used to calculate min gas - price. - -## New SDK messages - -TODO: Describe - -### CLI commands - -TODO: Describe - -### Queries - -TODO: Describe - -### Code structure - -TODO: Describe - -### Future directions - -- Want to add in a system to add in general "tx fee credits" for - different on-chain usages - - e.g. making 0 fee txs under certain usecases -- If other chains would like to use this, we should brainstorm - mechanisms for extending the metadata proto fields +* If you specify a min-tx-fee in the $BASEDENOM then + * Your node will allow any tx w/ tx fee in the whitelist of fees, and a sufficient osmo-equivalent price to enter your mempool + * The osmo-equivalent price for determining sufficiency is rechecked after every block. (During the mempools RecheckTx) + * TODO: further consider if we want to take this tradeoff. Allows someone who manipulates price for one block to flush txs using that asset as fee from most of the networks' mempools. + * The simple alternative is only check fee equivalency at a txs entry into the mempool, which allows someone to manipulate price down to have many txs enter the chain at low cost. + * Another alternative is to use TWAP instead of Spot Price once it is available on-chain + * The former concern isn't very worrisome as long as some nodes have 0 min tx fees. +* A separate min-gas-fee can be set on every node for arbitrage txs. Methods of detecting an arb tx atm + * does start token of a swap = final token of swap (definitionally correct) + * does it have multiple swap messages, with different tx ins. If so, we assume its an arb. + * This has false positives, but is intended to avoid the obvious solution of splitting an arb into multiple messages. + * We record all denoms seen across all swaps, and see if any duplicates. (TODO) + * Contains both JoinPool and ExitPool messages in one tx. + * Has some false positives. + * These false positives seem like they primarily will get hit during batching of many distinct operations, not really in one atomic action. +* A max wanted gas per any tx can be set to filter out attack txes. +* If tx wanted gas > than predefined threshold of 1M, then separate 'min-gas-price-for-high-gas-tx' option used to calculate min gas price. + +## Queries + +base-denom +- Query the base fee denom + +denom-pool-id +- Query the pool id associated with a specific whitelisted fee token + +fee-tokens +- Query the list of non-basedenom fee tokens and their associated pool ids + +## Future directions + +* Want to add in a system to add in general "tx fee credits" for different on-chain usages + * e.g. making 0 fee txs under certain usecases +* If other chains would like to use this, we should brainstorm mechanisms for extending the metadata proto fields diff --git a/x/txfees/spec/README.md b/x/txfees/spec/README.md deleted file mode 100644 index b88b4b30924..00000000000 --- a/x/txfees/spec/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# Txfees - -The txfees modules allows nodes to easily support many tokens for usage as txfees, while letting node operators only specify their tx fee parameters for a single "base" asset. -This is done by having this module maintain an allow-list of token denoms which can be used as tx fees, each with some associated metadata. -Then this metadata is used in tandem with a "Spot Price Calculator" provided to the module, to convert the provided tx fees into their equivalent value in the base denomination. -Currently the only supported metadata & spot price calculator is using a GAMM pool ID & the GAMM keeper. - -## State Changes - -* Adds a whitelist of tokens that can be used as fees on the chain. - * Any token not on this list cannot be provided as a tx fee. -* Adds a new SDK message for creating governance proposals for adding new TxFee denoms. - -## Local Mempool Filters Added - -* If you specify a min-tx-fee in the $BASEDENOM then - * Your node will allow any tx w/ tx fee in the whitelist of fees, and a sufficient osmo-equivalent price to enter your mempool - * The osmo-equivalent price for determining sufficiency is rechecked after every block. (During the mempools RecheckTx) - * TODO: further consider if we want to take this tradeoff. Allows someone who manipulates price for one block to flush txs using that asset as fee from most of the networks' mempools. - * The simple alternative is only check fee equivalency at a txs entry into the mempool, which allows someone to manipulate price down to have many txs enter the chain at low cost. - * Another alternative is to use TWAP instead of Spot Price once it is available on-chain - * The former concern isn't very worrisome as long as some nodes have 0 min tx fees. -* A separate min-gas-fee can be set on every node for arbitrage txs. Methods of detecting an arb tx atm - * does start token of a swap = final token of swap (definitionally correct) - * does it have multiple swap messages, with different tx ins. If so, we assume its an arb. - * This has false positives, but is intended to avoid the obvious solution of splitting an arb into multiple messages. - * We record all denoms seen across all swaps, and see if any duplicates. (TODO) - * Contains both JoinPool and ExitPool messages in one tx. - * Has some false positives. - * These false positives seem like they primarily will get hit during batching of many distinct operations, not really in one atomic action. -* A max wanted gas per any tx can be set to filter out attack txes. -* If tx wanted gas > than predefined threshold of 1M, then separate 'min-gas-price-for-high-gas-tx' option used to calculate min gas price. - -## Queries - -base-denom -- Query the base fee denom - -denom-pool-id -- Query the pool id associated with a specific whitelisted fee token - -fee-tokens -- Query the list of non-basedenom fee tokens and their associated pool ids - -## Future directions - -* Want to add in a system to add in general "tx fee credits" for different on-chain usages - * e.g. making 0 fee txs under certain usecases -* If other chains would like to use this, we should brainstorm mechanisms for extending the metadata proto fields From fc95cf0a231619d6b2b8a8bb200e0bac2562bc9d Mon Sep 17 00:00:00 2001 From: khanh <50263489+catShaark@users.noreply.github.com> Date: Thu, 28 Jul 2022 05:15:58 +0700 Subject: [PATCH 128/376] Remove unused cdc (#2221) * remove unused cdc * remove unused cdc in appmodule --- app/modules.go | 13 ++++++------- x/epochs/keeper/keeper.go | 5 ++--- x/epochs/module.go | 9 ++++----- x/incentives/module.go | 9 ++++----- x/lockup/keeper/genesis_test.go | 4 ++-- x/lockup/keeper/keeper.go | 2 -- x/lockup/module.go | 9 ++++----- x/pool-incentives/keeper/geneis_test.go | 4 ++-- x/pool-incentives/module.go | 5 ++--- x/superfluid/keeper/genesis_test.go | 4 ++-- x/superfluid/module.go | 9 ++++----- x/tokenfactory/keeper/keeper.go | 2 -- x/tokenfactory/module.go | 8 +++----- x/txfees/keeper/keeper.go | 2 -- x/txfees/module.go | 9 ++++----- 15 files changed, 39 insertions(+), 55 deletions(-) diff --git a/app/modules.go b/app/modules.go index 382131bbb71..95c1afdd491 100644 --- a/app/modules.go +++ b/app/modules.go @@ -124,13 +124,12 @@ func appModules( app.TransferModule, gamm.NewAppModule(appCodec, *app.GAMMKeeper, app.AccountKeeper, app.BankKeeper), twap.NewAppModule(*app.TwapKeeper), - txfees.NewAppModule(appCodec, *app.TxFeesKeeper), - incentives.NewAppModule(appCodec, *app.IncentivesKeeper, app.AccountKeeper, app.BankKeeper, app.EpochsKeeper), - lockup.NewAppModule(appCodec, *app.LockupKeeper, app.AccountKeeper, app.BankKeeper), - poolincentives.NewAppModule(appCodec, *app.PoolIncentivesKeeper), - epochs.NewAppModule(appCodec, *app.EpochsKeeper), + txfees.NewAppModule(*app.TxFeesKeeper), + incentives.NewAppModule(*app.IncentivesKeeper, app.AccountKeeper, app.BankKeeper, app.EpochsKeeper), + lockup.NewAppModule(*app.LockupKeeper, app.AccountKeeper, app.BankKeeper), + poolincentives.NewAppModule(*app.PoolIncentivesKeeper), + epochs.NewAppModule(*app.EpochsKeeper), superfluid.NewAppModule( - appCodec, *app.SuperfluidKeeper, app.AccountKeeper, app.BankKeeper, @@ -139,7 +138,7 @@ func appModules( app.GAMMKeeper, app.EpochsKeeper, ), - tokenfactory.NewAppModule(appCodec, *app.TokenFactoryKeeper, app.AccountKeeper, app.BankKeeper), + tokenfactory.NewAppModule(*app.TokenFactoryKeeper, app.AccountKeeper, app.BankKeeper), } } diff --git a/x/epochs/keeper/keeper.go b/x/epochs/keeper/keeper.go index 02f128df719..a45c8e07990 100644 --- a/x/epochs/keeper/keeper.go +++ b/x/epochs/keeper/keeper.go @@ -3,16 +3,16 @@ package keeper import ( "fmt" - "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "github.com/tendermint/tendermint/libs/log" + "github.com/osmosis-labs/osmosis/v10/x/epochs/types" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) type ( Keeper struct { - cdc codec.Codec storeKey sdk.StoreKey hooks types.EpochHooks } @@ -21,7 +21,6 @@ type ( // NewKeeper returns a new keeper by codec and storeKey inputs. func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey) *Keeper { return &Keeper{ - cdc: cdc, storeKey: storeKey, } } diff --git a/x/epochs/module.go b/x/epochs/module.go index de6c17ee220..3af73db3c68 100644 --- a/x/epochs/module.go +++ b/x/epochs/module.go @@ -45,11 +45,10 @@ var ( // AppModuleBasic implements the AppModuleBasic interface for the capability module. type AppModuleBasic struct { - cdc codec.Codec } -func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} +func NewAppModuleBasic() AppModuleBasic { + return AppModuleBasic{} } // Name returns the capability module's name. @@ -108,9 +107,9 @@ type AppModule struct { keeper keeper.Keeper } -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { +func NewAppModule(keeper keeper.Keeper) AppModule { return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), + AppModuleBasic: NewAppModuleBasic(), keeper: keeper, } } diff --git a/x/incentives/module.go b/x/incentives/module.go index edc66cfea10..18f3dfcb9d7 100644 --- a/x/incentives/module.go +++ b/x/incentives/module.go @@ -45,12 +45,11 @@ var ( // Implements the AppModuleBasic interface for the module. type AppModuleBasic struct { - cdc codec.Codec } // NewAppModuleBasic creates a new AppModuleBasic struct. -func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} +func NewAppModuleBasic() AppModuleBasic { + return AppModuleBasic{} } // Name returns the module's name. @@ -120,12 +119,12 @@ type AppModule struct { } // NewAppModule creates a new AppModule struct. -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, +func NewAppModule(keeper keeper.Keeper, accountKeeper stakingtypes.AccountKeeper, bankKeeper stakingtypes.BankKeeper, epochKeeper types.EpochKeeper, ) AppModule { return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), + AppModuleBasic: NewAppModuleBasic(), keeper: keeper, accountKeeper: accountKeeper, bankKeeper: bankKeeper, diff --git a/x/lockup/keeper/genesis_test.go b/x/lockup/keeper/genesis_test.go index 7a5d4adc0e8..4c2ea722455 100644 --- a/x/lockup/keeper/genesis_test.go +++ b/x/lockup/keeper/genesis_test.go @@ -127,7 +127,7 @@ func TestMarshalUnmarshalGenesis(t *testing.T) { encodingConfig := osmoapp.MakeEncodingConfig() appCodec := encodingConfig.Marshaler - am := lockup.NewAppModule(appCodec, *app.LockupKeeper, app.AccountKeeper, app.BankKeeper) + am := lockup.NewAppModule(*app.LockupKeeper, app.AccountKeeper, app.BankKeeper) err := simapp.FundAccount(app.BankKeeper, ctx, acc2, sdk.Coins{sdk.NewInt64Coin("foo", 5000000)}) require.NoError(t, err) @@ -139,7 +139,7 @@ func TestMarshalUnmarshalGenesis(t *testing.T) { app := osmoapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) ctx = ctx.WithBlockTime(now.Add(time.Second)) - am := lockup.NewAppModule(appCodec, *app.LockupKeeper, app.AccountKeeper, app.BankKeeper) + am := lockup.NewAppModule(*app.LockupKeeper, app.AccountKeeper, app.BankKeeper) am.InitGenesis(ctx, appCodec, genesisExported) }) } diff --git a/x/lockup/keeper/keeper.go b/x/lockup/keeper/keeper.go index 57785528c80..c411ec9903a 100644 --- a/x/lockup/keeper/keeper.go +++ b/x/lockup/keeper/keeper.go @@ -13,7 +13,6 @@ import ( // Keeper provides a way to manage module storage. type Keeper struct { - cdc codec.Codec storeKey sdk.StoreKey hooks types.LockupHooks @@ -26,7 +25,6 @@ type Keeper struct { // NewKeeper returns an instance of Keeper. func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey, ak types.AccountKeeper, bk types.BankKeeper, dk types.DistrKeeper) *Keeper { return &Keeper{ - cdc: cdc, storeKey: storeKey, ak: ak, bk: bk, diff --git a/x/lockup/module.go b/x/lockup/module.go index 217b92c4320..74522afdca2 100644 --- a/x/lockup/module.go +++ b/x/lockup/module.go @@ -48,11 +48,10 @@ var ( // AppModuleBasic implements the AppModuleBasic interface for the capability module. type AppModuleBasic struct { - cdc codec.Codec } -func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} +func NewAppModuleBasic() AppModuleBasic { + return AppModuleBasic{} } // Name returns the capability module's name. @@ -118,11 +117,11 @@ type AppModule struct { bankKeeper stakingtypes.BankKeeper } -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, +func NewAppModule(keeper keeper.Keeper, accountKeeper stakingtypes.AccountKeeper, bankKeeper stakingtypes.BankKeeper, ) AppModule { return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), + AppModuleBasic: NewAppModuleBasic(), keeper: keeper, accountKeeper: accountKeeper, diff --git a/x/pool-incentives/keeper/geneis_test.go b/x/pool-incentives/keeper/geneis_test.go index 5468664f50b..69d258817d6 100644 --- a/x/pool-incentives/keeper/geneis_test.go +++ b/x/pool-incentives/keeper/geneis_test.go @@ -46,7 +46,7 @@ func TestMarshalUnmarshalGenesis(t *testing.T) { encodingConfig := simapp.MakeEncodingConfig() appCodec := encodingConfig.Marshaler - am := pool_incentives.NewAppModule(appCodec, *app.PoolIncentivesKeeper) + am := pool_incentives.NewAppModule(*app.PoolIncentivesKeeper) genesis := testGenesis app.PoolIncentivesKeeper.InitGenesis(ctx, &genesis) @@ -57,7 +57,7 @@ func TestMarshalUnmarshalGenesis(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) ctx = ctx.WithBlockTime(now.Add(time.Second)) - am := pool_incentives.NewAppModule(appCodec, *app.PoolIncentivesKeeper) + am := pool_incentives.NewAppModule(*app.PoolIncentivesKeeper) am.InitGenesis(ctx, appCodec, genesisExported) }) } diff --git a/x/pool-incentives/module.go b/x/pool-incentives/module.go index 8892b8ac2e0..5f963bde10d 100644 --- a/x/pool-incentives/module.go +++ b/x/pool-incentives/module.go @@ -41,7 +41,6 @@ var ( ) type AppModuleBasic struct { - cdc codec.Codec } // Name returns the pool-incentives module's name. @@ -103,9 +102,9 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQuerier(am.keeper)) } -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { +func NewAppModule(keeper keeper.Keeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, + AppModuleBasic: AppModuleBasic{}, keeper: keeper, } } diff --git a/x/superfluid/keeper/genesis_test.go b/x/superfluid/keeper/genesis_test.go index 08f42a054c0..6f6a4b5bbca 100644 --- a/x/superfluid/keeper/genesis_test.go +++ b/x/superfluid/keeper/genesis_test.go @@ -56,7 +56,7 @@ func TestMarshalUnmarshalGenesis(t *testing.T) { encodingConfig := simapp.MakeEncodingConfig() appCodec := encodingConfig.Marshaler - am := superfluid.NewAppModule(appCodec, *app.SuperfluidKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.LockupKeeper, app.GAMMKeeper, app.EpochsKeeper) + am := superfluid.NewAppModule(*app.SuperfluidKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.LockupKeeper, app.GAMMKeeper, app.EpochsKeeper) genesis := testGenesis app.SuperfluidKeeper.InitGenesis(ctx, genesis) @@ -65,7 +65,7 @@ func TestMarshalUnmarshalGenesis(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) ctx = ctx.WithBlockTime(now.Add(time.Second)) - am := superfluid.NewAppModule(appCodec, *app.SuperfluidKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.LockupKeeper, app.GAMMKeeper, app.EpochsKeeper) + am := superfluid.NewAppModule(*app.SuperfluidKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.LockupKeeper, app.GAMMKeeper, app.EpochsKeeper) am.InitGenesis(ctx, appCodec, genesisExported) }) } diff --git a/x/superfluid/module.go b/x/superfluid/module.go index 434a155a49f..c53127ca2ff 100644 --- a/x/superfluid/module.go +++ b/x/superfluid/module.go @@ -44,11 +44,10 @@ var ( // AppModuleBasic implements the AppModuleBasic interface for the capability module. type AppModuleBasic struct { - cdc codec.Codec } -func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} +func NewAppModuleBasic() AppModuleBasic { + return AppModuleBasic{} } // Name returns the capability module's name. @@ -117,7 +116,7 @@ type AppModule struct { epochKeeper types.EpochKeeper } -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, +func NewAppModule(keeper keeper.Keeper, accountKeeper stakingtypes.AccountKeeper, bankKeeper stakingtypes.BankKeeper, stakingKeeper types.StakingKeeper, lockupKeeper types.LockupKeeper, @@ -125,7 +124,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, epochKeeper types.EpochKeeper, ) AppModule { return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), + AppModuleBasic: NewAppModuleBasic(), keeper: keeper, accountKeeper: accountKeeper, diff --git a/x/tokenfactory/keeper/keeper.go b/x/tokenfactory/keeper/keeper.go index 9b885a3b4a7..5841540185c 100644 --- a/x/tokenfactory/keeper/keeper.go +++ b/x/tokenfactory/keeper/keeper.go @@ -17,7 +17,6 @@ import ( type ( Keeper struct { - cdc codec.Codec storeKey sdk.StoreKey paramSpace paramtypes.Subspace @@ -42,7 +41,6 @@ func NewKeeper( } return Keeper{ - cdc: cdc, storeKey: storeKey, paramSpace: paramSpace, diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index f339049d8be..946674b6862 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -42,11 +42,10 @@ var ( // AppModuleBasic implements the AppModuleBasic interface for the capability module. type AppModuleBasic struct { - cdc codec.Codec } -func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} +func NewAppModuleBasic() AppModuleBasic { + return AppModuleBasic{} } // Name returns the x/tokenfactory module's name. @@ -111,13 +110,12 @@ type AppModule struct { } func NewAppModule( - cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, ) AppModule { return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), + AppModuleBasic: NewAppModuleBasic(), keeper: keeper, accountKeeper: accountKeeper, bankKeeper: bankKeeper, diff --git a/x/txfees/keeper/keeper.go b/x/txfees/keeper/keeper.go index 54a14d51897..54619e2d988 100644 --- a/x/txfees/keeper/keeper.go +++ b/x/txfees/keeper/keeper.go @@ -13,7 +13,6 @@ import ( ) type Keeper struct { - cdc codec.Codec storeKey sdk.StoreKey accountKeeper types.AccountKeeper @@ -37,7 +36,6 @@ func NewKeeper( nonNativeFeeCollectorName string, ) Keeper { return Keeper{ - cdc: cdc, accountKeeper: accountKeeper, bankKeeper: bankKeeper, epochKeeper: epochKeeper, diff --git a/x/txfees/module.go b/x/txfees/module.go index c52aebce8b7..943486f5151 100644 --- a/x/txfees/module.go +++ b/x/txfees/module.go @@ -43,11 +43,10 @@ const ModuleName = types.ModuleName // AppModuleBasic implements the AppModuleBasic interface for the txfees module. type AppModuleBasic struct { - cdc codec.Codec } -func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} +func NewAppModuleBasic() AppModuleBasic { + return AppModuleBasic{} } // Name returns the txfees module's name. @@ -108,9 +107,9 @@ type AppModule struct { keeper keeper.Keeper } -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { +func NewAppModule(keeper keeper.Keeper) AppModule { return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), + AppModuleBasic: NewAppModuleBasic(), keeper: keeper, } } From c7dd91eb5c403c30053cf47f789ad58dd04214a9 Mon Sep 17 00:00:00 2001 From: Xiangan He <76530366+xBalbinus@users.noreply.github.com> Date: Wed, 27 Jul 2022 23:55:56 -0400 Subject: [PATCH 129/376] breaking docs fixes (#2246) Closes: #XXX ## What is the purpose of the change This is a fix for some broken docs on the GAMM module specs ## Brief Changelog -Fixed duplicate transactions documentation to only contain the most updated and accurate ones. ## Testing and Verifying *(Please pick one of the following options)* **This change is a trivial rework / code cleanup without any test coverage.** *(or)* This change is already covered by existing tests, such as *(please describe tests)*. *(or)* This change added tests and can be verified as follows: **This has been tested by locally reproducing by building.** ## Documentation and Release Note - Does this pull request introduce a new feature or user-facing behavior changes? (yes / **no**) - Is a relevant changelog entry added to the `Unreleased` section in `CHANGELOG.md`? (yes / **no**) - How is the feature or change documented? (**not applicable** / specification (`x//spec/`) / [Osmosis docs repo](https://github.com/osmosis-labs/docs) / not documented) --- x/gamm/README.md | 418 +---------------------------------------------- 1 file changed, 6 insertions(+), 412 deletions(-) diff --git a/x/gamm/README.md b/x/gamm/README.md index 1163a412d53..1cccc21f134 100644 --- a/x/gamm/README.md +++ b/x/gamm/README.md @@ -386,7 +386,7 @@ osmosisd tx gamm swap-exact-amount-out 140530uosmo 407239 --swap-route-pool-ids [comment]: <> (Other resources Creating a liquidity bootstrapping pool and Creating a pool with a pool file) ::: -## Queries and Transactions +## Queries ## Queries @@ -543,412 +543,6 @@ Query the total amount of GAMM shares of pool 1. osmosisd query gamm total-share 1 ``` -## Transactions - -The **Transaction** submodule of the GAMM module provides the logic to create and interact with the liquidity pools. It contains the following functions: - -- [Create Pool](#create-pool) -- [Join Pool](#join-pool) -- [Exit Pool](#exit-pool) -- [Join Swap Extern Amount In](#join-swap-extern-amount-in) -- [Exit Swap Extern Amount Out](#exit-swap-extern-amount-out) -- [Join Swap Share Amount Out](#join-swap-share-amount-out) -- [Exit Swap Share Amount In](#exit-swap-share-amount-in) -- [Swap Exact Amount In](#swap-exact-amount-in) -- [Swap Exact Amount Out](#swap-exact-amount-out) - -### Estimate-swap-exact-amount-in - -Query the estimated result of the [swap-exact-amount-in](#swap-exact-amount-in) transaction. - -```sh -osmosisd query gamm estimate-swap-exact-amount-in [poolID] [sender] [tokenIn] --swap-route-pool-ids --swap-route-denoms -``` - -::: details Example - -Query the amount of ATOM (or `ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2`) the `sender` would receive for swapping `1 OSMO` in `pool 1`. - -```sh -osmosisd query gamm estimate-swap-exact-amount-in 1 osmo123nfq6m8f88m4g3sky570unsnk4zng4uqv7cm8 1000000uosmo --swap-route-pool-ids 1 --swap-route-denoms ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 -``` - -::: - -### Estimate-swap-exact-amount-out - -Query the estimated result of the [swap-exact-amount-out](#swap-exact-amount-out) transaction. - -```sh -osmosisd query gamm estimate-swap-exact-amount-out [poolID] [sender] [tokenOut] --swap-route-pool-ids --swap-route-denoms -``` - -::: details Example - -Query the amount of `OSMO` the `sender` would require to swap 1 ATOM (or `1000000ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2`) our of `pool 1`: - -```sh -osmosisd query gamm estimate-swap-exact-amount-out 1 osmo123nfq6m8f88m4g3sky570unsnk4zng4uqv7cm8 1000000ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 --swap-route-pool-ids 1 --swap-route-denoms uosmo -``` - -::: - -### Num-pools - -Query the number of active pools. - -```sh -osmosisd query gamm num-pools -``` - -### Pool - -Query the parameter and assets of a specific pool. - -```sh -osmosisd query gamm pool [poolID] [flags] -``` - -::: details Example - -Query parameters and assets from `pool 1`. - -```sh -osmosisd query gamm pool 1 -``` - -Which outputs: - -```sh - address: osmo1mw0ac6rwlp5r8wapwk3zs6g29h8fcscxqakdzw9emkne6c8wjp9q0t3v8t - id: 1 - pool_params: - swap_fee: "0.003000000000000000" - exit_fee: "0.000000000000000000" - smooth_weight_change_params: null - future-governor: 24h - total_weight: "1000000.000000000000000000" - total_shares: - denom: gamm/pool/1 - amount: "252329392916236134754561337" - pool_assets: - - | - token: - denom: ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 - amount: "4024633105693" - weight: "500000.000000000000000000" - - | - token: - denom: uosmo - amount: "21388879300450" - weight: "500000.000000000000000000" -``` - -::: - -### Pool-assets - -Query the assets of a specific pool. This query is a reduced form of the [pool](#pool) query. - -```sh -osmosisd query gamm pool-assets [poolID] [flags] -``` - -::: details Example - -Query the assets from `pool 1`. - -```sh -osmosisd query gamm pool-assets 1 -``` - -Which outputs: - -```sh -poolAssets: -- token: - amount: "4024839695885" - denom: ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 - weight: "536870912000000" -- token: - amount: "21387918414792" - denom: uosmo - weight: "536870912000000" -``` - -::: - -### Pool Params - -Query the parameters of a specific pool. This query is a reduced form of the [pool](#pool) query. - -```sh -osmosisd query gamm pool-params [poolID] [flags] -``` - -::: details Example - -Query the parameters from pool 1. - -```sh -osmosisd query gamm pool-params 1 -``` - -Which outputs: - -```sh -swap_fee: "0.003000000000000000" -exit_fee: "0.000000000000000000" -smooth_weight_change_params: null -``` - -::: - -### Pools - -Query parameters and assets of all active pools. - -```sh -osmosisd query gamm pools -``` - -### Spot-price - -Query the spot price of a pool asset based on a specific pool it is in. - -```sh -osmosisd query gamm spot-price [poolID] [tokenInDenom] [tokenOutDenom] [flags] -``` - -::: details Example - -Query the price of OSMO based on the price of ATOM in pool 1: - -```sh -osmosisd query gamm spot-price 1 uosmo ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 -``` - -Which outputs: - -```sh -spotPrice: "5.314387014412388547" -``` - -In other words, at the time of this writing, ~5.314 OSMO is equivalent to 1 ATOM. -::: - -### Total-liquidity - -Query the total liquidity of all active pools. - -```sh -osmosisd query gamm total-liquidity -``` - -### Total-share - -Query the total amount of GAMM shares of a specific pool. - -```sh -osmosisd query gamm total-share [poolID] [flags] -``` - -::: details Example - -Query the total amount of GAMM shares of pool 1. - -```sh -osmosisd query gamm total-share 1 -``` - -Which outputs: - -```sh -totalShares: - amount: "252328895834096787303097071" - denom: gamm/pool/1 -``` - -Indicating there are a total of `252328895.834096787303097071 gamm/pool/1` at the time of this writing - -::: - -### Create Pool - -Create a new liquidity pool and provide the initial liquidity to it. Pool initialization parameters must be provided through a JSON file using the flag *pool-file*. - -#### Usage - -```sh -osmosisd tx gamm create-pool [flags] -``` - -The configuration file *config.json* must specify the following parameters. - -```json -{ - "weights": [list weighted denoms], - "initial-deposit": [list of denoms with initial deposit amount], - "swap-fee": [swap fee in percentage], - "exit-fee": [exit fee in percentage], - "future-governor": [number of hours] -} -``` - -#### Example - -Create a new ATOM-OSMO liquidity pool with a swap and exit fee of 1%. - -```sh -tx gamm create-pool --pool-file ../public/config.json --from myKeyringWallet -``` - -The configuration file contains the following parameters. - -```json -{ - "weights": "5uatom,5uosmo", - "initial-deposit": "100uatom,100uosmo", - "swap-fee": "0.01", - "exit-fee": "0.01", - "future-governor": "168h" -} -``` - -### Join Pool - -Join a specific pool with a custom amount of tokens. Note that the flags *pool-id*, *max-amounts-in* and *share-amount-out* are required. - -#### Usage - -```sh -osmosisd tx gamm join-pool [flags] -``` - -#### Example - -Join pool 1 with 1 OSMO and the respective amount of ATOM, using myKeyringWallet. - -```sh -osmosisd tx gamm join-pool --pool-id 2 --max-amounts-in 1000000uosmo --max-amounts-in 1000000uion --share-amount-out 1000000 --from myKeyringWallet -``` - -### Exit Pool - -Exit a specific pool with a custom amount of tokens. Note that the flags *pool-id*, *min-amounts-out* and *share-amount-in* are required. - -#### Usage - -```sh -osmosisd tx gamm exit-pool [flags] -``` - -#### Example - -Exit pool one with 1 OSMO and the respective amount of ATOM using myKeyringWallet. - -```sh -osmosisd tx gamm exit-pool --pool-id 1 --min-amounts-out 1000000uosmo --share-amount-in 1000000 --from myKeyringWallet -``` - -### Join Swap Extern Amount In - -Note that the flags *pool-id* is required. - -#### Usage - -```sh -osmosisd tx gamm join-swap-extern-amount-in [token-in] [share-out-min-amount] [flags] -``` - -#### Example - -```sh -osmosisd tx gamm join-swap-extern-amount-in 1000000uosmo 1000000 --pool-id 1 --from myKeyringWallet -``` - -### Exit Swap Extern Amount Out - -Note that the flag *pool-id* is required. - -```sh -osmosisd tx gamm exit-swap-extern-amount-out [token-out] [share-in-max-amount] [flags] -``` - -#### Example - -```sh -osmosisd tx gamm exit-swap-extern-amount-out 1000000uosmo 1000000 --pool-id 1 --from myKeyringWallet -``` - -### Join Swap Share Amount Out - -Note that the flag *pool-id* is required. - -#### Usage - -```sh -osmosisd tx gamm join-swap-share-amount-out [token-in-denom] [token-in-max-amount] [share-out-amount] [flags] -``` - -#### Example - -```sh -osmosisd tx gamm join-swap-share-amount-out uosmo 1000000 1000000 --pool-id 1 --from myKeyringWallet -``` - -### Exit Swap Share Amount In - -Note that the flag *pool-id* is required. - -#### Usage - -```sh -osmosisd tx gamm exit-swap-share-amount-in [token-out-denom] [share-in-amount] [token-out-min-amount] [flags] -``` - -#### Example - -```sh -osmosisd tx gamm exit-swap-share-amount-in uosmo 1000000 1000000 --pool-id 1 --from myKeyringWallet -``` - -### Swap Exact Amount In - -Swap an exact amount of tokens into a specific pool. Note that the flags *swap-route-pool-ids* and *swap-route-denoms* are required. - -#### Usage - -```sh -osmosisd tx gamm swap-exact-amount-in [token-in] [token-out-min-amount] [flags] -``` - -#### Example - -Swap 1 OSMO through pool 1 into at least 0.3 ATOM using MyKeyringWallet. - -```sh -osmosisd tx gamm swap-exact-amount-in 1000000uosmo 300000 --swap-route-pool-ids 1 --swap-route-denoms ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 --from MyKeyringWallet -``` - -### Swap Exact Amount Out - -Swap an exact amount of tokens out of a specific pool. Note that the flags *swap-route-pool-ids* and *swap-route-denoms* are required. - -### Usage - -```sh -osmosisd tx gamm swap-exact-amount-out [token-out] [token-out-max-amount] [flags] -``` - -### Example - -Swap 1 ATOM through pool 1 into at most 2.5 OSMO using MyKeyringWallet. - -```sh -osmosisd tx gamm swap-exact-amount-out 1000000ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 250000 --swap-route-pool-ids 1 --swap-route-denoms uosmo --from MyKeyringWallet -``` - ## Other resources * [Creating a liquidity bootstrapping pool](./client/docs/create-lbp-pool.md) @@ -968,8 +562,6 @@ There are 5 types of events that exist in GAMM: This event is emitted in the message server when any of the gamm messages finish execution. -TBD - ### `types.TypeEvtPoolJoined` This event is emitted after one of `JoinPool` or `JoinPoolNoSwap` complete joining @@ -988,11 +580,13 @@ It consists of the following attributes: ### `types.TypeEvtPoolExited` -TBD +This event is emitted after `ExitPool` completes exiting +the requested pool successfully. ### `types.TypeEvtPoolCreated` -TBD +This event is emitted after `CreatePool` completes creating +the requested pool successfully. ### `types.TypeEvtTokenSwapped` @@ -1010,4 +604,4 @@ It consists of the following attributes: * types.AttributeKeyTokensIn * The value is the string representation of the tokens being swapped in. * types.AttributeKeyTokensOut - * The value is the string representation of the tokens being swapped out. + * The value is the string representation of the tokens being swapped out. \ No newline at end of file From 9f9736cbd4124662639351c08fdec677921a327b Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Thu, 28 Jul 2022 10:33:19 -0500 Subject: [PATCH 130/376] Create upgrade_11_binaries.json (#2250) --- .../osmosis-1/upgrades/v11/mainnet/upgrade_11_binaries.json | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 networks/osmosis-1/upgrades/v11/mainnet/upgrade_11_binaries.json diff --git a/networks/osmosis-1/upgrades/v11/mainnet/upgrade_11_binaries.json b/networks/osmosis-1/upgrades/v11/mainnet/upgrade_11_binaries.json new file mode 100644 index 00000000000..f56174c6e38 --- /dev/null +++ b/networks/osmosis-1/upgrades/v11/mainnet/upgrade_11_binaries.json @@ -0,0 +1,6 @@ +{ + "binaries": { + "linux/amd64": "https://github.com/osmosis-labs/osmosis/releases/download/v11.0.0/osmosisd-11.0.0-linux-amd64?checksum=sha256:d01423cf847b7f95a94ade8811bbf6dd9ec5938d46af0a14bc62caaaa7b7143e", + "linux/arm64": "https://github.com/osmosis-labs/osmosis/releases/download/v11.0.0/osmosisd-11.0.0-linux-arm64?checksum=sha256:375699e90e5b76fd3d7e7a9ab631b40badd97140136f361e6b3f06be3fbd863d" + } +} From cf39ea388b71eeb5a8bf6de5befdd39ed66c2ea7 Mon Sep 17 00:00:00 2001 From: Sishir Giri Date: Thu, 28 Jul 2022 11:26:44 -0700 Subject: [PATCH 131/376] [Test] gamm: Make test case for GetPoolDenoms (#2240) Closes: #2200 ## What is the purpose of the change Add test for function GetPoolDenoms ## Brief Changelog n/a ## Testing and Verifying added unit test ## Documentation and Release Note - Does this pull request introduce a new feature or user-facing behavior changes? (no) - Is a relevant changelog entry added to the `Unreleased` section in `CHANGELOG.md`? (no) - How is the feature or change documented? (not applicable / specification (`x//spec/`) / [Osmosis docs repo](https://github.com/osmosis-labs/docs) / not documented) --- x/gamm/keeper/pool.go | 6 +++++ x/gamm/keeper/pool_service_test.go | 39 ++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/x/gamm/keeper/pool.go b/x/gamm/keeper/pool.go index dae14c7a654..919b0fc599f 100644 --- a/x/gamm/keeper/pool.go +++ b/x/gamm/keeper/pool.go @@ -198,8 +198,14 @@ func (k Keeper) DeletePool(ctx sdk.Context, poolId uint64) error { // return nil // } +// GetPoolDenom retrieves the pool based on PoolId and +// returns the coin denoms that it holds. func (k Keeper) GetPoolDenoms(ctx sdk.Context, poolId uint64) ([]string, error) { pool, err := k.GetPoolAndPoke(ctx, poolId) + if err != nil { + return nil, err + } + denoms := osmoutils.CoinsDenoms(pool.GetTotalPoolLiquidity(ctx)) return denoms, err } diff --git a/x/gamm/keeper/pool_service_test.go b/x/gamm/keeper/pool_service_test.go index 7ceaaeb09ba..36f7457fb56 100644 --- a/x/gamm/keeper/pool_service_test.go +++ b/x/gamm/keeper/pool_service_test.go @@ -751,6 +751,45 @@ func (suite *KeeperTestSuite) TestJoinSwapExactAmountInConsistency() { } } +func (suite *KeeperTestSuite) TestGetPoolDenom() { + // setup pool with denoms + suite.FundAcc(suite.TestAccs[0], defaultAcctFunds) + poolCreateMsg := balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], defaultPoolParams, defaultPoolAssets, defaultFutureGovernor) + _, err := suite.App.GAMMKeeper.CreatePool(suite.Ctx, poolCreateMsg) + suite.Require().NoError(err) + + for _, tc := range []struct { + desc string + poolId uint64 + expectDenoms []string + expectErr bool + }{ + { + desc: "Valid PoolId", + poolId: 1, + expectDenoms: []string{"bar", "foo"}, + expectErr: false, + }, + { + desc: "Invalid PoolId", + poolId: 2, + expectDenoms: []string{"bar", "foo"}, + expectErr: true, + }, + } { + suite.Run(tc.desc, func() { + denoms, err := suite.App.GAMMKeeper.GetPoolDenoms(suite.Ctx, tc.poolId) + + if tc.expectErr { + suite.Require().Error(err) + } else { + suite.Require().NoError(err) + suite.Require().Equal(denoms, tc.expectDenoms) + } + }) + } +} + // func (suite *KeeperTestSuite) TestSetStableSwapScalingFactors() { // stableSwapPoolParams := stableswap.PoolParams{ // SwapFee: defaultSwapFee, From fe98f6e4453cd32035d277c21ef2f3669b677bb2 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Thu, 28 Jul 2022 16:44:08 -0500 Subject: [PATCH 132/376] chore: v11 upgrade guide (#2252) * Create guide.md * adds testnet guide * Update guide.md * Update guide.md * Apply suggestions from code review Co-authored-by: Roman * Update guide.md * Update guide.md Co-authored-by: Roman --- .../osmosis-1/upgrades/v11/mainnet/guide.md | 120 ++++++++++++++++++ .../osmosis-1/upgrades/v11/testnet/guide.md | 120 ++++++++++++++++++ 2 files changed, 240 insertions(+) create mode 100644 networks/osmosis-1/upgrades/v11/mainnet/guide.md create mode 100644 networks/osmosis-1/upgrades/v11/testnet/guide.md diff --git a/networks/osmosis-1/upgrades/v11/mainnet/guide.md b/networks/osmosis-1/upgrades/v11/mainnet/guide.md new file mode 100644 index 00000000000..19988b2600b --- /dev/null +++ b/networks/osmosis-1/upgrades/v11/mainnet/guide.md @@ -0,0 +1,120 @@ +# v10 to v11 Mainnet Upgrade Guide + +Osmosis v11 Gov Prop: + +Countdown: + +Height: 5432450 + +## Memory Requirements + +This upgrade will **not** be resource intensive. With that being said, we still recommend having 64GB of memory. If having 64GB of physical memory is not possible, the next best thing is to set up swap. + +Short version swap setup instructions: + +``` {.sh} +sudo swapoff -a +sudo fallocate -l 32G /swapfile +sudo chmod 600 /swapfile +sudo mkswap /swapfile +sudo swapon /swapfile +``` + +To persist swap after restart: + +``` {.sh} +sudo cp /etc/fstab /etc/fstab.bak +echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab +``` + +In depth swap setup instructions: + + +## Install and setup Cosmovisor + +We highly recommend validators use cosmovisor to run their nodes. This +will make low-downtime upgrades smoother, as validators don't have to +manually upgrade binaries during the upgrade, and instead can +pre-install new binaries, and cosmovisor will automatically update them +based on on-chain SoftwareUpgrade proposals. + +You should review the docs for cosmovisor located here: + + +If you choose to use cosmovisor, please continue with these +instructions: + +To install Cosmovisor: + +``` {.sh} +go install github.com/cosmos/cosmos-sdk/cosmovisor/cmd/cosmovisor@v1.0.0 +``` + +After this, you must make the necessary folders for cosmosvisor in your +daemon home directory (\~/.osmosisd). + +``` {.sh} +mkdir -p ~/.osmosisd +mkdir -p ~/.osmosisd/cosmovisor +mkdir -p ~/.osmosisd/cosmovisor/genesis +mkdir -p ~/.osmosisd/cosmovisor/genesis/bin +mkdir -p ~/.osmosisd/cosmovisor/upgrades +``` + +Copy the current osmosisd binary into the +cosmovisor/genesis folder and v9 folder. + +```{.sh} +cp $GOPATH/bin/osmosisd ~/.osmosisd/cosmovisor/genesis/bin +mkdir -p ~/.osmosisd/cosmovisor/upgrades/v9/bin +cp $GOPATH/bin/osmosisd ~/.osmosisd/cosmovisor/upgrades/v9/bin +``` + +Cosmovisor is now ready to be started. We will now set up Cosmovisor for the upgrade + +Set these environment variables: + +```{.sh} +echo "# Setup Cosmovisor" >> ~/.profile +echo "export DAEMON_NAME=osmosisd" >> ~/.profile +echo "export DAEMON_HOME=$HOME/.osmosisd" >> ~/.profile +echo "export DAEMON_ALLOW_DOWNLOAD_BINARIES=false" >> ~/.profile +echo "export DAEMON_LOG_BUFFER_SIZE=512" >> ~/.profile +echo "export DAEMON_RESTART_AFTER_UPGRADE=true" >> ~/.profile +echo "export UNSAFE_SKIP_BACKUP=true" >> ~/.profile +source ~/.profile +``` + +Now, create the required folder, make the build, and copy the daemon over to that folder + +```{.sh} +mkdir -p ~/.osmosisd/cosmovisor/upgrades/v11/bin +cd $HOME/osmosis +git pull +git checkout v11.0.0 +make build +cp build/osmosisd ~/.osmosisd/cosmovisor/upgrades/v11/bin +``` + +Now, at the upgrade height, Cosmovisor will upgrade to the v11 binary + +## Manual Option + +1. Wait for Osmosis to reach the upgrade height (5432450) + +2. Look for a panic message, followed by endless peer logs. Stop the daemon + +3. Run the following commands: +```{.sh} +cd $HOME/osmosis +git pull +git checkout v11.0.0 +make install +``` + +4. Start the osmosis daemon again, watch the upgrade happen, and then continue to hit blocks + +## Further Help + +If you need more help, please go to or join +our discord at . diff --git a/networks/osmosis-1/upgrades/v11/testnet/guide.md b/networks/osmosis-1/upgrades/v11/testnet/guide.md new file mode 100644 index 00000000000..889f7764deb --- /dev/null +++ b/networks/osmosis-1/upgrades/v11/testnet/guide.md @@ -0,0 +1,120 @@ +# v10 to v11 Testnet Upgrade Guide + +Osmosis v11 Gov Prop: + +Countdown: + +Height: 5865000 + +## Memory Requirements + +This upgrade will **not** be resource intensive. With that being said, we still recommend having 64GB of memory. If having 64GB of physical memory is not possible, the next best thing is to set up swap. + +Short version swap setup instructions: + +``` {.sh} +sudo swapoff -a +sudo fallocate -l 32G /swapfile +sudo chmod 600 /swapfile +sudo mkswap /swapfile +sudo swapon /swapfile +``` + +To persist swap after restart: + +``` {.sh} +sudo cp /etc/fstab /etc/fstab.bak +echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab +``` + +In depth swap setup instructions: + + +## Install and setup Cosmovisor + +We highly recommend validators use cosmovisor to run their nodes. This +will make low-downtime upgrades smoother, as validators don't have to +manually upgrade binaries during the upgrade, and instead can +pre-install new binaries, and cosmovisor will automatically update them +based on on-chain SoftwareUpgrade proposals. + +You should review the docs for cosmovisor located here: + + +If you choose to use cosmovisor, please continue with these +instructions: + +To install Cosmovisor: + +``` {.sh} +go install github.com/cosmos/cosmos-sdk/cosmovisor/cmd/cosmovisor@v1.0.0 +``` + +After this, you must make the necessary folders for cosmosvisor in your +daemon home directory (\~/.osmosisd). + +``` {.sh} +mkdir -p ~/.osmosisd +mkdir -p ~/.osmosisd/cosmovisor +mkdir -p ~/.osmosisd/cosmovisor/genesis +mkdir -p ~/.osmosisd/cosmovisor/genesis/bin +mkdir -p ~/.osmosisd/cosmovisor/upgrades +``` + +Copy the current osmosisd binary into the +cosmovisor/genesis folder and v9 folder. + +```{.sh} +cp $GOPATH/bin/osmosisd ~/.osmosisd/cosmovisor/genesis/bin +mkdir -p ~/.osmosisd/cosmovisor/upgrades/v9/bin +cp $GOPATH/bin/osmosisd ~/.osmosisd/cosmovisor/upgrades/v9/bin +``` + +Cosmovisor is now ready to be started. We will now set up Cosmovisor for the upgrade + +Set these environment variables: + +```{.sh} +echo "# Setup Cosmovisor" >> ~/.profile +echo "export DAEMON_NAME=osmosisd" >> ~/.profile +echo "export DAEMON_HOME=$HOME/.osmosisd" >> ~/.profile +echo "export DAEMON_ALLOW_DOWNLOAD_BINARIES=false" >> ~/.profile +echo "export DAEMON_LOG_BUFFER_SIZE=512" >> ~/.profile +echo "export DAEMON_RESTART_AFTER_UPGRADE=true" >> ~/.profile +echo "export UNSAFE_SKIP_BACKUP=true" >> ~/.profile +source ~/.profile +``` + +Now, create the required folder, make the build, and copy the daemon over to that folder + +```{.sh} +mkdir -p ~/.osmosisd/cosmovisor/upgrades/v11/bin +cd $HOME/osmosis +git pull +git checkout v11.0.0 +make build +cp build/osmosisd ~/.osmosisd/cosmovisor/upgrades/v11/bin +``` + +Now, at the upgrade height, Cosmovisor will upgrade to the v11 binary + +## Manual Option + +1. Wait for Osmosis to reach the upgrade height (5865000) + +2. Look for a panic message, followed by endless peer logs. Stop the daemon + +3. Run the following commands: +```{.sh} +cd $HOME/osmosis +git pull +git checkout v11.0.0 +make install +``` + +4. Start the osmosis daemon again, watch the upgrade happen, and then continue to hit blocks + +## Further Help + +If you need more help, please go to or join +our discord at . From c13d79892f7b12d1571dac5fe73ad5add9375530 Mon Sep 17 00:00:00 2001 From: Hieu Vu <72878483+hieuvubk@users.noreply.github.com> Date: Sat, 30 Jul 2022 03:46:08 +0700 Subject: [PATCH 133/376] Loockup msg server test (#2205) * validate msgs * add tests * format * conflict with exist test: cli/begin_unlocking_by_id * add amount to unlock_by_id in cli * refactor the tests * refactor tests * test_helper * move to apptesting * fix import cycle --- app/apptesting/test_suite.go | 7 + x/lockup/client/cli/cli_test.go | 1 + x/lockup/types/msgs.go | 27 +++- x/lockup/types/msgs_test.go | 266 +++++++++++++++++++++++++------- 4 files changed, 239 insertions(+), 62 deletions(-) diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index 152a5a7d3c1..64634bf543f 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -311,3 +311,10 @@ func CreateRandomAccounts(numAccts int) []sdk.AccAddress { return testAddrs } + +func GenerateTestAddrs() (string, string) { + pk1 := ed25519.GenPrivKey().PubKey() + validAddr := sdk.AccAddress(pk1.Address()).String() + invalidAddr := sdk.AccAddress("invalid").String() + return validAddr, invalidAddr +} diff --git a/x/lockup/client/cli/cli_test.go b/x/lockup/client/cli/cli_test.go index 06ef8156ece..f98cef019cf 100644 --- a/x/lockup/client/cli/cli_test.go +++ b/x/lockup/client/cli/cli_test.go @@ -253,6 +253,7 @@ func (s *IntegrationTestSuite) TestNewBeginUnlockPeriodLockCmd() { "begin unlocking by id", []string{ lockID, + fmt.Sprintf("--%s=%s", cli.FlagAmount, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(100))).String()), fmt.Sprintf("--%s=%s", flags.FlagFrom, newAddr), // common args fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), diff --git a/x/lockup/types/msgs.go b/x/lockup/types/msgs.go index bbbce794244..1fb8e83d510 100644 --- a/x/lockup/types/msgs.go +++ b/x/lockup/types/msgs.go @@ -72,6 +72,10 @@ func NewMsgBeginUnlockingAll(owner sdk.AccAddress) *MsgBeginUnlockingAll { func (m MsgBeginUnlockingAll) Route() string { return RouterKey } func (m MsgBeginUnlockingAll) Type() string { return TypeMsgBeginUnlockingAll } func (m MsgBeginUnlockingAll) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Owner) + if err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid owner address (%s)", err) + } return nil } @@ -98,6 +102,24 @@ func NewMsgBeginUnlocking(owner sdk.AccAddress, id uint64, coins sdk.Coins) *Msg func (m MsgBeginUnlocking) Route() string { return RouterKey } func (m MsgBeginUnlocking) Type() string { return TypeMsgBeginUnlocking } func (m MsgBeginUnlocking) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Owner) + if err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid owner address (%s)", err) + } + + if m.ID == 0 { + return fmt.Errorf("invalid lockup ID, got %v", m.ID) + } + + // only allow unlocks with a single denom + if m.Coins.Len() != 1 { + return fmt.Errorf("can only unlock one denom per lock ID, got %v", m.Coins) + } + + if !m.Coins.IsAllPositive() { + return fmt.Errorf("cannot unlock a zero or negative amount") + } + return nil } @@ -122,8 +144,9 @@ func NewMsgExtendLockup(owner sdk.AccAddress, id uint64, duration time.Duration) func (m MsgExtendLockup) Route() string { return RouterKey } func (m MsgExtendLockup) Type() string { return TypeMsgExtendLockup } func (m MsgExtendLockup) ValidateBasic() error { - if len(m.Owner) == 0 { - return fmt.Errorf("owner is empty") + _, err := sdk.AccAddressFromBech32(m.Owner) + if err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid owner address (%s)", err) } if m.ID == 0 { return fmt.Errorf("id is empty") diff --git a/x/lockup/types/msgs_test.go b/x/lockup/types/msgs_test.go index 8dd16cb3fd1..63d0aa097b4 100644 --- a/x/lockup/types/msgs_test.go +++ b/x/lockup/types/msgs_test.go @@ -1,4 +1,4 @@ -package types +package types_test import ( "testing" @@ -6,99 +6,245 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/osmosis-labs/osmosis/v10/app/apptesting" appParams "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/x/lockup/types" ) func TestMsgLockTokens(t *testing.T) { appParams.SetAddressPrefixes() - pk1 := ed25519.GenPrivKey().PubKey() - addr1 := sdk.AccAddress(pk1.Address()).String() - invalidAddr := sdk.AccAddress("invalid") - - createMsg := func(after func(msg MsgLockTokens) MsgLockTokens) MsgLockTokens { - properMsg := MsgLockTokens{ - Owner: addr1, - Duration: time.Hour, - Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(100))), - } - - return after(properMsg) - } - - msg := createMsg(func(msg MsgLockTokens) MsgLockTokens { - // Do nothing - return msg - }) - - require.Equal(t, msg.Route(), RouterKey) - require.Equal(t, msg.Type(), "lock_tokens") - signers := msg.GetSigners() - require.Equal(t, len(signers), 1) - require.Equal(t, signers[0].String(), addr1) + addr1, invalidAddr := apptesting.GenerateTestAddrs() tests := []struct { name string - msg MsgLockTokens + msg types.MsgLockTokens expectPass bool }{ { name: "proper msg", - msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { - // Do nothing - return msg - }), + msg: types.MsgLockTokens{ + Owner: addr1, + Duration: time.Hour, + Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(100))), + }, expectPass: true, }, { name: "invalid owner", - msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { - msg.Owner = invalidAddr.String() - return msg - }), - expectPass: false, + msg: types.MsgLockTokens{ + Owner: invalidAddr, + Duration: time.Hour, + Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(100))), + }, }, { name: "invalid duration", - msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { - msg.Duration = -1 - return msg - }), - expectPass: false, + msg: types.MsgLockTokens{ + Owner: addr1, + Duration: -1, + Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(100))), + }, }, { name: "invalid coin length", - msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { - msg.Coins = sdk.NewCoins(sdk.NewCoin("test1", sdk.NewInt(100000)), sdk.NewCoin("test2", sdk.NewInt(100000))) - return msg - }), - expectPass: false, + msg: types.MsgLockTokens{ + Owner: addr1, + Duration: time.Hour, + Coins: sdk.NewCoins(sdk.NewCoin("test1", sdk.NewInt(100000)), sdk.NewCoin("test2", sdk.NewInt(100000))), + }, }, { name: "zero token amount", - msg: createMsg(func(msg MsgLockTokens) MsgLockTokens { - msg.Coins = sdk.NewCoins(sdk.NewCoin("test1", sdk.NewInt(0))) - return msg - }), - expectPass: false, + msg: types.MsgLockTokens{ + Owner: addr1, + Duration: time.Hour, + Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(0))), + }, }, } for _, test := range tests { - if test.expectPass { - require.NoError(t, test.msg.ValidateBasic(), "test: %v", test.name) - } else { - require.Error(t, test.msg.ValidateBasic(), "test: %v", test.name) - } + t.Run(test.name, func(t *testing.T) { + if test.expectPass { + require.NoError(t, test.msg.ValidateBasic(), "test: %v", test.name) + require.Equal(t, test.msg.Route(), types.RouterKey) + require.Equal(t, test.msg.Type(), "lock_tokens") + signers := test.msg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1) + } else { + require.Error(t, test.msg.ValidateBasic(), "test: %v", test.name) + } + }) } } -// TODO: Complete table driven tests for the remaining messages +func TestMsgBeginUnlockingAll(t *testing.T) { + appParams.SetAddressPrefixes() + addr1, invalidAddr := apptesting.GenerateTestAddrs() + + tests := []struct { + name string + msg types.MsgBeginUnlockingAll + expectPass bool + }{ + { + name: "proper msg", + msg: types.MsgBeginUnlockingAll{ + Owner: addr1, + }, + expectPass: true, + }, + { + name: "invalid owner", + msg: types.MsgBeginUnlockingAll{ + Owner: invalidAddr, + }, + }, + } -// MsgBeginUnlockingAll + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if test.expectPass { + require.NoError(t, test.msg.ValidateBasic(), "test: %v", test.name) + require.Equal(t, test.msg.Route(), types.RouterKey) + require.Equal(t, test.msg.Type(), "begin_unlocking_all") + signers := test.msg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1) + } else { + require.Error(t, test.msg.ValidateBasic(), "test: %v", test.name) + } + }) + } +} -// MsgBeginUnlocking +func TestMsgBeginUnlocking(t *testing.T) { + appParams.SetAddressPrefixes() + addr1, invalidAddr := apptesting.GenerateTestAddrs() -// MsgExtendLockup + tests := []struct { + name string + msg types.MsgBeginUnlocking + expectPass bool + }{ + { + name: "proper msg", + msg: types.MsgBeginUnlocking{ + Owner: addr1, + ID: 1, + Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(100))), + }, + expectPass: true, + }, + { + name: "invalid owner", + msg: types.MsgBeginUnlocking{ + Owner: invalidAddr, + ID: 1, + Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(100))), + }, + }, + { + name: "invalid lockup ID", + msg: types.MsgBeginUnlocking{ + Owner: addr1, + ID: 0, + Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(100))), + }, + }, + { + name: "invalid coins length", + msg: types.MsgBeginUnlocking{ + Owner: addr1, + ID: 1, + Coins: sdk.NewCoins(sdk.NewCoin("test1", sdk.NewInt(100000)), sdk.NewCoin("test2", sdk.NewInt(100000))), + }, + }, + { + name: "not positive coins amount", + msg: types.MsgBeginUnlocking{ + Owner: addr1, + ID: 1, + Coins: sdk.NewCoins(sdk.NewCoin("test1", sdk.NewInt(0))), + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if test.expectPass { + require.NoError(t, test.msg.ValidateBasic(), "test: %v", test.name) + require.Equal(t, test.msg.Route(), types.RouterKey) + require.Equal(t, test.msg.Type(), "begin_unlocking") + signers := test.msg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1) + } else { + require.Error(t, test.msg.ValidateBasic(), "test: %v", test.name) + } + }) + } +} + +func TestMsgExtendLockup(t *testing.T) { + appParams.SetAddressPrefixes() + addr1, invalidAddr := apptesting.GenerateTestAddrs() + + tests := []struct { + name string + msg types.MsgExtendLockup + expectPass bool + }{ + { + name: "proper msg", + msg: types.MsgExtendLockup{ + Owner: addr1, + ID: 1, + Duration: time.Hour, + }, + expectPass: true, + }, + { + name: "invalid owner", + msg: types.MsgExtendLockup{ + Owner: invalidAddr, + ID: 1, + Duration: time.Hour, + }, + }, + { + name: "invalid lockup ID", + msg: types.MsgExtendLockup{ + Owner: addr1, + ID: 0, + Duration: time.Hour, + }, + }, + { + name: "invalid duration", + msg: types.MsgExtendLockup{ + Owner: addr1, + ID: 1, + Duration: -1, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if test.expectPass { + require.NoError(t, test.msg.ValidateBasic(), "test: %v", test.name) + require.Equal(t, test.msg.Route(), types.RouterKey) + require.Equal(t, test.msg.Type(), "edit_lockup") + signers := test.msg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1) + } else { + require.Error(t, test.msg.ValidateBasic(), "test: %v", test.name) + } + }) + } +} From 01144f64804d768d66794442f215cc61a7950b21 Mon Sep 17 00:00:00 2001 From: Roman Date: Fri, 29 Jul 2022 14:24:26 -0700 Subject: [PATCH 134/376] chore(upgrade): move v11 upgrade handler to v12, no-op for v11 (#2216) * chore(upgrade): move v11 upgrade handler to v12, no-op for v11 * init store upgrades * no run migrations * add v12 additions * make v11 upgrade handler close to v11.x * Update app/upgrades/v12/upgrades.go Co-authored-by: Adam Tucker Co-authored-by: Adam Tucker --- .github/mergify.yml | 10 +++++++- Makefile | 2 +- app/app.go | 3 ++- app/upgrades/v11/constants.go | 12 +++------ app/upgrades/v11/upgrades.go | 27 ++------------------ app/upgrades/v12/constants.go | 20 +++++++++++++++ app/upgrades/v12/upgrades.go | 47 +++++++++++++++++++++++++++++++++++ 7 files changed, 85 insertions(+), 36 deletions(-) create mode 100644 app/upgrades/v12/constants.go create mode 100644 app/upgrades/v12/upgrades.go diff --git a/.github/mergify.yml b/.github/mergify.yml index 2ed0f5835e2..f23d4bf5a03 100644 --- a/.github/mergify.yml +++ b/.github/mergify.yml @@ -85,4 +85,12 @@ pull_request_rules: actions: backport: branches: - - v10.x \ No newline at end of file + - v10.x + - name: backport patches to v11.x branch + conditions: + - base=main + - label=A:backport/v11.x + actions: + backport: + branches: + - v11.x diff --git a/Makefile b/Makefile index 79a7f1e4f64..58a3f128ee2 100644 --- a/Makefile +++ b/Makefile @@ -232,7 +232,7 @@ test-sim: @VERSION=$(VERSION) go test -mod=readonly $(PACKAGES_SIM) test-e2e: - @VERSION=$(VERSION) OSMOSIS_E2E_UPGRADE_VERSION="v11" go test -mod=readonly -timeout=25m -v $(PACKAGES_E2E) + @VERSION=$(VERSION) OSMOSIS_E2E_UPGRADE_VERSION="v12" go test -mod=readonly -timeout=25m -v $(PACKAGES_E2E) test-e2e-skip-upgrade: @VERSION=$(VERSION) OSMOSIS_E2E_SKIP_UPGRADE=True go test -mod=readonly -timeout=25m -v $(PACKAGES_E2E) diff --git a/app/app.go b/app/app.go index 815acd94cd1..4eb3c6af503 100644 --- a/app/app.go +++ b/app/app.go @@ -44,6 +44,7 @@ import ( "github.com/osmosis-labs/osmosis/v10/app/upgrades" v10 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v10" v11 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v11" + v12 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v12" v3 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v3" v4 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v4" v5 "github.com/osmosis-labs/osmosis/v10/app/upgrades/v5" @@ -89,7 +90,7 @@ var ( // _ sdksimapp.App = (*OsmosisApp)(nil) - Upgrades = []upgrades.Upgrade{v4.Upgrade, v5.Upgrade, v7.Upgrade, v9.Upgrade, v11.Upgrade} + Upgrades = []upgrades.Upgrade{v4.Upgrade, v5.Upgrade, v7.Upgrade, v9.Upgrade, v11.Upgrade, v12.Upgrade} Forks = []upgrades.Fork{v3.Fork, v6.Fork, v8.Fork, v10.Fork} ) diff --git a/app/upgrades/v11/constants.go b/app/upgrades/v11/constants.go index 6a1cc34ff4a..b0bd45c6f13 100644 --- a/app/upgrades/v11/constants.go +++ b/app/upgrades/v11/constants.go @@ -1,20 +1,16 @@ package v11 import ( - "github.com/osmosis-labs/osmosis/v10/app/upgrades" - twaptypes "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" - store "github.com/cosmos/cosmos-sdk/store/types" + + "github.com/osmosis-labs/osmosis/v10/app/upgrades" ) -// UpgradeName defines the on-chain upgrade name for the Osmosis v9 upgrade. +// UpgradeName defines the on-chain upgrade name for the Osmosis v11 upgrade. const UpgradeName = "v11" var Upgrade = upgrades.Upgrade{ UpgradeName: UpgradeName, CreateUpgradeHandler: CreateUpgradeHandler, - StoreUpgrades: store.StoreUpgrades{ - Added: []string{twaptypes.StoreKey}, - Deleted: []string{}, // double check bech32ibc - }, + StoreUpgrades: store.StoreUpgrades{}, } diff --git a/app/upgrades/v11/upgrades.go b/app/upgrades/v11/upgrades.go index 25af86205cf..83044cc0811 100644 --- a/app/upgrades/v11/upgrades.go +++ b/app/upgrades/v11/upgrades.go @@ -9,36 +9,13 @@ import ( "github.com/osmosis-labs/osmosis/v10/app/upgrades" ) -// We set the app version to pre-upgrade because it will be incremented by one -// after the upgrade is applied by the handler. -const preUpgradeAppVersion = 10 - func CreateUpgradeHandler( mm *module.Manager, configurator module.Configurator, bpm upgrades.BaseAppParamManager, keepers *keepers.AppKeepers, ) upgradetypes.UpgradeHandler { - return func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { - // Although the app version was already set during the v9 upgrade, our v10 was a fork. - // As a result, the upgrade handler was not executed to increment the app version. - // This change helps to correctly set the app version for v11. - if err := keepers.UpgradeKeeper.SetAppVersion(ctx, preUpgradeAppVersion); err != nil { - return nil, err - } - - // Set the max_age_num_blocks in the evidence params to reflect the 14 day - // unbonding period. - // - // Ref: https://github.com/osmosis-labs/osmosis/issues/1160 - cp := bpm.GetConsensusParams(ctx) - if cp != nil && cp.Evidence != nil { - evParams := cp.Evidence - evParams.MaxAgeNumBlocks = 186_092 - - bpm.StoreConsensusParams(ctx, cp) - } - - return mm.RunMigrations(ctx, configurator, fromVM) + return func(ctx sdk.Context, plan upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { + return mm.RunMigrations(ctx, configurator, vm) } } diff --git a/app/upgrades/v12/constants.go b/app/upgrades/v12/constants.go new file mode 100644 index 00000000000..85ae6e3f033 --- /dev/null +++ b/app/upgrades/v12/constants.go @@ -0,0 +1,20 @@ +package v12 + +import ( + "github.com/osmosis-labs/osmosis/v10/app/upgrades" + twaptypes "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" + + store "github.com/cosmos/cosmos-sdk/store/types" +) + +// UpgradeName defines the on-chain upgrade name for the Osmosis v12 upgrade. +const UpgradeName = "v12" + +var Upgrade = upgrades.Upgrade{ + UpgradeName: UpgradeName, + CreateUpgradeHandler: CreateUpgradeHandler, + StoreUpgrades: store.StoreUpgrades{ + Added: []string{twaptypes.StoreKey}, + Deleted: []string{}, // double check bech32ibc + }, +} diff --git a/app/upgrades/v12/upgrades.go b/app/upgrades/v12/upgrades.go new file mode 100644 index 00000000000..b921370df41 --- /dev/null +++ b/app/upgrades/v12/upgrades.go @@ -0,0 +1,47 @@ +package v12 + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + + "github.com/osmosis-labs/osmosis/v10/app/keepers" + "github.com/osmosis-labs/osmosis/v10/app/upgrades" +) + +// We set the app version to pre-upgrade because it will be incremented by one +// after the upgrade is applied by the handler. +const preUpgradeAppVersion = 11 + +func CreateUpgradeHandler( + mm *module.Manager, + configurator module.Configurator, + bpm upgrades.BaseAppParamManager, + keepers *keepers.AppKeepers, +) upgradetypes.UpgradeHandler { + return func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + // Although the app version was already set during the v9 upgrade, our v10 was a fork and + // v11 was decided to be limited to the "gauge creation minimum fee" change only: + // https://github.com/osmosis-labs/osmosis/pull/2202 + // + // As a result, the upgrade handler was not executed to increment the app version. + // This change helps to correctly set the app version for v12. + if err := keepers.UpgradeKeeper.SetAppVersion(ctx, preUpgradeAppVersion); err != nil { + return nil, err + } + + // Set the max_age_num_blocks in the evidence params to reflect the 14 day + // unbonding period. + // + // Ref: https://github.com/osmosis-labs/osmosis/issues/1160 + cp := bpm.GetConsensusParams(ctx) + if cp != nil && cp.Evidence != nil { + evParams := cp.Evidence + evParams.MaxAgeNumBlocks = 186_092 + + bpm.StoreConsensusParams(ctx, cp) + } + + return mm.RunMigrations(ctx, configurator, fromVM) + } +} From fce2e3130acf2312665fec73c4c9ecd1d0a2196a Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sun, 31 Jul 2022 07:16:23 -0600 Subject: [PATCH 135/376] Add TWAP spec (#2203) * Add README * Update for PR suggestions * Apply suggestions from code review Co-authored-by: Roman Co-authored-by: Roman --- .markdownlint.yml | 7 +- x/gamm/twap/README.md | 150 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 150 insertions(+), 7 deletions(-) diff --git a/.markdownlint.yml b/.markdownlint.yml index 7a7a4ae914d..85174e573cf 100644 --- a/.markdownlint.yml +++ b/.markdownlint.yml @@ -4,8 +4,11 @@ MD003: # Heading style style: "atx" # Can't disable MD007 :/ -# MD007: false +MD007: false MD009: false +MD010: + code_blocks: false MD013: code_blocks: false -MD024: false \ No newline at end of file +MD024: false +MD037: false # breaks on latex \ No newline at end of file diff --git a/x/gamm/twap/README.md b/x/gamm/twap/README.md index 6afca121295..e02d87a97dc 100644 --- a/x/gamm/twap/README.md +++ b/x/gamm/twap/README.md @@ -1,9 +1,149 @@ -# TWAP +# TWAP (Time Weighted Average Price) -We maintain TWAP entries for every gamm pool. +The TWAP package is responsible for being able to serve TWAPs for every AMM pool. -NOTE: Not yet integrated into state machine, this package is a stub. +A time weighted average price is a function that takes a sequence of `(time, price)` pairs, and returns a price representing an 'average' over the entire time period. The method of averaging can vary from the classic arithmetic mean, (such as geometric mean, harmonic mean), however we currently only implement arithmetic mean. -## Basic architecture notes +## Arithmetic mean TWAP -We maintain the list of pools altered within in a block \ No newline at end of file +Using the arithmetic mean, the TWAP of a sequence `(t_i, p_i)`, from `t_0` to `t_n`, indexed by time in ascending order, is: $$\frac{1}{t_n - t_0}\sum_{i=0}^{n-1} p_i (t_{i+1} - t_i)$$ +Notice that the latest price `p_n` isn't used, as it has lasted for a time interval of `0` seconds in this range! + +To illustrate with an example, given the sequence: `(0s, $1), (4s, $6), (5s, $1)`, the arithmetic mean TWAP is: +$$\frac{\$1 * (4s - 0s) + \$6 * (5s - 4s)}{5s - 0s} = \frac{\$10}{5} = \$2$$ + +## Computation via accumulators method + +The prior example for how to compute the TWAP takes linear time in the number of time entries in a range, which is too inefficient. We require TWAP operations to have constant time complexity (in the number of records). + +This is achieved by using an accumulator. In the case of an arithmetic TWAP, we can maintain an accumulator from `a_n`, representing the numerator of the TWAP expression for the interval `t_0...t_n`, namely +$$a_n = \sum_{i=0}^{n-1} p_i (t_{i+1} - t_i)$$ +If we maintain such an accumulator for every pool, with `t_0 = pool_creation_time` to `t_n = current_block_time`, we can easily compute the TWAP for any interval. The TWAP for the time interval of price points `t_i` to `t_j` is then $twap = \frac{a_j - a_i}{t_j - t_i}$, which is constant time given the accumulator values. + +In Osmosis, we maintain accumulator records for every pool, for the last 48 hours. +We also maintain within each accumulator record in state, the latest spot price. +This allows us to interpolate accumulation records between times. +Namely, if I want the twap from `t=10s` to `t=15s`, but the time records are at `9s, 13s, 17s`, this is fine. +Using the latest spot price in each record, we create the accumulator value for `t=10` by computing +`a_10 = a_9 + a_9_latest_spot_price * (10s - 9s)`, and `a_15 = a_13 + a_13_latest_spot_price * (15s - 13s)`. +Given these interpolated accumulation values, we can compute the TWAP as before. + + +## Module API + +The primary intended API is `GetArithmeticTwap`, which is documented below, and has a similar cosmwasm binding. + +```go +// GetArithmeticTwap returns an arithmetic time weighted average price. +// The returned twap is the time weighted average price (TWAP), using the arithmetic mean, of: +// * the base asset, in units of the quote asset (1 unit of base = x units of quote) +// * from (startTime, endTime), +// * as determined by prices from AMM pool `poolId`. +// +// startTime and endTime do not have to be real block times that occurred, +// the state machine will interpolate the accumulator values for those times +// from the latest Twap accumulation record prior to the provided time. +// +// startTime must be within 48 hours of ctx.BlockTime(), if you need older TWAPs, +// you will have to maintain the accumulator yourself. +// +// This function will error if: +// * startTime > endTime +// * endTime in the future +// * startTime older than 48 hours OR pool creation +// * pool with id poolId does not exist, or does not contain quoteAssetDenom, baseAssetDenom +// +// N.B. If there is a notable use case, the state machine could maintain more historical records, e.g. at one per hour. +func (k Keeper) GetArithmeticTwap(ctx sdk.Context, + poolId uint64, + baseAssetDenom string, quoteAssetDenom string, + startTime time.Time, endTime time.Time) (sdk.Dec, error) { ... } +``` + +There are convenience methods for `GetArithmeticTwapToNow` which sets `endTime = ctx.BlockTime()`, and has minor gas reduction. +For users who need TWAPs outside the 48 hours stored in the state machine, you can get the latest accumulation store record from `GetBeginBlockAccumulatorRecord`. + +## Code layout + +**api.go** is the main file you should look at as a user of this module. + +**logic.go** is the main file you should look at for how the TWAP implementation works. + +- types/* - Implement TwapRecord, GenesisState. Define AMM interface, and methods to format keys. +- api.go - Public API, that other users / modules can/should depend on +- hook_listener.go - Defines hooks & calls to logic.go, for triggering actions on +- keeper.go - generic SDK boilerplate (defining a wrapper for store keys + params) +- logic.go - Implements all TWAP module 'logic'. (Arithmetic, defining what to get/set where, etc.) +- module.go - SDK AppModule interface implementation. +- store.go - Managing logic for getting and setting things to underlying stores + +## Store layout + +We maintain TWAP accumulation records for every AMM pool on Osmosis. + +Because Osmosis supports multi-asset pools, a complicating factor is that we have to store a record for every asset pair in the pool. +For every pool, at a given point in time, we make one twap record entry per unique pair of denoms in the pool. If a pool has `k` denoms, the number of unique pairs is `k * (k - 1) / 2`. + +Each twap record stores [(source)](https://github.com/osmosis-labs/osmosis/tree/main/proto/osmosis/gamm/twap): +* last spot price of base asset A in terms of quote asset B +* last spot price of base asset B in terms of quote asset A +* Accumulation value of base asset A in terms of quote asset B +* Accumulation value of base asset B in terms of quote asset A + +All TWAP records are indexed in state by the time of write. + +A new TWAP record is created in two situations: +* When a pool is created +* In the `EndBlock`, if the block contains any potentially price changing event for the pool. (Swap, LP, Exit) + +When a pool is created, records are created with the current spot price of the pool. + +During `EndBlock`, new records are created, with: +* The accumulator's value is updated based upon the most recent prior accumulator's stored last spot price +* The `LastSpotPrice` value is equal to the EndBlock spot price. + +In the event that a pool is created, and has a swap in the same block, the record entries are over written with the end block price. + +### Tracking spot-price changing events in a block + +The flow by which we currently track spot price changing events in a block is as follows: +* AMM hook triggers for Swapping, LPing or Exiting a pool +* TWAP listens for this hook, and adds this pool ID to a local tracker +* In end block, TWAP iterates over every changed pool in that block, based on the local tracker, and updates their TWAP records +* In end block, TWAP clears the changed pool list, so it is blank by the next block. + +The mechanism by which we maintain this changed pool list, is the SDK `Transient Store`. +The transient store is a KV store in the SDK, that stores entries in memory, for the duration of a block, +and then clears on the block committing. This is done to save on gas (and I/O for the state machine). + +## Testing Methodology + +The pre-release testing methodology planned for the twap module is: + +- [ ] Using table driven unit tests to test all foreseen states of the module + - hook testing + - All swaps correctly trigger twap record updates + - Create pools cause records to be created + - store + - EndBlock triggers all relevant twaps to be saved correctly + - Block commit wipes temporary stores + - logic + - Make tables of expected input / output cases for: + - getMostRecentRecord + - getInterpolatedRecord + - updateRecord + - computeArithmeticTwap + - Test overflow handling in all relevant arithmetic + - Complete testing code coverage (up to return err lines) for logic.go file + - API + - Unit tests for the public API, under foreseeable setup conditions +- [ ] End to end migration tests + - Tests that migration of Osmosis pools created prior to the TWAP upgrade, get TWAPs recorded starting at the v11 upgrade. +- [ ] Integration into the Osmosis simulator + - The osmosis simulator, simulates building up complex state machine states, in random ways not seen before. We plan on, in a property check, maintaining expected TWAPs for short time ranges, and seeing that the keeper query will return the same value as what we get off of the raw price history for short history intervals. + - Not currently deemed release blocking, but planned: Integration for gas tracking, to ensure gas of reads/writes does not grow with time. +- [ ] Mutation testing usage + - integration of the TWAP module into [go mutation testing](https://github.com/osmosis-labs/go-mutesting): + - We've seen with the `tokenfactory` module that it succeeds at surfacing behavior for untested logic. + e.g. if you delete a line, or change the direction of a conditional, mutation tests show if regular Go tests catch it. + - We expect to get this to a state, where after mutation testing is ran, the only items it mutates, that is not caught in a test, is: Deleting `return err`, or `panic` lines, in the situation where that error return or panic isn't reachable. \ No newline at end of file From f606c4477462140e391a681a034dfc66dbb933cd Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Sun, 31 Jul 2022 11:42:03 -0500 Subject: [PATCH 136/376] simulator: tokenfactory sim updates (#2239) * tokenfactory sim updates * add go docs * Update x/tokenfactory/simulation/sim_msgs.go Co-authored-by: Roman * address Roman comments * use Roman's denom suggestion * Address Dev's comments * Remove use of appparams * hardcode tokenfactory creation fee Co-authored-by: Roman --- x/tokenfactory/module.go | 4 +- x/tokenfactory/simulation/sim_msgs.go | 96 +++++++++++++++++++++++---- 2 files changed, 87 insertions(+), 13 deletions(-) diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index 946674b6862..5a694320045 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -187,7 +187,7 @@ func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Valid // GenerateGenesisState creates a randomized GenState of the tokenfactory module. func (am AppModule) SimulatorGenesisState(simState *module.SimulationState, s *simtypes.SimCtx) { tfDefaultGen := types.DefaultGenesis() - tfDefaultGen.Params.DenomCreationFee = simulation.TokenFactoryCreationFee + tfDefaultGen.Params.DenomCreationFee = sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10000000))) tfDefaultGenJson := simState.Cdc.MustMarshalJSON(tfDefaultGen) simState.GenState[types.ModuleName] = tfDefaultGenJson } @@ -197,5 +197,7 @@ func (am AppModule) Actions() []simtypes.Action { return []simtypes.Action{ simtypes.NewMsgBasedAction("create token factory token", am.keeper, simulation.RandomMsgCreateDenom), simtypes.NewMsgBasedAction("mint token factory token", am.keeper, simulation.RandomMsgMintDenom), + simtypes.NewMsgBasedAction("burn token factory token", am.keeper, simulation.RandomMsgBurnDenom), + simtypes.NewMsgBasedAction("change admin token factory token", am.keeper, simulation.RandomMsgChangeAdmin), } } diff --git a/x/tokenfactory/simulation/sim_msgs.go b/x/tokenfactory/simulation/sim_msgs.go index 4fe4caa0281..bc3361d177c 100644 --- a/x/tokenfactory/simulation/sim_msgs.go +++ b/x/tokenfactory/simulation/sim_msgs.go @@ -13,43 +13,98 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -var ( - TokenFactoryCreationFee = sdk.NewCoins(sdk.NewInt64Coin("stake", 10_000_000)) -) - // RandomMsgCreateDenom creates a random tokenfactory denom that is no greater than 44 alphanumeric characters func RandomMsgCreateDenom(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgCreateDenom, error) { - minCoins := TokenFactoryCreationFee + minCoins := k.GetParams(ctx).DenomCreationFee acc, err := sim.RandomSimAccountWithMinCoins(ctx, minCoins) if err != nil { return nil, err } + return &types.MsgCreateDenom{ Sender: acc.Address.String(), Subdenom: sim.RandStringOfLength(types.MaxSubdenomLength), }, nil } +// RandomMsgMintDenom takes a random denom that has been created and uses the denom's admin to mint a random amount func RandomMsgMintDenom(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgMint, error) { acc, senderExists := sim.RandomSimAccountWithConstraint(accountCreatedTokenFactoryDenom(k, ctx)) if !senderExists { return nil, errors.New("no addr has created a tokenfactory coin") } - // Pick denom - store := k.GetCreatorPrefixStore(ctx, acc.Address.String()) - denoms := osmoutils.GatherAllKeysFromStore(store) - denom := simtypes.RandSelect(sim, denoms...) + + denom, addr, err := getTokenFactoryDenomAndItsAdmin(k, sim, ctx, acc) + if err != nil { + return nil, err + } + if addr == nil { + return nil, errors.New("denom has no admin") + } // TODO: Replace with an improved rand exponential coin mintAmount := sim.RandPositiveInt(sdk.NewIntFromUint64(1000_000000)) return &types.MsgMint{ - Sender: acc.Address.String(), + Sender: addr.String(), Amount: sdk.NewCoin(denom, mintAmount), }, nil } -// TODO: We are going to need to index the owner of an account as well, rather than creator -// to simulate admin changes +// RandomMsgBurnDenom takes a random denom that has been created and uses the denom's admin to burn a random amount +func RandomMsgBurnDenom(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgBurn, error) { + acc, senderExists := sim.RandomSimAccountWithConstraint(accountCreatedTokenFactoryDenom(k, ctx)) + if !senderExists { + return nil, errors.New("no addr has created a tokenfactory coin") + } + + denom, addr, err := getTokenFactoryDenomAndItsAdmin(k, sim, ctx, acc) + if err != nil { + return nil, err + } + if addr == nil { + return nil, errors.New("denom has no admin") + } + + denomBal := sim.BankKeeper().GetBalance(ctx, addr, denom) + if denomBal.IsZero() { + return nil, errors.New("addr does not have enough balance to burn") + } + + // TODO: Replace with an improved rand exponential coin + burnAmount := sim.RandPositiveInt(denomBal.Amount) + return &types.MsgBurn{ + Sender: addr.String(), + Amount: sdk.NewCoin(denom, burnAmount), + }, nil +} + +// RandomMsgChangeAdmin takes a random denom that has been created and changes the admin to another random account +func RandomMsgChangeAdmin(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgChangeAdmin, error) { + acc, senderExists := sim.RandomSimAccountWithConstraint(accountCreatedTokenFactoryDenom(k, ctx)) + if !senderExists { + return nil, errors.New("no addr has created a tokenfactory coin") + } + + denom, addr, err := getTokenFactoryDenomAndItsAdmin(k, sim, ctx, acc) + if err != nil { + return nil, err + } + if addr == nil { + return nil, errors.New("denom has no admin") + } + + newAdmin := sim.RandomSimAccount() + if newAdmin.Address.String() == addr.String() { + return nil, errors.New("new admin cannot be the same as current admin") + } + + return &types.MsgChangeAdmin{ + Sender: addr.String(), + Denom: denom, + NewAdmin: newAdmin.Address.String(), + }, nil +} + func accountCreatedTokenFactoryDenom(k keeper.Keeper, ctx sdk.Context) simtypes.SimAccountConstraint { return func(acc legacysimulationtype.Account) bool { store := k.GetCreatorPrefixStore(ctx, acc.Address.String()) @@ -58,3 +113,20 @@ func accountCreatedTokenFactoryDenom(k keeper.Keeper, ctx sdk.Context) simtypes. return iterator.Valid() } } + +func getTokenFactoryDenomAndItsAdmin(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context, acc legacysimulationtype.Account) (string, sdk.AccAddress, error) { + store := k.GetCreatorPrefixStore(ctx, acc.Address.String()) + denoms := osmoutils.GatherAllKeysFromStore(store) + denom := simtypes.RandSelect(sim, denoms...) + + authData, err := k.GetAuthorityMetadata(ctx, denom) + if err != nil { + return "", nil, err + } + admin := authData.Admin + addr, err := sdk.AccAddressFromBech32(admin) + if err != nil { + return "", nil, err + } + return denom, addr, nil +} From 5879583fa0c82857a1cb18b4bab8f18173b43de1 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sun, 31 Jul 2022 21:27:36 -0600 Subject: [PATCH 137/376] TWAP store.go & store_test.go files (#2199) * TWAP store.go & store_test.go files * Add godocs * fix lint * Apply suggestions from code review Co-authored-by: Roman * Add struct types for TestGetAllMostRecentRecordsForPool * Add pool 2 test * Port from twap_wip * Update x/gamm/twap/store.go Co-authored-by: Adam Tucker * Add GetAllMostRecentTwapsForPool comment Co-authored-by: Roman Co-authored-by: Adam Tucker --- x/gamm/twap/export_test.go | 45 +++++++++ x/gamm/twap/keeper_test.go | 63 ++++++++++++ x/gamm/twap/store.go | 118 ++++++++++++++++++++++- x/gamm/twap/store_test.go | 191 +++++++++++++++++++++++++++++++++++++ x/gamm/twap/types/keys.go | 6 +- 5 files changed, 419 insertions(+), 4 deletions(-) create mode 100644 x/gamm/twap/export_test.go create mode 100644 x/gamm/twap/keeper_test.go create mode 100644 x/gamm/twap/store_test.go diff --git a/x/gamm/twap/export_test.go b/x/gamm/twap/export_test.go new file mode 100644 index 00000000000..1991a25ba73 --- /dev/null +++ b/x/gamm/twap/export_test.go @@ -0,0 +1,45 @@ +package twap + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" +) + +func (k Keeper) StoreNewRecord(ctx sdk.Context, record types.TwapRecord) { + k.storeNewRecord(ctx, record) +} + +func (k Keeper) GetMostRecentRecordStoreRepresentation(ctx sdk.Context, poolId uint64, asset0Denom string, asset1Denom string) (types.TwapRecord, error) { + return k.getMostRecentRecordStoreRepresentation(ctx, poolId, asset0Denom, asset1Denom) +} + +func (k Keeper) GetAllMostRecentRecordsForPool(ctx sdk.Context, poolId uint64) ([]types.TwapRecord, error) { + return k.getAllMostRecentRecordsForPool(ctx, poolId) +} + +func (k Keeper) GetRecordAtOrBeforeTime(ctx sdk.Context, poolId uint64, time time.Time, asset0Denom string, asset1Denom string) (types.TwapRecord, error) { + return k.getRecordAtOrBeforeTime(ctx, poolId, time, asset0Denom, asset1Denom) +} + +func (k Keeper) TrackChangedPool(ctx sdk.Context, poolId uint64) { + k.trackChangedPool(ctx, poolId) +} + +func (k Keeper) GetChangedPools(ctx sdk.Context) []uint64 { + return k.getChangedPools(ctx) +} + +// func (k Keeper) UpdateRecord(ctx sdk.Context, record types.TwapRecord) types.TwapRecord { +// return k.updateRecord(ctx, record) +// } + +// func ComputeArithmeticTwap(startRecord types.TwapRecord, endRecord types.TwapRecord, quoteAsset string) sdk.Dec { +// return computeArithmeticTwap(startRecord, endRecord, quoteAsset) +// } + +// func InterpolateRecord(record types.TwapRecord, t time.Time) types.TwapRecord { +// return interpolateRecord(record, t) +// } diff --git a/x/gamm/twap/keeper_test.go b/x/gamm/twap/keeper_test.go new file mode 100644 index 00000000000..4ff8a68e015 --- /dev/null +++ b/x/gamm/twap/keeper_test.go @@ -0,0 +1,63 @@ +package twap_test + +import ( + "testing" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" + + "github.com/osmosis-labs/osmosis/v10/app/apptesting" + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap" + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" +) + +var defaultUniV2Coins = sdk.NewCoins(sdk.NewInt64Coin("token/B", 1_000_000_000), sdk.NewInt64Coin("token/A", 1_000_000_000)) +var baseTime = time.Unix(1257894000, 0).UTC() + +type TestSuite struct { + apptesting.KeeperTestHelper + twapkeeper *twap.Keeper +} + +func TestSuiteRun(t *testing.T) { + suite.Run(t, new(TestSuite)) +} + +func (s *TestSuite) SetupTest() { + s.Setup() + s.twapkeeper = s.App.TwapKeeper +} + +// sets up a new two asset pool, with spot price 1 +func (s *TestSuite) setupDefaultPool() (poolId uint64, denomA, denomB string) { + poolId = s.PrepareUni2PoolWithAssets(defaultUniV2Coins[0], defaultUniV2Coins[1]) + denomA, denomB = defaultUniV2Coins[1].Denom, defaultUniV2Coins[0].Denom + return +} + +func newEmptyPriceRecord(poolId uint64, t time.Time, asset0 string, asset1 string) types.TwapRecord { + return types.TwapRecord{ + PoolId: poolId, + Time: t, + Asset0Denom: asset0, + Asset1Denom: asset1, + + P0LastSpotPrice: sdk.ZeroDec(), + P1LastSpotPrice: sdk.ZeroDec(), + P0ArithmeticTwapAccumulator: sdk.ZeroDec(), + P1ArithmeticTwapAccumulator: sdk.ZeroDec(), + } +} + +func recordWithUpdatedAccum(record types.TwapRecord, accum0 sdk.Dec, accum1 sdk.Dec) types.TwapRecord { + record.P0ArithmeticTwapAccumulator = accum0 + record.P1ArithmeticTwapAccumulator = accum1 + return record +} + +func recordWithUpdatedSpotPrice(record types.TwapRecord, sp0 sdk.Dec, sp1 sdk.Dec) types.TwapRecord { + record.P0LastSpotPrice = sp0 + record.P1LastSpotPrice = sp1 + return record +} diff --git a/x/gamm/twap/store.go b/x/gamm/twap/store.go index 5a95438881c..e7bf9a551b8 100644 --- a/x/gamm/twap/store.go +++ b/x/gamm/twap/store.go @@ -1,11 +1,21 @@ +//nolint:unused,deadcode package twap import ( "encoding/binary" + "errors" + "fmt" + "time" sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/osmosis-labs/osmosis/v10/osmoutils" + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" ) +// trackChangedPool places an entry into a transient store, +// to track that this pool changed this block. +// This tracking is for use in EndBlock, to create new TWAP records. func (k Keeper) trackChangedPool(ctx sdk.Context, poolId uint64) { store := ctx.TransientStore(k.transientKey) poolIdBz := make([]byte, 8) @@ -15,17 +25,121 @@ func (k Keeper) trackChangedPool(ctx sdk.Context, poolId uint64) { store.Set(poolIdBz, sentinelExistsValue) } -//nolint:unused,deadcode +// getChangedPools returns all poolIDs that changed this block. +// This is to be guaranteed by trackChangedPool being called on every +// price-affecting pool action. func (k Keeper) getChangedPools(ctx sdk.Context) []uint64 { store := ctx.TransientStore(k.transientKey) iter := store.Iterator(nil, nil) defer iter.Close() alteredPoolIds := []uint64{} - for ; iter.Key() != nil; iter.Next() { + for ; iter.Valid(); iter.Next() { k := iter.Key() poolId := binary.LittleEndian.Uint64(k) alteredPoolIds = append(alteredPoolIds, poolId) } return alteredPoolIds } + +// storeHistoricalTWAP writes a twap to the store, in all needed indexing. +func (k Keeper) storeHistoricalTWAP(ctx sdk.Context, twap types.TwapRecord) { + store := ctx.KVStore(k.storeKey) + key1 := types.FormatHistoricalTimeIndexTWAPKey(twap.Time, twap.PoolId, twap.Asset0Denom, twap.Asset1Denom) + key2 := types.FormatHistoricalPoolIndexTWAPKey(twap.PoolId, twap.Time, twap.Asset0Denom, twap.Asset1Denom) + osmoutils.MustSet(store, key1, &twap) + osmoutils.MustSet(store, key2, &twap) +} + +func (k Keeper) pruneRecordsBeforeTime(ctx sdk.Context, lastTime time.Time) { + // TODO: Stub +} + +//nolint:unused,deadcode +func (k Keeper) deleteHistoricalRecord(ctx sdk.Context, twap types.TwapRecord) { + store := ctx.KVStore(k.storeKey) + key1 := types.FormatHistoricalTimeIndexTWAPKey(twap.Time, twap.PoolId, twap.Asset0Denom, twap.Asset1Denom) + key2 := types.FormatHistoricalPoolIndexTWAPKey(twap.PoolId, twap.Time, twap.Asset0Denom, twap.Asset1Denom) + store.Delete(key1) + store.Delete(key2) +} + +// getMostRecentRecordStoreRepresentation returns the most recent twap record in the store +// for the provided (pool, asset0, asset1) triplet. +// Its called store representation, because most recent record can refer to it being +// interpolated to the current block time, or after events in this block. +// Neither of which apply to the record this returns. +func (k Keeper) getMostRecentRecordStoreRepresentation(ctx sdk.Context, poolId uint64, asset0Denom string, asset1Denom string) (types.TwapRecord, error) { + store := ctx.KVStore(k.storeKey) + key := types.FormatMostRecentTWAPKey(poolId, asset0Denom, asset1Denom) + bz := store.Get(key) + return types.ParseTwapFromBz(bz) +} + +// getAllMostRecentRecordsForPool returns all most recent twap records +// (in state representation) for the provided pool id. +func (k Keeper) getAllMostRecentRecordsForPool(ctx sdk.Context, poolId uint64) ([]types.TwapRecord, error) { + store := ctx.KVStore(k.storeKey) + return types.GetAllMostRecentTwapsForPool(store, poolId) +} + +// storeNewRecord stores a record, in both the most recent record store and historical stores. +func (k Keeper) storeNewRecord(ctx sdk.Context, twap types.TwapRecord) { + store := ctx.KVStore(k.storeKey) + key := types.FormatMostRecentTWAPKey(twap.PoolId, twap.Asset0Denom, twap.Asset1Denom) + osmoutils.MustSet(store, key, &twap) + k.storeHistoricalTWAP(ctx, twap) +} + +// getRecordAtOrBeforeTime on a given input (id, t, asset0, asset1) +// returns the TWAP record from state for (id, t', asset0, asset1), +// where t' is such that: +// * t' <= t +// * there exists no t'' in state, where t'' < t' +// +// This returns an error if: +// * there is no historical record in state at or before t +// - Occurs if t is older than pruning period, or pool creation date. +// * there is no record for the asset pair (asset0, asset1) in particular +// - e.g. asset not in pool, or provided in wrong order. +func (k Keeper) getRecordAtOrBeforeTime(ctx sdk.Context, poolId uint64, t time.Time, asset0Denom string, asset1Denom string) (types.TwapRecord, error) { + store := ctx.KVStore(k.storeKey) + // We make an iteration from time=t + 1ns, to time=0 for this pool. + // Note that we cannot get any time entries from t + 1ns, as the key would be `prefix|t+1ns` + // and the end for a reverse iterator is exclusive. Thus the largest key that can be returned + // begins with a prefix of `prefix|t` + startKey := types.FormatHistoricalPoolIndexTimePrefix(poolId, time.Unix(0, 0)) + endKey := types.FormatHistoricalPoolIndexTimePrefix(poolId, t.Add(time.Nanosecond)) + lastParsedTime := time.Time{} + stopFn := func(key []byte) bool { + // halt iteration if we can't parse the time, or we've successfully parsed + // a time, and have iterated beyond records for that time. + parsedTime, err := types.ParseTimeFromHistoricalPoolIndexKey(key) + if err != nil { + return true + } + if lastParsedTime.After(parsedTime) { + return true + } + lastParsedTime = parsedTime + return false + } + + reverseIterate := true + twaps, err := osmoutils.GetIterValuesWithStop(store, startKey, endKey, reverseIterate, stopFn, types.ParseTwapFromBz) + if err != nil { + return types.TwapRecord{}, err + } + if len(twaps) == 0 { + return types.TwapRecord{}, errors.New("looking for a time thats too old, not in the historical index. " + + " Try storing the accumulator value.") + } + + for _, twap := range twaps { + if twap.Asset0Denom == asset0Denom && twap.Asset1Denom == asset1Denom { + return twap, nil + } + } + return types.TwapRecord{}, fmt.Errorf("TWAP not found, but there are twaps available for this time."+ + " Were provided asset0denom and asset1denom (%s, %s) correct, and in order (asset0 > asset1)?", asset0Denom, asset1Denom) +} diff --git a/x/gamm/twap/store_test.go b/x/gamm/twap/store_test.go new file mode 100644 index 00000000000..50712277af5 --- /dev/null +++ b/x/gamm/twap/store_test.go @@ -0,0 +1,191 @@ +package twap_test + +import ( + "time" + + "github.com/osmosis-labs/osmosis/v10/x/gamm/twap/types" +) + +// TestTrackChangedPool takes a list of poolIds as test cases, and runs one list per block. +// Every simulated block, checks that there no changed pools. +// Then runs k.trackChangedPool on every item in the test case list. +// Then, checks that changed pools return the list, deduplicated. +// +// This achieves testing the functionality that we depend on, that this clears every end block. +func (s *TestSuite) TestTrackChangedPool() { + tests := map[string][]uint64{ + "single": {1}, + "duplicated": {1, 1}, + "four": {1, 2, 3, 4}, + "many with dups": {1, 2, 3, 4, 3, 2, 1}, + } + for name, test := range tests { + s.Run(name, func() { + // Test that no cumulative ID registers as tracked + changedPools := s.twapkeeper.GetChangedPools(s.Ctx) + s.Require().Empty(changedPools) + + // Track every pool in list + cumulativeIds := map[uint64]bool{} + for _, v := range test { + cumulativeIds[v] = true + s.twapkeeper.TrackChangedPool(s.Ctx, v) + } + + changedPools = s.twapkeeper.GetChangedPools(s.Ctx) + s.Require().Equal(len(cumulativeIds), len(changedPools)) + for _, v := range changedPools { + s.Require().True(cumulativeIds[v]) + } + s.Commit() + }) + } +} + +// TestGetAllMostRecentRecordsForPool takes a list of records as test cases, +// and runs storeNewRecord for everything in sequence. +// Then it runs GetAllMostRecentRecordsForPool, and sees if its equal to expected +func (s *TestSuite) TestGetAllMostRecentRecordsForPool() { + tPlusOne := baseTime.Add(time.Second) + baseRecord := newEmptyPriceRecord(1, baseTime, "tokenB", "tokenA") + tPlusOneRecord := newEmptyPriceRecord(1, tPlusOne, "tokenB", "tokenA") + tests := map[string]struct { + recordsToSet []types.TwapRecord + poolId uint64 + expectedRecords []types.TwapRecord + }{ + "set single record": { + recordsToSet: []types.TwapRecord{baseRecord}, + poolId: 1, + expectedRecords: []types.TwapRecord{baseRecord}, + }, + "query non-existent pool": { + recordsToSet: []types.TwapRecord{baseRecord}, + poolId: 2, + expectedRecords: []types.TwapRecord{}, + }, + "set single record, different pool ID": { + recordsToSet: []types.TwapRecord{newEmptyPriceRecord(2, baseTime, "tokenB", "tokenA")}, + poolId: 2, + expectedRecords: []types.TwapRecord{newEmptyPriceRecord(2, baseTime, "tokenB", "tokenA")}, + }, + "set two records": { + recordsToSet: []types.TwapRecord{baseRecord, tPlusOneRecord}, + poolId: 1, + expectedRecords: []types.TwapRecord{tPlusOneRecord}, + }, + "set two records, reverse order": { + // The last record, independent of time, takes precedence for most recent. + recordsToSet: []types.TwapRecord{tPlusOneRecord, baseRecord}, + poolId: 1, + expectedRecords: []types.TwapRecord{baseRecord}, + }, + "set multi-asset pool record": { + recordsToSet: []types.TwapRecord{ + newEmptyPriceRecord(1, baseTime, "tokenB", "tokenA"), + newEmptyPriceRecord(1, baseTime, "tokenC", "tokenB"), + newEmptyPriceRecord(1, baseTime, "tokenC", "tokenA")}, + poolId: 1, + expectedRecords: []types.TwapRecord{ + newEmptyPriceRecord(1, baseTime, "tokenB", "tokenA"), + newEmptyPriceRecord(1, baseTime, "tokenC", "tokenA"), + newEmptyPriceRecord(1, baseTime, "tokenC", "tokenB")}, + }, + } + + for name, test := range tests { + s.Run(name, func() { + s.SetupTest() + for _, record := range test.recordsToSet { + s.twapkeeper.StoreNewRecord(s.Ctx, record) + } + actualRecords, err := s.twapkeeper.GetAllMostRecentRecordsForPool(s.Ctx, test.poolId) + s.Require().NoError(err) + s.Require().Equal(test.expectedRecords, actualRecords) + }) + } +} + +// TestGetRecordAtOrBeforeTime takes a list of records as test cases, +// and runs storeNewRecord for everything in sequence. +// Then it runs GetRecordAtOrBeforeTime, and sees if its equal to expected +func (s *TestSuite) TestGetRecordAtOrBeforeTime() { + type getRecordInput struct { + poolId uint64 + t time.Time + asset0Denom string + asset1Denom string + } + defaultInputAt := func(t time.Time) getRecordInput { return getRecordInput{1, t, "tokenB", "tokenA"} } + wrongPoolIdInputAt := func(t time.Time) getRecordInput { return getRecordInput{2, t, "tokenB", "tokenA"} } + defaultRevInputAt := func(t time.Time) getRecordInput { return getRecordInput{1, t, "tokenA", "tokenB"} } + baseRecord := newEmptyPriceRecord(1, baseTime, "tokenB", "tokenA") + tMin1 := baseTime.Add(-time.Second) + tMin1Record := newEmptyPriceRecord(1, tMin1, "tokenB", "tokenA") + tPlus1 := baseTime.Add(time.Second) + tPlus1Record := newEmptyPriceRecord(1, tPlus1, "tokenB", "tokenA") + + tests := map[string]struct { + recordsToSet []types.TwapRecord + input getRecordInput + expectedRecord types.TwapRecord + expErr bool + }{ + "no entries": {[]types.TwapRecord{}, defaultInputAt(baseTime), baseRecord, true}, + "get at latest (exact)": {[]types.TwapRecord{baseRecord}, defaultInputAt(baseTime), baseRecord, false}, + "rev at latest (exact)": {[]types.TwapRecord{baseRecord}, defaultRevInputAt(baseTime), baseRecord, true}, + + "get latest (exact) w/ past entries": { + []types.TwapRecord{tMin1Record, baseRecord}, defaultInputAt(baseTime), baseRecord, false}, + "get entry (exact) w/ a subsequent entry": { + []types.TwapRecord{tMin1Record, baseRecord}, defaultInputAt(tMin1), tMin1Record, false}, + "get sandwitched entry (exact)": { + []types.TwapRecord{tMin1Record, baseRecord, tPlus1Record}, defaultInputAt(baseTime), baseRecord, false}, + "rev sandwitched entry (exact)": { + []types.TwapRecord{tMin1Record, baseRecord, tPlus1Record}, defaultRevInputAt(baseTime), baseRecord, true}, + + "get future": {[]types.TwapRecord{baseRecord}, defaultInputAt(tPlus1), baseRecord, false}, + "get future w/ past entries": {[]types.TwapRecord{tMin1Record, baseRecord}, defaultInputAt(tPlus1), baseRecord, false}, + + "get in between entries (2 entry)": { + []types.TwapRecord{tMin1Record, baseRecord}, + defaultInputAt(baseTime.Add(-time.Millisecond)), tMin1Record, false}, + "get in between entries (3 entry)": { + []types.TwapRecord{tMin1Record, baseRecord, tPlus1Record}, + defaultInputAt(baseTime.Add(-time.Millisecond)), tMin1Record, false}, + "get in between entries (3 entry) #2": { + []types.TwapRecord{tMin1Record, baseRecord, tPlus1Record}, + defaultInputAt(baseTime.Add(time.Millisecond)), baseRecord, false}, + + "query too old": { + []types.TwapRecord{tMin1Record, baseRecord, tPlus1Record}, + defaultInputAt(baseTime.Add(-time.Second * 2)), + baseRecord, true}, + + "non-existent pool ID": { + []types.TwapRecord{tMin1Record, baseRecord, tPlus1Record}, + wrongPoolIdInputAt(baseTime), baseRecord, true}, + "pool2 record get": { + recordsToSet: []types.TwapRecord{newEmptyPriceRecord(2, baseTime, "tokenB", "tokenA")}, + input: wrongPoolIdInputAt(baseTime), + expectedRecord: newEmptyPriceRecord(2, baseTime, "tokenB", "tokenA"), + expErr: false}, + } + for name, test := range tests { + s.Run(name, func() { + s.SetupTest() + for _, record := range test.recordsToSet { + s.twapkeeper.StoreNewRecord(s.Ctx, record) + } + record, err := s.twapkeeper.GetRecordAtOrBeforeTime( + s.Ctx, + test.input.poolId, test.input.t, test.input.asset0Denom, test.input.asset1Denom) + if test.expErr { + s.Require().Error(err) + return + } + s.Require().NoError(err) + s.Require().Equal(test.expectedRecord, record) + }) + } +} diff --git a/x/gamm/twap/types/keys.go b/x/gamm/twap/types/keys.go index 32d683cf615..0a995c98e4c 100644 --- a/x/gamm/twap/types/keys.go +++ b/x/gamm/twap/types/keys.go @@ -82,9 +82,11 @@ func ParseTimeFromHistoricalPoolIndexKey(key []byte) (time.Time, error) { return t, nil } +// GetAllMostRecentTwapsForPool returns all of the most recent twap records for a pool id. +// if the pool id doesn't exist, then this returns a blank list. func GetAllMostRecentTwapsForPool(store sdk.KVStore, poolId uint64) ([]TwapRecord, error) { - startPrefix := fmt.Sprintf("%s%s%d%s", mostRecentTWAPsPrefix, KeySeparator, poolId, KeySeparator) - endPrefix := fmt.Sprintf("%s%s%d%s", mostRecentTWAPsPrefix, KeySeparator, poolId+1, KeySeparator) + startPrefix := fmt.Sprintf("%s%d%s", mostRecentTWAPsPrefix, poolId, KeySeparator) + endPrefix := fmt.Sprintf("%s%d%s", mostRecentTWAPsPrefix, poolId+1, KeySeparator) return osmoutils.GatherValuesFromStore(store, []byte(startPrefix), []byte(endPrefix), ParseTwapFromBz) } From 3c71c97216383dd8cd2b13e615f037f3bf253161 Mon Sep 17 00:00:00 2001 From: Roman Date: Mon, 1 Aug 2022 20:36:39 -0700 Subject: [PATCH 138/376] chore(deps): upgrade sdk with min proposer deposit and update e2e (#2243) * chore(deps): upgrade sdk with min proposer deposit and update e2e * update to correct tag * update tag * changelog * use default value from gov types for min deposit --- CHANGELOG.md | 4 ++++ go.mod | 4 ++-- go.sum | 4 ++-- tests/e2e/configurer/chain/commands.go | 18 +++++++++++------- tests/e2e/configurer/config/constants.go | 9 +++++++++ tests/e2e/configurer/upgrade.go | 5 ++++- tests/e2e/e2e_test.go | 7 +++++-- 7 files changed, 37 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95766a487b5..83e697b1e1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Improvements * [#2214](https://github.com/osmosis-labs/osmosis/pull/2214) Speedup epoch distribution, superfluid component +### SDK Upgrades +* [#2245](https://github.com/osmosis-labs/osmosis/pull/2244) Upgrade SDK with the following major changes: + * Minimum deposit on proposer at submission time: https://github.com/osmosis-labs/cosmos-sdk/pull/296 + ## [v9.0.0 - Nitrogen](https://github.com/osmosis-labs/osmosis/releases/tag/v9.0.0) The Nitrogen release brings with it a number of features enabling further cosmwasm development work in Osmosis. diff --git a/go.mod b/go.mod index 6fba47841e0..003f5345f42 100644 --- a/go.mod +++ b/go.mod @@ -285,8 +285,8 @@ require ( replace ( // branch: v0.27.0.rc3-osmo, current tag: v0.27.0.rc3-osmo github.com/CosmWasm/wasmd => github.com/osmosis-labs/wasmd v0.27.0-rc2.0.20220517191021-59051aa18d58 - // Our cosmos-sdk branch is: https://github.com/osmosis-labs/cosmos-sdk, current tag: v0.45.0x-osmo-v11-alpha.2, current branch: osmosis-main - github.com/cosmos/cosmos-sdk => github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220721082708-0aca1df58871 + // Our cosmos-sdk branch is: https://github.com/osmosis-labs/cosmos-sdk, current tag: 0.45.0x-osmo-v11-alpha.5 current branch: osmosis-main + github.com/cosmos/cosmos-sdk => github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220727221653-51bfa90799ee // Use Osmosis fast iavl github.com/cosmos/iavl => github.com/osmosis-labs/iavl v0.17.3-osmo-v7 // use cosmos-compatible protobufs diff --git a/go.sum b/go.sum index 4d61864a186..cc6454787e6 100644 --- a/go.sum +++ b/go.sum @@ -1042,8 +1042,8 @@ github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4 github.com/ory/dockertest v3.3.5+incompatible/go.mod h1:1vX4m9wsvi00u5bseYwXaSnhNrne+V0E6LAcBILJdPs= github.com/ory/dockertest/v3 v3.9.1 h1:v4dkG+dlu76goxMiTT2j8zV7s4oPPEppKT8K8p2f1kY= github.com/ory/dockertest/v3 v3.9.1/go.mod h1:42Ir9hmvaAPm0Mgibk6mBPi7SFvTXxEcnztDYOJ//uM= -github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220721082708-0aca1df58871 h1:VkQCYrUg8xpUOoDRP7pBcQi8ceqvxC75SBkDAKFFh3g= -github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220721082708-0aca1df58871/go.mod h1:uUkGXyCWol+CHoaMxZA0nKglvlN5uHBCMbMSsZoGSAs= +github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220727221653-51bfa90799ee h1:JUWaacaNfxC0IxxkpC/MsJozi1eKQztZX+Wa9OU6+cw= +github.com/osmosis-labs/cosmos-sdk v0.45.1-0.20220727221653-51bfa90799ee/go.mod h1:uUkGXyCWol+CHoaMxZA0nKglvlN5uHBCMbMSsZoGSAs= github.com/osmosis-labs/iavl v0.17.3-osmo-v7 h1:6KcADC/WhL7yDmNQxUIJt2XmzNt4FfRmq9gRke45w74= github.com/osmosis-labs/iavl v0.17.3-osmo-v7/go.mod h1:lJEOIlsd3sVO0JDyXWIXa9/Ur5FBscP26zJx0KxHjto= github.com/osmosis-labs/wasmd v0.27.0-rc2.0.20220517191021-59051aa18d58 h1:15l3Iss2oCGCeJRi2g3CuCnqmEjpAr3Le7cDnoN/LS0= diff --git a/tests/e2e/configurer/chain/commands.go b/tests/e2e/configurer/chain/commands.go index ac806545f70..c272251570e 100644 --- a/tests/e2e/configurer/chain/commands.go +++ b/tests/e2e/configurer/chain/commands.go @@ -6,6 +6,10 @@ import ( "strconv" "strings" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer/config" + + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" ) @@ -17,25 +21,25 @@ func (n *NodeConfig) CreatePool(poolFile, from string) { n.LogActionF("successfully created pool") } -func (n *NodeConfig) SubmitUpgradeProposal(upgradeVersion string, upgradeHeight int64) { +func (n *NodeConfig) SubmitUpgradeProposal(upgradeVersion string, upgradeHeight int64, initialDeposit sdk.Coin) { n.LogActionF("submitting upgrade proposal %s for height %d", upgradeVersion, upgradeHeight) - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%d", upgradeHeight), "--upgrade-info=\"\"", "--from=val"} + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "software-upgrade", upgradeVersion, fmt.Sprintf("--title=\"%s upgrade\"", upgradeVersion), "--description=\"upgrade proposal submission\"", fmt.Sprintf("--upgrade-height=%d", upgradeHeight), "--upgrade-info=\"\"", "--from=val", fmt.Sprintf("--deposit=%s", initialDeposit)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) n.LogActionF("successfully submitted upgrade proposal") } -func (n *NodeConfig) SubmitSuperfluidProposal(asset string) { +func (n *NodeConfig) SubmitSuperfluidProposal(asset string, initialDeposit sdk.Coin) { n.LogActionF("submitting superfluid proposal for asset %s", asset) - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "set-superfluid-assets-proposal", fmt.Sprintf("--superfluid-assets=%s", asset), fmt.Sprintf("--title=\"%s superfluid asset\"", asset), fmt.Sprintf("--description=\"%s superfluid asset\"", asset), "--from=val"} + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "set-superfluid-assets-proposal", fmt.Sprintf("--superfluid-assets=%s", asset), fmt.Sprintf("--title=\"%s superfluid asset\"", asset), fmt.Sprintf("--description=\"%s superfluid asset\"", asset), "--from=val", fmt.Sprintf("--deposit=%s", initialDeposit)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) n.LogActionF("successfully submitted superfluid proposal for asset %s", asset) } -func (n *NodeConfig) SubmitTextProposal(text string) { +func (n *NodeConfig) SubmitTextProposal(text string, initialDeposit sdk.Coin) { n.LogActionF("submitting text gov proposal") - cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "--type=text", fmt.Sprintf("--title=\"%s\"", text), "--description=\"test text proposal\"", "--from=val"} + cmd := []string{"osmosisd", "tx", "gov", "submit-proposal", "--type=text", fmt.Sprintf("--title=\"%s\"", text), "--description=\"test text proposal\"", "--from=val", fmt.Sprintf("--deposit=%s", initialDeposit)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) n.LogActionF("successfully submitted text gov proposal") @@ -43,7 +47,7 @@ func (n *NodeConfig) SubmitTextProposal(text string) { func (n *NodeConfig) DepositProposal(proposalNumber int) { n.LogActionF("depositing on proposal: %d", proposalNumber) - cmd := []string{"osmosisd", "tx", "gov", "deposit", fmt.Sprintf("%d", proposalNumber), "500000000uosmo", "--from=val"} + cmd := []string{"osmosisd", "tx", "gov", "deposit", fmt.Sprintf("%d", proposalNumber), sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.MinDepositValue)).String(), "--from=val"} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) require.NoError(n.t, err) n.LogActionF("successfully deposited on proposal %d", proposalNumber) diff --git a/tests/e2e/configurer/config/constants.go b/tests/e2e/configurer/config/constants.go index 3e2518261fd..64321c5c4fb 100644 --- a/tests/e2e/configurer/config/constants.go +++ b/tests/e2e/configurer/config/constants.go @@ -1,5 +1,7 @@ package config +import govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + const ( // if not skipping upgrade, how many blocks we allow for fork to run pre upgrade state creation ForkHeightPreUpgradeOffset int64 = 60 @@ -14,3 +16,10 @@ const ( // max retries for json unmarshalling MaxRetries = 60 ) + +var ( + // Minimum deposit value for a proposal to enter a voting period. + MinDepositValue = govtypes.DefaultMinDepositTokens.Int64() + // Minimum deposit value for proposal to be submitted. + InitialMinDeposit = MinDepositValue / 4 +) diff --git a/tests/e2e/configurer/upgrade.go b/tests/e2e/configurer/upgrade.go index d6fab3b2eba..57ca56121e5 100644 --- a/tests/e2e/configurer/upgrade.go +++ b/tests/e2e/configurer/upgrade.go @@ -7,6 +7,9 @@ import ( "testing" "time" + sdk "github.com/cosmos/cosmos-sdk/types" + + appparams "github.com/osmosis-labs/osmosis/v10/app/params" "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer/chain" "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer/config" "github.com/osmosis-labs/osmosis/v10/tests/e2e/containers" @@ -149,7 +152,7 @@ func (uc *UpgradeConfigurer) runProposalUpgrade() error { return err } chainConfig.UpgradePropHeight = currentHeight + int64(chainConfig.VotingPeriod) + int64(config.PropSubmitBlocks) + int64(config.PropBufferBlocks) - node.SubmitUpgradeProposal(uc.upgradeVersion, chainConfig.UpgradePropHeight) + node.SubmitUpgradeProposal(uc.upgradeVersion, chainConfig.UpgradePropHeight, sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.InitialMinDeposit))) chainConfig.LatestProposalNumber += 1 node.DepositProposal(chainConfig.LatestProposalNumber) } diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index a653430283b..24a52972046 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -7,8 +7,11 @@ import ( "strconv" "time" + sdk "github.com/cosmos/cosmos-sdk/types" coretypes "github.com/tendermint/tendermint/rpc/core/types" + appparams "github.com/osmosis-labs/osmosis/v10/app/params" + "github.com/osmosis-labs/osmosis/v10/tests/e2e/configurer/config" "github.com/osmosis-labs/osmosis/v10/tests/e2e/initialization" ) @@ -50,7 +53,7 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { s.NoError(err) // enable superfluid via proposal. - node.SubmitSuperfluidProposal("gamm/pool/1") + node.SubmitSuperfluidProposal("gamm/pool/1", sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.InitialMinDeposit))) chain.LatestProposalNumber += 1 node.DepositProposal(chain.LatestProposalNumber) for _, node := range chain.NodeConfigs { @@ -67,7 +70,7 @@ func (s *IntegrationTestSuite) TestSuperfluidVoting() { node.SuperfluidDelegate(chain.LatestLockNumber, chain.NodeConfigs[1].OperatorAddress, walletName) // create a text prop, deposit and vote yes - node.SubmitTextProposal("superfluid vote overwrite test") + node.SubmitTextProposal("superfluid vote overwrite test", sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.InitialMinDeposit))) chain.LatestProposalNumber += 1 node.DepositProposal(chain.LatestProposalNumber) for _, node := range chain.NodeConfigs { From f9c823514bda346adefd60a106bbb922dc7407fc Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Wed, 3 Aug 2022 00:58:09 +0900 Subject: [PATCH 139/376] Add codec init to tokenfactory (#2265) --- x/tokenfactory/types/codec.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/x/tokenfactory/types/codec.go b/x/tokenfactory/types/codec.go index 7b1c1413b37..6b7571f7005 100644 --- a/x/tokenfactory/types/codec.go +++ b/x/tokenfactory/types/codec.go @@ -29,4 +29,12 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } -var ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) +) + +func init() { + RegisterCodec(amino) + amino.Seal() +} From c3acdf86aac06a6b0b4e4bd457634a714bda7467 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 2 Aug 2022 09:27:35 -0700 Subject: [PATCH 140/376] refactor(x/mint): AfterEpochEndHook and tests (#2258) * refactor(x/mint): AfterEpochEndHook and tests * refactor/test(x/mint): after epoch end hooks * clean up * add panic case * remove TestEndOfEpochNoDistributionWhenIsNotYetStartTime - covered by table-driven * remove TestEndOfEpochMintedCoinDistribution - covered by table driven * remove TestMintedCoinDistributionWhenDevRewardsAddressEmpty - covered at different abstraction level * clean up * reuse variables and constants in hook tests * revert AfterEpochEnd * reduce duplicaton * Update x/mint/keeper/hooks_test.go Co-authored-by: Adam Tucker * Update x/mint/keeper/hooks_test.go Co-authored-by: Adam Tucker * Update x/mint/keeper/hooks.go Co-authored-by: Adam Tucker Co-authored-by: Adam Tucker --- x/gamm/pool-models/stableswap/amm_test.go | 17 +- x/mint/keeper/hooks.go | 12 +- x/mint/keeper/hooks_test.go | 632 ++++++++++++++-------- 3 files changed, 423 insertions(+), 238 deletions(-) diff --git a/x/gamm/pool-models/stableswap/amm_test.go b/x/gamm/pool-models/stableswap/amm_test.go index e77f83d5ec8..31681b9169f 100644 --- a/x/gamm/pool-models/stableswap/amm_test.go +++ b/x/gamm/pool-models/stableswap/amm_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/osmosis-labs/osmosis/v10/osmoutils" "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/internal/test_helpers" ) @@ -14,14 +15,6 @@ type StableSwapTestSuite struct { test_helpers.CfmmCommonTestSuite } -// Replace with https://github.com/cosmos/cosmos-sdk/blob/master/types/decimal.go#L892-L895 -// once our SDK branch is up to date with it -func decApproxEq(t *testing.T, exp sdk.Dec, actual sdk.Dec, errTolerance sdk.Dec) { - // We want |exp - actual| < errTolerance - diff := exp.Sub(actual).Abs() - require.True(t, diff.LTE(errTolerance), "expected %s, got %s, maximum errTolerance %s", exp, actual, errTolerance) -} - func TestCFMMInvariantTwoAssets(t *testing.T) { kErrTolerance := sdk.OneDec() @@ -53,15 +46,15 @@ func TestCFMMInvariantTwoAssets(t *testing.T) { xOut := solveCfmm(test.xReserve, test.yReserve, test.yIn) k1 := cfmmConstant(test.xReserve.Sub(xOut), test.yReserve.Add(test.yIn)) - decApproxEq(t, k0, k1, kErrTolerance) + osmoutils.DecApproxEq(t, k0, k1, kErrTolerance) // using multi-asset cfmm (should be equivalent with u = 1, w = 0) k2 := cfmmConstantMulti(test.xReserve, test.yReserve, sdk.OneDec(), sdk.ZeroDec()) - decApproxEq(t, k2, k0, kErrTolerance) + osmoutils.DecApproxEq(t, k2, k0, kErrTolerance) xOut2 := solveCfmmMulti(test.xReserve, test.yReserve, sdk.ZeroDec(), test.yIn) fmt.Println(xOut2) k3 := cfmmConstantMulti(test.xReserve.Sub(xOut2), test.yReserve.Add(test.yIn), sdk.OneDec(), sdk.ZeroDec()) - decApproxEq(t, k2, k3, kErrTolerance) + osmoutils.DecApproxEq(t, k2, k3, kErrTolerance) } } @@ -103,7 +96,7 @@ func TestCFMMInvariantMultiAssets(t *testing.T) { xOut2 := solveCfmmMulti(test.xReserve, test.yReserve, test.wSumSquares, test.yIn) fmt.Println(xOut2) k3 := cfmmConstantMulti(test.xReserve.Sub(xOut2), test.yReserve.Add(test.yIn), test.uReserve, test.wSumSquares) - decApproxEq(t, k2, k3, kErrTolerance) + osmoutils.DecApproxEq(t, k2, k3, kErrTolerance) } } diff --git a/x/mint/keeper/hooks.go b/x/mint/keeper/hooks.go index 6fb37f37692..2e58e4c00fc 100644 --- a/x/mint/keeper/hooks.go +++ b/x/mint/keeper/hooks.go @@ -10,9 +10,18 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// BeforeEpochStart is a hook which is executed before the start of an epoch. It is a no-op for mint module. func (k Keeper) BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) { + // no-op } +// AfterEpochEnd is a hook which is executed after the end of an epoch. +// This hook should attempt to mint and distribute coins according to +// the configuration set via parameters. In addition, it handles the logic +// for reducing minted coins according to the parameters. +// For an attempt to mint to occur: +// - given epochIdentifier must be equal to the mint epoch identifier set via parameters. +// - given epochNumber must be greater than or equal to the mint start epoch set via parameters. func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) { params := k.GetParams(ctx) @@ -25,14 +34,13 @@ func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumb } // fetch stored minter & params minter := k.GetMinter(ctx) - params := k.GetParams(ctx) // Check if we have hit an epoch where we update the inflation parameter. // We measure time between reductions in number of epochs. // This avoids issues with measuring in block numbers, as epochs have fixed intervals, with very // low variance at the relevant sizes. As a result, it is safe to store the epoch number // of the last reduction to be later retrieved for comparison. - if epochNumber >= k.GetParams(ctx).ReductionPeriodInEpochs+k.GetLastReductionEpochNum(ctx) { + if epochNumber >= params.ReductionPeriodInEpochs+k.GetLastReductionEpochNum(ctx) { // Reduce the reward per reduction period minter.EpochProvisions = minter.NextEpochProvisions(params) k.SetMinter(ctx, minter) diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index 65a70d9c1e2..b3b67adefdb 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -1,198 +1,396 @@ package keeper_test import ( - "time" - - abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" osmoapp "github.com/osmosis-labs/osmosis/v10/app" + "github.com/osmosis-labs/osmosis/v10/osmoutils" "github.com/osmosis-labs/osmosis/v10/x/mint/keeper" "github.com/osmosis-labs/osmosis/v10/x/mint/types" sdk "github.com/cosmos/cosmos-sdk/types" ) -func (suite *KeeperTestSuite) TestEndOfEpochMintedCoinDistribution() { - app := suite.App - ctx := suite.Ctx - - header := tmproto.Header{Height: app.LastBlockHeight() + 1} - app.BeginBlock(abci.RequestBeginBlock{Header: header}) - - params := app.IncentivesKeeper.GetParams(ctx) - futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) +const ( + // Most values here are taken from mainnet genesis to mimic real-world behavior: + // https://github.com/osmosis-labs/networks/raw/main/osmosis-1/genesis.json + defaultGenesisEpochProvisions = "821917808219.178082191780821917" + defaultEpochIdentifier = "day" + // actual value taken from mainnet for sanity checking calculations. + defaultMainnetThirdenedProvisions = "547945205479.452055068493150684" + defaultReductionPeriodInEpochs = 365 + defaultMintingRewardsDistributionStartEpoch int64 = 1 + defaultThirdeningEpochNum int64 = defaultReductionPeriodInEpochs + defaultMintingRewardsDistributionStartEpoch +) - // set developer rewards address - mintParams := app.MintKeeper.GetParams(ctx) - mintParams.WeightedDeveloperRewardsReceivers = []types.WeightedAddress{ - { - Address: sdk.AccAddress([]byte("addr1---------------")).String(), - Weight: sdk.NewDec(1), - }, - } - app.MintKeeper.SetParams(ctx, mintParams) - - height := int64(1) - lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) - // correct rewards - for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { - devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) - devRewardsModuleOrigin := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) - - // get pre-epoch osmo supply and supplyWithOffset - presupply := app.BankKeeper.GetSupply(ctx, mintParams.MintDenom) - presupplyWithOffset := app.BankKeeper.GetSupplyWithOffset(ctx, mintParams.MintDenom) - - app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) - app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - - mintParams = app.MintKeeper.GetParams(ctx) - mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.Staking) - suite.Require().NoError(err) - expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) - - // ensure post-epoch supply with offset changed by exactly the minted coins amount - // ensure post-epoch supply with offset changed by less than the minted coins amount (because of developer vesting account) - postsupply := app.BankKeeper.GetSupply(ctx, mintParams.MintDenom) - postsupplyWithOffset := app.BankKeeper.GetSupplyWithOffset(ctx, mintParams.MintDenom) - suite.Require().False(postsupply.IsEqual(presupply.Add(mintedCoin))) - suite.Require().True(postsupplyWithOffset.IsEqual(presupplyWithOffset.Add(mintedCoin))) - - // check community pool balance increase - feePoolNew := app.DistrKeeper.GetFeePool(ctx) - suite.Require().Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) - - // test that the dev rewards module account balance decreased by the correct amount - devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewards, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.Require().NoError(err) - suite.Require().Equal(devRewardsModuleAfter.Add(expectedDevRewards), devRewardsModuleOrigin, expectedRewards.String()) +var ( + defaultReductionFactor = sdk.NewDec(2).Quo(sdk.NewDec(3)) + defaultDistributionProportions = types.DistributionProportions{ + Staking: sdk.NewDecWithPrec(25, 2), + PoolIncentives: sdk.NewDecWithPrec(45, 2), + DeveloperRewards: sdk.NewDecWithPrec(25, 2), + CommunityPool: sdk.NewDecWithPrec(0o5, 2), } +) - app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) - app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - - lastReductionPeriod = app.MintKeeper.GetLastReductionEpochNum(ctx) - suite.Require().Equal(lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) - - for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { - devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) - devRewardsModuleOrigin := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) - - app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) - app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - - mintParams = app.MintKeeper.GetParams(ctx) - mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.Staking) - suite.Require().NoError(err) - expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) - - // check community pool balance increase - feePoolNew := app.DistrKeeper.GetFeePool(ctx) - suite.Require().Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) +// TestAfterEpochEnd tests that the after epoch end hook correctly +// distributes the rewards depending on what epoch it is in. +func (suite *KeeperTestSuite) TestAfterEpochEnd() { + var ( + testWeightedAddresses = []types.WeightedAddress{ + { + Address: testAddressOne.String(), + Weight: sdk.NewDecWithPrec(233, 3), + }, + { + Address: testAddressTwo.String(), + Weight: sdk.NewDecWithPrec(5, 1), + }, + { + Address: testAddressThree.String(), + Weight: sdk.NewDecWithPrec(50, 3), + }, + { + Address: testAddressFour.String(), + Weight: sdk.NewDecWithPrec(217, 3), + }, + } + maxArithmeticTolerance = sdk.NewDec(5) + expectedSupplyWithOffset = sdk.NewDec(0) + expectedSupply = sdk.NewDec(keeper.DeveloperVestingAmount) + ) - // test that the balance decreased by the correct amount - devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.Require().NoError(err) - suite.Require().Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) - } -} + suite.assertAddressWeightsAddUpToOne(testWeightedAddresses) -func (suite *KeeperTestSuite) TestMintedCoinDistributionWhenDevRewardsAddressEmpty() { - app := suite.App - ctx := suite.Ctx - - header := tmproto.Header{Height: app.LastBlockHeight() + 1} - app.BeginBlock(abci.RequestBeginBlock{Header: header}) - - params := app.IncentivesKeeper.GetParams(ctx) - futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) - - height := int64(1) - lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) - - checkDistribution := func(height int64) { - devRewardsModuleAcc := app.AccountKeeper.GetModuleAccount(ctx, types.DeveloperVestingModuleAcctName) - devRewardsModuleOrigin := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) - app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) - app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - - mintParams := app.MintKeeper.GetParams(ctx) - mintedCoin := app.MintKeeper.GetMinter(ctx).EpochProvision(mintParams) - expectedRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.Staking.Add(mintParams.DistributionProportions.DeveloperRewards)) - suite.Require().NoError(err) - expectedRewards := sdk.NewDecCoin("stake", expectedRewardsCoin.Amount) - - // check community pool balance increase - feePoolNew := app.DistrKeeper.GetFeePool(ctx) - suite.Require().Equal(feePoolOrigin.CommunityPool.Add(expectedRewards), feePoolNew.CommunityPool, height) - - // test that the dev rewards module account balance decreased by the correct amount - devRewardsModuleAfter := app.BankKeeper.GetAllBalances(ctx, devRewardsModuleAcc.GetAddress()) - expectedDevRewardsCoin, err := keeper.GetProportions(mintedCoin, mintParams.DistributionProportions.DeveloperRewards) - suite.Require().NoError(err) - suite.Require().Equal(devRewardsModuleAfter.Add(expectedDevRewardsCoin), devRewardsModuleOrigin, expectedRewards.String()) - } + defaultGenesisEpochProvisionsDec, err := sdk.NewDecFromStr(defaultGenesisEpochProvisions) - // correct rewards - for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { - checkDistribution(height) - } + defaultMainnetThirdenedProvisionsDec, err := sdk.NewDecFromStr(defaultMainnetThirdenedProvisions) + suite.Require().NoError(err) - app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) - app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) + testcases := map[string]struct { + // Args. + hookArgEpochNum int64 + + // Presets. + preExistingEpochNum int64 + mintDenom string + epochIdentifier string + genesisEpochProvisions sdk.Dec + reductionPeriodInEpochs int64 + reductionFactor sdk.Dec + distributionProportions types.DistributionProportions + weightedAddresses []types.WeightedAddress + mintStartEpoch int64 + + // Expected results. + expectedLastReductionEpochNum int64 + expectedDistribution sdk.Dec + expectedPanic bool + }{ + "before start epoch - no distributions": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch - 1, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: sdk.ZeroDec(), + }, + "at start epoch - distributes": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: defaultGenesisEpochProvisionsDec, + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch, + }, + "after start epoch - distributes": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch + 5, + + preExistingEpochNum: defaultMintingRewardsDistributionStartEpoch, + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: defaultGenesisEpochProvisionsDec, + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch, + }, + "before reduction epoch - distributes, no reduction": { + hookArgEpochNum: defaultReductionPeriodInEpochs, + + preExistingEpochNum: defaultMintingRewardsDistributionStartEpoch, + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: defaultGenesisEpochProvisionsDec, + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch, + }, + "at reduction epoch - distributes, reduction occurs": { + preExistingEpochNum: defaultMintingRewardsDistributionStartEpoch, + + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch + defaultReductionPeriodInEpochs, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: defaultMainnetThirdenedProvisionsDec, + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch + defaultReductionPeriodInEpochs, + }, + "after reduction epoch - distributes, with reduced amounts": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch + defaultReductionPeriodInEpochs, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: defaultMainnetThirdenedProvisionsDec, + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch + defaultReductionPeriodInEpochs, + }, + "start epoch == reduction epoch = curEpoch": { + hookArgEpochNum: defaultReductionPeriodInEpochs, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultReductionPeriodInEpochs, + + expectedDistribution: defaultMainnetThirdenedProvisionsDec, + expectedLastReductionEpochNum: defaultReductionPeriodInEpochs, + }, + "start epoch > reduction epoch": { + hookArgEpochNum: defaultReductionPeriodInEpochs, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultReductionPeriodInEpochs + 1, + + expectedDistribution: sdk.ZeroDec(), + }, + // N.B.: This test case would not work since it would require changing default genesis denom. + // Leaving it to potentially revisit in the future. + // "custom mint denom, at start epoch": {}, + "custom epochIdentifier, at start epoch": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: "week", + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: defaultGenesisEpochProvisionsDec, + }, + "custom genesisEpochProvisions, at start epoch": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: sdk.NewDec(1_000_000_000), + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: defaultGenesisEpochProvisionsDec, + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch, + }, + "custom reduction factor, reduction epoch": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch + defaultReductionPeriodInEpochs, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: sdk.NewDec(43).Quo(sdk.NewDec(55)), + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: defaultGenesisEpochProvisionsDec.Mul(sdk.NewDec(43)).Quo(sdk.NewDec(55)), + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch + defaultReductionPeriodInEpochs, + }, + "custom distribution proportions, at start epoch": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: types.DistributionProportions{ + Staking: sdk.NewDecWithPrec(11, 2), + PoolIncentives: sdk.NewDecWithPrec(22, 2), + DeveloperRewards: sdk.NewDecWithPrec(33, 2), + CommunityPool: sdk.NewDecWithPrec(34, 2), + }, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, - lastReductionPeriod = app.MintKeeper.GetLastReductionEpochNum(ctx) - suite.Require().Equal(lastReductionPeriod, app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs) + expectedDistribution: defaultGenesisEpochProvisionsDec, + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch, + }, + "custom weighted addresses, at start epoch": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch + 5, + + preExistingEpochNum: defaultMintingRewardsDistributionStartEpoch, + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: []types.WeightedAddress{ + { + Address: testAddressOne.String(), + Weight: sdk.NewDecWithPrec(11, 2), + }, + { + Address: testAddressTwo.String(), + Weight: sdk.NewDecWithPrec(22, 2), + }, + { + Address: testAddressThree.String(), + Weight: sdk.NewDecWithPrec(33, 2), + }, + { + Address: testAddressFour.String(), + Weight: sdk.NewDecWithPrec(34, 2), + }, + }, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, - for ; height < lastReductionPeriod+app.MintKeeper.GetParams(ctx).ReductionPeriodInEpochs; height++ { - checkDistribution(height) + expectedDistribution: defaultGenesisEpochProvisionsDec, + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch, + }, + "failed to hook due to developer vesting module account not having enough balance - panic": { + hookArgEpochNum: defaultMintingRewardsDistributionStartEpoch, + + mintDenom: sdk.DefaultBondDenom, + genesisEpochProvisions: defaultGenesisEpochProvisionsDec, + epochIdentifier: defaultEpochIdentifier, + reductionPeriodInEpochs: defaultReductionPeriodInEpochs, + reductionFactor: defaultReductionFactor, + distributionProportions: defaultDistributionProportions, + weightedAddresses: testWeightedAddresses, + mintStartEpoch: defaultMintingRewardsDistributionStartEpoch, + + expectedDistribution: defaultGenesisEpochProvisionsDec, + expectedLastReductionEpochNum: defaultMintingRewardsDistributionStartEpoch, + expectedPanic: true, + }, } -} - -func (suite *KeeperTestSuite) TestEndOfEpochNoDistributionWhenIsNotYetStartTime() { - app := suite.App - ctx := suite.Ctx - - mintParams := app.MintKeeper.GetParams(ctx) - mintParams.MintingRewardsDistributionStartEpoch = 4 - app.MintKeeper.SetParams(ctx, mintParams) - - header := tmproto.Header{Height: app.LastBlockHeight() + 1} - app.BeginBlock(abci.RequestBeginBlock{Header: header}) - params := app.IncentivesKeeper.GetParams(ctx) - futureCtx := ctx.WithBlockTime(time.Now().Add(time.Minute)) - - height := int64(1) - // Run through epochs 0 through mintParams.MintingRewardsDistributionStartEpoch - 1 - // ensure no rewards sent out - for ; height < mintParams.MintingRewardsDistributionStartEpoch; height++ { - feePoolOrigin := app.DistrKeeper.GetFeePool(ctx) - app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) - app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - - // check community pool balance not increase - feePoolNew := app.DistrKeeper.GetFeePool(ctx) - suite.Require().Equal(feePoolOrigin.CommunityPool, feePoolNew.CommunityPool, "height = %v", height) + for name, tc := range testcases { + suite.Run(name, func() { + mintParams := types.Params{ + MintDenom: tc.mintDenom, + GenesisEpochProvisions: tc.genesisEpochProvisions, + EpochIdentifier: tc.epochIdentifier, + ReductionPeriodInEpochs: tc.reductionPeriodInEpochs, + ReductionFactor: tc.reductionFactor, + DistributionProportions: tc.distributionProportions, + WeightedDeveloperRewardsReceivers: tc.weightedAddresses, + MintingRewardsDistributionStartEpoch: tc.mintStartEpoch, + } + + app := osmoapp.Setup(false) + ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + + mintKeeper := app.MintKeeper + distrKeeper := app.DistrKeeper + accountKeeper := app.AccountKeeper + bankKeeper := app.BankKeeper + + // Pre-set parameters and minter. + mintKeeper.SetParams(ctx, mintParams) + mintKeeper.SetLastReductionEpochNum(ctx, tc.preExistingEpochNum) + mintKeeper.SetMinter(ctx, types.Minter{ + EpochProvisions: defaultGenesisEpochProvisionsDec, + }) + + expectedDevRewards := tc.expectedDistribution.Mul(mintParams.DistributionProportions.DeveloperRewards) + + developerAccountBalanceBeforeHook := app.BankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), sdk.DefaultBondDenom) + + if tc.expectedPanic { + // If panic is expected, burn developer module account balance so that it causes an error that leads to a + // panic in the hook. + distrKeeper.FundCommunityPool(ctx, sdk.NewCoins(developerAccountBalanceBeforeHook), accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName)) + } + + osmoutils.ConditionalPanic(suite.T(), tc.expectedPanic, func() { + // System under test. + mintKeeper.AfterEpochEnd(ctx, defaultEpochIdentifier, tc.hookArgEpochNum) + }) + + // Validate developer account balance. + developerAccountBalanceAfterHook := bankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), sdk.DefaultBondDenom) + osmoutils.DecApproxEq(suite.T(), developerAccountBalanceBeforeHook.Amount.Sub(expectedDevRewards.TruncateInt()).ToDec(), developerAccountBalanceAfterHook.Amount.ToDec(), maxArithmeticTolerance) + + // Validate supply. + expectedSupply = expectedSupply.Add(tc.expectedDistribution).Sub(expectedDevRewards) + osmoutils.DecApproxEq(suite.T(), expectedSupply, developerAccountBalanceAfterHook.Amount.ToDec(), maxArithmeticTolerance) + + // Validate supply with offset. + expectedSupplyWithOffset = expectedSupply.Sub(developerAccountBalanceAfterHook.Amount.ToDec()) + osmoutils.DecApproxEq(suite.T(), expectedSupplyWithOffset, app.BankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount.ToDec(), maxArithmeticTolerance) + + // Validate epoch provisions. + suite.Require().Equal(tc.expectedLastReductionEpochNum, mintKeeper.GetLastReductionEpochNum(ctx)) + + if !tc.expectedDistribution.IsZero() { + // Validate distribution. + osmoutils.DecApproxEq(suite.T(), tc.expectedDistribution, mintKeeper.GetMinter(ctx).EpochProvisions, sdk.NewDecWithPrec(1, 18)) + } + }) } - // Run through epochs mintParams.MintingRewardsDistributionStartEpoch - // ensure tokens distributed - app.EpochsKeeper.BeforeEpochStart(futureCtx, params.DistrEpochIdentifier, height) - app.EpochsKeeper.AfterEpochEnd(futureCtx, params.DistrEpochIdentifier, height) - suite.Require().NotEqual(sdk.DecCoins{}, app.DistrKeeper.GetFeePool(ctx).CommunityPool, - "Tokens to community pool at start distribution epoch") - - // reduction period should be set to mintParams.MintingRewardsDistributionStartEpoch - lastReductionPeriod := app.MintKeeper.GetLastReductionEpochNum(ctx) - suite.Require().Equal(lastReductionPeriod, mintParams.MintingRewardsDistributionStartEpoch) } // TODO: Remove after rounding errors are addressed and resolved. @@ -201,38 +399,20 @@ func (suite *KeeperTestSuite) TestEndOfEpochNoDistributionWhenIsNotYetStartTime( // // Ref: https://github.com/osmosis-labs/osmosis/issues/1917 func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParameters() { - // Most values in this test are taken from mainnet genesis to mimic real-world behavior: - // https://github.com/osmosis-labs/networks/raw/main/osmosis-1/genesis.json - const ( - reductionPeriodInEpochs = 365 - mintingRewardsDistributionStartEpoch int64 = 1 - thirdeningEpochNum int64 = reductionPeriodInEpochs + mintingRewardsDistributionStartEpoch - - // different from mainnet since the difference is insignificant for testing purposes. - mintDenom = "stake" - genesisEpochProvisions = "821917808219.178082191780821917" - epochIdentifier = "day" - - // actual value taken from mainnet for sanity checking calculations. - mainnetThirdenedProvisions = "547945205479.452055068493150684" - - developerAccountBalance = 225_000_000_000_000 - ) - - reductionFactor := sdk.NewDec(2).Quo(sdk.NewDec(3)) - app := osmoapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + mintKeeper := app.MintKeeper + accountKeeper := app.AccountKeeper - genesisEpochProvisionsDec, err := sdk.NewDecFromStr(genesisEpochProvisions) + genesisEpochProvisionsDec, err := sdk.NewDecFromStr(defaultGenesisEpochProvisions) suite.Require().NoError(err) mintParams := types.Params{ - MintDenom: mintDenom, + MintDenom: sdk.DefaultBondDenom, GenesisEpochProvisions: genesisEpochProvisionsDec, - EpochIdentifier: epochIdentifier, - ReductionPeriodInEpochs: reductionPeriodInEpochs, - ReductionFactor: reductionFactor, + EpochIdentifier: defaultEpochIdentifier, + ReductionPeriodInEpochs: defaultReductionPeriodInEpochs, + ReductionFactor: defaultReductionFactor, DistributionProportions: types.DistributionProportions{ Staking: sdk.NewDecWithPrec(25, 2), PoolIncentives: sdk.NewDecWithPrec(45, 2), @@ -301,42 +481,37 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete Weight: sdk.NewDecWithPrec(8, 1).Quo(sdk.NewDec(1000)), // 0.0008 }, }, - MintingRewardsDistributionStartEpoch: mintingRewardsDistributionStartEpoch, + MintingRewardsDistributionStartEpoch: defaultMintingRewardsDistributionStartEpoch, } - sumOfWeights := sdk.ZeroDec() - // As a sanity check, ensure developer reward receivers add up to 1. - for _, w := range mintParams.WeightedDeveloperRewardsReceivers { - sumOfWeights = sumOfWeights.Add(w.Weight) - } - suite.Require().Equal(sdk.OneDec(), sumOfWeights) + suite.assertAddressWeightsAddUpToOne(mintParams.WeightedDeveloperRewardsReceivers) // Test setup parameters are not identical with mainnet. // Therfore, we set them here to the desired mainnet values. - app.MintKeeper.SetParams(ctx, mintParams) - app.MintKeeper.SetLastReductionEpochNum(ctx, 0) - app.MintKeeper.SetMinter(ctx, types.Minter{ + mintKeeper.SetParams(ctx, mintParams) + mintKeeper.SetLastReductionEpochNum(ctx, 0) + mintKeeper.SetMinter(ctx, types.Minter{ EpochProvisions: genesisEpochProvisionsDec, }) expectedSupplyWithOffset := sdk.NewDec(0) - expectedSupply := sdk.NewDec(developerAccountBalance) + expectedSupply := sdk.NewDec(keeper.DeveloperVestingAmount) - supplyWithOffset := app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom) + supplyWithOffset := app.BankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom) suite.Require().Equal(expectedSupplyWithOffset.TruncateInt64(), supplyWithOffset.Amount.Int64()) - supply := app.BankKeeper.GetSupply(ctx, mintDenom) + supply := app.BankKeeper.GetSupply(ctx, sdk.DefaultBondDenom) suite.Require().Equal(expectedSupply.TruncateInt64(), supply.Amount.Int64()) devRewardsDelta := sdk.ZeroDec() - epochProvisionsDelta := genesisEpochProvisionsDec.Sub(genesisEpochProvisionsDec.TruncateInt().ToDec()).Mul(sdk.NewDec(reductionPeriodInEpochs)) + epochProvisionsDelta := genesisEpochProvisionsDec.Sub(genesisEpochProvisionsDec.TruncateInt().ToDec()).Mul(sdk.NewDec(defaultReductionPeriodInEpochs)) // Actual test for running AfterEpochEnd hook thirdeningEpoch times. - for i := int64(1); i <= reductionPeriodInEpochs; i++ { - developerAccountBalanceBeforeHook := app.BankKeeper.GetBalance(ctx, app.AccountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), mintDenom) + for i := int64(1); i <= defaultReductionPeriodInEpochs; i++ { + developerAccountBalanceBeforeHook := app.BankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), sdk.DefaultBondDenom) // System undert test. - app.MintKeeper.AfterEpochEnd(ctx, epochIdentifier, i) + mintKeeper.AfterEpochEnd(ctx, defaultEpochIdentifier, i) // System truncates EpochProvisions because bank takes an Int. // This causes rounding errors. Let's refer to this source as #1. @@ -353,7 +528,7 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete devRewards := truncatedEpochProvisions.Mul(mintParams.DistributionProportions.DeveloperRewards).TruncateInt().ToDec() // We aim to exclude developer account balance from the supply with offset calculation. - developerAccountBalance := app.BankKeeper.GetBalance(ctx, app.AccountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), mintDenom) + developerAccountBalance := app.BankKeeper.GetBalance(ctx, accountKeeper.GetModuleAddress(types.DeveloperVestingModuleAcctName), sdk.DefaultBondDenom) // Make sure developer account balance has decreased by devRewards. // This check is now failing because of rounding errors. @@ -370,14 +545,14 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete } expectedSupply = expectedSupply.Add(truncatedEpochProvisions).Sub(devRewards) - suite.Require().Equal(expectedSupply.RoundInt(), app.BankKeeper.GetSupply(ctx, mintDenom).Amount) + suite.Require().Equal(expectedSupply.RoundInt(), app.BankKeeper.GetSupply(ctx, sdk.DefaultBondDenom).Amount) expectedSupplyWithOffset = expectedSupply.Sub(developerAccountBalance.Amount.ToDec()) - suite.Require().Equal(expectedSupplyWithOffset.RoundInt(), app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount) + suite.Require().Equal(expectedSupplyWithOffset.RoundInt(), app.BankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount) // Validate that the epoch provisions have not been reduced. - suite.Require().Equal(mintingRewardsDistributionStartEpoch, app.MintKeeper.GetLastReductionEpochNum(ctx)) - suite.Require().Equal(genesisEpochProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions.String()) + suite.Require().Equal(defaultMintingRewardsDistributionStartEpoch, mintKeeper.GetLastReductionEpochNum(ctx)) + suite.Require().Equal(defaultGenesisEpochProvisions, mintKeeper.GetMinter(ctx).EpochProvisions.String()) } // Validate total supply. @@ -386,23 +561,32 @@ func (suite *KeeperTestSuite) TestAfterEpochEnd_FirstYearThirdening_RealParamete // Here, we add the deltas to the actual supply and compare against expected. // // expectedTotalProvisionedSupply = 365 * 821917808219.178082191780821917 = 299_999_999_999_999.999999999999999705 - expectedTotalProvisionedSupply := sdk.NewDec(reductionPeriodInEpochs).Mul(genesisEpochProvisionsDec) + expectedTotalProvisionedSupply := sdk.NewDec(defaultReductionPeriodInEpochs).Mul(genesisEpochProvisionsDec) // actualTotalProvisionedSupply = 299_999_999_997_380 (off by 2619.999999999999999705) // devRewardsDelta = 2555 (hard to estimate but the source is from truncating dev rewards ) // epochProvisionsDelta = 0.178082191780821917 * 365 = 64.999999999999999705 - actualTotalProvisionedSupply := app.BankKeeper.GetSupplyWithOffset(ctx, mintDenom).Amount.ToDec() + actualTotalProvisionedSupply := app.BankKeeper.GetSupplyWithOffset(ctx, sdk.DefaultBondDenom).Amount.ToDec() // 299_999_999_999_999.999999999999999705 == 299_999_999_997_380 + 2555 + 64.999999999999999705 suite.Require().Equal(expectedTotalProvisionedSupply, actualTotalProvisionedSupply.Add(devRewardsDelta).Add(epochProvisionsDelta)) // This end of epoch should trigger thirdening. It will utilize the updated // (reduced) provisions. - app.MintKeeper.AfterEpochEnd(ctx, epochIdentifier, thirdeningEpochNum) + mintKeeper.AfterEpochEnd(ctx, defaultEpochIdentifier, defaultThirdeningEpochNum) - suite.Require().Equal(thirdeningEpochNum, app.MintKeeper.GetLastReductionEpochNum(ctx)) + suite.Require().Equal(defaultThirdeningEpochNum, mintKeeper.GetLastReductionEpochNum(ctx)) expectedThirdenedProvisions := mintParams.ReductionFactor.Mul(genesisEpochProvisionsDec) // Sanity check with the actual value on mainnet. - suite.Require().Equal(mainnetThirdenedProvisions, expectedThirdenedProvisions.String()) - suite.Require().Equal(expectedThirdenedProvisions, app.MintKeeper.GetMinter(ctx).EpochProvisions) + suite.Require().Equal(defaultMainnetThirdenedProvisions, expectedThirdenedProvisions.String()) + suite.Require().Equal(expectedThirdenedProvisions, mintKeeper.GetMinter(ctx).EpochProvisions) +} + +func (suite KeeperTestSuite) assertAddressWeightsAddUpToOne(receivers []types.WeightedAddress) { + sumOfWeights := sdk.ZeroDec() + // As a sanity check, ensure developer reward receivers add up to 1. + for _, w := range receivers { + sumOfWeights = sumOfWeights.Add(w.Weight) + } + suite.Require().Equal(sdk.OneDec(), sumOfWeights) } From 8cac090607989be4434a25cf73ad9007adb4389b Mon Sep 17 00:00:00 2001 From: alpo <62043214+AlpinYukseloglu@users.noreply.github.com> Date: Tue, 2 Aug 2022 10:31:18 -0700 Subject: [PATCH 141/376] gamm keeper delete obsolete files (#2160) * remove vestigial test files * move params into keeper.go * move stableswap scaling factor * change pool number to pool id where applicable * further pool number changes * make proto level pool number changes * add changelog entry * remove completed TODO comment * undo proto change Co-authored-by: Dev Ojha --- CHANGELOG.md | 1 + go.mod | 2 +- proto/osmosis/gamm/v1beta1/genesis.proto | 1 + x/gamm/keeper/genesis.go | 6 +- x/gamm/keeper/genesis_test | 6 +- x/gamm/keeper/grpc_query.go | 2 +- x/gamm/keeper/grpc_query_internal_test.go | 15 ---- x/gamm/keeper/keeper.go | 11 +++ x/gamm/keeper/marshal_bench_test.go | 85 ----------------------- x/gamm/keeper/params.go | 18 ----- x/gamm/keeper/pool.go | 52 +++----------- x/gamm/keeper/pool_service.go | 2 +- x/gamm/pool-models/balancer/pool_test.go | 10 +-- x/gamm/pool-models/stableswap/pool.go | 17 +++++ x/gamm/simulation/sim_msgs.go | 8 +-- x/gamm/types/genesis.pb.go | 7 +- x/gamm/types/key.go | 4 +- 17 files changed, 64 insertions(+), 183 deletions(-) delete mode 100644 x/gamm/keeper/grpc_query_internal_test.go delete mode 100644 x/gamm/keeper/marshal_bench_test.go delete mode 100644 x/gamm/keeper/params.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 83e697b1e1d..57488f765f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 #### Golang API breaks +* [#2160](https://github.com/osmosis-labs/osmosis/pull/2160) Clean up GAMM keeper (move `x/gamm/keeper/params.go` contents into `x/gamm/keeper/keeper.go`, replace all uses of `PoolNumber` with `PoolId`, move `SetStableSwapScalingFactors` to stableswap package, and delete marshal_bench_test.go and grpc_query_internal_test.go) * [#1987](https://github.com/osmosis-labs/osmosis/pull/1987) Remove `GammKeeper.GetNextPoolNumberAndIncrement` in favor of the non-mutative `GammKeeper.GetNextPoolNumber`. * [#1937](https://github.com/osmosis-labs/osmosis/pull/1937) Change `lockupKeeper.ExtendLock` to take in lockID instead of the direct lock struct. * [#1893](https://github.com/osmosis-labs/osmosis/pull/1893) Change `EpochsKeeper.SetEpochInfo` to `AddEpochInfo`, which has more safety checks with it. (Makes it suitable to be called within upgrades) diff --git a/go.mod b/go.mod index 003f5345f42..54e98017cb9 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.18 require ( github.com/CosmWasm/wasmd v0.24.0 github.com/cosmos/cosmos-proto v1.0.0-alpha7 - github.com/cosmos/cosmos-sdk v0.45.6 + github.com/cosmos/cosmos-sdk v0.46.0 github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/iavl v0.17.3 github.com/cosmos/ibc-go/v3 v3.0.0 diff --git a/proto/osmosis/gamm/v1beta1/genesis.proto b/proto/osmosis/gamm/v1beta1/genesis.proto index bece17a3d6e..043f23fef5e 100644 --- a/proto/osmosis/gamm/v1beta1/genesis.proto +++ b/proto/osmosis/gamm/v1beta1/genesis.proto @@ -21,6 +21,7 @@ option go_package = "github.com/osmosis-labs/osmosis/v10/x/gamm/types"; message GenesisState { repeated google.protobuf.Any pools = 1 [ (cosmos_proto.accepts_interface) = "PoolI" ]; + // will be renamed to next_pool_id in an upcoming version uint64 next_pool_number = 2; Params params = 3 [ (gogoproto.nullable) = false ]; } diff --git a/x/gamm/keeper/genesis.go b/x/gamm/keeper/genesis.go index 590581408e7..63546e11b2c 100644 --- a/x/gamm/keeper/genesis.go +++ b/x/gamm/keeper/genesis.go @@ -8,10 +8,10 @@ import ( ) // InitGenesis initializes the x/gamm module's state from a provided genesis -// state, which includes the current live pools, global pool parameters (e.g. pool creation fee), next pool number etc. +// state, which includes the current live pools, global pool parameters (e.g. pool creation fee), next pool id etc. func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState, unpacker codectypes.AnyUnpacker) { k.setParams(ctx, genState.Params) - k.setNextPoolNumber(ctx, genState.NextPoolNumber) + k.setNextPoolId(ctx, genState.NextPoolNumber) // Sums up the liquidity in all genesis state pools to find the total liquidity across all pools. // Also adds each genesis state pool to the x/gamm module's state @@ -51,7 +51,7 @@ func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { poolAnys = append(poolAnys, any) } return &types.GenesisState{ - NextPoolNumber: k.GetNextPoolNumber(ctx), + NextPoolNumber: k.GetNextPoolId(ctx), Pools: poolAnys, Params: k.GetParams(ctx), } diff --git a/x/gamm/keeper/genesis_test b/x/gamm/keeper/genesis_test index f522de32fa0..7e576e9fb40 100644 --- a/x/gamm/keeper/genesis_test +++ b/x/gamm/keeper/genesis_test @@ -41,13 +41,13 @@ func TestGammInitGenesis(t *testing.T) { gamm.InitGenesis(ctx, *app.GAMMKeeper, types.GenesisState{ Pools: []*codectypes.Any{any}, - NextPoolNumber: 2, + NextPoolId: 2, Params: types.Params{ PoolCreationFee: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000_000_000)}, }, }, app.AppCodec()) - require.Equal(t, app.GAMMKeeper.GetNextPoolNumberAndIncrement(ctx), uint64(2)) + require.Equal(t, app.GAMMKeeper.GetNextPoolIdAndIncrement(ctx), uint64(2)) poolStored, err := app.GAMMKeeper.GetPoolAndPoke(ctx, 1) require.NoError(t, err) require.Equal(t, balancerPool.GetId(), poolStored.GetId()) @@ -105,7 +105,7 @@ func TestGammExportGenesis(t *testing.T) { require.NoError(t, err) genesis := gamm.ExportGenesis(ctx, *app.GAMMKeeper) - require.Equal(t, genesis.NextPoolNumber, uint64(3)) + require.Equal(t, genesis.NextPoolId, uint64(3)) require.Len(t, genesis.Pools, 2) } diff --git a/x/gamm/keeper/grpc_query.go b/x/gamm/keeper/grpc_query.go index 52527ec9bda..befd81808ca 100644 --- a/x/gamm/keeper/grpc_query.go +++ b/x/gamm/keeper/grpc_query.go @@ -123,7 +123,7 @@ func (q Querier) NumPools(ctx context.Context, _ *types.QueryNumPoolsRequest) (* sdkCtx := sdk.UnwrapSDKContext(ctx) return &types.QueryNumPoolsResponse{ - NumPools: q.Keeper.GetNextPoolNumber(sdkCtx) - 1, + NumPools: q.Keeper.GetNextPoolId(sdkCtx) - 1, }, nil } diff --git a/x/gamm/keeper/grpc_query_internal_test.go b/x/gamm/keeper/grpc_query_internal_test.go deleted file mode 100644 index 03297192649..00000000000 --- a/x/gamm/keeper/grpc_query_internal_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestSdkIntMaxValue(t *testing.T) { - require.Panics(t, func() { - sdkIntMaxValue.Add(sdk.NewInt(1)) - }) -} diff --git a/x/gamm/keeper/keeper.go b/x/gamm/keeper/keeper.go index f88f3903896..06575aa1707 100644 --- a/x/gamm/keeper/keeper.go +++ b/x/gamm/keeper/keeper.go @@ -70,3 +70,14 @@ func (k *Keeper) SetHooks(gh types.GammHooks) *Keeper { return k } + +// GetParams returns the total set params. +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { + k.paramSpace.GetParamSet(ctx, ¶ms) + return params +} + +// SetParams sets the total set of params. +func (k Keeper) setParams(ctx sdk.Context, params types.Params) { + k.paramSpace.SetParamSet(ctx, ¶ms) +} diff --git a/x/gamm/keeper/marshal_bench_test.go b/x/gamm/keeper/marshal_bench_test.go deleted file mode 100644 index 132c6ddd550..00000000000 --- a/x/gamm/keeper/marshal_bench_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package keeper_test - -import ( - "math/rand" - "testing" - "time" - - "github.com/osmosis-labs/osmosis/v10/app" - "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" - balancertypes "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" - gammtypes "github.com/osmosis-labs/osmosis/v10/x/gamm/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" -) - -func genPoolAssets(r *rand.Rand) []balancertypes.PoolAsset { - denoms := []string{"IBC/0123456789ABCDEF012346789ABCDEF", "IBC/denom56789ABCDEF012346789ABCDEF"} - assets := []balancertypes.PoolAsset{} - for _, denom := range denoms { - amt, _ := simtypes.RandPositiveInt(r, sdk.NewIntWithDecimal(1, 40)) - reserveAmt := sdk.NewCoin(denom, amt) - weight := sdk.NewInt(r.Int63n(9) + 1) - assets = append(assets, balancertypes.PoolAsset{Token: reserveAmt, Weight: weight}) - } - - return assets -} - -func genPoolParams(r *rand.Rand) balancer.PoolParams { - swapFeeInt := int64(r.Intn(1e5)) - swapFee := sdk.NewDecWithPrec(swapFeeInt, 6) - - exitFeeInt := int64(r.Intn(1e5)) - exitFee := sdk.NewDecWithPrec(exitFeeInt, 6) - - // TODO: Randomly generate LBP params - return balancer.PoolParams{ - SwapFee: swapFee, - ExitFee: exitFee, - SmoothWeightChangeParams: nil, - } -} - -func setupPools(maxNumPoolsToGen int) []gammtypes.PoolI { - r := rand.New(rand.NewSource(10)) - // setup N pools - pools := make([]gammtypes.PoolI, 0, maxNumPoolsToGen) - for i := 0; i < maxNumPoolsToGen; i++ { - assets := genPoolAssets(r) - params := genPoolParams(r) - pool, _ := balancer.NewBalancerPool(uint64(i), params, assets, "FutureGovernorString", time.Now()) - pools = append(pools, &pool) - } - return pools -} - -func BenchmarkGammPoolSerialization(b *testing.B) { - app := app.Setup(false) - maxNumPoolsToGen := 5000 - pools := setupPools(maxNumPoolsToGen) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - j := i % maxNumPoolsToGen - app.GAMMKeeper.MarshalPool(pools[j]) - } -} - -func BenchmarkGammPoolDeserialization(b *testing.B) { - app := app.Setup(false) - maxNumPoolsToGen := 5000 - pools := setupPools(maxNumPoolsToGen) - marshals := make([][]byte, 0, maxNumPoolsToGen) - for i := 0; i < maxNumPoolsToGen; i++ { - bz, _ := app.GAMMKeeper.MarshalPool(pools[i]) - marshals = append(marshals, bz) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - j := i % maxNumPoolsToGen - app.GAMMKeeper.UnmarshalPool(marshals[j]) - } -} diff --git a/x/gamm/keeper/params.go b/x/gamm/keeper/params.go deleted file mode 100644 index 50ff384dc7e..00000000000 --- a/x/gamm/keeper/params.go +++ /dev/null @@ -1,18 +0,0 @@ -package keeper - -import ( - "github.com/osmosis-labs/osmosis/v10/x/gamm/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// GetParams returns the total set params. -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramSpace.GetParamSet(ctx, ¶ms) - return params -} - -// SetParams sets the total set of params. -func (k Keeper) setParams(ctx sdk.Context, params types.Params) { - k.paramSpace.SetParamSet(ctx, ¶ms) -} diff --git a/x/gamm/keeper/pool.go b/x/gamm/keeper/pool.go index 919b0fc599f..7c6c0b12611 100644 --- a/x/gamm/keeper/pool.go +++ b/x/gamm/keeper/pool.go @@ -10,7 +10,6 @@ import ( "github.com/osmosis-labs/osmosis/v10/osmoutils" "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/balancer" - "github.com/osmosis-labs/osmosis/v10/x/gamm/pool-models/stableswap" "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) @@ -210,20 +209,19 @@ func (k Keeper) GetPoolDenoms(ctx sdk.Context, poolId uint64) ([]string, error) return denoms, err } -// setNextPoolNumber sets next pool number. -func (k Keeper) setNextPoolNumber(ctx sdk.Context, poolNumber uint64) { +// setNextPoolId sets next pool Id. +func (k Keeper) setNextPoolId(ctx sdk.Context, poolId uint64) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshal(&gogotypes.UInt64Value{Value: poolNumber}) - store.Set(types.KeyNextGlobalPoolNumber, bz) + bz := k.cdc.MustMarshal(&gogotypes.UInt64Value{Value: poolId}) + store.Set(types.KeyNextGlobalPoolId, bz) } -// GetNextPoolNumber returns the next pool number. -// TODO: Rename NextPoolNumber to NextPoolId -func (k Keeper) GetNextPoolNumber(ctx sdk.Context) uint64 { +// GetNextPoolId returns the next pool Id. +func (k Keeper) GetNextPoolId(ctx sdk.Context) uint64 { var nextPoolId uint64 store := ctx.KVStore(k.storeKey) - bz := store.Get(types.KeyNextGlobalPoolNumber) + bz := store.Get(types.KeyNextGlobalPoolId) if bz == nil { panic(fmt.Errorf("pool has not been initialized -- Should have been done in InitGenesis")) } else { @@ -239,37 +237,9 @@ func (k Keeper) GetNextPoolNumber(ctx sdk.Context) uint64 { return nextPoolId } -// getNextPoolNumberAndIncrement returns the next pool number, and increments the corresponding state entry. -func (k Keeper) getNextPoolNumberAndIncrement(ctx sdk.Context) uint64 { - nextPoolId := k.GetNextPoolNumber(ctx) - k.setNextPoolNumber(ctx, nextPoolId+1) +// getNextPoolIdAndIncrement returns the next pool Id, and increments the corresponding state entry. +func (k Keeper) getNextPoolIdAndIncrement(ctx sdk.Context) uint64 { + nextPoolId := k.GetNextPoolId(ctx) + k.setNextPoolId(ctx, nextPoolId+1) return nextPoolId } - -// set ScalingFactors in stable stableswap pools -func (k *Keeper) SetStableSwapScalingFactors(ctx sdk.Context, scalingFactors []uint64, poolId uint64, scalingFactorGovernor string) error { - poolI, err := k.GetPoolAndPoke(ctx, poolId) - if err != nil { - return err - } - - stableswapPool, ok := poolI.(*stableswap.Pool) - if !ok { - return types.ErrNotStableSwapPool - } - - if scalingFactorGovernor != stableswapPool.ScalingFactorGovernor { - return types.ErrNotScalingFactorGovernor - } - - if len(scalingFactors) != stableswapPool.PoolLiquidity.Len() { - return types.ErrInvalidStableswapScalingFactors - } - - stableswapPool.ScalingFactor = scalingFactors - - if err = k.setPool(ctx, stableswapPool); err != nil { - return err - } - return nil -} diff --git a/x/gamm/keeper/pool_service.go b/x/gamm/keeper/pool_service.go index 904e14e96d4..d0d45ffdb1a 100644 --- a/x/gamm/keeper/pool_service.go +++ b/x/gamm/keeper/pool_service.go @@ -105,7 +105,7 @@ func (k Keeper) CreatePool(ctx sdk.Context, msg types.CreatePoolMsg) (uint64, er return 0, err } - poolId := k.getNextPoolNumberAndIncrement(ctx) + poolId := k.getNextPoolIdAndIncrement(ctx) pool, err := msg.CreatePool(ctx, poolId) if err != nil { return 0, err diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go index cab4a06952f..6c7f48a51c9 100644 --- a/x/gamm/pool-models/balancer/pool_test.go +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -1150,7 +1150,7 @@ func TestBalancerPoolPokeTokenWeights(t *testing.T) { return updatedCases } - for poolNum, tc := range tests { + for poolId, tc := range tests { paramsCopy := tc.params // First we create the initial pool assets we will use initialPoolAssets := make([]balancer.PoolAsset, len(paramsCopy.InitialPoolWeights)) @@ -1162,12 +1162,12 @@ func TestBalancerPoolPokeTokenWeights(t *testing.T) { initialPoolAssets[i] = assetCopy } // Initialize the pool - pacc, err := balancer.NewBalancerPool(uint64(poolNum), balancer.PoolParams{ + pacc, err := balancer.NewBalancerPool(uint64(poolId), balancer.PoolParams{ SwapFee: defaultSwapFee, ExitFee: defaultExitFee, SmoothWeightChangeParams: &tc.params, }, initialPoolAssets, defaultFutureGovernor, defaultCurBlockTime) - require.NoError(t, err, "poolNumber %v", poolNum) + require.NoError(t, err, "poolId %v", poolId) // Consistency check that SmoothWeightChangeParams params are set require.NotNil(t, pacc.PoolParams.SmoothWeightChangeParams) @@ -1180,8 +1180,8 @@ func TestBalancerPoolPokeTokenWeights(t *testing.T) { for assetNum, asset := range pacc.GetAllPoolAssets() { require.Equal(t, testCase.expectedWeights[assetNum], asset.Weight, - "Didn't get the expected weights, poolNumber %v, caseNumber %v, assetNumber %v", - poolNum, caseNum, assetNum) + "Didn't get the expected weights, poolId %v, caseNumber %v, assetNumber %v", + poolId, caseNum, assetNum) totalWeight = totalWeight.Add(asset.Weight) } diff --git a/x/gamm/pool-models/stableswap/pool.go b/x/gamm/pool-models/stableswap/pool.go index 82eaba14aa9..3729a22dbf2 100644 --- a/x/gamm/pool-models/stableswap/pool.go +++ b/x/gamm/pool-models/stableswap/pool.go @@ -270,3 +270,20 @@ func (p Pool) CalcExitPoolCoinsFromShares(ctx sdk.Context, exitingShares sdk.Int // no-op for stableswap func (p *Pool) PokePool(blockTime time.Time) {} + +// SetStableSwapScalingFactors sets scaling factors for pool to the given amount +// It should only be able to be successfully called by the pool's ScalingFactorGovernor +// TODO: move commented test for this function from x/gamm/keeper/pool_service_test.go once a pool_test.go file has been created for stableswap +func (p *Pool) SetStableSwapScalingFactors(ctx sdk.Context, scalingFactors []uint64, scalingFactorGovernor string) error { + if scalingFactorGovernor != p.ScalingFactorGovernor { + return types.ErrNotScalingFactorGovernor + } + + if len(scalingFactors) != p.PoolLiquidity.Len() { + return types.ErrInvalidStableswapScalingFactors + } + + p.ScalingFactor = scalingFactors + + return nil +} diff --git a/x/gamm/simulation/sim_msgs.go b/x/gamm/simulation/sim_msgs.go index 9e227cacc6e..21374cd75f3 100644 --- a/x/gamm/simulation/sim_msgs.go +++ b/x/gamm/simulation/sim_msgs.go @@ -15,15 +15,13 @@ import ( "github.com/osmosis-labs/osmosis/v10/x/gamm/types" ) -var ( - PoolCreationFee = sdk.NewInt64Coin("stake", 10_000_000) -) +var PoolCreationFee = sdk.NewInt64Coin("stake", 10_000_000) // RandomJoinPoolMsg pseudo-randomly selects an existing pool ID, attempts to find an account with the // respective underlying token denoms, and attempts to execute a join pool transaction func RandomJoinPoolMsg(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgJoinPool, error) { // get random pool - pool_id := simtypes.RandLTBound(sim, k.GetNextPoolNumber(ctx)) + pool_id := simtypes.RandLTBound(sim, k.GetNextPoolId(ctx)) pool, err := k.GetPoolAndPoke(ctx, pool_id) if err != nil { return &types.MsgJoinPool{}, err @@ -99,7 +97,7 @@ func deriveRealMinShareOutAmt(ctx sdk.Context, tokenIn sdk.Coins, pool types.Poo // respective unbonded gamm shares, and attempts to execute an exit pool transaction func RandomExitPoolMsg(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (*types.MsgExitPool, error) { // select a pseudo-random pool ID, max bound by the upcoming pool ID - pool_id := simtypes.RandLTBound(sim, k.GetNextPoolNumber(ctx)) + pool_id := simtypes.RandLTBound(sim, k.GetNextPoolId(ctx)) pool, err := k.GetPoolAndPoke(ctx, pool_id) if err != nil { return &types.MsgExitPool{}, err diff --git a/x/gamm/types/genesis.pb.go b/x/gamm/types/genesis.pb.go index 29f5c0a0f7a..0d9684ecec3 100644 --- a/x/gamm/types/genesis.pb.go +++ b/x/gamm/types/genesis.pb.go @@ -74,9 +74,10 @@ func (m *Params) GetPoolCreationFee() github_com_cosmos_cosmos_sdk_types.Coins { // GenesisState defines the gamm module's genesis state. type GenesisState struct { - Pools []*types1.Any `protobuf:"bytes,1,rep,name=pools,proto3" json:"pools,omitempty"` - NextPoolNumber uint64 `protobuf:"varint,2,opt,name=next_pool_number,json=nextPoolNumber,proto3" json:"next_pool_number,omitempty"` - Params Params `protobuf:"bytes,3,opt,name=params,proto3" json:"params"` + Pools []*types1.Any `protobuf:"bytes,1,rep,name=pools,proto3" json:"pools,omitempty"` + // will be renamed to next_pool_id in an upcoming version + NextPoolNumber uint64 `protobuf:"varint,2,opt,name=next_pool_number,json=nextPoolNumber,proto3" json:"next_pool_number,omitempty"` + Params Params `protobuf:"bytes,3,opt,name=params,proto3" json:"params"` } func (m *GenesisState) Reset() { *m = GenesisState{} } diff --git a/x/gamm/types/key.go b/x/gamm/types/key.go index ce03c67073e..0ec48b515f8 100644 --- a/x/gamm/types/key.go +++ b/x/gamm/types/key.go @@ -19,8 +19,8 @@ const ( ) var ( - // KeyNextGlobalPoolNumber defines key to store the next Pool ID to be used. - KeyNextGlobalPoolNumber = []byte{0x01} + // KeyNextGlobalPoolId defines key to store the next Pool ID to be used. + KeyNextGlobalPoolId = []byte{0x01} // KeyPrefixPools defines prefix to store pools. KeyPrefixPools = []byte{0x02} // KeyTotalLiquidity defines key to store total liquidity. From ef0dc173943a895473f3a53164d9f6e80c089b83 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 2 Aug 2022 17:12:07 -0700 Subject: [PATCH 142/376] fix(ci):import paths ci job token (#2281) --- .github/workflows/import_paths.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/import_paths.yml b/.github/workflows/import_paths.yml index bf6ea8ec420..ffb3013718b 100644 --- a/.github/workflows/import_paths.yml +++ b/.github/workflows/import_paths.yml @@ -60,7 +60,7 @@ jobs: - name: Create Pull Request uses: peter-evans/create-pull-request@v4 with: - token: ${{ secrets.ADD_TO_PROJECT_PAT }} + token: ${{ secrets.COMMIT_TO_BRANCH }} title: "auto: update Go import paths to v${{ inputs.version }}" commit-message: "auto: update Go import paths to v${{ inputs.version }}" body: "**Automated pull request**\n\nUpdating Go import paths to v${{ inputs.version }}" From d0aaca037266adee132ba743e8ea23ee69db370a Mon Sep 17 00:00:00 2001 From: Sishir Giri Date: Tue, 2 Aug 2022 17:19:10 -0700 Subject: [PATCH 143/376] x/incentives: refactor create gauge and add to gauge fees to use txfees denom (#2283) * revert to use dynamic denom * fixed keeper issue * rom comments * nit * adam comments --- CHANGELOG.md | 1 + app/keepers/keepers.go | 27 ++++++------ x/incentives/keeper/gauge.go | 16 ++++--- x/incentives/keeper/gauge_test.go | 33 +++++++------- x/incentives/keeper/keeper.go | 4 +- x/incentives/keeper/msg_server_test.go | 59 +++++++++++++------------- x/incentives/simulation/operations.go | 6 +-- x/incentives/types/expected_keepers.go | 5 +++ 8 files changed, 81 insertions(+), 70 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57488f765f4..1a32735bd12 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 * [#2147](https://github.com/osmosis-labs/osmosis/pull/2147) Set MaxAgeNumBlocks in v11 Upgrade Handler to two weeks. * [#2193](https://github.com/osmosis-labs/osmosis/pull/2193) Add TwapKeeper to the Osmosis app * [#2227](https://github.com/osmosis-labs/osmosis/pull/2227) Enable charging fee in base denom for `CreateGauge` and `AddToGauge`. +* [#2283](https://github.com/osmosis-labs/osmosis/pull/2283) x/incentives: refactor `CreateGauge` and `AddToGauge` fees to use txfees denom #### Golang API breaks diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index 3369228ba26..b88217fde6b 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -260,6 +260,19 @@ func (appKeepers *AppKeepers) InitNormalKeepers( appKeepers.EpochsKeeper = epochskeeper.NewKeeper(appCodec, appKeepers.keys[epochstypes.StoreKey]) + txFeesKeeper := txfeeskeeper.NewKeeper( + appCodec, + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + appKeepers.EpochsKeeper, + appKeepers.keys[txfeestypes.StoreKey], + appKeepers.GAMMKeeper, + appKeepers.GAMMKeeper, + txfeestypes.FeeCollectorName, + txfeestypes.NonNativeFeeCollectorName, + ) + appKeepers.TxFeesKeeper = &txFeesKeeper + appKeepers.IncentivesKeeper = incentiveskeeper.NewKeeper( appCodec, appKeepers.keys[incentivestypes.StoreKey], @@ -268,6 +281,7 @@ func (appKeepers *AppKeepers) InitNormalKeepers( appKeepers.LockupKeeper, appKeepers.EpochsKeeper, appKeepers.DistrKeeper, + appKeepers.TxFeesKeeper, ) appKeepers.SuperfluidKeeper = superfluidkeeper.NewKeeper( @@ -300,19 +314,6 @@ func (appKeepers *AppKeepers) InitNormalKeepers( ) appKeepers.PoolIncentivesKeeper = &poolIncentivesKeeper - txFeesKeeper := txfeeskeeper.NewKeeper( - appCodec, - appKeepers.AccountKeeper, - appKeepers.BankKeeper, - appKeepers.EpochsKeeper, - appKeepers.keys[txfeestypes.StoreKey], - appKeepers.GAMMKeeper, - appKeepers.GAMMKeeper, - txfeestypes.FeeCollectorName, - txfeestypes.NonNativeFeeCollectorName, - ) - appKeepers.TxFeesKeeper = &txFeesKeeper - tokenFactoryKeeper := tokenfactorykeeper.NewKeeper( appCodec, appKeepers.keys[tokenfactorytypes.StoreKey], diff --git a/x/incentives/keeper/gauge.go b/x/incentives/keeper/gauge.go index 8a8638bc243..636597714d2 100644 --- a/x/incentives/keeper/gauge.go +++ b/x/incentives/keeper/gauge.go @@ -11,7 +11,6 @@ import ( "github.com/gogo/protobuf/proto" db "github.com/tendermint/tm-db" - appparams "github.com/osmosis-labs/osmosis/v10/app/params" epochtypes "github.com/osmosis-labs/osmosis/v10/x/epochs/types" "github.com/osmosis-labs/osmosis/v10/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" @@ -287,12 +286,19 @@ func (k Keeper) GetEpochInfo(ctx sdk.Context) epochtypes.EpochInfo { // The fee is sent to the community pool. // Returns nil on success, error otherwise. func (k Keeper) chargeFeeIfSufficientFeeDenomBalance(ctx sdk.Context, address sdk.AccAddress, fee sdk.Int, gaugeCoins sdk.Coins) (err error) { - totalCost := gaugeCoins.AmountOf(appparams.BaseCoinUnit).Add(fee) - accountBalance := k.bk.GetBalance(ctx, address, appparams.BaseCoinUnit).Amount + feeDenom, err := k.tk.GetBaseDenom(ctx) + if err != nil { + return err + } + + totalCost := gaugeCoins.AmountOf(feeDenom).Add(fee) + accountBalance := k.bk.GetBalance(ctx, address, feeDenom).Amount + if accountBalance.LT(totalCost) { - return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "account's balance of %s (%s) is less than the total cost of the message (%s)", appparams.BaseCoinUnit, accountBalance, totalCost) + return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "account's balance of %s (%s) is less than the total cost of the message (%s)", feeDenom, accountBalance, totalCost) } - if err := k.dk.FundCommunityPool(ctx, sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, fee)), address); err != nil { + + if err := k.dk.FundCommunityPool(ctx, sdk.NewCoins(sdk.NewCoin(feeDenom, fee)), address); err != nil { return err } return nil diff --git a/x/incentives/keeper/gauge_test.go b/x/incentives/keeper/gauge_test.go index 2e36c881846..8ea072d5502 100644 --- a/x/incentives/keeper/gauge_test.go +++ b/x/incentives/keeper/gauge_test.go @@ -5,7 +5,6 @@ import ( "github.com/stretchr/testify/suite" - appparams "github.com/osmosis-labs/osmosis/v10/app/params" "github.com/osmosis-labs/osmosis/v10/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" @@ -250,51 +249,51 @@ func (suite *KeeperTestSuite) TestChargeFeeIfSufficientFeeDenomBalance() { expectError bool }{ "fee + base denom gauge coin == acount balance, success": { - accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + accountBalanceToFund: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee)), feeToCharge: baseFee / 2, - gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + gaugeCoins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee/2))), }, "fee + base denom gauge coin < acount balance, success": { - accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + accountBalanceToFund: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee)), feeToCharge: baseFee/2 - 1, - gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + gaugeCoins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee/2))), }, "fee + base denom gauge coin > acount balance, error": { accountBalanceToFund: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee)), feeToCharge: baseFee/2 + 1, - gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + gaugeCoins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee/2))), expectError: true, }, "fee + base denom gauge coin < acount balance, custom values, success": { - accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(11793193112)), + accountBalanceToFund: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(11793193112)), feeToCharge: 55, - gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(328812))), + gaugeCoins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(328812))), }, "account funded with coins other than base denom, error": { accountBalanceToFund: sdk.NewCoin("usdc", sdk.NewInt(baseFee)), feeToCharge: baseFee, - gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + gaugeCoins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee/2))), expectError: true, }, "fee == account balance, no gauge coins, success": { - accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + accountBalanceToFund: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee)), feeToCharge: baseFee, }, "gauge coins == account balance, no fee, success": { - accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), - gaugeCoins: sdk.NewCoins(sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee))), + accountBalanceToFund: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee)), + gaugeCoins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee))), }, "fee == account balance, gauge coins in denom other than base, success": { - accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + accountBalanceToFund: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee)), feeToCharge: baseFee, gaugeCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdk.NewInt(baseFee*2))), }, "fee + gauge coins == account balance, multiple gauge coins, one in denom other than base, success": { - accountBalanceToFund: sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee)), + accountBalanceToFund: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee)), feeToCharge: baseFee / 2, - gaugeCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdk.NewInt(baseFee*2)), sdk.NewCoin(appparams.DefaultBondDenom, sdk.NewInt(baseFee/2))), + gaugeCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdk.NewInt(baseFee*2)), sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseFee/2))), }, } @@ -311,13 +310,13 @@ func (suite *KeeperTestSuite) TestChargeFeeIfSufficientFeeDenomBalance() { // Pre-fund account. suite.FundAcc(testAccount, sdk.NewCoins(tc.accountBalanceToFund)) - oldBalanceAmount := bankKeeper.GetBalance(ctx, testAccount, appparams.DefaultBondDenom).Amount + oldBalanceAmount := bankKeeper.GetBalance(ctx, testAccount, sdk.DefaultBondDenom).Amount // System under test. err := incentivesKeepers.ChargeFeeIfSufficientFeeDenomBalance(ctx, testAccount, sdk.NewInt(tc.feeToCharge), tc.gaugeCoins) // Assertions. - newBalanceAmount := bankKeeper.GetBalance(ctx, testAccount, appparams.DefaultBondDenom).Amount + newBalanceAmount := bankKeeper.GetBalance(ctx, testAccount, sdk.DefaultBondDenom).Amount if tc.expectError { suite.Require().Error(err) diff --git a/x/incentives/keeper/keeper.go b/x/incentives/keeper/keeper.go index d21abad3579..37cbfb3397f 100644 --- a/x/incentives/keeper/keeper.go +++ b/x/incentives/keeper/keeper.go @@ -23,10 +23,11 @@ type Keeper struct { lk types.LockupKeeper ek types.EpochKeeper dk types.DistrKeeper + tk types.TxFeesKeeper } // NewKeeper returns a new instance of the incentive module keeper struct. -func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey, paramSpace paramtypes.Subspace, bk types.BankKeeper, lk types.LockupKeeper, ek types.EpochKeeper, dk types.DistrKeeper) *Keeper { +func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey, paramSpace paramtypes.Subspace, bk types.BankKeeper, lk types.LockupKeeper, ek types.EpochKeeper, dk types.DistrKeeper, txfk types.TxFeesKeeper) *Keeper { if !paramSpace.HasKeyTable() { paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) } @@ -39,6 +40,7 @@ func NewKeeper(cdc codec.Codec, storeKey sdk.StoreKey, paramSpace paramtypes.Sub lk: lk, ek: ek, dk: dk, + tk: txfk, } } diff --git a/x/incentives/keeper/msg_server_test.go b/x/incentives/keeper/msg_server_test.go index 497a5d2d92b..f6c8518a957 100644 --- a/x/incentives/keeper/msg_server_test.go +++ b/x/incentives/keeper/msg_server_test.go @@ -8,7 +8,6 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - appparams "github.com/osmosis-labs/osmosis/v10/app/params" "github.com/osmosis-labs/osmosis/v10/x/incentives/keeper" "github.com/osmosis-labs/osmosis/v10/x/incentives/types" lockuptypes "github.com/osmosis-labs/osmosis/v10/x/lockup/types" @@ -30,36 +29,36 @@ func (suite *KeeperTestSuite) TestCreateGauge_Fee() { }{ { name: "user creates a non-perpetual gauge and fills gauge with all remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(60000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(60000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), }, { name: "user creates a non-perpetual gauge and fills gauge with some remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), }, { name: "user with multiple denoms creates a non-perpetual gauge and fills gauge with some remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), }, { name: "module account creates a perpetual gauge and fills gauge with some remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), isPerpetual: true, isModuleAccount: true, }, { name: "user with multiple denoms creates a perpetual gauge and fills gauge with some remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), isPerpetual: true, }, { name: "user tries to create a non-perpetual gauge but does not have enough funds to pay for the create gauge fee", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(40000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(40000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), expectErr: true, }, { @@ -70,8 +69,8 @@ func (suite *KeeperTestSuite) TestCreateGauge_Fee() { }, { name: "one user tries to create a gauge, has enough funds to pay for the create gauge fee but not enough to fill the gauge", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(60000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(30000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(60000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(30000000))), expectErr: true, }, } @@ -126,7 +125,7 @@ func (suite *KeeperTestSuite) TestCreateGauge_Fee() { if tc.expectErr { suite.Require().Equal(tc.accountBalanceToFund.String(), balanceAmount.String(), "test: %v", tc.name) } else { - fee := sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, types.CreateGaugeFee)) + fee := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, types.CreateGaugeFee)) accountBalance := tc.accountBalanceToFund.Sub(tc.gaugeAddition) finalAccountBalance := accountBalance.Sub(fee) suite.Require().Equal(finalAccountBalance.String(), balanceAmount.String(), "test: %v", tc.name) @@ -147,36 +146,36 @@ func (suite *KeeperTestSuite) TestAddToGauge_Fee() { }{ { name: "user creates a non-perpetual gauge and fills gauge with all remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(35000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(35000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), }, { name: "user creates a non-perpetual gauge and fills gauge with some remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), }, { name: "user with multiple denoms creates a non-perpetual gauge and fills gauge with some remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), }, { name: "module account creates a perpetual gauge and fills gauge with some remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), isPerpetual: true, isModuleAccount: true, }, { name: "user with multiple denoms creates a perpetual gauge and fills gauge with some remaining tokens", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(70000000)), sdk.NewCoin("foo", sdk.NewInt(70000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), isPerpetual: true, }, { name: "user tries to create a non-perpetual gauge but does not have enough funds to pay for the create gauge fee", - accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(20000000))), - gaugeAddition: sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(10000000))), + accountBalanceToFund: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20000000))), + gaugeAddition: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10000000))), expectErr: true, }, { @@ -210,7 +209,7 @@ func (suite *KeeperTestSuite) TestAddToGauge_Fee() { } // System under test. - coins := sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(500000000))) + coins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(500000000))) gaugeID, _, _, _ := suite.SetupNewGauge(true, coins) if tc.nonexistentGauge { gaugeID = incentivesKeeper.GetLastGaugeID(ctx) + 1 @@ -234,7 +233,7 @@ func (suite *KeeperTestSuite) TestAddToGauge_Fee() { if tc.expectErr { suite.Require().Equal(tc.accountBalanceToFund.String(), bal.String(), "test: %v", tc.name) } else { - fee := sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, types.AddToGaugeFee)) + fee := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, types.AddToGaugeFee)) accountBalance := tc.accountBalanceToFund.Sub(tc.gaugeAddition) finalAccountBalance := accountBalance.Sub(fee) suite.Require().Equal(finalAccountBalance.String(), bal.String(), "test: %v", tc.name) diff --git a/x/incentives/simulation/operations.go b/x/incentives/simulation/operations.go index 81d4e0854c7..a8d10d2816c 100644 --- a/x/incentives/simulation/operations.go +++ b/x/incentives/simulation/operations.go @@ -18,8 +18,6 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - appparams "github.com/osmosis-labs/osmosis/v10/app/params" ) // Simulation operation weights constants. @@ -117,7 +115,7 @@ func SimulateMsgCreateGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankK ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { simAccount, _ := simtypes.RandomAcc(r, accs) simCoins := bk.SpendableCoins(ctx, simAccount.Address) - if simCoins.Len() <= 0 || simCoins.AmountOf(appparams.BaseCoinUnit).LT(types.CreateGaugeFee) { + if simCoins.AmountOf(sdk.DefaultBondDenom).LT(types.CreateGaugeFee) { return simtypes.NoOpMsg( types.ModuleName, types.TypeMsgCreateGauge, "Account have no coin"), nil, nil } @@ -156,7 +154,7 @@ func SimulateMsgAddToGauge(ak stakingTypes.AccountKeeper, bk stakingTypes.BankKe ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { simAccount, _ := simtypes.RandomAcc(r, accs) simCoins := bk.SpendableCoins(ctx, simAccount.Address) - if simCoins.Len() <= 0 || simCoins.AmountOf(appparams.BaseCoinUnit).LT(types.AddToGaugeFee) { + if simCoins.AmountOf(sdk.DefaultBondDenom).LT(types.AddToGaugeFee) { return simtypes.NoOpMsg( types.ModuleName, types.TypeMsgAddToGauge, "Account have no coin"), nil, nil } diff --git a/x/incentives/types/expected_keepers.go b/x/incentives/types/expected_keepers.go index 5319039c3fd..c0c04916feb 100644 --- a/x/incentives/types/expected_keepers.go +++ b/x/incentives/types/expected_keepers.go @@ -42,3 +42,8 @@ type EpochKeeper interface { type DistrKeeper interface { FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error } + +// TxFeesKeeper defines the expected interface needed to managing transaction fees. +type TxFeesKeeper interface { + GetBaseDenom(ctx sdk.Context) (denom string, err error) +} From 1592bb89a2b13dbedaa8ea63cbe83bf63ea31f1d Mon Sep 17 00:00:00 2001 From: Felix <62290842+ctrl-Felix@users.noreply.github.com> Date: Wed, 3 Aug 2022 16:11:54 +0200 Subject: [PATCH 144/376] fix: swagger docs & swagger generation #2233 (#2271) --- Makefile | 1 + client/docs/config.json | 100 +- client/docs/package.json | 2 +- client/docs/static/openapi/index.html | 720 +- client/docs/static/openapi/openapi.yaml | 45893 ++++++++++++++-------- client/docs/static/swagger/swagger.yaml | 43684 ++++++++++++-------- client/docs/statik/statik.go | 2 +- client/docs/yarn.lock | 144 +- scripts/generate-docs.sh | 4 +- 9 files changed, 56579 insertions(+), 33971 deletions(-) diff --git a/Makefile b/Makefile index 58a3f128ee2..d9b6e239f50 100644 --- a/Makefile +++ b/Makefile @@ -166,6 +166,7 @@ docs: @echo @echo "=========== Generate Complete ============" @echo +.PHONY: docs protoVer=v0.7 protoImageName=tendermintdev/sdk-proto-gen:$(protoVer) diff --git a/client/docs/config.json b/client/docs/config.json index 30662cb74b5..dce7013b055 100644 --- a/client/docs/config.json +++ b/client/docs/config.json @@ -7,26 +7,26 @@ }, "apis": [ { - "url": "../../tmp-swagger-gen/osmosis/gamm/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/osmosis/epochs/query.swagger.json", "operationIds": { "rename": { - "Params": "GAMMParams" + "Params": "EpochsParams" } } }, { - "url": "../../tmp-swagger-gen/osmosis/epochs/query.swagger.json", + "url": "../../tmp-swagger-gen/osmosis/gamm/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "EpochsParams" + "Params": "GAMMParams" } } }, { - "url": "../../tmp-swagger-gen/osmosis/pool-incentives/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/osmosis/incentives/query.swagger.json", "operationIds": { "rename": { - "Params": "PoolIncentivesParams" + "Params": "IncentivesParams" } } }, @@ -39,26 +39,44 @@ } }, { - "url": "../../tmp-swagger-gen/osmosis/incentives/query.swagger.json", + "url": "../../tmp-swagger-gen/osmosis/mint/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "IncentivesParams" + "Params": "MintParams" + } + } + }, + { + "url": "../../tmp-swagger-gen/osmosis/pool-incentives/v1beta1/query.swagger.json", + "operationIds": { + "rename": { + "LockableDurations": "PoolLockableDurations", + "Params": "PoolIncentivesParams" } } }, { - "url": "../../tmp-swagger-gen/osmosis/claim/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/osmosis/superfluid/query.swagger.json", "operationIds": { "rename": { - "Params": "ClaimParams" + "Params": "SuperfluidParams" } } }, { - "url": "../../tmp-swagger-gen/osmosis/mint/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/osmosis/tokenfactory/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "MintParams" + "Params": "TokenfactoryParams" + } + } + }, + { + "url": "../../tmp-swagger-gen/osmosis/txfees/v1beta1/query.swagger.json", + "operationIds": { + "rename": { + "Params": "TxFeesParams", + "BaseDenom": "TxFeesBaseDenom" } } }, @@ -71,100 +89,106 @@ } }, { - "url": "../../tmp-swagger-gen/cosmos/bank/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/authz/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "BankParams" + "Params": "AuthzParams" } } }, { - "url": "../../tmp-swagger-gen/cosmos/distribution/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/bank/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "DistributionParams" + "Params": "BankParams" } } }, { - "url": "../../tmp-swagger-gen/cosmos/evidence/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/base/tendermint/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "EvidenceParams" + "Params": "BaseParams" } } }, { - "url": "../../tmp-swagger-gen/cosmos/gov/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/distribution/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "GovParams" + "Params": "DistributionParams" } } }, { - "url": "../../tmp-swagger-gen/cosmos/params/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/evidence/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "Params" + "Params": "EvidenceParams" } } }, { - "url": "../../tmp-swagger-gen/cosmos/slashing/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/feegrant/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "SlashingParams" + "Params": "FeegrantParams" } } }, { - "url": "../../tmp-swagger-gen/cosmos/staking/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/gov/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "StakingParams", - "Pool": "StakingPool", - "DelegatorValidators": "StakingDelegatorValidators" + "Params": "GovParams" } } }, { - "url": "../../tmp-swagger-gen/cosmos/upgrade/v1beta1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/mint/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "UpgradeParams" + "Params": "CosmosMintParams" } } }, { - "url": "../../tmp-swagger-gen/ibc/core/channel/v1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/params/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "IBCChannelParams" + "Params": "Params" } } }, { - "url": "../../tmp-swagger-gen/ibc/core/client/v1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/slashing/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "IBCClientParams" + "Params": "SlashingParams" } } }, { - "url": "../../tmp-swagger-gen/ibc/core/connection/v1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/staking/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "IBCConnectionParams" + "Params": "StakingParams", + "Pool": "StakingPool", + "DelegatorValidators": "StakingDelegatorValidators" } } }, { - "url": "../../tmp-swagger-gen/ibc/applications/transfer/v1/query.swagger.json", + "url": "../../tmp-swagger-gen/cosmos/tx/v1beta1/service.swagger.json", + "dereference": { + "circular": "ignore" + } + }, + { + "url": "../../tmp-swagger-gen/cosmos/upgrade/v1beta1/query.swagger.json", "operationIds": { "rename": { - "Params": "IBCTransferParams" + "Params": "UpgradeParams" } } } diff --git a/client/docs/package.json b/client/docs/package.json index c38bc57fabb..baf109a506a 100644 --- a/client/docs/package.json +++ b/client/docs/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "redoc-cli": "^0.9.12", - "swagger-combine": "^1.3.0", + "swagger-combine": "^1.4.0", "swagger2openapi": "^7.0.3" } } diff --git a/client/docs/static/openapi/index.html b/client/docs/static/openapi/index.html index 68c0a07abd1..368811ac057 100644 --- a/client/docs/static/openapi/index.html +++ b/client/docs/static/openapi/index.html @@ -146,6 +146,8 @@ data-styled.g9[id="sc-fujyUd"]{content:"dmdCWO,"}/*!sc*/ .kWxjDZ{font-family:Montserrat,sans-serif;font-weight:400;font-size:1.57143em;line-height:1.6em;color:black;}/*!sc*/ data-styled.g10[id="sc-pNWxx"]{content:"kWxjDZ,"}/*!sc*/ +.eCIxyj{color:#ffffff;}/*!sc*/ +data-styled.g12[id="sc-kEqYlL"]{content:"eCIxyj,"}/*!sc*/ .hAFWNc{border-bottom:1px solid rgba(38,50,56,0.3);margin:1em 0 1em 0;color:rgba(38,50,56,0.5);font-weight:normal;text-transform:uppercase;font-size:0.929em;line-height:20px;}/*!sc*/ data-styled.g13[id="sc-iqAbSa"]{content:"hAFWNc,"}/*!sc*/ .hzAFMi{cursor:pointer;margin-left:-20px;padding:0;line-height:1;width:20px;display:inline-block;outline:0;}/*!sc*/ @@ -159,7 +161,8 @@ .jlUNTT polygon{fill:#d41f1c;}/*!sc*/ .hFuYxn{height:20px;width:20px;vertical-align:middle;float:right;-webkit-transition:-webkit-transform 0.2s ease-out;-webkit-transition:transform 0.2s ease-out;transition:transform 0.2s ease-out;-webkit-transform:rotateZ(0);-ms-transform:rotateZ(0);transform:rotateZ(0);}/*!sc*/ .hFuYxn polygon{fill:white;}/*!sc*/ -data-styled.g15[id="sc-dIsAE"]{content:"hlNMKC,zIEmD,jlUNTT,hFuYxn,"}/*!sc*/ +.dWXhZG{height:18px;width:18px;vertical-align:middle;-webkit-transition:-webkit-transform 0.2s ease-out;-webkit-transition:transform 0.2s ease-out;transition:transform 0.2s ease-out;-webkit-transform:rotateZ(-90deg);-ms-transform:rotateZ(-90deg);transform:rotateZ(-90deg);}/*!sc*/ +data-styled.g15[id="sc-dIsAE"]{content:"hlNMKC,zIEmD,jlUNTT,hFuYxn,dWXhZG,"}/*!sc*/ .bfyodq{border-left:1px solid #a4a4c6;box-sizing:border-box;position:relative;padding:10px 10px 10px 0;}/*!sc*/ tr:first-of-type > .sc-hBMVcZ,tr.last > .bfyodq{border-left-width:0;background-position:top left;background-repeat:no-repeat;background-size:1px 100%;}/*!sc*/ tr:first-of-type > .sc-hBMVcZ{background-image:linear-gradient( to bottom, transparent 0%, transparent 22px, #a4a4c6 22px, #a4a4c6 100% );}/*!sc*/ @@ -182,6 +185,21 @@ .buVWLu .sc-dIvqjp,.buVWLu .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp,.buVWLu .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp{margin:1em;margin-right:0;background:#fafafa;}/*!sc*/ .buVWLu .sc-dIvqjp .sc-dIvqjp,.buVWLu .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp,.buVWLu .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp .sc-dIvqjp{background:#ffffff;}/*!sc*/ data-styled.g24[id="sc-hHEjAm"]{content:"buVWLu,"}/*!sc*/ +.diVOEA{margin-left:10px;text-transform:none;font-size:0.929em;color:black;}/*!sc*/ +data-styled.g43[id="sc-jcwofb"]{content:"diVOEA,"}/*!sc*/ +.ceoCql > ul{list-style:none;padding:0;margin:0;margin:0 -5px;}/*!sc*/ +.ceoCql > ul > li{padding:5px 10px;display:inline-block;background-color:#11171a;border-bottom:1px solid rgba(0,0,0,0.5);cursor:pointer;text-align:center;outline:none;color:#b3b3b3;margin:0 5px 5px 5px;border:1px solid #07090b;border-radius:5px;min-width:60px;font-size:0.9em;font-weight:bold;}/*!sc*/ +.ceoCql > ul > li.react-tabs__tab--selected{color:#333333;background:#ffffff;}/*!sc*/ +.ceoCql > ul > li.react-tabs__tab--selected:focus{outline:auto;}/*!sc*/ +.ceoCql > ul > li:only-child{-webkit-flex:none;-ms-flex:none;flex:none;min-width:100px;}/*!sc*/ +.ceoCql > ul > li.tab-success{color:#1d8127;}/*!sc*/ +.ceoCql > ul > li.tab-redirect{color:#ffa500;}/*!sc*/ +.ceoCql > ul > li.tab-info{color:#87ceeb;}/*!sc*/ +.ceoCql > ul > li.tab-error{color:#d41f1c;}/*!sc*/ +.ceoCql > .react-tabs__tab-panel{background:#11171a;}/*!sc*/ +.ceoCql > .react-tabs__tab-panel > div,.ceoCql > .react-tabs__tab-panel > pre{padding:20px;margin:0;}/*!sc*/ +.ceoCql > .react-tabs__tab-panel > div > pre{padding:0;}/*!sc*/ +data-styled.g44[id="sc-carGAA"]{content:"ceoCql,"}/*!sc*/ .cOZQxS code[class*='language-'],.cOZQxS pre[class*='language-']{text-shadow:0 -0.1em 0.2em black;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none;}/*!sc*/ @media print{.cOZQxS code[class*='language-'],.cOZQxS pre[class*='language-']{text-shadow:none;}}/*!sc*/ .cOZQxS pre[class*='language-']{padding:1em;margin:0.5em 0;overflow:auto;}/*!sc*/ @@ -201,6 +219,11 @@ .cOZQxS .token.entity{cursor:help;}/*!sc*/ .cOZQxS .token.deleted{color:red;}/*!sc*/ data-styled.g46[id="sc-iBzFoy"]{content:"cOZQxS,"}/*!sc*/ +.kizJoo{opacity:0.4;-webkit-transition:opacity 0.3s ease;transition:opacity 0.3s ease;text-align:right;}/*!sc*/ +.kizJoo:focus-within{opacity:1;}/*!sc*/ +.kizJoo > button{background-color:transparent;border:0;color:inherit;padding:2px 10px;font-family:Roboto,sans-serif;font-size:14px;line-height:1.5em;cursor:pointer;outline:0;}/*!sc*/ +.kizJoo > button:hover,.kizJoo > button:focus{background:rgba(255,255,255,0.1);}/*!sc*/ +data-styled.g47[id="sc-efHXLn"]{content:"kizJoo,"}/*!sc*/ .ps{overflow:hidden !important;overflow-anchor:none;-ms-overflow-style:none;touch-action:auto;-ms-touch-action:auto;}/*!sc*/ .ps__rail-x{display:none;opacity:0;-webkit-transition:background-color .2s linear,opacity .2s linear;transition:background-color .2s linear,opacity .2s linear;-webkit-transition:background-color .2s linear,opacity .2s linear;height:15px;bottom:0px;position:absolute;}/*!sc*/ .ps__rail-y{display:none;opacity:0;-webkit-transition:background-color .2s linear,opacity .2s linear;transition:background-color .2s linear,opacity .2s linear;-webkit-transition:background-color .2s linear,opacity .2s linear;width:15px;right:0;position:absolute;}/*!sc*/ @@ -292,12 +315,50 @@ .gecBYU a:visited{color:#32329f;}/*!sc*/ .gecBYU a:hover{color:#6868cf;}/*!sc*/ data-styled.g54[id="sc-ArjOu"]{content:"gecBYU,"}/*!sc*/ +.eQwAZu{position:relative;}/*!sc*/ +data-styled.g55[id="sc-khIgXV"]{content:"eQwAZu,"}/*!sc*/ +.hwFewY:hover > .sc-efHXLn{opacity:1;}/*!sc*/ +data-styled.g60[id="sc-iNiQeE"]{content:"hwFewY,"}/*!sc*/ +.bFlCqe{font-family:Courier,monospace;font-size:13px;white-space:pre;contain:content;overflow-x:auto;}/*!sc*/ +.bFlCqe .redoc-json > .collapser{display:none;}/*!sc*/ +.bFlCqe .callback-function{color:gray;}/*!sc*/ +.bFlCqe .collapser:after{content:'-';cursor:pointer;}/*!sc*/ +.bFlCqe .collapsed > .collapser:after{content:'+';cursor:pointer;}/*!sc*/ +.bFlCqe .ellipsis:after{content:' … ';}/*!sc*/ +.bFlCqe .collapsible{margin-left:2em;}/*!sc*/ +.bFlCqe .hoverable{padding-top:1px;padding-bottom:1px;padding-left:2px;padding-right:2px;border-radius:2px;}/*!sc*/ +.bFlCqe .hovered{background-color:rgba(235,238,249,1);}/*!sc*/ +.bFlCqe .collapser{padding-right:6px;padding-left:6px;}/*!sc*/ +.bFlCqe ul{list-style-type:none;padding:0px;margin:0px 0px 0px 26px;}/*!sc*/ +.bFlCqe li{position:relative;display:block;}/*!sc*/ +.bFlCqe .hoverable{display:inline-block;}/*!sc*/ +.bFlCqe .selected{outline-style:solid;outline-width:1px;outline-style:dotted;}/*!sc*/ +.bFlCqe .collapsed > .collapsible{display:none;}/*!sc*/ +.bFlCqe .ellipsis{display:none;}/*!sc*/ +.bFlCqe .collapsed > .ellipsis{display:inherit;}/*!sc*/ +.bFlCqe .collapser{position:absolute;top:1px;left:-1.5em;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-user-select:none;}/*!sc*/ +data-styled.g61[id="sc-jffIyK"]{content:"bFlCqe,"}/*!sc*/ +.gasyRS{padding:0.9em;background-color:rgba(38,50,56,0.4);margin:0 0 10px 0;display:block;font-family:Montserrat,sans-serif;font-size:0.929em;line-height:1.5em;}/*!sc*/ +data-styled.g62[id="sc-eJoaVz"]{content:"gasyRS,"}/*!sc*/ +.bbKFgY{font-family:Montserrat,sans-serif;font-size:12px;position:absolute;z-index:1;top:-11px;left:12px;font-weight:600;color:rgba(255,255,255,0.4);}/*!sc*/ +data-styled.g63[id="sc-oefIU"]{content:"bbKFgY,"}/*!sc*/ +.bqSAvT{position:relative;}/*!sc*/ +data-styled.g64[id="sc-hhIhEF"]{content:"bqSAvT,"}/*!sc*/ +.fhUivV{margin-top:15px;}/*!sc*/ +data-styled.g67[id="sc-gGLyOc"]{content:"fhUivV,"}/*!sc*/ +.Hlvtr button{background-color:transparent;border:0;outline:0;font-size:13px;font-family:Courier,monospace;cursor:pointer;padding:0;color:#333333;}/*!sc*/ +.Hlvtr button:focus{font-weight:600;}/*!sc*/ +.Hlvtr .sc-dIsAE{height:1.1em;width:1.1em;}/*!sc*/ +.Hlvtr .sc-dIsAE polygon{fill:#808080;}/*!sc*/ +data-styled.g68[id="sc-ckTRkR"]{content:"Hlvtr,"}/*!sc*/ .ffLJSh{vertical-align:middle;font-size:13px;line-height:20px;}/*!sc*/ data-styled.g69[id="sc-fbIXFq"]{content:"ffLJSh,"}/*!sc*/ .lmAzvs{color:rgba(128,128,128,0.8);}/*!sc*/ data-styled.g70[id="sc-FRqcf"]{content:"lmAzvs,"}/*!sc*/ .hftVBq{color:#808080;}/*!sc*/ data-styled.g71[id="sc-fXazxj"]{content:"hftVBq,"}/*!sc*/ +.SmIsP{color:#808080;word-break:break-word;}/*!sc*/ +data-styled.g72[id="sc-dvXXZy"]{content:"SmIsP,"}/*!sc*/ .cRaJfP{vertical-align:middle;font-size:13px;line-height:20px;}/*!sc*/ data-styled.g73[id="sc-TtZHJ"]{content:"cRaJfP,"}/*!sc*/ .bfDxeF{color:#d41f1c;font-size:0.9em;font-weight:normal;margin-left:20px;line-height:1;}/*!sc*/ @@ -305,9 +366,6 @@ .dYpOEw{border-radius:2px;background-color:rgba(51,51,51,0.05);color:rgba(51,51,51,0.9);padding:0 5px;border:1px solid rgba(51,51,51,0.1);font-family:Courier,monospace;}/*!sc*/ .sc-eKYRpg + .sc-eKYRpg{margin-left:0;}/*!sc*/ data-styled.g78[id="sc-eKYRpg"]{content:"dYpOEw,"}/*!sc*/ -.hDztXq{border-radius:2px;background-color:rgba(142,142,220,0.05);color:rgba(50,50,159,0.9);margin:0 5px;padding:0 5px;border:1px solid rgba(50,50,159,0.1);font-family:Courier,monospace;}/*!sc*/ -.sc-kHWWFa + .sc-kHWWFa{margin-left:0;}/*!sc*/ -data-styled.g80[id="sc-kHWWFa"]{content:"hDztXq,"}/*!sc*/ .bCtQK{margin-top:0;margin-bottom:0.5em;}/*!sc*/ data-styled.g86[id="sc-fuIRbl"]{content:"bCtQK,"}/*!sc*/ .htVLwM{border:1px solid #32329f;color:#32329f;font-weight:normal;margin-left:0.5em;padding:4px 8px 4px;display:inline-block;-webkit-text-decoration:none;text-decoration:none;cursor:pointer;}/*!sc*/ @@ -356,7 +414,8 @@ .lbxURJ:focus{box-shadow:inset 0 2px 2px rgba(0,0,0,0.45),0 2px 0 rgba(128,128,128,0.25);}/*!sc*/ data-styled.g107[id="sc-xGAYn"]{content:"lbxURJ,"}/*!sc*/ .fDdIiv{font-size:0.929em;line-height:20px;background-color:#6bbd5b;color:#ffffff;padding:3px 10px;text-transform:uppercase;font-family:Montserrat,sans-serif;margin:0;}/*!sc*/ -data-styled.g108[id="sc-dWBSoC"]{content:"fDdIiv,"}/*!sc*/ +.gyWLOi{font-size:0.929em;line-height:20px;background-color:#248fb2;color:#ffffff;padding:3px 10px;text-transform:uppercase;font-family:Montserrat,sans-serif;margin:0;}/*!sc*/ +data-styled.g108[id="sc-dWBSoC"]{content:"fDdIiv,gyWLOi,"}/*!sc*/ .hnNwwi{position:absolute;width:100%;z-index:100;background:#fafafa;color:#263238;box-sizing:border-box;box-shadow:0px 0px 6px rgba(0,0,0,0.33);overflow:hidden;border-bottom-left-radius:4px;border-bottom-right-radius:4px;-webkit-transition:all 0.25s ease;transition:all 0.25s ease;visibility:hidden;-webkit-transform:translateY(-50%) scaleY(0);-ms-transform:translateY(-50%) scaleY(0);transform:translateY(-50%) scaleY(0);}/*!sc*/ data-styled.g109[id="sc-jHcYrh"]{content:"hnNwwi,"}/*!sc*/ .gtKCCj{padding:10px;}/*!sc*/ @@ -373,6 +432,8 @@ data-styled.g116[id="sc-ljslrt"]{content:"fcVGze,"}/*!sc*/ .bBmAHf{-webkit-backface-visibility:hidden;backface-visibility:hidden;contain:content;overflow:hidden;}/*!sc*/ data-styled.g128[id="sc-eXuzZk"]{content:"bBmAHf,"}/*!sc*/ +.eokZKJ{margin-bottom:30px;}/*!sc*/ +data-styled.g129[id="sc-iGkqGz"]{content:"eokZKJ,"}/*!sc*/ .gHivHp{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;width:20px;height:20px;-webkit-align-self:center;-ms-flex-item-align:center;align-self:center;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;color:#32329f;}/*!sc*/ data-styled.g130[id="sc-irKEWy"]{content:"gHivHp,"}/*!sc*/ .hVKzgS{width:260px;background-color:#fafafa;overflow:hidden;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-backface-visibility:hidden;backface-visibility:hidden;height:100vh;position:-webkit-sticky;position:sticky;position:-webkit-sticky;top:0;}/*!sc*/ @@ -405,32 +466,38 @@ -

Osmosis - gRPC Gateway docs (1.0.0)

Download OpenAPI specification:Download

A REST interface for state queries, legacy transactions

-

Query

NumPools

Responses

Query

CurrentEpoch provide current epoch of specified identifier

query Parameters
identifier
string

Responses

EpochInfos provide running epochInfos

Responses

NumPools

Responses

Pools

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin querying the next page most efficiently. Only one of offset or key @@ -459,45 +530,138 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

Per Pool gRPC Endpoints

path Parameters
poolId
required
string <uint64>

Responses

Per Pool gRPC Endpoints

path Parameters
pool_id
required
string <uint64>

Responses

PoolParams

path Parameters
poolId
required
string <uint64>

Responses

PoolParams

path Parameters
pool_id
required
string <uint64>

Responses

SpotPrice

path Parameters
poolId
required
string <uint64>
query Parameters
tokenInDenom
string
tokenOutDenom
string
withSwapFee
boolean

Responses

SpotPrice defines a gRPC query handler that returns the spot price given +a base denomination and a quote denomination.

path Parameters
pool_id
required
string <uint64>
query Parameters
base_asset_denom
string
quote_asset_denom
string

Responses

PoolAssets

path Parameters
poolId
required
string <uint64>

Responses

TotalPoolLiquidity

path Parameters
pool_id
required
string <uint64>

Responses

TotalShare

path Parameters
poolId
required
string <uint64>

Responses

TotalShares

path Parameters
pool_id
required
string <uint64>

Responses

TotalLiquidity

Responses

TotalLiquidity

Responses

Estimate the swap.

path Parameters
poolId
required
string <uint64>
query Parameters
sender
string
tokenIn
string

Responses

Estimate the swap.

path Parameters
pool_id
required
string <uint64>
query Parameters
sender
string
token_in
string

Responses

EstimateSwapExactAmountOut

path Parameters
poolId
required
string <uint64>
query Parameters
sender
string
tokenOut
string

Responses

EstimateSwapExactAmountOut

path Parameters
pool_id
required
string <uint64>
query Parameters
sender
string
token_out
string

Responses

CurrentEpoch provide current epoch of specified identifier

query Parameters
identifier
string

Responses

ActiveGauges returns active gauges

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +querying the next page most efficiently. Only one of offset or key +should be set.

+
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. +It is less efficient than using key. Only one of offset or key should +be set.

+
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. +If left empty it will default to a value to be set by each app.

+
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +a count of the total number of items available for pagination in UIs. +count_total is only respected when offset is used. It is ignored when key +is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

+

Responses

EpochInfos provide running epochInfos

Responses

ActiveGaugesPerDenom returns active gauges by denom

query Parameters
denom
string

Desired denom when querying active gagues.

+
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +querying the next page most efficiently. Only one of offset or key +should be set.

+
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. +It is less efficient than using key. Only one of offset or key should +be set.

+
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. +If left empty it will default to a value to be set by each app.

+
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +a count of the total number of items available for pagination in UIs. +count_total is only respected when offset is used. It is ignored when key +is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

+

Responses

GaugeByID returns gauges by their respective ID

path Parameters
id
required
string <uint64>

Gague ID being queried

+

Responses

Gauges returns both upcoming and active gauges

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +querying the next page most efficiently. Only one of offset or key +should be set.

+
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. +It is less efficient than using key. Only one of offset or key should +be set.

+
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. +If left empty it will default to a value to be set by each app.

+
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +a count of the total number of items available for pagination in UIs. +count_total is only respected when offset is used. It is ignored when key +is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

+

Responses

DistrInfo

Responses

LockableDurations returns lockable durations that are valid to distribute +incentives for

Responses

GaugeIds takes the pool id and returns the matching gauge ids and durations

path Parameters
pool_id
required
string <uint64>

Responses

ModuleDistributedCoins returns coins that are distributed by the module so +far

Responses

IncentivizedPools

Responses

ModuleToDistributeCoins returns coins that are going to be distributed

Responses

RewardsEst returns an estimate of the rewards from now until a specified +time in the future The querier either provides an address or a set of locks +for which they want to find the associated rewards

path Parameters
owner
required
string

Address that is being queried for future estimated rewards

+
query Parameters
lock_ids
Array of strings <uint64>

Lock IDs included in future reward estimation.

+
end_epoch
string <int64>

Upper time limit of reward estimation +Lower limit is current epoch.

+

Responses

LockableDurations

Responses

Returns scheduled gauges that have not yet occured

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +querying the next page most efficiently. Only one of offset or key +should be set.

+
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. +It is less efficient than using key. Only one of offset or key should +be set.

+
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. +If left empty it will default to a value to be set by each app.

+
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +a count of the total number of items available for pagination in UIs. +count_total is only respected when offset is used. It is ignored when key +is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

+

Responses

UpcomingGaugesPerDenom returns scheduled gauges that have not yet occured +by denom

query Parameters
denom
string

Filter for upcoming gagues that match specific denom.

+
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +querying the next page most efficiently. Only one of offset or key +should be set.

+
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. +It is less efficient than using key. Only one of offset or key should +be set.

+
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. +If left empty it will default to a value to be set by each app.

+
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +a count of the total number of items available for pagination in UIs. +count_total is only respected when offset is used. It is ignored when key +is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

+

Responses

PoolIncentivesParams

Responses

Return a locked coins that can't be withdrawn

path Parameters
owner
required
string

Responses

Return a locked coins that can't be withdrawn

path Parameters
owner
required
string

Responses

Returns account locked records with a specific duration

path Parameters
owner
required
string
query Parameters
duration
string

Responses

Returns account locked records with longer duration

path Parameters
owner
required
string
query Parameters
duration
string

Responses

Returns account locked records with longer duration

path Parameters
owner
required
string
query Parameters
duration
string

Responses

Returns account's locked records for a denom with longer duration

path Parameters
owner
required
string
query Parameters
duration
string
denom
string

Responses

Returns lock record by id

path Parameters
lock_id
required
string <uint64>

Responses

Return full balance of the module

Responses

Returns total locked per denom with longer past given time

query Parameters
denom
string
duration
string

Responses

Return full balance of the module

Responses

Return locked balance of the module

Responses

returns active gauges

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +

Returns synthetic lockups by native lockup id

path Parameters
lock_id
required
string <uint64>

Responses

EpochProvisions returns the current minting epoch provisions value.

Responses

Params returns the total set of minting parameters.

Responses

DistrInfo returns the pool's matching gauge ids and weights.

Responses

ExternalIncentiveGauges returns external incentive gauges.

Responses

GaugeIds takes the pool id and returns the matching gauge ids and durations

path Parameters
pool_id
required
string <uint64>

Responses

IncentivizedPools returns currently incentivized pools

Responses

LockableDurations returns lock durations for pools.

Responses

Params returns pool incentives params.

Responses

Returns all registered superfluid assets.

Responses

Returns all superfluid intermediary accounts.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin querying the next page most efficiently. Only one of offset or key should be set.

pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. @@ -531,15 +717,63 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

returns Gauge by id

path Parameters
id
required
string <uint64>

Responses

Returns the total amount of osmo superfluidly staked. +Response is denominated in uosmo.

Responses

Returns the osmo equivalent multiplier used in the most recent epoch.

query Parameters
denom
string

Responses

Returns superfluid asset type, whether if it's a native asset or an lp +share.

query Parameters
denom
string

Responses

Returns intermediary account connected to a superfluid staked lock by id

path Parameters
lock_id
required
string <uint64>

Responses

Returns the amount of a specific denom delegated to a specific validator +This is labeled an estimate, because the way it calculates the amount can +lead rounding errors from the true delegated amount

query Parameters
validator_address
string
denom
string

Responses

Params returns the total set of superfluid parameters.

Responses

Returns the coins superfluid delegated for the delegator, validator, denom +triplet

query Parameters
delegator_address
string
validator_address
string
denom
string

Responses

Returns all the delegated superfluid poistions for a specific delegator.

path Parameters
delegator_address
required
string

Responses

Returns all the superfluid positions of a specific denom delegated to one +validator

query Parameters
validator_address
string
denom
string

Responses

Returns all the undelegating superfluid poistions for a specific delegator.

path Parameters
delegator_address
required
string
query Parameters
denom
string

Responses

Returns the specified delegations for a specific delegator

path Parameters
delegator_address
required
string

Responses

DenomAuthorityMetadata defines a gRPC query method for fetching +DenomAuthorityMetadata for a particular denom.

path Parameters
denom
required
string

Responses

DenomsFromCreator defines a gRPC query method for fetching all +denominations created by a specific admin/creator.

path Parameters
creator
required
string

Responses

Params defines a gRPC query method that returns the tokenfactory module's +parameters.

Responses

Returns a list of all base denom tokens and their corresponding pools.

Responses

returns gauges both upcoming and active

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +

Returns the poolID for a specified denom input.

path Parameters
denom
required
string

Responses

FeeTokens returns a list of all the whitelisted fee tokens and their +corresponding pools. It does not include the BaseDenom, which has its own +query endpoint

Responses

DenomSpotPrice returns all spot prices by each registered token denom.

query Parameters
denom
string

Responses

Accounts returns all the existing accounts

Since: cosmos-sdk 0.43

+
query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin querying the next page most efficiently. Only one of offset or key should be set.

pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. @@ -547,21 +781,23 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

returns coins that are distributed by module so far

Responses

Account returns account details based on address.

path Parameters
address
required
string

address defines the address to query for.

+

Responses

returns coins that is going to be distributed

Responses

ModuleAccounts returns all the existing module accounts.

Responses

RewardsEst returns an estimate of the rewards at a future specific time. -The querier either provides an address or a set of locks -for which they want to find the associated rewards.

path Parameters
owner
required
string
query Parameters
lock_ids
Array of strings <uint64>
end_epoch
string <int64>

Responses

Params queries all parameters.

Responses

returns scheduled gauges

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +

Returns list of `Authorization`, granted to the grantee by the granter.

query Parameters
granter
string
grantee
string
msg_type_url
string

Optional, msg_type_url, when set, will query only grants matching given msg type.

+
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin querying the next page most efficiently. Only one of offset or key should be set.

pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. @@ -569,32 +805,15 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

ClaimRecord

path Parameters
address
required
string

Responses

ClaimableForAction

path Parameters
address
required
string
action
required
string
Enum: "ActionAddLiquidity" "ActionSwap" "ActionVote" "ActionDelegateStake"

Responses

ModuleAccountBalance

Responses

ClaimParams

Responses

TotalClaimable

path Parameters
address
required
string

Responses

EpochProvisions current minting epoch provisions value.

Responses

Params returns the total set of minting parameters.

Responses

Account returns account details based on address.

path Parameters
address
required
string

address defines the address to query for.

-

Responses

Params queries all parameters.

Responses

AllBalances queries the balance of all coins for a single account.

path Parameters
address
required
string

address is the address to query balances for.

+

AllBalances queries the balance of all coins for a single account.

path Parameters
address
required
string

address is the address to query balances for.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin querying the next page most efficiently. Only one of offset or key should be set.

@@ -603,17 +822,22 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

Balance queries the balance of a single coin for a single account.

path Parameters
address
required
string

address is the address to query balances for.

-
denom
required
string

denom is the coin denom to query balances for.

+

Balance queries the balance of a single coin for a single account.

path Parameters
address
required
string

address is the address to query balances for.

+
query Parameters
denom
string

denom is the coin denom to query balances for.

Responses

DenomsMetadata queries the client metadata for all registered coin denominations.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +

BaseDenom queries for a base denomination given a denom that can either be +the base denom itself or a metadata denom unit that maps to the base denom.

query Parameters
denom
string

Responses

DenomsMetadata queries the client metadata for all registered coin denominations.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin querying the next page most efficiently. Only one of offset or key should be set.

pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. @@ -621,10 +845,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

DenomsMetadata queries the client metadata of a given coin denomination.

path Parameters
denom
required
string

denom is the coin denom to query the metadata for.

@@ -632,12 +858,45 @@

Params queries the parameters of x/bank module.

Responses

TotalSupply queries the total supply of all coins.

Responses

TotalSupply queries the total supply of all coins.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +querying the next page most efficiently. Only one of offset or key +should be set.

+
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. +It is less efficient than using key. Only one of offset or key should +be set.

+
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. +If left empty it will default to a value to be set by each app.

+
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +a count of the total number of items available for pagination in UIs. +count_total is only respected when offset is used. It is ignored when key +is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

+

Responses

SupplyOf queries the supply of a single coin.

path Parameters
denom
required
string

denom is the coin denom to query balances for.

Responses

CommunityPool queries the community pool coins.

Responses

TotalSupplyWithoutOffset queries the total supply of all coins.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +querying the next page most efficiently. Only one of offset or key +should be set.

+
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. +It is less efficient than using key. Only one of offset or key should +be set.

+
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. +If left empty it will default to a value to be set by each app.

+
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +a count of the total number of items available for pagination in UIs. +count_total is only respected when offset is used. It is ignored when key +is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

+

Responses

SupplyOf queries the supply of a single coin.

path Parameters
denom
required
string

denom is the coin denom to query balances for.

+

Responses

CommunityPool queries the community pool coins.

Responses

DelegationTotalRewards queries the total rewards accrued by a each validator.

path Parameters
delegator_address
required
string

delegator_address defines the delegator address to query for.

@@ -672,10 +931,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

AllEvidence queries all evidence.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin @@ -686,16 +947,38 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

Evidence queries evidence based on evidence hash.

path Parameters
evidence_hash
required
string <byte>

evidence_hash defines the hash of the requested evidence.

Responses

Params queries all parameters of the gov module.

path Parameters
params_type
required
string

params_type defines which parameters to query for, can be one of "voting", +

Allowance returns fee granted to the grantee by the granter.

path Parameters
granter
required
string

granter is the address of the user granting an allowance of their funds.

+
grantee
required
string

grantee is the address of the user being granted an allowance of another user's funds.

+

Responses

Allowances returns all the grants for address.

path Parameters
grantee
required
string
query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +querying the next page most efficiently. Only one of offset or key +should be set.

+
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. +It is less efficient than using key. Only one of offset or key should +be set.

+
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. +If left empty it will default to a value to be set by each app.

+
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +a count of the total number of items available for pagination in UIs. +count_total is only respected when offset is used. It is ignored when key +is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

+

Responses

Params queries all parameters of the gov module.

path Parameters
params_type
required
string

params_type defines which parameters to query for, can be one of "voting", "tallying" or "deposit".

Responses

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

Proposal queries proposal details based on ProposalID.

path Parameters
proposal_id
required
string <uint64>

proposal_id defines the unique id of the proposal.

@@ -741,10 +1026,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

Deposit queries single deposit information based proposalID, depositAddr.

path Parameters
proposal_id
required
string <uint64>

proposal_id defines the unique id of the proposal.

@@ -763,17 +1050,25 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

Vote queries voted information based on proposalID, voterAddr.

path Parameters
proposal_id
required
string <uint64>

proposal_id defines the unique id of the proposal.

voter
required
string

voter defines the oter address for the proposals.

Responses

Params queries a specific parameter of a module, given its subspace and +

AnnualProvisions current minting annual provisions value.

Responses

Inflation returns the current minting inflation value.

Responses

Params returns the total set of minting parameters.

Responses

Params queries a specific parameter of a module, given its subspace and key.

query Parameters
subspace
string

subspace defines the module to query the parameter for.

key
string

key defines the key of the parameter in the subspace.

Responses

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

SigningInfo queries the signing info of given cons address

path Parameters
cons_address
required
string

cons_address is the address to query signing info of

@@ -806,10 +1103,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

Redelegations queries redelegations of given address.

path Parameters
delegator_addr
required
string

delegator_addr defines the delegator address to query for.

@@ -823,10 +1122,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

DelegatorUnbondingDelegations queries all unbonding delegations of a given @@ -839,10 +1140,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

DelegatorValidators queries all validators info for given delegator @@ -855,10 +1158,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

DelegatorValidator queries validator info for given delegator validator @@ -882,10 +1187,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

Validator queries validator info for given validator address.

path Parameters
validator_addr
required
string

validator_addr defines the validator address to query for.

@@ -900,10 +1207,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

Delegation queries delegate info for given validator delegator pair.

path Parameters
validator_addr
required
string

validator_addr defines the validator address to query for.

@@ -924,10 +1233,12 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

AppliedPlan queries a previously applied upgrade plan by its name.

path Parameters
name
required
string

name is the name of the applied plan to query for.

@@ -935,51 +1246,30 @@

CurrentPlan queries the current upgrade plan.

Responses

UpgradedConsensusState queries the consensus state that will serve +

ModuleVersions queries the list of module versions from state.

Since: cosmos-sdk 0.43

+
query Parameters
module_name
string

module_name is a field to query a specific module +consensus version from state. Leaving this empty will +fetch the full list of module versions from state.

+

Responses

UpgradedConsensusState queries the consensus state that will serve as a trusted kernel for the next version of this chain. It will only be stored at the last height of this chain. -UpgradedConsensusState RPC not supported with legacy querier

path Parameters
last_height
required
string <int64>

last height of the current chain must be sent in request +UpgradedConsensusState RPC not supported with legacy querier +This rpc is deprecated now that IBC has its own replacement +(https://github.com/cosmos/ibc-go/blob/2c880a22e9f9cc75f62b527ca94aa75ce1106001/proto/ibc/core/client/v1/query.proto#L54)

path Parameters
last_height
required
string <int64>

last height of the current chain must be sent in request as this is the height under which next consensus state is stored

Responses

Channels queries all the IBC channels of a chain.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin -querying the next page most efficiently. Only one of offset or key -should be set.

-
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. -It is less efficient than using key. Only one of offset or key should -be set.

-
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. -If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include -a count of the total number of items available for pagination in UIs. -count_total is only respected when offset is used. It is ignored when key -is set.

-

Responses

Channel queries an IBC Channel.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-

Responses

Service

GetLatestBlock returns the latest block.

Responses

ChannelClientState queries for the client state for the channel associated -with the provided channel identifiers.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-

Responses

GetBlockByHeight queries block for given height.

path Parameters
height
required
string <int64>

Responses

ChannelConsensusState queries for the consensus state for the channel -associated with the provided channel identifiers.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-
revision_number
required
string <uint64>

revision number of the consensus state

-
revision_height
required
string <uint64>

revision height of the consensus state

-

Responses

GetNodeInfo queries the current node info.

Responses

NextSequenceReceive returns the next receive sequence for a given channel.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-

Responses

GetSyncing queries node syncing.

Responses

PacketAcknowledgements returns all the packet acknowledgements associated -with a channel.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-
query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +

GetLatestValidatorSet queries latest validator-set.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin querying the next page most efficiently. Only one of offset or key should be set.

pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. @@ -987,21 +1277,15 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

PacketAcknowledgement queries a stored packet acknowledgement hash.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-
sequence
required
string <uint64>

packet sequence

-

Responses

PacketCommitments returns all the packet commitments hashes associated -with a channel.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-
query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +

GetValidatorSetByHeight queries validator-set at a given height.

path Parameters
height
required
string <int64>
query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin querying the next page most efficiently. Only one of offset or key should be set.

pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. @@ -1009,98 +1293,21 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

Responses

UnreceivedAcks returns all the unreceived IBC acknowledgements associated with a -channel and sequences.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-
packet_ack_sequences
required
Array of strings <uint64> non-empty

list of acknowledgement sequences

-

Responses

UnreceivedPackets returns all the unreceived IBC packets associated with a -channel and sequences.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-
packet_commitment_sequences
required
Array of strings <uint64> non-empty

list of packet sequences

-

Responses

PacketCommitment queries a stored packet commitment hash.

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-
sequence
required
string <uint64>

packet sequence

-

Responses

Simulate simulates executing a transaction for estimating gas usage.

Request Body schema: application/json
object (cosmos.tx.v1beta1.Tx)

Tx is the standard type used for broadcasting transactions.

+
tx_bytes
string <byte>

tx_bytes is the raw transaction.

+

Since: cosmos-sdk 0.43

+

Responses

PacketReceipt queries if a given packet sequence has been received on the queried chain

path Parameters
channel_id
required
string

channel unique identifier

-
port_id
required
string

port unique identifier

-
sequence
required
string <uint64>

packet sequence

-

Responses

ConnectionChannels queries all the channels associated with a connection -end.

path Parameters
connection
required
string

connection unique identifier

-
query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin -querying the next page most efficiently. Only one of offset or key -should be set.

-
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. -It is less efficient than using key. Only one of offset or key should -be set.

-
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. -If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include -a count of the total number of items available for pagination in UIs. -count_total is only respected when offset is used. It is ignored when key -is set.

-

Responses

ClientParams queries all parameters of the ibc client.

Responses

ClientStates queries all the IBC light clients of a chain.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin -querying the next page most efficiently. Only one of offset or key -should be set.

-
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. -It is less efficient than using key. Only one of offset or key should -be set.

-
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. -If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include -a count of the total number of items available for pagination in UIs. -count_total is only respected when offset is used. It is ignored when key -is set.

-

Responses

ClientState queries an IBC light client.

path Parameters
client_id
required
string

client state unique identifier

-

Responses

ConsensusStates queries all the consensus state associated with a given -client.

path Parameters
client_id
required
string

client identifier

-
query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin -querying the next page most efficiently. Only one of offset or key -should be set.

-
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. -It is less efficient than using key. Only one of offset or key should -be set.

-
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. -If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include -a count of the total number of items available for pagination in UIs. -count_total is only respected when offset is used. It is ignored when key -is set.

-

Responses

ConsensusState queries a consensus state associated with a client state at -a given height.

path Parameters
client_id
required
string

client identifier

-
revision_number
required
string <uint64>

consensus state revision number

-
revision_height
required
string <uint64>

consensus state revision height

-
query Parameters
latest_height
boolean

latest_height overrrides the height field and queries the latest stored -ConsensusState.

-

Responses

ClientConnections queries the connection paths associated with a client -state.

path Parameters
client_id
required
string

client identifier associated with a connection

-

Responses

Connections queries all the IBC connections of a chain.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin +

Request samples

Content type
application/json
{
  • "tx":
    {
    },
  • "tx_bytes": "string"
}

GetTxsEvent fetches txs by event.

query Parameters
events
Array of strings

events is the list of transaction event type.

+
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin querying the next page most efficiently. Only one of offset or key should be set.

pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. @@ -1108,45 +1315,38 @@ be set.

pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include +

pagination.count_total
boolean

count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set.

+
pagination.reverse
boolean

reverse is set to true if results are to be returned in the descending order.

+

Since: cosmos-sdk 0.43

+
order_by
string
Default: "ORDER_BY_UNSPECIFIED"
Enum: "ORDER_BY_UNSPECIFIED" "ORDER_BY_ASC" "ORDER_BY_DESC"
    +
  • ORDER_BY_UNSPECIFIED: ORDER_BY_UNSPECIFIED specifies an unknown sorting order. OrderBy defaults to ASC in this case.
  • +
  • ORDER_BY_ASC: ORDER_BY_ASC defines ascending order
  • +
  • ORDER_BY_DESC: ORDER_BY_DESC defines descending order
  • +

Responses

Connection queries an IBC connection end.

path Parameters
connection_id
required
string

connection unique identifier

-

Responses

ConnectionClientState queries the client state associated with the -connection.

path Parameters
connection_id
required
string

connection identifier

-

Responses

ConnectionConsensusState queries the consensus state associated with the -connection.

path Parameters
connection_id
required
string

connection identifier

-
revision_number
required
string <uint64>
revision_height
required
string <uint64>

Responses

DenomTraces queries all denomination traces.

query Parameters
pagination.key
string <byte>

key is a value returned in PageResponse.next_key to begin -querying the next page most efficiently. Only one of offset or key -should be set.

-
pagination.offset
string <uint64>

offset is a numeric offset that can be used when key is unavailable. -It is less efficient than using key. Only one of offset or key should -be set.

-
pagination.limit
string <uint64>

limit is the total number of results to be returned in the result page. -If left empty it will default to a value to be set by each app.

-
pagination.count_total
boolean

count_total is set to true to indicate that the result set should include -a count of the total number of items available for pagination in UIs. -count_total is only respected when offset is used. It is ignored when key -is set.

-

Responses

BroadcastTx broadcast transaction.

Request Body schema: application/json
tx_bytes
string <byte>

tx_bytes is the raw transaction.

+
mode
string
Default: "BROADCAST_MODE_UNSPECIFIED"
Enum: "BROADCAST_MODE_UNSPECIFIED" "BROADCAST_MODE_BLOCK" "BROADCAST_MODE_SYNC" "BROADCAST_MODE_ASYNC"

BroadcastMode specifies the broadcast mode for the TxService.Broadcast RPC method.

+
    +
  • BROADCAST_MODE_UNSPECIFIED: zero-value for mode ordering
  • +
  • BROADCAST_MODE_BLOCK: BROADCAST_MODE_BLOCK defines a tx broadcasting mode where the client waits for +the tx to be committed in a block.
  • +
  • BROADCAST_MODE_SYNC: BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits for +a CheckTx execution response only.
  • +
  • BROADCAST_MODE_ASYNC: BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client returns +immediately.
  • +
+

Responses

DenomTrace queries a denomination trace information.

path Parameters
hash
required
string

hash (in hex format) of the denomination trace information.

+

Request samples

Content type
application/json
{
  • "tx_bytes": "string",
  • "mode": "BROADCAST_MODE_UNSPECIFIED"
}

GetTx fetches a tx by hash.

path Parameters
hash
required
string

hash is the tx hash to query, encoded as a hex string.

Responses

Params queries all parameters of the ibc-transfer module.

Responses

+