chore(all): replace all fmt.Errorf without paramters with errors.New (#21068)

This commit is contained in:
yukionfire 2024-07-25 20:54:49 +08:00 committed by GitHub
parent 6a2d039e12
commit d6ad92db0f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
57 changed files with 127 additions and 103 deletions

View File

@ -2,6 +2,7 @@ package baseapp
import (
gocontext "context"
"errors"
"fmt"
abci "github.com/cometbft/cometbft/api/cometbft/abci/v1"
@ -60,5 +61,5 @@ func (q *QueryServiceTestHelper) Invoke(_ gocontext.Context, method string, args
// NewStream implements the grpc ClientConn.NewStream method
func (q *QueryServiceTestHelper) NewStream(gocontext.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) {
return nil, fmt.Errorf("not supported")
return nil, errors.New("not supported")
}

View File

@ -290,7 +290,7 @@ func readTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, err
if keyType == keyring.TypeLedger && clientCtx.SignModeStr == flags.SignModeTextual {
if !slices.Contains(clientCtx.TxConfig.SignModeHandler().SupportedModes(), signingv1beta1.SignMode_SIGN_MODE_TEXTUAL) {
return clientCtx, fmt.Errorf("SIGN_MODE_TEXTUAL is not available")
return clientCtx, errors.New("SIGN_MODE_TEXTUAL is not available")
}
}

View File

@ -2,7 +2,7 @@ package client
import (
gocontext "context"
"fmt"
"errors"
"reflect"
"strconv"
@ -123,7 +123,7 @@ func (ctx Context) Invoke(grpcCtx gocontext.Context, method string, req, reply i
// NewStream implements the grpc ClientConn.NewStream method
func (Context) NewStream(gocontext.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) {
return nil, fmt.Errorf("streaming rpc not supported")
return nil, errors.New("streaming rpc not supported")
}
// gRPCCodec checks if Context's Codec is codec.GRPCCodecProvider

View File

@ -102,12 +102,12 @@ func LoadArchiveCmd() *cobra.Command {
savedSnapshot := <-quitChan
if savedSnapshot == nil {
return fmt.Errorf("failed to save snapshot")
return errors.New("failed to save snapshot")
}
if !reflect.DeepEqual(&snapshot, savedSnapshot) {
_ = snapshotStore.Delete(snapshot.Height, snapshot.Format)
return fmt.Errorf("invalid archive, the saved snapshot is not equal to the original one")
return errors.New("invalid archive, the saved snapshot is not equal to the original one")
}
return nil

View File

@ -441,7 +441,7 @@ func (f Factory) BuildSimTx(msgs ...sdk.Msg) ([]byte, error) {
encoder := f.txConfig.TxEncoder()
if encoder == nil {
return nil, fmt.Errorf("cannot simulate tx: tx encoder is nil")
return nil, errors.New("cannot simulate tx: tx encoder is nil")
}
return encoder(txb.GetTx())

View File

@ -2,6 +2,7 @@ package tx
import (
"context"
"errors"
"fmt"
"strings"
"testing"
@ -44,7 +45,7 @@ type mockContext struct {
func (m mockContext) Invoke(_ context.Context, _ string, _, reply interface{}, _ ...grpc.CallOption) (err error) {
if m.wantErr {
return fmt.Errorf("mock err")
return errors.New("mock err")
}
*(reply.(*txtypes.SimulateResponse)) = txtypes.SimulateResponse{

View File

@ -2,7 +2,7 @@ package flag
import (
"context"
"fmt"
"errors"
"strings"
"google.golang.org/protobuf/reflect/protoreflect"
@ -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)

View File

@ -1,7 +1,7 @@
package coins
import (
"fmt"
"errors"
"regexp"
"strings"
@ -19,13 +19,13 @@ func ParseCoin(input string) (*basev1beta1.Coin, error) {
input = strings.TrimSpace(input)
if input == "" {
return nil, fmt.Errorf("empty input when parsing coin")
return nil, errors.New("empty input when parsing coin")
}
matches := coinRegex.FindStringSubmatch(input)
if len(matches) == 0 {
return nil, fmt.Errorf("invalid input format")
return nil, errors.New("invalid input format")
}
return &basev1beta1.Coin{

View File

@ -1,6 +1,7 @@
package prompt
import (
"errors"
"fmt"
"net/url"
@ -10,7 +11,7 @@ import (
// ValidatePromptNotEmpty validates that the input is not empty.
func ValidatePromptNotEmpty(input string) error {
if input == "" {
return fmt.Errorf("input cannot be empty")
return errors.New("input cannot be empty")
}
return nil

View File

@ -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:

View File

@ -1,6 +1,7 @@
package collections
import (
"errors"
"fmt"
"testing"
@ -188,7 +189,7 @@ func TestWalk(t *testing.T) {
})
require.NoError(t, err)
sentinelErr := fmt.Errorf("sentinel error")
sentinelErr := errors.New("sentinel error")
err = m.Walk(ctx, nil, func(key, value uint64) (stop bool, err error) {
require.LessOrEqual(t, key, uint64(3)) // asserts that after the number three we stop
if key == 3 {

View File

@ -2,7 +2,7 @@ package collections
import (
"context"
"fmt"
"errors"
"testing"
"github.com/stretchr/testify/require"
@ -53,7 +53,7 @@ func TestMap_Clear(t *testing.T) {
err := m.Clear(ctx, nil)
require.NoError(t, err)
err = m.Walk(ctx, nil, func(key, value uint64) (bool, error) {
return false, fmt.Errorf("should never be called")
return false, errors.New("should never be called")
})
require.NoError(t, err)
})

View File

@ -1,6 +1,7 @@
package appconfig
import (
"errors"
"fmt"
"reflect"
"strings"
@ -95,7 +96,7 @@ func Compose(appConfig gogoproto.Message) depinject.Config {
for _, module := range appConfigConcrete.Modules {
if module.Name == "" {
return depinject.Error(fmt.Errorf("module is missing name"))
return depinject.Error(errors.New("module is missing name"))
}
if module.Config == nil {

View File

@ -1,6 +1,7 @@
package depinject_test
import (
"errors"
"fmt"
"os"
"testing"
@ -300,7 +301,7 @@ func TestCyclic(t *testing.T) {
}
func TestErrorOption(t *testing.T) {
err := depinject.Inject(depinject.Error(fmt.Errorf("an error")))
err := depinject.Inject(depinject.Error(errors.New("an error")))
require.Error(t, err)
}
@ -606,7 +607,7 @@ func ProvideTestOutput() (TestOutput, error) {
}
func ProvideTestOutputErr() (TestOutput, error) {
return TestOutput{}, fmt.Errorf("error")
return TestOutput{}, errors.New("error")
}
func TestStructArgs(t *testing.T) {

View File

@ -1,7 +1,7 @@
package codegen
import (
"fmt"
"errors"
"go/ast"
"go/token"
"strconv"
@ -61,7 +61,7 @@ func NewFileGen(file *ast.File, codegenPkgPath string) (*FileGen, error) {
if spec.Name != nil {
name := spec.Name.Name
if name == "." {
return nil, fmt.Errorf(". package imports are not allowed")
return nil, errors.New(". package imports are not allowed")
}
info = &importInfo{importPrefix: name, ImportSpec: spec}

View File

@ -3,6 +3,7 @@ package postgres
import (
"context"
"database/sql"
"errors"
"fmt"
"cosmossdk.io/schema/appdata"
@ -23,7 +24,7 @@ type SqlLogger = func(msg, sql string, params ...interface{})
func StartIndexer(ctx context.Context, logger SqlLogger, config Config) (appdata.Listener, error) {
if config.DatabaseURL == "" {
return appdata.Listener{}, fmt.Errorf("missing database URL")
return appdata.Listener{}, errors.New("missing database URL")
}
driver := config.DatabaseDriver

View File

@ -1,6 +1,7 @@
package testutil_test
import (
"errors"
"fmt"
"testing"
@ -21,7 +22,7 @@ func TestSetArgsWithOriginalMethod(t *testing.T) {
c, _ := cmd.Flags().GetBool("c")
switch {
case a && b, a && c, b && c:
return fmt.Errorf("a,b,c only one could be true")
return errors.New("a,b,c only one could be true")
}
return nil
},

View File

@ -2,7 +2,7 @@ package ormfield
import (
"encoding/binary"
"fmt"
"errors"
"io"
"google.golang.org/protobuf/reflect/protoreflect"
@ -183,6 +183,6 @@ func DecodeCompactUint32(reader io.Reader) (uint32, error) {
x |= uint32(buf[4])
return x, nil
default:
return 0, fmt.Errorf("unexpected case")
return 0, errors.New("unexpected case")
}
}

View File

@ -2,7 +2,7 @@ package ormfield
import (
"encoding/binary"
"fmt"
"errors"
"io"
"google.golang.org/protobuf/reflect/protoreflect"
@ -213,6 +213,6 @@ func DecodeCompactUint64(reader io.Reader) (uint64, error) {
x |= uint64(buf[8])
return x, nil
default:
return 0, fmt.Errorf("unexpected case")
return 0, errors.New("unexpected case")
}
}

View File

@ -1,7 +1,7 @@
package listinternal
import (
"fmt"
"errors"
"google.golang.org/protobuf/proto"
)
@ -17,7 +17,7 @@ type Options struct {
func (o Options) Validate() error {
if len(o.Cursor) != 0 {
if o.Offset > 0 {
return fmt.Errorf("can only specify one of cursor or offset")
return errors.New("can only specify one of cursor or offset")
}
}
return nil

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"math"
@ -111,7 +112,7 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt
case ormv1alpha1.StorageType_STORAGE_TYPE_MEMORY:
service := options.MemoryStoreService
if service == nil {
return nil, fmt.Errorf("missing MemoryStoreService")
return nil, errors.New("missing MemoryStoreService")
}
backendResolver = func(ctx context.Context) (ormtable.ReadBackend, error) {
@ -124,7 +125,7 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt
case ormv1alpha1.StorageType_STORAGE_TYPE_TRANSIENT:
service := options.TransientStoreService
if service == nil {
return nil, fmt.Errorf("missing TransientStoreService")
return nil, errors.New("missing TransientStoreService")
}
backendResolver = func(ctx context.Context) (ormtable.ReadBackend, error) {

View File

@ -4,7 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"errors"
"strings"
"testing"
@ -103,7 +103,7 @@ func (k keeper) Burn(ctx context.Context, acct, denom string, amount uint64) err
}
if amount > supply.Amount {
return fmt.Errorf("insufficient supply")
return errors.New("insufficient supply")
}
supply.Amount -= amount
@ -171,7 +171,7 @@ func (k keeper) safeSubBalance(ctx context.Context, acct, denom string, amount u
}
if amount > balance.Amount {
return fmt.Errorf("insufficient funds")
return errors.New("insufficient funds")
}
balance.Amount -= amount

View File

@ -2,6 +2,7 @@ package ormtable
import (
"context"
"errors"
"fmt"
"cosmossdk.io/core/store"
@ -182,7 +183,7 @@ var defaultContextKey = contextKeyType("backend")
func getBackendDefault(ctx context.Context) (ReadBackend, error) {
value := ctx.Value(defaultContextKey)
if value == nil {
return nil, fmt.Errorf("can't resolve backend")
return nil, errors.New("can't resolve backend")
}
backend, ok := value.(ReadBackend)

View File

@ -2,6 +2,7 @@ package ormtable_test
import (
"context"
"errors"
"fmt"
"testing"
@ -143,7 +144,7 @@ func insertBalance(store kv.Store, balance *testpb.Balance) error {
}
if has {
return fmt.Errorf("already exists")
return errors.New("already exists")
}
bz, err := proto.Marshal(balance)
@ -223,7 +224,7 @@ func getBalance(store kv.Store, address, denom string) (*testpb.Balance, error)
}
if bz == nil {
return nil, fmt.Errorf("not found")
return nil, errors.New("not found")
}
balance := testpb.Balance{}

View File

@ -2,7 +2,7 @@ package runtime
import (
"context"
"fmt"
"errors"
"testing"
"github.com/stretchr/testify/require"
@ -52,7 +52,7 @@ func TestBranchService(t *testing.T) {
ctx := testutil.DefaultContext(sk, tsk)
err := bs.Execute(ctx, func(ctx context.Context) error {
doStateChange(ctx)
return fmt.Errorf("failure")
return errors.New("failure")
})
require.Error(t, err)
assertRollback(ctx, true)
@ -76,7 +76,7 @@ func TestBranchService(t *testing.T) {
ctx := testutil.DefaultContext(sk, tsk)
gasUsed, err := bs.ExecuteWithGasLimit(ctx, 4_000, func(ctx context.Context) error {
doStateChange(ctx)
return fmt.Errorf("failure")
return errors.New("failure")
})
require.Error(t, err)
// assert gas used

View File

@ -410,7 +410,7 @@ func (m *MM[T]) 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")
}
}
}

View File

@ -1,6 +1,7 @@
package decoding
import (
"errors"
"fmt"
"reflect"
"sort"
@ -360,7 +361,7 @@ func (e exampleBankModule) subBalance(acct, denom string, amount uint64) error {
key := balanceKey(acct, denom)
cur := e.store.GetUInt64(key)
if cur < amount {
return fmt.Errorf("insufficient balance")
return errors.New("insufficient balance")
}
e.store.SetUInt64(key, cur-amount)
return nil

View File

@ -3,6 +3,7 @@ package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
@ -239,7 +240,7 @@ $ %s query block --%s=%s <hash>
case auth.TypeHeight:
if args[0] == "" {
return fmt.Errorf("argument should be a block height")
return errors.New("argument should be a block height")
}
// optional height
@ -265,7 +266,7 @@ $ %s query block --%s=%s <hash>
case auth.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.

View File

@ -162,7 +162,7 @@ func newTxDescriptor(ir codectypes.InterfaceRegistry) (*TxDescriptor, error) {
// get base tx type name
txPbName := proto.MessageName(&tx.Tx{})
if txPbName == "" {
return nil, fmt.Errorf("unable to get *tx.Tx protobuf name")
return nil, errors.New("unable to get *tx.Tx protobuf name")
}
// get msgs
sdkMsgImplementers := ir.ListImplementations(sdk.MsgInterfaceProtoName)

View File

@ -3,6 +3,7 @@ package telemetry
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
@ -145,7 +146,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()
@ -171,7 +172,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)

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
appmanager "cosmossdk.io/core/app"
@ -46,7 +47,7 @@ func (a AppManager[T]) InitGenesis(
return nil, nil, fmt.Errorf("unable to get latest state: %w", err)
}
if v != 0 { // TODO: genesis state may be > 0, we need to set version on store
return nil, nil, fmt.Errorf("cannot init genesis on non-zero state")
return nil, nil, errors.New("cannot init genesis on non-zero state")
}
var genTxs []T

View File

@ -543,7 +543,7 @@ func (c *Consensus[T]) VerifyVoteExtension(
}
if c.verifyVoteExt == nil {
return nil, fmt.Errorf("vote extensions are enabled but no verify function was set")
return nil, errors.New("vote extensions are enabled but no verify function was set")
}
_, latestStore, err := c.store.StateLatest()
@ -579,7 +579,7 @@ func (c *Consensus[T]) ExtendVote(ctx context.Context, req *abciproto.ExtendVote
}
if c.verifyVoteExt == nil {
return nil, fmt.Errorf("vote extensions are enabled but no verify function was set")
return nil, errors.New("vote extensions are enabled but no verify function was set")
}
_, latestStore, err := c.store.StateLatest()

View File

@ -2,6 +2,7 @@ package cometbft
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
@ -253,7 +254,7 @@ $ %s query block --%s=%s <hash>
switch typ {
case TypeHeight:
if args[0] == "" {
return fmt.Errorf("argument should be a block height")
return errors.New("argument should be a block height")
}
// optional height
@ -284,7 +285,7 @@ $ %s query block --%s=%s <hash>
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.

View File

@ -140,7 +140,7 @@ func (h *DefaultProposalHandler[T]) ProcessHandler() ProcessHandler[T] {
if maxBlockGas > 0 {
gaslimit, err := tx.GetGasLimit()
if err != nil {
return fmt.Errorf("failed to get gas limit")
return errors.New("failed to get gas limit")
}
totalTxGas += gaslimit
if totalTxGas > maxBlockGas {

View File

@ -2,6 +2,7 @@ package cometbft
import (
"context"
"errors"
"fmt"
"math"
"strings"
@ -296,7 +297,7 @@ func (c *Consensus[T]) GetConsensusParams(ctx context.Context) (*cmtproto.Consen
}
if r, ok := res.(*consensus.QueryParamsResponse); !ok {
return nil, fmt.Errorf("failed to query consensus params")
return nil, errors.New("failed to query consensus params")
} else {
// convert our params to cometbft params
evidenceMaxDuration := r.Params.Evidence.MaxAgeDuration

View File

@ -2,7 +2,7 @@ package stf
import (
"context"
"fmt"
"errors"
"testing"
gogotypes "github.com/cosmos/gogoproto/types"
@ -70,7 +70,7 @@ func TestBranchService(t *testing.T) {
stfCtx := makeContext()
gasUsed, err := branchService.ExecuteWithGasLimit(stfCtx, 10000, func(ctx context.Context) error {
kvSet(t, ctx, "cookies")
return fmt.Errorf("fail")
return errors.New("fail")
})
require.Error(t, err)
require.NotZero(t, gasUsed)

View File

@ -3,7 +3,7 @@ package stf
import (
"context"
"crypto/sha256"
"fmt"
"errors"
"testing"
"time"
@ -158,7 +158,7 @@ func TestSTF(t *testing.T) {
// update the stf to fail on the handler
s := s.clone()
addMsgHandlerToSTF(t, &s, func(ctx context.Context, msg *gogotypes.BoolValue) (*gogotypes.BoolValue, error) {
return nil, fmt.Errorf("failure")
return nil, errors.New("failure")
})
blockResult, newState, err := s.DeliverBlock(context.Background(), &appmanager.BlockRequest[mock.Tx]{
@ -180,7 +180,7 @@ func TestSTF(t *testing.T) {
t.Run("tx is success but post tx failed", func(t *testing.T) {
s := s.clone()
s.postTxExec = func(ctx context.Context, tx mock.Tx, success bool) error {
return fmt.Errorf("post tx failure")
return errors.New("post tx failure")
}
blockResult, newState, err := s.DeliverBlock(context.Background(), &appmanager.BlockRequest[mock.Tx]{
Height: uint64(1),
@ -201,9 +201,9 @@ func TestSTF(t *testing.T) {
t.Run("tx failed and post tx failed", func(t *testing.T) {
s := s.clone()
addMsgHandlerToSTF(t, &s, func(ctx context.Context, msg *gogotypes.BoolValue) (*gogotypes.BoolValue, error) {
return nil, fmt.Errorf("exec failure")
return nil, errors.New("exec failure")
})
s.postTxExec = func(ctx context.Context, tx mock.Tx, success bool) error { return fmt.Errorf("post tx failure") }
s.postTxExec = func(ctx context.Context, tx mock.Tx, success bool) error { return errors.New("post tx failure") }
blockResult, newState, err := s.DeliverBlock(context.Background(), &appmanager.BlockRequest[mock.Tx]{
Height: uint64(1),
Time: time.Date(2024, 2, 3, 18, 23, 0, 0, time.UTC),
@ -223,7 +223,7 @@ func TestSTF(t *testing.T) {
t.Run("fail validate tx", func(t *testing.T) {
// update stf to fail on the validation step
s := s.clone()
s.doTxValidation = func(ctx context.Context, tx mock.Tx) error { return fmt.Errorf("failure") }
s.doTxValidation = func(ctx context.Context, tx mock.Tx) error { return errors.New("failure") }
blockResult, newState, err := s.DeliverBlock(context.Background(), &appmanager.BlockRequest[mock.Tx]{
Height: uint64(1),
Time: time.Date(2024, 2, 3, 18, 23, 0, 0, time.UTC),

View File

@ -244,7 +244,7 @@ func (c *CommitStore) PausePruning(pause bool) {
// Snapshot implements snapshotstypes.CommitSnapshotter.
func (c *CommitStore) Snapshot(version uint64, protoWriter protoio.Writer) error {
if version == 0 {
return fmt.Errorf("the snapshot version must be greater than 0")
return errors.New("the snapshot version must be greater than 0")
}
latestVersion, err := c.GetLatestVersion()
@ -348,7 +348,7 @@ loop:
case *snapshotstypes.SnapshotItem_IAVL:
if importer == nil {
return snapshotstypes.SnapshotItem{}, fmt.Errorf("received IAVL node item before store item")
return snapshotstypes.SnapshotItem{}, errors.New("received IAVL node item before store item")
}
node := item.IAVL
if node.Height > int32(math.MaxInt8) {

View File

@ -215,7 +215,7 @@ func (m *Manager) GetMigratedVersion() uint64 {
func (m *Manager) Sync() error {
version := m.GetMigratedVersion()
if version == 0 {
return fmt.Errorf("migration is not done yet")
return errors.New("migration is not done yet")
}
version += 1

View File

@ -2,6 +2,7 @@ package integration_test
import (
"context"
"errors"
"fmt"
"io"
"testing"
@ -112,7 +113,7 @@ func Example() {
// in this example the result is an empty response, a nil check is enough
// in other cases, it is recommended to check the result value.
if result == nil {
panic(fmt.Errorf("unexpected nil result"))
panic(errors.New("unexpected nil result"))
}
// we now check the result
@ -220,7 +221,7 @@ func Example_oneModule() {
// in this example the result is an empty response, a nil check is enough
// in other cases, it is recommended to check the result value.
if result == nil {
panic(fmt.Errorf("unexpected nil result"))
panic(errors.New("unexpected nil result"))
}
// we now check the result

View File

@ -350,7 +350,7 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) {
apiListenAddr = cfg.APIAddress
} else {
if len(portPool) == 0 {
return nil, fmt.Errorf("failed to get port for API server")
return nil, errors.New("failed to get port for API server")
}
port := <-portPool
apiListenAddr = fmt.Sprintf("tcp://127.0.0.1:%s", port)
@ -367,7 +367,7 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) {
cmtCfg.RPC.ListenAddress = cfg.RPCAddress
} else {
if len(portPool) == 0 {
return nil, fmt.Errorf("failed to get port for RPC server")
return nil, errors.New("failed to get port for RPC server")
}
port := <-portPool
cmtCfg.RPC.ListenAddress = fmt.Sprintf("tcp://127.0.0.1:%s", port)
@ -377,7 +377,7 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) {
appCfg.GRPC.Address = cfg.GRPCAddress
} else {
if len(portPool) == 0 {
return nil, fmt.Errorf("failed to get port for GRPC server")
return nil, errors.New("failed to get port for GRPC server")
}
port := <-portPool
appCfg.GRPC.Address = fmt.Sprintf("127.0.0.1:%s", port)
@ -410,14 +410,14 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) {
monikers[i] = nodeDirName
if len(portPool) == 0 {
return nil, fmt.Errorf("failed to get port for Proxy server")
return nil, errors.New("failed to get port for Proxy server")
}
port := <-portPool
proxyAddr := fmt.Sprintf("tcp://127.0.0.1:%s", port)
cmtCfg.ProxyApp = proxyAddr
if len(portPool) == 0 {
return nil, fmt.Errorf("failed to get port for Proxy server")
return nil, errors.New("failed to get port for Proxy server")
}
port = <-portPool
p2pAddr := fmt.Sprintf("tcp://127.0.0.1:%s", port)

View File

@ -3,7 +3,7 @@ package sims
import (
"bytes"
"encoding/hex"
"fmt"
"errors"
"strconv"
errorsmod "cosmossdk.io/errors"
@ -108,7 +108,7 @@ func TestAddr(addr, bech string) (sdk.AccAddress, error) {
}
bechexpected := res.String()
if bech != bechexpected {
return nil, fmt.Errorf("bech encoding doesn't match reference")
return nil, errors.New("bech encoding doesn't match reference")
}
bechres, err := sdk.AccAddressFromBech32(bech)

View File

@ -2,6 +2,7 @@ package sims
import (
"encoding/json"
"errors"
"fmt"
"time"
@ -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 (

View File

@ -3,7 +3,7 @@ package sims
import (
"bufio"
"encoding/json"
"fmt"
"errors"
"io"
"math/rand"
"os"
@ -289,7 +289,7 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONCodec, genesisFile str
a, ok := acc.GetCachedValue().(sdk.AccountI)
if !ok {
return *genesis, nil, fmt.Errorf("expected account")
return *genesis, nil, errors.New("expected account")
}
// create simulator accounts

View File

@ -2,6 +2,7 @@ package testdata
import (
"context"
"errors"
"fmt"
"testing"
@ -27,7 +28,7 @@ var _ QueryServer = QueryImpl{}
func (e QueryImpl) TestAny(_ context.Context, request *TestAnyRequest) (*TestAnyResponse, error) {
animal, ok := request.AnyAnimal.GetCachedValue().(test.Animal)
if !ok {
return nil, fmt.Errorf("expected Animal")
return nil, errors.New("expected Animal")
}
any, err := types.NewAnyWithValue(animal.(proto.Message))

View File

@ -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

View File

@ -1,7 +1,7 @@
package internal
import (
"fmt"
"errors"
"runtime/debug"
"strings"
@ -19,7 +19,7 @@ func VersionCmd() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
version, ok := debug.ReadBuildInfo()
if !ok {
return fmt.Errorf("failed to get hubl version")
return errors.New("failed to get hubl version")
}
cmd.Printf("hubl version: %s\n", strings.TrimSpace(version.Main.Version))

View File

@ -2,6 +2,7 @@ package types
import (
"encoding/binary"
"errors"
"fmt"
"time"
@ -255,7 +256,7 @@ var timeSize = len(FormatTimeBytes(time.Time{}))
func (timeKeyCodec) Decode(buffer []byte) (int, time.Time, error) {
if len(buffer) != timeSize {
return 0, time.Time{}, fmt.Errorf("invalid time buffer size")
return 0, time.Time{}, errors.New("invalid time buffer size")
}
t, err := ParseTimeBytes(buffer)
if err != nil {

View File

@ -1,6 +1,7 @@
package mempool_test
import (
"errors"
"fmt"
"math/rand"
"testing"
@ -217,7 +218,7 @@ func (s *MempoolTestSuite) TestDefaultMempool() {
// a tx which does not implement SigVerifiableTx should not be inserted
tx := &sigErrTx{getSigs: func() ([]txsigning.SignatureV2, error) {
return nil, fmt.Errorf("error")
return nil, errors.New("error")
}}
require.Error(t, s.mempool.Insert(ctx, tx))
require.Error(t, s.mempool.Remove(tx))

View File

@ -2,6 +2,7 @@ package mempool
import (
"context"
"errors"
"fmt"
"math"
"sync"
@ -215,7 +216,7 @@ func (mp *PriorityNonceMempool[C]) Insert(ctx context.Context, tx sdk.Tx) error
return err
}
if len(sigs) == 0 {
return fmt.Errorf("tx must have at least one signer")
return errors.New("tx must have at least one signer")
}
sig := sigs[0]
@ -436,7 +437,7 @@ func (mp *PriorityNonceMempool[C]) Remove(tx sdk.Tx) error {
return err
}
if len(sigs) == 0 {
return fmt.Errorf("attempted to remove a tx with no signatures")
return errors.New("attempted to remove a tx with no signatures")
}
sig := sigs[0]
@ -466,7 +467,7 @@ func (mp *PriorityNonceMempool[C]) Remove(tx sdk.Tx) error {
func IsEmpty[C comparable](mempool Mempool) error {
mp := mempool.(*PriorityNonceMempool[C])
if mp.priorityIndex.Len() != 0 {
return fmt.Errorf("priorityIndex not empty")
return errors.New("priorityIndex not empty")
}
countKeys := make([]C, 0, len(mp.priorityCounts))

View File

@ -4,7 +4,7 @@ import (
"context"
crand "crypto/rand" // #nosec // crypto/rand is used for seed generation
"encoding/binary"
"fmt"
"errors"
"math/rand" // #nosec // math/rand is used for random selection and seeded from crypto/rand
"sync"
@ -133,7 +133,7 @@ func (snm *SenderNonceMempool) Insert(_ context.Context, tx sdk.Tx) error {
return err
}
if len(sigs) == 0 {
return fmt.Errorf("tx must have at least one signer")
return errors.New("tx must have at least one signer")
}
sig := sigs[0]
@ -206,7 +206,7 @@ func (snm *SenderNonceMempool) Remove(tx sdk.Tx) error {
return err
}
if len(sigs) == 0 {
return fmt.Errorf("tx must have at least one signer")
return errors.New("tx must have at least one signer")
}
sig := sigs[0]

View File

@ -1,6 +1,7 @@
package mempool_test
import (
"errors"
"fmt"
"math/rand"
"testing"
@ -52,7 +53,7 @@ func TestDefaultSignerExtractor(t *testing.T) {
ext := mempool.NewDefaultSignerExtractionAdapter()
goodTx := testTx{id: 0, priority: 0, nonce: 0, address: sa}
badTx := &sigErrTx{getSigs: func() ([]txsigning.SignatureV2, error) {
return nil, fmt.Errorf("error")
return nil, errors.New("error")
}}
nonSigVerify := nonVerifiableTx{}
@ -63,7 +64,7 @@ func TestDefaultSignerExtractor(t *testing.T) {
err error
}{
{name: "valid tx extracts sigs", tx: goodTx, sea: ext, err: nil},
{name: "invalid tx fails on sig", tx: badTx, sea: ext, err: fmt.Errorf("err")},
{name: "invalid tx fails on sig", tx: badTx, sea: ext, err: errors.New("err")},
{name: "non-verifiable tx fails on conversion", tx: nonSigVerify, sea: ext, err: fmt.Errorf("tx of type %T does not implement SigVerifiableTx", nonSigVerify)},
}
for _, test := range tests {

View File

@ -3,7 +3,6 @@ package query
import (
"context"
"errors"
"fmt"
"cosmossdk.io/collections"
collcodec "cosmossdk.io/collections/codec"
@ -87,7 +86,7 @@ func CollectionFilteredPaginate[K, V any, C Collection[K, V], T any](
reverse := pageReq.Reverse
if offset > 0 && key != nil {
return nil, nil, fmt.Errorf("invalid request, either offset or key is expected, got both")
return nil, nil, errors.New("invalid request, either offset or key is expected, got both")
}
opt := new(CollectionsPaginateOptions[K])

View File

@ -1,7 +1,7 @@
package query
import (
"fmt"
"errors"
"github.com/cosmos/gogoproto/proto"
@ -26,7 +26,7 @@ func FilteredPaginate(
pageRequest = initPageRequestDefaults(pageRequest)
if pageRequest.Offset > 0 && pageRequest.Key != nil {
return nil, fmt.Errorf("invalid request, either offset or key is expected, got both")
return nil, errors.New("invalid request, either offset or key is expected, got both")
}
var (
@ -151,7 +151,7 @@ func GenericFilteredPaginate[T, F proto.Message](
results := []F{}
if pageRequest.Offset > 0 && pageRequest.Key != nil {
return results, nil, fmt.Errorf("invalid request, either offset or key is expected, got both")
return results, nil, errors.New("invalid request, either offset or key is expected, got both")
}
var (

View File

@ -1,7 +1,7 @@
package query
import (
"fmt"
"errors"
"math"
db "github.com/cosmos/cosmos-db"
@ -62,7 +62,7 @@ func Paginate(
pageRequest = initPageRequestDefaults(pageRequest)
if pageRequest.Offset > 0 && pageRequest.Key != nil {
return nil, fmt.Errorf("invalid request, either offset or key is expected, got both")
return nil, errors.New("invalid request, either offset or key is expected, got both")
}
iterator := getIterator(prefixStore, pageRequest.Key, pageRequest.Reverse)

View File

@ -1,7 +1,7 @@
package simulation
import (
"fmt"
"errors"
"math/rand"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
@ -90,7 +90,7 @@ func RandomFees(r *rand.Rand, spendableCoins sdk.Coins) (sdk.Coins, error) {
}
if randCoin.Amount.IsZero() {
return nil, fmt.Errorf("no coins found for random fees")
return nil, errors.New("no coins found for random fees")
}
amt, err := RandPositiveInt(r, randCoin.Amount)

View File

@ -2,6 +2,7 @@ package keeper
import (
"context"
"errors"
"fmt"
"time"
@ -65,7 +66,7 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) error
// sanity check to avoid trying to distribute more than what is available
if data.LastBalance.LT(totalToBeDistributed) {
return fmt.Errorf("total to be distributed is greater than the last balance")
return errors.New("total to be distributed is greater than the last balance")
}
return nil