diff --git a/charts/chainlink-cluster/dashboard/dashboard.go b/charts/chainlink-cluster/dashboard/dashboard.go index 19a596b63e9..54b59ae25e6 100644 --- a/charts/chainlink-cluster/dashboard/dashboard.go +++ b/charts/chainlink-cluster/dashboard/dashboard.go @@ -14,7 +14,7 @@ import ( "github.com/K-Phoen/grabana/timeseries" "github.com/K-Phoen/grabana/timeseries/axis" "github.com/K-Phoen/grabana/variable/query" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) /* @@ -954,10 +954,10 @@ func (m *CLClusterDashboard) Deploy(ctx context.Context) error { client := grabana.NewClient(&http.Client{}, m.GrafanaURL, grabana.WithAPIToken(m.GrafanaToken)) folder, err := client.FindOrCreateFolder(ctx, m.Folder) if err != nil { - return errors.Wrap(err, ErrFailedToCreateFolder) + return pkgerrors.Wrap(err, ErrFailedToCreateFolder) } if _, err := client.UpsertDashboard(ctx, folder, m.builder); err != nil { - return errors.Wrap(err, ErrFailedToCreateDashboard) + return pkgerrors.Wrap(err, ErrFailedToCreateDashboard) } return nil } diff --git a/core/auth/auth.go b/core/auth/auth.go index f881afab736..62f1ab528a2 100644 --- a/core/auth/auth.go +++ b/core/auth/auth.go @@ -4,9 +4,10 @@ import ( "encoding/hex" "fmt" + pkgerrors "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink/v2/core/utils" - "github.com/pkg/errors" "golang.org/x/crypto/sha3" ) @@ -14,7 +15,7 @@ var ( // ErrorAuthFailed is a generic authentication failed - but not because of // some system failure on our behalf (i.e. HTTP 5xx), more detail is not // given - ErrorAuthFailed = errors.New("Authentication failed") + ErrorAuthFailed = pkgerrors.New("Authentication failed") ) // Token is used for API authentication. @@ -57,7 +58,7 @@ func HashedSecret(ta *Token, salt string) (string, error) { hasher := sha3.New256() _, err := hasher.Write(hashInput(ta, salt)) if err != nil { - return "", errors.Wrap(err, "error writing external initiator authentication to hasher") + return "", pkgerrors.Wrap(err, "error writing external initiator authentication to hasher") } return hex.EncodeToString(hasher.Sum(nil)), nil } diff --git a/core/bridges/external_initiator.go b/core/bridges/external_initiator.go index 53d00e77bbb..bfec3adb407 100644 --- a/core/bridges/external_initiator.go +++ b/core/bridges/external_initiator.go @@ -5,11 +5,11 @@ import ( "strings" "time" + pkgerrors "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/store/models" "github.com/smartcontractkit/chainlink/v2/core/utils" - - "github.com/pkg/errors" ) // ExternalInitiatorRequest is the incoming record used to create an ExternalInitiator. @@ -42,7 +42,7 @@ func NewExternalInitiator( salt := utils.NewSecret(utils.DefaultSecretSize) hashedSecret, err := auth.HashedSecret(eia, salt) if err != nil { - return nil, errors.Wrap(err, "error hashing secret for external initiator") + return nil, pkgerrors.Wrap(err, "error hashing secret for external initiator") } return &ExternalInitiator{ diff --git a/core/bridges/orm.go b/core/bridges/orm.go index 8ae6b855c88..f4728ea0662 100644 --- a/core/bridges/orm.go +++ b/core/bridges/orm.go @@ -7,7 +7,7 @@ import ( "time" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/logger" @@ -67,7 +67,7 @@ func (o *orm) FindBridge(name BridgeName) (bt BridgeType, err error) { // Expects all bridges to be unique func (o *orm) FindBridges(names []BridgeName) (bts []BridgeType, err error) { if len(names) == 0 { - return nil, errors.Errorf("at least one bridge name is required") + return nil, pkgerrors.Errorf("at least one bridge name is required") } var allFoundBts []BridgeType @@ -99,7 +99,7 @@ func (o *orm) FindBridges(names []BridgeName) (bts []BridgeType, err error) { } allFoundBts = append(allFoundBts, bts...) if len(allFoundBts) != len(names) { - return nil, errors.Errorf("not all bridges exist, asked for %v, exists %v", names, allFoundBts) + return nil, pkgerrors.Errorf("not all bridges exist, asked for %v, exists %v", names, allFoundBts) } return allFoundBts, nil } @@ -128,11 +128,11 @@ func (o *orm) DeleteBridgeType(bt *BridgeType) error { func (o *orm) BridgeTypes(offset int, limit int) (bridges []BridgeType, count int, err error) { err = o.q.Transaction(func(tx pg.Queryer) error { if err = tx.Get(&count, "SELECT COUNT(*) FROM bridge_types"); err != nil { - return errors.Wrap(err, "BridgeTypes failed to get count") + return pkgerrors.Wrap(err, "BridgeTypes failed to get count") } sql := `SELECT * FROM bridge_types ORDER BY name asc LIMIT $1 OFFSET $2;` if err = tx.Select(&bridges, sql, limit, offset); err != nil { - return errors.Wrap(err, "BridgeTypes failed to load bridge_types") + return pkgerrors.Wrap(err, "BridgeTypes failed to load bridge_types") } return nil }, pg.OptReadOnlyTx()) @@ -157,7 +157,7 @@ func (o *orm) CreateBridgeType(bt *BridgeType) error { o.bridgeTypesCache.Store(bt.Name, *bt) } - return errors.Wrap(err, "CreateBridgeType failed") + return pkgerrors.Wrap(err, "CreateBridgeType failed") } // UpdateBridgeType updates the bridge type. @@ -179,7 +179,7 @@ func (o *orm) GetCachedResponse(dotId string, specId int32, maxElapsed time.Dura finished_at > ($3) ORDER BY finished_at DESC LIMIT 1;` - err = errors.Wrap(o.q.Get(&response, sql, dotId, specId, stalenessThreshold), fmt.Sprintf("failed to fetch last good value for task %s spec %d", dotId, specId)) + err = pkgerrors.Wrap(o.q.Get(&response, sql, dotId, specId, stalenessThreshold), fmt.Sprintf("failed to fetch last good value for task %s spec %d", dotId, specId)) return } @@ -190,7 +190,7 @@ func (o *orm) UpsertBridgeResponse(dotId string, specId int32, response []byte) DO UPDATE SET value = $3, finished_at = $4;` err := o.q.ExecQ(sql, dotId, specId, response, time.Now()) - return errors.Wrap(err, "failed to upsert bridge response") + return pkgerrors.Wrap(err, "failed to upsert bridge response") } // --- External Initiator @@ -199,12 +199,12 @@ func (o *orm) UpsertBridgeResponse(dotId string, specId int32, response []byte) func (o *orm) ExternalInitiators(offset int, limit int) (exis []ExternalInitiator, count int, err error) { err = o.q.Transaction(func(tx pg.Queryer) error { if err = tx.Get(&count, "SELECT COUNT(*) FROM external_initiators"); err != nil { - return errors.Wrap(err, "ExternalInitiators failed to get count") + return pkgerrors.Wrap(err, "ExternalInitiators failed to get count") } sql := `SELECT * FROM external_initiators ORDER BY name asc LIMIT $1 OFFSET $2;` if err = tx.Select(&exis, sql, limit, offset); err != nil { - return errors.Wrap(err, "ExternalInitiators failed to load external_initiators") + return pkgerrors.Wrap(err, "ExternalInitiators failed to load external_initiators") } return nil }, pg.OptReadOnlyTx()) @@ -221,12 +221,12 @@ func (o *orm) CreateExternalInitiator(externalInitiator *ExternalInitiator) (err var stmt *sqlx.NamedStmt stmt, err = tx.PrepareNamed(query) if err != nil { - return errors.Wrap(err, "failed to prepare named stmt") + return pkgerrors.Wrap(err, "failed to prepare named stmt") } defer stmt.Close() - return errors.Wrap(stmt.Get(externalInitiator, externalInitiator), "failed to load external_initiator") + return pkgerrors.Wrap(stmt.Get(externalInitiator, externalInitiator), "failed to load external_initiator") }) - return errors.Wrap(err, "CreateExternalInitiator failed") + return pkgerrors.Wrap(err, "CreateExternalInitiator failed") } // DeleteExternalInitiator removes an external initiator diff --git a/core/cbor/cbor.go b/core/cbor/cbor.go index cc3f74e423e..fb6e6c88f95 100644 --- a/core/cbor/cbor.go +++ b/core/cbor/cbor.go @@ -6,7 +6,7 @@ import ( "math/big" "github.com/fxamacker/cbor/v2" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) // ParseDietCBOR attempts to coerce the input byte array into valid CBOR. @@ -28,7 +28,7 @@ func ParseDietCBOR(b []byte) (map[string]interface{}, error) { output, ok := coerced.(map[string]interface{}) if !ok { - return nil, errors.New("cbor data cannot be coerced to map") + return nil, pkgerrors.New("cbor data cannot be coerced to map") } return output, nil diff --git a/core/chains/evm/assets/wei.go b/core/chains/evm/assets/wei.go index 8bacabfdb4a..3621e4492a4 100644 --- a/core/chains/evm/assets/wei.go +++ b/core/chains/evm/assets/wei.go @@ -6,7 +6,7 @@ import ( "math/big" "strings" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" "golang.org/x/exp/constraints" @@ -185,7 +185,7 @@ func (w *Wei) UnmarshalText(b []byte) error { t = strings.TrimSuffix(t, " ") d, err := decimal.NewFromString(t) if err != nil { - return errors.Wrapf(err, "unable to parse %q", s) + return pkgerrors.Wrapf(err, "unable to parse %q", s) } se := suffixExp(suf) if d.IsInteger() { @@ -196,8 +196,8 @@ func (w *Wei) UnmarshalText(b []byte) error { d = d.Mul(decimal.New(1, se)) if !d.IsInteger() { - err := errors.New("maximum precision is wei") - return errors.Wrapf(err, "unable to parse %q", s) + err := pkgerrors.New("maximum precision is wei") + return pkgerrors.Wrapf(err, "unable to parse %q", s) } *w = (Wei)(*d.BigInt()) return nil @@ -206,13 +206,13 @@ func (w *Wei) UnmarshalText(b []byte) error { // unrecognized or missing suffix d, err := decimal.NewFromString(s) if err != nil { - return errors.Wrapf(err, "unable to parse %q", s) + return pkgerrors.Wrapf(err, "unable to parse %q", s) } if d.IsInteger() { *w = (Wei)(*d.BigInt()) return nil } - return errors.Errorf("unable to parse %q", s) + return pkgerrors.Errorf("unable to parse %q", s) } func (w *Wei) ToInt() *big.Int { diff --git a/core/chains/evm/client/client.go b/core/chains/evm/client/client.go index e2ae8c26403..70d989ae808 100644 --- a/core/chains/evm/client/client.go +++ b/core/chains/evm/client/client.go @@ -22,7 +22,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) const queryTimeout = 10 * time.Second @@ -126,7 +126,7 @@ func NewClientWithNodes(lggr logger.Logger, selectionMode string, leaseDuration // node's remote chain ID matches the local one func (client *client) Dial(ctx context.Context) error { if err := client.pool.Dial(ctx); err != nil { - return errors.Wrap(err, "failed to dial pool") + return pkgerrors.Wrap(err, "failed to dial pool") } return nil } diff --git a/core/chains/evm/client/client_test.go b/core/chains/evm/client/client_test.go index 281b8bf4227..62acf146e48 100644 --- a/core/chains/evm/client/client_test.go +++ b/core/chains/evm/client/client_test.go @@ -17,7 +17,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" @@ -145,7 +145,7 @@ func TestEthClient_TransactionReceipt(t *testing.T) { hash := common.HexToHash(txHash) _, err = ethClient.TransactionReceipt(testutils.Context(t), hash) - require.Equal(t, ethereum.NotFound, errors.Cause(err)) + require.Equal(t, ethereum.NotFound, pkgerrors.Cause(err)) } }) } diff --git a/core/chains/evm/client/erroring_node.go b/core/chains/evm/client/erroring_node.go index 059f76d608a..00e8465bca3 100644 --- a/core/chains/evm/client/erroring_node.go +++ b/core/chains/evm/client/erroring_node.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) var _ Node = (*erroringNode)(nil) @@ -27,104 +27,104 @@ func (e *erroringNode) SubscribersCount() int32 { func (e *erroringNode) ChainID() (chainID *big.Int) { return nil } -func (e *erroringNode) Start(ctx context.Context) error { return errors.New(e.errMsg) } +func (e *erroringNode) Start(ctx context.Context) error { return pkgerrors.New(e.errMsg) } func (e *erroringNode) Close() error { return nil } func (e *erroringNode) Verify(ctx context.Context, expectedChainID *big.Int) (err error) { - return errors.New(e.errMsg) + return pkgerrors.New(e.errMsg) } func (e *erroringNode) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { - return errors.New(e.errMsg) + return pkgerrors.New(e.errMsg) } func (e *erroringNode) BatchCallContext(ctx context.Context, b []rpc.BatchElem) error { - return errors.New(e.errMsg) + return pkgerrors.New(e.errMsg) } func (e *erroringNode) SendTransaction(ctx context.Context, tx *types.Transaction) error { - return errors.New(e.errMsg) + return pkgerrors.New(e.errMsg) } func (e *erroringNode) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { - return 0, errors.New(e.errMsg) + return 0, pkgerrors.New(e.errMsg) } func (e *erroringNode) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) { - return 0, errors.New(e.errMsg) + return 0, pkgerrors.New(e.errMsg) } func (e *erroringNode) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) BlockNumber(ctx context.Context) (uint64, error) { - return 0, errors.New(e.errMsg) + return 0, pkgerrors.New(e.errMsg) } func (e *erroringNode) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { - return 0, errors.New(e.errMsg) + return 0, pkgerrors.New(e.errMsg) } func (e *erroringNode) SuggestGasPrice(ctx context.Context) (*big.Int, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) HeaderByNumber(_ context.Context, _ *big.Int) (*types.Header, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) HeaderByHash(_ context.Context, _ common.Hash) (*types.Header, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) EthSubscribe(ctx context.Context, channel chan<- *evmtypes.Head, args ...interface{}) (ethereum.Subscription, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) String() string { diff --git a/core/chains/evm/client/errors.go b/core/chains/evm/client/errors.go index 1c470f0cfc6..42a983b40d7 100644 --- a/core/chains/evm/client/errors.go +++ b/core/chains/evm/client/errors.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -36,7 +36,7 @@ func (s *SendError) Fatal() bool { // CauseStr returns the string of the original error func (s *SendError) CauseStr() string { if s.err != nil { - return errors.Cause(s.err).Error() + return pkgerrors.Cause(s.err).Error() } return "" } @@ -316,7 +316,7 @@ func (s *SendError) IsTimeout() bool { if s.err == nil { return false } - return errors.Is(s.err, context.DeadlineExceeded) + return pkgerrors.Is(s.err, context.DeadlineExceeded) } // IsCanceled indicates if the error was caused by an context cancellation @@ -327,18 +327,18 @@ func (s *SendError) IsCanceled() bool { if s.err == nil { return false } - return errors.Is(s.err, context.Canceled) + return pkgerrors.Is(s.err, context.Canceled) } func NewFatalSendError(e error) *SendError { if e == nil { return nil } - return &SendError{err: errors.WithStack(e), fatal: true} + return &SendError{err: pkgerrors.WithStack(e), fatal: true} } func NewSendErrorS(s string) *SendError { - return NewSendError(errors.New(s)) + return NewSendError(pkgerrors.New(s)) } func NewSendError(e error) *SendError { @@ -346,7 +346,7 @@ func NewSendError(e error) *SendError { return nil } fatal := isFatalSendError(e) - return &SendError{err: errors.WithStack(e), fatal: fatal} + return &SendError{err: pkgerrors.WithStack(e), fatal: fatal} } // Geth/parity returns these errors if the transaction failed in such a way that: @@ -356,7 +356,7 @@ func isFatalSendError(err error) bool { if err == nil { return false } - str := errors.Cause(err).Error() + str := pkgerrors.Cause(err).Error() for _, client := range clients { if _, ok := client[Fatal]; !ok { continue @@ -414,20 +414,20 @@ func ExtractRPCErrorOrNil(err error) *JsonError { // { "error": { "code": 3, "data": "0xABC123...", "message": "execution reverted: hello world" } } // revert reason automatically parsed if a simple require and included in message. func ExtractRPCError(baseErr error) (*JsonError, error) { if baseErr == nil { - return nil, errors.New("no error present") + return nil, pkgerrors.New("no error present") } - cause := errors.Cause(baseErr) + cause := pkgerrors.Cause(baseErr) jsonBytes, err := json.Marshal(cause) if err != nil { - return nil, errors.Wrap(err, "unable to marshal err to json") + return nil, pkgerrors.Wrap(err, "unable to marshal err to json") } jErr := JsonError{} err = json.Unmarshal(jsonBytes, &jErr) if err != nil { - return nil, errors.Wrapf(err, "unable to unmarshal json into jsonError struct (got: %v)", baseErr) + return nil, pkgerrors.Wrapf(err, "unable to unmarshal json into jsonError struct (got: %v)", baseErr) } if jErr.Code == 0 { - return nil, errors.Errorf("not a RPCError because it does not have a code (got: %v)", baseErr) + return nil, pkgerrors.Errorf("not a RPCError because it does not have a code (got: %v)", baseErr) } return &jErr, nil } diff --git a/core/chains/evm/client/errors_test.go b/core/chains/evm/client/errors_test.go index f47b93c0400..e6ba89fcb5a 100644 --- a/core/chains/evm/client/errors_test.go +++ b/core/chains/evm/client/errors_test.go @@ -3,14 +3,14 @@ package client_test import ( "testing" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" ) func newSendErrorWrapped(s string) *evmclient.SendError { - return evmclient.NewSendError(errors.Wrap(errors.New(s), "wrapped with some old bollocks")) + return evmclient.NewSendError(pkgerrors.Wrap(pkgerrors.New(s), "wrapped with some old bollocks")) } type errorCase struct { @@ -362,7 +362,7 @@ func Test_Eth_Errors_Fatal(t *testing.T) { for _, test := range tests { t.Run(test.message, func(t *testing.T) { - err := evmclient.NewSendError(errors.New(test.message)) + err := evmclient.NewSendError(pkgerrors.New(test.message)) assert.Equal(t, test.expect, err.Fatal()) }) } diff --git a/core/chains/evm/client/helpers_test.go b/core/chains/evm/client/helpers_test.go index 467195e11e8..105c9ae34cd 100644 --- a/core/chains/evm/client/helpers_test.go +++ b/core/chains/evm/client/helpers_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" commonclient "github.com/smartcontractkit/chainlink/v2/common/client" @@ -39,7 +39,7 @@ func NewClientWithTestNode(t *testing.T, nodePoolCfg config.NodePool, noNewHeads } if parsed.Scheme != "ws" && parsed.Scheme != "wss" { - return nil, errors.Errorf("ethereum url scheme must be websocket: %s", parsed.String()) + return nil, pkgerrors.Errorf("ethereum url scheme must be websocket: %s", parsed.String()) } lggr := logger.Sugared(logger.Test(t)) @@ -50,7 +50,7 @@ func NewClientWithTestNode(t *testing.T, nodePoolCfg config.NodePool, noNewHeads var sendonlys []SendOnlyNode for i, url := range sendonlyRPCURLs { if url.Scheme != "http" && url.Scheme != "https" { - return nil, errors.Errorf("sendonly ethereum rpc url scheme must be http(s): %s", url.String()) + return nil, pkgerrors.Errorf("sendonly ethereum rpc url scheme must be http(s): %s", url.String()) } s := NewSendOnlyNode(lggr, url, fmt.Sprintf("eth-sendonly-%d", i), chainID) sendonlys = append(sendonlys, s) @@ -83,7 +83,7 @@ func NewChainClientWithTestNode( } if parsed.Scheme != "ws" && parsed.Scheme != "wss" { - return nil, errors.Errorf("ethereum url scheme must be websocket: %s", parsed.String()) + return nil, pkgerrors.Errorf("ethereum url scheme must be websocket: %s", parsed.String()) } lggr := logger.Test(t) @@ -96,7 +96,7 @@ func NewChainClientWithTestNode( var sendonlys []commonclient.SendOnlyNode[*big.Int, RPCCLient] for i, u := range sendonlyRPCURLs { if u.Scheme != "http" && u.Scheme != "https" { - return nil, errors.Errorf("sendonly ethereum rpc url scheme must be http(s): %s", u.String()) + return nil, pkgerrors.Errorf("sendonly ethereum rpc url scheme must be http(s): %s", u.String()) } var empty url.URL rpc := NewRPCClient(lggr, empty, &sendonlyRPCURLs[i], fmt.Sprintf("eth-sendonly-rpc-%d", i), id, chainID, commonclient.Secondary) diff --git a/core/chains/evm/client/node.go b/core/chains/evm/client/node.go index aa472d605a6..474ff2700b4 100644 --- a/core/chains/evm/client/node.go +++ b/core/chains/evm/client/node.go @@ -15,7 +15,7 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/rpc" "github.com/google/uuid" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -245,7 +245,7 @@ func (n *node) start(startCtx context.Context) { verifyCtx, verifyCancel := n.makeQueryCtx(startCtx) defer verifyCancel() - if err := n.verify(verifyCtx); errors.Is(err, errInvalidChainID) { + if err := n.verify(verifyCtx); pkgerrors.Is(err, errInvalidChainID) { n.lfcLog.Errorw("Verify failed: EVM Node has the wrong chain ID", "err", err) n.declareInvalidChainID() return @@ -274,7 +274,7 @@ func (n *node) dial(callerCtx context.Context) error { wsrpc, err := rpc.DialWebsocket(ctx, n.ws.uri.String(), "") if err != nil { promEVMPoolRPCNodeDialsFailed.WithLabelValues(n.chainID.String(), n.name).Inc() - return errors.Wrapf(err, "error while dialing websocket: %v", n.ws.uri.Redacted()) + return pkgerrors.Wrapf(err, "error while dialing websocket: %v", n.ws.uri.Redacted()) } var httprpc *rpc.Client @@ -282,7 +282,7 @@ func (n *node) dial(callerCtx context.Context) error { httprpc, err = rpc.DialHTTP(n.http.uri.String()) if err != nil { promEVMPoolRPCNodeDialsFailed.WithLabelValues(n.chainID.String(), n.name).Inc() - return errors.Wrapf(err, "error while dialing HTTP: %v", n.http.uri.Redacted()) + return pkgerrors.Wrapf(err, "error while dialing HTTP: %v", n.http.uri.Redacted()) } } @@ -299,7 +299,7 @@ func (n *node) dial(callerCtx context.Context) error { return nil } -var errInvalidChainID = errors.New("invalid chain id") +var errInvalidChainID = pkgerrors.New("invalid chain id") // verify checks that all connections to eth nodes match the given chain ID // Not thread-safe @@ -323,10 +323,10 @@ func (n *node) verify(callerCtx context.Context) (err error) { var chainID *big.Int if chainID, err = n.ws.geth.ChainID(ctx); err != nil { promFailed() - return errors.Wrapf(err, "failed to verify chain ID for node %s", n.name) + return pkgerrors.Wrapf(err, "failed to verify chain ID for node %s", n.name) } else if chainID.Cmp(n.chainID) != 0 { promFailed() - return errors.Wrapf( + return pkgerrors.Wrapf( errInvalidChainID, "websocket rpc ChainID doesn't match local chain ID: RPC ID=%s, local ID=%s, node name=%s", chainID.String(), @@ -337,10 +337,10 @@ func (n *node) verify(callerCtx context.Context) (err error) { if n.http != nil { if chainID, err = n.http.geth.ChainID(ctx); err != nil { promFailed() - return errors.Wrapf(err, "failed to verify chain ID for node %s", n.name) + return pkgerrors.Wrapf(err, "failed to verify chain ID for node %s", n.name) } else if chainID.Cmp(n.chainID) != 0 { promFailed() - return errors.Wrapf( + return pkgerrors.Wrapf( errInvalidChainID, "http rpc ChainID doesn't match local chain ID: RPC ID=%s, local ID=%s, node name=%s", chainID.String(), @@ -1094,10 +1094,10 @@ func wrap(err error, tp string) error { if err == nil { return nil } - if errors.Cause(err).Error() == "context deadline exceeded" { - err = errors.Wrap(err, "remote eth node timed out") + if pkgerrors.Cause(err).Error() == "context deadline exceeded" { + err = pkgerrors.Wrap(err, "remote eth node timed out") } - return errors.Wrapf(err, "%s call failed", tp) + return pkgerrors.Wrapf(err, "%s call failed", tp) } // makeLiveQueryCtxAndSafeGetClients wraps makeQueryCtx but returns error if node is not NodeStateAlive. @@ -1106,7 +1106,7 @@ func (n *node) makeLiveQueryCtxAndSafeGetClients(parentCtx context.Context) (ctx // context n.stateMu.RLock() if n.state != NodeStateAlive { - err = errors.Errorf("cannot execute RPC call on node with state: %s", n.state) + err = pkgerrors.Errorf("cannot execute RPC call on node with state: %s", n.state) n.stateMu.RUnlock() return } diff --git a/core/chains/evm/client/node_lifecycle.go b/core/chains/evm/client/node_lifecycle.go index f2232a14935..41add532222 100644 --- a/core/chains/evm/client/node_lifecycle.go +++ b/core/chains/evm/client/node_lifecycle.go @@ -7,7 +7,7 @@ import ( "math/big" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -381,7 +381,7 @@ func (n *node) unreachableLoop() { err = n.verify(n.nodeCtx) - if errors.Is(err, errInvalidChainID) { + if pkgerrors.Is(err, errInvalidChainID) { lggr.Errorw("Failed to redial RPC node; remote endpoint returned the wrong chain ID", "err", err) n.declareInvalidChainID() return @@ -426,7 +426,7 @@ func (n *node) invalidChainIDLoop() { return case <-time.After(chainIDRecheckBackoff.Duration()): err := n.verify(n.nodeCtx) - if errors.Is(err, errInvalidChainID) { + if pkgerrors.Is(err, errInvalidChainID) { lggr.Errorw("Failed to verify RPC node; remote endpoint returned the wrong chain ID", "err", err) continue } else if err != nil { diff --git a/core/chains/evm/client/pool.go b/core/chains/evm/client/pool.go index 3c33b3dbd0a..891fd8c9226 100644 --- a/core/chains/evm/client/pool.go +++ b/core/chains/evm/client/pool.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -133,12 +133,12 @@ func NewPool(lggr logger.Logger, selectionMode string, leaseDuration time.Durati func (p *Pool) Dial(ctx context.Context) error { return p.StartOnce("Pool", func() (merr error) { if len(p.nodes) == 0 { - return errors.Errorf("no available nodes for chain %s", p.chainID.String()) + return pkgerrors.Errorf("no available nodes for chain %s", p.chainID.String()) } var ms services.MultiStart for _, n := range p.nodes { if n.ChainID().Cmp(p.chainID) != 0 { - return ms.CloseBecause(errors.Errorf("node %s has chain ID %s which does not match pool chain ID of %s", n.String(), n.ChainID().String(), p.chainID.String())) + return ms.CloseBecause(pkgerrors.Errorf("node %s has chain ID %s which does not match pool chain ID of %s", n.String(), n.ChainID().String(), p.chainID.String())) } rawNode, ok := n.(*node) if ok { @@ -155,7 +155,7 @@ func (p *Pool) Dial(ctx context.Context) error { } for _, s := range p.sendonlys { if s.ChainID().Cmp(p.chainID) != 0 { - return ms.CloseBecause(errors.Errorf("sendonly node %s has chain ID %s which does not match pool chain ID of %s", s.String(), s.ChainID().String(), p.chainID.String())) + return ms.CloseBecause(pkgerrors.Errorf("sendonly node %s has chain ID %s which does not match pool chain ID of %s", s.String(), s.ChainID().String(), p.chainID.String())) } if err := ms.Start(ctx, s); err != nil { return err diff --git a/core/chains/evm/client/rpc_client.go b/core/chains/evm/client/rpc_client.go index 08791658430..f682303c11c 100644 --- a/core/chains/evm/client/rpc_client.go +++ b/core/chains/evm/client/rpc_client.go @@ -16,7 +16,7 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/rpc" "github.com/google/uuid" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" commonassets "github.com/smartcontractkit/chainlink-common/pkg/assets" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -128,7 +128,7 @@ func (r *rpcClient) Dial(callerCtx context.Context) error { wsrpc, err := rpc.DialWebsocket(ctx, r.ws.uri.String(), "") if err != nil { promEVMPoolRPCNodeDialsFailed.WithLabelValues(r.chainID.String(), r.name).Inc() - return errors.Wrapf(err, "error while dialing websocket: %v", r.ws.uri.Redacted()) + return pkgerrors.Wrapf(err, "error while dialing websocket: %v", r.ws.uri.Redacted()) } r.ws.rpc = wsrpc @@ -157,7 +157,7 @@ func (r *rpcClient) DialHTTP() error { httprpc, err := rpc.DialHTTP(r.http.uri.String()) if err != nil { promEVMPoolRPCNodeDialsFailed.WithLabelValues(r.chainID.String(), r.name).Inc() - return errors.Wrapf(err, "error while dialing HTTP: %v", r.http.uri.Redacted()) + return pkgerrors.Wrapf(err, "error while dialing HTTP: %v", r.http.uri.Redacted()) } r.http.rpc = httprpc @@ -580,7 +580,7 @@ func (r *rpcClient) SendTransaction(ctx context.Context, tx *types.Transaction) func (r *rpcClient) SimulateTransaction(ctx context.Context, tx *types.Transaction) error { // Not Implemented - return errors.New("SimulateTransaction not implemented") + return pkgerrors.New("SimulateTransaction not implemented") } func (r *rpcClient) SendEmptyTransaction( @@ -592,7 +592,7 @@ func (r *rpcClient) SendEmptyTransaction( fromAddress common.Address, ) (txhash string, err error) { // Not Implemented - return "", errors.New("SendEmptyTransaction not implemented") + return "", pkgerrors.New("SendEmptyTransaction not implemented") } // PendingSequenceAt returns one higher than the highest nonce from both mempool and mined transactions @@ -1065,10 +1065,10 @@ func wrapCallError(err error, tp string) error { if err == nil { return nil } - if errors.Cause(err).Error() == "context deadline exceeded" { - err = errors.Wrap(err, "remote node timed out") + if pkgerrors.Cause(err).Error() == "context deadline exceeded" { + err = pkgerrors.Wrap(err, "remote node timed out") } - return errors.Wrapf(err, "%s call failed", tp) + return pkgerrors.Wrapf(err, "%s call failed", tp) } func (r *rpcClient) wrapWS(err error) error { diff --git a/core/chains/evm/forwarders/forwarder_manager.go b/core/chains/evm/forwarders/forwarder_manager.go index cabedf79aee..452bb87cae2 100644 --- a/core/chains/evm/forwarders/forwarder_manager.go +++ b/core/chains/evm/forwarders/forwarder_manager.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/jmoiron/sqlx" @@ -82,7 +82,7 @@ func (f *FwdMgr) Start(ctx context.Context) error { fwdrs, err := f.ORM.FindForwardersByChain(big.Big(*chainId)) if err != nil { - return errors.Wrapf(err, "Failed to retrieve forwarders for chain %d", chainId) + return pkgerrors.Wrapf(err, "Failed to retrieve forwarders for chain %d", chainId) } if len(fwdrs) != 0 { f.initForwardersCache(ctx, fwdrs) @@ -93,12 +93,12 @@ func (f *FwdMgr) Start(ctx context.Context) error { f.authRcvr, err = authorized_receiver.NewAuthorizedReceiver(common.Address{}, f.evmClient) if err != nil { - return errors.Wrap(err, "Failed to init AuthorizedReceiver") + return pkgerrors.Wrap(err, "Failed to init AuthorizedReceiver") } f.offchainAgg, err = offchain_aggregator_wrapper.NewOffchainAggregator(common.Address{}, f.evmClient) if err != nil { - return errors.Wrap(err, "Failed to init OffchainAggregator") + return pkgerrors.Wrap(err, "Failed to init OffchainAggregator") } f.wg.Add(1) @@ -130,7 +130,7 @@ func (f *FwdMgr) ForwarderFor(addr common.Address) (forwarder common.Address, er } } } - return common.Address{}, errors.Errorf("Cannot find forwarder for given EOA") + return common.Address{}, pkgerrors.Errorf("Cannot find forwarder for given EOA") } func (f *FwdMgr) ConvertPayload(dest common.Address, origPayload []byte) ([]byte, error) { @@ -148,7 +148,7 @@ func (f *FwdMgr) ConvertPayload(dest common.Address, origPayload []byte) ([]byte func (f *FwdMgr) getForwardedPayload(dest common.Address, origPayload []byte) ([]byte, error) { callArgs, err := forwardABI.Inputs.Pack(dest, origPayload) if err != nil { - return nil, errors.Wrap(err, "Failed to pack forwarder payload") + return nil, pkgerrors.Wrap(err, "Failed to pack forwarder payload") } dataBytes := append(forwardABI.ID, callArgs...) @@ -161,7 +161,7 @@ func (f *FwdMgr) getContractSenders(addr common.Address) ([]common.Address, erro } senders, err := f.getAuthorizedSenders(f.ctx, addr) if err != nil { - return nil, errors.Wrapf(err, "Failed to call getAuthorizedSenders on %s", addr) + return nil, pkgerrors.Wrapf(err, "Failed to call getAuthorizedSenders on %s", addr) } f.setCachedSenders(addr, senders) if err = f.subscribeSendersChangedLogs(addr); err != nil { @@ -173,7 +173,7 @@ func (f *FwdMgr) getContractSenders(addr common.Address) ([]common.Address, erro func (f *FwdMgr) getAuthorizedSenders(ctx context.Context, addr common.Address) ([]common.Address, error) { c, err := authorized_receiver.NewAuthorizedReceiverCaller(addr, f.evmClient) if err != nil { - return nil, errors.Wrap(err, "Failed to init forwarder caller") + return nil, pkgerrors.Wrap(err, "Failed to init forwarder caller") } opts := bind.CallOpts{Context: ctx, Pending: false} senders, err := c.GetAuthorizedSenders(&opts) @@ -296,7 +296,7 @@ func (f *FwdMgr) handleAuthChange(log evmlogpoller.Log) error { if ethLog.Topics[0] == authChangedTopic { event, err := f.authRcvr.ParseAuthorizedSendersChanged(ethLog) if err != nil { - return errors.New("Failed to parse senders change log") + return pkgerrors.New("Failed to parse senders change log") } f.setCachedSenders(event.Raw.Address, event.Senders) } diff --git a/core/chains/evm/forwarders/orm.go b/core/chains/evm/forwarders/orm.go index 2a455360190..8b4ba5273a3 100644 --- a/core/chains/evm/forwarders/orm.go +++ b/core/chains/evm/forwarders/orm.go @@ -5,7 +5,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big" @@ -64,7 +64,7 @@ func (o *orm) DeleteForwarder(id int64, cleanup func(tx pg.Queryer, evmChainID i // If the forwarder wasn't found, we still want to delete the filter. // In that case, the transaction must return nil, even though DeleteForwarder // will return sql.ErrNoRows - if err2 != nil && !errors.Is(err2, sql.ErrNoRows) { + if err2 != nil && !pkgerrors.Is(err2, sql.ErrNoRows) { return err2 } rowsAffected, err2 = result.RowsAffected() @@ -116,19 +116,19 @@ func (o *orm) FindForwardersInListByChain(evmChainId big.Big, addrs []common.Add ) if err != nil { - return nil, errors.Wrap(err, "Failed to format query") + return nil, pkgerrors.Wrap(err, "Failed to format query") } query, args, err = sqlx.In(query, args...) if err != nil { - return nil, errors.Wrap(err, "Failed to run sqlx.IN on query") + return nil, pkgerrors.Wrap(err, "Failed to run sqlx.IN on query") } query = o.q.Rebind(query) err = o.q.Select(&fwdrs, query, args...) if err != nil { - return nil, errors.Wrap(err, "Failed to execute query") + return nil, pkgerrors.Wrap(err, "Failed to execute query") } return fwdrs, nil diff --git a/core/chains/evm/gas/arbitrum_estimator.go b/core/chains/evm/gas/arbitrum_estimator.go index a94fddc0e9d..525d439e3e4 100644 --- a/core/chains/evm/gas/arbitrum_estimator.go +++ b/core/chains/evm/gas/arbitrum_estimator.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -76,7 +76,7 @@ func (a *arbitrumEstimator) Name() string { func (a *arbitrumEstimator) Start(ctx context.Context) error { return a.StartOnce("ArbitrumEstimator", func() error { if err := a.EvmEstimator.Start(ctx); err != nil { - return errors.Wrap(err, "failed to start gas price estimator") + return pkgerrors.Wrap(err, "failed to start gas price estimator") } go a.run() <-a.chInitialised @@ -86,7 +86,7 @@ func (a *arbitrumEstimator) Start(ctx context.Context) error { func (a *arbitrumEstimator) Close() error { return a.StopOnce("ArbitrumEstimator", func() (err error) { close(a.chStop) - err = errors.Wrap(a.EvmEstimator.Close(), "failed to stop gas price estimator") + err = pkgerrors.Wrap(a.EvmEstimator.Close(), "failed to stop gas price estimator") <-a.chDone return }) @@ -117,7 +117,7 @@ func (a *arbitrumEstimator) GetLegacyGas(ctx context.Context, calldata []byte, l select { case a.chForceRefetch <- ch: case <-a.chStop: - err = errors.New("estimator stopped") + err = pkgerrors.New("estimator stopped") return case <-ctx.Done(): err = ctx.Err() @@ -126,7 +126,7 @@ func (a *arbitrumEstimator) GetLegacyGas(ctx context.Context, calldata []byte, l select { case <-ch: case <-a.chStop: - err = errors.New("estimator stopped") + err = pkgerrors.New("estimator stopped") return case <-ctx.Done(): err = ctx.Err() @@ -139,7 +139,7 @@ func (a *arbitrumEstimator) GetLegacyGas(ctx context.Context, calldata []byte, l "perL1CalldataUnit", perL1CalldataUnit, "chainSpecificGasLimit", chainSpecificGasLimit) }) if !ok { - return nil, 0, errors.New("estimator is not started") + return nil, 0, pkgerrors.New("estimator is not started") } else if err != nil { return } diff --git a/core/chains/evm/gas/arbitrum_estimator_test.go b/core/chains/evm/gas/arbitrum_estimator_test.go index dad48b528bb..e5a5af8d4f8 100644 --- a/core/chains/evm/gas/arbitrum_estimator_test.go +++ b/core/chains/evm/gas/arbitrum_estimator_test.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -149,7 +149,7 @@ func TestArbitrumEstimator(t *testing.T) { ethClient := mocks.NewETHClient(t) o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, client, ethClient) - client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(errors.New("kaboom")) + client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(pkgerrors.New("kaboom")) ethClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), mock.IsType(&big.Int{})).Run(func(args mock.Arguments) { callMsg := args.Get(1).(ethereum.CallMsg) blockNumber := args.Get(2).(*big.Int) diff --git a/core/chains/evm/gas/block_history_estimator.go b/core/chains/evm/gas/block_history_estimator.go index c8eee2f1bd0..66f3e5d2e67 100644 --- a/core/chains/evm/gas/block_history_estimator.go +++ b/core/chains/evm/gas/block_history_estimator.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -204,7 +204,7 @@ func (b *BlockHistoryEstimator) Start(ctx context.Context) error { b.logger.Infof("Inclusion checking enabled, bumping will be prevented on transactions that have been priced above the %d percentile for %d blocks", b.bhConfig.CheckInclusionPercentile(), b.bhConfig.CheckInclusionBlocks()) } if b.bhConfig.BlockHistorySize() == 0 { - return errors.New("BlockHistorySize must be set to a value greater than 0") + return pkgerrors.New("BlockHistorySize must be set to a value greater than 0") } fetchCtx, cancel := context.WithTimeout(ctx, MaxStartTime) @@ -222,7 +222,7 @@ func (b *BlockHistoryEstimator) Start(ctx context.Context) error { // NOTE: This only checks the start context, not the fetch context if ctx.Err() != nil { - return errors.Wrap(ctx.Err(), "failed to start BlockHistoryEstimator due to main context error") + return pkgerrors.Wrap(ctx.Err(), "failed to start BlockHistoryEstimator due to main context error") } b.wg.Add(1) @@ -253,11 +253,11 @@ func (b *BlockHistoryEstimator) GetLegacyGas(_ context.Context, _ []byte, gasLim gasPrice = b.getGasPrice() }) if !ok { - return nil, 0, errors.New("BlockHistoryEstimator is not started; cannot estimate gas") + return nil, 0, pkgerrors.New("BlockHistoryEstimator is not started; cannot estimate gas") } if gasPrice == nil { if !b.initialFetch.Load() { - return nil, 0, errors.New("BlockHistoryEstimator has not finished the first gas estimation yet, likely because a failure on start") + return nil, 0, pkgerrors.New("BlockHistoryEstimator has not finished the first gas estimation yet, likely because a failure on start") } b.logger.Warnw("Failed to estimate gas price. This is likely because there aren't any valid transactions to estimate from."+ "Using Evm.GasEstimator.PriceDefault as fallback.", "blocks", b.getBlockHistoryNumbers()) @@ -290,7 +290,7 @@ func (b *BlockHistoryEstimator) getTipCap() *assets.Wei { func (b *BlockHistoryEstimator) BumpLegacyGas(_ context.Context, originalGasPrice *assets.Wei, gasLimit uint32, maxGasPriceWei *assets.Wei, attempts []EvmPriorAttempt) (bumpedGasPrice *assets.Wei, chainSpecificGasLimit uint32, err error) { if b.bhConfig.CheckInclusionBlocks() > 0 { if err = b.checkConnectivity(attempts); err != nil { - if errors.Is(err, commonfee.ErrConnectivity) { + if pkgerrors.Is(err, commonfee.ErrConnectivity) { b.logger.Criticalw(BumpingHaltedLabel, "err", err) b.SvcErrBuffer.Append(err) promBlockHistoryEstimatorConnectivityFailureCount.WithLabelValues(b.chainID.String(), "legacy").Inc() @@ -323,7 +323,7 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er if attempt.BroadcastBeforeBlockNum == nil { // this shouldn't happen; any broadcast attempt ought to have a // BroadcastBeforeBlockNum otherwise its an assumption violation - return errors.Errorf("BroadcastBeforeBlockNum was unexpectedly nil for attempt %s", attempt.TxHash) + return pkgerrors.Errorf("BroadcastBeforeBlockNum was unexpectedly nil for attempt %s", attempt.TxHash) } broadcastBeforeBlockNum := *attempt.BroadcastBeforeBlockNum blocksSinceBroadcast := *latestBlockNum - broadcastBeforeBlockNum @@ -352,11 +352,11 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er case 0x2: eip1559 = true default: - return errors.Errorf("attempt %s has unknown transaction type 0x%d", attempt.TxHash, attempt.TxType) + return pkgerrors.Errorf("attempt %s has unknown transaction type 0x%d", attempt.TxHash, attempt.TxType) } gasPrice, tipCap, err := b.calculatePercentilePrices(blocks, percentile, eip1559, nil, nil) if err != nil { - if errors.Is(err, ErrNoSuitableTransactions) { + if pkgerrors.Is(err, ErrNoSuitableTransactions) { b.logger.Warnf("no suitable transactions found to verify if transaction %s has been included within expected inclusion blocks of %d", attempt.TxHash, expectInclusionWithinBlocks) return nil } @@ -365,7 +365,7 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er } if !eip1559 { if attempt.GasPrice.Cmp(gasPrice) > 0 { - return errors.Wrapf(commonfee.ErrConnectivity, "transaction %s has gas price of %s, which is above percentile=%d%% (percentile price: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.GasPrice, percentile, gasPrice, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) + return pkgerrors.Wrapf(commonfee.ErrConnectivity, "transaction %s has gas price of %s, which is above percentile=%d%% (percentile price: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.GasPrice, percentile, gasPrice, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) } continue } @@ -382,7 +382,7 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er } } if sufficientFeeCap && attempt.DynamicFee.TipCap.Cmp(tipCap) > 0 { - return errors.Wrapf(commonfee.ErrConnectivity, "transaction %s has tip cap of %s, which is above percentile=%d%% (percentile tip cap: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.DynamicFee.TipCap, percentile, tipCap, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) + return pkgerrors.Wrapf(commonfee.ErrConnectivity, "transaction %s has tip cap of %s, which is above percentile=%d%% (percentile tip cap: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.DynamicFee.TipCap, percentile, tipCap, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) } } return nil @@ -390,7 +390,7 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er func (b *BlockHistoryEstimator) GetDynamicFee(_ context.Context, gasLimit uint32, maxGasPriceWei *assets.Wei) (fee DynamicFee, chainSpecificGasLimit uint32, err error) { if !b.eConfig.EIP1559DynamicFees() { - return fee, 0, errors.New("Can't get dynamic fee, EIP1559 is disabled") + return fee, 0, pkgerrors.New("Can't get dynamic fee, EIP1559 is disabled") } var feeCap *assets.Wei @@ -405,7 +405,7 @@ func (b *BlockHistoryEstimator) GetDynamicFee(_ context.Context, gasLimit uint32 tipCap = b.tipCap if tipCap == nil { if !b.initialFetch.Load() { - err = errors.New("BlockHistoryEstimator has not finished the first gas estimation yet, likely because a failure on start") + err = pkgerrors.New("BlockHistoryEstimator has not finished the first gas estimation yet, likely because a failure on start") return } b.logger.Warnw("Failed to estimate gas price. This is likely because there aren't any valid transactions to estimate from."+ @@ -426,12 +426,12 @@ func (b *BlockHistoryEstimator) GetDynamicFee(_ context.Context, gasLimit uint32 // This shouldn't happen on EIP-1559 blocks, since if the tip cap // is set, Start must have succeeded and we would expect an initial // base fee to be set as well - err = errors.New("BlockHistoryEstimator: no value for latest block base fee; cannot estimate EIP-1559 base fee. Are you trying to run with EIP1559 enabled on a non-EIP1559 chain?") + err = pkgerrors.New("BlockHistoryEstimator: no value for latest block base fee; cannot estimate EIP-1559 base fee. Are you trying to run with EIP1559 enabled on a non-EIP1559 chain?") return } }) if !ok { - return fee, 0, errors.New("BlockHistoryEstimator is not started; cannot estimate gas") + return fee, 0, pkgerrors.New("BlockHistoryEstimator is not started; cannot estimate gas") } if err != nil { return fee, 0, err @@ -464,7 +464,7 @@ func calcFeeCap(latestAvailableBaseFeePerGas *assets.Wei, bufferBlocks int, tipC func (b *BlockHistoryEstimator) BumpDynamicFee(_ context.Context, originalFee DynamicFee, originalGasLimit uint32, maxGasPriceWei *assets.Wei, attempts []EvmPriorAttempt) (bumped DynamicFee, chainSpecificGasLimit uint32, err error) { if b.bhConfig.CheckInclusionBlocks() > 0 { if err = b.checkConnectivity(attempts); err != nil { - if errors.Is(err, commonfee.ErrConnectivity) { + if pkgerrors.Is(err, commonfee.ErrConnectivity) { b.logger.Criticalw(BumpingHaltedLabel, "err", err) b.SvcErrBuffer.Append(err) promBlockHistoryEstimatorConnectivityFailureCount.WithLabelValues(b.chainID.String(), "eip1559").Inc() @@ -531,7 +531,7 @@ func (b *BlockHistoryEstimator) Recalculate(head *evmtypes.Head) { } }) if err != nil { - if errors.Is(err, ErrNoSuitableTransactions) { + if pkgerrors.Is(err, ErrNoSuitableTransactions) { lggr.Debug("No suitable transactions, skipping") } else { lggr.Warnw("Cannot calculate percentile prices", "err", err) @@ -586,12 +586,12 @@ func (b *BlockHistoryEstimator) FetchBlocks(ctx context.Context, head *evmtypes. historySize := b.size if historySize <= 0 { - return errors.Errorf("BlockHistoryEstimator: history size must be > 0, got: %d", historySize) + return pkgerrors.Errorf("BlockHistoryEstimator: history size must be > 0, got: %d", historySize) } highestBlockToFetch := head.Number - blockDelay if highestBlockToFetch < 0 { - return errors.Errorf("BlockHistoryEstimator: cannot fetch, current block height %v is lower than EVM.RPCBlockQueryDelay=%v", head.Number, blockDelay) + return pkgerrors.Errorf("BlockHistoryEstimator: cannot fetch, current block height %v is lower than EVM.RPCBlockQueryDelay=%v", head.Number, blockDelay) } lowestBlockToFetch := head.Number - historySize - blockDelay + 1 if lowestBlockToFetch < 0 { @@ -639,7 +639,7 @@ func (b *BlockHistoryEstimator) FetchBlocks(ctx context.Context, head *evmtypes. for _, req := range reqs { result, err := req.Result, req.Error if err != nil { - if errors.Is(err, evmtypes.ErrMissingBlock) { + if pkgerrors.Is(err, evmtypes.ErrMissingBlock) { num := HexToInt64(req.Args[0]) missingBlocks = append(missingBlocks, num) lggr.Debugw( @@ -655,10 +655,10 @@ func (b *BlockHistoryEstimator) FetchBlocks(ctx context.Context, head *evmtypes. block, is := result.(*evmtypes.Block) if !is { - return errors.Errorf("expected result to be a %T, got %T", &evmtypes.Block{}, result) + return pkgerrors.Errorf("expected result to be a %T, got %T", &evmtypes.Block{}, result) } if block == nil { - return errors.New("invariant violation: got nil block") + return pkgerrors.New("invariant violation: got nil block") } if block.Hash == (common.Hash{}) { lggr.Warnw("Block was missing hash", "block", b, "headNum", head.Number, "blockNum", block.Number) @@ -714,26 +714,26 @@ func (b *BlockHistoryEstimator) batchFetch(ctx context.Context, reqs []rpc.Batch b.logger.Tracew(fmt.Sprintf("Batch fetching blocks %v thru %v", HexToInt64(reqs[i].Args[0]), HexToInt64(reqs[j-1].Args[0]))) err := b.ethClient.BatchCallContext(ctx, reqs[i:j]) - if errors.Is(err, context.DeadlineExceeded) { + if pkgerrors.Is(err, context.DeadlineExceeded) { // We ran out of time, return what we have b.logger.Warnf("Batch fetching timed out; loaded %d/%d results", i, len(reqs)) for k := i; k < len(reqs); k++ { if k < j { - reqs[k].Error = errors.Wrap(err, "request failed") + reqs[k].Error = pkgerrors.Wrap(err, "request failed") } else { - reqs[k].Error = errors.Wrap(err, "request skipped; previous request exceeded deadline") + reqs[k].Error = pkgerrors.Wrap(err, "request skipped; previous request exceeded deadline") } } return nil } else if err != nil { - return errors.Wrap(err, "BlockHistoryEstimator#fetchBlocks error fetching blocks with BatchCallContext") + return pkgerrors.Wrap(err, "BlockHistoryEstimator#fetchBlocks error fetching blocks with BatchCallContext") } } return nil } var ( - ErrNoSuitableTransactions = errors.New("no suitable transactions") + ErrNoSuitableTransactions = pkgerrors.New("no suitable transactions") ) func (b *BlockHistoryEstimator) calculatePercentilePrices(blocks []evmtypes.Block, percentile int, eip1559 bool, f func(gasPrices []*assets.Wei), f2 func(tipCaps []*assets.Wei)) (gasPrice, tipCap *assets.Wei, err error) { @@ -794,7 +794,7 @@ func (b *BlockHistoryEstimator) getPricesFromBlocks(blocks []evmtypes.Block, eip func verifyBlock(block evmtypes.Block, eip1559 bool) error { if eip1559 && block.BaseFeePerGas == nil { - return errors.New("EIP-1559 mode was enabled, but block was missing baseFeePerGas") + return pkgerrors.New("EIP-1559 mode was enabled, but block was missing baseFeePerGas") } return nil } diff --git a/core/chains/evm/gas/block_history_estimator_test.go b/core/chains/evm/gas/block_history_estimator_test.go index dfb4adf11ef..0cb160a172c 100644 --- a/core/chains/evm/gas/block_history_estimator_test.go +++ b/core/chains/evm/gas/block_history_estimator_test.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -143,7 +143,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { ethClient.On("BatchCallContext", mock.Anything, mock.MatchedBy(func(b []rpc.BatchElem) bool { return len(b) == 1 && b[0].Method == "eth_getBlockByNumber" && b[0].Args[0] == gas.Int64ToHex(41) && b[0].Args[1].(bool) && reflect.TypeOf(b[0].Result) == reflect.TypeOf(&evmtypes.Block{}) - })).Return(errors.Wrap(context.DeadlineExceeded, "some error message")).Once() + })).Return(pkgerrors.Wrap(context.DeadlineExceeded, "some error message")).Once() err := bhe.Start(testutils.Context(t)) require.NoError(t, err) @@ -177,7 +177,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { bhe := newBlockHistoryEstimator(t, ethClient, cfg, geCfg, bhCfg) - ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(nil, errors.New("something exploded")) + ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(nil, pkgerrors.New("something exploded")) err := bhe.Start(testutils.Context(t)) require.NoError(t, err) @@ -200,7 +200,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { h := &evmtypes.Head{Hash: utils.NewHash(), Number: 42, BaseFeePerGas: assets.NewWeiI(420)} ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(h, nil) - ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(errors.New("something went wrong")) + ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(pkgerrors.New("something went wrong")) err := bhe.Start(testutils.Context(t)) require.NoError(t, err) @@ -223,7 +223,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { h := &evmtypes.Head{Hash: utils.NewHash(), Number: 42, BaseFeePerGas: assets.NewWeiI(420)} ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(h, nil) - ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(errors.New("this error doesn't matter")) + ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(pkgerrors.New("this error doesn't matter")) ctx, cancel := context.WithCancel(testutils.Context(t)) cancel() @@ -239,7 +239,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { h := &evmtypes.Head{Hash: utils.NewHash(), Number: 42, BaseFeePerGas: assets.NewWeiI(420)} ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(h, nil) - ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(errors.New("this error doesn't matter")).Run(func(_ mock.Arguments) { + ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(pkgerrors.New("this error doesn't matter")).Run(func(_ mock.Arguments) { time.Sleep(gas.MaxStartTime + 1*time.Second) }) @@ -342,7 +342,7 @@ func TestBlockHistoryEstimator_FetchBlocks(t *testing.T) { bhe := newBlockHistoryEstimator(t, ethClient, cfg, geCfg, bhCfg) - ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(errors.New("something exploded")) + ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(pkgerrors.New("something exploded")) err := bhe.FetchBlocks(testutils.Context(t), cltest.Head(42)) require.Error(t, err) @@ -390,7 +390,7 @@ func TestBlockHistoryEstimator_FetchBlocks(t *testing.T) { elems := args.Get(1).([]rpc.BatchElem) elems[0].Result = &b43 // This errored block (42) will be ignored - elems[1].Error = errors.New("something went wrong") + elems[1].Error = pkgerrors.New("something went wrong") }) ethClient.On("BatchCallContext", mock.Anything, mock.MatchedBy(func(b []rpc.BatchElem) bool { return len(b) == 1 && @@ -2392,7 +2392,7 @@ func TestBlockHistoryEstimator_Bumps(t *testing.T) { _, _, err := bhe.BumpLegacyGas(testutils.Context(t), assets.NewWeiI(42), 100000, maxGasPrice, attempts) require.Error(t, err) - assert.True(t, errors.Is(err, commonfee.ErrConnectivity)) + assert.True(t, pkgerrors.Is(err, commonfee.ErrConnectivity)) assert.Contains(t, err.Error(), fmt.Sprintf("transaction %s has gas price of 1 kwei, which is above percentile=10%% (percentile price: 1 wei) for blocks 1 thru 1 (checking 1 blocks)", attempts[0].TxHash)) }) @@ -2505,7 +2505,7 @@ func TestBlockHistoryEstimator_Bumps(t *testing.T) { _, _, err := bhe.BumpDynamicFee(testutils.Context(t), originalFee, 100000, maxGasPrice, attempts) require.Error(t, err) - assert.True(t, errors.Is(err, commonfee.ErrConnectivity)) + assert.True(t, pkgerrors.Is(err, commonfee.ErrConnectivity)) assert.Contains(t, err.Error(), fmt.Sprintf("transaction %s has tip cap of 25 wei, which is above percentile=10%% (percentile tip cap: 1 wei) for blocks 1 thru 1 (checking 1 blocks)", attempts[0].TxHash)) }) diff --git a/core/chains/evm/gas/fixed_price_estimator.go b/core/chains/evm/gas/fixed_price_estimator.go index 4d9f45a1bd4..a69be3b0d05 100644 --- a/core/chains/evm/gas/fixed_price_estimator.go +++ b/core/chains/evm/gas/fixed_price_estimator.go @@ -3,7 +3,7 @@ package gas import ( "context" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" commonfee "github.com/smartcontractkit/chainlink/v2/common/fee" @@ -99,7 +99,7 @@ func (f *fixedPriceEstimator) GetDynamicFee(_ context.Context, originalGasLimit gasTipCap := f.config.TipCapDefault() if gasTipCap == nil { - return d, 0, errors.New("cannot calculate dynamic fee: EthGasTipCapDefault was not set") + return d, 0, pkgerrors.New("cannot calculate dynamic fee: EthGasTipCapDefault was not set") } chainSpecificGasLimit, err = commonfee.ApplyMultiplier(originalGasLimit, f.config.LimitMultiplier()) if err != nil { diff --git a/core/chains/evm/gas/models.go b/core/chains/evm/gas/models.go index 0b3ebdd0ee3..44e85af37ff 100644 --- a/core/chains/evm/gas/models.go +++ b/core/chains/evm/gas/models.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -187,11 +187,11 @@ func (e *WrappedEvmEstimator) Name() string { func (e *WrappedEvmEstimator) Start(ctx context.Context) error { return e.StartOnce(e.Name(), func() error { if err := e.EvmEstimator.Start(ctx); err != nil { - return errors.Wrap(err, "failed to start EVMEstimator") + return pkgerrors.Wrap(err, "failed to start EVMEstimator") } if e.l1Oracle != nil { if err := e.l1Oracle.Start(ctx); err != nil { - return errors.Wrap(err, "failed to start L1Oracle") + return pkgerrors.Wrap(err, "failed to start L1Oracle") } } return nil @@ -201,9 +201,9 @@ func (e *WrappedEvmEstimator) Close() error { return e.StopOnce(e.Name(), func() error { var errEVM, errOracle error - errEVM = errors.Wrap(e.EvmEstimator.Close(), "failed to stop EVMEstimator") + errEVM = pkgerrors.Wrap(e.EvmEstimator.Close(), "failed to stop EVMEstimator") if e.l1Oracle != nil { - errOracle = errors.Wrap(e.l1Oracle.Close(), "failed to stop L1Oracle") + errOracle = pkgerrors.Wrap(e.l1Oracle.Close(), "failed to stop L1Oracle") } if errEVM != nil { @@ -277,7 +277,7 @@ func (e *WrappedEvmEstimator) GetMaxCost(ctx context.Context, amount assets.Eth, func (e *WrappedEvmEstimator) BumpFee(ctx context.Context, originalFee EvmFee, feeLimit uint32, maxFeePrice *assets.Wei, attempts []EvmPriorAttempt) (bumpedFee EvmFee, chainSpecificFeeLimit uint32, err error) { // validate only 1 fee type is present if (!originalFee.ValidDynamic() && originalFee.Legacy == nil) || (originalFee.ValidDynamic() && originalFee.Legacy != nil) { - err = errors.New("only one dynamic or legacy fee can be defined") + err = pkgerrors.New("only one dynamic or legacy fee can be defined") return } @@ -377,13 +377,13 @@ func bumpGasPrice(cfg bumpConfig, lggr logger.SugaredLogger, currentGasPrice, or bumpedGasPrice = maxBumpedFee(lggr, currentGasPrice, bumpedGasPrice, maxGasPrice, "gas price") if bumpedGasPrice.Cmp(maxGasPrice) > 0 { - return maxGasPrice, errors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped gas price of %s would exceed configured max gas price of %s (original price was %s). %s", + return maxGasPrice, pkgerrors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped gas price of %s would exceed configured max gas price of %s (original price was %s). %s", bumpedGasPrice.String(), maxGasPrice, originalGasPrice.String(), label.NodeConnectivityProblemWarning) } else if bumpedGasPrice.Cmp(originalGasPrice) == 0 { // NOTE: This really shouldn't happen since we enforce minimums for // EVM.GasEstimator.BumpPercent and EVM.GasEstimator.BumpMin in the config validation, // but it's here anyway for a "belts and braces" approach - return bumpedGasPrice, errors.Wrapf(commonfee.ErrBump, "bumped gas price of %s is equal to original gas price of %s."+ + return bumpedGasPrice, pkgerrors.Wrapf(commonfee.ErrBump, "bumped gas price of %s is equal to original gas price of %s."+ " ACTION REQUIRED: This is a configuration error, you must increase either "+ "EVM.GasEstimator.BumpPercent or EVM.GasEstimator.BumpMin", bumpedGasPrice.String(), originalGasPrice.String()) } @@ -419,13 +419,13 @@ func bumpDynamicFee(cfg bumpConfig, feeCapBufferBlocks uint16, lggr logger.Sugar bumpedTipCap = maxBumpedFee(lggr, currentTipCap, bumpedTipCap, maxGasPrice, "tip cap") if bumpedTipCap.Cmp(maxGasPrice) > 0 { - return bumpedFee, errors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped tip cap of %s would exceed configured max gas price of %s (original fee: tip cap %s, fee cap %s). %s", + return bumpedFee, pkgerrors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped tip cap of %s would exceed configured max gas price of %s (original fee: tip cap %s, fee cap %s). %s", bumpedTipCap.String(), maxGasPrice, originalFee.TipCap.String(), originalFee.FeeCap.String(), label.NodeConnectivityProblemWarning) } else if bumpedTipCap.Cmp(originalFee.TipCap) <= 0 { // NOTE: This really shouldn't happen since we enforce minimums for // EVM.GasEstimator.BumpPercent and EVM.GasEstimator.BumpMin in the config validation, // but it's here anyway for a "belts and braces" approach - return bumpedFee, errors.Wrapf(commonfee.ErrBump, "bumped gas tip cap of %s is less than or equal to original gas tip cap of %s."+ + return bumpedFee, pkgerrors.Wrapf(commonfee.ErrBump, "bumped gas tip cap of %s is less than or equal to original gas tip cap of %s."+ " ACTION REQUIRED: This is a configuration error, you must increase either "+ "EVM.GasEstimator.BumpPercent or EVM.GasEstimator.BumpMin", bumpedTipCap.String(), originalFee.TipCap.String()) } @@ -445,7 +445,7 @@ func bumpDynamicFee(cfg bumpConfig, feeCapBufferBlocks uint16, lggr logger.Sugar } if bumpedFeeCap.Cmp(maxGasPrice) > 0 { - return bumpedFee, errors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped fee cap of %s would exceed configured max gas price of %s (original fee: tip cap %s, fee cap %s). %s", + return bumpedFee, pkgerrors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped fee cap of %s would exceed configured max gas price of %s (original fee: tip cap %s, fee cap %s). %s", bumpedFeeCap.String(), maxGasPrice, originalFee.TipCap.String(), originalFee.FeeCap.String(), label.NodeConnectivityProblemWarning) } diff --git a/core/chains/evm/gas/models_test.go b/core/chains/evm/gas/models_test.go index 95a7a471eba..9c0e63a602b 100644 --- a/core/chains/evm/gas/models_test.go +++ b/core/chains/evm/gas/models_test.go @@ -4,7 +4,7 @@ import ( "math/big" "testing" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -201,9 +201,9 @@ func TestWrappedEvmEstimator(t *testing.T) { oracle := rollupMocks.NewL1Oracle(t) evmEstimatorKey := "evm" - evmEstimatorError := errors.New("evm error") + evmEstimatorError := pkgerrors.New("evm error") oracleKey := "oracle" - oracleError := errors.New("oracle error") + oracleError := pkgerrors.New("oracle error") evmEstimator.On("HealthReport").Return(map[string]error{evmEstimatorKey: evmEstimatorError}).Twice() oracle.On("HealthReport").Return(map[string]error{oracleKey: oracleError}).Once() @@ -211,14 +211,14 @@ func TestWrappedEvmEstimator(t *testing.T) { estimator := gas.NewWrappedEvmEstimator(lggr, getEst, false, nil) report := estimator.HealthReport() - require.True(t, errors.Is(report[evmEstimatorKey], evmEstimatorError)) + require.True(t, pkgerrors.Is(report[evmEstimatorKey], evmEstimatorError)) require.Nil(t, report[oracleKey]) require.NotNil(t, report[mockEstimatorName]) estimator = gas.NewWrappedEvmEstimator(lggr, getEst, false, oracle) report = estimator.HealthReport() - require.True(t, errors.Is(report[evmEstimatorKey], evmEstimatorError)) - require.True(t, errors.Is(report[oracleKey], oracleError)) + require.True(t, pkgerrors.Is(report[evmEstimatorKey], evmEstimatorError)) + require.True(t, pkgerrors.Is(report[oracleKey], oracleError)) require.NotNil(t, report[mockEstimatorName]) }) } diff --git a/core/chains/evm/gas/suggested_price_estimator.go b/core/chains/evm/gas/suggested_price_estimator.go index fe6483f40f3..d58a1155b91 100644 --- a/core/chains/evm/gas/suggested_price_estimator.go +++ b/core/chains/evm/gas/suggested_price_estimator.go @@ -8,7 +8,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -138,14 +138,14 @@ func (o *SuggestedPriceEstimator) forceRefresh(ctx context.Context) (err error) select { case o.chForceRefetch <- ch: case <-o.chStop: - return errors.New("estimator stopped") + return pkgerrors.New("estimator stopped") case <-ctx.Done(): return ctx.Err() } select { case <-ch: case <-o.chStop: - return errors.New("estimator stopped") + return pkgerrors.New("estimator stopped") case <-ctx.Done(): return ctx.Err() } @@ -155,12 +155,12 @@ func (o *SuggestedPriceEstimator) forceRefresh(ctx context.Context) (err error) func (o *SuggestedPriceEstimator) OnNewLongestChain(context.Context, *evmtypes.Head) {} func (*SuggestedPriceEstimator) GetDynamicFee(_ context.Context, _ uint32, _ *assets.Wei) (fee DynamicFee, chainSpecificGasLimit uint32, err error) { - err = errors.New("dynamic fees are not implemented for this estimator") + err = pkgerrors.New("dynamic fees are not implemented for this estimator") return } func (*SuggestedPriceEstimator) BumpDynamicFee(_ context.Context, _ DynamicFee, _ uint32, _ *assets.Wei, _ []EvmPriorAttempt) (bumped DynamicFee, chainSpecificGasLimit uint32, err error) { - err = errors.New("dynamic fees are not implemented for this estimator") + err = pkgerrors.New("dynamic fees are not implemented for this estimator") return } @@ -171,19 +171,19 @@ func (o *SuggestedPriceEstimator) GetLegacyGas(ctx context.Context, _ []byte, Ga err = o.forceRefresh(ctx) } if gasPrice = o.getGasPrice(); gasPrice == nil { - err = errors.New("failed to estimate gas; gas price not set") + err = pkgerrors.New("failed to estimate gas; gas price not set") return } o.logger.Debugw("GetLegacyGas", "GasPrice", gasPrice, "GasLimit", GasLimit) }) if !ok { - return nil, 0, errors.New("estimator is not started") + return nil, 0, pkgerrors.New("estimator is not started") } else if err != nil { return } // For L2 chains, submitting a transaction that is not priced high enough will cause the call to fail, so if the cap is lower than the RPC suggested gas price, this transaction cannot succeed if gasPrice != nil && gasPrice.Cmp(maxGasPriceWei) > 0 { - return nil, 0, errors.Errorf("estimated gas price: %s is greater than the maximum gas price configured: %s", gasPrice.String(), maxGasPriceWei.String()) + return nil, 0, pkgerrors.Errorf("estimated gas price: %s is greater than the maximum gas price configured: %s", gasPrice.String(), maxGasPriceWei.String()) } return } @@ -203,18 +203,18 @@ func (o *SuggestedPriceEstimator) BumpLegacyGas(ctx context.Context, originalFee } err = o.forceRefresh(ctx) if newGasPrice = o.getGasPrice(); newGasPrice == nil { - err = errors.New("failed to refresh and return gas; gas price not set") + err = pkgerrors.New("failed to refresh and return gas; gas price not set") return } o.logger.Debugw("GasPrice", newGasPrice, "GasLimit", feeLimit) }) if !ok { - return nil, 0, errors.New("estimator is not started") + return nil, 0, pkgerrors.New("estimator is not started") } else if err != nil { return } if newGasPrice != nil && newGasPrice.Cmp(maxGasPriceWei) > 0 { - return nil, 0, errors.Errorf("estimated gas price: %s is greater than the maximum gas price configured: %s", newGasPrice.String(), maxGasPriceWei.String()) + return nil, 0, pkgerrors.Errorf("estimated gas price: %s is greater than the maximum gas price configured: %s", newGasPrice.String(), maxGasPriceWei.String()) } // Add a buffer on top of the gas price returned by the RPC. // Bump logic when using the suggested gas price from an RPC is realistically only needed when there is increased volatility in gas price. diff --git a/core/chains/evm/gas/suggested_price_estimator_test.go b/core/chains/evm/gas/suggested_price_estimator_test.go index 9006554564d..c09582774b8 100644 --- a/core/chains/evm/gas/suggested_price_estimator_test.go +++ b/core/chains/evm/gas/suggested_price_estimator_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -87,7 +87,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { client := mocks.NewRPCClient(t) o := gas.NewSuggestedPriceEstimator(logger.Test(t), client, cfg) - client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(errors.New("kaboom")) + client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(pkgerrors.New("kaboom")) servicetest.RunHealthy(t, o) @@ -203,7 +203,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { client := mocks.NewRPCClient(t) o := gas.NewSuggestedPriceEstimator(logger.Test(t), client, cfg) - client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(errors.New("kaboom")) + client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(pkgerrors.New("kaboom")) servicetest.RunHealthy(t, o) @@ -219,7 +219,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { res := args.Get(1).(*hexutil.Big) (*big.Int)(res).SetInt64(40) }).Once() - client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(errors.New("kaboom")) + client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(pkgerrors.New("kaboom")) servicetest.RunHealthy(t, o) diff --git a/core/chains/evm/headtracker/head_listener_test.go b/core/chains/evm/headtracker/head_listener_test.go index 3ba9c0863da..e5131aca422 100644 --- a/core/chains/evm/headtracker/head_listener_test.go +++ b/core/chains/evm/headtracker/head_listener_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -155,7 +155,7 @@ func Test_HeadListener_SubscriptionErr(t *testing.T) { closeErr bool }{ {"nil error", nil, false}, - {"socket error", errors.New("close 1006 (abnormal closure): unexpected EOF"), false}, + {"socket error", pkgerrors.New("close 1006 (abnormal closure): unexpected EOF"), false}, {"close Err channel", nil, true}, } diff --git a/core/chains/evm/headtracker/orm.go b/core/chains/evm/headtracker/orm.go index 859f6764b63..a1957388b9b 100644 --- a/core/chains/evm/headtracker/orm.go +++ b/core/chains/evm/headtracker/orm.go @@ -6,7 +6,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/jmoiron/sqlx" @@ -47,7 +47,7 @@ func (orm *orm) IdempotentInsertHead(ctx context.Context, head *evmtypes.Head) e :hash, :number, :parent_hash, :created_at, :timestamp, :l1_block_number, :evm_chain_id, :base_fee_per_gas) ON CONFLICT (evm_chain_id, hash) DO NOTHING` err := q.ExecQNamed(query, head) - return errors.Wrap(err, "IdempotentInsertHead failed to insert head") + return pkgerrors.Wrap(err, "IdempotentInsertHead failed to insert head") } func (orm *orm) TrimOldHeads(ctx context.Context, n uint) (err error) { @@ -69,17 +69,17 @@ func (orm *orm) LatestHead(ctx context.Context) (head *evmtypes.Head, err error) head = new(evmtypes.Head) q := orm.q.WithOpts(pg.WithParentCtx(ctx)) err = q.Get(head, `SELECT * FROM evm.heads WHERE evm_chain_id = $1 ORDER BY number DESC, created_at DESC, id DESC LIMIT 1`, orm.chainID) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } - err = errors.Wrap(err, "LatestHead failed") + err = pkgerrors.Wrap(err, "LatestHead failed") return } func (orm *orm) LatestHeads(ctx context.Context, limit uint) (heads []*evmtypes.Head, err error) { q := orm.q.WithOpts(pg.WithParentCtx(ctx)) err = q.Select(&heads, `SELECT * FROM evm.heads WHERE evm_chain_id = $1 ORDER BY number DESC, created_at DESC, id DESC LIMIT $2`, orm.chainID, limit) - err = errors.Wrap(err, "LatestHeads failed") + err = pkgerrors.Wrap(err, "LatestHeads failed") return } @@ -87,7 +87,7 @@ func (orm *orm) HeadByHash(ctx context.Context, hash common.Hash) (head *evmtype q := orm.q.WithOpts(pg.WithParentCtx(ctx)) head = new(evmtypes.Head) err = q.Get(head, `SELECT * FROM evm.heads WHERE evm_chain_id = $1 AND hash = $2`, orm.chainID, hash) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } return head, err diff --git a/core/chains/evm/log/broadcaster.go b/core/chains/evm/log/broadcaster.go index 8321dd30bfe..c4db2a4826c 100644 --- a/core/chains/evm/log/broadcaster.go +++ b/core/chains/evm/log/broadcaster.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -773,13 +773,13 @@ func (n *NullBroadcaster) TrackedAddressesCount() uint32 { return 0 } func (n *NullBroadcaster) WasAlreadyConsumed(lb Broadcast, qopts ...pg.QOpt) (bool, error) { - return false, errors.New(n.ErrMsg) + return false, pkgerrors.New(n.ErrMsg) } func (n *NullBroadcaster) MarkConsumed(lb Broadcast, qopts ...pg.QOpt) error { - return errors.New(n.ErrMsg) + return pkgerrors.New(n.ErrMsg) } func (n *NullBroadcaster) MarkManyConsumed(lbs []Broadcast, qopts ...pg.QOpt) error { - return errors.New(n.ErrMsg) + return pkgerrors.New(n.ErrMsg) } func (n *NullBroadcaster) AddDependents(int) {} diff --git a/core/chains/evm/log/orm.go b/core/chains/evm/log/orm.go index 51ed9f2f132..25012d5c8e0 100644 --- a/core/chains/evm/log/orm.go +++ b/core/chains/evm/log/orm.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/jmoiron/sqlx" @@ -75,7 +75,7 @@ func (o *orm) WasBroadcastConsumed(blockHash common.Hash, logIndex uint, jobID i } q := o.q.WithOpts(qopts...) err = q.Get(&consumed, query, args...) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return false, nil } return consumed, err @@ -91,7 +91,7 @@ func (o *orm) FindBroadcasts(fromBlockNum int64, toBlockNum int64) ([]LogBroadca ` err := o.q.Select(&broadcasts, query, fromBlockNum, toBlockNum, o.evmChainID) if err != nil { - return nil, errors.Wrap(err, "failed to find log broadcasts") + return nil, pkgerrors.Wrap(err, "failed to find log broadcasts") } return broadcasts, err } @@ -102,7 +102,7 @@ func (o *orm) CreateBroadcast(blockHash common.Hash, blockNumber uint64, logInde INSERT INTO log_broadcasts (block_hash, block_number, log_index, job_id, created_at, updated_at, consumed, evm_chain_id) VALUES ($1, $2, $3, $4, NOW(), NOW(), false, $5) `, blockHash, blockNumber, logIndex, jobID, o.evmChainID) - return errors.Wrap(err, "failed to create log broadcast") + return pkgerrors.Wrap(err, "failed to create log broadcast") } func (o *orm) MarkBroadcastConsumed(blockHash common.Hash, blockNumber uint64, logIndex uint, jobID int32, qopts ...pg.QOpt) error { @@ -113,7 +113,7 @@ func (o *orm) MarkBroadcastConsumed(blockHash common.Hash, blockNumber uint64, l ON CONFLICT (job_id, block_hash, log_index, evm_chain_id) DO UPDATE SET consumed = true, updated_at = NOW() `, blockHash, blockNumber, logIndex, jobID, o.evmChainID) - return errors.Wrap(err, "failed to mark log broadcast as consumed") + return pkgerrors.Wrap(err, "failed to mark log broadcast as consumed") } // MarkBroadcastsConsumed marks many broadcasts as consumed. @@ -150,7 +150,7 @@ SET consumed = true, updated_at = NOW(); } q := o.q.WithOpts(qopts...) _, err := q.NamedExec(query, inputs) - return errors.Wrap(err, "mark broadcasts consumed") + return pkgerrors.Wrap(err, "mark broadcasts consumed") } // MarkBroadcastsUnconsumed implements the ORM interface. @@ -162,7 +162,7 @@ func (o *orm) MarkBroadcastsUnconsumed(fromBlock int64, qopts ...pg.QOpt) error WHERE block_number >= $1 AND evm_chain_id = $2 `, fromBlock, o.evmChainID) - return errors.Wrap(err, "failed to mark broadcasts unconsumed") + return pkgerrors.Wrap(err, "failed to mark broadcasts unconsumed") } func (o *orm) Reinitialize(qopts ...pg.QOpt) (*int64, error) { @@ -201,7 +201,7 @@ func (o *orm) SetPendingMinBlock(blockNumber *int64, qopts ...pg.QOpt) error { INSERT INTO log_broadcasts_pending (evm_chain_id, block_number, created_at, updated_at) VALUES ($1, $2, NOW(), NOW()) ON CONFLICT (evm_chain_id) DO UPDATE SET block_number = $3, updated_at = NOW() `, o.evmChainID, blockNumber, blockNumber) - return errors.Wrap(err, "failed to set pending broadcast block number") + return pkgerrors.Wrap(err, "failed to set pending broadcast block number") } func (o *orm) GetPendingMinBlock(qopts ...pg.QOpt) (*int64, error) { @@ -210,10 +210,10 @@ func (o *orm) GetPendingMinBlock(qopts ...pg.QOpt) (*int64, error) { err := q.Get(&blockNumber, ` SELECT block_number FROM log_broadcasts_pending WHERE evm_chain_id = $1 `, o.evmChainID) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } else if err != nil { - return nil, errors.Wrap(err, "failed to get broadcasts pending number") + return nil, pkgerrors.Wrap(err, "failed to get broadcasts pending number") } return blockNumber, nil } @@ -227,10 +227,10 @@ func (o *orm) getUnconsumedMinBlock(qopts ...pg.QOpt) (*int64, error) { AND consumed = false AND block_number IS NOT NULL `, o.evmChainID) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } else if err != nil { - return nil, errors.Wrap(err, "failed to get unconsumed broadcasts min block number") + return nil, pkgerrors.Wrap(err, "failed to get unconsumed broadcasts min block number") } return blockNumber, nil } @@ -243,7 +243,7 @@ func (o *orm) removeUnconsumed(qopts ...pg.QOpt) error { AND consumed = false AND block_number IS NOT NULL `, o.evmChainID) - return errors.Wrap(err, "failed to delete unconsumed broadcasts") + return pkgerrors.Wrap(err, "failed to delete unconsumed broadcasts") } // LogBroadcast - data from log_broadcasts table columns diff --git a/core/chains/evm/log/registrations.go b/core/chains/evm/log/registrations.go index 346a6776e86..1bb6c8c59c0 100644 --- a/core/chains/evm/log/registrations.go +++ b/core/chains/evm/log/registrations.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" @@ -119,12 +119,12 @@ func (r *registrations) handlersWithGreaterConfs(confs uint32) (handlersWithGrea // maps modified are only used for checks func (r *registrations) checkAddSubscriber(sub *subscriber) error { if sub.opts.MinIncomingConfirmations <= 0 { - return errors.Errorf("LogBroadcaster requires that MinIncomingConfirmations must be at least 1 (got %v). Logs must have been confirmed in at least 1 block, it does not support reading logs from the mempool before they have been mined", sub.opts.MinIncomingConfirmations) + return pkgerrors.Errorf("LogBroadcaster requires that MinIncomingConfirmations must be at least 1 (got %v). Logs must have been confirmed in at least 1 block, it does not support reading logs from the mempool before they have been mined", sub.opts.MinIncomingConfirmations) } jobID := sub.listener.JobID() if _, exists := r.registeredSubs[sub]; exists { - return errors.Errorf("Cannot add subscriber %p for job ID %v: already added", sub, jobID) + return pkgerrors.Errorf("Cannot add subscriber %p for job ID %v: already added", sub, jobID) } r.registeredSubs[sub] = struct{}{} addrs, exists := r.jobIDAddrs[jobID] @@ -132,7 +132,7 @@ func (r *registrations) checkAddSubscriber(sub *subscriber) error { r.jobIDAddrs[jobID] = make(map[common.Address]struct{}) } if _, exists := addrs[sub.opts.Contract]; exists { - return errors.Errorf("Cannot add subscriber %p: only one subscription is allowed per jobID/contract address. There is already a subscription with job ID %v listening on %s", sub, jobID, sub.opts.Contract.Hex()) + return pkgerrors.Errorf("Cannot add subscriber %p: only one subscription is allowed per jobID/contract address. There is already a subscription with job ID %v listening on %s", sub, jobID, sub.opts.Contract.Hex()) } r.jobIDAddrs[jobID][sub.opts.Contract] = struct{}{} return nil @@ -165,16 +165,16 @@ func (r *registrations) removeSubscriber(sub *subscriber) (needsResubscribe bool func (r *registrations) checkRemoveSubscriber(sub *subscriber) error { jobID := sub.listener.JobID() if _, exists := r.registeredSubs[sub]; !exists { - return errors.Errorf("Cannot remove subscriber %p for job ID %v: not registered", sub, jobID) + return pkgerrors.Errorf("Cannot remove subscriber %p for job ID %v: not registered", sub, jobID) } delete(r.registeredSubs, sub) addrs, exists := r.jobIDAddrs[jobID] if !exists { - return errors.Errorf("Cannot remove subscriber %p: jobIDAddrs was missing job ID %v", sub, jobID) + return pkgerrors.Errorf("Cannot remove subscriber %p: jobIDAddrs was missing job ID %v", sub, jobID) } _, exists = addrs[sub.opts.Contract] if !exists { - return errors.Errorf("Cannot remove subscriber %p: jobIDAddrs was missing address %s", sub, sub.opts.Contract.Hex()) + return pkgerrors.Errorf("Cannot remove subscriber %p: jobIDAddrs was missing address %s", sub, sub.opts.Contract.Hex()) } delete(r.jobIDAddrs[jobID], sub.opts.Contract) if len(r.jobIDAddrs[jobID]) == 0 { diff --git a/core/chains/evm/logpoller/disabled.go b/core/chains/evm/logpoller/disabled.go index 05d591042f4..8d92b8d29f6 100644 --- a/core/chains/evm/logpoller/disabled.go +++ b/core/chains/evm/logpoller/disabled.go @@ -5,13 +5,13 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/services/pg" ) var ( - ErrDisabled = errors.New("log poller disabled") + ErrDisabled = pkgerrors.New("log poller disabled") LogPollerDisabled LogPoller = disabled{} ) diff --git a/core/chains/evm/logpoller/helper_test.go b/core/chains/evm/logpoller/helper_test.go index cb0fbd247fc..3215a7ec20c 100644 --- a/core/chains/evm/logpoller/helper_test.go +++ b/core/chains/evm/logpoller/helper_test.go @@ -15,7 +15,7 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/ethdb" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -99,7 +99,7 @@ func (th *TestHarness) PollAndSaveLogs(ctx context.Context, currentBlockNumber i func (th *TestHarness) assertDontHave(t *testing.T, start, end int) { for i := start; i < end; i++ { _, err := th.ORM.SelectBlockByNumber(int64(i)) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) } } diff --git a/core/chains/evm/logpoller/log_poller.go b/core/chains/evm/logpoller/log_poller.go index ba617a2178b..a19bbfda7f1 100644 --- a/core/chains/evm/logpoller/log_poller.go +++ b/core/chains/evm/logpoller/log_poller.go @@ -17,7 +17,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "golang.org/x/exp/maps" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -89,9 +89,9 @@ type Client interface { var ( _ LogPollerTest = &logPoller{} - ErrReplayRequestAborted = errors.New("aborted, replay request cancelled") - ErrReplayInProgress = errors.New("replay request cancelled, but replay is already in progress") - ErrLogPollerShutdown = errors.New("replay aborted due to log poller shutdown") + ErrReplayRequestAborted = pkgerrors.New("aborted, replay request cancelled") + ErrReplayInProgress = pkgerrors.New("replay request cancelled, but replay is already in progress") + ErrLogPollerShutdown = pkgerrors.New("replay aborted due to log poller shutdown") ) type logPoller struct { @@ -226,20 +226,20 @@ func (filter *Filter) Contains(other *Filter) bool { // Warnings/debug information is keyed by filter name. func (lp *logPoller) RegisterFilter(filter Filter, qopts ...pg.QOpt) error { if len(filter.Addresses) == 0 { - return errors.Errorf("at least one address must be specified") + return pkgerrors.Errorf("at least one address must be specified") } if len(filter.EventSigs) == 0 { - return errors.Errorf("at least one event must be specified") + return pkgerrors.Errorf("at least one event must be specified") } for _, eventSig := range filter.EventSigs { if eventSig == [common.HashLength]byte{} { - return errors.Errorf("empty event sig") + return pkgerrors.Errorf("empty event sig") } } for _, addr := range filter.Addresses { if addr == [common.AddressLength]byte{} { - return errors.Errorf("empty address") + return pkgerrors.Errorf("empty address") } } @@ -256,7 +256,7 @@ func (lp *logPoller) RegisterFilter(filter Filter, qopts ...pg.QOpt) error { } if err := lp.orm.InsertFilter(filter, qopts...); err != nil { - return errors.Wrap(err, "error inserting filter") + return pkgerrors.Wrap(err, "error inserting filter") } lp.filters[filter.Name] = filter lp.filterDirty = true @@ -277,7 +277,7 @@ func (lp *logPoller) UnregisterFilter(name string, qopts ...pg.QOpt) error { } if err := lp.orm.DeleteFilter(name, qopts...); err != nil { - return errors.Wrap(err, "error deleting filter") + return pkgerrors.Wrap(err, "error deleting filter") } delete(lp.filters, name) lp.filterDirty = true @@ -352,13 +352,13 @@ func (lp *logPoller) Replay(ctx context.Context, fromBlock int64) error { return err } if fromBlock < 1 || fromBlock > latest.Number { - return errors.Errorf("Invalid replay block number %v, acceptable range [1, %v]", fromBlock, latest.Number) + return pkgerrors.Errorf("Invalid replay block number %v, acceptable range [1, %v]", fromBlock, latest.Number) } // Block until replay notification accepted or cancelled. select { case lp.replayStart <- fromBlock: case <-ctx.Done(): - return errors.Wrap(ErrReplayRequestAborted, ctx.Err().Error()) + return pkgerrors.Wrap(ErrReplayRequestAborted, ctx.Err().Error()) } // Block until replay complete or cancelled. select { @@ -423,7 +423,7 @@ func (lp *logPoller) HealthReport() map[string]error { func (lp *logPoller) GetReplayFromBlock(ctx context.Context, requested int64) (int64, error) { lastProcessed, err := lp.orm.SelectLatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if !errors.Is(err, sql.ErrNoRows) { + if !pkgerrors.Is(err, sql.ErrNoRows) { // Real DB error return 0, err } @@ -449,7 +449,7 @@ func (lp *logPoller) run() { filters, err := lp.orm.LoadFilters(pg.WithParentCtx(lp.ctx)) if err != nil { - return errors.Wrapf(err, "Failed to load initial filters from db, retrying") + return pkgerrors.Wrapf(err, "Failed to load initial filters from db, retrying") } lp.filters = filters @@ -503,7 +503,7 @@ func (lp *logPoller) run() { var start int64 lastProcessed, err := lp.orm.SelectLatestBlock(pg.WithParentCtx(lp.ctx)) if err != nil { - if !errors.Is(err, sql.ErrNoRows) { + if !pkgerrors.Is(err, sql.ErrNoRows) { // Assume transient db reading issue, retry forever. lp.lggr.Errorw("unable to get starting block", "err", err) continue @@ -586,7 +586,7 @@ func (lp *logPoller) BackupPollAndSaveLogs(ctx context.Context, backupPollerBloc if lp.backupPollerNextBlock == 0 { lastProcessed, err := lp.orm.SelectLatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { lp.lggr.Warnw("Backup log poller ran before first successful log poller run, skipping") } else { lp.lggr.Errorw("Backup log poller unable to get starting block", "err", err) @@ -687,7 +687,7 @@ func (lp *logPoller) backfill(ctx context.Context, start, end int64) error { gethLogs, err := lp.ec.FilterLogs(ctx, lp.Filter(big.NewInt(from), big.NewInt(to), nil)) if err != nil { var rpcErr client.JsonError - if errors.As(err, &rpcErr) { + if pkgerrors.As(err, &rpcErr) { if rpcErr.Code != jsonRpcLimitExceeded { lp.lggr.Errorw("Unable to query for logs", "err", err, "from", from, "to", to) return err @@ -740,20 +740,20 @@ func (lp *logPoller) getCurrentBlockMaybeHandleReorg(ctx context.Context, curren // Additional sanity checks, don't necessarily trust the RPC. if currentBlock == nil { lp.lggr.Errorf("Unexpected nil block from RPC", "currentBlockNumber", currentBlockNumber) - return nil, errors.Errorf("Got nil block for %d", currentBlockNumber) + return nil, pkgerrors.Errorf("Got nil block for %d", currentBlockNumber) } if currentBlock.Number != currentBlockNumber { lp.lggr.Warnw("Unable to get currentBlock, rpc returned incorrect block", "currentBlockNumber", currentBlockNumber, "got", currentBlock.Number) - return nil, errors.Errorf("Block mismatch have %d want %d", currentBlock.Number, currentBlockNumber) + return nil, pkgerrors.Errorf("Block mismatch have %d want %d", currentBlock.Number, currentBlockNumber) } } // Does this currentBlock point to the same parent that we have saved? // If not, there was a reorg, so we need to rewind. expectedParent, err1 := lp.orm.SelectBlockByNumber(currentBlockNumber-1, pg.WithParentCtx(ctx)) - if err1 != nil && !errors.Is(err1, sql.ErrNoRows) { + if err1 != nil && !pkgerrors.Is(err1, sql.ErrNoRows) { // If err is not a 'no rows' error, assume transient db issue and retry lp.lggr.Warnw("Unable to read latestBlockNumber currentBlock saved", "err", err1, "currentBlockNumber", currentBlockNumber) - return nil, errors.New("Unable to read latestBlockNumber currentBlock saved") + return nil, pkgerrors.New("Unable to read latestBlockNumber currentBlock saved") } // We will not have the previous currentBlock on initial poll. havePreviousBlock := err1 == nil @@ -769,7 +769,7 @@ func (lp *logPoller) getCurrentBlockMaybeHandleReorg(ctx context.Context, curren blockAfterLCA, err2 := lp.findBlockAfterLCA(ctx, currentBlock, expectedParent.FinalizedBlockNumber) if err2 != nil { lp.lggr.Warnw("Unable to find LCA after reorg, retrying", "err", err2) - return nil, errors.New("Unable to find LCA after reorg, retrying") + return nil, pkgerrors.New("Unable to find LCA after reorg, retrying") } lp.lggr.Infow("Reorg detected", "blockAfterLCA", blockAfterLCA.Number, "currentBlockNumber", currentBlockNumber) @@ -950,7 +950,7 @@ func (lp *logPoller) findBlockAfterLCA(ctx context.Context, current *evmtypes.He } } lp.lggr.Criticalw("Reorg greater than finality depth detected", "finalityTag", lp.useFinalityTag, "current", current.Number, "latestFinalized", latestFinalizedBlockNumber) - rerr := errors.New("Reorg greater than finality depth") + rerr := pkgerrors.New("Reorg greater than finality depth") lp.SvcErrBuffer.Append(rerr) return nil, rerr } @@ -1133,7 +1133,7 @@ func (lp *logPoller) GetBlocksRange(ctx context.Context, numbers []uint64, qopts } if len(blocksNotFound) > 0 { - return nil, errors.Errorf("blocks were not found in db or RPC call: %v", blocksNotFound) + return nil, pkgerrors.Errorf("blocks were not found in db or RPC call: %v", blocksNotFound) } return blocks, nil @@ -1205,16 +1205,16 @@ func (lp *logPoller) batchFetchBlocks(ctx context.Context, blocksRequested []str block, is := r.Result.(*evmtypes.Head) if !is { - return nil, errors.Errorf("expected result to be a %T, got %T", &evmtypes.Head{}, r.Result) + return nil, pkgerrors.Errorf("expected result to be a %T, got %T", &evmtypes.Head{}, r.Result) } if block == nil { - return nil, errors.New("invariant violation: got nil block") + return nil, pkgerrors.New("invariant violation: got nil block") } if block.Hash == (common.Hash{}) { - return nil, errors.Errorf("missing block hash for block number: %d", block.Number) + return nil, pkgerrors.Errorf("missing block hash for block number: %d", block.Number) } if block.Number < 0 { - return nil, errors.Errorf("expected block number to be >= to 0, got %d", block.Number) + return nil, pkgerrors.Errorf("expected block number to be >= to 0, got %d", block.Number) } blocks = append(blocks, block) } diff --git a/core/chains/evm/logpoller/log_poller_internal_test.go b/core/chains/evm/logpoller/log_poller_internal_test.go index 124c16d26f3..0bde65e5556 100644 --- a/core/chains/evm/logpoller/log_poller_internal_test.go +++ b/core/chains/evm/logpoller/log_poller_internal_test.go @@ -14,7 +14,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -286,7 +286,7 @@ func TestLogPoller_Replay(t *testing.T) { // Replay() should return error code received from replayComplete t.Run("returns error code on replay complete", func(t *testing.T) { ctx := testutils.Context(t) - anyErr := errors.New("any error") + anyErr := pkgerrors.New("any error") done := make(chan struct{}) go func() { defer close(done) @@ -412,7 +412,7 @@ func TestLogPoller_Replay(t *testing.T) { t.Cleanup(lp.reset) servicetest.Run(t, lp) - anyErr := errors.New("async error") + anyErr := pkgerrors.New("async error") observedLogs.TakeAll() lp.ReplayAsync(4) diff --git a/core/chains/evm/logpoller/orm.go b/core/chains/evm/logpoller/orm.go index c0e870870e6..f61845b870f 100644 --- a/core/chains/evm/logpoller/orm.go +++ b/core/chains/evm/logpoller/orm.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -361,7 +361,7 @@ func (o *DbORM) insertLogsWithinTx(logs []Log, tx pg.Queryer) error { ) if err != nil { - if errors.Is(err, context.DeadlineExceeded) && batchInsertSize > 500 { + if pkgerrors.Is(err, context.DeadlineExceeded) && batchInsertSize > 500 { // In case of DB timeouts, try to insert again with a smaller batch upto a limit batchInsertSize /= 2 i -= batchInsertSize // counteract +=batchInsertSize on next loop iteration @@ -376,7 +376,7 @@ func (o *DbORM) insertLogsWithinTx(logs []Log, tx pg.Queryer) error { func (o *DbORM) validateLogs(logs []Log) error { for _, log := range logs { if o.chainID.Cmp(log.EvmChainId.ToInt()) != 0 { - return errors.Errorf("invalid chainID in log got %v want %v", log.EvmChainId.ToInt(), o.chainID) + return pkgerrors.Errorf("invalid chainID in log got %v want %v", log.EvmChainId.ToInt(), o.chainID) } } return nil @@ -475,7 +475,7 @@ func (o *DbORM) SelectLogsWithSigs(start, end int64, address common.Address, eve AND event_sig = ANY(:event_sig_array) AND block_number BETWEEN :start_block AND :end_block ORDER BY (block_number, log_index)`, args) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } return logs, err @@ -526,7 +526,7 @@ func (o *DbORM) SelectLatestLogEventSigsAddrsWithConfs(fromBlock int64, addresse ORDER BY block_number ASC`, nestedBlockNumberQuery(confs)) var logs []Log if err := o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil { - return nil, errors.Wrap(err, "failed to execute query") + return nil, pkgerrors.Wrap(err, "failed to execute query") } return logs, nil } diff --git a/core/chains/evm/logpoller/orm_test.go b/core/chains/evm/logpoller/orm_test.go index 8f89a237fd4..655a7295dab 100644 --- a/core/chains/evm/logpoller/orm_test.go +++ b/core/chains/evm/logpoller/orm_test.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/jackc/pgx/v4" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -205,17 +205,17 @@ func TestORM(t *testing.T) { require.NoError(t, o1.DeleteLogsAndBlocksAfter(10)) _, err = o1.SelectBlockByHash(common.HexToHash("0x1234")) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // Delete blocks from another chain. require.NoError(t, o2.DeleteLogsAndBlocksAfter(11)) _, err = o2.SelectBlockByHash(common.HexToHash("0x1234")) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // Delete blocks after should also delete block 12. _, err = o2.SelectBlockByHash(common.HexToHash("0x1235")) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // Should be able to insert and read back a log. topic := common.HexToHash("0x1599") @@ -331,7 +331,7 @@ func TestORM(t *testing.T) { // With no blocks, should be an error _, err = o1.SelectLatestLogByEventSigWithConfs(topic, common.HexToAddress("0x1234"), 0) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // With block 10, only 0 confs should work require.NoError(t, o1.InsertBlock(common.HexToHash("0x1234"), 10, time.Now(), 0)) log, err := o1.SelectLatestLogByEventSigWithConfs(topic, common.HexToAddress("0x1234"), 0) @@ -339,7 +339,7 @@ func TestORM(t *testing.T) { assert.Equal(t, int64(10), log.BlockNumber) _, err = o1.SelectLatestLogByEventSigWithConfs(topic, common.HexToAddress("0x1234"), 1) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // With block 12, anything <=2 should work require.NoError(t, o1.InsertBlock(common.HexToHash("0x1234"), 11, time.Now(), 0)) require.NoError(t, o1.InsertBlock(common.HexToHash("0x1235"), 12, time.Now(), 0)) @@ -351,7 +351,7 @@ func TestORM(t *testing.T) { require.NoError(t, err) _, err = o1.SelectLatestLogByEventSigWithConfs(topic, common.HexToAddress("0x1234"), 3) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // Required for confirmations to work require.NoError(t, o1.InsertBlock(common.HexToHash("0x1234"), 13, time.Now(), 0)) diff --git a/core/chains/evm/monitor/balance.go b/core/chains/evm/monitor/balance.go index bb271ad1d46..16e2fd527bf 100644 --- a/core/chains/evm/monitor/balance.go +++ b/core/chains/evm/monitor/balance.go @@ -9,7 +9,7 @@ import ( "time" gethCommon "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -231,7 +231,7 @@ func ApproximateFloat64(e *assets.Eth) (float64, error) { bf := new(big.Float).Quo(ef, weif) f64, _ := bf.Float64() if f64 == math.Inf(1) || f64 == math.Inf(-1) { - return math.Inf(1), errors.New("assets.Eth.Float64: Could not approximate Eth value into float") + return math.Inf(1), pkgerrors.New("assets.Eth.Float64: Could not approximate Eth value into float") } return f64, nil } diff --git a/core/chains/evm/monitor/balance_test.go b/core/chains/evm/monitor/balance_test.go index 246d5d0759f..85e0ec669bf 100644 --- a/core/chains/evm/monitor/balance_test.go +++ b/core/chains/evm/monitor/balance_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/onsi/gomega" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -123,7 +123,7 @@ func TestBalanceMonitor_Start(t *testing.T) { ethClient.On("BalanceAt", mock.Anything, k0Addr, nilBigInt). Once(). - Return(nil, errors.New("a little easter egg for the 4chan link marines error")) + Return(nil, pkgerrors.New("a little easter egg for the 4chan link marines error")) servicetest.RunHealthy(t, bm) diff --git a/core/chains/evm/txmgr/attempts.go b/core/chains/evm/txmgr/attempts.go index e37f0e4d2d8..892920c0f67 100644 --- a/core/chains/evm/txmgr/attempts.go +++ b/core/chains/evm/txmgr/attempts.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" feetypes "github.com/smartcontractkit/chainlink/v2/common/fee/types" @@ -59,7 +59,7 @@ func (c *evmTxAttemptBuilder) NewTxAttemptWithType(ctx context.Context, etx Tx, keySpecificMaxGasPriceWei := c.feeConfig.PriceMaxKey(etx.FromAddress) fee, feeLimit, err = c.EvmFeeEstimator.GetFee(ctx, etx.EncodedPayload, etx.FeeLimit, keySpecificMaxGasPriceWei, opts...) if err != nil { - return attempt, fee, feeLimit, true, errors.Wrap(err, "failed to get fee") // estimator errors are retryable + return attempt, fee, feeLimit, true, pkgerrors.Wrap(err, "failed to get fee") // estimator errors are retryable } attempt, retryable, err = c.NewCustomTxAttempt(ctx, etx, fee, feeLimit, txType, lggr) @@ -73,7 +73,7 @@ func (c *evmTxAttemptBuilder) NewBumpTxAttempt(ctx context.Context, etx Tx, prev bumpedFee, bumpedFeeLimit, err = c.EvmFeeEstimator.BumpFee(ctx, previousAttempt.TxFee, etx.FeeLimit, keySpecificMaxGasPriceWei, newEvmPriorAttempts(priorAttempts)) if err != nil { - return attempt, bumpedFee, bumpedFeeLimit, true, errors.Wrap(err, "failed to bump fee") // estimator errors are retryable + return attempt, bumpedFee, bumpedFeeLimit, true, pkgerrors.Wrap(err, "failed to bump fee") // estimator errors are retryable } attempt, retryable, err = c.NewCustomTxAttempt(ctx, etx, bumpedFee, bumpedFeeLimit, previousAttempt.TxType, lggr) @@ -86,7 +86,7 @@ func (c *evmTxAttemptBuilder) NewCustomTxAttempt(ctx context.Context, etx Tx, fe switch txType { case 0x0: // legacy if fee.Legacy == nil { - err = errors.Errorf("Attempt %v is a type 0 transaction but estimator did not return legacy fee bump", attempt.ID) + err = pkgerrors.Errorf("Attempt %v is a type 0 transaction but estimator did not return legacy fee bump", attempt.ID) logger.Sugared(lggr).AssumptionViolation(err.Error()) return attempt, false, err // not retryable } @@ -94,7 +94,7 @@ func (c *evmTxAttemptBuilder) NewCustomTxAttempt(ctx context.Context, etx Tx, fe return attempt, true, err case 0x2: // dynamic, EIP1559 if !fee.ValidDynamic() { - err = errors.Errorf("Attempt %v is a type 2 transaction but estimator did not return dynamic fee bump", attempt.ID) + err = pkgerrors.Errorf("Attempt %v is a type 2 transaction but estimator did not return dynamic fee bump", attempt.ID) logger.Sugared(lggr).AssumptionViolation(err.Error()) return attempt, false, err // not retryable } @@ -104,7 +104,7 @@ func (c *evmTxAttemptBuilder) NewCustomTxAttempt(ctx context.Context, etx Tx, fe }, gasLimit) return attempt, true, err default: - err = errors.Errorf("invariant violation: Attempt %v had unrecognised transaction type %v"+ + err = pkgerrors.Errorf("invariant violation: Attempt %v had unrecognised transaction type %v"+ "This is a bug! Please report to https://github.com/smartcontractkit/chainlink/issues", attempt.ID, attempt.TxType) logger.Sugared(lggr).AssumptionViolation(err.Error()) return attempt, false, err // not retryable @@ -117,7 +117,7 @@ func (c *evmTxAttemptBuilder) NewEmptyTxAttempt(ctx context.Context, nonce evmty payload := []byte{} if fee.Legacy == nil { - return attempt, errors.New("NewEmptyTranscation: legacy fee cannot be nil") + return attempt, pkgerrors.New("NewEmptyTranscation: legacy fee cannot be nil") } tx := newLegacyTransaction( @@ -132,7 +132,7 @@ func (c *evmTxAttemptBuilder) NewEmptyTxAttempt(ctx context.Context, nonce evmty transaction := types.NewTx(&tx) hash, signedTxBytes, err := c.SignTx(ctx, fromAddress, transaction) if err != nil { - return attempt, errors.Wrapf(err, "error using account %s to sign empty transaction", fromAddress.String()) + return attempt, pkgerrors.Wrapf(err, "error using account %s to sign empty transaction", fromAddress.String()) } attempt.SignedRawTx = signedTxBytes @@ -143,7 +143,7 @@ func (c *evmTxAttemptBuilder) NewEmptyTxAttempt(ctx context.Context, nonce evmty func (c *evmTxAttemptBuilder) newDynamicFeeAttempt(ctx context.Context, etx Tx, fee gas.DynamicFee, gasLimit uint32) (attempt TxAttempt, err error) { if err = validateDynamicFeeGas(c.feeConfig, c.feeConfig.TipCapMin(), fee, gasLimit, etx); err != nil { - return attempt, errors.Wrap(err, "error validating gas") + return attempt, pkgerrors.Wrap(err, "error validating gas") } d := newDynamicFeeTransaction( @@ -190,25 +190,25 @@ func validateDynamicFeeGas(kse keySpecificEstimator, tipCapMinimum *assets.Wei, // Assertions from: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md // Prevent impossibly large numbers if gasFeeCap.ToInt().Cmp(Max256BitUInt) > 0 { - return errors.New("impossibly large fee cap") + return pkgerrors.New("impossibly large fee cap") } if gasTipCap.ToInt().Cmp(Max256BitUInt) > 0 { - return errors.New("impossibly large tip cap") + return pkgerrors.New("impossibly large tip cap") } // The total must be at least as large as the tip if gasFeeCap.Cmp(gasTipCap) < 0 { - return errors.Errorf("gas fee cap must be greater than or equal to gas tip cap (fee cap: %s, tip cap: %s)", gasFeeCap.String(), gasTipCap.String()) + return pkgerrors.Errorf("gas fee cap must be greater than or equal to gas tip cap (fee cap: %s, tip cap: %s)", gasFeeCap.String(), gasTipCap.String()) } // Configuration sanity-check max := kse.PriceMaxKey(etx.FromAddress) if gasFeeCap.Cmp(max) > 0 { - return errors.Errorf("cannot create tx attempt: specified gas fee cap of %s would exceed max configured gas price of %s for key %s", gasFeeCap.String(), max.String(), etx.FromAddress.String()) + return pkgerrors.Errorf("cannot create tx attempt: specified gas fee cap of %s would exceed max configured gas price of %s for key %s", gasFeeCap.String(), max.String(), etx.FromAddress.String()) } // Tip must be above minimum minTip := tipCapMinimum if gasTipCap.Cmp(minTip) < 0 { - return errors.Errorf("cannot create tx attempt: specified gas tip cap of %s is below min configured gas tip of %s for key %s", gasTipCap.String(), minTip.String(), etx.FromAddress.String()) + return pkgerrors.Errorf("cannot create tx attempt: specified gas tip cap of %s is below min configured gas tip of %s for key %s", gasTipCap.String(), minTip.String(), etx.FromAddress.String()) } return nil } @@ -228,7 +228,7 @@ func newDynamicFeeTransaction(nonce uint64, to common.Address, value *big.Int, g func (c *evmTxAttemptBuilder) newLegacyAttempt(ctx context.Context, etx Tx, gasPrice *assets.Wei, gasLimit uint32) (attempt TxAttempt, err error) { if err = validateLegacyGas(ctx, c.feeConfig, c.feeConfig.PriceMin(), gasPrice, gasLimit, etx); err != nil { - return attempt, errors.Wrap(err, "error validating gas") + return attempt, pkgerrors.Wrap(err, "error validating gas") } tx := newLegacyTransaction( @@ -243,7 +243,7 @@ func (c *evmTxAttemptBuilder) newLegacyAttempt(ctx context.Context, etx Tx, gasP transaction := types.NewTx(&tx) hash, signedTxBytes, err := c.SignTx(ctx, etx.FromAddress, transaction) if err != nil { - return attempt, errors.Wrapf(err, "error using account %s to sign transaction %v", etx.FromAddress, etx.ID) + return attempt, pkgerrors.Wrapf(err, "error using account %s to sign transaction %v", etx.FromAddress, etx.ID) } attempt.State = txmgrtypes.TxAttemptInProgress @@ -266,11 +266,11 @@ func validateLegacyGas(ctx context.Context, kse keySpecificEstimator, minGasPric } max := kse.PriceMaxKey(etx.FromAddress) if gasPrice.Cmp(max) > 0 { - return errors.Errorf("cannot create tx attempt: specified gas price of %s would exceed max configured gas price of %s for key %s", gasPrice.String(), max.String(), etx.FromAddress.String()) + return pkgerrors.Errorf("cannot create tx attempt: specified gas price of %s would exceed max configured gas price of %s for key %s", gasPrice.String(), max.String(), etx.FromAddress.String()) } min := minGasPriceWei if gasPrice.Cmp(min) < 0 { - return errors.Errorf("cannot create tx attempt: specified gas price of %s is below min configured gas price of %s for key %s", gasPrice.String(), min.String(), etx.FromAddress.String()) + return pkgerrors.Errorf("cannot create tx attempt: specified gas price of %s is below min configured gas price of %s for key %s", gasPrice.String(), min.String(), etx.FromAddress.String()) } return nil } @@ -278,7 +278,7 @@ func validateLegacyGas(ctx context.Context, kse keySpecificEstimator, minGasPric func (c *evmTxAttemptBuilder) newSignedAttempt(ctx context.Context, etx Tx, tx *types.Transaction) (attempt TxAttempt, err error) { hash, signedTxBytes, err := c.SignTx(ctx, etx.FromAddress, tx) if err != nil { - return attempt, errors.Wrapf(err, "error using account %s to sign transaction %v", etx.FromAddress.String(), etx.ID) + return attempt, pkgerrors.Wrapf(err, "error using account %s to sign transaction %v", etx.FromAddress.String(), etx.ID) } attempt.State = txmgrtypes.TxAttemptInProgress @@ -308,7 +308,7 @@ func (c *evmTxAttemptBuilder) SignTx(ctx context.Context, address common.Address } rlp := new(bytes.Buffer) if err := signedTx.EncodeRLP(rlp); err != nil { - return common.Hash{}, nil, errors.Wrap(err, "SignTx failed") + return common.Hash{}, nil, pkgerrors.Wrap(err, "SignTx failed") } txHash := signedTx.Hash() return txHash, rlp.Bytes(), nil diff --git a/core/chains/evm/txmgr/attempts_test.go b/core/chains/evm/txmgr/attempts_test.go index e0b3cd59ce7..b1e24984c37 100644 --- a/core/chains/evm/txmgr/attempts_test.go +++ b/core/chains/evm/txmgr/attempts_test.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" gethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -257,8 +257,8 @@ func TestTxm_NewCustomTxAttempt_NonRetryableErrors(t *testing.T) { func TestTxm_EvmTxAttemptBuilder_RetryableEstimatorError(t *testing.T) { est := gasmocks.NewEvmFeeEstimator(t) - est.On("GetFee", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(gas.EvmFee{}, uint32(0), errors.New("fail")) - est.On("BumpFee", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(gas.EvmFee{}, uint32(0), errors.New("fail")) + est.On("GetFee", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(gas.EvmFee{}, uint32(0), pkgerrors.New("fail")) + est.On("BumpFee", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(gas.EvmFee{}, uint32(0), pkgerrors.New("fail")) kst := ksmocks.NewEth(t) lggr := logger.Test(t) diff --git a/core/chains/evm/txmgr/common.go b/core/chains/evm/txmgr/common.go index d1e851f0c21..75fd3628ed5 100644 --- a/core/chains/evm/txmgr/common.go +++ b/core/chains/evm/txmgr/common.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" @@ -74,7 +74,7 @@ func batchSendTransactions( logger.Debugw(fmt.Sprintf("Batch sending transactions %v thru %v", i, j)) if err := ethClient.BatchCallContextAll(ctx, reqs[i:j]); err != nil { - return reqs, now, successfulBroadcast, errors.Wrap(err, "failed to batch send transactions") + return reqs, now, successfulBroadcast, pkgerrors.Wrap(err, "failed to batch send transactions") } successfulBroadcast = append(successfulBroadcast, ethTxIDs[i:j]...) } diff --git a/core/chains/evm/txmgr/nonce_syncer.go b/core/chains/evm/txmgr/nonce_syncer.go index 2936736b3b3..0cb52a1321e 100644 --- a/core/chains/evm/txmgr/nonce_syncer.go +++ b/core/chains/evm/txmgr/nonce_syncer.go @@ -6,7 +6,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/common/txmgr" @@ -76,13 +76,13 @@ func NewNonceSyncer( // Calling it later is not safe and could lead to races. func (s nonceSyncerImpl) Sync(ctx context.Context, addr common.Address, localNonce types.Nonce) (nonce types.Nonce, err error) { nonce, err = s.fastForwardNonceIfNecessary(ctx, addr, localNonce) - return nonce, errors.Wrap(err, "NonceSyncer#fastForwardNoncesIfNecessary failed") + return nonce, pkgerrors.Wrap(err, "NonceSyncer#fastForwardNoncesIfNecessary failed") } func (s nonceSyncerImpl) fastForwardNonceIfNecessary(ctx context.Context, address common.Address, localNonce types.Nonce) (types.Nonce, error) { chainNonce, err := s.pendingNonceFromEthClient(ctx, address) if err != nil { - return localNonce, errors.Wrap(err, "GetNextNonce failed to loadInitialNonceFromEthClient") + return localNonce, pkgerrors.Wrap(err, "GetNextNonce failed to loadInitialNonceFromEthClient") } if chainNonce == 0 { return localNonce, nil @@ -102,5 +102,5 @@ func (s nonceSyncerImpl) fastForwardNonceIfNecessary(ctx context.Context, addres func (s nonceSyncerImpl) pendingNonceFromEthClient(ctx context.Context, account common.Address) (types.Nonce, error) { nextNonce, err := s.client.PendingSequenceAt(ctx, account) - return nextNonce, errors.WithStack(err) + return nextNonce, pkgerrors.WithStack(err) } diff --git a/core/chains/evm/txmgr/nonce_syncer_test.go b/core/chains/evm/txmgr/nonce_syncer_test.go index f757b8863d1..d9a741fb3c5 100644 --- a/core/chains/evm/txmgr/nonce_syncer_test.go +++ b/core/chains/evm/txmgr/nonce_syncer_test.go @@ -12,7 +12,7 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/evmtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -32,7 +32,7 @@ func Test_NonceSyncer_Sync(t *testing.T) { ns := txmgr.NewNonceSyncer(txStore, logger.Test(t), ethClient) - ethClient.On("PendingNonceAt", mock.Anything, from).Return(uint64(0), errors.New("something exploded")) + ethClient.On("PendingNonceAt", mock.Anything, from).Return(uint64(0), pkgerrors.New("something exploded")) _, err := ns.Sync(testutils.Context(t), from, types.Nonce(0)) require.Error(t, err) assert.Contains(t, err.Error(), "something exploded") diff --git a/core/chains/evm/txmgr/resender_test.go b/core/chains/evm/txmgr/resender_test.go index e8c1c9e079f..7cf575e8c8d 100644 --- a/core/chains/evm/txmgr/resender_test.go +++ b/core/chains/evm/txmgr/resender_test.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -177,7 +177,7 @@ func Test_EthResender_Start(t *testing.T) { })).Return(nil).Run(func(args mock.Arguments) { elems := args.Get(1).([]rpc.BatchElem) // It should update BroadcastAt even if there is an error here - elems[0].Error = errors.New("kaboom") + elems[0].Error = pkgerrors.New("kaboom") }) func() { diff --git a/core/chains/evm/txmgr/transmitchecker.go b/core/chains/evm/txmgr/transmitchecker.go index 5a5cc3dbcd4..8956f2ae626 100644 --- a/core/chains/evm/txmgr/transmitchecker.go +++ b/core/chains/evm/txmgr/transmitchecker.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" bigmath "github.com/smartcontractkit/chainlink-common/pkg/utils/big_math" @@ -53,11 +53,11 @@ func (c *CheckerFactory) BuildChecker(spec TransmitCheckerSpec) (TransmitChecker return &SimulateChecker{c.Client}, nil case TransmitCheckerTypeVRFV1: if spec.VRFCoordinatorAddress == nil { - return nil, errors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) + return nil, pkgerrors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) } coord, err := v1.NewVRFCoordinator(*spec.VRFCoordinatorAddress, c.Client) if err != nil { - return nil, errors.Wrapf(err, + return nil, pkgerrors.Wrapf(err, "failed to create VRF V1 coordinator at address %v", spec.VRFCoordinatorAddress) } return &VRFV1Checker{ @@ -66,15 +66,15 @@ func (c *CheckerFactory) BuildChecker(spec TransmitCheckerSpec) (TransmitChecker }, nil case TransmitCheckerTypeVRFV2: if spec.VRFCoordinatorAddress == nil { - return nil, errors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) + return nil, pkgerrors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) } coord, err := v2.NewVRFCoordinatorV2(*spec.VRFCoordinatorAddress, c.Client) if err != nil { - return nil, errors.Wrapf(err, + return nil, pkgerrors.Wrapf(err, "failed to create VRF V2 coordinator at address %v", spec.VRFCoordinatorAddress) } if spec.VRFRequestBlockNumber == nil { - return nil, errors.New("VRFRequestBlockNumber parameter must be non-nil") + return nil, pkgerrors.New("VRFRequestBlockNumber parameter must be non-nil") } return &VRFV2Checker{ GetCommitment: coord.GetCommitment, @@ -83,15 +83,15 @@ func (c *CheckerFactory) BuildChecker(spec TransmitCheckerSpec) (TransmitChecker }, nil case TransmitCheckerTypeVRFV2Plus: if spec.VRFCoordinatorAddress == nil { - return nil, errors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) + return nil, pkgerrors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) } coord, err := vrf_coordinator_v2plus_interface.NewIVRFCoordinatorV2PlusInternal(*spec.VRFCoordinatorAddress, c.Client) if err != nil { - return nil, errors.Wrapf(err, + return nil, pkgerrors.Wrapf(err, "failed to create VRF V2 coordinator plus at address %v", spec.VRFCoordinatorAddress) } if spec.VRFRequestBlockNumber == nil { - return nil, errors.New("VRFRequestBlockNumber parameter must be non-nil") + return nil, pkgerrors.New("VRFRequestBlockNumber parameter must be non-nil") } return &VRFV2Checker{ GetCommitment: coord.SRequestCommitments, @@ -101,7 +101,7 @@ func (c *CheckerFactory) BuildChecker(spec TransmitCheckerSpec) (TransmitChecker case "": return NoChecker, nil default: - return nil, errors.Errorf("unrecognized checker type: %s", spec.CheckerType) + return nil, pkgerrors.Errorf("unrecognized checker type: %s", spec.CheckerType) } } @@ -150,7 +150,7 @@ func (s *SimulateChecker) Check( if jErr := evmclient.ExtractRPCErrorOrNil(err); jErr != nil { l.Criticalw("Transaction reverted during simulation", "ethTxAttemptID", a.ID, "txHash", a.Hash, "err", err, "rpcErr", jErr.String(), "returnValue", b.String()) - return errors.Errorf("transaction reverted during simulation: %s", jErr.String()) + return pkgerrors.Errorf("transaction reverted during simulation: %s", jErr.String()) } l.Warnw("Transaction simulation failed, will attempt to send anyway", "ethTxAttemptID", a.ID, "txHash", a.Hash, "err", err, "returnValue", b.String()) @@ -259,7 +259,7 @@ func (v *VRFV1Checker) Check( "ethTxID", tx.ID, "meta", tx.Meta, "reqID", reqID) - return errors.New("request already fulfilled") + return pkgerrors.New("request already fulfilled") } // Request not fulfilled return nil @@ -350,7 +350,7 @@ func (v *VRFV2Checker) Check( "ethTxID", tx.ID, "meta", tx.Meta, "vrfRequestId", vrfRequestID) - return errors.New("request already fulfilled") + return pkgerrors.New("request already fulfilled") } l.Debugw("Request not yet fulfilled", "ethTxID", tx.ID, diff --git a/core/chains/evm/txmgr/transmitchecker_test.go b/core/chains/evm/txmgr/transmitchecker_test.go index d2f668da11b..2fce9cf7aac 100644 --- a/core/chains/evm/txmgr/transmitchecker_test.go +++ b/core/chains/evm/txmgr/transmitchecker_test.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/mock" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -165,7 +165,7 @@ func TestTransmitCheckers(t *testing.T) { mock.AnythingOfType("*hexutil.Bytes"), "eth_call", mock.MatchedBy(func(callarg map[string]interface{}) bool { return fmt.Sprintf("%s", callarg["value"]) == "0x282" // 642 - }), "latest").Return(errors.New("error")).Once() + }), "latest").Return(pkgerrors.New("error")).Once() // Non-revert errors are logged but should not prevent transmission, and do not need // to be passed to the caller @@ -221,7 +221,7 @@ func TestTransmitCheckers(t *testing.T) { Callbacks: func(opts *bind.CallOpts, reqID [32]byte) (v1.Callbacks, error) { if opts.BlockNumber.Cmp(big.NewInt(6)) != 0 { // Ensure correct logic is applied to get callbacks. - return v1.Callbacks{}, errors.New("error getting callback") + return v1.Callbacks{}, pkgerrors.New("error getting callback") } if reqID == r1 { // Request 1 is already fulfilled @@ -230,7 +230,7 @@ func TestTransmitCheckers(t *testing.T) { }, nil } else if reqID == r2 { // Request 2 errors - return v1.Callbacks{}, errors.New("error getting commitment") + return v1.Callbacks{}, pkgerrors.New("error getting commitment") } return v1.Callbacks{ SeedAndBlockNum: [32]byte{1}, @@ -277,7 +277,7 @@ func TestTransmitCheckers(t *testing.T) { t.Run("failure fetching tx receipt and block head", func(t *testing.T) { tx, attempt := txRequest(t, r1, false) - mockBatch.Return(errors.New("could not fetch")) + mockBatch.Return(pkgerrors.New("could not fetch")) err := checker.Check(ctx, log, tx, attempt) require.NoError(t, err) }) @@ -324,7 +324,7 @@ func TestTransmitCheckers(t *testing.T) { return [32]byte{}, nil } else if requestID.String() == "2" { // Request 2 errors - return [32]byte{}, errors.New("error getting commitment") + return [32]byte{}, pkgerrors.New("error getting commitment") } // All other requests are unfulfilled return [32]byte{1}, nil @@ -355,7 +355,7 @@ func TestTransmitCheckers(t *testing.T) { t.Run("can't get header", func(t *testing.T) { checker.HeadByNumber = func(ctx context.Context, n *big.Int) (*evmtypes.Head, error) { - return nil, errors.New("can't get head") + return nil, pkgerrors.New("can't get head") } tx, attempt := txRequest(t, big.NewInt(3)) require.NoError(t, checker.Check(ctx, log, tx, attempt)) diff --git a/core/chains/evm/types/internal/blocks/transactions.go b/core/chains/evm/types/internal/blocks/transactions.go index b607e2dcfd1..887a16f99d1 100644 --- a/core/chains/evm/types/internal/blocks/transactions.go +++ b/core/chains/evm/types/internal/blocks/transactions.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) type TxType uint8 @@ -22,7 +22,7 @@ func (txt *TxType) UnmarshalJSON(data []byte) error { return err } if hx > math.MaxUint8 { - return errors.Errorf("expected 'type' to fit into a single byte, got: '%s'", data) + return pkgerrors.Errorf("expected 'type' to fit into a single byte, got: '%s'", data) } *txt = TxType(hx) return nil diff --git a/core/chains/evm/types/models.go b/core/chains/evm/types/models.go index 7db38fc6821..464eb901005 100644 --- a/core/chains/evm/types/models.go +++ b/core/chains/evm/types/models.go @@ -13,7 +13,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/ugorji/go/codec" "github.com/smartcontractkit/chainlink-common/pkg/utils/hex" @@ -355,7 +355,7 @@ func (b Block) MarshalJSON() ([]byte, error) { return buf.Bytes(), nil } -var ErrMissingBlock = errors.New("missing block") +var ErrMissingBlock = pkgerrors.New("missing block") // UnmarshalJSON unmarshals to a Block func (b *Block) UnmarshalJSON(data []byte) error { @@ -370,12 +370,12 @@ func (b *Block) UnmarshalJSON(data []byte) error { return err } if bi.Empty() { - return errors.WithStack(ErrMissingBlock) + return pkgerrors.WithStack(ErrMissingBlock) } n, err := hexutil.DecodeBig(bi.Number) if err != nil { - return errors.Wrapf(err, "failed to decode block number while unmarshalling block, got: '%s' in '%s'", bi.Number, data) + return pkgerrors.Wrapf(err, "failed to decode block number while unmarshalling block, got: '%s' in '%s'", bi.Number, data) } *b = Block{ Number: n.Int64(), @@ -421,7 +421,7 @@ func (t *Transaction) UnmarshalJSON(data []byte) error { } if ti.Gas == nil { - return errors.Errorf("expected 'gas' to not be null, got: '%s'", data) + return pkgerrors.Errorf("expected 'gas' to not be null, got: '%s'", data) } if ti.Type == nil { tpe := LegacyTxType @@ -502,7 +502,7 @@ func unmarshalFromString(s string, f *FunctionSelector) error { } bytes := common.FromHex(s) if len(bytes) != FunctionSelectorLength { - return errors.New("function ID must be 4 bytes in length") + return pkgerrors.New("function ID must be 4 bytes in length") } f.SetBytes(bytes) } else { @@ -559,7 +559,7 @@ type UntrustedBytes []byte func (ary UntrustedBytes) SafeByteSlice(start int, end int) ([]byte, error) { if end > len(ary) || start > end || start < 0 || end < 0 { var empty []byte - return empty, errors.New("out of bounds slice access") + return empty, pkgerrors.New("out of bounds slice access") } return ary[start:end], nil } diff --git a/core/chains/evm/types/models_test.go b/core/chains/evm/types/models_test.go index f2f58c3a983..4fc986ae9d3 100644 --- a/core/chains/evm/types/models_test.go +++ b/core/chains/evm/types/models_test.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -935,8 +935,8 @@ func TestBlock_UnmarshalJSON(t *testing.T) { b := new(evmtypes.Block) err := b.UnmarshalJSON([]byte("null")) assert.Error(t, err) - assert.Equal(t, errors.Cause(err), evmtypes.ErrMissingBlock) - assert.True(t, errors.Is(err, evmtypes.ErrMissingBlock)) + assert.Equal(t, pkgerrors.Cause(err), evmtypes.ErrMissingBlock) + assert.True(t, pkgerrors.Is(err, evmtypes.ErrMissingBlock)) }) t.Run("unmarshals EIP-4844 block", func(t *testing.T) { b := new(evmtypes.Block) diff --git a/core/chains/evm/types/types.go b/core/chains/evm/types/types.go index c3ad584ebbd..89739e61e1b 100644 --- a/core/chains/evm/types/types.go +++ b/core/chains/evm/types/types.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" gethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/jackc/pgtype" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink-common/pkg/types" @@ -143,7 +143,7 @@ func (r *Receipt) UnmarshalJSON(input []byte) error { } var dec Receipt if err := json.Unmarshal(input, &dec); err != nil { - return errors.Wrap(err, "could not unmarshal receipt") + return pkgerrors.Wrap(err, "could not unmarshal receipt") } if dec.PostState != nil { r.PostState = *dec.PostState @@ -182,7 +182,7 @@ func (r *Receipt) UnmarshalJSON(input []byte) error { func (r *Receipt) Scan(value interface{}) error { b, ok := value.([]byte) if !ok { - return errors.New("type assertion to []byte failed") + return pkgerrors.New("type assertion to []byte failed") } return json.Unmarshal(b, r) @@ -294,7 +294,7 @@ func (l *Log) UnmarshalJSON(input []byte) error { } var dec Log if err := json.Unmarshal(input, &dec); err != nil { - return errors.Wrap(err, "could not unmarshal log") + return pkgerrors.Wrap(err, "could not unmarshal log") } if dec.Address != nil { l.Address = *dec.Address @@ -330,20 +330,20 @@ func (a *AddressArray) Scan(src interface{}) error { baArray := pgtype.ByteaArray{} err := baArray.Scan(src) if err != nil { - return errors.Wrap(err, "Expected BYTEA[] column for AddressArray") + return pkgerrors.Wrap(err, "Expected BYTEA[] column for AddressArray") } if baArray.Status != pgtype.Present { *a = nil return nil } if len(baArray.Dimensions) > 1 { - return errors.Errorf("Expected AddressArray to be 1-dimensional. Dimensions = %v", baArray.Dimensions) + return pkgerrors.Errorf("Expected AddressArray to be 1-dimensional. Dimensions = %v", baArray.Dimensions) } for i, ba := range baArray.Elements { addr := common.Address{} if ba.Status != pgtype.Present { - return errors.Errorf("Expected all addresses in AddressArray to be non-NULL. Got AddressArray[%d] = NULL", i) + return pkgerrors.Errorf("Expected all addresses in AddressArray to be non-NULL. Got AddressArray[%d] = NULL", i) } err = addr.Scan(ba.Bytes) if err != nil { @@ -361,20 +361,20 @@ func (h *HashArray) Scan(src interface{}) error { baArray := pgtype.ByteaArray{} err := baArray.Scan(src) if err != nil { - return errors.Wrap(err, "Expected BYTEA[] column for HashArray") + return pkgerrors.Wrap(err, "Expected BYTEA[] column for HashArray") } if baArray.Status != pgtype.Present { *h = nil return nil } if len(baArray.Dimensions) > 1 { - return errors.Errorf("Expected HashArray to be 1-dimensional. Dimensions = %v", baArray.Dimensions) + return pkgerrors.Errorf("Expected HashArray to be 1-dimensional. Dimensions = %v", baArray.Dimensions) } for i, ba := range baArray.Elements { hash := common.Hash{} if ba.Status != pgtype.Present { - return errors.Errorf("Expected all hashes in HashArray to be non-NULL. Got HashArray[%d] = NULL", i) + return pkgerrors.Errorf("Expected all hashes in HashArray to be non-NULL. Got HashArray[%d] = NULL", i) } err = hash.Scan(ba.Bytes) if err != nil { diff --git a/core/chains/evm/utils/ethabi.go b/core/chains/evm/utils/ethabi.go index 61d365933d2..08dfd54f430 100644 --- a/core/chains/evm/utils/ethabi.go +++ b/core/chains/evm/utils/ethabi.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" "github.com/tidwall/gjson" @@ -222,7 +222,7 @@ func EVMWordSignedBigInt(val *big.Int) ([]byte, error) { // a signed representation. Returns error on overflow. func EVMWordBigInt(val *big.Int) ([]byte, error) { if val.Sign() == -1 { - return nil, errors.New("Uint256 cannot be negative") + return nil, pkgerrors.New("Uint256 cannot be negative") } bytes := val.Bytes() if len(bytes) > EVMWordByteLen { diff --git a/core/chains/evm/utils/ethabi_test.go b/core/chains/evm/utils/ethabi_test.go index b99d906eae7..f28a083ff01 100644 --- a/core/chains/evm/utils/ethabi_test.go +++ b/core/chains/evm/utils/ethabi_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" @@ -636,7 +636,7 @@ func EVMTranscodeBytes(value gjson.Result) ([]byte, error) { vInt, _ := v.Int(nil) word, err := EVMWordSignedBigInt(vInt) if err != nil { - return nil, errors.Wrap(err, "while converting float to int256") + return nil, pkgerrors.Wrap(err, "while converting float to int256") } return EVMEncodeBytes(word), nil default: diff --git a/core/config/app_config.go b/core/config/app_config.go index 648939b871b..290e14dcc45 100644 --- a/core/config/app_config.go +++ b/core/config/app_config.go @@ -4,13 +4,13 @@ import ( "time" "github.com/google/uuid" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/zap/zapcore" ) // nolint var ( - ErrEnvUnset = errors.New("env var unset") + ErrEnvUnset = pkgerrors.New("env var unset") ) type LogfFn func(string, ...any) diff --git a/core/config/docs/docs_test.go b/core/config/docs/docs_test.go index 8b4e38b980d..919113e1d93 100644 --- a/core/config/docs/docs_test.go +++ b/core/config/docs/docs_test.go @@ -6,7 +6,7 @@ import ( "github.com/kylelemons/godebug/diff" gotoml "github.com/pelletier/go-toml/v2" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -31,7 +31,7 @@ func TestDoc(t *testing.T) { var strict *gotoml.StrictMissingError if err != nil && strings.Contains(err.Error(), "undecoded keys: ") { t.Errorf("Docs contain extra fields: %v", err) - } else if errors.As(err, &strict) { + } else if pkgerrors.As(err, &strict) { t.Fatal("StrictMissingError:", strict.String()) } else { require.NoError(t, err) diff --git a/core/config/parse/parsers.go b/core/config/parse/parsers.go index 6243b74dd52..371354ba36e 100644 --- a/core/config/parse/parsers.go +++ b/core/config/parse/parsers.go @@ -10,7 +10,7 @@ import ( "time" "github.com/mitchellh/go-homedir" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/zap/zapcore" commonassets "github.com/smartcontractkit/chainlink-common/pkg/assets" @@ -113,7 +113,7 @@ func HomeDir(str string) (string, error) { func DatabaseURL(s string) (url.URL, error) { uri, err := url.Parse(s) if err != nil { - return url.URL{}, errors.Wrapf(err, "invalid database url %s", s) + return url.URL{}, pkgerrors.Wrapf(err, "invalid database url %s", s) } if uri.String() == "" { return *uri, nil diff --git a/core/gethwrappers/versions.go b/core/gethwrappers/versions.go index acdefd06a59..43a59ddbb75 100644 --- a/core/gethwrappers/versions.go +++ b/core/gethwrappers/versions.go @@ -9,7 +9,7 @@ import ( "sort" "strings" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/multierr" ) @@ -44,11 +44,11 @@ func dbPath() (path string, err error) { func versionsDBLineReader() (*bufio.Scanner, error) { versionsDBPath, err := dbPath() if err != nil { - return nil, errors.Wrapf(err, "could not construct versions DB path") + return nil, pkgerrors.Wrapf(err, "could not construct versions DB path") } versionsDBFile, err := os.Open(versionsDBPath) if err != nil { - return nil, errors.Wrapf(err, "could not open versions database") + return nil, pkgerrors.Wrapf(err, "could not open versions database") } return bufio.NewScanner(versionsDBFile), nil @@ -66,28 +66,28 @@ func ReadVersionsDB() (*IntegratedVersion, error) { for db.Scan() { line := strings.Fields(db.Text()) if !strings.HasSuffix(line[0], ":") { - return nil, errors.Errorf( + return nil, pkgerrors.Errorf( `each line in versions.txt should start with "$TOPIC:"`) } topic := stripTrailingColon(line[0], "") if topic == "GETH_VERSION" { if len(line) != 2 { - return nil, errors.Errorf("GETH_VERSION line should contain geth "+ + return nil, pkgerrors.Errorf("GETH_VERSION line should contain geth "+ "version, and only that: %s", line) } if rv.GethVersion != "" { - return nil, errors.Errorf("more than one geth version") + return nil, pkgerrors.Errorf("more than one geth version") } rv.GethVersion = line[1] } else { // It's a wrapper from a compiler artifact if len(line) != 4 { - return nil, errors.Errorf(`"%s" should have four elements `+ + return nil, pkgerrors.Errorf(`"%s" should have four elements `+ `": "`, db.Text()) } _, alreadyExists := rv.ContractVersions[topic] if alreadyExists { - return nil, errors.Errorf(`topic "%s" already mentioned`, topic) + return nil, pkgerrors.Errorf(`topic "%s" already mentioned`, topic) } rv.ContractVersions[topic] = ContractVersion{ AbiPath: line[1], BinaryPath: line[2], Hash: line[3], @@ -102,11 +102,11 @@ var stripTrailingColon = regexp.MustCompile(":$").ReplaceAllString func WriteVersionsDB(db *IntegratedVersion) (err error) { versionsDBPath, err := dbPath() if err != nil { - return errors.Wrap(err, "could not construct path to versions DB") + return pkgerrors.Wrap(err, "could not construct path to versions DB") } f, err := os.Create(versionsDBPath) if err != nil { - return errors.Wrapf(err, "while opening %s", versionsDBPath) + return pkgerrors.Wrapf(err, "while opening %s", versionsDBPath) } defer func() { if cerr := f.Close(); cerr != nil { @@ -116,10 +116,10 @@ func WriteVersionsDB(db *IntegratedVersion) (err error) { gethLine := "GETH_VERSION: " + db.GethVersion + "\n" n, err := f.WriteString(gethLine) if err != nil { - return errors.Wrapf(err, "while recording geth version line") + return pkgerrors.Wrapf(err, "while recording geth version line") } if n != len(gethLine) { - return errors.Errorf("failed to write entire geth version line, %s", gethLine) + return pkgerrors.Errorf("failed to write entire geth version line, %s", gethLine) } var pkgNames []string for name := range db.ContractVersions { @@ -132,10 +132,10 @@ func WriteVersionsDB(db *IntegratedVersion) (err error) { vinfo.AbiPath, vinfo.BinaryPath, vinfo.Hash) n, err = f.WriteString(versionLine) if err != nil { - return errors.Wrapf(err, "while recording %s version line", name) + return pkgerrors.Wrapf(err, "while recording %s version line", name) } if n != len(versionLine) { - return errors.Errorf("failed to write entire version line %s", versionLine) + return pkgerrors.Errorf("failed to write entire version line %s", versionLine) } } return nil diff --git a/core/internal/testutils/httptest/httptest.go b/core/internal/testutils/httptest/httptest.go index 7607ca7552d..a1bd941fb02 100644 --- a/core/internal/testutils/httptest/httptest.go +++ b/core/internal/testutils/httptest/httptest.go @@ -6,7 +6,7 @@ import ( "net/http" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) // NewTestHTTPClient returns a real HTTP client that may only make requests to @@ -31,7 +31,7 @@ func testDialContext(ctx context.Context, network, address string) (net.Conn, er } a := con.RemoteAddr().(*net.TCPAddr) if a != nil && !a.IP.IsLoopback() { - return nil, errors.Errorf("Test HTTP client may only dial localhost, got address: %v", a.String()) + return nil, pkgerrors.Errorf("Test HTTP client may only dial localhost, got address: %v", a.String()) } return con, err } diff --git a/core/internal/testutils/keystest/keystest.go b/core/internal/testutils/keystest/keystest.go index beb7e580f1b..850e1ad1fa0 100644 --- a/core/internal/testutils/keystest/keystest.go +++ b/core/internal/testutils/keystest/keystest.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/crypto" "github.com/google/uuid" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) // NewKey pulled from geth @@ -19,7 +19,7 @@ func NewKey() (key keystore.Key, err error) { id, err := uuid.NewRandom() if err != nil { - return key, errors.Errorf("Could not create random uuid: %v", err) + return key, pkgerrors.Errorf("Could not create random uuid: %v", err) } return keystore.Key{ diff --git a/core/logger/zap.go b/core/logger/zap.go index c739a80d45a..e11458bdf8b 100644 --- a/core/logger/zap.go +++ b/core/logger/zap.go @@ -3,7 +3,7 @@ package logger import ( "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) @@ -76,7 +76,7 @@ func (l *zapLogger) Sync() error { return nil } var msg string - if uw := errors.Unwrap(err); uw != nil { + if uw := pkgerrors.Unwrap(err); uw != nil { msg = uw.Error() } else { msg = err.Error() diff --git a/core/sessions/localauth/orm.go b/core/sessions/localauth/orm.go index 013f719ad34..8afaf5e7fc1 100644 --- a/core/sessions/localauth/orm.go +++ b/core/sessions/localauth/orm.go @@ -7,7 +7,7 @@ import ( "time" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/utils/mathutil" "github.com/smartcontractkit/chainlink/v2/core/auth" @@ -69,7 +69,7 @@ func (o *orm) ListUsers() (users []sessions.User, err error) { func (o *orm) findValidSession(sessionID string) (email string, err error) { if err := o.q.Get(&email, "SELECT email FROM sessions WHERE id = $1 AND last_used + $2 >= now() FOR UPDATE", sessionID, o.sessionDuration); err != nil { o.lggr.Infof("query result: %v", email) - return email, errors.Wrap(err, "no matching user for provided session token") + return email, pkgerrors.Wrap(err, "no matching user for provided session token") } return email, nil } @@ -152,12 +152,12 @@ func (o *orm) CreateSession(sr sessions.SessionRequest) (string, error) { // for MFA tokens leaking if an account has MFA tokens or not. if !constantTimeEmailCompare(strings.ToLower(sr.Email), strings.ToLower(user.Email)) { o.auditLogger.Audit(audit.AuthLoginFailedEmail, map[string]interface{}{"email": sr.Email}) - return "", errors.New("Invalid email") + return "", pkgerrors.New("Invalid email") } if !utils.CheckPasswordHash(sr.Password, user.HashedPassword) { o.auditLogger.Audit(audit.AuthLoginFailedPassword, map[string]interface{}{"email": sr.Email}) - return "", errors.New("Invalid password") + return "", pkgerrors.New("Invalid password") } // Load all valid MFA tokens associated with user's email @@ -165,7 +165,7 @@ func (o *orm) CreateSession(sr sessions.SessionRequest) (string, error) { if err != nil { // There was an error with the database query lggr.Errorf("Could not fetch user's MFA data: %v", err) - return "", errors.New("MFA Error") + return "", pkgerrors.New("MFA Error") } // No webauthn tokens registered for the current user, so normal authentication is now complete @@ -185,16 +185,16 @@ func (o *orm) CreateSession(sr sessions.SessionRequest) (string, error) { options, webauthnError := sessions.BeginWebAuthnLogin(user, uwas, sr) if webauthnError != nil { lggr.Errorf("Could not begin WebAuthn verification: %v", webauthnError) - return "", errors.New("MFA Error") + return "", pkgerrors.New("MFA Error") } j, jsonError := json.Marshal(options) if jsonError != nil { lggr.Errorf("Could not serialize WebAuthn challenge: %v", jsonError) - return "", errors.New("MFA Error") + return "", pkgerrors.New("MFA Error") } - return "", errors.New(string(j)) + return "", pkgerrors.New(string(j)) } // The user is at the final stage of logging in with MFA. We have an @@ -206,7 +206,7 @@ func (o *orm) CreateSession(sr sessions.SessionRequest) (string, error) { // The user does have WebAuthn enabled but failed the check o.auditLogger.Audit(audit.AuthLoginFailed2FA, map[string]interface{}{"email": sr.Email, "error": err}) lggr.Errorf("User sent an invalid attestation: %v", err) - return "", errors.New("MFA Error") + return "", pkgerrors.New("MFA Error") } lggr.Infof("User passed MFA authentication and login will proceed") @@ -256,13 +256,13 @@ func (o *orm) UpdateRole(email, newRole string) (sessions.User, error) { var userToEdit sessions.User if newRole == "" { - return userToEdit, errors.New("user role must be specified") + return userToEdit, pkgerrors.New("user role must be specified") } err := o.q.Transaction(func(tx pg.Queryer) error { // First, attempt to load specified user by email if err := tx.Get(&userToEdit, "SELECT * FROM users WHERE lower(email) = lower($1)", email); err != nil { - return errors.New("no matching user for provided email") + return pkgerrors.New("no matching user for provided email") } // Patch validated role @@ -275,13 +275,13 @@ func (o *orm) UpdateRole(email, newRole string) (sessions.User, error) { _, err = tx.Exec("DELETE FROM sessions WHERE email = lower($1)", email) if err != nil { o.lggr.Errorf("Failed to purge user sessions for UpdateRole", "err", err) - return errors.New("error updating API user") + return pkgerrors.New("error updating API user") } sql := "UPDATE users SET role = $1, updated_at = now() WHERE lower(email) = lower($2) RETURNING *" if err := tx.Get(&userToEdit, sql, userToEdit.Role, email); err != nil { o.lggr.Errorf("Error updating API user", "err", err) - return errors.New("error updating API user") + return pkgerrors.New("error updating API user") } return nil @@ -304,10 +304,10 @@ func (o *orm) SetPassword(user *sessions.User, newPassword string) error { func (o *orm) TestPassword(email string, password string) error { var hashedPassword string if err := o.q.Get(&hashedPassword, "SELECT hashed_password FROM users WHERE lower(email) = lower($1)", email); err != nil { - return errors.New("no matching user for provided email") + return pkgerrors.New("no matching user for provided email") } if !utils.CheckPasswordHash(password, hashedPassword) { - return errors.New("passwords don't match") + return pkgerrors.New("passwords don't match") } return nil } @@ -328,7 +328,7 @@ func (o *orm) SetAuthToken(user *sessions.User, token *auth.Token) error { salt := utils.NewSecret(utils.DefaultSecretSize) hashedSecret, err := auth.HashedSecret(token, salt) if err != nil { - return errors.Wrap(err, "user") + return pkgerrors.Wrap(err, "user") } sql := "UPDATE users SET token_salt = $1, token_key = $2, token_hashed_secret = $3, updated_at = now() WHERE email = $4 RETURNING *" return o.q.Get(user, sql, salt, token.AccessKey, hashedSecret, user.Email) diff --git a/core/sessions/session.go b/core/sessions/session.go index 90964596e9a..49f403b6a81 100644 --- a/core/sessions/session.go +++ b/core/sessions/session.go @@ -4,7 +4,7 @@ import ( "crypto/subtle" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink/v2/core/auth" @@ -55,7 +55,7 @@ func (u *User) SetAuthToken(token *auth.Token) error { salt := utils.NewSecret(utils.DefaultSecretSize) hashedSecret, err := auth.HashedSecret(token, salt) if err != nil { - return errors.Wrap(err, "user") + return pkgerrors.Wrap(err, "user") } u.TokenSalt = null.StringFrom(salt) u.TokenKey = null.StringFrom(token.AccessKey) diff --git a/core/sessions/user.go b/core/sessions/user.go index f2e4827b922..bcedaa4b197 100644 --- a/core/sessions/user.go +++ b/core/sessions/user.go @@ -5,7 +5,7 @@ import ( "net/mail" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -58,7 +58,7 @@ func NewUser(email string, plainPwd string, role UserRole) (User, error) { // ValidateEmail is the single point of logic for user email validations func ValidateEmail(email string) error { if len(email) == 0 { - return errors.New("Must enter an email") + return pkgerrors.New("Must enter an email") } _, err := mail.ParseAddress(email) return err @@ -67,10 +67,10 @@ func ValidateEmail(email string) error { // ValidateAndHashPassword is the single point of logic for user password validations func ValidateAndHashPassword(plainPwd string) (string, error) { if err := utils.VerifyPasswordComplexity(plainPwd); err != nil { - return "", errors.Wrapf(err, "password insufficiently complex:\n%s", utils.PasswordComplexityRequirements) + return "", pkgerrors.Wrapf(err, "password insufficiently complex:\n%s", utils.PasswordComplexityRequirements) } if len(plainPwd) > MaxBcryptPasswordLength { - return "", errors.Errorf("must enter a password less than %v characters", MaxBcryptPasswordLength) + return "", pkgerrors.Errorf("must enter a password less than %v characters", MaxBcryptPasswordLength) } pwd, err := utils.HashPassword(plainPwd) @@ -104,5 +104,5 @@ func GetUserRole(role string) (UserRole, error) { UserRoleRun, UserRoleView, ) - return UserRole(""), errors.New(errStr) + return UserRole(""), pkgerrors.New(errStr) } diff --git a/core/sessions/webauthn.go b/core/sessions/webauthn.go index 89e7758bc5b..c959bec08de 100644 --- a/core/sessions/webauthn.go +++ b/core/sessions/webauthn.go @@ -10,7 +10,7 @@ import ( "github.com/go-webauthn/webauthn/protocol" "github.com/go-webauthn/webauthn/webauthn" sqlxTypes "github.com/jmoiron/sqlx/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) // WebAuthn holds the credentials for API user. @@ -93,7 +93,7 @@ func (store *WebAuthnSessionStore) FinishWebAuthnRegistration(user User, uwas [] credential, err := webAuthn.FinishRegistration(waUser, sessionData, response) if err != nil { - return nil, errors.Wrap(err, "failed to FinishRegistration") + return nil, pkgerrors.Wrap(err, "failed to FinishRegistration") } return credential, nil @@ -137,7 +137,7 @@ func FinishWebAuthnLogin(user User, uwas []WebAuthn, sr SessionRequest) error { }) if err != nil { - return errors.Wrapf(err, "failed to create webAuthn structure with RPID: %s and RPOrigin: %s", sr.WebAuthnConfig.RPID, sr.WebAuthnConfig.RPOrigin) + return pkgerrors.Wrapf(err, "failed to create webAuthn structure with RPID: %s and RPOrigin: %s", sr.WebAuthnConfig.RPID, sr.WebAuthnConfig.RPOrigin) } credential, err := protocol.ParseCredentialRequestResponseBody(strings.NewReader(sr.WebAuthnData)) @@ -272,7 +272,7 @@ func (store *WebAuthnSessionStore) take(key string) (val string, ok bool) { func (store *WebAuthnSessionStore) GetWebauthnSession(key string) (data webauthn.SessionData, err error) { assertion, ok := store.take(key) if !ok { - err = errors.New("assertion not in challenge store") + err = pkgerrors.New("assertion not in challenge store") return } err = json.Unmarshal([]byte(assertion), &data) diff --git a/core/store/migrate/migrate.go b/core/store/migrate/migrate.go index 04da4c48e92..aff3229e92a 100644 --- a/core/store/migrate/migrate.go +++ b/core/store/migrate/migrate.go @@ -10,7 +10,7 @@ import ( "strings" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/pressly/goose/v3" "gopkg.in/guregu/null.v4" @@ -62,7 +62,7 @@ func ensureMigrated(ctx context.Context, db *sql.DB, lggr logger.Logger) error { } } if !found { - return errors.New("database state is too old. Need to migrate to chainlink version 0.9.10 first before upgrading to this version. This upgrade is NOT REVERSIBLE, so it is STRONGLY RECOMMENDED that you take a database backup before continuing") + return pkgerrors.New("database state is too old. Need to migrate to chainlink version 0.9.10 first before upgrading to this version. This upgrade is NOT REVERSIBLE, so it is STRONGLY RECOMMENDED that you take a database backup before continuing") } // ensure a goose migrations table exists with it's initial v0 @@ -88,7 +88,7 @@ func ensureMigrated(ctx context.Context, db *sql.DB, lggr logger.Logger) error { id, err = strconv.ParseInt(name[:idx], 10, 64) if err == nil && id <= 0 { - return errors.New("migration IDs must be greater than zero") + return pkgerrors.New("migration IDs must be greater than zero") } } @@ -144,7 +144,7 @@ func SetMigrationENVVars(generalConfig chainlink.GeneralConfig) error { if generalConfig.EVMEnabled() { err := os.Setenv(env.EVMChainIDNotNullMigration0195, generalConfig.EVMConfigs()[0].ChainID.String()) if err != nil { - panic(errors.Wrap(err, "failed to set migrations env variables")) + panic(pkgerrors.Wrap(err, "failed to set migrations env variables")) } } return nil