Skip to content

Commit

Permalink
refactor: use errors.New to replace fmt.Errorf with no parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
0x2d3c committed Jun 10, 2024
1 parent 7fb2668 commit 9a192fd
Show file tree
Hide file tree
Showing 22 changed files with 65 additions and 53 deletions.
7 changes: 4 additions & 3 deletions client/rpc/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
Expand All @@ -17,7 +18,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/version"
)

Expand Down Expand Up @@ -187,7 +188,7 @@ $ %[1]sd tx [flags] | %[1]sd q wait-tx
return clientCtx.PrintProto(newResponseFormatBroadcastTxCommit(res))
}
case <-ctx.Done():
return errors.ErrLogic.Wrapf("timed out waiting for transaction %X to be included in a block", hash)
return sdkerrors.ErrLogic.Wrapf("timed out waiting for transaction %X to be included in a block", hash)
}
return nil
},
Expand All @@ -214,5 +215,5 @@ func parseHashFromInput(in []byte) ([]byte, error) {
return hex.DecodeString(hash)
}
}
return nil, fmt.Errorf("txhash not found")
return nil, errors.New("txhash not found")
}
4 changes: 2 additions & 2 deletions client/v2/autocli/flag/coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package flag

import (
"context"
"fmt"
"errors"
"strings"

"google.golang.org/protobuf/reflect/protoreflect"
Expand Down Expand Up @@ -38,7 +38,7 @@ func (c *coinValue) String() string {

func (c *coinValue) Set(stringValue string) error {
if strings.Contains(stringValue, ",") {
return fmt.Errorf("coin flag must be a single coin, specific multiple coins with multiple flags or spaces")
return errors.New("coin flag must be a single coin, specific multiple coins with multiple flags or spaces")
}

coin, err := coins.ParseCoin(stringValue)
Expand Down
3 changes: 2 additions & 1 deletion client/v2/autocli/flag/pubkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package flag

import (
"context"
"errors"
"fmt"

"google.golang.org/protobuf/reflect/protoreflect"
Expand Down Expand Up @@ -47,7 +48,7 @@ func (a *pubkeyValue) Set(s string) error {

any, err := types.NewAnyWithValue(pk)
if err != nil {
return fmt.Errorf("error converting to any type")
return errors.New("error converting to any type")
}

a.value = any
Expand Down
9 changes: 5 additions & 4 deletions client/v2/autocli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package autocli

import (
"context"
"errors"
"fmt"
"io"
"strings"
Expand Down Expand Up @@ -176,14 +177,14 @@ func encoder(encoder aminojson.Encoder) aminojson.Encoder {
fields := msg.Descriptor().Fields()
secondsField := fields.ByName(secondsName)
if secondsField == nil {
return fmt.Errorf("expected seconds field")
return errors.New("expected seconds field")
}

seconds := msg.Get(secondsField).Int()

nanosField := fields.ByName(nanosName)
if nanosField == nil {
return fmt.Errorf("expected nanos field")
return errors.New("expected nanos field")
}

nanos := msg.Get(nanosField).Int()
Expand All @@ -199,14 +200,14 @@ func encoder(encoder aminojson.Encoder) aminojson.Encoder {
fields := msg.Descriptor().Fields()
denomField := fields.ByName(denomName)
if denomField == nil {
return fmt.Errorf("expected denom field")
return errors.New("expected denom field")
}

denom := msg.Get(denomField).String()

amountField := fields.ByName(amountName)
if amountField == nil {
return fmt.Errorf("expected amount field")
return errors.New("expected amount field")
}

amount := msg.Get(amountField).String()
Expand Down
2 changes: 1 addition & 1 deletion client/v2/offchain/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func verifySignature(
return err
}
if !pubKey.VerifySignature(signBytes, data.Signature) {
return fmt.Errorf("unable to verify single signer signature")
return errors.New("unable to verify single signer signature")
}
return nil
default:
Expand Down
2 changes: 1 addition & 1 deletion runtime/v2/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ func (m *MM) RunMigrations(ctx context.Context, fromVM appmodulev2.VersionMap) (

// The module manager assumes only one module will update the validator set, and it can't be a new module.
if len(moduleValUpdates) > 0 {
return nil, fmt.Errorf("validator InitGenesis update is already set by another module")
return nil, errors.New("validator InitGenesis update is already set by another module")
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion store/v2/root/factory.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package root

import (
"errors"
"fmt"
"os"

Expand Down Expand Up @@ -92,7 +93,7 @@ func CreateRootStore(opts *FactoryOptions) (store.RootStore, error) {
case SCTypeIavl:
trees[key] = iavl.NewIavlTree(db.NewPrefixDB(opts.SCRawDB, []byte(key)), opts.Logger, opts.IavlConfig)
case SCTypeIavlV2:
return nil, fmt.Errorf("iavl v2 not supported")
return nil, errors.New("iavl v2 not supported")
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions telemetry/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/hashicorp/go-metrics"
"github.com/hashicorp/go-metrics/datadog"
metricsprom "github.com/hashicorp/go-metrics/prometheus"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/expfmt"
)
Expand Down Expand Up @@ -192,7 +193,7 @@ func (m *Metrics) Gather(format string) (GatherResponse, error) {
// If Prometheus metrics are not enabled, it returns an error.
func (m *Metrics) gatherPrometheus() (GatherResponse, error) {
if !m.prometheusEnabled {
return GatherResponse{}, fmt.Errorf("prometheus metrics are not enabled")
return GatherResponse{}, errors.New("prometheus metrics are not enabled")
}

metricsFamilies, err := prometheus.DefaultGatherer.Gather()
Expand All @@ -218,7 +219,7 @@ func (m *Metrics) gatherPrometheus() (GatherResponse, error) {
func (m *Metrics) gatherGeneric() (GatherResponse, error) {
gm, ok := m.sink.(DisplayableSink)
if !ok {
return GatherResponse{}, fmt.Errorf("non in-memory metrics sink does not support generic format")
return GatherResponse{}, errors.New("non in-memory metrics sink does not support generic format")
}

summary, err := gm.DisplayMetrics(nil, nil)
Expand Down
6 changes: 3 additions & 3 deletions testutil/key.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package testutil

import (
"fmt"
"errors"

"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
Expand Down Expand Up @@ -47,12 +47,12 @@ func GenerateSaveCoinKey(

// ensure no overwrite
if !overwrite && exists {
return sdk.AccAddress{}, "", fmt.Errorf("key already exists, overwrite is disabled")
return sdk.AccAddress{}, "", errors.New("key already exists, overwrite is disabled")
}

if exists {
if err := keybase.Delete(keyName); err != nil {
return sdk.AccAddress{}, "", fmt.Errorf("failed to overwrite key")
return sdk.AccAddress{}, "", errors.New("failed to overwrite key")
}
}

Expand Down
3 changes: 2 additions & 1 deletion testutil/sims/app_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package sims

import (
"encoding/json"
"errors"
"fmt"
"time"

Expand Down Expand Up @@ -164,7 +165,7 @@ func SetupWithConfiguration(appConfig depinject.Config, startupConfig StartupCon
// create validator set
valSet, err := startupConfig.ValidatorSet()
if err != nil {
return nil, fmt.Errorf("failed to create validator set")
return nil, errors.New("failed to create validator set")
}

var (
Expand Down
2 changes: 1 addition & 1 deletion tools/cosmovisor/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ func parseEnvDuration(input string) (time.Duration, error) {
}

if duration <= 0 {
return 0, fmt.Errorf("must be greater than 0")
return 0, errors.New("must be greater than 0")
}

return duration, nil
Expand Down
15 changes: 8 additions & 7 deletions x/auth/client/cli/query.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"errors"
"fmt"
"strings"

Expand All @@ -11,7 +12,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
querytypes "github.com/cosmos/cosmos-sdk/types/query"
"github.com/cosmos/cosmos-sdk/version"
)
Expand Down Expand Up @@ -101,7 +102,7 @@ $ %s query tx --%s=%s <sig1_base64>,<sig2_base64...>
switch typ {
case TypeHash:
if args[0] == "" {
return fmt.Errorf("argument should be a tx hash")
return errors.New("argument should be a tx hash")
}

// if hash is given, then query the tx by hash
Expand Down Expand Up @@ -135,19 +136,19 @@ $ %s query tx --%s=%s <sig1_base64>,<sig2_base64...>
}

if len(txs.Txs) == 0 {
return fmt.Errorf("found no txs matching given signatures")
return errors.New("found no txs matching given signatures")
}
if len(txs.Txs) > 1 {
// This case means there's a bug somewhere else in the code as this
// should not happen.
return errors.ErrLogic.Wrapf("found %d txs matching given signatures", len(txs.Txs))
return sdkerrors.ErrLogic.Wrapf("found %d txs matching given signatures", len(txs.Txs))
}

return clientCtx.PrintProto(txs.Txs[0])

case TypeAccSeq:
if args[0] == "" {
return fmt.Errorf("`acc_seq` type takes an argument '<addr>/<seq>'")
return errors.New("`acc_seq` type takes an argument '<addr>/<seq>'")
}

query := fmt.Sprintf("%s.%s='%s'", sdk.EventTypeTx, sdk.AttributeKeyAccountSequence, args[0])
Expand All @@ -158,7 +159,7 @@ $ %s query tx --%s=%s <sig1_base64>,<sig2_base64...>
}

if len(txs.Txs) == 0 {
return fmt.Errorf("found no txs matching given address and sequence combination")
return errors.New("found no txs matching given address and sequence combination")
}
if len(txs.Txs) > 1 {
// This case means there's a bug somewhere else in the code as this
Expand All @@ -183,7 +184,7 @@ $ %s query tx --%s=%s <sig1_base64>,<sig2_base64...>
// ParseSigArgs parses comma-separated signatures from the CLI arguments.
func ParseSigArgs(args []string) ([]string, error) {
if len(args) != 1 || args[0] == "" {
return nil, fmt.Errorf("argument should be comma-separated signatures")
return nil, errors.New("argument should be comma-separated signatures")
}

return strings.Split(args[0], ","), nil
Expand Down
4 changes: 2 additions & 2 deletions x/authz/client/cli/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ Examples:
}

if !spendLimit.IsAllPositive() {
return fmt.Errorf("spend-limit should be greater than zero")
return errors.New("spend-limit should be greater than zero")
}

allowList, err := cmd.Flags().GetStringSlice(FlagAllowList)
Expand Down Expand Up @@ -202,7 +202,7 @@ Examples:
}

if !spendLimit.IsPositive() {
return fmt.Errorf("spend-limit should be greater than zero")
return errors.New("spend-limit should be greater than zero")
}
delegateLimit = &spendLimit
}
Expand Down
3 changes: 2 additions & 1 deletion x/crisis/types/genesis.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types

import (
"errors"
"fmt"

sdkmath "cosmossdk.io/math"
Expand All @@ -25,7 +26,7 @@ func DefaultGenesisState() *GenesisState {
// ValidateGenesis - validate crisis genesis data
func ValidateGenesis(data *GenesisState) error {
if !data.ConstantFee.IsValid() {
return fmt.Errorf("constant fee is invalid")
return errors.New("constant fee is invalid")
}
if !data.ConstantFee.IsPositive() {
return fmt.Errorf("constant fee must be positive: %s", data.ConstantFee)
Expand Down
3 changes: 2 additions & 1 deletion x/distribution/types/params.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types

import (
"errors"
"fmt"

"cosmossdk.io/math"
Expand Down Expand Up @@ -28,7 +29,7 @@ func validateCommunityTax(i interface{}) error {
}

if v.IsNil() {
return fmt.Errorf("community tax must be not nil")
return errors.New("community tax must be not nil")
}
if v.IsNegative() {
return fmt.Errorf("community tax must be positive: %s", v)
Expand Down
3 changes: 2 additions & 1 deletion x/evidence/types/genesis.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types

import (
"errors"
"fmt"

"github.com/cosmos/gogoproto/proto"
Expand Down Expand Up @@ -44,7 +45,7 @@ func (gs GenesisState) Validate() error {
for _, e := range gs.Evidence {
evi, ok := e.GetCachedValue().(exported.Evidence)
if !ok {
return fmt.Errorf("expected evidence")
return errors.New("expected evidence")
}
if err := evi.ValidateBasic(); err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion x/genutil/types/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ func (cs *ConsensusGenesis) UnmarshalJSON(b []byte) error {

func (cs *ConsensusGenesis) ValidateAndComplete() error {
if cs == nil {
return fmt.Errorf("consensus genesis cannot be nil")
return errors.New("consensus genesis cannot be nil")
}

if cs.Params == nil {
Expand Down
3 changes: 2 additions & 1 deletion x/genutil/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package genutil

import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
Expand Down Expand Up @@ -52,7 +53,7 @@ func InitializeNodeValidatorFiles(config *cfg.Config) (nodeID string, valPubKey
// If no valid mnemonic is given, a random one will be used instead.
func InitializeNodeValidatorFilesFromMnemonic(config *cfg.Config, mnemonic string) (nodeID string, valPubKey cryptotypes.PubKey, err error) {
if len(mnemonic) > 0 && !bip39.IsMnemonicValid(mnemonic) {
return "", nil, fmt.Errorf("invalid mnemonic")
return "", nil, errors.New("invalid mnemonic")
}
nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile())
if err != nil {
Expand Down
Loading

0 comments on commit 9a192fd

Please sign in to comment.