diff --git a/.circleci/config.yml b/.circleci/config.yml index 1840a201ea..10d20f5cac 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -60,6 +60,18 @@ jobs: paths: - ".git" + lint: + executor: golang + docker: + - image: golangci/golangci-lint:v1.42.1-alpine + steps: + - checkout + - run: + name: Lint + command: | + golangci-lint run --version + golangci-lint run --tests=false --timeout=5m0s + test-cover: executor: golang parallelism: 4 @@ -191,6 +203,9 @@ workflows: tags: only: - /^v.*/ + - lint: + requires: + - setup-dependencies - test-cover: requires: - setup-dependencies diff --git a/.golangci.yml b/.golangci.yml index c177059086..17d5384ea3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,4 +1,8 @@ +run: + tests: false + linters: + disable-all: true enable: - bodyclose - deadcode @@ -9,17 +13,15 @@ linters: - gocritic - gofmt - goimports - - golint + - revive - gosec - gosimple - govet - ineffassign - - interfacer - misspell - - maligned - nakedret - prealloc - - scopelint + - exportloopref - staticcheck - structcheck - stylecheck @@ -40,13 +42,13 @@ issues: linters-settings: dogsled: max-blank-identifiers: 3 - maligned: - # print struct with more effective memory layout or not, false by default - suggest-new: true errcheck: # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; # default is false: such cases aren't reported by default. check-blank: true + maligned: + # print struct with more effective memory layout or not, false by default + suggest-new: true golint: # minimal confidence for issues, default is 0.8 min-confidence: 0 diff --git a/CHANGELOG.md b/CHANGELOG.md index f6507d6e61..bc246d8e0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Remove unused flags from command prompt for storing contract [\#647](https://github.com/CosmWasm/wasmd/issues/647) - Ran `make format` [\#649](https://github.com/CosmWasm/wasmd/issues/649) +- Add golangci lint check to circleci jobs [\620](https://github.com/CosmWasm/wasmd/issues/620) [Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.20.0...HEAD) diff --git a/Makefile b/Makefile index df086ed7c6..711780e573 100644 --- a/Makefile +++ b/Makefile @@ -146,13 +146,13 @@ test-sim-multi-seed-short: runsim ############################################################################### lint: - golangci-lint run - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" | xargs gofmt -d -s + golangci-lint run --tests=false + find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "*_test.go" | xargs gofmt -d -s format: - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs gofmt -w -s - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs misspell -w - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs goimports -w -local github.com/CosmWasm/wasmd + find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" -not -path "*.pb.go" | xargs gofmt -w -s + find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" -not -path "*.pb.go" | xargs misspell -w + find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" -not -path "*.pb.go" | xargs goimports -w -local github.com/CosmWasm/wasmd ############################################################################### diff --git a/app/app.go b/app/app.go index 46307b2140..358487a5a9 100644 --- a/app/app.go +++ b/app/app.go @@ -184,11 +184,6 @@ var ( ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, wasm.ModuleName: {authtypes.Burner}, } - - // module accounts that are allowed to receive tokens - allowedReceivingModAcc = map[string]bool{ - distrtypes.ModuleName: true, - } ) // Verify app interface at compile time @@ -200,7 +195,7 @@ var ( // WasmApp extended ABCI application type WasmApp struct { *baseapp.BaseApp - legacyAmino *codec.LegacyAmino + legacyAmino *codec.LegacyAmino //nolint appCodec codec.Marshaler interfaceRegistry types.InterfaceRegistry @@ -562,7 +557,7 @@ func (app *WasmApp) ModuleAccountAddrs() map[string]bool { // // NOTE: This is solely to be used for testing purposes as it may be desirable // for modules to register their own custom testing types. -func (app *WasmApp) LegacyAmino() *codec.LegacyAmino { +func (app *WasmApp) LegacyAmino() *codec.LegacyAmino { //nolint return app.legacyAmino } @@ -636,7 +631,7 @@ func GetMaccPerms() map[string][]string { } // initParamsKeeper init params keeper and its subspaces -func initParamsKeeper(appCodec codec.BinaryMarshaler, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper { +func initParamsKeeper(appCodec codec.BinaryMarshaler, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper { //nolint paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) paramsKeeper.Subspace(authtypes.ModuleName) diff --git a/app/encoding.go b/app/encoding.go index 1bd14b7827..435cf54f61 100644 --- a/app/encoding.go +++ b/app/encoding.go @@ -14,7 +14,7 @@ type EncodingConfig struct { InterfaceRegistry types.InterfaceRegistry Marshaler codec.Marshaler TxConfig client.TxConfig - Amino *codec.LegacyAmino + Amino *codec.LegacyAmino //nolint } func MakeEncodingConfig() EncodingConfig { diff --git a/app/export.go b/app/export.go index eba7c9b555..88168e9a41 100644 --- a/app/export.go +++ b/app/export.go @@ -72,7 +72,10 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ // withdraw all validator commission app.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = app.distrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + _, err := app.distrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + if err != nil { + panic(err) + } return false }) @@ -88,7 +91,10 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ if err != nil { panic(err) } - _, _ = app.distrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) + _, err = app.distrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) + if err != nil { + panic(err) + } } // clear validator slash events diff --git a/app/test_helpers.go b/app/test_helpers.go index 54c896616a..9548f22805 100644 --- a/app/test_helpers.go +++ b/app/test_helpers.go @@ -208,18 +208,24 @@ func createRandomAccounts(accNum int) []sdk.AccAddress { // createIncrementalAccounts is a strategy used by addTestAddrs() in order to generated addresses in ascending order. func createIncrementalAccounts(accNum int) []sdk.AccAddress { - var addresses []sdk.AccAddress + addresses := make([]sdk.AccAddress, 0, accNum) var buffer bytes.Buffer // start at 100 so we can make up to 999 test addresses with valid test addresses for i := 100; i < (accNum + 100); i++ { numString := strconv.Itoa(i) - buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") //base address string + buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") // base address string - buffer.WriteString(numString) //adding on final two digits to make addresses unique - res, _ := sdk.AccAddressFromHex(buffer.String()) + buffer.WriteString(numString) // adding on final two digits to make addresses unique + res, err := sdk.AccAddressFromHex(buffer.String()) + if err != nil { + panic(err) + } bech := res.String() - addr, _ := TestAddr(buffer.String(), bech) + addr, err := TestAddr(buffer.String(), bech) + if err != nil { + panic(err) + } addresses = append(addresses, addr) buffer.Reset() @@ -409,7 +415,7 @@ func incrementAllSequenceNumbers(initSeqNums []uint64) { // CreateTestPubKeys returns a total of numPubKeys public keys in ascending order. func CreateTestPubKeys(numPubKeys int) []cryptotypes.PubKey { - var publicKeys []cryptotypes.PubKey + publicKeys := make([]cryptotypes.PubKey, 0, numPubKeys) var buffer bytes.Buffer // start at 10 to avoid changing 1 to 01, 2 to 02, etc diff --git a/cmd/wasmd/genaccounts.go b/cmd/wasmd/genaccounts.go index 252301d637..6429aafcca 100644 --- a/cmd/wasmd/genaccounts.go +++ b/cmd/wasmd/genaccounts.go @@ -51,7 +51,10 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { inBuf := bufio.NewReader(cmd.InOrStdin()) - keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend) + if err != nil { + return err + } // attempt to lookup address from Keybase if no address was provided kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf) @@ -72,9 +75,18 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa return fmt.Errorf("failed to parse coins: %w", err) } - vestingStart, _ := cmd.Flags().GetInt64(flagVestingStart) - vestingEnd, _ := cmd.Flags().GetInt64(flagVestingEnd) - vestingAmtStr, _ := cmd.Flags().GetString(flagVestingAmt) + vestingStart, err := cmd.Flags().GetInt64(flagVestingStart) + if err != nil { + return err + } + vestingEnd, err := cmd.Flags().GetInt64(flagVestingEnd) + if err != nil { + return err + } + vestingAmtStr, err := cmd.Flags().GetString(flagVestingAmt) + if err != nil { + return err + } vestingAmt, err := sdk.ParseCoinsNormalized(vestingAmtStr) if err != nil { diff --git a/cmd/wasmd/root.go b/cmd/wasmd/root.go index 969d9ed572..dde807e65f 100644 --- a/cmd/wasmd/root.go +++ b/cmd/wasmd/root.go @@ -19,9 +19,6 @@ import ( "github.com/tendermint/tendermint/libs/log" dbm "github.com/tendermint/tm-db" - "github.com/CosmWasm/wasmd/x/wasm" - clientcodec "github.com/CosmWasm/wasmd/x/wasm/client/codec" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/debug" @@ -41,6 +38,8 @@ import ( genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" "github.com/CosmWasm/wasmd/app" + "github.com/CosmWasm/wasmd/x/wasm" + clientcodec "github.com/CosmWasm/wasmd/x/wasm/client/codec" ) // NewRootCmd creates a new root command for wasmd. It is called once in the diff --git a/go.mod b/go.mod index 6dbfb6f9dc..ea8502ffc5 100644 --- a/go.mod +++ b/go.mod @@ -28,6 +28,7 @@ require ( github.com/tendermint/tm-db v0.6.4 google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71 google.golang.org/grpc v1.40.0 + google.golang.org/protobuf v1.27.1 // indirect gopkg.in/yaml.v2 v2.4.0 ) diff --git a/x/wasm/client/cli/genesis_msg.go b/x/wasm/client/cli/genesis_msg.go index a3291699bf..aa2090e9aa 100644 --- a/x/wasm/client/cli/genesis_msg.go +++ b/x/wasm/client/cli/genesis_msg.go @@ -4,7 +4,6 @@ import ( "bufio" "bytes" "crypto/sha256" - "encoding/binary" "encoding/json" "errors" "fmt" @@ -21,7 +20,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/genutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/spf13/cobra" - "github.com/tendermint/tendermint/crypto" tmtypes "github.com/tendermint/tendermint/types" "github.com/CosmWasm/wasmd/x/wasm/types" @@ -214,7 +212,7 @@ func GenesisListCodesCmd(defaultNodeHome string, genReader GenesisReader) *cobra if err != nil { return err } - return printJsonOutput(cmd, all) + return printJSONOutput(cmd, all) }, } @@ -237,7 +235,7 @@ func GenesisListContractsCmd(defaultNodeHome string, genReader GenesisReader) *c } state := g.WasmModuleState all := getAllContracts(state) - return printJsonOutput(cmd, all) + return printJSONOutput(cmd, all) }, } cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") @@ -246,7 +244,7 @@ func GenesisListContractsCmd(defaultNodeHome string, genReader GenesisReader) *c } // clientCtx marshaller works only with proto or bytes so we marshal the output ourself -func printJsonOutput(cmd *cobra.Command, obj interface{}) error { +func printJSONOutput(cmd *cobra.Command, obj interface{}) error { clientCtx := client.GetClientContextFromCmd(cmd) bz, err := json.MarshalIndent(obj, "", " ") if err != nil { @@ -261,12 +259,12 @@ type codeMeta struct { } func getAllCodes(state *types.GenesisState) ([]codeMeta, error) { - var all []codeMeta - for _, c := range state.Codes { - all = append(all, codeMeta{ + all := make([]codeMeta, len(state.Codes)) + for i, c := range state.Codes { + all[i] = codeMeta{ CodeID: c.CodeID, Info: c.CodeInfo, - }) + } } // add inflight seq := codeSeqValue(state) @@ -304,12 +302,12 @@ type contractMeta struct { } func getAllContracts(state *types.GenesisState) []contractMeta { - var all []contractMeta - for _, c := range state.Contracts { - all = append(all, contractMeta{ + all := make([]contractMeta, len(state.Contracts)) + for i, c := range state.Contracts { + all[i] = contractMeta{ ContractAddress: c.ContractAddress, Info: c.ContractInfo, - }) + } } // add inflight seq := contractSeqValue(state) @@ -494,7 +492,10 @@ func getActorAddress(cmd *cobra.Command) (sdk.AccAddress, error) { return actorAddr, nil } inBuf := bufio.NewReader(cmd.InOrStdin()) - keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend) + if err != nil { + return nil, err + } homeDir := client.GetClientContextFromCmd(cmd).HomeDir // attempt to lookup address from Keybase if no address was provided @@ -509,11 +510,3 @@ func getActorAddress(cmd *cobra.Command) (sdk.AccAddress, error) { } return info.GetAddress(), nil } - -// addrFromUint64 is a helper for address generation, copied from keeper -func addrFromUint64(id uint64) sdk.AccAddress { - addr := make([]byte, 20) - addr[0] = 'C' - binary.PutUvarint(addr[1:], id) - return sdk.AccAddress(crypto.AddressHash(addr)) -} diff --git a/x/wasm/client/cli/new_tx.go b/x/wasm/client/cli/new_tx.go index 0ff1086cdc..e3b47792e6 100644 --- a/x/wasm/client/cli/new_tx.go +++ b/x/wasm/client/cli/new_tx.go @@ -21,6 +21,9 @@ func MigrateContractCmd() *cobra.Command { Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } msg, err := parseMigrateContractArgs(args, clientCtx) if err != nil { @@ -63,6 +66,9 @@ func UpdateContractAdminCmd() *cobra.Command { Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } msg, err := parseUpdateContractAdminArgs(args, clientCtx) if err != nil { diff --git a/x/wasm/client/cli/query.go b/x/wasm/client/cli/query.go index 7e77ffbb24..4398cfe744 100644 --- a/x/wasm/client/cli/query.go +++ b/x/wasm/client/cli/query.go @@ -151,7 +151,7 @@ func GetCmdQueryCode() *cobra.Command { } fmt.Printf("Downloading wasm code to %s\n", args[1]) - return ioutil.WriteFile(args[1], res.Data, 0644) + return ioutil.WriteFile(args[1], res.Data, 0644) //nolint }, } flags.AddQueryFlagsToCmd(cmd) @@ -474,6 +474,9 @@ func withPageKeyDecoded(flagSet *flag.FlagSet) *flag.FlagSet { if err != nil { panic(err.Error()) } - flagSet.Set(flags.FlagPageKey, string(raw)) + err = flagSet.Set(flags.FlagPageKey, string(raw)) + if err != nil { + panic(err.Error()) + } return flagSet } diff --git a/x/wasm/client/cli/tx.go b/x/wasm/client/cli/tx.go index 8390e59831..1bcc334d6a 100644 --- a/x/wasm/client/cli/tx.go +++ b/x/wasm/client/cli/tx.go @@ -138,8 +138,10 @@ func InstantiateContractCmd() *cobra.Command { Aliases: []string{"start", "init", "inst", "i"}, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } msg, err := parseInstantiateArgs(args[0], args[1], clientCtx.GetFromAddress(), cmd.Flags()) if err != nil { @@ -207,6 +209,9 @@ func ExecuteContractCmd() *cobra.Command { Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } msg, err := parseExecuteArgs(args[0], args[1], clientCtx.GetFromAddress(), cmd.Flags()) if err != nil { diff --git a/x/wasm/client/rest/gov.go b/x/wasm/client/rest/gov.go index 8ad6830b94..9bc4d6098c 100644 --- a/x/wasm/client/rest/gov.go +++ b/x/wasm/client/rest/gov.go @@ -14,7 +14,7 @@ import ( "github.com/CosmWasm/wasmd/x/wasm/types" ) -type StoreCodeProposalJsonReq struct { +type StoreCodeProposalJSONReq struct { BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` Title string `json:"title" yaml:"title"` @@ -29,7 +29,7 @@ type StoreCodeProposalJsonReq struct { InstantiatePermission *types.AccessConfig `json:"instantiate_permission" yaml:"instantiate_permission"` } -func (s StoreCodeProposalJsonReq) Content() govtypes.Content { +func (s StoreCodeProposalJSONReq) Content() govtypes.Content { return &types.StoreCodeProposal{ Title: s.Title, Description: s.Description, @@ -38,13 +38,13 @@ func (s StoreCodeProposalJsonReq) Content() govtypes.Content { InstantiatePermission: s.InstantiatePermission, } } -func (s StoreCodeProposalJsonReq) GetProposer() string { +func (s StoreCodeProposalJSONReq) GetProposer() string { return s.Proposer } -func (s StoreCodeProposalJsonReq) GetDeposit() sdk.Coins { +func (s StoreCodeProposalJSONReq) GetDeposit() sdk.Coins { return s.Deposit } -func (s StoreCodeProposalJsonReq) GetBaseReq() rest.BaseReq { +func (s StoreCodeProposalJSONReq) GetBaseReq() rest.BaseReq { return s.BaseReq } @@ -52,7 +52,7 @@ func StoreCodeProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler return govrest.ProposalRESTHandler{ SubRoute: "wasm_store_code", Handler: func(w http.ResponseWriter, r *http.Request) { - var req StoreCodeProposalJsonReq + var req StoreCodeProposalJSONReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } @@ -61,7 +61,7 @@ func StoreCodeProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler } } -type InstantiateProposalJsonReq struct { +type InstantiateProposalJSONReq struct { BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` Title string `json:"title" yaml:"title"` @@ -79,7 +79,7 @@ type InstantiateProposalJsonReq struct { Funds sdk.Coins `json:"funds" yaml:"funds"` } -func (s InstantiateProposalJsonReq) Content() govtypes.Content { +func (s InstantiateProposalJSONReq) Content() govtypes.Content { return &types.InstantiateContractProposal{ Title: s.Title, Description: s.Description, @@ -91,13 +91,13 @@ func (s InstantiateProposalJsonReq) Content() govtypes.Content { Funds: s.Funds, } } -func (s InstantiateProposalJsonReq) GetProposer() string { +func (s InstantiateProposalJSONReq) GetProposer() string { return s.Proposer } -func (s InstantiateProposalJsonReq) GetDeposit() sdk.Coins { +func (s InstantiateProposalJSONReq) GetDeposit() sdk.Coins { return s.Deposit } -func (s InstantiateProposalJsonReq) GetBaseReq() rest.BaseReq { +func (s InstantiateProposalJSONReq) GetBaseReq() rest.BaseReq { return s.BaseReq } @@ -105,7 +105,7 @@ func InstantiateProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandl return govrest.ProposalRESTHandler{ SubRoute: "wasm_instantiate", Handler: func(w http.ResponseWriter, r *http.Request) { - var req InstantiateProposalJsonReq + var req InstantiateProposalJSONReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } @@ -114,7 +114,7 @@ func InstantiateProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandl } } -type MigrateProposalJsonReq struct { +type MigrateProposalJSONReq struct { BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` Title string `json:"title" yaml:"title"` @@ -130,7 +130,7 @@ type MigrateProposalJsonReq struct { RunAs string `json:"run_as" yaml:"run_as"` } -func (s MigrateProposalJsonReq) Content() govtypes.Content { +func (s MigrateProposalJSONReq) Content() govtypes.Content { return &types.MigrateContractProposal{ Title: s.Title, Description: s.Description, @@ -140,20 +140,20 @@ func (s MigrateProposalJsonReq) Content() govtypes.Content { RunAs: s.RunAs, } } -func (s MigrateProposalJsonReq) GetProposer() string { +func (s MigrateProposalJSONReq) GetProposer() string { return s.Proposer } -func (s MigrateProposalJsonReq) GetDeposit() sdk.Coins { +func (s MigrateProposalJSONReq) GetDeposit() sdk.Coins { return s.Deposit } -func (s MigrateProposalJsonReq) GetBaseReq() rest.BaseReq { +func (s MigrateProposalJSONReq) GetBaseReq() rest.BaseReq { return s.BaseReq } func MigrateProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "wasm_migrate", Handler: func(w http.ResponseWriter, r *http.Request) { - var req MigrateProposalJsonReq + var req MigrateProposalJSONReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } @@ -162,7 +162,7 @@ func MigrateProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { } } -type UpdateAdminJsonReq struct { +type UpdateAdminJSONReq struct { BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` Title string `json:"title" yaml:"title"` @@ -175,7 +175,7 @@ type UpdateAdminJsonReq struct { Contract string `json:"contract" yaml:"contract"` } -func (s UpdateAdminJsonReq) Content() govtypes.Content { +func (s UpdateAdminJSONReq) Content() govtypes.Content { return &types.UpdateAdminProposal{ Title: s.Title, Description: s.Description, @@ -183,20 +183,20 @@ func (s UpdateAdminJsonReq) Content() govtypes.Content { NewAdmin: s.NewAdmin, } } -func (s UpdateAdminJsonReq) GetProposer() string { +func (s UpdateAdminJSONReq) GetProposer() string { return s.Proposer } -func (s UpdateAdminJsonReq) GetDeposit() sdk.Coins { +func (s UpdateAdminJSONReq) GetDeposit() sdk.Coins { return s.Deposit } -func (s UpdateAdminJsonReq) GetBaseReq() rest.BaseReq { +func (s UpdateAdminJSONReq) GetBaseReq() rest.BaseReq { return s.BaseReq } func UpdateContractAdminProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "wasm_update_admin", Handler: func(w http.ResponseWriter, r *http.Request) { - var req UpdateAdminJsonReq + var req UpdateAdminJSONReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } @@ -205,7 +205,7 @@ func UpdateContractAdminProposalHandler(cliCtx client.Context) govrest.ProposalR } } -type ClearAdminJsonReq struct { +type ClearAdminJSONReq struct { BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` Title string `json:"title" yaml:"title"` @@ -217,27 +217,27 @@ type ClearAdminJsonReq struct { Contract string `json:"contract" yaml:"contract"` } -func (s ClearAdminJsonReq) Content() govtypes.Content { +func (s ClearAdminJSONReq) Content() govtypes.Content { return &types.ClearAdminProposal{ Title: s.Title, Description: s.Description, Contract: s.Contract, } } -func (s ClearAdminJsonReq) GetProposer() string { +func (s ClearAdminJSONReq) GetProposer() string { return s.Proposer } -func (s ClearAdminJsonReq) GetDeposit() sdk.Coins { +func (s ClearAdminJSONReq) GetDeposit() sdk.Coins { return s.Deposit } -func (s ClearAdminJsonReq) GetBaseReq() rest.BaseReq { +func (s ClearAdminJSONReq) GetBaseReq() rest.BaseReq { return s.BaseReq } func ClearContractAdminProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "wasm_clear_admin", Handler: func(w http.ResponseWriter, r *http.Request) { - var req ClearAdminJsonReq + var req ClearAdminJSONReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } diff --git a/x/wasm/client/rest/tx.go b/x/wasm/client/rest/tx.go index 1a3bcb6c5e..847875e6b4 100644 --- a/x/wasm/client/rest/tx.go +++ b/x/wasm/client/rest/tx.go @@ -88,7 +88,6 @@ func instantiateContractHandlerFn(cliCtx client.Context) http.HandlerFunc { return } vars := mux.Vars(r) - codeId := vars["codeId"] req.BaseReq = req.BaseReq.Sanitize() if !req.BaseReq.ValidateBasic(w) { @@ -96,7 +95,7 @@ func instantiateContractHandlerFn(cliCtx client.Context) http.HandlerFunc { } // get the id of the code to instantiate - codeID, err := strconv.ParseUint(codeId, 10, 64) + codeID, err := strconv.ParseUint(vars["codeId"], 10, 64) if err != nil { return } diff --git a/x/wasm/handler.go b/x/wasm/handler.go index dc5656ab16..0007e75ff9 100644 --- a/x/wasm/handler.go +++ b/x/wasm/handler.go @@ -25,7 +25,7 @@ func NewHandler(k types.ContractOpsKeeper) sdk.Handler { err error ) switch msg := msg.(type) { - case *MsgStoreCode: + case *MsgStoreCode: //nolint res, err = msgServer.StoreCode(sdk.WrapSDKContext(ctx), msg) case *MsgInstantiateContract: res, err = msgServer.InstantiateContract(sdk.WrapSDKContext(ctx), msg) diff --git a/x/wasm/ibctesting/chain.go b/x/wasm/ibctesting/chain.go index 2a02260d6d..512df1ab81 100644 --- a/x/wasm/ibctesting/chain.go +++ b/x/wasm/ibctesting/chain.go @@ -10,8 +10,6 @@ import ( "testing" "time" - ibctesting "github.com/cosmos/cosmos-sdk/x/ibc/testing" - wasmd "github.com/CosmWasm/wasmd/app" "github.com/CosmWasm/wasmd/x/wasm/keeper" @@ -41,6 +39,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/ibc/core/exported" "github.com/cosmos/cosmos-sdk/x/ibc/core/types" ibctmtypes "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/07-tendermint/types" + ibctesting "github.com/cosmos/cosmos-sdk/x/ibc/testing" "github.com/cosmos/cosmos-sdk/x/ibc/testing/mock" "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -323,7 +322,10 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { chain.NextBlock() // increment sequence for successful transaction execution - chain.SenderAccount.SetSequence(chain.SenderAccount.GetSequence() + 1) + err = chain.SenderAccount.SetSequence(chain.SenderAccount.GetSequence() + 1) + if err != nil { + return nil, err + } // TODO: also return acks needed to send toSend := getSendPackets(r.Events) @@ -367,12 +369,12 @@ func getAckPackets(evts []abci.Event) []PacketAck { } // Used for various debug statements above when needed... do not remove -func showEvent(evt abci.Event) { - fmt.Printf("evt.Type: %s\n", evt.Type) - for _, attr := range evt.Attributes { - fmt.Printf(" %s = %s\n", string(attr.Key), string(attr.Value)) - } -} +// func showEvent(evt abci.Event) { +// fmt.Printf("evt.Type: %s\n", evt.Type) +// for _, attr := range evt.Attributes { +// fmt.Printf(" %s = %s\n", string(attr.Key), string(attr.Value)) +// } +//} func parsePacketFromEvent(evt abci.Event) channeltypes.Packet { return channeltypes.Packet{ @@ -525,7 +527,7 @@ func (chain *TestChain) GetFirstTestConnection(clientID, counterpartyClientID st return chain.ConstructNextTestConnection(clientID, counterpartyClientID) } -// Add ibctesting.TestChannel appends a new ibctesting.TestChannel which contains references to the port and channel ID +// AddTestChannel Add ibctesting.TestChannel appends a new ibctesting.TestChannel which contains references to the port and channel ID // used for channel creation and interaction. See 'Next ibctesting.TestChannel' for channel ID naming format. func (chain *TestChain) AddTestChannel(conn *ibctesting.TestConnection, portID string) ibctesting.TestChannel { channel := chain.NextChannel(conn, portID) @@ -533,7 +535,7 @@ func (chain *TestChain) AddTestChannel(conn *ibctesting.TestConnection, portID s return channel } -// Next ibctesting.TestChannel returns the next test channel to be created on this connection, but does not +// NextChannel Next ibctesting.TestChannel returns the next test channel to be created on this connection, but does not // add it to the list of created channels. This function is expected to be used when the caller // has not created the associated channel in app state, but would still like to refer to the // non-existent channel usually to test for its non-existence. @@ -698,11 +700,9 @@ func (chain *TestChain) CreateTMClientHeader(chainID string, blockHeight int64, Commit: commit.ToProto(), } - if tmValSet != nil { - valSet, err = tmValSet.ToProto() - if err != nil { - panic(err) - } + valSet, err = tmValSet.ToProto() + if err != nil { + panic(err) } if tmTrustedVals != nil { diff --git a/x/wasm/ibctesting/coordinator.go b/x/wasm/ibctesting/coordinator.go index 2b0cf70640..2549bc0c95 100644 --- a/x/wasm/ibctesting/coordinator.go +++ b/x/wasm/ibctesting/coordinator.go @@ -6,16 +6,16 @@ import ( "testing" "time" - ibctesting "github.com/cosmos/cosmos-sdk/x/ibc/testing" - - "github.com/CosmWasm/wasmd/x/wasm/keeper" - sdk "github.com/cosmos/cosmos-sdk/types" channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types" host "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host" "github.com/cosmos/cosmos-sdk/x/ibc/core/exported" + ibctesting "github.com/cosmos/cosmos-sdk/x/ibc/testing" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + + "github.com/CosmWasm/wasmd/x/wasm/keeper" ) var ( @@ -393,8 +393,11 @@ func (coord *Coordinator) RelayAndAckPendingPackets(src, dest *TestChain, srcCli coord.IncrementTime() coord.CommitBlock(src) err := coord.UpdateClient(dest, src, dstClientID, exported.Tendermint) + if err != nil { + return err + } for _, packet := range toSend { - err = coord.RecvPacket(src, dest, srcClientID, packet) + err := coord.RecvPacket(src, dest, srcClientID, packet) if err != nil { return err } diff --git a/x/wasm/ibctesting/wasm.go b/x/wasm/ibctesting/wasm.go index 89fad09457..b752b24608 100644 --- a/x/wasm/ibctesting/wasm.go +++ b/x/wasm/ibctesting/wasm.go @@ -9,7 +9,7 @@ import ( "strings" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/golang/protobuf/proto" + "github.com/golang/protobuf/proto" //nolint "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/rand" @@ -24,72 +24,72 @@ var wasmIdent = []byte("\x00\x61\x73\x6D") // This method can be called to prepare the store with some valid CodeInfo and ContractInfo. The returned // Address is the contract address for this instance. Test should make use of this data and/or use NewIBCContractMockWasmer // for using a contract mock in Go. -func (c *TestChain) SeedNewContractInstance() sdk.AccAddress { - pInstResp := c.StoreCode(append(wasmIdent, rand.Bytes(10)...)) +func (chain *TestChain) SeedNewContractInstance() sdk.AccAddress { + pInstResp := chain.StoreCode(append(wasmIdent, rand.Bytes(10)...)) codeID := pInstResp.CodeID - anyAddressStr := c.SenderAccount.GetAddress().String() + anyAddressStr := chain.SenderAccount.GetAddress().String() initMsg := []byte(fmt.Sprintf(`{"verifier": %q, "beneficiary": %q}`, anyAddressStr, anyAddressStr)) - return c.InstantiateContract(codeID, initMsg) + return chain.InstantiateContract(codeID, initMsg) } -func (c *TestChain) StoreCodeFile(filename string) types.MsgStoreCodeResponse { +func (chain *TestChain) StoreCodeFile(filename string) types.MsgStoreCodeResponse { wasmCode, err := ioutil.ReadFile(filename) - require.NoError(c.t, err) + require.NoError(chain.t, err) if strings.HasSuffix(filename, "wasm") { // compress for gas limit var buf bytes.Buffer gz := gzip.NewWriter(&buf) _, err := gz.Write(wasmCode) - require.NoError(c.t, err) + require.NoError(chain.t, err) err = gz.Close() - require.NoError(c.t, err) + require.NoError(chain.t, err) wasmCode = buf.Bytes() } - return c.StoreCode(wasmCode) + return chain.StoreCode(wasmCode) } -func (c *TestChain) StoreCode(byteCode []byte) types.MsgStoreCodeResponse { +func (chain *TestChain) StoreCode(byteCode []byte) types.MsgStoreCodeResponse { storeMsg := &types.MsgStoreCode{ - Sender: c.SenderAccount.GetAddress().String(), + Sender: chain.SenderAccount.GetAddress().String(), WASMByteCode: byteCode, } - r, err := c.SendMsgs(storeMsg) - require.NoError(c.t, err) - protoResult := c.parseSDKResultData(r) - require.Len(c.t, protoResult.Data, 1) + r, err := chain.SendMsgs(storeMsg) + require.NoError(chain.t, err) + protoResult := chain.parseSDKResultData(r) + require.Len(chain.t, protoResult.Data, 1) // unmarshal protobuf response from data var pInstResp types.MsgStoreCodeResponse - require.NoError(c.t, pInstResp.Unmarshal(protoResult.Data[0].Data)) - require.NotEmpty(c.t, pInstResp.CodeID) + require.NoError(chain.t, pInstResp.Unmarshal(protoResult.Data[0].Data)) + require.NotEmpty(chain.t, pInstResp.CodeID) return pInstResp } -func (c *TestChain) InstantiateContract(codeID uint64, initMsg []byte) sdk.AccAddress { +func (chain *TestChain) InstantiateContract(codeID uint64, initMsg []byte) sdk.AccAddress { instantiateMsg := &types.MsgInstantiateContract{ - Sender: c.SenderAccount.GetAddress().String(), - Admin: c.SenderAccount.GetAddress().String(), + Sender: chain.SenderAccount.GetAddress().String(), + Admin: chain.SenderAccount.GetAddress().String(), CodeID: codeID, Label: "ibc-test", Msg: initMsg, Funds: sdk.Coins{TestCoin}, } - r, err := c.SendMsgs(instantiateMsg) - require.NoError(c.t, err) - protoResult := c.parseSDKResultData(r) - require.Len(c.t, protoResult.Data, 1) + r, err := chain.SendMsgs(instantiateMsg) + require.NoError(chain.t, err) + protoResult := chain.parseSDKResultData(r) + require.Len(chain.t, protoResult.Data, 1) var pExecResp types.MsgInstantiateContractResponse - require.NoError(c.t, pExecResp.Unmarshal(protoResult.Data[0].Data)) + require.NoError(chain.t, pExecResp.Unmarshal(protoResult.Data[0].Data)) a, err := sdk.AccAddressFromBech32(pExecResp.Address) - require.NoError(c.t, err) + require.NoError(chain.t, err) return a } -// This will serialize the query message and submit it to the contract. +// SmartQuery This will serialize the query message and submit it to the contract. // The response is parsed into the provided interface. // Usage: SmartQuery(addr, QueryMsg{Foo: 1}, &response) -func (c *TestChain) SmartQuery(contractAddr string, queryMsg interface{}, response interface{}) error { +func (chain *TestChain) SmartQuery(contractAddr string, queryMsg interface{}, response interface{}) error { msg, err := json.Marshal(queryMsg) if err != nil { return err @@ -105,13 +105,13 @@ func (c *TestChain) SmartQuery(contractAddr string, queryMsg interface{}, respon } // TODO: what is the query? - res := c.App.Query(abci.RequestQuery{ + res := chain.App.Query(abci.RequestQuery{ Path: "/cosmwasm.wasm.v1.Query/SmartContractState", Data: reqBin, }) if res.Code != 0 { - return fmt.Errorf("Query failed: (%d) %s", res.Code, res.Log) + return fmt.Errorf("query failed: (%d) %s", res.Code, res.Log) } // unpack protobuf @@ -124,18 +124,18 @@ func (c *TestChain) SmartQuery(contractAddr string, queryMsg interface{}, respon return json.Unmarshal(resp.Data, response) } -func (c *TestChain) parseSDKResultData(r *sdk.Result) sdk.TxMsgData { +func (chain *TestChain) parseSDKResultData(r *sdk.Result) sdk.TxMsgData { var protoResult sdk.TxMsgData - require.NoError(c.t, proto.Unmarshal(r.Data, &protoResult)) + require.NoError(chain.t, proto.Unmarshal(r.Data, &protoResult)) return protoResult } // ContractInfo is a helper function to returns the ContractInfo for the given contract address -func (c *TestChain) ContractInfo(contractAddr sdk.AccAddress) *types.ContractInfo { - return c.TestSupport().WasmKeeper().GetContractInfo(c.GetContext(), contractAddr) +func (chain *TestChain) ContractInfo(contractAddr sdk.AccAddress) *types.ContractInfo { + return chain.TestSupport().WasmKeeper().GetContractInfo(chain.GetContext(), contractAddr) } // TestSupport provides access to package private keepers. -func (c *TestChain) TestSupport() *wasmd.TestSupport { - return wasmd.NewTestSupport(c.t, c.App) +func (chain *TestChain) TestSupport() *wasmd.TestSupport { + return wasmd.NewTestSupport(chain.t, chain.App) } diff --git a/x/wasm/keeper/ante.go b/x/wasm/keeper/ante.go index 29cb282037..2b95e415c8 100644 --- a/x/wasm/keeper/ante.go +++ b/x/wasm/keeper/ante.go @@ -29,7 +29,7 @@ func (a CountTXDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, store := ctx.KVStore(a.storeKey) currentHeight := ctx.BlockHeight() - var txCounter uint32 = 0 // start with 0 + var txCounter uint32 // start with 0 // load counter when exists if bz := store.Get(types.TXCounterPrefix); bz != nil { lastHeight, val := decodeHeightCounter(bz) diff --git a/x/wasm/keeper/api.go b/x/wasm/keeper/api.go index 44d4ad2dfb..4d47cce79e 100644 --- a/x/wasm/keeper/api.go +++ b/x/wasm/keeper/api.go @@ -21,7 +21,7 @@ const ( var ( costHumanize = DefaultGasCostHumanAddress * DefaultGasMultiplier costCanonical = DefaultGasCostCanonicalAddress * DefaultGasMultiplier - costJsonDeserialization = wasmvmtypes.UFraction{ + costJSONDeserialization = wasmvmtypes.UFraction{ Numerator: DefaultDeserializationCostPerByte * DefaultGasMultiplier, Denominator: 1, } @@ -29,7 +29,7 @@ var ( func humanAddress(canon []byte) (string, uint64, error) { if len(canon) != sdk.AddrLen { - return "", costHumanize, fmt.Errorf("Expected %d byte address", sdk.AddrLen) + return "", costHumanize, fmt.Errorf("expected %d byte address", sdk.AddrLen) } return sdk.AccAddress(canon).String(), costHumanize, nil } diff --git a/x/wasm/keeper/gas_register.go b/x/wasm/keeper/gas_register.go index f11782aa01..c21606344f 100644 --- a/x/wasm/keeper/gas_register.go +++ b/x/wasm/keeper/gas_register.go @@ -164,7 +164,7 @@ func (g WasmGasRegister) ReplyCosts(pinned bool, reply wasmvmtypes.Reply) sdk.Ga var attrs []wasmvmtypes.EventAttribute for _, e := range reply.Result.Ok.Events { eventGas += sdk.Gas(len(e.Type)) * g.c.EventAttributeDataCost - attrs = append(e.Attributes) + attrs = append(attrs, e.Attributes...) } // apply free tier on the whole set not per event eventGas += g.EventCosts(attrs, nil) diff --git a/x/wasm/keeper/handler_plugin_encoders_test.go b/x/wasm/keeper/handler_plugin_encoders_test.go index 90b4c04ff1..67743171b8 100644 --- a/x/wasm/keeper/handler_plugin_encoders_test.go +++ b/x/wasm/keeper/handler_plugin_encoders_test.go @@ -12,8 +12,6 @@ import ( "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" - "github.com/CosmWasm/wasmd/x/wasm/keeper/wasmtesting" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -21,6 +19,7 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" + "github.com/CosmWasm/wasmd/x/wasm/keeper/wasmtesting" "github.com/CosmWasm/wasmd/x/wasm/types" ) diff --git a/x/wasm/keeper/ibc.go b/x/wasm/keeper/ibc.go index 02529abb1d..d99bafa630 100644 --- a/x/wasm/keeper/ibc.go +++ b/x/wasm/keeper/ibc.go @@ -50,7 +50,7 @@ func (k Keeper) AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Cap } // ClaimCapability allows the transfer module to claim a capability -//that IBC module passes to it +// that IBC module passes to it func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error { return k.capabilityKeeper.ClaimCapability(ctx, cap, name) } diff --git a/x/wasm/keeper/keeper.go b/x/wasm/keeper/keeper.go index 28729f3b82..9c1cdc2c50 100644 --- a/x/wasm/keeper/keeper.go +++ b/x/wasm/keeper/keeper.go @@ -19,7 +19,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/log" "github.com/CosmWasm/wasmd/x/wasm/types" @@ -281,7 +280,7 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A // instantiate wasm contract gas := k.runtimeGasForContract(ctx) - res, gasUsed, err := k.wasmVM.Instantiate(codeInfo.CodeHash, env, info, initMsg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJsonDeserialization) + res, gasUsed, err := k.wasmVM.Instantiate(codeInfo.CodeHash, env, info, initMsg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if err != nil { return nil, nil, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error()) @@ -349,7 +348,7 @@ func (k Keeper) execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller // prepare querier querier := k.newQueryHandler(ctx, contractAddress) gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.Execute(codeInfo.CodeHash, env, info, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJsonDeserialization) + res, gasUsed, execErr := k.wasmVM.Execute(codeInfo.CodeHash, env, info, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) @@ -410,7 +409,7 @@ func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller prefixStoreKey := types.GetContractStorePrefix(contractAddress) prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) gas := k.runtimeGasForContract(ctx) - res, gasUsed, err := k.wasmVM.Migrate(newCodeInfo.CodeHash, env, msg, &prefixStore, cosmwasmAPI, &querier, k.gasMeter(ctx), gas, costJsonDeserialization) + res, gasUsed, err := k.wasmVM.Migrate(newCodeInfo.CodeHash, env, msg, &prefixStore, cosmwasmAPI, &querier, k.gasMeter(ctx), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if err != nil { return nil, sdkerrors.Wrap(types.ErrMigrationFailed, err.Error()) @@ -456,7 +455,7 @@ func (k Keeper) Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte // prepare querier querier := k.newQueryHandler(ctx, contractAddress) gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.Sudo(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJsonDeserialization) + res, gasUsed, execErr := k.wasmVM.Sudo(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) @@ -491,7 +490,7 @@ func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply was // prepare querier querier := k.newQueryHandler(ctx, contractAddress) gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.Reply(codeInfo.CodeHash, env, reply, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJsonDeserialization) + res, gasUsed, execErr := k.wasmVM.Reply(codeInfo.CodeHash, env, reply, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) @@ -557,7 +556,7 @@ func (k Keeper) appendToContractHistory(ctx sdk.Context, contractAddr sdk.AccAdd for _, e := range newEntries { pos++ key := types.GetContractCodeHistoryElementKey(contractAddr, pos) - store.Set(key, k.cdc.MustMarshalBinaryBare(&e)) + store.Set(key, k.cdc.MustMarshalBinaryBare(&e)) //nolint } } @@ -601,7 +600,7 @@ func (k Keeper) QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []b querier := k.newQueryHandler(ctx, contractAddr) env := types.NewEnv(ctx, contractAddr) - queryResult, gasUsed, qErr := k.wasmVM.Query(codeInfo.CodeHash, env, req, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), k.runtimeGasForContract(ctx), costJsonDeserialization) + queryResult, gasUsed, qErr := k.wasmVM.Query(codeInfo.CodeHash, env, req, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), k.runtimeGasForContract(ctx), costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if qErr != nil { return nil, sdkerrors.Wrap(types.ErrQueryFailed, qErr.Error()) @@ -976,13 +975,6 @@ func (k Keeper) newQueryHandler(ctx sdk.Context, contractAddress sdk.AccAddress) return NewQueryHandler(ctx, k.wasmVMQueryHandler, contractAddress, k.gasRegister) } -func addrFromUint64(id uint64) sdk.AccAddress { - addr := make([]byte, 20) - addr[0] = 'C' - binary.PutUvarint(addr[1:], id) - return sdk.AccAddress(crypto.AddressHash(addr)) -} - // MultipliedGasMeter wraps the GasMeter from context and multiplies all reads by out defined multiplier type MultipliedGasMeter struct { originalMeter sdk.GasMeter diff --git a/x/wasm/keeper/keeper_test.go b/x/wasm/keeper/keeper_test.go index 116334c746..b205fb8589 100644 --- a/x/wasm/keeper/keeper_test.go +++ b/x/wasm/keeper/keeper_test.go @@ -11,18 +11,19 @@ import ( wasmvm "github.com/CosmWasm/wasmvm" wasmvmtypes "github.com/CosmWasm/wasmvm/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - - "github.com/CosmWasm/wasmd/x/wasm/keeper/wasmtesting" stypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "github.com/CosmWasm/wasmd/x/wasm/keeper/wasmtesting" "github.com/CosmWasm/wasmd/x/wasm/types" ) @@ -663,7 +664,7 @@ func TestExecuteWithNonExistingAddress(t *testing.T) { creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) // unauthorized - trialCtx so we don't change state - nonExistingAddress := addrFromUint64(9999) + nonExistingAddress := RandomAccountAddress(t) _, err := keeper.Execute(ctx, nonExistingAddress, creator, []byte(`{}`), nil) require.True(t, types.ErrNotFound.Is(err), err) } diff --git a/x/wasm/keeper/legacy_querier.go b/x/wasm/keeper/legacy_querier.go index af2d25ea2b..4c1ba4d8ee 100644 --- a/x/wasm/keeper/legacy_querier.go +++ b/x/wasm/keeper/legacy_querier.go @@ -36,15 +36,15 @@ func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier { ) switch path[0] { case QueryGetContract: - addr, err := sdk.AccAddressFromBech32(path[1]) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) + addr, addrErr := sdk.AccAddressFromBech32(path[1]) + if addrErr != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, addrErr.Error()) } rsp, err = queryContractInfo(ctx, addr, keeper) case QueryListContractByCode: - codeID, err := strconv.ParseUint(path[1], 10, 64) - if err != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", err.Error()) + codeID, parseErr := strconv.ParseUint(path[1], 10, 64) + if parseErr != nil { + return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", parseErr.Error()) } rsp = queryContractListByCode(ctx, codeID, keeper) case QueryGetContractState: @@ -53,17 +53,17 @@ func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier { } return queryContractState(ctx, path[1], path[2], req.Data, gasLimit, keeper) case QueryGetCode: - codeID, err := strconv.ParseUint(path[1], 10, 64) - if err != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", err.Error()) + codeID, parseErr := strconv.ParseUint(path[1], 10, 64) + if parseErr != nil { + return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", parseErr.Error()) } rsp, err = queryCode(ctx, codeID, keeper) case QueryListCode: rsp, err = queryCodeList(ctx, keeper) case QueryContractHistory: - contractAddr, err := sdk.AccAddressFromBech32(path[1]) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) + contractAddr, addrErr := sdk.AccAddressFromBech32(path[1]) + if addrErr != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, addrErr.Error()) } rsp, err = queryContractHistory(ctx, contractAddr, keeper) default: diff --git a/x/wasm/keeper/metrics.go b/x/wasm/keeper/metrics.go index d271335e49..4c4b959f50 100644 --- a/x/wasm/keeper/metrics.go +++ b/x/wasm/keeper/metrics.go @@ -27,7 +27,7 @@ type WasmVMMetricsCollector struct { CacheSizeDescr *prometheus.Desc } -//NewWasmVMMetricsCollector constructor +// NewWasmVMMetricsCollector constructor func NewWasmVMMetricsCollector(s metricSource) *WasmVMMetricsCollector { return &WasmVMMetricsCollector{ source: s, diff --git a/x/wasm/keeper/msg_dispatcher.go b/x/wasm/keeper/msg_dispatcher.go index b2ffbb4ca6..edbfe162dc 100644 --- a/x/wasm/keeper/msg_dispatcher.go +++ b/x/wasm/keeper/msg_dispatcher.go @@ -126,7 +126,7 @@ func (d MessageDispatcher) DispatchSubmessages(ctx sdk.Context, contractAddr sdk } result = wasmvmtypes.SubcallResult{ Ok: &wasmvmtypes.SubcallResponse{ - Events: sdkEventsToWasmVmEvents(filteredEvents), + Events: sdkEventsToWasmVMEvents(filteredEvents), Data: responseData, }, } @@ -166,18 +166,18 @@ func filterEvents(events []sdk.Event) []sdk.Event { return res } -func sdkEventsToWasmVmEvents(events []sdk.Event) []wasmvmtypes.Event { +func sdkEventsToWasmVMEvents(events []sdk.Event) []wasmvmtypes.Event { res := make([]wasmvmtypes.Event, len(events)) for i, ev := range events { res[i] = wasmvmtypes.Event{ Type: ev.Type, - Attributes: sdkAttributesToWasmVmAttributes(ev.Attributes), + Attributes: sdkAttributesToWasmVMAttributes(ev.Attributes), } } return res } -func sdkAttributesToWasmVmAttributes(attrs []abci.EventAttribute) []wasmvmtypes.EventAttribute { +func sdkAttributesToWasmVMAttributes(attrs []abci.EventAttribute) []wasmvmtypes.EventAttribute { res := make([]wasmvmtypes.EventAttribute, len(attrs)) for i, attr := range attrs { res[i] = wasmvmtypes.EventAttribute{ diff --git a/x/wasm/keeper/options.go b/x/wasm/keeper/options.go index b028a2745b..8885ac218c 100644 --- a/x/wasm/keeper/options.go +++ b/x/wasm/keeper/options.go @@ -109,8 +109,8 @@ func WithGasRegister(x GasRegister) Option { }) } -// WithApiCosts sets custom api costs. Amounts are in cosmwasm gas Not SDK gas. -func WithApiCosts(human, canonical uint64) Option { +// WithAPICosts sets custom api costs. Amounts are in cosmwasm gas Not SDK gas. +func WithAPICosts(human, canonical uint64) Option { return optsFn(func(_ *Keeper) { costHumanize = human costCanonical = canonical diff --git a/x/wasm/keeper/options_test.go b/x/wasm/keeper/options_test.go index 40f3fd9c89..89af95b7bc 100644 --- a/x/wasm/keeper/options_test.go +++ b/x/wasm/keeper/options_test.go @@ -68,7 +68,7 @@ func TestConstructorOptions(t *testing.T) { }, }, "api costs": { - srcOpt: WithApiCosts(1, 2), + srcOpt: WithAPICosts(1, 2), verify: func(t *testing.T, k Keeper) { t.Cleanup(setApiDefaults) assert.Equal(t, uint64(1), costHumanize) diff --git a/x/wasm/keeper/querier.go b/x/wasm/keeper/querier.go index 40faa7ae16..3047a46bbb 100644 --- a/x/wasm/keeper/querier.go +++ b/x/wasm/keeper/querier.go @@ -27,7 +27,7 @@ type grpcQuerier struct { } // NewGrpcQuerier constructor -func NewGrpcQuerier(cdc codec.Marshaler, storeKey sdk.StoreKey, keeper types.ViewKeeper, queryGasLimit sdk.Gas) *grpcQuerier { +func NewGrpcQuerier(cdc codec.Marshaler, storeKey sdk.StoreKey, keeper types.ViewKeeper, queryGasLimit sdk.Gas) *grpcQuerier { //nolint return &grpcQuerier{cdc: cdc, storeKey: storeKey, keeper: keeper, queryGasLimit: queryGasLimit} } diff --git a/x/wasm/keeper/query_plugins.go b/x/wasm/keeper/query_plugins.go index 10600ae2ab..6475945a44 100644 --- a/x/wasm/keeper/query_plugins.go +++ b/x/wasm/keeper/query_plugins.go @@ -288,7 +288,7 @@ func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKee } if request.AllValidators != nil { validators := keeper.GetBondedValidatorsByPower(ctx) - //validators := keeper.GetAllValidators(ctx) + // validators := keeper.GetAllValidators(ctx) wasmVals := make([]wasmvmtypes.Validator, len(validators)) for i, v := range validators { wasmVals[i] = wasmvmtypes.Validator{ diff --git a/x/wasm/keeper/relay.go b/x/wasm/keeper/relay.go index 345f2304ef..84ee1de726 100644 --- a/x/wasm/keeper/relay.go +++ b/x/wasm/keeper/relay.go @@ -34,7 +34,7 @@ func (k Keeper) OnOpenChannel( querier := k.newQueryHandler(ctx, contractAddr) gas := k.runtimeGasForContract(ctx) - gasUsed, execErr := k.wasmVM.IBCChannelOpen(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJsonDeserialization) + gasUsed, execErr := k.wasmVM.IBCChannelOpen(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { return sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) @@ -65,7 +65,7 @@ func (k Keeper) OnConnectChannel( querier := k.newQueryHandler(ctx, contractAddr) gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCChannelConnect(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJsonDeserialization) + res, gasUsed, execErr := k.wasmVM.IBCChannelConnect(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { return sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) @@ -96,7 +96,7 @@ func (k Keeper) OnCloseChannel( querier := k.newQueryHandler(ctx, contractAddr) gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCChannelClose(codeInfo.CodeHash, params, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJsonDeserialization) + res, gasUsed, execErr := k.wasmVM.IBCChannelClose(codeInfo.CodeHash, params, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { return sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) @@ -126,7 +126,7 @@ func (k Keeper) OnRecvPacket( querier := k.newQueryHandler(ctx, contractAddr) gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCPacketReceive(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJsonDeserialization) + res, gasUsed, execErr := k.wasmVM.IBCPacketReceive(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) @@ -157,7 +157,7 @@ func (k Keeper) OnAckPacket( querier := k.newQueryHandler(ctx, contractAddr) gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCPacketAck(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJsonDeserialization) + res, gasUsed, execErr := k.wasmVM.IBCPacketAck(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { return sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) @@ -184,7 +184,7 @@ func (k Keeper) OnTimeoutPacket( querier := k.newQueryHandler(ctx, contractAddr) gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCPacketTimeout(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJsonDeserialization) + res, gasUsed, execErr := k.wasmVM.IBCPacketTimeout(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { return sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) diff --git a/x/wasm/keeper/test_common.go b/x/wasm/keeper/test_common.go index 28a7f0d6e9..e1f3b9df88 100644 --- a/x/wasm/keeper/test_common.go +++ b/x/wasm/keeper/test_common.go @@ -498,7 +498,7 @@ func StoreRandomContract(t TestingT, ctx sdk.Context, keepers TestKeepers, mock creator, _, creatorAddr := keyPubAddr() fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount) keepers.WasmKeeper.wasmVM = mock - wasmCode := append(wasmIdent, rand.Bytes(10)...) + wasmCode := append(wasmIdent, rand.Bytes(10)...) //nolint codeID, err := keepers.ContractKeeper.Create(ctx, creatorAddr, wasmCode, nil) require.NoError(t, err) exampleContract := ExampleContract{InitialAmount: anyAmount, Creator: creator, CreatorAddr: creatorAddr, CodeID: codeID} @@ -599,7 +599,7 @@ func (m BurnerExampleInitMsg) GetBytes(t TestingT) []byte { return initMsgBz } -func createFakeFundedAccount(t TestingT, ctx sdk.Context, am authkeeper.AccountKeeper, bank bankkeeper.Keeper, coins sdk.Coins) sdk.AccAddress { +func createFakeFundedAccount(t TestingT, ctx sdk.Context, am authkeeper.AccountKeeper, bank bankkeeper.Keeper, coins sdk.Coins) sdk.AccAddress { //nolint _, _, addr := keyPubAddr() fundAccounts(t, ctx, am, bank, addr, coins) return addr @@ -611,7 +611,7 @@ func fundAccounts(t TestingT, ctx sdk.Context, am authkeeper.AccountKeeper, bank require.NoError(t, bank.SetBalances(ctx, addr, coins)) } -var keyCounter uint64 = 0 +var keyCounter uint64 // we need to make this deterministic (same every test run), as encoded address size and thus gas cost, // depends on the actual bytes (due to ugly CanonicalAddress encoding) diff --git a/x/wasm/keeper/wasmtesting/mock_engine.go b/x/wasm/keeper/wasmtesting/mock_engine.go index 41394119b2..b0995bbccf 100644 --- a/x/wasm/keeper/wasmtesting/mock_engine.go +++ b/x/wasm/keeper/wasmtesting/mock_engine.go @@ -290,14 +290,14 @@ type contractExecutable interface { ) (*wasmvmtypes.Response, uint64, error) } -//MakeInstantiable adds some noop functions to not fail when contract is used for instantiation +// MakeInstantiable adds some noop functions to not fail when contract is used for instantiation func MakeInstantiable(m *MockWasmer) { m.CreateFn = HashOnlyCreateFn m.InstantiateFn = NoOpInstantiateFn m.AnalyzeCodeFn = WithoutIBCAnalyzeFn } -//MakeIBCInstantiable adds some noop functions to not fail when contract is used for instantiation +// MakeIBCInstantiable adds some noop functions to not fail when contract is used for instantiation func MakeIBCInstantiable(m *MockWasmer) { MakeInstantiable(m) m.AnalyzeCodeFn = HasIBCAnalyzeFn diff --git a/x/wasm/module.go b/x/wasm/module.go index 5f1b1c1bec..3e56967d58 100644 --- a/x/wasm/module.go +++ b/x/wasm/module.go @@ -40,12 +40,12 @@ const ( // AppModuleBasic defines the basic application module used by the wasm module. type AppModuleBasic struct{} -func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { +func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { //nolint RegisterCodec(amino) } func (b AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, serveMux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(clientCtx)) + types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(clientCtx)) //nolint } // Name returns the wasm module's name. @@ -86,12 +86,12 @@ func (b AppModuleBasic) GetQueryCmd() *cobra.Command { return cli.GetQueryCmd() } -// RegisterInterfaceTypes implements InterfaceModule +// RegisterInterfaces implements InterfaceModule func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -//____________________________________________________________________________ +// ____________________________________________________________________________ // AppModule implements an application module for the wasm module. type AppModule struct { @@ -116,7 +116,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterQueryServer(cfg.QueryServer(), NewQuerier(am.keeper)) } -func (am AppModule) LegacyQuerierHandler(amino *codec.LegacyAmino) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(amino *codec.LegacyAmino) sdk.Querier { //nolint return keeper.NewLegacyQuerier(am.keeper, am.keeper.QueryGasLimit()) } @@ -161,7 +161,7 @@ func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Validato return []abci.ValidatorUpdate{} } -//____________________________________________________________________________ +// ____________________________________________________________________________ // AppModuleSimulation functions @@ -189,7 +189,7 @@ func (am AppModule) WeightedOperations(simState module.SimulationState) []simtyp return nil } -//____________________________________________________________________________ +// ____________________________________________________________________________ // AddModuleInitFlags implements servertypes.ModuleInitFlags interface. func AddModuleInitFlags(startCmd *cobra.Command) { diff --git a/x/wasm/types/codec.go b/x/wasm/types/codec.go index 70fa771cef..7213496f20 100644 --- a/x/wasm/types/codec.go +++ b/x/wasm/types/codec.go @@ -10,7 +10,7 @@ import ( ) // RegisterLegacyAminoCodec registers the account types and interface -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { //nolint cdc.RegisterConcrete(&MsgStoreCode{}, "wasm/MsgStoreCode", nil) cdc.RegisterConcrete(&MsgInstantiateContract{}, "wasm/MsgInstantiateContract", nil) cdc.RegisterConcrete(&MsgExecuteContract{}, "wasm/MsgExecuteContract", nil) diff --git a/x/wasm/types/exported_keepers.go b/x/wasm/types/exported_keepers.go index 345cbf09df..02f227648b 100644 --- a/x/wasm/types/exported_keepers.go +++ b/x/wasm/types/exported_keepers.go @@ -2,25 +2,24 @@ package types import ( wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" ) // ViewKeeper provides read only operations type ViewKeeper interface { - GetContractHistory(ctx types.Context, contractAddr types.AccAddress) []ContractCodeHistoryEntry - QuerySmart(ctx types.Context, contractAddr types.AccAddress, req []byte) ([]byte, error) - QueryRaw(ctx types.Context, contractAddress types.AccAddress, key []byte) []byte + GetContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress) []ContractCodeHistoryEntry + QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) + QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte HasContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) bool - GetContractInfo(ctx types.Context, contractAddress types.AccAddress) *ContractInfo - IterateContractInfo(ctx types.Context, cb func(types.AccAddress, ContractInfo) bool) + GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *ContractInfo + IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, ContractInfo) bool) IterateContractsByCode(ctx sdk.Context, codeID uint64, cb func(address sdk.AccAddress) bool) - GetContractState(ctx types.Context, contractAddress types.AccAddress) types.Iterator - GetCodeInfo(ctx types.Context, codeID uint64) *CodeInfo - IterateCodeInfos(ctx types.Context, cb func(uint64, CodeInfo) bool) - GetByteCode(ctx types.Context, codeID uint64) ([]byte, error) - IsPinnedCode(ctx types.Context, codeID uint64) bool + GetContractState(ctx sdk.Context, contractAddress sdk.AccAddress) sdk.Iterator + GetCodeInfo(ctx sdk.Context, codeID uint64) *CodeInfo + IterateCodeInfos(ctx sdk.Context, cb func(uint64, CodeInfo) bool) + GetByteCode(ctx sdk.Context, codeID uint64) ([]byte, error) + IsPinnedCode(ctx sdk.Context, codeID uint64) bool } // ContractOpsKeeper contains mutable operations on a contract. @@ -86,7 +85,7 @@ type IBCContractKeeper interface { msg wasmvmtypes.IBCPacketTimeoutMsg, ) error // ClaimCapability allows the transfer module to claim a capability - //that IBC module passes to it + // that IBC module passes to it ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error // AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool diff --git a/x/wasm/types/genesis.go b/x/wasm/types/genesis.go index 5aa9ba02a0..98df6fd6ad 100644 --- a/x/wasm/types/genesis.go +++ b/x/wasm/types/genesis.go @@ -1,6 +1,5 @@ package types -import "C" import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/wasm/types/params.go b/x/wasm/types/params.go index cbfbfc8548..1a3eede898 100644 --- a/x/wasm/types/params.go +++ b/x/wasm/types/params.go @@ -103,7 +103,10 @@ func DefaultParams() Params { } func (p Params) String() string { - out, _ := yaml.Marshal(p) + out, err := yaml.Marshal(p) + if err != nil { + panic(err) + } return string(out) } @@ -165,30 +168,30 @@ func validateMaxWasmCodeSize(i interface{}) error { return nil } -func (v AccessConfig) ValidateBasic() error { - switch v.Permission { +func (a AccessConfig) ValidateBasic() error { + switch a.Permission { case AccessTypeUnspecified: return sdkerrors.Wrap(ErrEmpty, "type") case AccessTypeNobody, AccessTypeEverybody: - if len(v.Address) != 0 { + if len(a.Address) != 0 { return sdkerrors.Wrap(ErrInvalid, "address not allowed for this type") } return nil case AccessTypeOnlyAddress: - _, err := sdk.AccAddressFromBech32(v.Address) + _, err := sdk.AccAddressFromBech32(a.Address) return err } - return sdkerrors.Wrapf(ErrInvalid, "unknown type: %q", v.Permission) + return sdkerrors.Wrapf(ErrInvalid, "unknown type: %q", a.Permission) } -func (v AccessConfig) Allowed(actor sdk.AccAddress) bool { - switch v.Permission { +func (a AccessConfig) Allowed(actor sdk.AccAddress) bool { + switch a.Permission { case AccessTypeNobody: return false case AccessTypeEverybody: return true case AccessTypeOnlyAddress: - return v.Address == actor.String() + return a.Address == actor.String() default: panic("unknown type") } diff --git a/x/wasm/types/types.go b/x/wasm/types/types.go index 075cfe1317..9215eb9aee 100644 --- a/x/wasm/types/types.go +++ b/x/wasm/types/types.go @@ -196,9 +196,9 @@ type ContractInfoExtension interface { var _ codectypes.UnpackInterfacesMessage = &ContractInfo{} // UnpackInterfaces implements codectypes.UnpackInterfaces -func (m *ContractInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (c *ContractInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { var details ContractInfoExtension - if err := unpacker.UnpackAny(m.Extension, &details); err != nil { + if err := unpacker.UnpackAny(c.Extension, &details); err != nil { return err } return codectypes.UnpackInterfaces(details, unpacker)