Skip to content

Commit

Permalink
Apply linter and fix basic linting issues on codebase (#1941)
Browse files Browse the repository at this point in the history
* Fix shadowing linting setting.

* Fix linting for imports.

* Changelog entry.

* Fix imports order.

* Lint majority of app package.

* Additional linting to apps package.

* Add linting to cmd package.

* Add linting to genaccounts_test.go

* Lint attribute module.

* Lint metadata module.

* Lint marker module.

* Lint msgfees.

* Lint name.

* Additional internal linting

* Basic linting on the rest of our modules.
  • Loading branch information
Taztingo authored Apr 19, 2024
1 parent 484fe50 commit 0ced31a
Show file tree
Hide file tree
Showing 61 changed files with 133 additions and 210 deletions.
26 changes: 16 additions & 10 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ import (
authcodec "github.com/cosmos/cosmos-sdk/x/auth/codec"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation"
"github.com/cosmos/cosmos-sdk/x/auth/tx"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
txmodule "github.com/cosmos/cosmos-sdk/x/auth/tx/config"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
Expand Down Expand Up @@ -340,7 +339,7 @@ func New(
})
appCodec := codec.NewProtoCodec(interfaceRegistry)
legacyAmino := codec.NewLegacyAmino()
txConfig := tx.NewTxConfig(appCodec, tx.DefaultSignModes)
txConfig := authtx.NewTxConfig(appCodec, authtx.DefaultSignModes)

std.RegisterLegacyAminoCodec(legacyAmino)
std.RegisterInterfaces(interfaceRegistry)
Expand Down Expand Up @@ -448,13 +447,14 @@ func New(
)

// optional: enable sign mode textual by overwriting the default tx config (after setting the bank keeper)
enabledSignModes := append(tx.DefaultSignModes, sigtypes.SignMode_SIGN_MODE_TEXTUAL)
txConfigOpts := tx.ConfigOptions{
enabledSignModes := authtx.DefaultSignModes
enabledSignModes = append(enabledSignModes, sigtypes.SignMode_SIGN_MODE_TEXTUAL)
txConfigOpts := authtx.ConfigOptions{
EnabledSignModes: enabledSignModes,
TextualCoinMetadataQueryFn: txmodule.NewBankKeeperCoinMetadataQueryFn(app.BankKeeper),
}
var err error
txConfig, err = tx.NewTxConfigWithOptions(appCodec, txConfigOpts)
txConfig, err = authtx.NewTxConfigWithOptions(appCodec, txConfigOpts)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -551,7 +551,7 @@ func New(
app.NameKeeper = namekeeper.NewKeeper(appCodec, keys[nametypes.StoreKey])

app.AttributeKeeper = attributekeeper.NewKeeper(
appCodec, keys[attributetypes.StoreKey], app.GetSubspace(attributetypes.ModuleName), app.AccountKeeper, &app.NameKeeper,
appCodec, keys[attributetypes.StoreKey], app.AccountKeeper, &app.NameKeeper,
)

markerReqAttrBypassAddrs := []sdk.AccAddress{
Expand Down Expand Up @@ -986,7 +986,9 @@ func New(

app.mm.RegisterInvariants(app.CrisisKeeper)
app.configurator = module.NewConfigurator(app.appCodec, app.BaseApp.MsgServiceRouter(), app.GRPCQueryRouter())
app.mm.RegisterServices(app.configurator)
if err := app.mm.RegisterServices(app.configurator); err != nil {
panic(err)
}

app.sm = module.NewSimulationManager(
auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)),
Expand Down Expand Up @@ -1178,7 +1180,7 @@ func filterBeginBlockerEvents(responseBeginBlock sdk.BeginBlock) []abci.Event {
func shouldFilterEvent(e abci.Event) bool {
if e.Type == distrtypes.EventTypeCommission || e.Type == distrtypes.EventTypeRewards || e.Type == distrtypes.EventTypeProposerReward || e.Type == banktypes.EventTypeTransfer || e.Type == banktypes.EventTypeCoinSpent || e.Type == banktypes.EventTypeCoinReceived {
for _, a := range e.Attributes {
if string(a.Key) == sdk.AttributeKeyAmount && len(a.Value) == 0 {
if a.Key == sdk.AttributeKeyAmount && len(a.Value) == 0 {
return true
}
}
Expand All @@ -1197,7 +1199,9 @@ func (app *App) InitChainer(ctx sdk.Context, req *abci.RequestInitChain) (*abci.
if err := json.Unmarshal(req.AppStateBytes, &genesisState); err != nil {
panic(err)
}
app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap())
if err := app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()); err != nil {
panic(err)
}
return app.mm.InitGenesis(ctx, app.appCodec, genesisState)
}

Expand Down Expand Up @@ -1415,7 +1419,9 @@ func (app *App) injectUpgrade(name string) { //nolint:unused // This is designed
// But the upgrade keeper often its own migration stuff that change some store key stuff.
// ScheduleUpgrade tries to read some of that changed store stuff and fails if the migration hasn't
// been applied yet. So we're doing things the hard way here.
app.UpgradeKeeper.ClearUpgradePlan(ctx)
if err := app.UpgradeKeeper.ClearUpgradePlan(ctx); err != nil {
panic(err)
}
store := ctx.KVStore(app.GetKey(upgradetypes.StoreKey))
bz := app.appCodec.MustMarshal(&plan)
store.Set(upgradetypes.PlanKey(), bz)
Expand Down
2 changes: 1 addition & 1 deletion app/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ func logAddrs(t *testing.T, addrs []sdk.AccAddress, name string) {
}
}

func assertNoDupeAccountNumbers(t *testing.T, ctx sdk.Context, app *App, accts []sdk.AccountI, name string) bool {
func assertNoDupeAccountNumbers(t *testing.T, _ sdk.Context, _ *App, accts []sdk.AccountI, name string) bool {
t.Helper()
byAcctNum := map[uint64][]sdk.AccountI{}
acctNums := []uint64{}
Expand Down
9 changes: 7 additions & 2 deletions app/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,12 +251,17 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str
/* Handle slashing state. */

// reset start height on signing infos
app.SlashingKeeper.IterateValidatorSigningInfos(
err = app.SlashingKeeper.IterateValidatorSigningInfos(
ctx,
func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) {
info.StartHeight = 0
app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info)
if err := app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info); err != nil {
panic(fmt.Errorf("could not set validator signing for %s: %w", addr, err))
}
return false
},
)
if err != nil {
panic(fmt.Errorf("could not iterate validator signing infos: %w", err))
}
}
3 changes: 1 addition & 2 deletions app/group.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ func (t GroupCheckerFunc) IsGroupAddress(ctx sdk.Context, account sdk.AccAddress
func NewGroupCheckerFunc(querier GroupPolicyQuerier) GroupCheckerFunc {
return GroupCheckerFunc(func(ctx sdk.Context, account sdk.AccAddress) bool {
msg := &group.QueryGroupPolicyInfoRequest{Address: account.String()}
goCtx := sdk.WrapSDKContext(ctx)
_, err := querier.GroupPolicyInfo(goCtx, msg)
_, err := querier.GroupPolicyInfo(ctx, msg)
return err == nil
})
}
19 changes: 6 additions & 13 deletions app/upgrades.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,7 @@ var upgrades = map[string]appUpgrade{
return nil, err
}

err = updateIBCClients(ctx, app)
if err != nil {
return nil, err
}
updateIBCClients(ctx, app)

removeInactiveValidatorDelegations(ctx, app)

Expand Down Expand Up @@ -120,10 +117,7 @@ var upgrades = map[string]appUpgrade{
return nil, err
}

err = updateIBCClients(ctx, app)
if err != nil {
return nil, err
}
updateIBCClients(ctx, app)

removeInactiveValidatorDelegations(ctx, app)

Expand Down Expand Up @@ -290,13 +284,12 @@ func pruneIBCExpiredConsensusStates(ctx sdk.Context, app *App) error {

// updateIBCClients updates the allowed clients for IBC.
// TODO: Remove with the umber handlers.
func updateIBCClients(ctx sdk.Context, app *App) error {
func updateIBCClients(ctx sdk.Context, app *App) {
ctx.Logger().Info("Updating IBC AllowedClients.")
params := app.IBCKeeper.ClientKeeper.GetParams(ctx)
params.AllowedClients = append(params.AllowedClients, exported.Localhost)
app.IBCKeeper.ClientKeeper.SetParams(ctx, params)
ctx.Logger().Info("Done updating IBC AllowedClients.")
return nil
}

// migrateBaseappParams migrates to new ConsensusParamsKeeper
Expand Down Expand Up @@ -344,7 +337,7 @@ func migrateAttributeParams(ctx sdk.Context, app *App) {
if attributeParamSpace.Has(ctx, attributetypes.ParamStoreKeyMaxValueLength) {
attributeParamSpace.Get(ctx, attributetypes.ParamStoreKeyMaxValueLength, &maxValueLength)
}
app.AttributeKeeper.SetParams(ctx, attributetypes.Params{MaxValueLength: uint32(maxValueLength)})
app.AttributeKeeper.SetParams(ctx, attributetypes.Params{MaxValueLength: maxValueLength})
ctx.Logger().Info("Done migrating attribute params.")
}

Expand All @@ -360,7 +353,7 @@ func migrateMarkerParams(ctx sdk.Context, app *App) {
if markerParamSpace.Has(ctx, markertypes.ParamStoreKeyMaxTotalSupply) {
var maxTotalSupply uint64
markerParamSpace.Get(ctx, markertypes.ParamStoreKeyMaxTotalSupply, &maxTotalSupply)
params.MaxTotalSupply = maxTotalSupply
params.MaxTotalSupply = maxTotalSupply //nolint:staticcheck
}

// TODO: remove markertypes.ParamStoreKeyEnableGovernance with the umber handlers.
Expand Down Expand Up @@ -399,7 +392,7 @@ func migrateMetadataOSLocatorParams(ctx sdk.Context, app *App) {
if metadataParamSpace.Has(ctx, metadatatypes.ParamStoreKeyMaxValueLength) {
metadataParamSpace.Get(ctx, metadatatypes.ParamStoreKeyMaxValueLength, &maxValueLength)
}
app.MetadataKeeper.SetOSLocatorParams(ctx, metadatatypes.OSLocatorParams{MaxUriLength: uint32(maxValueLength)})
app.MetadataKeeper.SetOSLocatorParams(ctx, metadatatypes.OSLocatorParams{MaxUriLength: maxValueLength})
ctx.Logger().Info("Done migrating metadata os locator params.")
}

Expand Down
3 changes: 1 addition & 2 deletions app/upgrades_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/staking/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"

"github.com/provenance-io/provenance/internal/helpers"
Expand Down Expand Up @@ -261,7 +260,7 @@ func (s *UpgradeTestSuite) CreateValidator(unbondedTime time.Time, status stakin
func (s *UpgradeTestSuite) DelegateToValidator(valAddress sdk.ValAddress, delegatorAddress sdk.AccAddress, coin sdk.Coin) {
validator, err := s.app.StakingKeeper.GetValidator(s.ctx, valAddress)
s.Require().NoError(err, "GetValidator(%q)", valAddress.String())
_, err = s.app.StakingKeeper.Delegate(s.ctx, delegatorAddress, coin.Amount, types.Unbonded, validator, true)
_, err = s.app.StakingKeeper.Delegate(s.ctx, delegatorAddress, coin.Amount, stakingtypes.Unbonded, validator, true)
s.Require().NoError(err, "Delegate(%q, %q, unbonded, %q, true) error", delegatorAddress.String(), coin.String(), valAddress.String())
}

Expand Down
6 changes: 3 additions & 3 deletions cmd/provenanced/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ The directory that houses the configuration and data for the blockchain. This di
`,
Example: fmt.Sprintf(`$ %[1]s home`, configCmdStart),
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
return runConfigHomeCmd(cmd)
},
}
Expand All @@ -207,7 +207,7 @@ Settings that are their default value will not be included.
`, provconfig.PackedConfFilename, provconfig.AppConfFilename, provconfig.TmConfFilename, provconfig.ClientConfFilename),
Example: fmt.Sprintf(`$ %[1]s pack`, configCmdStart),
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
return runConfigPackCmd(cmd)
},
}
Expand All @@ -231,7 +231,7 @@ This can also be used to update the config files using the current template so t
`, provconfig.PackedConfFilename, provconfig.AppConfFilename, provconfig.TmConfFilename, provconfig.ClientConfFilename),
Example: fmt.Sprintf(`$ %[1]s unpack`, configCmdStart),
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
return runConfigUnpackCmd(cmd)
},
}
Expand Down
20 changes: 1 addition & 19 deletions cmd/provenanced/cmd/genaccounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -606,7 +605,7 @@ Currently, the denom and price defaults to 1905nhash
}

// AddGenesisMsgFeeCmd returns add-genesis-msg-fee cobra command.
func AddGenesisMsgFeeCmd(defaultNodeHome string, interfaceRegistry types.InterfaceRegistry) *cobra.Command {
func AddGenesisMsgFeeCmd(defaultNodeHome string) *cobra.Command {
cmd := &cobra.Command{
Use: "add-genesis-msg-fee [msg-url] [additional-fee]",
Short: "Add a msg fee to genesis.json",
Expand All @@ -630,10 +629,6 @@ func AddGenesisMsgFeeCmd(defaultNodeHome string, interfaceRegistry types.Interfa
msgType = "/" + msgType
}

if err := checkMsgTypeValid(interfaceRegistry, msgType); err != nil {
return err
}

additionalFee, err := sdk.ParseCoinNormalized(args[1])
if err != nil {
return fmt.Errorf("failed to parse coin: %w", err)
Expand Down Expand Up @@ -681,19 +676,6 @@ func AddGenesisMsgFeeCmd(defaultNodeHome string, interfaceRegistry types.Interfa
return cmd
}

func checkMsgTypeValid(registry types.InterfaceRegistry, msgTypeURL string) error {
msg, err := registry.Resolve(msgTypeURL)
if err != nil {
return err
}

_, ok := msg.(sdk.Msg)
if !ok {
return fmt.Errorf("message type is not a sdk message: %v", msgTypeURL)
}
return err
}

// AddGenesisDefaultMarketCmd returns add-genesis-default-market cobra command.
func AddGenesisDefaultMarketCmd(defaultNodeHome string) *cobra.Command {
cmd := &cobra.Command{
Expand Down
17 changes: 5 additions & 12 deletions cmd/provenanced/cmd/genaccounts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
genutiltest "github.com/cosmos/cosmos-sdk/x/genutil/client/testutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"

"github.com/provenance-io/provenance/app"
provenancecmd "github.com/provenance-io/provenance/cmd/provenanced/cmd"
"github.com/provenance-io/provenance/testutil/assertions"
"github.com/provenance-io/provenance/testutil/mocks"
Expand Down Expand Up @@ -99,8 +98,6 @@ func TestAddGenesisAccountCmd(t *testing.T) {
}

func TestAddGenesisMsgFeeCmd(t *testing.T) {
encCfg := app.MakeTestEncodingConfig(t)

tests := []struct {
name string
msgType string
Expand Down Expand Up @@ -158,7 +155,7 @@ func TestAddGenesisMsgFeeCmd(t *testing.T) {
ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx)

cmd := provenancecmd.AddGenesisCustomFloorPriceDenomCmd(home)
cmdFee := provenancecmd.AddGenesisMsgFeeCmd(home, encCfg.InterfaceRegistry)
cmdFee := provenancecmd.AddGenesisMsgFeeCmd(home)
cmd.SetArgs([]string{
tc.msgFeeFloorCoin,
fmt.Sprintf("--%s=home", flags.FlagHome)})
Expand Down Expand Up @@ -384,9 +381,7 @@ func TestAddGenesisDefaultMarketCmd(t *testing.T) {
appState[exchange.ModuleName], err = cdc.MarshalJSON(tc.iniExGenState)
require.NoError(t, err, "setup: MarshalJSON exchange genesis state")
} else {
if _, found := appState[exchange.ModuleName]; found {
delete(appState, exchange.ModuleName)
}
delete(appState, exchange.ModuleName)
}

var authState authtypes.GenesisState
Expand Down Expand Up @@ -442,7 +437,7 @@ func TestAddGenesisDefaultMarketCmd(t *testing.T) {
return
}

appState, genDoc, err = genutiltypes.GenesisStateFromGenFile(genFile)
appState, _, err = genutiltypes.GenesisStateFromGenFile(genFile)
require.NoError(t, err, "GenesisStateFromGenFile(%q)", genFile)
var actExGenState exchange.GenesisState
err = cdc.UnmarshalJSON(appState[exchange.ModuleName], &actExGenState)
Expand Down Expand Up @@ -716,9 +711,7 @@ func TestAddGenesisCustomMarketCmd(t *testing.T) {
appState[exchange.ModuleName], err = cdc.MarshalJSON(tc.iniExGenState)
require.NoError(t, err, "setup: MarshalJSON exchange genesis state")
} else {
if _, found := appState[exchange.ModuleName]; found {
delete(appState, exchange.ModuleName)
}
delete(appState, exchange.ModuleName)
}

genDoc.AppState, err = json.Marshal(appState)
Expand Down Expand Up @@ -746,7 +739,7 @@ func TestAddGenesisCustomMarketCmd(t *testing.T) {
return
}

appState, genDoc, err = genutiltypes.GenesisStateFromGenFile(genFile)
appState, _, err = genutiltypes.GenesisStateFromGenFile(genFile)
require.NoError(t, err, "GenesisStateFromGenFile(%q)", genFile)
var actExGenState exchange.GenesisState
err = cdc.UnmarshalJSON(appState[exchange.ModuleName], &actExGenState)
Expand Down
4 changes: 2 additions & 2 deletions cmd/provenanced/cmd/pre_upgrade.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ Exit code meanings:
SilenceUsage: true, // No need to print usage if the command fails.
// Cosmovisor doesn't provide any args, and none are expected. But we want an
// exit code of 30 here (instead of 1), so we're not using cobra.NoArgs.
Args: func(cmd *cobra.Command, args []string) error {
Args: func(_ *cobra.Command, args []string) error {
if len(args) != 0 {
return errors.Join(fmt.Errorf("expected 0 args, received %d", len(args)), ErrFail)
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
err := UpdateConfig(cmd)
if err != nil {
return errors.Join(fmt.Errorf("could not update config file(s): %w", err), ErrFail)
Expand Down
5 changes: 3 additions & 2 deletions cmd/provenanced/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ func NewRootCmd(sealConfig bool) (*cobra.Command, params.EncodingConfig) {
// sets the RPC client needed for SIGN_MODE_TEXTUAL. This sign mode
// is only available if the client is online.
if !initClientCtx.Offline {
enabledSignModes := append(tx.DefaultSignModes, signing.SignMode_SIGN_MODE_TEXTUAL)
enabledSignModes := tx.DefaultSignModes
enabledSignModes = append(enabledSignModes, signing.SignMode_SIGN_MODE_TEXTUAL)
txConfigOpts := tx.ConfigOptions{
EnabledSignModes: enabledSignModes,
TextualCoinMetadataQueryFn: txmodule.NewGRPCCoinMetadataQueryFn(initClientCtx),
Expand Down Expand Up @@ -201,7 +202,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, b
AddGenesisAccountCmd(app.DefaultNodeHome),
AddRootDomainAccountCmd(app.DefaultNodeHome),
AddGenesisMarkerCmd(app.DefaultNodeHome),
AddGenesisMsgFeeCmd(app.DefaultNodeHome, encodingConfig.InterfaceRegistry),
AddGenesisMsgFeeCmd(app.DefaultNodeHome),
AddGenesisCustomFloorPriceDenomCmd(app.DefaultNodeHome),
AddGenesisDefaultMarketCmd(app.DefaultNodeHome),
AddGenesisCustomMarketCmd(app.DefaultNodeHome),
Expand Down
2 changes: 1 addition & 1 deletion internal/handlers/msg_service_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ func (msr *PioMsgServiceRouter) registerMsgServiceHandler(sd *grpc.ServiceDesc,

// Call the method handler from the service description with the handler object.
// We don't do any decoding here because the decoding was already done.
res, err := methodHandler(handler, sdk.WrapSDKContext(ctx), noopDecoder, interceptor)
res, err := methodHandler(handler, ctx, noopDecoder, interceptor)
if err != nil {
return nil, err
}
Expand Down
Loading

0 comments on commit 0ced31a

Please sign in to comment.