chore(x): replace fmt.Errorf without parameters with errors.New (#21032)

This commit is contained in:
yukionfire
2024-07-23 08:10:09 +00:00
committed by GitHub
parent c2df06c985
commit 67b5a5d268
14 changed files with 64 additions and 57 deletions
+2 -1
View File
@@ -1,6 +1,7 @@
package cli
import (
"errors"
"fmt"
"github.com/spf13/cobra"
@@ -64,7 +65,7 @@ When using '--dry-run' a key name cannot be used, only a bech32 address.`,
}
if coins.IsZero() {
return fmt.Errorf("must send positive amount")
return errors.New("must send positive amount")
}
split, err := cmd.Flags().GetBool(FlagSplit)
+3 -3
View File
@@ -52,12 +52,12 @@ func (k Keeper) calculateDelegationRewardsBetween(ctx context.Context, val sdk.V
) (sdk.DecCoins, error) {
// sanity check
if startingPeriod > endingPeriod {
return sdk.DecCoins{}, fmt.Errorf("startingPeriod cannot be greater than endingPeriod")
return sdk.DecCoins{}, errors.New("startingPeriod cannot be greater than endingPeriod")
}
// sanity check
if stake.IsNegative() {
return sdk.DecCoins{}, fmt.Errorf("stake should not be negative")
return sdk.DecCoins{}, errors.New("stake should not be negative")
}
valBz, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator())
@@ -78,7 +78,7 @@ func (k Keeper) calculateDelegationRewardsBetween(ctx context.Context, val sdk.V
difference := ending.CumulativeRewardRatio.Sub(starting.CumulativeRewardRatio)
if difference.IsAnyNegative() {
return sdk.DecCoins{}, fmt.Errorf("negative rewards should not be possible")
return sdk.DecCoins{}, errors.New("negative rewards should not be possible")
}
// note: necessary to truncate so we don't allow withdrawing more rewards than owed
rewards := difference.MulDecTruncate(stake)
+2 -1
View File
@@ -1,6 +1,7 @@
package types
import (
"errors"
"fmt"
"cosmossdk.io/math"
@@ -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)
+2 -1
View File
@@ -1,6 +1,7 @@
package types
import (
"errors"
"fmt"
"github.com/cosmos/gogoproto/proto"
@@ -45,7 +46,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
+2 -2
View File
@@ -2,7 +2,7 @@ package feegrant
import (
"context"
"fmt"
"errors"
"time"
"cosmossdk.io/core/appmodule"
@@ -28,7 +28,7 @@ var _ FeeAllowanceI = (*BasicAllowance)(nil)
func (a *BasicAllowance) Accept(ctx context.Context, fee sdk.Coins, _ []sdk.Msg) (bool, error) {
environment, ok := ctx.Value(corecontext.EnvironmentContextKey).(appmodule.Environment)
if !ok {
return false, fmt.Errorf("environment not set")
return false, errors.New("environment not set")
}
headerInfo := environment.HeaderService.HeaderInfo(ctx)
if a.Expiration != nil && a.Expiration.Before(headerInfo.Time) {
+3 -3
View File
@@ -2,7 +2,7 @@ package feegrant
import (
"context"
"fmt"
"errors"
"time"
"github.com/cosmos/gogoproto/proto"
@@ -100,7 +100,7 @@ func (a *AllowedMsgAllowance) allowedMsgsToMap(ctx context.Context) (map[string]
msgsMap := make(map[string]bool, len(a.AllowedMessages))
environment, ok := ctx.Value(corecontext.EnvironmentContextKey).(appmodule.Environment)
if !ok {
return nil, fmt.Errorf("environment not set")
return nil, errors.New("environment not set")
}
gasMeter := environment.GasService.GasMeter(ctx)
for _, msg := range a.AllowedMessages {
@@ -120,7 +120,7 @@ func (a *AllowedMsgAllowance) allMsgTypesAllowed(ctx context.Context, msgs []sdk
}
environment, ok := ctx.Value(corecontext.EnvironmentContextKey).(appmodule.Environment)
if !ok {
return false, fmt.Errorf("environment not set")
return false, errors.New("environment not set")
}
gasMeter := environment.GasService.GasMeter(ctx)
for _, msg := range msgs {
+3 -3
View File
@@ -3,7 +3,7 @@ package cli_test
import (
"context"
"encoding/json"
"fmt"
"errors"
"io"
"os"
"path/filepath"
@@ -164,7 +164,7 @@ func (e *mockExporter) Export(
modulesToExport []string,
) (types.ExportedApp, error) {
if e.Err == nil && isZeroExportedApp(e.ExportApp) {
panic(fmt.Errorf("(*mockExporter).Export called without setting e.ExportApp or e.Err"))
panic(errors.New("(*mockExporter).Export called without setting e.ExportApp or e.Err"))
}
e.WasCalled = true
@@ -311,7 +311,7 @@ func TestExportCLI(t *testing.T) {
t.Parallel()
e := new(mockExporter)
e.Err = fmt.Errorf("whoopsie")
e.Err = errors.New("whoopsie")
sys := NewExportSystem(t, e.Export)
_ = sys.MustRun(t, "init", "some_moniker")
+3 -2
View File
@@ -2,6 +2,7 @@ package genutil
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
@@ -60,7 +61,7 @@ func InitializeNodeValidatorFilesFromMnemonic(config *cfg.Config, mnemonic, keyT
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 {
@@ -103,7 +104,7 @@ func InitializeNodeValidatorFilesFromMnemonic(config *cfg.Config, mnemonic, keyT
privKey = tmed25519.GenPrivKeyFromSecret([]byte(mnemonic))
case "bls12_381":
// TODO: need to add support for getting from mnemonic in Comet.
return "", nil, fmt.Errorf("BLS key type does not support mnemonic")
return "", nil, errors.New("BLS key type does not support mnemonic")
default:
privKey = tmed25519.GenPrivKeyFromSecret([]byte(mnemonic))
}
+4 -3
View File
@@ -2,6 +2,7 @@ package cli
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
@@ -28,15 +29,15 @@ type legacyProposal struct {
// validate the legacyProposal
func (p legacyProposal) validate() error {
if p.Type == "" {
return fmt.Errorf("proposal type is required")
return errors.New("proposal type is required")
}
if p.Title == "" {
return fmt.Errorf("proposal title is required")
return errors.New("proposal title is required")
}
if p.Description == "" {
return fmt.Errorf("proposal description is required")
return errors.New("proposal description is required")
}
return nil
}
+2 -1
View File
@@ -1,6 +1,7 @@
package keeper_test
import (
"errors"
"fmt"
"testing"
"time"
@@ -266,7 +267,7 @@ func trackMockBalances(bankKeeper *govtestutil.MockBankKeeper) error {
}
newBalance, negative := balances[senderAddr].SafeSub(coins...)
if negative {
return fmt.Errorf("not enough balance")
return errors.New("not enough balance")
}
balances[senderAddr] = newBalance
return nil
+2 -1
View File
@@ -2,6 +2,7 @@ package cli
import (
"encoding/json"
"errors"
"fmt"
"os"
@@ -14,7 +15,7 @@ import (
// parseDecisionPolicy reads and parses the decision policy.
func parseDecisionPolicy(cdc codec.Codec, decisionPolicyFile string) (group.DecisionPolicy, error) {
if decisionPolicyFile == "" {
return nil, fmt.Errorf("decision policy is required")
return nil, errors.New("decision policy is required")
}
contents, err := os.ReadFile(decisionPolicyFile)
+9 -9
View File
@@ -2,12 +2,12 @@
package math
import (
"fmt"
"errors"
"github.com/cockroachdb/apd/v2"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/x/group/errors"
grouperrors "cosmossdk.io/x/group/errors"
)
// Dec is a wrapper struct around apd.Decimal that does no mutation of apd.Decimal's when performing
@@ -23,10 +23,10 @@ type Dec struct {
func NewPositiveDecFromString(s string) (Dec, error) {
d, err := NewDecFromString(s)
if err != nil {
return Dec{}, errors.ErrInvalidDecString.Wrap(err.Error())
return Dec{}, grouperrors.ErrInvalidDecString.Wrap(err.Error())
}
if !d.IsPositive() {
return Dec{}, errors.ErrInvalidDecString.Wrapf("expected a positive decimal, got %s", s)
return Dec{}, grouperrors.ErrInvalidDecString.Wrapf("expected a positive decimal, got %s", s)
}
return d, nil
}
@@ -34,10 +34,10 @@ func NewPositiveDecFromString(s string) (Dec, error) {
func NewNonNegativeDecFromString(s string) (Dec, error) {
d, err := NewDecFromString(s)
if err != nil {
return Dec{}, errors.ErrInvalidDecString.Wrap(err.Error())
return Dec{}, grouperrors.ErrInvalidDecString.Wrap(err.Error())
}
if d.IsNegative() {
return Dec{}, errors.ErrInvalidDecString.Wrapf("expected a non-negative decimal, got %s", s)
return Dec{}, grouperrors.ErrInvalidDecString.Wrapf("expected a non-negative decimal, got %s", s)
}
return d, nil
}
@@ -51,11 +51,11 @@ func (x Dec) IsPositive() bool {
func NewDecFromString(s string) (Dec, error) {
d, _, err := apd.NewFromString(s)
if err != nil {
return Dec{}, errors.ErrInvalidDecString.Wrap(err.Error())
return Dec{}, grouperrors.ErrInvalidDecString.Wrap(err.Error())
}
if d.Form != apd.Finite {
return Dec{}, errors.ErrInvalidDecString.Wrapf("expected a finite decimal, got %s", s)
return Dec{}, grouperrors.ErrInvalidDecString.Wrapf("expected a finite decimal, got %s", s)
}
return Dec{*d}, nil
@@ -136,7 +136,7 @@ func SubNonNegative(x, y Dec) (Dec, error) {
}
if z.IsNegative() {
return z, fmt.Errorf("result negative during non-negative subtraction")
return z, errors.New("result negative during non-negative subtraction")
}
return z, nil
+22 -22
View File
@@ -1,13 +1,13 @@
package orm
import (
"fmt"
"errors"
"reflect"
"github.com/cosmos/gogoproto/proto"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/x/group/errors"
grouperrors "cosmossdk.io/x/group/errors"
"github.com/cosmos/cosmos-sdk/types/query"
)
@@ -20,7 +20,7 @@ const defaultPageLimit = 100
type IteratorFunc func(dest proto.Message) (RowID, error)
// LoadNext loads the next value in the sequence into the pointer passed as dest and returns the key. If there
// are no more items the errors.ErrORMIteratorDone error is returned
// are no more items the grouperrors.ErrORMIteratorDone error is returned
// The key is the rowID and not any MultiKeyIndex key.
func (i IteratorFunc) LoadNext(dest proto.Message) (RowID, error) {
return i(dest)
@@ -35,10 +35,10 @@ func NewSingleValueIterator(rowID RowID, val []byte) Iterator {
var closed bool
return IteratorFunc(func(dest proto.Message) (RowID, error) {
if dest == nil {
return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination object must not be nil")
return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination object must not be nil")
}
if closed || val == nil {
return nil, errors.ErrORMIteratorDone
return nil, grouperrors.ErrORMIteratorDone
}
closed = true
return rowID, proto.Unmarshal(val, dest)
@@ -48,7 +48,7 @@ func NewSingleValueIterator(rowID RowID, val []byte) Iterator {
// Iterator that return ErrORMInvalidIterator only.
func NewInvalidIterator() Iterator {
return IteratorFunc(func(dest proto.Message) (RowID, error) {
return nil, errors.ErrORMInvalidIterator
return nil, grouperrors.ErrORMInvalidIterator
})
}
@@ -63,20 +63,20 @@ type LimitedIterator struct {
// max can be 0 or any positive number
func LimitIterator(parent Iterator, max int) (*LimitedIterator, error) {
if max < 0 {
return nil, errors.ErrORMInvalidArgument.Wrap("quantity must not be negative")
return nil, grouperrors.ErrORMInvalidArgument.Wrap("quantity must not be negative")
}
if parent == nil {
return nil, errors.ErrORMInvalidArgument.Wrap("parent iterator must not be nil")
return nil, grouperrors.ErrORMInvalidArgument.Wrap("parent iterator must not be nil")
}
return &LimitedIterator{remainingCount: max, parentIterator: parent}, nil
}
// LoadNext loads the next value in the sequence into the pointer passed as dest and returns the key. If there
// are no more items or the defined max number of elements was returned the `errors.ErrORMIteratorDone` error is returned
// are no more items or the defined max number of elements was returned the `grouperrors.ErrORMIteratorDone` error is returned
// The key is the rowID and not any MultiKeyIndex key.
func (i *LimitedIterator) LoadNext(dest proto.Message) (RowID, error) {
if i.remainingCount == 0 {
return nil, errors.ErrORMIteratorDone
return nil, grouperrors.ErrORMIteratorDone
}
i.remainingCount--
return i.parentIterator.LoadNext(dest)
@@ -91,7 +91,7 @@ func (i LimitedIterator) Close() error {
// When the iterator is closed or has no elements the according error is passed as return value.
func First(it Iterator, dest proto.Message) (RowID, error) {
if it == nil {
return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "iterator must not be nil")
return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "iterator must not be nil")
}
defer it.Close()
binKey, err := it.LoadNext(dest)
@@ -136,7 +136,7 @@ func Paginate(
countTotal := pageRequest.CountTotal
if offset > 0 && 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")
}
if limit == 0 {
@@ -147,7 +147,7 @@ func Paginate(
}
if it == nil {
return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "iterator must not be nil")
return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "iterator must not be nil")
}
defer it.Close()
@@ -177,11 +177,11 @@ func Paginate(
modelProto, ok := model.Interface().(proto.Message)
if !ok {
return nil, errorsmod.Wrapf(errors.ErrORMInvalidArgument, "%s should implement codec.ProtoMarshaler", elemType)
return nil, errorsmod.Wrapf(grouperrors.ErrORMInvalidArgument, "%s should implement codec.ProtoMarshaler", elemType)
}
binKey, err := it.LoadNext(modelProto)
if err != nil {
if errors.ErrORMIteratorDone.Is(err) {
if grouperrors.ErrORMIteratorDone.Is(err) {
break
}
return nil, err
@@ -237,7 +237,7 @@ type ModelSlicePtr interface{}
// require.NoError(t, err)
func ReadAll(it Iterator, dest ModelSlicePtr) ([]RowID, error) {
if it == nil {
return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "iterator must not be nil")
return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "iterator must not be nil")
}
defer it.Close()
@@ -261,7 +261,7 @@ func ReadAll(it Iterator, dest ModelSlicePtr) ([]RowID, error) {
switch {
case err == nil:
tmpSlice = reflect.Append(tmpSlice, val)
case errors.ErrORMIteratorDone.Is(err):
case grouperrors.ErrORMIteratorDone.Is(err):
destRef.Set(tmpSlice)
return rowIDs, nil
default:
@@ -276,14 +276,14 @@ func ReadAll(it Iterator, dest ModelSlicePtr) ([]RowID, error) {
// It overwrites destRef and tmpSlice using reflection.
func assertDest(dest ModelSlicePtr, destRef, tmpSlice *reflect.Value) (reflect.Type, error) {
if dest == nil {
return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination must not be nil")
return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination must not be nil")
}
tp := reflect.ValueOf(dest)
if tp.Kind() != reflect.Ptr {
return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination must be a pointer to a slice")
return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination must be a pointer to a slice")
}
if tp.Elem().Kind() != reflect.Slice {
return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination must point to a slice")
return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination must point to a slice")
}
// Since dest is just an interface{}, we overwrite destRef using reflection
@@ -291,7 +291,7 @@ func assertDest(dest ModelSlicePtr, destRef, tmpSlice *reflect.Value) (reflect.T
*destRef = tp.Elem()
// We need to verify that we can call Set() on destRef.
if !destRef.CanSet() {
return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination not assignable")
return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination not assignable")
}
elemType := reflect.TypeOf(dest).Elem().Elem()
@@ -299,7 +299,7 @@ func assertDest(dest ModelSlicePtr, destRef, tmpSlice *reflect.Value) (reflect.T
protoMarshaler := reflect.TypeOf((*proto.Message)(nil)).Elem()
if !elemType.Implements(protoMarshaler) &&
!reflect.PtrTo(elemType).Implements(protoMarshaler) {
return nil, errorsmod.Wrapf(errors.ErrORMInvalidArgument, "unsupported type :%s", elemType)
return nil, errorsmod.Wrapf(grouperrors.ErrORMInvalidArgument, "unsupported type :%s", elemType)
}
// tmpSlice is a slice value for the specified type
+5 -5
View File
@@ -3,7 +3,7 @@ package keeper_test
import (
"bytes"
"context"
"fmt"
"errors"
"sort"
"strings"
"time"
@@ -2706,7 +2706,7 @@ func (s *TestSuite) TestExecProposal() {
setupProposal: func(ctx context.Context) uint64 {
msgs := []sdk.Msg{msgSend1, msgSend2}
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil)
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error"))
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, errors.New("error"))
return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES)
},
@@ -2723,7 +2723,7 @@ func (s *TestSuite) TestExecProposal() {
// Wait after min execution period end before Exec
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx = sdkCtx.WithHeaderInfo(header.Info{Time: sdkCtx.HeaderInfo().Time.Add(minExecutionPeriod)}) // MinExecutionPeriod is 5s
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error"))
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, errors.New("error"))
_, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: s.addrsStr[0], ProposalId: myProposalID})
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, nil)
@@ -2902,7 +2902,7 @@ func (s *TestSuite) TestExecPrunedProposalsAndVotes() {
}
msgs := []sdk.Msg{msgSend1, msgSend2}
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, fmt.Errorf("error"))
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, errors.New("error"))
return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES)
},
@@ -2920,7 +2920,7 @@ func (s *TestSuite) TestExecPrunedProposalsAndVotes() {
myProposalID := submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES)
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error"))
s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, errors.New("error"))
// Wait for min execution period end
sdkCtx := sdk.UnwrapSDKContext(ctx)