diff --git a/.golangci.yml b/.golangci.yml index 19d70d9e4c6..eecd8dd6d68 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,81 +10,55 @@ linters: enable: - asciicheck - bidichk - # - bodyclose <- needs go 1.18 support - # - contextcheck <- needs go 1.18 support - # - cyclop - depguard - # - dogsled <- disabled because we would like to participate in the iditerod - # - dupl <- really just catches cli stub text - durationcheck - errcheck - errname -# - errorlint <- later -# - exhaustive <- too picky - # - exhaustivestruct <- disabled because we don't want to use every element of every struct - exportloopref - # - forbidigo <- forbids fmt.Print* by default - forcetypeassert - # - funlen <- some of our functions are longer than this by necessity - # - gci <- questionable utility - # - gochecknoglobals <- disabled because we want some globals - # - gochecknoinits <- disabled because we want to use init() - # - gocognit <- disabled for same reason as gocyclo - goconst - # - gocritic <- re enable later to catch capitalized local variables - # - gocyclo <- disabled because it won't work with how we cosmos - # - godot - # - godox <- detects TODO/BUG/FIXME and we may wantnthis later but isn't appropriate now - # - goerr113 <- disabled due to lack of comprehension - - gofmt - # - gofumpt <- disabled https://github.com/osmosis-labs/osmosis/issues/1309 + - gocritic + - gofumpt - goheader - - goimports - # - gomoddirectives <- disables replaces - gomodguard - goprintffuncname -# - gosec <- triggers too much for this round and should be re-enabled later - - gosimple # specializes in simplifying code, subset of staticcheck binary. + - gosec + - gosimple - govet - # - ifshort <- questionable value, unclear if globally helping readability. - importas - ineffassign - # - ireturn <- disabled because we want to return interfaces - # - lll <- disabled as it is a bit much. Maybe we have a desired limit? - makezero - misspell - nakedret -# - nestif <- ? - # - nilerr <- needs go 1.18 support - nilnil - # - nlreturn <- disabled as it doesn't auto-fix something simple and doesn't add anything useful - # - noctx <- needs go 1.18 support - # - nolintlint <- disabled because we use nolint in some places + - nolintlint - paralleltest - # - prealloc <- disabled because it makes simple code complicated -# - predeclared <- later - promlinter -# - 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 # set of rules from staticcheck, subset of staticcheck binary. - - stylecheck # replacement of golint, subset of staticcheck binary. - # - tagliatelle <- disabled for defying cosmos idiom + - revive + - staticcheck + - stylecheck - tenv - testpackage -# - thelper <- later - # - tparallel <- needs go 1.18 support - typecheck - unconvert -# - unparam <- looks for unused parameters (enable later) - - unused # looks for unused variables, subset of staticcheck binary. - # - varnamelen <- disabled because defies idiom - # - wastedassign + - unparam + - unused - whitespace -# - wrapcheck -# - wsl issues: + exclude: + - "var-naming" + - "poolId should be poolID" + - "lockId should be lockID" + - "gaugeId should be gaugeID" + - "nodeNameToId should be nodeNameToID" + - "lastCommitId should be lastCommitID" + - "latestPoolId should be latestPoolID" + - "poolIDStr should be poolIDStr" + - "chainId should be chainID" + - "portId should be portID" + - "setNextPoolId should be setNextPoolID" + - "getNextPoolId should be getNextPoolID" exclude-rules: - path: bench_test\.go linters: @@ -92,24 +66,21 @@ 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 - linters: - - staticcheck + - staticcheck text: "SA1024: cutset contains duplicate characters" # proved to not provide much value, only false positives. - linters: - - staticcheck + - staticcheck text: "SA9004: only the first constant in this group has an explicit type" # explicitly recommended in go syntax - linters: - - stylecheck + - stylecheck text: "ST1003:" # requires identifiers with "id" to be "ID". - linters: - - stylecheck + - stylecheck + - revive text: "ST1005:" # punctuation in error messages + - linters: + - nolintlint + text: "should be written without leading space as" # conflicts with gofumpt max-issues-per-linter: 10000 max-same-issues: 10000 diff --git a/.vscode/settings.json b/.vscode/settings.json index 2c0a4eb2d63..4e0041d9573 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,7 @@ { "tabnine.experimentalAutoImports": true, "go.lintTool": "golangci-lint", - "go.formatTool": "goimports", + "go.formatTool": "gofumpt", "go.useLanguageServer": true, "[go.mod]": { "editor.formatOnSave": true, @@ -24,4 +24,4 @@ "editor.defaultFormatter": "xaver.clang-format" }, "clang-format.style": "{BasedOnStyle: Google, IndentWidth: 2, ColumnLimit: 120, AlignConsecutiveAssignments: true, AlignConsecutiveDeclarations: true, SpacesInSquareBrackets: true}" -} +} \ No newline at end of file diff --git a/app/app.go b/app/app.go index 002ed3816bf..25a2da3f4bf 100644 --- a/app/app.go +++ b/app/app.go @@ -51,7 +51,7 @@ import ( v7 "github.com/osmosis-labs/osmosis/v12/app/upgrades/v7" v8 "github.com/osmosis-labs/osmosis/v12/app/upgrades/v8" v9 "github.com/osmosis-labs/osmosis/v12/app/upgrades/v9" - _ "github.com/osmosis-labs/osmosis/v12/client/docs/statik" + _ "github.com/osmosis-labs/osmosis/v12/client/docs/statik" // imports statik file system for swagger UI support "github.com/osmosis-labs/osmosis/v12/simulation/simtypes" ) diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index cb0a02b0859..f01f095b828 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -47,7 +47,7 @@ import ( // IBC Transfer: Defines the "transfer" IBC port transfer "github.com/cosmos/ibc-go/v3/modules/apps/transfer" - _ "github.com/osmosis-labs/osmosis/v12/client/docs/statik" + _ "github.com/osmosis-labs/osmosis/v12/client/docs/statik" // Import statik for docs owasm "github.com/osmosis-labs/osmosis/v12/wasmbinding" epochskeeper "github.com/osmosis-labs/osmosis/v12/x/epochs/keeper" epochstypes "github.com/osmosis-labs/osmosis/v12/x/epochs/types" diff --git a/app/keepers/modules.go b/app/keepers/modules.go index 88f214644c7..7e5b050eaa4 100644 --- a/app/keepers/modules.go +++ b/app/keepers/modules.go @@ -27,7 +27,7 @@ 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/v12/client/docs/statik" + _ "github.com/osmosis-labs/osmosis/v12/client/docs/statik" // import statik for docs "github.com/osmosis-labs/osmosis/v12/x/epochs" "github.com/osmosis-labs/osmosis/v12/x/gamm" "github.com/osmosis-labs/osmosis/v12/x/incentives" diff --git a/app/modules.go b/app/modules.go index 3f9fe96c020..5deae77c8fd 100644 --- a/app/modules.go +++ b/app/modules.go @@ -41,7 +41,7 @@ import ( upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" appparams "github.com/osmosis-labs/osmosis/v12/app/params" - _ "github.com/osmosis-labs/osmosis/v12/client/docs/statik" + _ "github.com/osmosis-labs/osmosis/v12/client/docs/statik" // Import statik for docs "github.com/osmosis-labs/osmosis/v12/osmoutils/partialord" "github.com/osmosis-labs/osmosis/v12/simulation/simtypes" "github.com/osmosis-labs/osmosis/v12/x/epochs" @@ -217,7 +217,7 @@ func OrderInitGenesis(allModuleNames []string) []string { func createSimulationManager( app *OsmosisApp, encodingConfig appparams.EncodingConfig, - skipGenesisInvariants bool, + skipGenesisInvariants bool, //nolint:unparam ) *simtypes.Manager { appCodec := encodingConfig.Marshaler diff --git a/app/upgrades/v5/whitelist_feetokens.go b/app/upgrades/v5/whitelist_feetokens.go index e0a40202bbb..e9d4bf2ca94 100644 --- a/app/upgrades/v5/whitelist_feetokens.go +++ b/app/upgrades/v5/whitelist_feetokens.go @@ -17,7 +17,7 @@ import ( // We nolint because these are strings of whitelisted ibc denoms. // //nolint:gosec -var feetoken_whitelist_data = ` +var feetokenWhitelistData = ` ion,uion,2 atom,ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2,1 akt,ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4,3 @@ -43,7 +43,7 @@ boot,ibc/FE2CD1E6828EC0FAB8AF39BAC45BC25B965BA67CCBC50C13A14BD610B0D1E2C4,597 ` func InitialWhitelistedFeetokens(ctx sdk.Context, gamm *gammkeeper.Keeper) []types.FeeToken { - r := csv.NewReader(strings.NewReader(feetoken_whitelist_data)) + r := csv.NewReader(strings.NewReader(feetokenWhitelistData)) assets, err := r.ReadAll() if err != nil { panic(err) diff --git a/app/upgrades/v8/msg_filter_ante.go b/app/upgrades/v8/msg_filter_ante.go index 9ebc5ff5970..bf0d06e07fa 100644 --- a/app/upgrades/v8/msg_filter_ante.go +++ b/app/upgrades/v8/msg_filter_ante.go @@ -4,6 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + superfluidtypes "github.com/osmosis-labs/osmosis/v12/x/superfluid/types" ) @@ -26,7 +27,7 @@ func (mfd MsgFilterDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bo func hasInvalidMsgs(msgs []sdk.Msg) bool { for _, msg := range msgs { - switch msg.(type) { + switch msg.(type) { //nolint:gocritic // no reason to rewrite to an if statement case *superfluidtypes.MsgUnPoolWhitelistedPool: return true } diff --git a/app/upgrades/v9/msg_filter_ante.go b/app/upgrades/v9/msg_filter_ante.go index b6035b35976..af461154c34 100644 --- a/app/upgrades/v9/msg_filter_ante.go +++ b/app/upgrades/v9/msg_filter_ante.go @@ -25,7 +25,7 @@ func (mfd MsgFilterDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bo func hasInvalidMsgs(msgs []sdk.Msg) bool { for _, msg := range msgs { - switch msg.(type) { + switch msg.(type) { //nolint:gocritic // no reason to rewrite to an if statement. case *ibcchanneltypes.MsgTimeoutOnClose: return true } diff --git a/cmd/osmosisd/cmd/balances_from_state_export.go b/cmd/osmosisd/cmd/balances_from_state_export.go index 2ed9dbd113e..39f90b44d82 100644 --- a/cmd/osmosisd/cmd/balances_from_state_export.go +++ b/cmd/osmosisd/cmd/balances_from_state_export.go @@ -293,7 +293,7 @@ Example: return fmt.Errorf("failed to marshal snapshot: %w", err) } - err = os.WriteFile(snapshotOutput, snapshotJSON, 0o644) + err = os.WriteFile(snapshotOutput, snapshotJSON, 0o600) return err }, } diff --git a/cmd/osmosisd/cmd/forceprune.go b/cmd/osmosisd/cmd/forceprune.go index eb032e915a3..4e70e09350f 100644 --- a/cmd/osmosisd/cmd/forceprune.go +++ b/cmd/osmosisd/cmd/forceprune.go @@ -21,9 +21,9 @@ import ( const ( batchMaxSize = 1000 - kValidators = "validatorsKey:" - kConsensusParams = "consensusParamsKey:" - kABCIResponses = "abciResponsesKey:" + Validators = "validatorsKey:" + ConsensusParams = "consensusParamsKey:" + ABCIResponses = "abciResponsesKey:" fullHeight = "full_height" minHeight = "min_height" defaultFullHeight = "188000" @@ -102,15 +102,14 @@ func pruneBlockStoreAndGetHeights(dbPath string, fullHeight int64) ( DisableSeeksCompaction: true, } - db_bs, err := tmdb.NewGoLevelDBWithOpts("blockstore", dbPath, &opts) + blockstore, err := tmdb.NewGoLevelDBWithOpts("blockstore", dbPath, &opts) if err != nil { return 0, 0, err } - // nolint: staticcheck - defer db_bs.Close() + defer blockstore.Close() - bs := tmstore.NewBlockStore(db_bs) + bs := tmstore.NewBlockStore(blockstore) startHeight = bs.Base() currentHeight = bs.Height() @@ -125,7 +124,7 @@ func pruneBlockStoreAndGetHeights(dbPath string, fullHeight int64) ( // 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 { + if err := blockstore.Close(); err != nil { return 0, 0, err } @@ -165,24 +164,24 @@ func forcepruneStateStore(dbPath string, startHeight, currentHeight, minHeight, } defer db.Close() - stateDBKeys := []string{kValidators, kConsensusParams, kABCIResponses} + stateDBKeys := []string{Validators, ConsensusParams, ABCIResponses} fmt.Println("Pruning State Store ...") for i, s := range stateDBKeys { fmt.Println(i, s) - retain_height := int64(0) - if s == kABCIResponses { - retain_height = currentHeight - minHeight + retainHeight := int64(0) + if s == ABCIResponses { + retainHeight = currentHeight - minHeight } else { - retain_height = currentHeight - fullHeight + retainHeight = currentHeight - fullHeight } batch := new(leveldb.Batch) curBatchSize := uint64(0) - fmt.Println(startHeight, currentHeight, retain_height) + fmt.Println(startHeight, currentHeight, retainHeight) - for c := startHeight; c < retain_height; c++ { + for c := startHeight; c < retainHeight; c++ { batch.Delete([]byte(s + strconv.FormatInt(c, 10))) curBatchSize++ diff --git a/cmd/osmosisd/cmd/genesis.go b/cmd/osmosisd/cmd/genesis.go index fc445cc1c64..590d57e383e 100644 --- a/cmd/osmosisd/cmd/genesis.go +++ b/cmd/osmosisd/cmd/genesis.go @@ -34,8 +34,6 @@ import ( ) // PrepareGenesisCmd returns prepare-genesis cobra Command. -// -//nolint:ineffassign func PrepareGenesisCmd(defaultNodeHome string, mbm module.BasicManager) *cobra.Command { cmd := &cobra.Command{ Use: "prepare-genesis", @@ -67,7 +65,7 @@ Example: // get genesis params var genesisParams GenesisParams network := args[0] - if network == "testnet" { + if network == "testnet" { //nolint:gocritic // no reason to rewrite this into a switch statement. genesisParams = TestnetGenesisParams() } else if network == "mainnet" { genesisParams = MainnetGenesisParams() diff --git a/cmd/osmosisd/cmd/testnet.go b/cmd/osmosisd/cmd/testnet.go index 81aaacc8086..f8eb203ca59 100644 --- a/cmd/osmosisd/cmd/testnet.go +++ b/cmd/osmosisd/cmd/testnet.go @@ -392,7 +392,7 @@ func calculateIP(ip string, i int) (string, error) { } func writeFile(name string, dir string, contents []byte) error { - writePath := filepath.Join(dir) + writePath := filepath.Join(dir) //nolint:gocritic file := filepath.Join(writePath, name) err := tmos.EnsureDir(writePath, 0o755) diff --git a/osmomath/math.go b/osmomath/math.go index d8f341bb605..c36d08dfbe6 100644 --- a/osmomath/math.go +++ b/osmomath/math.go @@ -11,13 +11,13 @@ import ( var powPrecision, _ = sdk.NewDecFromStr("0.00000001") // Singletons. -// nolint: deadcode, unused +// nolint: unused var zero sdk.Dec = sdk.ZeroDec() var ( - one_half sdk.Dec = sdk.MustNewDecFromStr("0.5") - one sdk.Dec = sdk.OneDec() - two sdk.Dec = sdk.MustNewDecFromStr("2") + oneHalf sdk.Dec = sdk.MustNewDecFromStr("0.5") + one sdk.Dec = sdk.OneDec() + two sdk.Dec = sdk.MustNewDecFromStr("2") ) // Returns the internal "power precision". @@ -37,9 +37,8 @@ func GetPowPrecision() sdk.Dec { func AbsDifferenceWithSign(a, b sdk.Dec) (sdk.Dec, bool) { if a.GTE(b) { return a.SubMut(b), false - } else { - return a.NegMut().AddMut(b), true } + return a.NegMut().AddMut(b), true } // func largeBasePow(base sdk.Dec, exp sdk.Dec) sdk.Dec { @@ -94,7 +93,7 @@ func PowApprox(base sdk.Dec, exp sdk.Dec, precision sdk.Dec) sdk.Dec { // Common case optimization // Optimize for it being equal to one-half - if exp.Equal(one_half) { + if exp.Equal(oneHalf) { output, err := base.ApproxSqrt() if err != nil { panic(err) diff --git a/osmomath/sigfig_round.go b/osmomath/sigfig_round.go index be845fb1aff..93c994371ad 100644 --- a/osmomath/sigfig_round.go +++ b/osmomath/sigfig_round.go @@ -15,7 +15,7 @@ func SigFigRound(d sdk.Dec, tenToSigFig sdk.Int) sdk.Dec { // take note of floor div, vs normal div k := uint64(0) dTimesK := d - for ; dTimesK.LT(pointOne); k += 1 { + for ; dTimesK.LT(pointOne); k++ { dTimesK.MulInt64Mut(10) } // d * 10^k * 10^sigfig diff --git a/osmoutils/binary_search.go b/osmoutils/binary_search.go index 9d3e247dce8..046c2d94ce8 100644 --- a/osmoutils/binary_search.go +++ b/osmoutils/binary_search.go @@ -73,9 +73,9 @@ func BinarySearch(f func(input sdk.Int) (sdk.Int, error), return sdk.Int{}, err } curIteration := 0 - for ; curIteration < maxIterations; curIteration += 1 { + for ; curIteration < maxIterations; curIteration++ { compRes := errTolerance.Compare(curOutput, targetOutput) - if compRes > 0 { + if compRes > 0 { //nolint:gocritic // no need to use switch here upperbound = curEstimate } else if compRes < 0 { lowerbound = curEstimate diff --git a/osmoutils/partialord/partialord.go b/osmoutils/partialord/partialord.go index 5428e70f5c6..f0be0ed8910 100644 --- a/osmoutils/partialord/partialord.go +++ b/osmoutils/partialord/partialord.go @@ -35,16 +35,16 @@ func handleDAGErr(err error) { } // After marks that A should come after B -func (ord *PartialOrdering) After(A string, B string) { +func (ord *PartialOrdering) After(a string, b string) { // Set that A depends on B / an edge from B -> A - err := ord.dag.AddEdge(B, A) + err := ord.dag.AddEdge(b, a) handleDAGErr(err) } // After marks that A should come before B -func (ord *PartialOrdering) Before(A string, B string) { +func (ord *PartialOrdering) Before(a string, b string) { // Set that B depends on A / an edge from A -> B - err := ord.dag.AddEdge(A, B) + err := ord.dag.AddEdge(a, b) handleDAGErr(err) } diff --git a/simulation/executor/event_stats.go b/simulation/executor/event_stats.go index 2ee2af76657..c8b599e4605 100644 --- a/simulation/executor/event_stats.go +++ b/simulation/executor/event_stats.go @@ -54,10 +54,10 @@ func (es EventStats) ExportJSON(path string) { } } -func (es EventStats) exportEvents(ExportStatsPath string, w io.Writer) { - if ExportStatsPath != "" { - fmt.Printf("Exporting simulation statistics to %s...", ExportStatsPath) - es.ExportJSON(ExportStatsPath) +func (es EventStats) exportEvents(exportStatsPath string, w io.Writer) { + if exportStatsPath != "" { + 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/mock_tendermint.go b/simulation/executor/mock_tendermint.go index 6e21f7da8ea..8527fad5431 100644 --- a/simulation/executor/mock_tendermint.go +++ b/simulation/executor/mock_tendermint.go @@ -215,7 +215,7 @@ func randomVoteInfos(r *rand.Rand, simParams Params, validators mockValidators, } func randomDoubleSignEvidence(r *rand.Rand, params Params, - validators mockValidators, pastTimes []time.Time, + validators mockValidators, pastTimes []time.Time, //nolint:unparam pastVoteInfos [][]abci.VoteInfo, event func(route, op, evResult string), header tmproto.Header, voteInfos []abci.VoteInfo, ) []abci.Evidence { diff --git a/simulation/executor/simulate.go b/simulation/executor/simulate.go index 268d6600be9..d7db8415a32 100644 --- a/simulation/executor/simulate.go +++ b/simulation/executor/simulate.go @@ -120,7 +120,7 @@ func cursedInitializationLogic( ) (*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)) + r := rand.New(rand.NewSource(config.Seed)) //nolint:gosec simParams := RandomParams(r) fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(simParams)) diff --git a/simulation/executor/stats_db.go b/simulation/executor/stats_db.go index ed2e208c769..f8bc7fac377 100644 --- a/simulation/executor/stats_db.go +++ b/simulation/executor/stats_db.go @@ -5,7 +5,7 @@ import ( "embed" "fmt" - _ "github.com/mattn/go-sqlite3" + _ "github.com/mattn/go-sqlite3" // sqlite3 import for simulation tests "github.com/cosmos/cosmos-sdk/types/simulation" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" diff --git a/simulation/executor/util.go b/simulation/executor/util.go index 6ac79e465a5..fe6d41f9966 100644 --- a/simulation/executor/util.go +++ b/simulation/executor/util.go @@ -8,7 +8,7 @@ import ( "github.com/osmosis-labs/osmosis/v12/simulation/simtypes" ) -func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) { +func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) { //nolint:unparam testingMode = false if _t, ok := tb.(*testing.T); ok { diff --git a/simulation/simtypes/account.go b/simulation/simtypes/account.go index 9b375bf52da..5d43ab4c582 100644 --- a/simulation/simtypes/account.go +++ b/simulation/simtypes/account.go @@ -46,7 +46,7 @@ func (sim *SimCtx) RandomSimAccountWithMinCoins(ctx sdk.Context, coins sdk.Coins } acc, found := sim.RandomSimAccountWithConstraint(accHasMinCoins) if !found { - return simulation.Account{}, errors.New("no address with min balance found.") + return simulation.Account{}, errors.New("no address with min balance found") } return acc, nil } @@ -81,7 +81,7 @@ func (sim *SimCtx) RandomSimAccountWithBalance(ctx sdk.Context) (simulation.Acco } 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 simulation.Account{}, errors.New("no address with balance found. Check simulator configuration, this should be very rare") } return acc, nil } diff --git a/simulation/simtypes/action.go b/simulation/simtypes/action.go index bd29ad06749..f9ff07bfc01 100644 --- a/simulation/simtypes/action.go +++ b/simulation/simtypes/action.go @@ -28,7 +28,7 @@ type Action interface { WithFrequency(w Frequency) Action } -type selectActionFn func(r *rand.Rand) ActionsWithMetadata +type SelectActionFn func(r *rand.Rand) ActionsWithMetadata type weightedOperationAction struct { moduleName string @@ -99,7 +99,7 @@ func (m msgBasedAction) WithFrequency(w Frequency) Action { m.frequency = w; ret 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, resultData []byte, err error, + operationMsg simulation.OperationMsg, futureOps []simulation.FutureOperation, resultData []byte, err error, ) { msg, err := m.msgGenerator(sim, ctx) if err != nil { @@ -125,7 +125,7 @@ func totalFrequency(actions []ActionsWithMetadata) int { return totalFrequency } -func GetSelectActionFn(actions []ActionsWithMetadata) selectActionFn { +func GetSelectActionFn(actions []ActionsWithMetadata) SelectActionFn { totalOpFrequency := totalFrequency(actions) return func(r *rand.Rand) ActionsWithMetadata { diff --git a/simulation/simtypes/manager.go b/simulation/simtypes/manager.go index 8ddf60146c1..49c55cffaac 100644 --- a/simulation/simtypes/manager.go +++ b/simulation/simtypes/manager.go @@ -106,7 +106,7 @@ func (m Manager) legacyActions(seed int64, cdc codec.JSONCodec) []ActionsWithMet Cdc: cdc, } - r := rand.New(rand.NewSource(seed)) + r := rand.New(rand.NewSource(seed)) //nolint:gosec // first pass generate randomized params + proposal contents for _, moduleName := range m.moduleManager.OrderInitGenesis { if simModule, ok := m.legacyModules[moduleName]; ok { diff --git a/simulation/simtypes/random/sdkrand.go b/simulation/simtypes/random/sdkrand.go index 89c950ef346..99c7df659b7 100644 --- a/simulation/simtypes/random/sdkrand.go +++ b/simulation/simtypes/random/sdkrand.go @@ -150,7 +150,7 @@ func DeriveRand(r *rand.Rand) *rand.Rand { ms[i] = rand.NewSource(r.Int63()) } - return rand.New(ms) + return rand.New(ms) //nolint:gosec } type multiSource []rand.Source diff --git a/simulation/simtypes/simctx.go b/simulation/simtypes/simctx.go index 0a26a652520..9eb995ddf77 100644 --- a/simulation/simtypes/simctx.go +++ b/simulation/simtypes/simctx.go @@ -138,13 +138,13 @@ func (rm *randManager) WrapRand(domainSeparator string) randManager { sepInt := stringToSeed(domainSeparator) newSeed := rm.internalSeed + sepInt - r := rand.New(rand.NewSource(newSeed)) + r := rand.New(rand.NewSource(newSeed)) //nolint:gosec return newRandManager(r) } func (rm *randManager) GetRand() *rand.Rand { - rm.rCounter += 1 - r := rand.New(rand.NewSource(rm.internalSeed + rm.rCounter)) + rm.rCounter++ + r := rand.New(rand.NewSource(rm.internalSeed + rm.rCounter)) //nolint:gosec return r } @@ -156,7 +156,7 @@ func (rm *randManager) GetSeededRand(seed string) *rand.Rand { } seedInt := stringToSeed(seed) newSeed := rm.internalSeed + seedInt - r := rand.New(rand.NewSource(newSeed)) + r := rand.New(rand.NewSource(newSeed)) //nolint:gosec rm.seededMap[seed] = r return r } diff --git a/simulation/simtypes/txbuilder.go b/simulation/simtypes/txbuilder.go index 73aab81db19..88e89308d2a 100644 --- a/simulation/simtypes/txbuilder.go +++ b/simulation/simtypes/txbuilder.go @@ -54,7 +54,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, []byte, error) { +func (sim *SimCtx) deliverTx(tx sdk.Tx, msg sdk.Msg, msgName string) (simulation.OperationMsg, []simulation.FutureOperation, []byte, error) { //nolint:unparam // this is a test txConfig := params.MakeEncodingConfig().TxConfig // TODO: unhardcode gasInfo, results, err := sim.BaseApp().Deliver(txConfig.TxEncoder(), tx) if err != nil { @@ -112,7 +112,6 @@ func genTx(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, ch if err != nil { panic(err) } - //nolint:forcetypeassert sigs[i] = sig err = txBuilder.SetSignatures(sigs...) if err != nil { diff --git a/store/node.go b/store/node.go index 5f1629508ca..4bbb28c2b33 100644 --- a/store/node.go +++ b/store/node.go @@ -243,7 +243,7 @@ func (node *Node) setAcc(idx int, acc sdk.Int) *Node { } func (node *Node) insert(idx int, c *Child) *Node { - arr := append(node.Children[:idx], append([]*Child{c}, node.Children[idx:]...)...) + arr := append(node.Children[:idx], append([]*Child{c}, node.Children[idx:]...)...) //nolint:gocritic return NewNode(arr...) } diff --git a/tests/e2e/configurer/base.go b/tests/e2e/configurer/base.go index 6ce67da251d..3c5dd3d1818 100644 --- a/tests/e2e/configurer/base.go +++ b/tests/e2e/configurer/base.go @@ -122,7 +122,7 @@ func (bc *baseConfigurer) runIBCRelayer(chainConfigA *chain.Config, chainConfigB endpoint := fmt.Sprintf("http://%s/state", hermesResource.GetHostPort("3031/tcp")) require.Eventually(bc.t, func() bool { - resp, err := http.Get(endpoint) + resp, err := http.Get(endpoint) //nolint:gosec // this is a test if err != nil { return false } diff --git a/tests/e2e/configurer/chain/chain.go b/tests/e2e/configurer/chain/chain.go index fb39b752d60..d26e7a82f10 100644 --- a/tests/e2e/configurer/chain/chain.go +++ b/tests/e2e/configurer/chain/chain.go @@ -153,9 +153,8 @@ func (c *Config) SendIBC(dstChain *Config, recipient string, token sdk.Coin) { resPre := initialization.OsmoToken.Amount resPost := tokenPost.Sub(tokenPre) return resPost.Uint64() == resPre.Uint64() - } else { - return false } + return false }, 5*time.Minute, time.Second, @@ -169,7 +168,7 @@ func (c *Config) EnableSuperfluidAsset(denom string) { chain, err := c.GetDefaultNode() require.NoError(c.t, err) chain.SubmitSuperfluidProposal(denom, sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.InitialMinDeposit))) - c.LatestProposalNumber += 1 + c.LatestProposalNumber++ chain.DepositProposal(c.LatestProposalNumber, false) for _, node := range c.NodeConfigs { node.VoteYesProposal(initialization.ValidatorWalletName, c.LatestProposalNumber) @@ -182,13 +181,13 @@ func (c *Config) LockAndAddToExistingLock(amount sdk.Int, denom, lockupWalletAdd // lock tokens chain.LockTokens(fmt.Sprintf("%v%s", amount, denom), "240s", lockupWalletAddr) - c.LatestLockNumber += 1 + c.LatestLockNumber++ // add to existing lock chain.AddToExistingLock(amount, denom, "240s", lockupWalletAddr) // superfluid lock tokens chain.LockTokens(fmt.Sprintf("%v%s", amount, denom), "240s", lockupWalletSuperfluidAddr) - c.LatestLockNumber += 1 + c.LatestLockNumber++ chain.SuperfluidDelegate(c.LatestLockNumber, c.NodeConfigs[1].OperatorAddress, lockupWalletSuperfluidAddr) // add to existing lock chain.AddToExistingLock(amount, denom, "240s", lockupWalletSuperfluidAddr) diff --git a/tests/e2e/configurer/factory.go b/tests/e2e/configurer/factory.go index a9a80f8a9d8..2b86465fcc6 100644 --- a/tests/e2e/configurer/factory.go +++ b/tests/e2e/configurer/factory.go @@ -111,7 +111,7 @@ func New(t *testing.T, isIBCEnabled, isDebugLogEnabled bool, upgradeSettings Upg return nil, err } - if isIBCEnabled && upgradeSettings.IsEnabled { + if isIBCEnabled && upgradeSettings.IsEnabled { //nolint:gocritic // no reason to rewrite this to a switch statement. // skip none - configure two chains via Docker // to utilize the older version of osmosis to upgrade from return NewUpgradeConfigurer(t, diff --git a/tests/e2e/configurer/upgrade.go b/tests/e2e/configurer/upgrade.go index e0345bc1be8..cc91e6fffc2 100644 --- a/tests/e2e/configurer/upgrade.go +++ b/tests/e2e/configurer/upgrade.go @@ -67,7 +67,7 @@ func (uc *UpgradeConfigurer) ConfigureChain(chainConfig *chain.Config) error { forkHeight := uc.forkHeight if forkHeight > 0 { - forkHeight = forkHeight - config.ForkHeightPreUpgradeOffset + forkHeight -= config.ForkHeightPreUpgradeOffset } chainInitResource, err := uc.containerManager.RunChainInitResource(chainConfig.Id, int(chainConfig.VotingPeriod), int(chainConfig.ExpeditedVotingPeriod), validatorConfigBytes, tmpDir, int(forkHeight)) @@ -162,7 +162,7 @@ func (uc *UpgradeConfigurer) runProposalUpgrade() error { currentHeight := node.QueryCurrentHeight() chainConfig.UpgradePropHeight = currentHeight + int64(chainConfig.VotingPeriod) + int64(config.PropSubmitBlocks) + int64(config.PropBufferBlocks) node.SubmitUpgradeProposal(uc.upgradeVersion, chainConfig.UpgradePropHeight, sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewInt(config.InitialMinDeposit))) - chainConfig.LatestProposalNumber += 1 + chainConfig.LatestProposalNumber++ node.DepositProposal(chainConfig.LatestProposalNumber, false) } node.VoteYesProposal(initialization.ValidatorWalletName, chainConfig.LatestProposalNumber) diff --git a/tests/e2e/containers/containers.go b/tests/e2e/containers/containers.go index a402eb2b468..0365a87a50a 100644 --- a/tests/e2e/containers/containers.go +++ b/tests/e2e/containers/containers.go @@ -58,7 +58,7 @@ func NewManager(isUpgrade bool, isFork bool, isDebugLogEnabled bool) (docker *Ma // and searching for `code: 0` 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...) + txCommand := append(command, allTxArgs...) //nolint:gocritic successStr := "code: 0" return m.ExecCmd(t, containerName, txCommand, successStr) } diff --git a/tests/e2e/initialization/chain.go b/tests/e2e/initialization/chain.go index 690503b78a5..b37e4fbd4d6 100644 --- a/tests/e2e/initialization/chain.go +++ b/tests/e2e/initialization/chain.go @@ -12,7 +12,7 @@ type internalChain struct { nodes []*internalNode } -func new(id, dataDir string) (*internalChain, error) { +func new(id, dataDir string) (*internalChain, error) { //nolint // this is a test and it is testing when error is nil chainMeta := ChainMeta{ Id: id, DataDir: dataDir, diff --git a/tests/e2e/initialization/chain/main.go b/tests/e2e/initialization/chain/main.go index 7704b2ebd96..c9a273c8016 100644 --- a/tests/e2e/initialization/chain/main.go +++ b/tests/e2e/initialization/chain/main.go @@ -50,7 +50,7 @@ func main() { b, _ := json.Marshal(createdChain) fileName := fmt.Sprintf("%v/%v-encode", dataDir, chainId) - if err = os.WriteFile(fileName, b, 0o777); err != nil { + if err = os.WriteFile(fileName, b, 0o777); err != nil { //nolint:gosec panic(err) } } diff --git a/tests/e2e/initialization/config.go b/tests/e2e/initialization/config.go index adb86b44c34..67e4f166a98 100644 --- a/tests/e2e/initialization/config.go +++ b/tests/e2e/initialization/config.go @@ -158,7 +158,6 @@ func addAccount(path, moniker, amountStr string, accAddr sdk.AccAddress, forkHei return genutil.ExportGenesisFile(genDoc, genFile) } -//nolint:typecheck func updateModuleGenesis[V proto.Message](appGenState map[string]json.RawMessage, moduleName string, protoVal V, updateGenesis func(V)) error { if err := util.Cdc.UnmarshalJSON(appGenState[moduleName], protoVal); err != nil { return err diff --git a/wasmbinding/message_plugin.go b/wasmbinding/message_plugin.go index cf87fe65143..b0e9d615f98 100644 --- a/wasmbinding/message_plugin.go +++ b/wasmbinding/message_plugin.go @@ -217,7 +217,7 @@ func PerformSwap(keeper *gammkeeper.Keeper, ctx sdk.Context, contractAddr sdk.Ac if swap == nil { return nil, wasmvmtypes.InvalidRequest{Err: "gamm perform swap null swap"} } - if swap.Amount.ExactIn != nil { + if swap.Amount.ExactIn != nil { //nolint:gocritic // no reason to rewrite into a switch statement routes := []gammtypes.SwapAmountInRoute{{ PoolId: swap.First.PoolId, TokenOutDenom: swap.First.DenomOut, diff --git a/x/epochs/keeper/abci.go b/x/epochs/keeper/abci.go index dcf62ad8940..0165cd3ac9e 100644 --- a/x/epochs/keeper/abci.go +++ b/x/epochs/keeper/abci.go @@ -44,7 +44,7 @@ func (k Keeper) BeginBlocker(ctx sdk.Context) { ), ) k.AfterEpochEnd(ctx, epochInfo.Identifier, epochInfo.CurrentEpoch) - epochInfo.CurrentEpoch += 1 + epochInfo.CurrentEpoch++ epochInfo.CurrentEpochStartTime = epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration) logger.Info(fmt.Sprintf("Starting epoch with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) } diff --git a/x/gamm/client/cli/query.go b/x/gamm/client/cli/query.go index 28cb7f8ffbc..f9282f55fc9 100644 --- a/x/gamm/client/cli/query.go +++ b/x/gamm/client/cli/query.go @@ -226,15 +226,14 @@ $ %s query gamm pool-params 1 if err != nil { return err } - return writeOutputBoilerplate(clientCtx, out) - } else { - out, err := clientCtx.Codec.MarshalJSON(res) - if err != nil { - return err - } - return writeOutputBoilerplate(clientCtx, out) } + out, err := clientCtx.Codec.MarshalJSON(res) + if err != nil { + return err + } + + return writeOutputBoilerplate(clientCtx, out) }, } diff --git a/x/gamm/module.go b/x/gamm/module.go index 907db5b90ec..d4ac8f31730 100644 --- a/x/gamm/module.go +++ b/x/gamm/module.go @@ -2,11 +2,10 @@ 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 + - 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/pool.go b/x/gamm/pool-models/balancer/pool.go index 510502d8ee5..21eb8f6cf9f 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -125,17 +125,17 @@ func (p *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 (p *Pool) SetInitialPoolAssets(PoolAssets []PoolAsset) error { +func (p *Pool) SetInitialPoolAssets(poolAssets []PoolAsset) error { exists := make(map[string]bool) for _, asset := range p.PoolAssets { exists[asset.Token.Denom] = true } newTotalWeight := p.TotalWeight - scaledPoolAssets := make([]PoolAsset, 0, len(PoolAssets)) + scaledPoolAssets := make([]PoolAsset, 0, len(poolAssets)) // TODO: Refactor this into PoolAsset.validate() - for _, asset := range PoolAssets { + for _, asset := range poolAssets { if asset.Token.Amount.LTE(sdk.ZeroInt()) { return fmt.Errorf("can't add the zero or negative balance of token") } @@ -244,34 +244,34 @@ func (p Pool) getPoolAssetAndIndex(denom string) (int, PoolAsset, error) { } func (p Pool) parsePoolAssetsByDenoms(tokenADenom, tokenBDenom string) ( - Aasset PoolAsset, Basset PoolAsset, err error, + assetA PoolAsset, assetB PoolAsset, err error, ) { - Aasset, found1 := getPoolAssetByDenom(p.PoolAssets, tokenADenom) - Basset, found2 := getPoolAssetByDenom(p.PoolAssets, tokenBDenom) + assetA, found1 := getPoolAssetByDenom(p.PoolAssets, tokenADenom) + assetB, 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 assetA, assetB, errors.New("one of the provided pool denoms does not exist in pool") } - return Aasset, Basset, nil + return assetA, assetB, nil } func (p Pool) parsePoolAssets(tokensA sdk.Coins, tokenBDenom string) ( - tokenA sdk.Coin, Aasset PoolAsset, Basset PoolAsset, err error, + tokenA sdk.Coin, assetA PoolAsset, assetB PoolAsset, err error, ) { if len(tokensA) != 1 { - return tokenA, Aasset, Basset, errors.New("expected tokensB to be of length one") + return tokenA, assetA, assetB, errors.New("expected tokensB to be of length one") } - Aasset, Basset, err = p.parsePoolAssetsByDenoms(tokensA[0].Denom, tokenBDenom) - return tokensA[0], Aasset, Basset, err + assetA, assetB, err = p.parsePoolAssetsByDenoms(tokensA[0].Denom, tokenBDenom) + return tokensA[0], assetA, assetB, err } func (p Pool) parsePoolAssetsCoins(tokensA sdk.Coins, tokensB sdk.Coins) ( - Aasset PoolAsset, Basset PoolAsset, err error, + assetA PoolAsset, assetB PoolAsset, err error, ) { if len(tokensB) != 1 { - return Aasset, Basset, errors.New("expected tokensA to be of length one") + return assetA, assetB, errors.New("expected tokensA to be of length one") } - _, Aasset, Basset, err = p.parsePoolAssets(tokensA, tokensB[0].Denom) - return Aasset, Basset, err + _, assetA, assetB, err = p.parsePoolAssets(tokensA, tokensB[0].Denom) + return assetA, assetB, err } func (p *Pool) IncreaseLiquidity(sharesOut sdk.Int, coinsIn sdk.Coins) { diff --git a/x/gamm/pool-models/stableswap/amm.go b/x/gamm/pool-models/stableswap/amm.go index 30c92620841..903fe9e27ba 100644 --- a/x/gamm/pool-models/stableswap/amm.go +++ b/x/gamm/pool-models/stableswap/amm.go @@ -15,6 +15,8 @@ var ( ) // solidly CFMM is xy(x^2 + y^2) = k +// +//nolint:unused func cfmmConstant(xReserve, yReserve sdk.Dec) sdk.Dec { if !xReserve.IsPositive() || !yReserve.IsPositive() { panic("invalid input: reserves must be positive") @@ -30,6 +32,8 @@ 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:unused func cfmmConstantMulti(xReserve, yReserve, uReserve, vSumSquares sdk.Dec) sdk.Dec { if !xReserve.IsPositive() || !yReserve.IsPositive() || !uReserve.IsPositive() || vSumSquares.IsNegative() { panic("invalid input: reserves must be positive") @@ -171,6 +175,8 @@ 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:unused func solveCfmmMulti(xReserve, yReserve, wSumSquares, yIn sdk.Dec) sdk.Dec { if !xReserve.IsPositive() || !yReserve.IsPositive() || !yIn.IsPositive() { panic("invalid input: reserves and input must be positive") @@ -275,11 +281,13 @@ func solveCfmmMulti(xReserve, yReserve, wSumSquares, yIn sdk.Dec) sdk.Dec { return a } +//nolint:unused func approxDecEqual(a, b, tol sdk.Dec) bool { diff := a.Sub(b).Abs() return diff.Quo(a).LTE(tol) && diff.Quo(b).LTE(tol) } +//nolint:unused var ( twodec = sdk.MustNewDecFromStr("2.0") threshold = sdk.NewDecWithPrec(1, 10) // Correct within a factor of 1 * 10^{-10} @@ -287,6 +295,8 @@ var ( // solveCFMMBinarySearch searches the correct dx using binary search over constant K. // added for future extension +// +//nolint:unused 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) @@ -310,6 +320,8 @@ 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:unused 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) @@ -352,6 +364,8 @@ func spotPrice(baseReserve, quoteReserve sdk.Dec) sdk.Dec { } // returns outAmt as a decimal +// +//nolint:unparam 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 { @@ -365,7 +379,7 @@ func (p *Pool) calcOutAmtGivenIn(tokenIn sdk.Coin, tokenOutDenom string, swapFee } // returns inAmt as a decimal -func (p *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, swapFee sdk.Dec) (sdk.Dec, error) { +func (p *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, swapFee sdk.Dec) (sdk.Dec, error) { //nolint:unparam reserves, err := p.getScaledPoolAmts(tokenInDenom, tokenOut.Denom) if err != nil { return sdk.Dec{}, err @@ -378,7 +392,7 @@ func (p *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, swapFee return inAmt, nil } -func (p *Pool) calcSingleAssetJoinShares(tokenIn sdk.Coin, swapFee sdk.Dec) (sdk.Int, error) { +func (p *Pool) calcSingleAssetJoinShares(tokenIn sdk.Coin, swapFee sdk.Dec) (sdk.Int, error) { //nolint:unparam poolWithAddedLiquidityAndShares := func(newLiquidity sdk.Coin, newShares sdk.Int) types.PoolI { paCopy := p.Copy() paCopy.updatePoolForJoin(sdk.NewCoins(tokenIn), newShares) diff --git a/x/gamm/pool-models/stableswap/pool.go b/x/gamm/pool-models/stableswap/pool.go index 464c7a569eb..7ea921186b3 100644 --- a/x/gamm/pool-models/stableswap/pool.go +++ b/x/gamm/pool-models/stableswap/pool.go @@ -94,7 +94,9 @@ 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 +// getPoolAmts returns pool liquidity of the provided denoms, in the same order the denoms were provided in +// +//nolint:unused func (p Pool) getPoolAmts(denoms ...string) ([]sdk.Int, error) { result := make([]sdk.Int, len(denoms)) poolLiquidity := p.PoolLiquidity diff --git a/x/gamm/simulation/sim_msgs.go b/x/gamm/simulation/sim_msgs.go index 7ceebefe190..14d12cf9241 100644 --- a/x/gamm/simulation/sim_msgs.go +++ b/x/gamm/simulation/sim_msgs.go @@ -399,7 +399,7 @@ func deriveRealMinShareOutAmt(ctx sdk.Context, tokenIn sdk.Coins, pool types.Poo return minShareOutAmt, nil } -func createPoolRestriction(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) simtypes.SimAccountConstraint { +func createPoolRestriction(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) simtypes.SimAccountConstraint { //nolint:unparam return func(acc legacysimulationtype.Account) bool { accCoins := sim.BankKeeper().SpendableCoins(ctx, acc.Address) hasTwoCoins := len(accCoins) >= 2 diff --git a/x/incentives/client/cli/query.go b/x/incentives/client/cli/query.go index 3e3e058403a..8d4d5cc888b 100644 --- a/x/incentives/client/cli/query.go +++ b/x/incentives/client/cli/query.go @@ -391,7 +391,7 @@ $ %s query incentives rewards-estimation } // 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 == "" { + if lockIdsCombined == "" && owner == "" { //nolint:gocritic // no reason to rewrite to switch statement. 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 diff --git a/x/incentives/keeper/distribute.go b/x/incentives/keeper/distribute.go index 90f3780e6fc..a0cf0aa62cd 100644 --- a/x/incentives/keeper/distribute.go +++ b/x/incentives/keeper/distribute.go @@ -146,7 +146,7 @@ func (k Keeper) FilteredLocksDistributionEst(ctx sdk.Context, gauge types.Gauge, } // increase filled epochs after distribution - gauge.FilledEpochs += 1 + gauge.FilledEpochs++ gauge.DistributedCoins = gauge.DistributedCoins.Add(remainCoinsPerEpoch...) return gauge, filteredDistrCoins, false, nil @@ -180,7 +180,7 @@ func (d *distributionInfo) addLockRewards(owner string, rewards sdk.Coins) error d.idToDistrCoins[id] = rewards.Add(oldDistrCoins...) } else { id := d.nextID - d.nextID += 1 + d.nextID++ d.lockOwnerAddrToID[owner] = id decodedOwnerAddr, err := sdk.AccAddressFromBech32(owner) if err != nil { @@ -243,7 +243,7 @@ func (k Keeper) distributeSyntheticInternal( for _, lock := range locks { if v, ok := qualifiedLocksMap[lock.ID]; ok { qualifiedLocksMap[lock.ID] = lockIndexPair{v.lock, curIndex} - curIndex += 1 + curIndex++ } } @@ -311,7 +311,7 @@ func (k Keeper) distributeInternal( // 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 { - gauge.FilledEpochs += 1 + gauge.FilledEpochs++ gauge.DistributedCoins = gauge.DistributedCoins.Add(newlyDistributedCoins...) if err := k.setGauge(ctx, &gauge); err != nil { return err diff --git a/x/incentives/keeper/gauge.go b/x/incentives/keeper/gauge.go index a376885be13..b49dae3f2e9 100644 --- a/x/incentives/keeper/gauge.go +++ b/x/incentives/keeper/gauge.go @@ -78,7 +78,7 @@ func (k Keeper) SetGaugeWithRefKey(ctx sdk.Context, gauge *types.Gauge) error { timeKey := getTimeKey(gauge.StartTime) activeOrUpcomingGauge := gauge.IsActiveGauge(curTime) || gauge.IsUpcomingGauge(curTime) - if gauge.IsUpcomingGauge(curTime) { + if gauge.IsUpcomingGauge(curTime) { //nolint:gocritic // no reason to rewrite to a switch statement. combinedKeys := combineKeys(types.KeyPrefixUpcomingGauges, timeKey) return k.CreateGaugeRefKeys(ctx, gauge, combinedKeys, activeOrUpcomingGauge) } else if gauge.IsActiveGauge(curTime) { diff --git a/x/incentives/keeper/store.go b/x/incentives/keeper/store.go index 6f223804fcf..7c3e83e09f9 100644 --- a/x/incentives/keeper/store.go +++ b/x/incentives/keeper/store.go @@ -22,14 +22,14 @@ func (k Keeper) GetLastGaugeID(ctx sdk.Context) uint64 { } // SetLastGaugeID sets the last used gauge ID to the provided ID. -func (k Keeper) SetLastGaugeID(ctx sdk.Context, ID uint64) { +func (k Keeper) SetLastGaugeID(ctx sdk.Context, id uint64) { store := ctx.KVStore(k.storeKey) - store.Set(types.KeyLastGaugeID, sdk.Uint64ToBigEndian(ID)) + store.Set(types.KeyLastGaugeID, sdk.Uint64ToBigEndian(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)) +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. @@ -93,11 +93,11 @@ func (k Keeper) getAllGaugeIDsByDenom(ctx sdk.Context, denom string) []uint64 { } // 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) +func (k Keeper) deleteGaugeIDForDenom(ctx sdk.Context, id uint64, denom string) error { + return k.deleteGaugeRefByKey(ctx, gaugeDenomStoreKey(denom), id) } // 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) +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 94fd9c44d4d..a06aee1fee0 100644 --- a/x/incentives/keeper/utils.go +++ b/x/incentives/keeper/utils.go @@ -9,9 +9,9 @@ import ( ) // 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 { +func findIndex(iDs []uint64, iD uint64) int { + for index, id := range iDs { + if id == iD { return index } } @@ -19,13 +19,13 @@ func findIndex(IDs []uint64, ID uint64) int { } // 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) +func removeValue(iDs []uint64, iD uint64) ([]uint64, int) { + index := findIndex(iDs, iD) if index < 0 { - return IDs, index + return iDs, index } - IDs[index] = IDs[len(IDs)-1] // set last element to index - return IDs[:len(IDs)-1], index + iDs[index] = iDs[len(iDs)-1] // set last element to index + return iDs[:len(iDs)-1], index } // getTimeKey returns the time key used when getting a set of gauges. diff --git a/x/incentives/simulation/operations.go b/x/incentives/simulation/operations.go index 40fb3b75fc8..e059b8ee1ee 100644 --- a/x/incentives/simulation/operations.go +++ b/x/incentives/simulation/operations.go @@ -24,8 +24,8 @@ import ( const ( DefaultWeightMsgCreateGauge int = 10 DefaultWeightMsgAddToGauge int = 10 - OpWeightMsgCreateGauge = "op_weight_msg_create_gauge" - OpWeightMsgAddToGauge = "op_weight_msg_add_to_gauge" + OpWeightMsgCreateGauge = "op_weight_msg_create_gauge" //nolint:gosec + OpWeightMsgAddToGauge = "op_weight_msg_add_to_gauge" //nolint:gosec ) // WeightedOperations returns all the operations from the module with their respective weights. diff --git a/x/lockup/client/cli/query.go b/x/lockup/client/cli/query.go index 6977e0625b3..c27cbd99932 100644 --- a/x/lockup/client/cli/query.go +++ b/x/lockup/client/cli/query.go @@ -785,7 +785,7 @@ $ %s query lockup output-all-locks if err != nil { return err } - err = os.WriteFile("lock_export.json", bz, 0o777) + err = os.WriteFile("lock_export.json", bz, 0o777) //nolint:gosec // if we're using 777, I figure there's a reason to do so. if err != nil { return err } diff --git a/x/lockup/client/rest/rest.go b/x/lockup/client/rest/rest.go index 60a4faee74d..5f82a46144a 100644 --- a/x/lockup/client/rest/rest.go +++ b/x/lockup/client/rest/rest.go @@ -10,7 +10,6 @@ import ( ) // REST Variable names -// nolint const ( LockID = "lock-id" RestOwnerAddress = "owner" diff --git a/x/lockup/keeper/migration.go b/x/lockup/keeper/migration.go index 079b054b07a..cebc0f05a4c 100644 --- a/x/lockup/keeper/migration.go +++ b/x/lockup/keeper/migration.go @@ -101,7 +101,7 @@ func MergeLockupsForSimilarDurations( } k.SetLastLockID(ctx, normalID) normals[key] = normalID - numLocksCreated += 1 + numLocksCreated++ } else { normalLockPtr, err := k.GetLockByID(ctx, normalID) if err != nil { diff --git a/x/lockup/keeper/store.go b/x/lockup/keeper/store.go index 79f2c315fa1..6f7bc437230 100644 --- a/x/lockup/keeper/store.go +++ b/x/lockup/keeper/store.go @@ -6,6 +6,7 @@ import ( "time" "github.com/gogo/protobuf/proto" + "github.com/osmosis-labs/osmosis/v12/x/lockup/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -25,14 +26,14 @@ func (k Keeper) GetLastLockID(ctx sdk.Context) uint64 { } // SetLastLockID save ID used by last lock. -func (k Keeper) SetLastLockID(ctx sdk.Context, ID uint64) { +func (k Keeper) SetLastLockID(ctx sdk.Context, id uint64) { store := ctx.KVStore(k.storeKey) - store.Set(types.KeyLastLockID, sdk.Uint64ToBigEndian(ID)) + store.Set(types.KeyLastLockID, sdk.Uint64ToBigEndian(id)) } // lockStoreKey returns action store key from ID. -func lockStoreKey(ID uint64) []byte { - return combineKeys(types.KeyPrefixPeriodLock, sdk.Uint64ToBigEndian(ID)) +func lockStoreKey(id uint64) []byte { + return combineKeys(types.KeyPrefixPeriodLock, sdk.Uint64ToBigEndian(id)) } // syntheticLockStoreKey returns synthetic store key from ID and synth denom. diff --git a/x/lockup/types/events.go b/x/lockup/types/events.go index 8dbd4f6166c..c2c3ea69c65 100644 --- a/x/lockup/types/events.go +++ b/x/lockup/types/events.go @@ -1,6 +1,8 @@ package types // event types. +// +//nolint:gosec // these aren't hard-coded credentials const ( TypeEvtLockTokens = "lock_tokens" TypeEvtAddTokensToLock = "add_tokens_to_lock" diff --git a/x/lockup/types/lock.go b/x/lockup/types/lock.go index 24cd878115c..51979c71589 100644 --- a/x/lockup/types/lock.go +++ b/x/lockup/types/lock.go @@ -9,9 +9,9 @@ import ( ) // NewPeriodLock returns a new instance of period lock. -func NewPeriodLock(ID uint64, owner sdk.AccAddress, duration time.Duration, endTime time.Time, coins sdk.Coins) PeriodLock { +func NewPeriodLock(id uint64, owner sdk.AccAddress, duration time.Duration, endTime time.Time, coins sdk.Coins) PeriodLock { return PeriodLock{ - ID: ID, + ID: id, Owner: owner.String(), Duration: duration, EndTime: endTime, diff --git a/x/mint/types/params.go b/x/mint/types/params.go index c3245ce1bc1..ffa34f701ad 100644 --- a/x/mint/types/params.go +++ b/x/mint/types/params.go @@ -35,7 +35,7 @@ func ParamKeyTable() paramtypes.KeyTable { // 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, + reductionFactor sdk.Dec, reductionPeriodInEpochs int64, distrProportions DistributionProportions, weightedDevRewardsReceivers []WeightedAddress, mintingRewardsDistributionStartEpoch int64, ) Params { return Params{ @@ -43,7 +43,7 @@ func NewParams( GenesisEpochProvisions: genesisEpochProvisions, EpochIdentifier: epochIdentifier, ReductionPeriodInEpochs: reductionPeriodInEpochs, - ReductionFactor: ReductionFactor, + ReductionFactor: reductionFactor, DistributionProportions: distrProportions, WeightedDeveloperRewardsReceivers: weightedDevRewardsReceivers, MintingRewardsDistributionStartEpoch: mintingRewardsDistributionStartEpoch, diff --git a/x/pool-incentives/types/gov.go b/x/pool-incentives/types/gov.go index 12a993d74b8..432a822328b 100644 --- a/x/pool-incentives/types/gov.go +++ b/x/pool-incentives/types/gov.go @@ -72,7 +72,7 @@ func (p ReplacePoolIncentivesProposal) String() string { // TODO: Make this prettier recordsStr := "" for _, record := range p.Records { - recordsStr = recordsStr + fmt.Sprintf("(GaugeId: %d, Weight: %s) ", record.GaugeId, record.Weight.String()) + recordsStr += fmt.Sprintf("(GaugeId: %d, Weight: %s) ", record.GaugeId, record.Weight.String()) } var b strings.Builder @@ -129,7 +129,7 @@ func (p UpdatePoolIncentivesProposal) String() string { // TODO: Make this prettier recordsStr := "" for _, record := range p.Records { - recordsStr = recordsStr + fmt.Sprintf("(GaugeId: %d, Weight: %s) ", record.GaugeId, record.Weight.String()) + recordsStr += fmt.Sprintf("(GaugeId: %d, Weight: %s) ", record.GaugeId, record.Weight.String()) } var b strings.Builder diff --git a/x/superfluid/keeper/stake.go b/x/superfluid/keeper/stake.go index 0a74e093699..e490d80ff9c 100644 --- a/x/superfluid/keeper/stake.go +++ b/x/superfluid/keeper/stake.go @@ -68,7 +68,7 @@ func (k Keeper) RefreshIntermediaryDelegationAmounts(ctx sdk.Context) { refreshedAmount := k.GetExpectedDelegationAmount(ctx, acc) - if refreshedAmount.GT(currentAmount) { + if refreshedAmount.GT(currentAmount) { //nolint:gocritic // no need to use switch here adjustment := refreshedAmount.Sub(currentAmount) err = k.mintOsmoTokensAndDelegate(ctx, adjustment, acc) if err != nil { @@ -119,7 +119,7 @@ func (k Keeper) IncreaseSuperfluidDelegation(ctx sdk.Context, lockID uint64, amo // 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 { +func (k Keeper) validateLockForSF(ctx sdk.Context, lock *lockuptypes.PeriodLock, sender string) error { //nolint:unparam if lock.Owner != sender { return lockuptypes.ErrNotLockOwner } diff --git a/x/superfluid/keeper/synthetic_lock_wrapper.go b/x/superfluid/keeper/synthetic_lock_wrapper.go index dfff4522de6..3afe4840531 100644 --- a/x/superfluid/keeper/synthetic_lock_wrapper.go +++ b/x/superfluid/keeper/synthetic_lock_wrapper.go @@ -47,9 +47,8 @@ func (k Keeper) createSyntheticLockup(ctx sdk.Context, isUnlocking := true synthdenom := unstakingSyntheticDenom(intermediateAcc.Denom, intermediateAcc.ValAddr) return k.lk.CreateSyntheticLockup(ctx, underlyingLockId, synthdenom, unbondingDuration, isUnlocking) - } else { - notUnlocking := false - synthdenom := stakingSyntheticDenom(intermediateAcc.Denom, intermediateAcc.ValAddr) - return k.lk.CreateSyntheticLockup(ctx, underlyingLockId, synthdenom, unbondingDuration, notUnlocking) } + notUnlocking := false + synthdenom := stakingSyntheticDenom(intermediateAcc.Denom, intermediateAcc.ValAddr) + return k.lk.CreateSyntheticLockup(ctx, underlyingLockId, synthdenom, unbondingDuration, notUnlocking) } diff --git a/x/superfluid/simulation/operations.go b/x/superfluid/simulation/operations.go index ca448b07578..16e6ff5a4a2 100644 --- a/x/superfluid/simulation/operations.go +++ b/x/superfluid/simulation/operations.go @@ -27,9 +27,9 @@ const ( DefaultWeightSetSuperfluidAssetsProposal int = 5 DefaultWeightRemoveSuperfluidAssetsProposal int = 2 - OpWeightMsgSuperfluidDelegate = "op_weight_msg_superfluid_delegate" - OpWeightMsgSuperfluidUndelegate = "op_weight_msg_superfluid_undelegate" - OpWeightMsgSuperfluidRedelegate = "op_weight_msg_superfluid_redelegate" + OpWeightMsgSuperfluidDelegate = "op_weight_msg_superfluid_delegate" //nolint:gosec + OpWeightMsgSuperfluidUndelegate = "op_weight_msg_superfluid_undelegate" //nolint:gosec + OpWeightMsgSuperfluidRedelegate = "op_weight_msg_superfluid_redelegate" //nolint:gosec ) // WeightedOperations returns all the operations from the module with their respective weights. diff --git a/x/superfluid/simulation/proposals.go b/x/superfluid/simulation/proposals.go index 723ba58f87e..ce18096f4eb 100644 --- a/x/superfluid/simulation/proposals.go +++ b/x/superfluid/simulation/proposals.go @@ -13,8 +13,8 @@ import ( ) const ( - OpWeightSetSuperfluidAssetsProposal = "op_weight_set_superfluid_assets_proposal" - OpWeightRemoveSuperfluidAssetsProposal = "op_weight_remove_superfluid_assets_proposal" + OpWeightSetSuperfluidAssetsProposal = "op_weight_set_superfluid_assets_proposal" //nolint:gosec + OpWeightRemoveSuperfluidAssetsProposal = "op_weight_remove_superfluid_assets_proposal" //nolint:gosec ) // ProposalContents defines the module weighted proposals' contents. diff --git a/x/tokenfactory/keeper/createdenom.go b/x/tokenfactory/keeper/createdenom.go index 8abec1efd52..330b4142c28 100644 --- a/x/tokenfactory/keeper/createdenom.go +++ b/x/tokenfactory/keeper/createdenom.go @@ -70,6 +70,7 @@ func (k Keeper) validateCreateDenom(ctx sdk.Context, creatorAddr string, subdeno return denom, nil } +//nolint:unparam func (k Keeper) chargeForCreateDenom(ctx sdk.Context, creatorAddr string, subdenom string) (err error) { // Send creation fee to community pool creationFee := k.GetParams(ctx).DenomCreationFee diff --git a/x/tokenfactory/types/events.go b/x/tokenfactory/types/events.go index 94196fd034d..fd504c60851 100644 --- a/x/tokenfactory/types/events.go +++ b/x/tokenfactory/types/events.go @@ -1,6 +1,8 @@ package types // event types +// +//nolint:gosec // these aren't hard-coded credentials const ( AttributeAmount = "amount" AttributeCreator = "creator" diff --git a/x/twap/logic.go b/x/twap/logic.go index 58e63937db6..98e3a8db814 100644 --- a/x/twap/logic.go +++ b/x/twap/logic.go @@ -233,7 +233,7 @@ func (k Keeper) getMostRecentRecord(ctx sdk.Context, poolId uint64, assetA, asse // (endRecord.Accumulator - startRecord.Accumulator) / (endRecord.Time - startRecord.Time) func computeArithmeticTwap(startRecord types.TwapRecord, endRecord types.TwapRecord, quoteAsset string) (sdk.Dec, error) { // see if we need to return an error, due to spot price issues - var err error = nil + var err error if endRecord.LastErrorTime.After(startRecord.Time) || endRecord.LastErrorTime.Equal(startRecord.Time) { err = errors.New("twap: error in pool spot price occurred between start and end time, twap result may be faulty") } diff --git a/x/twap/store.go b/x/twap/store.go index e86f3b9ea10..738f4ee968f 100644 --- a/x/twap/store.go +++ b/x/twap/store.go @@ -199,9 +199,8 @@ func (k Keeper) getRecordAtOrBeforeTime(ctx sdk.Context, poolId uint64, t time.T return types.TwapRecord{}, fmt.Errorf( "getTwapRecord: querying for assets %s %s that are not in pool id %d", asset0Denom, asset1Denom, poolId) - } else { - return types.TwapRecord{}, timeTooOldError{Time: t} } + return types.TwapRecord{}, timeTooOldError{Time: t} } if twap.Asset0Denom != asset0Denom || twap.Asset1Denom != asset1Denom || twap.PoolId != poolId { return types.TwapRecord{}, fmt.Errorf("internal error, got twap but its data is wrong")