From 558613d8558fd7899f06e8fdab814975dee8fd0a Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 18 Jan 2024 15:43:29 -0500 Subject: [PATCH] rename errors to pkgerrors for non standlib and replace multierr.Combine with errors.Join --- common/txmgr/broadcaster.go | 3 +- common/txmgr/confirmer.go | 13 +- core/chains/evm/utils/utils_test.go | 4 +- core/chains/legacyevm/chain.go | 13 +- core/cmd/cosmos_transaction_commands.go | 6 +- core/cmd/evm_transaction_commands.go | 8 +- core/cmd/shell.go | 25 ++- core/cmd/solana_transaction_commands.go | 11 +- core/internal/testutils/pgtest/txdb.go | 4 +- core/services/chainlink/application.go | 17 +- core/services/chainlink/cfgtest/cfgtest.go | 8 +- core/services/chainlink/config_general.go | 11 +- core/services/functions/connector_handler.go | 7 +- core/services/gateway/connectionmanager.go | 2 +- core/services/gateway/gateway.go | 9 +- .../handlers/functions/handler.functions.go | 5 +- .../gateway/handlers/handler.dummy.go | 5 +- core/services/job/orm.go | 208 +++++++++--------- core/services/ocr/database.go | 46 ++-- .../ocr2/plugins/s4/integration_test.go | 14 +- .../services/ocrcommon/discoverer_database.go | 10 +- core/services/pg/lease_lock.go | 38 ++-- core/services/pg/transaction.go | 10 +- core/services/pipeline/models.go | 16 +- core/services/pipeline/task.base64decode.go | 12 +- core/services/pipeline/task.base64encode.go | 14 +- core/services/pipeline/task.bridge.go | 24 +- core/services/pipeline/task.cborparse.go | 18 +- core/services/pipeline/task.conditional.go | 12 +- core/services/pipeline/task.divide.go | 18 +- core/services/pipeline/task.estimategas.go | 18 +- core/services/pipeline/task.eth_abi_decode.go | 14 +- .../pipeline/task.eth_abi_decode_log.go | 22 +- core/services/pipeline/task.eth_abi_encode.go | 20 +- .../pipeline/task.eth_abi_encode_2.go | 22 +- core/services/pipeline/task.eth_call.go | 30 +-- core/services/pipeline/task.eth_tx.go | 40 ++-- core/services/pipeline/task.hexdecode.go | 15 +- core/services/pipeline/task.hexencode.go | 26 +-- core/services/pipeline/task.http.go | 24 +- core/services/pipeline/task.jsonparse.go | 28 +-- core/services/pipeline/task.length.go | 10 +- core/services/pipeline/task.lessthan.go | 12 +- core/services/pipeline/task.lowercase.go | 10 +- core/services/pipeline/task.mean.go | 18 +- core/services/pipeline/task.median.go | 14 +- core/services/pipeline/task.merge.go | 12 +- core/services/pipeline/task.mode.go | 16 +- core/services/pipeline/task.multiply.go | 14 +- core/services/pipeline/task.sum.go | 16 +- core/services/pipeline/task.uppercase.go | 10 +- core/services/pipeline/task.vrf.go | 22 +- core/services/pipeline/task.vrfv2.go | 30 +-- core/services/pipeline/task.vrfv2plus.go | 32 +-- core/services/promreporter/prom_reporter.go | 20 +- core/services/relay/evm/functions.go | 25 +-- core/services/relay/evm/relayer_extender.go | 10 +- core/services/relay/grpc_provider_server.go | 4 +- .../vrf/v2/listener_v2_log_processor.go | 43 ++-- core/services/webhook/validate.go | 9 +- core/utils/files.go | 20 +- core/utils/http/http_allowed_ips.go | 14 +- core/web/eth_keys_controller.go | 32 +-- core/web/loader/getters.go | 12 +- 64 files changed, 626 insertions(+), 629 deletions(-) diff --git a/common/txmgr/broadcaster.go b/common/txmgr/broadcaster.go index 9f2204f37e2..d83241145c5 100644 --- a/common/txmgr/broadcaster.go +++ b/common/txmgr/broadcaster.go @@ -12,7 +12,6 @@ import ( "github.com/jpillora/backoff" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "go.uber.org/multierr" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink-common/pkg/chains/label" @@ -669,7 +668,7 @@ func (eb *Broadcaster[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, SEQ, FEE]) hand `Urgent resolution required, Chainlink is currently operating in a degraded state and may miss transactions`, "attempt", attempt) nextSequence, e := eb.client.PendingSequenceAt(ctx, etx.FromAddress) if e != nil { - err = multierr.Combine(e, err) + err = errors.Join(e, err) return fmt.Errorf("failed to fetch latest pending sequence after encountering unknown RPC error while sending transaction: %w", err), true } if nextSequence.Int64() > (*etx.Sequence).Int64() { diff --git a/common/txmgr/confirmer.go b/common/txmgr/confirmer.go index f10481fef56..8d6fac04efe 100644 --- a/common/txmgr/confirmer.go +++ b/common/txmgr/confirmer.go @@ -12,7 +12,6 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/chains/label" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -608,13 +607,13 @@ func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) Reb // It is safe to process separate keys concurrently // NOTE: This design will block one key if another takes a really long time to execute wg.Add(len(ec.enabledAddresses)) - errors := []error{} + errs := []error{} var errMu sync.Mutex for _, address := range ec.enabledAddresses { go func(fromAddress ADDR) { if err := ec.rebroadcastWhereNecessary(ctx, fromAddress, blockHeight); err != nil { errMu.Lock() - errors = append(errors, err) + errs = append(errs, err) errMu.Unlock() ec.lggr.Errorw("Error in RebroadcastWhereNecessary", "err", err, "fromAddress", fromAddress) } @@ -625,7 +624,7 @@ func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) Reb wg.Wait() - return multierr.Combine(errors...) + return errors.Join(errs...) } func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) rebroadcastWhereNecessary(ctx context.Context, address ADDR, blockHeight int64) error { @@ -938,14 +937,14 @@ func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) Ens // It is safe to process separate keys concurrently // NOTE: This design will block one key if another takes a really long time to execute var wg sync.WaitGroup - errors := []error{} + errs := []error{} var errMu sync.Mutex wg.Add(len(ec.enabledAddresses)) for _, address := range ec.enabledAddresses { go func(fromAddress ADDR) { if err := ec.handleAnyInProgressAttempts(ctx, fromAddress, head.BlockNumber()); err != nil { errMu.Lock() - errors = append(errors, err) + errs = append(errs, err) errMu.Unlock() ec.lggr.Errorw("Error in handleAnyInProgressAttempts", "err", err, "fromAddress", fromAddress) } @@ -956,7 +955,7 @@ func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) Ens wg.Wait() - return multierr.Combine(errors...) + return errors.Join(errs...) } func hasReceiptInLongestChain[ diff --git a/core/chains/evm/utils/utils_test.go b/core/chains/evm/utils/utils_test.go index 9e8b44864ad..8e4d2e6c873 100644 --- a/core/chains/evm/utils/utils_test.go +++ b/core/chains/evm/utils/utils_test.go @@ -2,6 +2,7 @@ package utils_test import ( "context" + "errors" "math/big" "strings" "sync/atomic" @@ -11,7 +12,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/stretchr/testify/assert" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" @@ -101,7 +101,7 @@ func TestClient_ParseEthereumAddress(t *testing.T) { assert.True(t, a1 == a2) _, lowerErr := parse(strings.ToLower(address)) _, upperErr := parse(strings.ToUpper(address)) - shouldBeError := multierr.Combine(lowerErr, upperErr) + shouldBeError := errors.Join(lowerErr, upperErr) assert.Error(t, shouldBeError) assert.True(t, strings.Contains(shouldBeError.Error(), no0xPrefix)) } diff --git a/core/chains/legacyevm/chain.go b/core/chains/legacyevm/chain.go index 0e0e1e65aca..e1600ea5cd2 100644 --- a/core/chains/legacyevm/chain.go +++ b/core/chains/legacyevm/chain.go @@ -9,7 +9,6 @@ import ( "time" gotoml "github.com/pelletier/go-toml/v2" - "go.uber.org/multierr" "github.com/jmoiron/sqlx" @@ -345,13 +344,13 @@ func (c *chain) Close() error { merr = c.balanceMonitor.Close() } c.logger.Debug("Chain: stopping logBroadcaster") - merr = multierr.Combine(merr, c.logBroadcaster.Close()) + merr = errors.Join(merr, c.logBroadcaster.Close()) c.logger.Debug("Chain: stopping headTracker") - merr = multierr.Combine(merr, c.headTracker.Close()) + merr = errors.Join(merr, c.headTracker.Close()) c.logger.Debug("Chain: stopping headBroadcaster") - merr = multierr.Combine(merr, c.headBroadcaster.Close()) + merr = errors.Join(merr, c.headBroadcaster.Close()) c.logger.Debug("Chain: stopping evmTxm") - merr = multierr.Combine(merr, c.txm.Close()) + merr = errors.Join(merr, c.txm.Close()) c.logger.Debug("Chain: stopping client") c.client.Close() c.logger.Debug("Chain: stopped") @@ -360,7 +359,7 @@ func (c *chain) Close() error { } func (c *chain) Ready() (merr error) { - merr = multierr.Combine( + merr = errors.Join( c.StateMachine.Ready(), c.txm.Ready(), c.headBroadcaster.Ready(), @@ -368,7 +367,7 @@ func (c *chain) Ready() (merr error) { c.logBroadcaster.Ready(), ) if c.balanceMonitor != nil { - merr = multierr.Combine(merr, c.balanceMonitor.Ready()) + merr = errors.Join(merr, c.balanceMonitor.Ready()) } return } diff --git a/core/cmd/cosmos_transaction_commands.go b/core/cmd/cosmos_transaction_commands.go index 576a64adfb0..0e9febeb70c 100644 --- a/core/cmd/cosmos_transaction_commands.go +++ b/core/cmd/cosmos_transaction_commands.go @@ -74,14 +74,14 @@ func (s *Shell) CosmosSendNativeToken(c *cli.Context) (err error) { amount, err := sdk.NewDecFromStr(c.Args().Get(1)) if err != nil { - return s.errorOut(multierr.Combine( + return s.errorOut(errors.Join( fmt.Errorf("invalid coin: %w", err))) } unparsedFromAddress := c.Args().Get(2) fromAddress, err := sdk.AccAddressFromBech32(unparsedFromAddress) if err != nil { - return s.errorOut(multierr.Combine( + return s.errorOut(errors.Join( fmt.Errorf("while parsing withdrawal source address %v", unparsedFromAddress), err)) } @@ -89,7 +89,7 @@ func (s *Shell) CosmosSendNativeToken(c *cli.Context) (err error) { unparsedDestinationAddress := c.Args().Get(3) destinationAddress, err := sdk.AccAddressFromBech32(unparsedDestinationAddress) if err != nil { - return s.errorOut(multierr.Combine( + return s.errorOut(errors.Join( fmt.Errorf("while parsing withdrawal destination address %v", unparsedDestinationAddress), err)) } diff --git a/core/cmd/evm_transaction_commands.go b/core/cmd/evm_transaction_commands.go index 28a4fa23a3b..e1611021439 100644 --- a/core/cmd/evm_transaction_commands.go +++ b/core/cmd/evm_transaction_commands.go @@ -144,7 +144,7 @@ func (s *Shell) SendEther(c *cli.Context) (err error) { value, err = stringutils.ToInt64(c.Args().Get(0)) if err != nil { - return s.errorOut(multierr.Combine( + return s.errorOut(errors.Join( errors.New("while parsing WEI transfer amount"), err)) } @@ -152,7 +152,7 @@ func (s *Shell) SendEther(c *cli.Context) (err error) { } else { amount, err = assets.NewEthValueS(c.Args().Get(0)) if err != nil { - return s.errorOut(multierr.Combine( + return s.errorOut(errors.Join( errors.New("while parsing ETH transfer amount"), err)) } } @@ -160,7 +160,7 @@ func (s *Shell) SendEther(c *cli.Context) (err error) { unparsedFromAddress := c.Args().Get(1) fromAddress, err := utils.ParseEthereumAddress(unparsedFromAddress) if err != nil { - return s.errorOut(multierr.Combine( + return s.errorOut(errors.Join( fmt.Errorf("while parsing withdrawal source address %v", unparsedFromAddress), err)) } @@ -168,7 +168,7 @@ func (s *Shell) SendEther(c *cli.Context) (err error) { unparsedDestinationAddress := c.Args().Get(2) destinationAddress, err := utils.ParseEthereumAddress(unparsedDestinationAddress) if err != nil { - return s.errorOut(multierr.Combine( + return s.errorOut(errors.Join( fmt.Errorf("while parsing withdrawal destination address %v", unparsedDestinationAddress), err)) } diff --git a/core/cmd/shell.go b/core/cmd/shell.go index 5ca938b1b40..05081cdc314 100644 --- a/core/cmd/shell.go +++ b/core/cmd/shell.go @@ -6,6 +6,7 @@ import ( "crypto/tls" "database/sql" "encoding/json" + "errors" "fmt" "io" "log/slog" @@ -24,7 +25,7 @@ import ( "github.com/Masterminds/semver/v3" "github.com/getsentry/sentry-go" "github.com/gin-gonic/gin" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" "go.uber.org/zap/zapcore" @@ -308,7 +309,7 @@ func takeBackupIfVersionUpgrade(dbUrl url.URL, rootDir string, cfg periodicbacku databaseBackup, err := periodicbackup.NewDatabaseBackup(dbUrl, rootDir, cfg, lggr) if err != nil { - return errors.Wrap(err, "takeBackupIfVersionUpgrade failed") + return pkgerrors.Wrap(err, "takeBackupIfVersionUpgrade failed") } //Because backups can take a long time we must start a "fake" health report to prevent @@ -343,7 +344,7 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err } if err := sentryInit(config.Sentry()); err != nil { - return errors.Wrap(err, "failed to initialize sentry") + return pkgerrors.Wrap(err, "failed to initialize sentry") } ws := config.WebServer() @@ -353,7 +354,7 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err handler, err := web.NewRouter(app, prometheus) if err != nil { - return errors.Wrap(err, "failed to create web router") + return pkgerrors.Wrap(err, "failed to create web router") } server := server{handler: handler, lggr: app.GetLogger()} @@ -381,15 +382,15 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err <-gCtx.Done() var err error if server.httpServer != nil { - err = errors.WithStack(server.httpServer.Shutdown(context.Background())) + err = pkgerrors.WithStack(server.httpServer.Shutdown(context.Background())) } if server.tlsServer != nil { - err = multierr.Combine(err, errors.WithStack(server.tlsServer.Shutdown(context.Background()))) + err = errors.Join(err, pkgerrors.WithStack(server.tlsServer.Shutdown(context.Background()))) } return err }) - return errors.WithStack(g.Wait()) + return pkgerrors.WithStack(g.Wait()) } func sentryInit(cfg config.Sentry) error { @@ -455,7 +456,7 @@ func (s *server) run(ip net.IP, port uint16, writeTimeout time.Duration) error { s.lggr.Infow(fmt.Sprintf("Listening and serving HTTP on %s", addr), "ip", ip, "port", port) s.httpServer = createServer(s.handler, addr, writeTimeout) err := s.httpServer.ListenAndServe() - return errors.Wrap(err, "failed to run plaintext HTTP server") + return pkgerrors.Wrap(err, "failed to run plaintext HTTP server") } func (s *server) runTLS(ip net.IP, port uint16, certFile, keyFile string, requestTimeout time.Duration) error { @@ -463,7 +464,7 @@ func (s *server) runTLS(ip net.IP, port uint16, certFile, keyFile string, reques s.lggr.Infow(fmt.Sprintf("Listening and serving HTTPS on %s", addr), "ip", ip, "port", port) s.tlsServer = createServer(s.handler, addr, requestTimeout) err := s.tlsServer.ListenAndServeTLS(certFile, keyFile) - return errors.Wrap(err, "failed to run TLS server (NOTE: you can disable TLS server completely and silence these errors by setting WebServer.TLS.HTTPSPort=0 in your config)") + return pkgerrors.Wrap(err, "failed to run TLS server (NOTE: you can disable TLS server completely and silence these errors by setting WebServer.TLS.HTTPSPort=0 in your config)") } func createServer(handler *gin.Engine, addr string, requestTimeout time.Duration) *http.Server { @@ -812,7 +813,7 @@ func (t *promptingAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lg // Load list of users to determine which to assume, or if a user needs to be created dbUsers, err := orm.ListUsers() if err != nil { - return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization") + return sessions.User{}, pkgerrors.Wrap(err, "Unable to List users for initialization") } // If there are no users in the database, prompt for initial admin user creation @@ -871,14 +872,14 @@ func (f fileAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lggr log // Load list of users to determine which to assume, or if a user needs to be created dbUsers, err := orm.ListUsers() if err != nil { - return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization") + return sessions.User{}, pkgerrors.Wrap(err, "Unable to List users for initialization") } // If there are no users in the database, create initial admin user from session request from file creds if len(dbUsers) == 0 { user, err2 := sessions.NewUser(request.Email, request.Password, sessions.UserRoleAdmin) if err2 != nil { - return user, errors.Wrap(err2, "failed to instantiate new user") + return user, pkgerrors.Wrap(err2, "failed to instantiate new user") } return user, orm.CreateUser(&user) } diff --git a/core/cmd/solana_transaction_commands.go b/core/cmd/solana_transaction_commands.go index 23e94eee50b..7eaac7930a2 100644 --- a/core/cmd/solana_transaction_commands.go +++ b/core/cmd/solana_transaction_commands.go @@ -3,11 +3,12 @@ package cmd import ( "bytes" "encoding/json" + "errors" "fmt" "strconv" solanaGo "github.com/gagliardetto/solana-go" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -72,16 +73,16 @@ func (s *Shell) SolanaSendSol(c *cli.Context) (err error) { unparsedFromAddress := c.Args().Get(1) fromAddress, err := solanaGo.PublicKeyFromBase58(unparsedFromAddress) if err != nil { - return s.errorOut(multierr.Combine( - errors.Errorf("while parsing withdrawal source address %v", + return s.errorOut(errors.Join( + pkgerrors.Errorf("while parsing withdrawal source address %v", unparsedFromAddress), err)) } unparsedDestinationAddress := c.Args().Get(2) destinationAddress, err := solanaGo.PublicKeyFromBase58(unparsedDestinationAddress) if err != nil { - return s.errorOut(multierr.Combine( - errors.Errorf("while parsing withdrawal destination address %v", + return s.errorOut(errors.Join( + pkgerrors.Errorf("while parsing withdrawal destination address %v", unparsedDestinationAddress), err)) } diff --git a/core/internal/testutils/pgtest/txdb.go b/core/internal/testutils/pgtest/txdb.go index da9fd6cb2d0..7e790f41894 100644 --- a/core/internal/testutils/pgtest/txdb.go +++ b/core/internal/testutils/pgtest/txdb.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "database/sql/driver" + "errors" "flag" "fmt" "io" @@ -13,7 +14,6 @@ import ( "testing" "github.com/jmoiron/sqlx" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/config/env" "github.com/smartcontractkit/chainlink/v2/core/store/dialects" @@ -351,7 +351,7 @@ func (s stmt) Query(args []driver.Value) (driver.Rows, error) { } rows, err := s.st.Query(mapArgs(args)...) defer func() { - err = multierr.Combine(err, rows.Close()) + err = errors.Join(err, rows.Close()) }() if err != nil { return nil, err diff --git a/core/services/chainlink/application.go b/core/services/chainlink/application.go index a9f9c22df52..7b4a9951460 100644 --- a/core/services/chainlink/application.go +++ b/core/services/chainlink/application.go @@ -3,6 +3,7 @@ package chainlink import ( "bytes" "context" + "errors" "fmt" "math/big" "net/http" @@ -12,7 +13,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/google/uuid" "github.com/grafana/pyroscope-go" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/multierr" "go.uber.org/zap/zapcore" @@ -204,7 +205,7 @@ func NewApplication(opts ApplicationOpts) (Application, error) { var err error profiler, err = logger.StartPyroscope(cfg.Pyroscope(), cfg.AutoPprof()) if err != nil { - return nil, errors.Wrap(err, "starting pyroscope (automatic pprof profiling) failed") + return nil, pkgerrors.Wrap(err, "starting pyroscope (automatic pprof profiling) failed") } } else { globalLogger.Debug("Pyroscope (automatic pprof profiling) is disabled") @@ -232,7 +233,7 @@ func NewApplication(opts ApplicationOpts) (Application, error) { databaseBackup, err := periodicbackup.NewDatabaseBackup(cfg.Database().URL(), cfg.RootDir(), backupCfg, globalLogger) if err != nil { - return nil, errors.Wrap(err, "NewApplication: failed to initialize database backup") + return nil, pkgerrors.Wrap(err, "NewApplication: failed to initialize database backup") } srvcs = append(srvcs, databaseBackup) } else { @@ -274,14 +275,14 @@ func NewApplication(opts ApplicationOpts) (Application, error) { db, cfg.Database(), cfg.WebServer().LDAP(), cfg.Insecure().DevWebServer(), globalLogger, auditLogger, ) if err != nil { - return nil, errors.Wrap(err, "NewApplication: failed to initialize LDAP Authentication module") + return nil, pkgerrors.Wrap(err, "NewApplication: failed to initialize LDAP Authentication module") } sessionReaper = ldapauth.NewLDAPServerStateSync(db, cfg.Database(), cfg.WebServer().LDAP(), globalLogger) case sessions.LocalAuth: authenticationProvider = localauth.NewORM(db, cfg.WebServer().SessionTimeout().Duration(), globalLogger, cfg.Database(), auditLogger) sessionReaper = localauth.NewSessionReaper(db.DB, cfg.WebServer(), globalLogger) default: - return nil, errors.Errorf("NewApplication: Unexpected 'AuthenticationMethod': %s supported values: %s, %s", authMethod, sessions.LocalAuth, sessions.LDAPAuth) + return nil, pkgerrors.Errorf("NewApplication: Unexpected 'AuthenticationMethod': %s supported values: %s, %s", authMethod, sessions.LocalAuth, sessions.LDAPAuth) } var ( @@ -541,8 +542,8 @@ func (app *ChainlinkApplication) Start(ctx context.Context) error { var ms services.MultiStart for _, service := range app.srvcs { if ctx.Err() != nil { - err := errors.Wrap(ctx.Err(), "aborting start") - return multierr.Combine(err, ms.Close()) + err := pkgerrors.Wrap(ctx.Err(), "aborting start") + return errors.Join(err, ms.Close()) } app.logger.Debugw("Starting service...", "name", service.Name()) @@ -729,7 +730,7 @@ func (app *ChainlinkApplication) RunJobV2( } jb, err := app.jobORM.FindJob(ctx, jobID) if err != nil { - return 0, errors.Wrapf(err, "job ID %v", jobID) + return 0, pkgerrors.Wrapf(err, "job ID %v", jobID) } var runID int64 diff --git a/core/services/chainlink/cfgtest/cfgtest.go b/core/services/chainlink/cfgtest/cfgtest.go index 1438b702fc1..60058df14e4 100644 --- a/core/services/chainlink/cfgtest/cfgtest.go +++ b/core/services/chainlink/cfgtest/cfgtest.go @@ -2,13 +2,13 @@ package cfgtest import ( "encoding" + "errors" "fmt" "reflect" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -34,7 +34,7 @@ func assertFieldsNotNil(t *testing.T, prefix string, s reflect.Value) (err error } key += tf.Name } - err = multierr.Combine(err, assertValNotNil(t, key, f)) + err = errors.Join(err, assertValNotNil(t, key, f)) } return } @@ -50,7 +50,7 @@ func assertValuesNotNil(t *testing.T, prefix string, m reflect.Value) (err error mi := m.MapRange() for mi.Next() { key := prefix + mi.Key().String() - err = multierr.Combine(err, assertValNotNil(t, key, mi.Value())) + err = errors.Join(err, assertValNotNil(t, key, mi.Value())) } return } @@ -61,7 +61,7 @@ func assertElementsNotNil(t *testing.T, prefix string, s reflect.Value) (err err require.Equal(t, reflect.Slice, s.Kind()) for i := 0; i < s.Len(); i++ { - err = multierr.Combine(err, assertValNotNil(t, prefix, s.Index(i))) + err = errors.Join(err, assertValNotNil(t, prefix, s.Index(i))) } return } diff --git a/core/services/chainlink/config_general.go b/core/services/chainlink/config_general.go index 97243926973..ce3ba3a3099 100644 --- a/core/services/chainlink/config_general.go +++ b/core/services/chainlink/config_general.go @@ -2,6 +2,7 @@ package chainlink import ( _ "embed" + "errors" "fmt" "os" "path/filepath" @@ -9,7 +10,7 @@ import ( "sync" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/multierr" "go.uber.org/zap/zapcore" @@ -70,7 +71,7 @@ func (o *GeneralConfigOpts) Setup(configFiles []string, secretsFiles []string) e for _, fileName := range configFiles { b, err := os.ReadFile(fileName) if err != nil { - return errors.Wrapf(err, "failed to read config file: %s", fileName) + return pkgerrors.Wrapf(err, "failed to read config file: %s", fileName) } configs = append(configs, string(b)) } @@ -85,7 +86,7 @@ func (o *GeneralConfigOpts) Setup(configFiles []string, secretsFiles []string) e for _, fileName := range secretsFiles { b, err := os.ReadFile(fileName) if err != nil { - return errors.Wrapf(err, "failed to read secrets file: %s", fileName) + return pkgerrors.Wrapf(err, "failed to read secrets file: %s", fileName) } secrets = append(secrets, string(b)) } @@ -214,7 +215,7 @@ func (g *generalConfig) Validate() error { } func (g *generalConfig) validate(secretsValidationFn func() error) error { - err := multierr.Combine( + err := errors.Join( validateEnv(), g.c.Validate(), secretsValidationFn(), @@ -245,7 +246,7 @@ func validateEnv() (err error) { } i := strings.Index(kv, "=") if i == -1 { - return errors.Errorf("malformed .env file line: %s", kv) + return pkgerrors.Errorf("malformed .env file line: %s", kv) } k := kv[:i] _, ok := os.LookupEnv(k) diff --git a/core/services/functions/connector_handler.go b/core/services/functions/connector_handler.go index 1594dc6eb56..4e8245e8b17 100644 --- a/core/services/functions/connector_handler.go +++ b/core/services/functions/connector_handler.go @@ -5,12 +5,11 @@ import ( "context" "crypto/ecdsa" "encoding/json" + "errors" "fmt" "sync" "time" - "go.uber.org/multierr" - ethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/prometheus/client_golang/prometheus" @@ -150,8 +149,8 @@ func (h *functionsConnectorHandler) Start(ctx context.Context) error { func (h *functionsConnectorHandler) Close() error { return h.StopOnce("FunctionsConnectorHandler", func() (err error) { close(h.chStop) - err = multierr.Combine(err, h.allowlist.Close()) - err = multierr.Combine(err, h.subscriptions.Close()) + err = errors.Join(err, h.allowlist.Close()) + err = errors.Join(err, h.subscriptions.Close()) h.shutdownWaitGroup.Wait() return }) diff --git a/core/services/gateway/connectionmanager.go b/core/services/gateway/connectionmanager.go index 9f88b51e7b5..52734f9927f 100644 --- a/core/services/gateway/connectionmanager.go +++ b/core/services/gateway/connectionmanager.go @@ -157,7 +157,7 @@ func (m *connectionManager) Start(ctx context.Context) error { func (m *connectionManager) Close() error { return m.StopOnce("ConnectionManager", func() (err error) { m.lggr.Info("closing connection manager") - err = multierr.Combine(err, m.wsServer.Close()) + err = errors.Join(err, m.wsServer.Close()) for _, donConnMgr := range m.dons { close(donConnMgr.shutdownCh) for _, nodeState := range donConnMgr.nodes { diff --git a/core/services/gateway/gateway.go b/core/services/gateway/gateway.go index 79ddf0a5c69..7e0eaf9ea39 100644 --- a/core/services/gateway/gateway.go +++ b/core/services/gateway/gateway.go @@ -3,11 +3,10 @@ package gateway import ( "context" "encoding/json" + "errors" "fmt" "strings" - "go.uber.org/multierr" - "github.com/ethereum/go-ethereum/common" "github.com/prometheus/client_golang/prometheus" @@ -117,10 +116,10 @@ func (g *gateway) Start(ctx context.Context) error { func (g *gateway) Close() error { return g.StopOnce("Gateway", func() (err error) { g.lggr.Info("closing gateway") - err = multierr.Combine(err, g.httpServer.Close()) - err = multierr.Combine(err, g.connMgr.Close()) + err = errors.Join(err, g.httpServer.Close()) + err = errors.Join(err, g.connMgr.Close()) for _, handler := range g.handlers { - err = multierr.Combine(err, handler.Close()) + err = errors.Join(err, handler.Close()) } return }) diff --git a/core/services/gateway/handlers/functions/handler.functions.go b/core/services/gateway/handlers/functions/handler.functions.go index 2872c72f761..247f3fb99e8 100644 --- a/core/services/gateway/handlers/functions/handler.functions.go +++ b/core/services/gateway/handlers/functions/handler.functions.go @@ -13,7 +13,6 @@ import ( "github.com/jmoiron/sqlx" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/assets" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -374,10 +373,10 @@ func (h *functionsHandler) Close() error { return h.StopOnce("FunctionsHandler", func() (err error) { close(h.chStop) if h.allowlist != nil { - err = multierr.Combine(err, h.allowlist.Close()) + err = errors.Join(err, h.allowlist.Close()) } if h.subscriptions != nil { - err = multierr.Combine(err, h.subscriptions.Close()) + err = errors.Join(err, h.subscriptions.Close()) } return }) diff --git a/core/services/gateway/handlers/handler.dummy.go b/core/services/gateway/handlers/handler.dummy.go index 9cdd0865606..1a59b1d1da3 100644 --- a/core/services/gateway/handlers/handler.dummy.go +++ b/core/services/gateway/handlers/handler.dummy.go @@ -2,10 +2,9 @@ package handlers import ( "context" + "errors" "sync" - "go.uber.org/multierr" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/gateway/api" "github.com/smartcontractkit/chainlink/v2/core/services/gateway/config" @@ -45,7 +44,7 @@ func (d *dummyHandler) HandleUserMessage(ctx context.Context, msg *api.Message, var err error // Send to all nodes. for _, member := range d.donConfig.Members { - err = multierr.Combine(err, don.SendToNode(ctx, member.Address, msg)) + err = errors.Join(err, don.SendToNode(ctx, member.Address, msg)) } return err } diff --git a/core/services/job/orm.go b/core/services/job/orm.go index 82c6be2963c..ddec703d489 100644 --- a/core/services/job/orm.go +++ b/core/services/job/orm.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "encoding/json" + "errors" "fmt" "reflect" "slices" @@ -13,8 +14,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgconn" "github.com/lib/pq" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/jmoiron/sqlx" @@ -36,10 +36,10 @@ import ( ) var ( - ErrNoSuchKeyBundle = errors.New("no such key bundle exists") - ErrNoSuchTransmitterKey = errors.New("no such transmitter key exists") - ErrNoSuchSendingKey = errors.New("no such sending key exists") - ErrNoSuchPublicKey = errors.New("no such public key exists") + ErrNoSuchKeyBundle = pkgerrors.New("no such key bundle exists") + ErrNoSuchTransmitterKey = pkgerrors.New("no such transmitter key exists") + ErrNoSuchSendingKey = pkgerrors.New("no such sending key exists") + ErrNoSuchPublicKey = pkgerrors.New("no such public key exists") ) //go:generate mockery --quiet --name ORM --output ./mocks/ --case=underscore @@ -155,19 +155,19 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { switch jb.Type { case DirectRequest: if jb.DirectRequestSpec.EVMChainID == nil { - return errors.New("evm chain id must be defined") + return pkgerrors.New("evm chain id must be defined") } var specID int32 sql := `INSERT INTO direct_request_specs (contract_address, min_incoming_confirmations, requesters, min_contract_payment, evm_chain_id, created_at, updated_at) VALUES (:contract_address, :min_incoming_confirmations, :requesters, :min_contract_payment, :evm_chain_id, now(), now()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, jb.DirectRequestSpec); err != nil { - return errors.Wrap(err, "failed to create DirectRequestSpec") + return pkgerrors.Wrap(err, "failed to create DirectRequestSpec") } jb.DirectRequestSpecID = &specID case FluxMonitor: if jb.FluxMonitorSpec.EVMChainID == nil { - return errors.New("evm chain id must be defined") + return pkgerrors.New("evm chain id must be defined") } var specID int32 sql := `INSERT INTO flux_monitor_specs (contract_address, threshold, absolute_threshold, poll_timer_period, poll_timer_disabled, idle_timer_period, idle_timer_disabled, @@ -176,25 +176,25 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { :drumbeat_schedule, :drumbeat_random_delay, :drumbeat_enabled, :min_payment, :evm_chain_id, NOW(), NOW()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, jb.FluxMonitorSpec); err != nil { - return errors.Wrap(err, "failed to create FluxMonitorSpec") + return pkgerrors.Wrap(err, "failed to create FluxMonitorSpec") } jb.FluxMonitorSpecID = &specID case OffchainReporting: if jb.OCROracleSpec.EVMChainID == nil { - return errors.New("evm chain id must be defined") + return pkgerrors.New("evm chain id must be defined") } var specID int32 if jb.OCROracleSpec.EncryptedOCRKeyBundleID != nil { _, err := o.keyStore.OCR().Get(jb.OCROracleSpec.EncryptedOCRKeyBundleID.String()) if err != nil { - return errors.Wrapf(ErrNoSuchKeyBundle, "no key bundle with id: %x", jb.OCROracleSpec.EncryptedOCRKeyBundleID) + return pkgerrors.Wrapf(ErrNoSuchKeyBundle, "no key bundle with id: %x", jb.OCROracleSpec.EncryptedOCRKeyBundleID) } } if jb.OCROracleSpec.TransmitterAddress != nil { _, err := o.keyStore.Eth().Get(jb.OCROracleSpec.TransmitterAddress.Hex()) if err != nil { - return errors.Wrapf(ErrNoSuchTransmitterKey, "no key matching transmitter address: %s", jb.OCROracleSpec.TransmitterAddress.Hex()) + return pkgerrors.Wrapf(ErrNoSuchTransmitterKey, "no key matching transmitter address: %s", jb.OCROracleSpec.TransmitterAddress.Hex()) } } @@ -204,12 +204,12 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { jb.OCROracleSpec.ContractAddress, newChainID, ) - if !errors.Is(err, sql.ErrNoRows) { + if !pkgerrors.Is(err, sql.ErrNoRows) { if err != nil { - return errors.Wrap(err, "failed to validate OffchainreportingOracleSpec on creation") + return pkgerrors.Wrap(err, "failed to validate OffchainreportingOracleSpec on creation") } - return errors.Errorf("a job with contract address %s already exists for chain ID %s", jb.OCROracleSpec.ContractAddress, newChainID) + return pkgerrors.Errorf("a job with contract address %s already exists for chain ID %s", jb.OCROracleSpec.ContractAddress, newChainID) } sql := `INSERT INTO ocr_oracle_specs (contract_address, p2pv2_bootstrappers, is_bootstrap_peer, encrypted_ocr_key_bundle_id, transmitter_address, @@ -221,7 +221,7 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { RETURNING id;` err = pg.PrepareQueryRowx(tx, sql, &specID, jb.OCROracleSpec) if err != nil { - return errors.Wrap(err, "failed to create OffchainreportingOracleSpec") + return pkgerrors.Wrap(err, "failed to create OffchainreportingOracleSpec") } jb.OCROracleSpecID = &specID case OffchainReporting2: @@ -230,12 +230,12 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { if jb.OCR2OracleSpec.OCRKeyBundleID.Valid { _, err := o.keyStore.OCR2().Get(jb.OCR2OracleSpec.OCRKeyBundleID.String) if err != nil { - return errors.Wrapf(ErrNoSuchKeyBundle, "no key bundle with id: %q", jb.OCR2OracleSpec.OCRKeyBundleID.ValueOrZero()) + return pkgerrors.Wrapf(ErrNoSuchKeyBundle, "no key bundle with id: %q", jb.OCR2OracleSpec.OCRKeyBundleID.ValueOrZero()) } } if jb.OCR2OracleSpec.RelayConfig["sendingKeys"] != nil && jb.OCR2OracleSpec.TransmitterID.Valid { - return errors.New("sending keys and transmitter ID can't both be defined") + return pkgerrors.New("sending keys and transmitter ID can't both be defined") } // checks if they are present and if they are valid @@ -245,26 +245,26 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { } if !sendingKeysDefined && !jb.OCR2OracleSpec.TransmitterID.Valid { - return errors.New("neither sending keys nor transmitter ID is defined") + return pkgerrors.New("neither sending keys nor transmitter ID is defined") } if !sendingKeysDefined { if err = ValidateKeyStoreMatch(jb.OCR2OracleSpec, o.keyStore, jb.OCR2OracleSpec.TransmitterID.String); err != nil { - return errors.Wrap(ErrNoSuchTransmitterKey, err.Error()) + return pkgerrors.Wrap(ErrNoSuchTransmitterKey, err.Error()) } } if jb.ForwardingAllowed && !slices.Contains(ForwardersSupportedPlugins, jb.OCR2OracleSpec.PluginType) { - return errors.Errorf("forwarding is not currently supported for %s jobs", jb.OCR2OracleSpec.PluginType) + return pkgerrors.Errorf("forwarding is not currently supported for %s jobs", jb.OCR2OracleSpec.PluginType) } if jb.OCR2OracleSpec.PluginType == types.Mercury { if jb.OCR2OracleSpec.FeedID == nil { - return errors.New("feed ID is required for mercury plugin type") + return pkgerrors.New("feed ID is required for mercury plugin type") } } else { if jb.OCR2OracleSpec.FeedID != nil { - return errors.New("feed ID is not currently supported for non-mercury jobs") + return pkgerrors.New("feed ID is not currently supported for non-mercury jobs") } } @@ -272,7 +272,7 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { var cfg medianconfig.PluginConfig err2 := json.Unmarshal(jb.OCR2OracleSpec.PluginConfig.Bytes(), &cfg) if err2 != nil { - return errors.Wrap(err2, "failed to parse plugin config") + return pkgerrors.Wrap(err2, "failed to parse plugin config") } feePipeline, err2 := pipeline.Parse(cfg.JuelsPerFeeCoinPipeline) if err2 != nil { @@ -292,19 +292,19 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { RETURNING id;` err = pg.PrepareQueryRowx(tx, sql, &specID, jb.OCR2OracleSpec) if err != nil { - return errors.Wrap(err, "failed to create Offchainreporting2OracleSpec") + return pkgerrors.Wrap(err, "failed to create Offchainreporting2OracleSpec") } jb.OCR2OracleSpecID = &specID case Keeper: if jb.KeeperSpec.EVMChainID == nil { - return errors.New("evm chain id must be defined") + return pkgerrors.New("evm chain id must be defined") } var specID int32 sql := `INSERT INTO keeper_specs (contract_address, from_address, evm_chain_id, created_at, updated_at) VALUES (:contract_address, :from_address, :evm_chain_id, NOW(), NOW()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, jb.KeeperSpec); err != nil { - return errors.Wrap(err, "failed to create KeeperSpec") + return pkgerrors.Wrap(err, "failed to create KeeperSpec") } jb.KeeperSpecID = &specID case Cron: @@ -313,12 +313,12 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { VALUES (:cron_schedule, NOW(), NOW()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, jb.CronSpec); err != nil { - return errors.Wrap(err, "failed to create CronSpec") + return pkgerrors.Wrap(err, "failed to create CronSpec") } jb.CronSpecID = &specID case VRF: if jb.VRFSpec.EVMChainID == nil { - return errors.New("evm chain id must be defined") + return pkgerrors.New("evm chain id must be defined") } var specID int32 sql := `INSERT INTO vrf_specs ( @@ -339,20 +339,20 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { err := pg.PrepareQueryRowx(tx, sql, &specID, toVRFSpecRow(jb.VRFSpec)) var pqErr *pgconn.PgError - ok := errors.As(err, &pqErr) + ok := pkgerrors.As(err, &pqErr) if err != nil && ok && pqErr.Code == "23503" { if pqErr.ConstraintName == "vrf_specs_public_key_fkey" { - return errors.Wrapf(ErrNoSuchPublicKey, "%s", jb.VRFSpec.PublicKey.String()) + return pkgerrors.Wrapf(ErrNoSuchPublicKey, "%s", jb.VRFSpec.PublicKey.String()) } } if err != nil { - return errors.Wrap(err, "failed to create VRFSpec") + return pkgerrors.Wrap(err, "failed to create VRFSpec") } jb.VRFSpecID = &specID case Webhook: err := o.InsertWebhookSpec(jb.WebhookSpec, pg.WithQueryer(tx)) if err != nil { - return errors.Wrap(err, "failed to create WebhookSpec") + return pkgerrors.Wrap(err, "failed to create WebhookSpec") } jb.WebhookSpecID = &jb.WebhookSpec.ID @@ -364,58 +364,58 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { VALUES (:external_initiator_id, :webhook_spec_id, :spec);` query, args, err := tx.BindNamed(sql, jb.WebhookSpec.ExternalInitiatorWebhookSpecs) if err != nil { - return errors.Wrap(err, "failed to bindquery for ExternalInitiatorWebhookSpecs") + return pkgerrors.Wrap(err, "failed to bindquery for ExternalInitiatorWebhookSpecs") } if _, err = tx.Exec(query, args...); err != nil { - return errors.Wrap(err, "failed to create ExternalInitiatorWebhookSpecs") + return pkgerrors.Wrap(err, "failed to create ExternalInitiatorWebhookSpecs") } } case BlockhashStore: if jb.BlockhashStoreSpec.EVMChainID == nil { - return errors.New("evm chain id must be defined") + return pkgerrors.New("evm chain id must be defined") } var specID int32 sql := `INSERT INTO blockhash_store_specs (coordinator_v1_address, coordinator_v2_address, coordinator_v2_plus_address, trusted_blockhash_store_address, trusted_blockhash_store_batch_size, wait_blocks, lookback_blocks, heartbeat_period, blockhash_store_address, poll_period, run_timeout, evm_chain_id, from_addresses, created_at, updated_at) VALUES (:coordinator_v1_address, :coordinator_v2_address, :coordinator_v2_plus_address, :trusted_blockhash_store_address, :trusted_blockhash_store_batch_size, :wait_blocks, :lookback_blocks, :heartbeat_period, :blockhash_store_address, :poll_period, :run_timeout, :evm_chain_id, :from_addresses, NOW(), NOW()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, toBlockhashStoreSpecRow(jb.BlockhashStoreSpec)); err != nil { - return errors.Wrap(err, "failed to create BlockhashStore spec") + return pkgerrors.Wrap(err, "failed to create BlockhashStore spec") } jb.BlockhashStoreSpecID = &specID case BlockHeaderFeeder: if jb.BlockHeaderFeederSpec.EVMChainID == nil { - return errors.New("evm chain id must be defined") + return pkgerrors.New("evm chain id must be defined") } var specID int32 sql := `INSERT INTO block_header_feeder_specs (coordinator_v1_address, coordinator_v2_address, coordinator_v2_plus_address, wait_blocks, lookback_blocks, blockhash_store_address, batch_blockhash_store_address, poll_period, run_timeout, evm_chain_id, from_addresses, get_blockhashes_batch_size, store_blockhashes_batch_size, created_at, updated_at) VALUES (:coordinator_v1_address, :coordinator_v2_address, :coordinator_v2_plus_address, :wait_blocks, :lookback_blocks, :blockhash_store_address, :batch_blockhash_store_address, :poll_period, :run_timeout, :evm_chain_id, :from_addresses, :get_blockhashes_batch_size, :store_blockhashes_batch_size, NOW(), NOW()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, toBlockHeaderFeederSpecRow(jb.BlockHeaderFeederSpec)); err != nil { - return errors.Wrap(err, "failed to create BlockHeaderFeeder spec") + return pkgerrors.Wrap(err, "failed to create BlockHeaderFeeder spec") } jb.BlockHeaderFeederSpecID = &specID case LegacyGasStationServer: if jb.LegacyGasStationServerSpec.EVMChainID == nil { - return errors.New("evm chain id must be defined") + return pkgerrors.New("evm chain id must be defined") } var specID int32 sql := `INSERT INTO legacy_gas_station_server_specs (forwarder_address, evm_chain_id, ccip_chain_selector, from_addresses, created_at, updated_at) VALUES (:forwarder_address, :evm_chain_id, :ccip_chain_selector, :from_addresses, NOW(), NOW()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, toLegacyGasStationServerSpecRow(jb.LegacyGasStationServerSpec)); err != nil { - return errors.Wrap(err, "failed to create LegacyGasStationServer spec") + return pkgerrors.Wrap(err, "failed to create LegacyGasStationServer spec") } jb.LegacyGasStationServerSpecID = &specID case LegacyGasStationSidecar: if jb.LegacyGasStationSidecarSpec.EVMChainID == nil { - return errors.New("evm chain id must be defined") + return pkgerrors.New("evm chain id must be defined") } var specID int32 sql := `INSERT INTO legacy_gas_station_sidecar_specs (forwarder_address, off_ramp_address, lookback_blocks, poll_period, run_timeout, evm_chain_id, ccip_chain_selector, created_at, updated_at) VALUES (:forwarder_address, :off_ramp_address, :lookback_blocks, :poll_period, :run_timeout, :evm_chain_id, :ccip_chain_selector, NOW(), NOW()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, jb.LegacyGasStationSidecarSpec); err != nil { - return errors.Wrap(err, "failed to create LegacyGasStationSidecar spec") + return pkgerrors.Wrap(err, "failed to create LegacyGasStationSidecar spec") } jb.LegacyGasStationSidecarSpecID = &specID case Bootstrap: @@ -428,7 +428,7 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { :contract_config_confirmations, NOW(), NOW()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, jb.BootstrapSpec); err != nil { - return errors.Wrap(err, "failed to create BootstrapSpec for jobSpec") + return pkgerrors.Wrap(err, "failed to create BootstrapSpec for jobSpec") } jb.BootstrapSpecID = &specID case Gateway: @@ -437,7 +437,7 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { VALUES (:gateway_config, NOW(), NOW()) RETURNING id;` if err := pg.PrepareQueryRowx(tx, sql, &specID, jb.GatewaySpec); err != nil { - return errors.Wrap(err, "failed to create GatewaySpec for jobSpec") + return pkgerrors.Wrap(err, "failed to create GatewaySpec for jobSpec") } jb.GatewaySpecID = &specID case Stream: @@ -448,17 +448,17 @@ func (o *orm) CreateJob(jb *Job, qopts ...pg.QOpt) error { pipelineSpecID, err := o.pipelineORM.CreateSpec(p, jb.MaxTaskDuration, pg.WithQueryer(tx)) if err != nil { - return errors.Wrap(err, "failed to create pipeline spec") + return pkgerrors.Wrap(err, "failed to create pipeline spec") } jb.PipelineSpecID = pipelineSpecID err = o.InsertJob(jb, pg.WithQueryer(tx)) jobID = jb.ID - return errors.Wrap(err, "failed to insert job") + return pkgerrors.Wrap(err, "failed to insert job") }) if err != nil { - return errors.Wrap(err, "CreateJobFailed") + return pkgerrors.Wrap(err, "CreateJobFailed") } return o.findJob(jb, "id", jobID, qopts...) @@ -469,29 +469,29 @@ func ValidateKeyStoreMatch(spec *OCR2OracleSpec, keyStore keystore.Master, key s if spec.PluginType == types.Mercury { _, err := keyStore.CSA().Get(key) if err != nil { - return errors.Errorf("no CSA key matching: %q", key) + return pkgerrors.Errorf("no CSA key matching: %q", key) } } else { switch spec.Relay { case relay.EVM: _, err := keyStore.Eth().Get(key) if err != nil { - return errors.Errorf("no EVM key matching: %q", key) + return pkgerrors.Errorf("no EVM key matching: %q", key) } case relay.Cosmos: _, err := keyStore.Cosmos().Get(key) if err != nil { - return errors.Errorf("no Cosmos key matching: %q", key) + return pkgerrors.Errorf("no Cosmos key matching: %q", key) } case relay.Solana: _, err := keyStore.Solana().Get(key) if err != nil { - return errors.Errorf("no Solana key matching: %q", key) + return pkgerrors.Errorf("no Solana key matching: %q", key) } case relay.StarkNet: _, err := keyStore.StarkNet().Get(key) if err != nil { - return errors.Errorf("no Starknet key matching: %q", key) + return pkgerrors.Errorf("no Starknet key matching: %q", key) } } } @@ -507,7 +507,7 @@ func areSendingKeysDefined(jb *Job, keystore keystore.Master) (bool, error) { for _, sendingKey := range sendingKeys { if err = ValidateKeyStoreMatch(jb.OCR2OracleSpec, keystore, sendingKey); err != nil { - return false, errors.Wrap(ErrNoSuchSendingKey, err.Error()) + return false, pkgerrors.Wrap(ErrNoSuchSendingKey, err.Error()) } } @@ -614,11 +614,11 @@ func (o *orm) DeleteJob(id int32, qopts ...pg.QOpt) error { res, cancel, err := q.ExecQIter(query, id) defer cancel() if err != nil { - return errors.Wrap(err, "DeleteJob failed to delete job") + return pkgerrors.Wrap(err, "DeleteJob failed to delete job") } rowsAffected, err := res.RowsAffected() if err != nil { - return errors.Wrap(err, "DeleteJob failed getting RowsAffected") + return pkgerrors.Wrap(err, "DeleteJob failed getting RowsAffected") } if rowsAffected == 0 { return sql.ErrNoRows @@ -637,7 +637,7 @@ func (o *orm) RecordError(jobID int32, description string, qopts ...pg.QOpt) err err := q.ExecQ(sql, jobID, description, time.Now()) // Noop if the job has been deleted. var pqErr *pgconn.PgError - ok := errors.As(err, &pqErr) + ok := pkgerrors.As(err, &pqErr) if err != nil && ok && pqErr.Code == "23503" { if pqErr.ConstraintName == "job_spec_errors_v2_job_id_fkey" { return nil @@ -655,11 +655,11 @@ func (o *orm) DismissError(ctx context.Context, ID int64) error { res, cancel, err := q.ExecQIter("DELETE FROM job_spec_errors WHERE id = $1", ID) defer cancel() if err != nil { - return errors.Wrap(err, "failed to dismiss error") + return pkgerrors.Wrap(err, "failed to dismiss error") } n, err := res.RowsAffected() if err != nil { - return errors.Wrap(err, "failed to dismiss error") + return pkgerrors.Wrap(err, "failed to dismiss error") } if n == 0 { return sql.ErrNoRows @@ -673,7 +673,7 @@ func (o *orm) FindSpecError(id int64, qopts ...pg.QOpt) (SpecError, error) { specErr := new(SpecError) err := o.q.WithOpts(qopts...).Get(specErr, stmt, id) - return *specErr, errors.Wrap(err, "FindSpecError failed") + return *specErr, pkgerrors.Wrap(err, "FindSpecError failed") } func (o *orm) FindJobs(offset, limit int) (jobs []Job, count int, err error) { @@ -761,7 +761,7 @@ func LoadConfigVarsLocalOCR(evmOcrCfg evmconfig.OCR, os OCROracleSpec, ocrCfg OC func LoadConfigVarsOCR(evmOcrCfg evmconfig.OCR, ocrCfg OCRConfig, os OCROracleSpec) (*OCROracleSpec, error) { if os.TransmitterAddress == nil { ta, err := ocrCfg.TransmitterAddress() - if !errors.Is(errors.Cause(err), config.ErrEnvUnset) { + if !pkgerrors.Is(pkgerrors.Cause(err), config.ErrEnvUnset) { if err != nil { return nil, err } @@ -802,17 +802,17 @@ func (o *orm) FindJobWithoutSpecErrors(id int32) (jb Job, err error) { stmt := "SELECT * FROM jobs WHERE id = $1 LIMIT 1" err = tx.Get(&jb, stmt, id) if err != nil { - return errors.Wrap(err, "failed to load job") + return pkgerrors.Wrap(err, "failed to load job") } if err = LoadAllJobTypes(tx, &jb); err != nil { - return errors.Wrap(err, "failed to load job types") + return pkgerrors.Wrap(err, "failed to load job types") } return nil }, pg.OptReadOnlyTx()) if err != nil { - return jb, errors.Wrap(err, "FindJobWithoutSpecErrors failed") + return jb, pkgerrors.Wrap(err, "FindJobWithoutSpecErrors failed") } return jb, nil @@ -825,7 +825,7 @@ func (o *orm) FindSpecErrorsByJobIDs(ids []int32, qopts ...pg.QOpt) ([]SpecError var specErrs []SpecError err := o.q.WithOpts(qopts...).Select(&specErrs, stmt, ids) - return specErrs, errors.Wrap(err, "FindSpecErrorsByJobIDs failed") + return specErrs, pkgerrors.Wrap(err, "FindSpecErrorsByJobIDs failed") } func (o *orm) FindJobByExternalJobID(externalJobID uuid.UUID, qopts ...pg.QOpt) (jb Job, err error) { @@ -846,9 +846,9 @@ WHERE ocrspec.id IS NOT NULL OR fmspec.id IS NOT NULL ` err = tx.Get(&jobID, stmt, address, evmChainID) - if !errors.Is(err, sql.ErrNoRows) { + if !pkgerrors.Is(err, sql.ErrNoRows) { if err != nil { - return errors.Wrap(err, "error searching for job by contract address") + return pkgerrors.Wrap(err, "error searching for job by contract address") } return nil } @@ -856,7 +856,7 @@ WHERE ocrspec.id IS NOT NULL OR fmspec.id IS NOT NULL return err }) - return jobID, errors.Wrap(err, "FindJobIDByAddress failed") + return jobID, pkgerrors.Wrap(err, "FindJobIDByAddress failed") } func (o *orm) FindOCR2JobIDByAddress(contractID string, feedID *common.Hash, qopts ...pg.QOpt) (jobID int32, err error) { @@ -873,9 +873,9 @@ WHERE ocr2spec.id IS NOT NULL OR bs.id IS NOT NULL ` err = tx.Get(&jobID, stmt, contractID, feedID) - if !errors.Is(err, sql.ErrNoRows) { + if !pkgerrors.Is(err, sql.ErrNoRows) { if err != nil { - return errors.Wrapf(err, "error searching for job by contract id=%s and feed id=%s", contractID, feedID) + return pkgerrors.Wrapf(err, "error searching for job by contract id=%s and feed id=%s", contractID, feedID) } return nil } @@ -883,7 +883,7 @@ WHERE ocr2spec.id IS NOT NULL OR bs.id IS NOT NULL return err }) - return jobID, errors.Wrap(err, "FindOCR2JobIDByAddress failed") + return jobID, pkgerrors.Wrap(err, "FindOCR2JobIDByAddress failed") } func (o *orm) findJob(jb *Job, col string, arg interface{}, qopts ...pg.QOpt) error { @@ -892,7 +892,7 @@ func (o *orm) findJob(jb *Job, col string, arg interface{}, qopts ...pg.QOpt) er sql := fmt.Sprintf(`SELECT * FROM jobs WHERE %s = $1 LIMIT 1`, col) err := tx.Get(jb, sql, arg) if err != nil { - return errors.Wrap(err, "failed to load job") + return pkgerrors.Wrap(err, "failed to load job") } if err = LoadAllJobTypes(tx, jb); err != nil { @@ -902,7 +902,7 @@ func (o *orm) findJob(jb *Job, col string, arg interface{}, qopts ...pg.QOpt) er return loadJobSpecErrors(tx, jb) }) if err != nil { - return errors.Wrap(err, "findJob failed") + return pkgerrors.Wrap(err, "findJob failed") } return nil } @@ -932,7 +932,7 @@ func (o *orm) FindJobIDsWithBridge(name string) (jids []int32, err error) { var p *pipeline.Pipeline p, err = pipeline.Parse(sources[i]) if err != nil { - return errors.Wrapf(err, "could not parse dag for job %d", id) + return pkgerrors.Wrapf(err, "could not parse dag for job %d", id) } for _, task := range p.Tasks { if task.Type() == pipeline.TaskTypeBridge { @@ -944,7 +944,7 @@ func (o *orm) FindJobIDsWithBridge(name string) (jids []int32, err error) { } return nil }) - return jids, errors.Wrap(err, "FindJobIDsWithBridge failed") + return jids, pkgerrors.Wrap(err, "FindJobIDsWithBridge failed") } // PipelineRunsByJobsIDs returns pipeline runs for multiple jobs, not preloading data @@ -953,7 +953,7 @@ func (o *orm) PipelineRunsByJobsIDs(ids []int32) (runs []pipeline.Run, err error stmt := `SELECT pipeline_runs.* FROM pipeline_runs INNER JOIN jobs ON pipeline_runs.pipeline_spec_id = jobs.pipeline_spec_id WHERE jobs.id = ANY($1) ORDER BY pipeline_runs.created_at DESC, pipeline_runs.id DESC;` if err = tx.Select(&runs, stmt, ids); err != nil { - return errors.Wrap(err, "error loading runs") + return pkgerrors.Wrap(err, "error loading runs") } runs, err = o.loadPipelineRunsRelations(runs, tx) @@ -961,7 +961,7 @@ func (o *orm) PipelineRunsByJobsIDs(ids []int32) (runs []pipeline.Run, err error return err }) - return runs, errors.Wrap(err, "PipelineRunsByJobsIDs failed") + return runs, pkgerrors.Wrap(err, "PipelineRunsByJobsIDs failed") } func (o *orm) loadPipelineRunIDs(jobID *int32, offset, limit int, tx pg.Queryer) (ids []int64, err error) { @@ -969,7 +969,7 @@ func (o *orm) loadPipelineRunIDs(jobID *int32, offset, limit int, tx pg.Queryer) var res sql.NullInt64 if err = tx.Get(&res, "SELECT MAX(id) FROM pipeline_runs"); err != nil { - err = errors.Wrap(err, "error while loading runs") + err = pkgerrors.Wrap(err, "error while loading runs") return } else if !res.Valid { // MAX() will return NULL if there are no rows in table. This is not an error @@ -997,7 +997,7 @@ func (o *orm) loadPipelineRunIDs(jobID *int32, offset, limit int, tx pg.Queryer) var batch []int64 minID := maxID - n if err = tx.Select(&batch, stmt, offset, limit-len(ids), minID, maxID); err != nil { - err = errors.Wrap(err, "error loading runs") + err = pkgerrors.Wrap(err, "error loading runs") return } ids = append(ids, batch...) @@ -1015,13 +1015,13 @@ func (o *orm) loadPipelineRunIDs(jobID *int32, offset, limit int, tx pg.Queryer) ), minID, maxID, ) if err != nil { - err = errors.Wrap(err, "error loading from pipeline_runs") + err = pkgerrors.Wrap(err, "error loading from pipeline_runs") return } offset -= skipped if offset < 0 { // sanity assertion, if this ever happened it would probably mean db corruption or pg bug lggr.AssumptionViolationw("offset < 0 while reading pipeline_runs") - err = errors.Wrap(err, "internal db error while reading pipeline_runs") + err = pkgerrors.Wrap(err, "internal db error while reading pipeline_runs") return } lggr.Debugw("loadPipelineRunIDs empty batch", "minId", minID, "maxID", maxID, "n", n, "len(ids)", len(ids), "limit", limit, "offset", offset, "skipped", skipped) @@ -1050,7 +1050,7 @@ func (o *orm) FindTaskResultByRunIDAndTaskName(runID int64, taskName string, qop } taskRun := taskRuns[0] if !taskRun.Error.IsZero() { - return errors.New(taskRun.Error.ValueOrZero()) + return pkgerrors.New(taskRun.Error.ValueOrZero()) } resBytes, errB := taskRun.Output.MarshalJSON() if errB != nil { @@ -1059,7 +1059,7 @@ func (o *orm) FindTaskResultByRunIDAndTaskName(runID int64, taskName string, qop result = resBytes return nil }) - return result, errors.Wrap(err, "failed") + return result, pkgerrors.Wrap(err, "failed") } // FindPipelineRunIDsByJobID fetches the ids of pipeline runs for a job. @@ -1068,7 +1068,7 @@ func (o *orm) FindPipelineRunIDsByJobID(jobID int32, offset, limit int) (ids []i ids, err = o.loadPipelineRunIDs(&jobID, offset, limit, tx) return err }) - return ids, errors.Wrap(err, "FindPipelineRunIDsByJobID failed") + return ids, pkgerrors.Wrap(err, "FindPipelineRunIDsByJobID failed") } func (o *orm) loadPipelineRunsByID(ids []int64, tx pg.Queryer) (runs []pipeline.Run, err error) { @@ -1079,7 +1079,7 @@ func (o *orm) loadPipelineRunsByID(ids []int64, tx pg.Queryer) (runs []pipeline. ORDER BY created_at DESC, id DESC ` if err = tx.Select(&runs, stmt, ids); err != nil { - err = errors.Wrap(err, "error loading runs") + err = pkgerrors.Wrap(err, "error loading runs") return } @@ -1093,7 +1093,7 @@ func (o *orm) FindPipelineRunsByIDs(ids []int64) (runs []pipeline.Run, err error return err }) - return runs, errors.Wrap(err, "FindPipelineRunsByIDs failed") + return runs, pkgerrors.Wrap(err, "FindPipelineRunsByIDs failed") } // FindPipelineRunByID returns pipeline run with the id. @@ -1108,7 +1108,7 @@ WHERE id = $1 ` if err := tx.Get(&run, stmt, id); err != nil { - return errors.Wrap(err, "error loading run") + return pkgerrors.Wrap(err, "error loading run") } runs, err := o.loadPipelineRunsRelations([]pipeline.Run{run}, tx) @@ -1118,7 +1118,7 @@ WHERE id = $1 return err }) - return run, errors.Wrap(err, "FindPipelineRunByID failed") + return run, pkgerrors.Wrap(err, "FindPipelineRunByID failed") } // CountPipelineRunsByJobID returns the total number of pipeline runs for a job. @@ -1126,13 +1126,13 @@ func (o *orm) CountPipelineRunsByJobID(jobID int32) (count int32, err error) { err = o.q.Transaction(func(tx pg.Queryer) error { stmt := "SELECT COUNT(*) FROM pipeline_runs JOIN jobs USING (pipeline_spec_id) WHERE jobs.id = $1" if err = tx.Get(&count, stmt, jobID); err != nil { - return errors.Wrap(err, "error counting runs") + return pkgerrors.Wrap(err, "error counting runs") } return err }) - return count, errors.Wrap(err, "CountPipelineRunsByJobID failed") + return count, pkgerrors.Wrap(err, "CountPipelineRunsByJobID failed") } func (o *orm) FindJobsByPipelineSpecIDs(ids []int32) ([]Job, error) { @@ -1142,7 +1142,7 @@ func (o *orm) FindJobsByPipelineSpecIDs(ids []int32) ([]Job, error) { stmt := `SELECT * FROM jobs WHERE jobs.pipeline_spec_id = ANY($1) ORDER BY id ASC ` if err := tx.Select(&jbs, stmt, ids); err != nil { - return errors.Wrap(err, "error fetching jobs by pipeline spec IDs") + return pkgerrors.Wrap(err, "error fetching jobs by pipeline spec IDs") } err := LoadAllJobsTypes(tx, jbs) @@ -1153,7 +1153,7 @@ func (o *orm) FindJobsByPipelineSpecIDs(ids []int32) ([]Job, error) { return nil }) - return jbs, errors.Wrap(err, "FindJobsByPipelineSpecIDs failed") + return jbs, pkgerrors.Wrap(err, "FindJobsByPipelineSpecIDs failed") } // PipelineRuns returns pipeline runs for a job, with spec and taskruns loaded, latest first @@ -1166,7 +1166,7 @@ func (o *orm) PipelineRuns(jobID *int32, offset, size int) (runs []pipeline.Run, err = o.q.Transaction(func(tx pg.Queryer) error { sql := fmt.Sprintf(`SELECT count(*) FROM pipeline_runs %s`, filter) if err = tx.QueryRowx(sql).Scan(&count); err != nil { - return errors.Wrap(err, "error counting runs") + return pkgerrors.Wrap(err, "error counting runs") } var ids []int64 @@ -1176,7 +1176,7 @@ func (o *orm) PipelineRuns(jobID *int32, offset, size int) (runs []pipeline.Run, return err }) - return runs, count, errors.Wrap(err, "PipelineRuns failed") + return runs, count, pkgerrors.Wrap(err, "PipelineRuns failed") } func (o *orm) loadPipelineRunsRelations(runs []pipeline.Run, tx pg.Queryer) ([]pipeline.Run, error) { @@ -1195,7 +1195,7 @@ func (o *orm) loadPipelineRunsRelations(runs []pipeline.Run, tx pg.Queryer) ([]p stmt := `SELECT pipeline_specs.*, jobs.id AS job_id FROM pipeline_specs JOIN jobs ON pipeline_specs.id = jobs.pipeline_spec_id WHERE pipeline_specs.id = ANY($1);` var specs []pipeline.Spec if err := o.q.Select(&specs, stmt, specIDs); err != nil { - return nil, errors.Wrap(err, "error loading specs") + return nil, pkgerrors.Wrap(err, "error loading specs") } for _, spec := range specs { specM[spec.ID] = spec @@ -1214,7 +1214,7 @@ func (o *orm) loadPipelineRunsRelations(runs []pipeline.Run, tx pg.Queryer) ([]p var taskRuns []pipeline.TaskRun stmt = `SELECT * FROM pipeline_task_runs WHERE pipeline_run_id = ANY($1) ORDER BY pipeline_run_id, created_at, id;` if err := tx.Select(&taskRuns, stmt, runIDs); err != nil { - return nil, errors.Wrap(err, "error loading pipeline_task_runs") + return nil, pkgerrors.Wrap(err, "error loading pipeline_task_runs") } for _, taskRun := range taskRuns { run := runM[taskRun.PipelineRunID] @@ -1238,7 +1238,7 @@ func LoadAllJobsTypes(tx pg.Queryer, jobs []Job) error { } func LoadAllJobTypes(tx pg.Queryer, job *Job) error { - return multierr.Combine( + return errors.Join( loadJobType(tx, job, "PipelineSpec", "pipeline_specs", &job.PipelineSpecID), loadJobType(tx, job, "FluxMonitorSpec", "flux_monitor_specs", job.FluxMonitorSpecID), loadJobType(tx, job, "DirectRequestSpec", "direct_request_specs", job.DirectRequestSpecID), @@ -1273,7 +1273,7 @@ func loadJobType(tx pg.Queryer, job *Job, field, table string, id *int32) error err := tx.Get(dest, fmt.Sprintf(`SELECT * FROM %s WHERE id = $1`, table), *id) if err != nil { - return errors.Wrapf(err, "failed to load job type %s with id %d", table, *id) + return pkgerrors.Wrapf(err, "failed to load job type %s with id %d", table, *id) } reflect.ValueOf(job).Elem().FieldByName(field).Set(destVal) return nil @@ -1287,7 +1287,7 @@ func loadVRFJob(tx pg.Queryer, job *Job, id *int32) error { var row vrfSpecRow err := tx.Get(&row, `SELECT * FROM vrf_specs WHERE id = $1`, *id) if err != nil { - return errors.Wrapf(err, `failed to load job type VRFSpec with id %d`, *id) + return pkgerrors.Wrapf(err, `failed to load job type VRFSpec with id %d`, *id) } job.VRFSpec = row.toVRFSpec() @@ -1326,7 +1326,7 @@ func loadBlockhashStoreJob(tx pg.Queryer, job *Job, id *int32) error { var row blockhashStoreSpecRow err := tx.Get(&row, `SELECT * FROM blockhash_store_specs WHERE id = $1`, *id) if err != nil { - return errors.Wrapf(err, `failed to load job type BlockhashStoreSpec with id %d`, *id) + return pkgerrors.Wrapf(err, `failed to load job type BlockhashStoreSpec with id %d`, *id) } job.BlockhashStoreSpec = row.toBlockhashStoreSpec() @@ -1365,7 +1365,7 @@ func loadBlockHeaderFeederJob(tx pg.Queryer, job *Job, id *int32) error { var row blockHeaderFeederSpecRow err := tx.Get(&row, `SELECT * FROM block_header_feeder_specs WHERE id = $1`, *id) if err != nil { - return errors.Wrapf(err, `failed to load job type BlockHeaderFeederSpec with id %d`, *id) + return pkgerrors.Wrapf(err, `failed to load job type BlockHeaderFeederSpec with id %d`, *id) } job.BlockHeaderFeederSpec = row.toBlockHeaderFeederSpec() @@ -1404,7 +1404,7 @@ func loadLegacyGasStationServerJob(tx pg.Queryer, job *Job, id *int32) error { var row legacyGasStationServerSpecRow err := tx.Get(&row, `SELECT * FROM legacy_gas_station_server_specs WHERE id = $1`, *id) if err != nil { - return errors.Wrapf(err, `failed to load job type LegacyGasStationServerSpec with id %d`, *id) + return pkgerrors.Wrapf(err, `failed to load job type LegacyGasStationServerSpec with id %d`, *id) } job.LegacyGasStationServerSpec = row.toLegacyGasStationServerSpec() @@ -1436,5 +1436,5 @@ func (r legacyGasStationServerSpecRow) toLegacyGasStationServerSpec() *LegacyGas } func loadJobSpecErrors(tx pg.Queryer, jb *Job) error { - return errors.Wrapf(tx.Select(&jb.JobSpecErrors, `SELECT * FROM job_spec_errors WHERE job_id = $1`, jb.ID), "failed to load job spec errors for job %d", jb.ID) + return pkgerrors.Wrapf(tx.Select(&jb.JobSpecErrors, `SELECT * FROM job_spec_errors WHERE job_id = $1`, jb.ID), "failed to load job spec errors for job %d", jb.ID) } diff --git a/core/services/ocr/database.go b/core/services/ocr/database.go index 977c371c15d..53d5611f7c0 100644 --- a/core/services/ocr/database.go +++ b/core/services/ocr/database.go @@ -4,12 +4,12 @@ import ( "context" "database/sql" "encoding/json" + "errors" "time" "github.com/ethereum/go-ethereum/common" "github.com/lib/pq" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/jmoiron/sqlx" "github.com/smartcontractkit/libocr/gethwrappers/offchainaggregator" @@ -55,11 +55,11 @@ func (d *db) ReadState(ctx context.Context, cd ocrtypes.ConfigDigest) (ps *ocrty var highestSentEpochTmp int64 err = d.q.QueryRowxContext(ctx, stmt, d.oracleSpecID, cd).Scan(&ps.Epoch, &highestSentEpochTmp, pq.Array(&tmp)) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } if err != nil { - return nil, errors.Wrap(err, "ReadState failed") + return nil, pkgerrors.Wrap(err, "ReadState failed") } ps.HighestSentEpoch = uint32(highestSentEpochTmp) @@ -94,7 +94,7 @@ func (d *db) WriteState(ctx context.Context, cd ocrtypes.ConfigDigest, state ocr ctx, stmt, d.oracleSpecID, cd, state.Epoch, state.HighestSentEpoch, pq.Array(&highestReceivedEpoch), ) - return errors.Wrap(err, "WriteState failed") + return pkgerrors.Wrap(err, "WriteState failed") } func (d *db) ReadConfig(ctx context.Context) (c *ocrtypes.ContractConfig, err error) { @@ -117,11 +117,11 @@ func (d *db) ReadConfig(ctx context.Context) (c *ocrtypes.ContractConfig, err er &c.EncodedConfigVersion, &c.Encoded, ) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } if err != nil { - return nil, errors.Wrap(err, "ReadConfig failed") + return nil, pkgerrors.Wrap(err, "ReadConfig failed") } for _, s := range signers { @@ -157,7 +157,7 @@ func (d *db) WriteConfig(ctx context.Context, c ocrtypes.ContractConfig) error { ` _, err := d.q.ExecContext(ctx, stmt, d.oracleSpecID, c.ConfigDigest, pq.ByteaArray(signers), pq.ByteaArray(transmitters), c.Threshold, int(c.EncodedConfigVersion), c.Encoded) - return errors.Wrap(err, "WriteConfig failed") + return pkgerrors.Wrap(err, "WriteConfig failed") } func (d *db) StorePendingTransmission(ctx context.Context, k ocrtypes.ReportTimestamp, p ocrtypes.PendingTransmission) error { @@ -203,7 +203,7 @@ func (d *db) StorePendingTransmission(ctx context.Context, k ocrtypes.ReportTime _, err := d.q.ExecContext(ctx, stmt, d.oracleSpecID, k.ConfigDigest, k.Epoch, k.Round, p.Time, median, p.SerializedReport, pq.ByteaArray(rs), pq.ByteaArray(ss), p.Vs[:]) - return errors.Wrap(err, "StorePendingTransmission failed") + return pkgerrors.Wrap(err, "StorePendingTransmission failed") } func (d *db) PendingTransmissionsWithConfigDigest(ctx context.Context, cd ocrtypes.ConfigDigest) (map[ocrtypes.ReportTimestamp]ocrtypes.PendingTransmission, error) { @@ -223,7 +223,7 @@ FROM ocr_pending_transmissions WHERE ocr_oracle_spec_id = $1 AND config_digest = $2 `, d.oracleSpecID, cd) if err != nil { - return nil, errors.Wrap(err, "PendingTransmissionsWithConfigDigest failed to query rows") + return nil, pkgerrors.Wrap(err, "PendingTransmissionsWithConfigDigest failed to query rows") } defer d.lggr.ErrorIfFn(rows.Close, "Error closing ocr_pending_transmissions rows") @@ -238,25 +238,25 @@ WHERE ocr_oracle_spec_id = $1 AND config_digest = $2 var ss [][]byte var vs []byte if err := rows.Scan(&k.ConfigDigest, &k.Epoch, &k.Round, &p.Time, &median, &p.SerializedReport, (*pq.ByteaArray)(&rs), (*pq.ByteaArray)(&ss), &vs); err != nil { - return nil, errors.Wrap(err, "PendingTransmissionsWithConfigDigest failed to scan row") + return nil, pkgerrors.Wrap(err, "PendingTransmissionsWithConfigDigest failed to scan row") } p.Median = median.ToInt() for i, v := range rs { var r [32]byte if n := copy(r[:], v); n != 32 { - return nil, errors.Errorf("expected 32 bytes for rs value at index %v, got %v bytes", i, n) + return nil, pkgerrors.Errorf("expected 32 bytes for rs value at index %v, got %v bytes", i, n) } p.Rs = append(p.Rs, r) } for i, v := range ss { var s [32]byte if n := copy(s[:], v); n != 32 { - return nil, errors.Errorf("expected 32 bytes for ss value at index %v, got %v bytes", i, n) + return nil, pkgerrors.Errorf("expected 32 bytes for ss value at index %v, got %v bytes", i, n) } p.Ss = append(p.Ss, s) } if n := copy(p.Vs[:], vs); n != 32 { - return nil, errors.Errorf("expected 32 bytes for vs, got %v bytes", n) + return nil, pkgerrors.Errorf("expected 32 bytes for vs, got %v bytes", n) } m[k] = p } @@ -274,7 +274,7 @@ DELETE FROM ocr_pending_transmissions WHERE ocr_oracle_spec_id = $1 AND config_digest = $2 AND epoch = $3 AND round = $4 `, d.oracleSpecID, k.ConfigDigest, k.Epoch, k.Round) - err = errors.Wrap(err, "DeletePendingTransmission failed") + err = pkgerrors.Wrap(err, "DeletePendingTransmission failed") return } @@ -285,7 +285,7 @@ DELETE FROM ocr_pending_transmissions WHERE ocr_oracle_spec_id = $1 AND time < $2 `, d.oracleSpecID, t) - err = errors.Wrap(err, "DeletePendingTransmissionsOlderThan failed") + err = pkgerrors.Wrap(err, "DeletePendingTransmissionsOlderThan failed") return } @@ -293,7 +293,7 @@ WHERE ocr_oracle_spec_id = $1 AND time < $2 func (d *db) SaveLatestRoundRequested(tx pg.Queryer, rr offchainaggregator.OffchainAggregatorRoundRequested) error { rawLog, err := json.Marshal(rr.Raw) if err != nil { - return errors.Wrap(err, "could not marshal log as JSON") + return pkgerrors.Wrap(err, "could not marshal log as JSON") } _, err = tx.Exec(` INSERT INTO ocr_latest_round_requested (ocr_oracle_spec_id, requester, config_digest, epoch, round, raw) @@ -305,7 +305,7 @@ VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (ocr_oracle_spec_id) DO UPDATE SET raw = EXCLUDED.raw `, d.oracleSpecID, rr.Requester, rr.ConfigDigest[:], rr.Epoch, rr.Round, rawLog) - return errors.Wrap(err, "could not save latest round requested") + return pkgerrors.Wrap(err, "could not save latest round requested") } func (d *db) LoadLatestRoundRequested() (rr offchainaggregator.OffchainAggregatorRoundRequested, err error) { @@ -316,9 +316,9 @@ WHERE ocr_oracle_spec_id = $1 LIMIT 1 `, d.oracleSpecID) if err != nil { - return rr, errors.Wrap(err, "LoadLatestRoundRequested failed to query rows") + return rr, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to query rows") } - defer func() { err = multierr.Combine(err, rows.Close()) }() + defer func() { err = errors.Join(err, rows.Close()) }() for rows.Next() { var configDigest []byte @@ -326,13 +326,13 @@ LIMIT 1 var err2 error err2 = rows.Scan(&rr.Requester, &configDigest, &rr.Epoch, &rr.Round, &rawLog) - err = multierr.Combine(err2, errors.Wrap(err, "LoadLatestRoundRequested failed to scan row")) + err = errors.Join(err2, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to scan row")) rr.ConfigDigest, err2 = ocrtypes.BytesToConfigDigest(configDigest) - err = multierr.Combine(err2, errors.Wrap(err, "LoadLatestRoundRequested failed to decode config digest")) + err = errors.Join(err2, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to decode config digest")) err2 = json.Unmarshal(rawLog, &rr.Raw) - err = multierr.Combine(err2, errors.Wrap(err, "LoadLatestRoundRequested failed to unmarshal raw log")) + err = errors.Join(err2, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to unmarshal raw log")) } if err = rows.Err(); err != nil { diff --git a/core/services/ocr2/plugins/s4/integration_test.go b/core/services/ocr2/plugins/s4/integration_test.go index 8efe38f8e2d..e027793b59a 100644 --- a/core/services/ocr2/plugins/s4/integration_test.go +++ b/core/services/ocr2/plugins/s4/integration_test.go @@ -3,6 +3,7 @@ package s4_test import ( "context" "crypto/ecdsa" + "errors" "fmt" "maps" "math/rand" @@ -26,7 +27,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.uber.org/multierr" ) // Disclaimer: this is not a true integration test, it's more of a S4 feature test, on purpose. @@ -72,14 +72,14 @@ func newDON(t *testing.T, size int, config *s4.PluginConfig) *don { } func (d *don) simulateOCR(ctx context.Context, rounds int) []error { - errors := make([]error, d.size) + errs := make([]error, d.size) for i := 0; i < rounds && ctx.Err() == nil; i++ { leaderIndex := i % d.size leader := d.plugins[leaderIndex] query, err := leader.Query(ctx, types.ReportTimestamp{}) if err != nil { - errors[leaderIndex] = multierr.Combine(errors[leaderIndex], err) + errs[leaderIndex] = errors.Join(errs[leaderIndex], err) continue } @@ -87,7 +87,7 @@ func (d *don) simulateOCR(ctx context.Context, rounds int) []error { for i := 0; i < d.size; i++ { observation, err2 := d.plugins[i].Observation(ctx, types.ReportTimestamp{}, query) if err2 != nil { - errors[i] = multierr.Combine(errors[i], err2) + errs[i] = errors.Join(errs[i], err2) continue } aos = append(aos, types.AttributedObservation{ @@ -101,17 +101,17 @@ func (d *don) simulateOCR(ctx context.Context, rounds int) []error { _, report, err := leader.Report(ctx, types.ReportTimestamp{}, query, aos) if err != nil { - errors[leaderIndex] = multierr.Combine(errors[leaderIndex], err) + errs[leaderIndex] = errors.Join(errs[leaderIndex], err) continue } for i := 0; i < d.size; i++ { _, err2 := d.plugins[i].ShouldAcceptFinalizedReport(ctx, types.ReportTimestamp{}, report) - errors[i] = multierr.Combine(errors[i], err2) + errs[i] = errors.Join(errs[i], err2) } } - return errors + return errs } func compareSnapshots(s1, s2 []*s4_svc.SnapshotRow) bool { diff --git a/core/services/ocrcommon/discoverer_database.go b/core/services/ocrcommon/discoverer_database.go index 9413b11ad07..2f1cc6829e8 100644 --- a/core/services/ocrcommon/discoverer_database.go +++ b/core/services/ocrcommon/discoverer_database.go @@ -3,10 +3,10 @@ package ocrcommon import ( "context" "database/sql" + "errors" "github.com/lib/pq" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" ocrnetworking "github.com/smartcontractkit/libocr/networking/types" ) @@ -34,7 +34,7 @@ VALUES ($1,$2,$3,NOW(),NOW()) ON CONFLICT (local_peer_id, remote_peer_id) DO UPD ann = EXCLUDED.ann, updated_at = EXCLUDED.updated_at ;`, d.peerID, peerID, ann) - return errors.Wrap(err, "DiscovererDatabase failed to StoreAnnouncement") + return pkgerrors.Wrap(err, "DiscovererDatabase failed to StoreAnnouncement") } // ReadAnnouncements returns one serialized announcement (if available) for each of the peerIDs in the form of a map @@ -43,9 +43,9 @@ func (d *DiscovererDatabase) ReadAnnouncements(ctx context.Context, peerIDs []st rows, err := d.db.QueryContext(ctx, ` SELECT remote_peer_id, ann FROM ocr_discoverer_announcements WHERE remote_peer_id = ANY($1) AND local_peer_id = $2`, pq.Array(peerIDs), d.peerID) if err != nil { - return nil, errors.Wrap(err, "DiscovererDatabase failed to ReadAnnouncements") + return nil, pkgerrors.Wrap(err, "DiscovererDatabase failed to ReadAnnouncements") } - defer func() { err = multierr.Combine(err, rows.Close()) }() + defer func() { err = errors.Join(err, rows.Close()) }() results = make(map[string][]byte) for rows.Next() { var peerID string diff --git a/core/services/pg/lease_lock.go b/core/services/pg/lease_lock.go index 58ec2781245..60f9162af44 100644 --- a/core/services/pg/lease_lock.go +++ b/core/services/pg/lease_lock.go @@ -3,14 +3,14 @@ package pg import ( "context" "database/sql" + "errors" "fmt" "sync" "time" "github.com/google/uuid" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/logger" @@ -98,11 +98,11 @@ func (l *leaseLock) TakeAndHold(ctx context.Context) (err error) { defer cancel() if l.conn == nil { if err = l.checkoutConn(qctx); err != nil { - return errors.Wrap(err, "lease lock failed to checkout initial connection") + return pkgerrors.Wrap(err, "lease lock failed to checkout initial connection") } } gotLease, err = l.getLease(qctx, isInitial) - if errors.Is(err, sql.ErrConnDone) { + if pkgerrors.Is(err, sql.ErrConnDone) { l.logger.Warnw("DB connection was unexpectedly closed; checking out a new one", "err", err) l.conn = nil return err @@ -110,12 +110,12 @@ func (l *leaseLock) TakeAndHold(ctx context.Context) (err error) { return nil }() - if errors.Is(err, sql.ErrConnDone) { + if pkgerrors.Is(err, sql.ErrConnDone) { continue } else if err != nil { - err = errors.Wrap(err, "failed to get lease lock") + err = pkgerrors.Wrap(err, "failed to get lease lock") if l.conn != nil { - err = multierr.Combine(err, l.conn.Close()) + err = errors.Join(err, l.conn.Close()) } return err } @@ -127,9 +127,9 @@ func (l *leaseLock) TakeAndHold(ctx context.Context) (err error) { retryCount++ select { case <-ctx.Done(): - err = errors.New("stopped") + err = pkgerrors.New("stopped") if l.conn != nil { - err = multierr.Combine(err, l.conn.Close()) + err = errors.Join(err, l.conn.Close()) } return err case <-time.After(utils.WithJitter(l.cfg.LeaseRefreshInterval)): @@ -159,12 +159,12 @@ func (l *leaseLock) Release() { func (l *leaseLock) checkoutConn(ctx context.Context) (err error) { newConn, err := l.db.Connx(ctx) if err != nil { - return errors.Wrap(err, "failed checking out connection from pool") + return pkgerrors.Wrap(err, "failed checking out connection from pool") } l.conn = newConn if err = l.setInitialTimeouts(ctx); err != nil { - return multierr.Combine( - errors.Wrap(err, "failed to set initial timeouts"), + return errors.Join( + pkgerrors.Wrap(err, "failed to set initial timeouts"), l.conn.Close(), ) } @@ -177,7 +177,7 @@ func (l *leaseLock) setInitialTimeouts(ctx context.Context) error { // the transaction - we do not want to leave rows locked if this process is // dead ms := l.cfg.LeaseDuration.Milliseconds() - return multierr.Combine( + return errors.Join( utils.JustError(l.conn.ExecContext(ctx, fmt.Sprintf(`SET SESSION lock_timeout = %d`, ms))), utils.JustError(l.conn.ExecContext(ctx, fmt.Sprintf(`SET SESSION idle_in_transaction_session_timeout = %d`, ms))), ) @@ -199,7 +199,7 @@ func (l *leaseLock) loop(ctx context.Context) { select { case <-ctx.Done(): qctx, cancel := context.WithTimeout(context.Background(), l.cfg.DefaultQueryTimeout) - err := multierr.Combine( + err := errors.Join( utils.JustError(l.conn.ExecContext(qctx, `UPDATE lease_lock SET expires_at=NOW() WHERE client_id = $1 AND expires_at > NOW()`, l.id)), l.conn.Close(), ) @@ -211,7 +211,7 @@ func (l *leaseLock) loop(ctx context.Context) { case <-refresh.C: qctx, cancel := context.WithTimeout(ctx, l.cfg.LeaseDuration) gotLease, err := l.getLease(qctx, false) - if errors.Is(err, sql.ErrConnDone) { + if pkgerrors.Is(err, sql.ErrConnDone) { l.logger.Warnw("DB connection was unexpectedly closed; checking out a new one", "err", err) if err = l.checkoutConn(ctx); err != nil { l.logger.Warnw("Error trying to refresh connection", "err", err) @@ -252,7 +252,7 @@ func (l *leaseLock) getLease(ctx context.Context, isInitial bool) (gotLease bool if isInitial { for _, query := range initialSQL { if _, err = tx.Exec(query); err != nil { - return errors.Wrap(err, "failed to create initial lease_lock table") + return pkgerrors.Wrap(err, "failed to create initial lease_lock table") } } } @@ -269,19 +269,19 @@ OR lease_lock.expires_at < NOW() `, l.id, leaseDuration) if err != nil { - return errors.Wrap(err, "failed to upsert lease_lock") + return pkgerrors.Wrap(err, "failed to upsert lease_lock") } var rowsAffected int64 rowsAffected, err = res.RowsAffected() if err != nil { - return errors.Wrap(err, "failed to get RowsAffected for lease lock upsert") + return pkgerrors.Wrap(err, "failed to get RowsAffected for lease lock upsert") } if rowsAffected > 0 { gotLease = true } return nil }) - return gotLease, errors.Wrap(err, "leaseLock#GetLease failed") + return gotLease, pkgerrors.Wrap(err, "leaseLock#GetLease failed") } func (l *leaseLock) ClientID() uuid.UUID { diff --git a/core/services/pg/transaction.go b/core/services/pg/transaction.go index fd7e74baca3..c51c4e79dcc 100644 --- a/core/services/pg/transaction.go +++ b/core/services/pg/transaction.go @@ -3,13 +3,13 @@ package pg import ( "context" "database/sql" + "errors" "fmt" "time" "github.com/getsentry/sentry-go" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" corelogger "github.com/smartcontractkit/chainlink/v2/core/logger" @@ -54,7 +54,7 @@ func sqlxTransactionQ(ctx context.Context, db txBeginner, lggr logger.Logger, fn var tx *sqlx.Tx tx, err = db.BeginTxx(ctx, &txOpts) if err != nil { - return errors.Wrap(err, "failed to begin transaction") + return pkgerrors.Wrap(err, "failed to begin transaction") } defer func() { @@ -81,11 +81,11 @@ func sqlxTransactionQ(ctx context.Context, db txBeginner, lggr logger.Logger, fn lggr.Errorf("Error in transaction, rolling back: %s", err) // An error occurred, rollback and return error if rerr := tx.Rollback(); rerr != nil { - err = multierr.Combine(err, errors.WithStack(rerr)) + err = errors.Join(err, pkgerrors.WithStack(rerr)) } } else { // All good! Time to commit. - err = errors.WithStack(tx.Commit()) + err = pkgerrors.WithStack(tx.Commit()) } }() diff --git a/core/services/pipeline/models.go b/core/services/pipeline/models.go index d2c722f98b8..e797e0d9364 100644 --- a/core/services/pipeline/models.go +++ b/core/services/pipeline/models.go @@ -3,15 +3,15 @@ package pipeline import ( "database/sql/driver" "encoding/json" + "errors" "fmt" "math/big" "strconv" "time" "github.com/google/uuid" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" - "go.uber.org/multierr" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink/v2/core/store/models" @@ -205,7 +205,7 @@ func (re *RunErrors) Scan(value interface{}) error { } bytes, ok := value.([]byte) if !ok { - return errors.Errorf("RunErrors#Scan received a value of type %T", value) + return pkgerrors.Errorf("RunErrors#Scan received a value of type %T", value) } return json.Unmarshal(bytes, re) } @@ -231,7 +231,7 @@ func (re RunErrors) HasError() bool { func (re RunErrors) ToError() error { toErr := func(ns null.String) error { if !ns.IsZero() { - return errors.New(ns.String) + return pkgerrors.New(ns.String) } return nil } @@ -239,7 +239,7 @@ func (re RunErrors) ToError() error { for _, e := range re { errs = append(errs, toErr(e)) } - return multierr.Combine(errs...) + return errors.Join(errs...) } type ResumeRequest struct { @@ -250,14 +250,14 @@ type ResumeRequest struct { func (rr ResumeRequest) ToResult() (Result, error) { var res Result if rr.Error.Valid && rr.Value == nil { - res.Error = errors.New(rr.Error.ValueOrZero()) + res.Error = pkgerrors.New(rr.Error.ValueOrZero()) return res, nil } if !rr.Error.Valid && rr.Value != nil { res.Value = []byte(rr.Value) return res, nil } - return Result{}, errors.New("must provide only one of either 'value' or 'error' key") + return Result{}, pkgerrors.New("must provide only one of either 'value' or 'error' key") } type TaskRun struct { @@ -296,7 +296,7 @@ func (tr TaskRun) GetDotID() string { func (tr TaskRun) Result() Result { var result Result if !tr.Error.IsZero() { - result.Error = errors.New(tr.Error.ValueOrZero()) + result.Error = pkgerrors.New(tr.Error.ValueOrZero()) } else if tr.Output.Valid && tr.Output.Val != nil { result.Value = tr.Output.Val } diff --git a/core/services/pipeline/task.base64decode.go b/core/services/pipeline/task.base64decode.go index db741894705..3384260eb00 100644 --- a/core/services/pipeline/task.base64decode.go +++ b/core/services/pipeline/task.base64decode.go @@ -3,9 +3,9 @@ package pipeline import ( "context" "encoding/base64" + "errors" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -27,13 +27,13 @@ func (t *Base64DecodeTask) Type() TaskType { func (t *Base64DecodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var input StringParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err != nil { return Result{Error: err}, runInfo @@ -41,7 +41,7 @@ func (t *Base64DecodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, in bs, err := base64.StdEncoding.DecodeString(input.String()) if err != nil { - return Result{Error: errors.Wrap(err, "failed to decode base64 string")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "failed to decode base64 string")}, runInfo } return Result{Value: bs}, runInfo diff --git a/core/services/pipeline/task.base64encode.go b/core/services/pipeline/task.base64encode.go index 8e7b6358889..5a0995309a1 100644 --- a/core/services/pipeline/task.base64encode.go +++ b/core/services/pipeline/task.base64encode.go @@ -3,9 +3,9 @@ package pipeline import ( "context" "encoding/base64" + "errors" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -27,12 +27,12 @@ func (t *Base64EncodeTask) Type() TaskType { func (t *Base64EncodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var stringInput StringParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&stringInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&stringInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err == nil { // string @@ -40,8 +40,8 @@ func (t *Base64EncodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, in } var bytesInput BytesParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&bytesInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&bytesInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err == nil { // bytes diff --git a/core/services/pipeline/task.bridge.go b/core/services/pipeline/task.bridge.go index f9490ea791d..db3e15c51f8 100644 --- a/core/services/pipeline/task.bridge.go +++ b/core/services/pipeline/task.bridge.go @@ -4,15 +4,15 @@ import ( "context" "database/sql" "encoding/json" + "errors" "net/http" "net/url" "path" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/logger" @@ -83,7 +83,7 @@ func (t *BridgeTask) Type() TaskType { func (t *BridgeTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { inputValues, err := CheckInputs(inputs, -1, -1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( @@ -93,19 +93,19 @@ func (t *BridgeTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inp cacheTTL Uint64Param reqHeaders StringSliceParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&name, From(NonemptyString(t.Name))), "name"), - errors.Wrap(ResolveParam(&requestData, From(VarExpr(t.RequestData, vars), JSONWithVarExprs(t.RequestData, vars, false), nil)), "requestData"), - errors.Wrap(ResolveParam(&includeInputAtKey, From(t.IncludeInputAtKey)), "includeInputAtKey"), - errors.Wrap(ResolveParam(&cacheTTL, From(ValidDurationInSeconds(t.CacheTTL), t.bridgeConfig.BridgeCacheTTL().Seconds())), "cacheTTL"), - errors.Wrap(ResolveParam(&reqHeaders, From(NonemptyString(t.Headers), "[]")), "reqHeaders"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&name, From(NonemptyString(t.Name))), "name"), + pkgerrors.Wrap(ResolveParam(&requestData, From(VarExpr(t.RequestData, vars), JSONWithVarExprs(t.RequestData, vars, false), nil)), "requestData"), + pkgerrors.Wrap(ResolveParam(&includeInputAtKey, From(t.IncludeInputAtKey)), "includeInputAtKey"), + pkgerrors.Wrap(ResolveParam(&cacheTTL, From(ValidDurationInSeconds(t.CacheTTL), t.bridgeConfig.BridgeCacheTTL().Seconds())), "cacheTTL"), + pkgerrors.Wrap(ResolveParam(&reqHeaders, From(NonemptyString(t.Headers), "[]")), "reqHeaders"), ) if err != nil { return Result{Error: err}, runInfo } if len(reqHeaders)%2 != 0 { - return Result{Error: errors.Errorf("headers must have an even number of elements")}, runInfo + return Result{Error: pkgerrors.Errorf("headers must have an even number of elements")}, runInfo } url, err := t.getBridgeURLFromName(name) @@ -177,7 +177,7 @@ func (t *BridgeTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inp responseBytes, cacheErr = t.orm.GetCachedResponse(t.dotID, t.specId, cacheDuration) if cacheErr != nil { promBridgeCacheErrors.WithLabelValues(t.Name).Inc() - if !errors.Is(cacheErr, sql.ErrNoRows) { + if !pkgerrors.Is(cacheErr, sql.ErrNoRows) { lggr.Warnw("Bridge task: cache fallback failed", "err", cacheErr.Error(), "url", url.String(), @@ -237,7 +237,7 @@ func (t *BridgeTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inp func (t BridgeTask) getBridgeURLFromName(name StringParam) (URLParam, error) { bt, err := t.orm.FindBridge(bridges.BridgeName(name)) if err != nil { - return URLParam{}, errors.Wrapf(err, "could not find bridge with name '%s'", name) + return URLParam{}, pkgerrors.Wrapf(err, "could not find bridge with name '%s'", name) } return URLParam(bt.URL), nil } diff --git a/core/services/pipeline/task.cborparse.go b/core/services/pipeline/task.cborparse.go index 35bf81fe07b..d28b4d2ab56 100644 --- a/core/services/pipeline/task.cborparse.go +++ b/core/services/pipeline/task.cborparse.go @@ -2,9 +2,9 @@ package pipeline import ( "context" + "errors" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/cbor" "github.com/smartcontractkit/chainlink/v2/core/logger" @@ -34,16 +34,16 @@ func (t *CBORParseTask) Type() TaskType { func (t *CBORParseTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, -1, -1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( data BytesParam mode StringParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars))), "data"), - errors.Wrap(ResolveParam(&mode, From(NonemptyString(t.Mode), "diet")), "mode"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars))), "data"), + pkgerrors.Wrap(ResolveParam(&mode, From(NonemptyString(t.Mode), "diet")), "mode"), ) if err != nil { return Result{Error: err}, runInfo @@ -56,16 +56,16 @@ func (t *CBORParseTask) Run(_ context.Context, _ logger.Logger, vars Vars, input // empty map parsed, err := cbor.ParseDietCBOR(data) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "CBORParse: data: %v", err)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "CBORParse: data: %v", err)}, runInfo } return Result{Value: parsed}, runInfo case "standard": parsed, err := cbor.ParseStandardCBOR(data) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "CBORParse: data: %v", err)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "CBORParse: data: %v", err)}, runInfo } return Result{Value: parsed}, runInfo default: - return Result{Error: errors.Errorf("unrecognised mode: %s", mode)}, runInfo + return Result{Error: pkgerrors.Errorf("unrecognised mode: %s", mode)}, runInfo } } diff --git a/core/services/pipeline/task.conditional.go b/core/services/pipeline/task.conditional.go index bf025e2292b..ce463d8f0e1 100644 --- a/core/services/pipeline/task.conditional.go +++ b/core/services/pipeline/task.conditional.go @@ -2,9 +2,9 @@ package pipeline import ( "context" + "errors" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -26,19 +26,19 @@ func (t *ConditionalTask) Type() TaskType { func (t *ConditionalTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( boolParam BoolParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&boolParam, From(VarExpr(t.Data, vars), Input(inputs, 0), nil)), "data"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&boolParam, From(VarExpr(t.Data, vars), Input(inputs, 0), nil)), "data"), ) if err != nil { return Result{Error: err}, runInfo } if !boolParam { - return Result{Error: errors.New("conditional was not satisfied")}, runInfo + return Result{Error: pkgerrors.New("conditional was not satisfied")}, runInfo } return Result{Value: true}, runInfo } diff --git a/core/services/pipeline/task.divide.go b/core/services/pipeline/task.divide.go index 7bf91175a62..35b87d6fd05 100644 --- a/core/services/pipeline/task.divide.go +++ b/core/services/pipeline/task.divide.go @@ -2,10 +2,10 @@ package pipeline import ( "context" + "errors" "math" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -23,8 +23,8 @@ type DivideTask struct { var _ Task = (*DivideTask)(nil) var ( - ErrDivideByZero = errors.New("divide by zero") - ErrDivisionOverlow = errors.New("division overflow") + ErrDivideByZero = pkgerrors.New("divide by zero") + ErrDivisionOverlow = pkgerrors.New("division overflow") ) func (t *DivideTask) Type() TaskType { @@ -34,7 +34,7 @@ func (t *DivideTask) Type() TaskType { func (t *DivideTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, -1, -1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( @@ -42,10 +42,10 @@ func (t *DivideTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs [ b DecimalParam maybePrecision MaybeInt32Param ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&a, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), - errors.Wrap(ResolveParam(&b, From(VarExpr(t.Divisor, vars), NonemptyString(t.Divisor))), "divisor"), - errors.Wrap(ResolveParam(&maybePrecision, From(VarExpr(t.Precision, vars), t.Precision)), "precision"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&a, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + pkgerrors.Wrap(ResolveParam(&b, From(VarExpr(t.Divisor, vars), NonemptyString(t.Divisor))), "divisor"), + pkgerrors.Wrap(ResolveParam(&maybePrecision, From(VarExpr(t.Precision, vars), t.Precision)), "precision"), ) if err != nil { return Result{Error: err}, runInfo diff --git a/core/services/pipeline/task.estimategas.go b/core/services/pipeline/task.estimategas.go index 43c148b287f..64df252b9f6 100644 --- a/core/services/pipeline/task.estimategas.go +++ b/core/services/pipeline/task.estimategas.go @@ -2,15 +2,15 @@ package pipeline import ( "context" + "errors" "fmt" "math" "strconv" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" "github.com/smartcontractkit/chainlink/v2/core/chains/legacyevm" @@ -40,7 +40,7 @@ type GasEstimator interface { var ( _ Task = (*EstimateGasLimitTask)(nil) - ErrInvalidMultiplier = errors.New("Invalid multiplier") + ErrInvalidMultiplier = pkgerrors.New("Invalid multiplier") ) func (t *EstimateGasLimitTask) Type() TaskType { @@ -62,13 +62,13 @@ func (t *EstimateGasLimitTask) Run(ctx context.Context, lggr logger.Logger, vars multiplier DecimalParam chainID StringParam ) - err := multierr.Combine( - errors.Wrap(ResolveParam(&fromAddr, From(VarExpr(t.From, vars), utils.ZeroAddress)), "from"), - errors.Wrap(ResolveParam(&toAddr, From(VarExpr(t.To, vars), NonemptyString(t.To))), "to"), - errors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), NonemptyString(t.Data))), "data"), + err := errors.Join( + pkgerrors.Wrap(ResolveParam(&fromAddr, From(VarExpr(t.From, vars), utils.ZeroAddress)), "from"), + pkgerrors.Wrap(ResolveParam(&toAddr, From(VarExpr(t.To, vars), NonemptyString(t.To))), "to"), + pkgerrors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), NonemptyString(t.Data))), "data"), // Default to 1, i.e. exactly what estimateGas suggests - errors.Wrap(ResolveParam(&multiplier, From(VarExpr(t.Multiplier, vars), NonemptyString(t.Multiplier), decimal.New(1, 0))), "multiplier"), - errors.Wrap(ResolveParam(&chainID, From(VarExpr(t.getEvmChainID(), vars), NonemptyString(t.getEvmChainID()), "")), "evmChainID"), + pkgerrors.Wrap(ResolveParam(&multiplier, From(VarExpr(t.Multiplier, vars), NonemptyString(t.Multiplier), decimal.New(1, 0))), "multiplier"), + pkgerrors.Wrap(ResolveParam(&chainID, From(VarExpr(t.getEvmChainID(), vars), NonemptyString(t.getEvmChainID()), "")), "evmChainID"), ) if err != nil { return Result{Error: err}, runInfo diff --git a/core/services/pipeline/task.eth_abi_decode.go b/core/services/pipeline/task.eth_abi_decode.go index ddd84062353..7592d21e26d 100644 --- a/core/services/pipeline/task.eth_abi_decode.go +++ b/core/services/pipeline/task.eth_abi_decode.go @@ -2,9 +2,9 @@ package pipeline import ( "context" + "errors" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -27,16 +27,16 @@ func (t *ETHABIDecodeTask) Type() TaskType { func (t *ETHABIDecodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( data BytesParam theABI BytesParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), Input(inputs, 0))), "data"), - errors.Wrap(ResolveParam(&theABI, From(NonemptyString(t.ABI))), "abi"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), Input(inputs, 0))), "data"), + pkgerrors.Wrap(ResolveParam(&theABI, From(NonemptyString(t.ABI))), "abi"), ) if err != nil { return Result{Error: err}, runInfo @@ -44,7 +44,7 @@ func (t *ETHABIDecodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, in args, _, err := ParseETHABIArgsString([]byte(theABI), false) if err != nil { - return Result{Error: errors.Wrap(ErrBadInput, err.Error())}, runInfo + return Result{Error: pkgerrors.Wrap(ErrBadInput, err.Error())}, runInfo } out := make(map[string]interface{}) diff --git a/core/services/pipeline/task.eth_abi_decode_log.go b/core/services/pipeline/task.eth_abi_decode_log.go index 1e00fac7a4b..31822a609b3 100644 --- a/core/services/pipeline/task.eth_abi_decode_log.go +++ b/core/services/pipeline/task.eth_abi_decode_log.go @@ -2,10 +2,10 @@ package pipeline import ( "context" + "errors" "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -29,7 +29,7 @@ func (t *ETHABIDecodeLogTask) Type() TaskType { func (t *ETHABIDecodeLogTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, -1, -1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( @@ -37,10 +37,10 @@ func (t *ETHABIDecodeLogTask) Run(_ context.Context, _ logger.Logger, vars Vars, data BytesParam topics HashSliceParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), nil)), "data"), - errors.Wrap(ResolveParam(&topics, From(VarExpr(t.Topics, vars))), "topics"), - errors.Wrap(ResolveParam(&theABI, From(NonemptyString(t.ABI))), "abi"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), nil)), "data"), + pkgerrors.Wrap(ResolveParam(&topics, From(VarExpr(t.Topics, vars))), "topics"), + pkgerrors.Wrap(ResolveParam(&theABI, From(NonemptyString(t.ABI))), "abi"), ) if err != nil { return Result{Error: err}, runInfo @@ -48,22 +48,22 @@ func (t *ETHABIDecodeLogTask) Run(_ context.Context, _ logger.Logger, vars Vars, _, args, indexedArgs, err := parseETHABIString([]byte(theABI), true) if err != nil { - return Result{Error: errors.Wrap(ErrBadInput, err.Error())}, runInfo + return Result{Error: pkgerrors.Wrap(ErrBadInput, err.Error())}, runInfo } out := make(map[string]interface{}) if len(data) > 0 { if err2 := args.UnpackIntoMap(out, []byte(data)); err2 != nil { - return Result{Error: errors.Wrap(ErrBadInput, err2.Error())}, runInfo + return Result{Error: pkgerrors.Wrap(ErrBadInput, err2.Error())}, runInfo } } if len(indexedArgs) > 0 { if len(topics) != len(indexedArgs)+1 { - return Result{Error: errors.Wrap(ErrBadInput, "topic/field count mismatch")}, runInfo + return Result{Error: pkgerrors.Wrap(ErrBadInput, "topic/field count mismatch")}, runInfo } err = abi.ParseTopicsIntoMap(out, indexedArgs, topics[1:]) if err != nil { - return Result{Error: errors.Wrap(ErrBadInput, err.Error())}, runInfo + return Result{Error: pkgerrors.Wrap(ErrBadInput, err.Error())}, runInfo } } return Result{Value: out}, runInfo diff --git a/core/services/pipeline/task.eth_abi_encode.go b/core/services/pipeline/task.eth_abi_encode.go index 99f6ed0a46a..0f93b368e19 100644 --- a/core/services/pipeline/task.eth_abi_encode.go +++ b/core/services/pipeline/task.eth_abi_encode.go @@ -2,11 +2,11 @@ package pipeline import ( "context" + "errors" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -29,16 +29,16 @@ func (t *ETHABIEncodeTask) Type() TaskType { func (t *ETHABIEncodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, -1, -1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( inputValues MapParam theABI BytesParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&inputValues, From(VarExpr(t.Data, vars), JSONWithVarExprs(t.Data, vars, false), nil)), "data"), - errors.Wrap(ResolveParam(&theABI, From(NonemptyString(t.ABI))), "abi"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&inputValues, From(VarExpr(t.Data, vars), JSONWithVarExprs(t.Data, vars, false), nil)), "data"), + pkgerrors.Wrap(ResolveParam(&theABI, From(NonemptyString(t.ABI))), "abi"), ) if err != nil { return Result{Error: err}, runInfo @@ -46,7 +46,7 @@ func (t *ETHABIEncodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, in methodName, args, _, err := parseETHABIString([]byte(theABI), false) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "ETHABIEncode: while parsing ABI string: %v", err)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "ETHABIEncode: while parsing ABI string: %v", err)}, runInfo } method := abi.NewMethod(methodName, methodName, abi.Function, "", false, false, args, nil) @@ -54,18 +54,18 @@ func (t *ETHABIEncodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, in for _, arg := range args { val, exists := inputValues[arg.Name] if !exists { - return Result{Error: errors.Wrapf(ErrBadInput, "ETHABIEncode: argument '%v' is missing", arg.Name)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "ETHABIEncode: argument '%v' is missing", arg.Name)}, runInfo } val, err = convertToETHABIType(val, arg.Type) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "ETHABIEncode: while converting argument '%v' from %T to %v: %v", arg.Name, val, arg.Type, err)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "ETHABIEncode: while converting argument '%v' from %T to %v: %v", arg.Name, val, arg.Type, err)}, runInfo } vals = append(vals, val) } argsEncoded, err := method.Inputs.Pack(vals...) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "ETHABIEncode: could not ABI encode values: %v", err)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "ETHABIEncode: could not ABI encode values: %v", err)}, runInfo } var dataBytes []byte if methodName != "" { diff --git a/core/services/pipeline/task.eth_abi_encode_2.go b/core/services/pipeline/task.eth_abi_encode_2.go index f4f96ece8cd..3d9fb30174e 100644 --- a/core/services/pipeline/task.eth_abi_encode_2.go +++ b/core/services/pipeline/task.eth_abi_encode_2.go @@ -3,11 +3,11 @@ package pipeline import ( "context" "encoding/json" + "errors" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -30,16 +30,16 @@ func (t *ETHABIEncodeTask2) Type() TaskType { func (t *ETHABIEncodeTask2) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (Result, RunInfo) { _, err := CheckInputs(inputs, -1, -1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, RunInfo{} + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, RunInfo{} } var ( inputValues MapParam theABI BytesParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&inputValues, From(VarExpr(t.Data, vars), JSONWithVarExprs(t.Data, vars, false), nil)), "data"), - errors.Wrap(ResolveParam(&theABI, From(NonemptyString(t.ABI))), "abi"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&inputValues, From(VarExpr(t.Data, vars), JSONWithVarExprs(t.Data, vars, false), nil)), "data"), + pkgerrors.Wrap(ResolveParam(&theABI, From(NonemptyString(t.ABI))), "abi"), ) if err != nil { return Result{Error: err}, RunInfo{} @@ -48,7 +48,7 @@ func (t *ETHABIEncodeTask2) Run(_ context.Context, _ logger.Logger, vars Vars, i inputMethod := Method{} err = json.Unmarshal(theABI, &inputMethod) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "ETHABIEncode: while parsing ABI string: %v", err)}, RunInfo{} + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "ETHABIEncode: while parsing ABI string: %v", err)}, RunInfo{} } method := abi.NewMethod(inputMethod.Name, inputMethod.Name, abi.Function, "", false, false, inputMethod.Inputs, nil) @@ -56,22 +56,22 @@ func (t *ETHABIEncodeTask2) Run(_ context.Context, _ logger.Logger, vars Vars, i var vals []interface{} for _, arg := range method.Inputs { if len(arg.Name) == 0 { - return Result{Error: errors.Wrapf(ErrBadInput, "ETHABIEncode: bad ABI specification, missing argument name")}, RunInfo{} + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "ETHABIEncode: bad ABI specification, missing argument name")}, RunInfo{} } val, exists := inputValues[arg.Name] if !exists { - return Result{Error: errors.Wrapf(ErrBadInput, "ETHABIEncode: argument '%v' is missing", arg.Name)}, RunInfo{} + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "ETHABIEncode: argument '%v' is missing", arg.Name)}, RunInfo{} } val, err = convertToETHABIType(val, arg.Type) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "ETHABIEncode: while converting argument '%v' from %T to %v: %v", arg.Name, val, arg.Type, err)}, RunInfo{} + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "ETHABIEncode: while converting argument '%v' from %T to %v: %v", arg.Name, val, arg.Type, err)}, RunInfo{} } vals = append(vals, val) } argsEncoded, err := method.Inputs.Pack(vals...) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "ETHABIEncode: could not ABI encode values: %v", err)}, RunInfo{} + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "ETHABIEncode: could not ABI encode values: %v", err)}, RunInfo{} } var dataBytes []byte if method.Name != "" { diff --git a/core/services/pipeline/task.eth_call.go b/core/services/pipeline/task.eth_call.go index 56b2df08c4e..fc5685e8636 100644 --- a/core/services/pipeline/task.eth_call.go +++ b/core/services/pipeline/task.eth_call.go @@ -2,15 +2,15 @@ package pipeline import ( "context" + "errors" "fmt" "time" "github.com/ethereum/go-ethereum" "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" - "go.uber.org/multierr" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" @@ -65,7 +65,7 @@ func (t *ETHCallTask) getEvmChainID() string { func (t *ETHCallTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, -1, -1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( @@ -79,21 +79,21 @@ func (t *ETHCallTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, in gasUnlimited BoolParam chainID StringParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&contractAddr, From(VarExpr(t.Contract, vars), NonemptyString(t.Contract))), "contract"), - errors.Wrap(ResolveParam(&from, From(VarExpr(t.From, vars), NonemptyString(t.From), utils.ZeroAddress)), "from"), - errors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), JSONWithVarExprs(t.Data, vars, false))), "data"), - errors.Wrap(ResolveParam(&gas, From(VarExpr(t.Gas, vars), NonemptyString(t.Gas), 0)), "gas"), - errors.Wrap(ResolveParam(&gasPrice, From(VarExpr(t.GasPrice, vars), t.GasPrice)), "gasPrice"), - errors.Wrap(ResolveParam(&gasTipCap, From(VarExpr(t.GasTipCap, vars), t.GasTipCap)), "gasTipCap"), - errors.Wrap(ResolveParam(&gasFeeCap, From(VarExpr(t.GasFeeCap, vars), t.GasFeeCap)), "gasFeeCap"), - errors.Wrap(ResolveParam(&chainID, From(VarExpr(t.getEvmChainID(), vars), NonemptyString(t.getEvmChainID()), "")), "evmChainID"), - errors.Wrap(ResolveParam(&gasUnlimited, From(VarExpr(t.GasUnlimited, vars), NonemptyString(t.GasUnlimited), false)), "gasUnlimited"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&contractAddr, From(VarExpr(t.Contract, vars), NonemptyString(t.Contract))), "contract"), + pkgerrors.Wrap(ResolveParam(&from, From(VarExpr(t.From, vars), NonemptyString(t.From), utils.ZeroAddress)), "from"), + pkgerrors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), JSONWithVarExprs(t.Data, vars, false))), "data"), + pkgerrors.Wrap(ResolveParam(&gas, From(VarExpr(t.Gas, vars), NonemptyString(t.Gas), 0)), "gas"), + pkgerrors.Wrap(ResolveParam(&gasPrice, From(VarExpr(t.GasPrice, vars), t.GasPrice)), "gasPrice"), + pkgerrors.Wrap(ResolveParam(&gasTipCap, From(VarExpr(t.GasTipCap, vars), t.GasTipCap)), "gasTipCap"), + pkgerrors.Wrap(ResolveParam(&gasFeeCap, From(VarExpr(t.GasFeeCap, vars), t.GasFeeCap)), "gasFeeCap"), + pkgerrors.Wrap(ResolveParam(&chainID, From(VarExpr(t.getEvmChainID(), vars), NonemptyString(t.getEvmChainID()), "")), "evmChainID"), + pkgerrors.Wrap(ResolveParam(&gasUnlimited, From(VarExpr(t.GasUnlimited, vars), NonemptyString(t.GasUnlimited), false)), "gasUnlimited"), ) if err != nil { return Result{Error: err}, runInfo } else if len(data) == 0 { - return Result{Error: errors.Wrapf(ErrBadInput, "data param must not be empty")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "data param must not be empty")}, runInfo } chain, err := t.legacyChains.Get(string(chainID)) @@ -105,7 +105,7 @@ func (t *ETHCallTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, in var selectedGas uint32 if gasUnlimited { if gas > 0 { - return Result{Error: errors.Wrapf(ErrBadInput, "gas must be zero when gasUnlimited is true")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "gas must be zero when gasUnlimited is true")}, runInfo } } else { if gas > 0 { diff --git a/core/services/pipeline/task.eth_tx.go b/core/services/pipeline/task.eth_tx.go index 1687c974140..d549f96dbf7 100644 --- a/core/services/pipeline/task.eth_tx.go +++ b/core/services/pipeline/task.eth_tx.go @@ -2,6 +2,7 @@ package pipeline import ( "context" + "errors" "fmt" "math/big" "reflect" @@ -9,8 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink-common/pkg/utils/hex" @@ -65,7 +65,7 @@ func (t *ETHTxTask) getEvmChainID() string { func (t *ETHTxTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { var chainID StringParam - err := errors.Wrap(ResolveParam(&chainID, From(VarExpr(t.getEvmChainID(), vars), NonemptyString(t.getEvmChainID()), "")), "evmChainID") + err := pkgerrors.Wrap(ResolveParam(&chainID, From(VarExpr(t.getEvmChainID(), vars), NonemptyString(t.getEvmChainID()), "")), "evmChainID") if err != nil { return Result{Error: err}, runInfo } @@ -80,7 +80,7 @@ func (t *ETHTxTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inpu txManager := chain.TxManager() _, err = CheckInputs(inputs, -1, -1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } maximumGasLimit := SelectGasLimit(cfg.GasEstimator(), t.jobType, t.specGasLimit) @@ -95,15 +95,15 @@ func (t *ETHTxTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inpu transmitCheckerMap MapParam failOnRevert BoolParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&fromAddrs, From(VarExpr(t.From, vars), JSONWithVarExprs(t.From, vars, false), NonemptyString(t.From), nil)), "from"), - errors.Wrap(ResolveParam(&toAddr, From(VarExpr(t.To, vars), NonemptyString(t.To))), "to"), - errors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), NonemptyString(t.Data))), "data"), - errors.Wrap(ResolveParam(&gasLimit, From(VarExpr(t.GasLimit, vars), NonemptyString(t.GasLimit), maximumGasLimit)), "gasLimit"), - errors.Wrap(ResolveParam(&txMetaMap, From(VarExpr(t.TxMeta, vars), JSONWithVarExprs(t.TxMeta, vars, false), MapParam{})), "txMeta"), - errors.Wrap(ResolveParam(&maybeMinConfirmations, From(VarExpr(t.MinConfirmations, vars), NonemptyString(t.MinConfirmations), "")), "minConfirmations"), - errors.Wrap(ResolveParam(&transmitCheckerMap, From(VarExpr(t.TransmitChecker, vars), JSONWithVarExprs(t.TransmitChecker, vars, false), MapParam{})), "transmitChecker"), - errors.Wrap(ResolveParam(&failOnRevert, From(NonemptyString(t.FailOnRevert), false)), "failOnRevert"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&fromAddrs, From(VarExpr(t.From, vars), JSONWithVarExprs(t.From, vars, false), NonemptyString(t.From), nil)), "from"), + pkgerrors.Wrap(ResolveParam(&toAddr, From(VarExpr(t.To, vars), NonemptyString(t.To))), "to"), + pkgerrors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), NonemptyString(t.Data))), "data"), + pkgerrors.Wrap(ResolveParam(&gasLimit, From(VarExpr(t.GasLimit, vars), NonemptyString(t.GasLimit), maximumGasLimit)), "gasLimit"), + pkgerrors.Wrap(ResolveParam(&txMetaMap, From(VarExpr(t.TxMeta, vars), JSONWithVarExprs(t.TxMeta, vars, false), MapParam{})), "txMeta"), + pkgerrors.Wrap(ResolveParam(&maybeMinConfirmations, From(VarExpr(t.MinConfirmations, vars), NonemptyString(t.MinConfirmations), "")), "minConfirmations"), + pkgerrors.Wrap(ResolveParam(&transmitCheckerMap, From(VarExpr(t.TransmitChecker, vars), JSONWithVarExprs(t.TransmitChecker, vars, false), MapParam{})), "transmitChecker"), + pkgerrors.Wrap(ResolveParam(&failOnRevert, From(NonemptyString(t.FailOnRevert), false)), "failOnRevert"), ) if err != nil { return Result{Error: err}, runInfo @@ -129,9 +129,9 @@ func (t *ETHTxTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inpu fromAddr, err := t.keyStore.GetRoundRobinAddress(chain.ID(), fromAddrs...) if err != nil { - err = errors.Wrap(err, "ETHTxTask failed to get fromAddress") + err = pkgerrors.Wrap(err, "ETHTxTask failed to get fromAddress") lggr.Error(err) - return Result{Error: errors.Wrapf(ErrTaskRunFailed, "while querying keystore: %v", err)}, retryableRunInfo() + return Result{Error: pkgerrors.Wrapf(ErrTaskRunFailed, "while querying keystore: %v", err)}, retryableRunInfo() } // TODO(sc-55115): Allow job specs to pass in the strategy that they want @@ -166,7 +166,7 @@ func (t *ETHTxTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inpu _, err = txManager.CreateTransaction(ctx, txRequest) if err != nil { - return Result{Error: errors.Wrapf(ErrTaskRunFailed, "while creating transaction: %v", err)}, retryableRunInfo() + return Result{Error: pkgerrors.Wrapf(ErrTaskRunFailed, "while creating transaction: %v", err)}, retryableRunInfo() } if minOutgoingConfirmations > 0 { @@ -200,12 +200,12 @@ func decodeMeta(metaMap MapParam) (*txmgr.TxMeta, error) { }, }) if err != nil { - return &txMeta, errors.Wrapf(ErrBadInput, "txMeta: %v", err) + return &txMeta, pkgerrors.Wrapf(ErrBadInput, "txMeta: %v", err) } err = metaDecoder.Decode(metaMap) if err != nil { - return &txMeta, errors.Wrapf(ErrBadInput, "txMeta: %v", err) + return &txMeta, pkgerrors.Wrapf(ErrBadInput, "txMeta: %v", err) } return &txMeta, nil } @@ -231,12 +231,12 @@ func decodeTransmitChecker(checkerMap MapParam) (txmgr.TransmitCheckerSpec, erro }, }) if err != nil { - return transmitChecker, errors.Wrapf(ErrBadInput, "transmitChecker: %v", err) + return transmitChecker, pkgerrors.Wrapf(ErrBadInput, "transmitChecker: %v", err) } err = checkerDecoder.Decode(checkerMap) if err != nil { - return transmitChecker, errors.Wrapf(ErrBadInput, "transmitChecker: %v", err) + return transmitChecker, pkgerrors.Wrapf(ErrBadInput, "transmitChecker: %v", err) } return transmitChecker, nil } diff --git a/core/services/pipeline/task.hexdecode.go b/core/services/pipeline/task.hexdecode.go index 893130bcf2c..69c3d22921b 100644 --- a/core/services/pipeline/task.hexdecode.go +++ b/core/services/pipeline/task.hexdecode.go @@ -3,10 +3,9 @@ package pipeline import ( "context" "encoding/hex" + "errors" - "github.com/pkg/errors" - "go.uber.org/multierr" - + pkgerrors "github.com/pkg/errors" commonhex "github.com/smartcontractkit/chainlink-common/pkg/utils/hex" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -28,13 +27,13 @@ func (t *HexDecodeTask) Type() TaskType { func (t *HexDecodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var input StringParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err != nil { return Result{Error: err}, runInfo @@ -46,8 +45,8 @@ func (t *HexDecodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, input if err == nil { return Result{Value: bs}, runInfo } - return Result{Error: errors.Wrap(err, "failed to decode hex string")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "failed to decode hex string")}, runInfo } - return Result{Error: errors.New("hex string must have prefix 0x")}, runInfo + return Result{Error: pkgerrors.New("hex string must have prefix 0x")}, runInfo } diff --git a/core/services/pipeline/task.hexencode.go b/core/services/pipeline/task.hexencode.go index c74259e6538..2641f7d34f9 100644 --- a/core/services/pipeline/task.hexencode.go +++ b/core/services/pipeline/task.hexencode.go @@ -3,10 +3,10 @@ package pipeline import ( "context" "encoding/hex" + "errors" "fmt" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -35,12 +35,12 @@ func addHexPrefix(val string) string { func (t *HexEncodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var stringInput StringParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&stringInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&stringInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err == nil { // string @@ -48,8 +48,8 @@ func (t *HexEncodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, input } var bytesInput BytesParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&bytesInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&bytesInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err == nil { // bytes @@ -57,22 +57,22 @@ func (t *HexEncodeTask) Run(_ context.Context, _ logger.Logger, vars Vars, input } var decimalInput DecimalParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&decimalInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&decimalInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err == nil && !decimalInput.Decimal().IsInteger() { // decimal - return Result{Error: errors.New("decimal input")}, runInfo + return Result{Error: pkgerrors.New("decimal input")}, runInfo } var bigIntInput MaybeBigIntParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&bigIntInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&bigIntInput, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err == nil { // one of integer types if bigIntInput.BigInt().Sign() == -1 { - return Result{Error: errors.New("negative integer")}, runInfo + return Result{Error: pkgerrors.New("negative integer")}, runInfo } return Result{Value: addHexPrefix(fmt.Sprintf("%x", bigIntInput.BigInt()))}, runInfo } diff --git a/core/services/pipeline/task.http.go b/core/services/pipeline/task.http.go index 3d49ea43168..917da51a8d7 100644 --- a/core/services/pipeline/task.http.go +++ b/core/services/pipeline/task.http.go @@ -3,12 +3,12 @@ package pipeline import ( "context" "encoding/json" + "errors" "net/http" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/logger" clhttp "github.com/smartcontractkit/chainlink/v2/core/utils/http" @@ -54,7 +54,7 @@ func (t *HTTPTask) Type() TaskType { func (t *HTTPTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, -1, -1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( @@ -64,22 +64,22 @@ func (t *HTTPTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, input allowUnrestrictedNetworkAccess BoolParam reqHeaders StringSliceParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&method, From(NonemptyString(t.Method), "GET")), "method"), - errors.Wrap(ResolveParam(&url, From(VarExpr(t.URL, vars), NonemptyString(t.URL))), "url"), - errors.Wrap(ResolveParam(&requestData, From(VarExpr(t.RequestData, vars), JSONWithVarExprs(t.RequestData, vars, false), nil)), "requestData"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&method, From(NonemptyString(t.Method), "GET")), "method"), + pkgerrors.Wrap(ResolveParam(&url, From(VarExpr(t.URL, vars), NonemptyString(t.URL))), "url"), + pkgerrors.Wrap(ResolveParam(&requestData, From(VarExpr(t.RequestData, vars), JSONWithVarExprs(t.RequestData, vars, false), nil)), "requestData"), // Any hardcoded strings used for URL uses the unrestricted HTTP adapter // Interpolated variable URLs use restricted HTTP adapter by default // You must set allowUnrestrictedNetworkAccess=true on the task to enable variable-interpolated URLs to make restricted network requests - errors.Wrap(ResolveParam(&allowUnrestrictedNetworkAccess, From(NonemptyString(t.AllowUnrestrictedNetworkAccess), !variableRegexp.MatchString(t.URL))), "allowUnrestrictedNetworkAccess"), - errors.Wrap(ResolveParam(&reqHeaders, From(NonemptyString(t.Headers), "[]")), "reqHeaders"), + pkgerrors.Wrap(ResolveParam(&allowUnrestrictedNetworkAccess, From(NonemptyString(t.AllowUnrestrictedNetworkAccess), !variableRegexp.MatchString(t.URL))), "allowUnrestrictedNetworkAccess"), + pkgerrors.Wrap(ResolveParam(&reqHeaders, From(NonemptyString(t.Headers), "[]")), "reqHeaders"), ) if err != nil { return Result{Error: err}, runInfo } if len(reqHeaders)%2 != 0 { - return Result{Error: errors.Errorf("headers must have an even number of elements")}, runInfo + return Result{Error: pkgerrors.Errorf("headers must have an even number of elements")}, runInfo } requestDataJSON, err := json.Marshal(requestData) @@ -105,8 +105,8 @@ func (t *HTTPTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, input } responseBytes, statusCode, respHeaders, elapsed, err := makeHTTPRequest(requestCtx, lggr, method, url, reqHeaders, requestData, client, t.config.DefaultHTTPLimit()) if err != nil { - if errors.Is(errors.Cause(err), clhttp.ErrDisallowedIP) { - err = errors.Wrap(err, `connections to local resources are disabled by default, if you are sure this is safe, you can enable on a per-task basis by setting allowUnrestrictedNetworkAccess="true" in the pipeline task spec, e.g. fetch [type="http" method=GET url="$(decode_cbor.url)" allowUnrestrictedNetworkAccess="true"]`) + if pkgerrors.Is(pkgerrors.Cause(err), clhttp.ErrDisallowedIP) { + err = pkgerrors.Wrap(err, `connections to local resources are disabled by default, if you are sure this is safe, you can enable on a per-task basis by setting allowUnrestrictedNetworkAccess="true" in the pipeline task spec, e.g. fetch [type="http" method=GET url="$(decode_cbor.url)" allowUnrestrictedNetworkAccess="true"]`) } return Result{Error: err}, RunInfo{IsRetryable: isRetryableHTTPError(statusCode, err)} } diff --git a/core/services/pipeline/task.jsonparse.go b/core/services/pipeline/task.jsonparse.go index 8eef106c3a9..2f81c735ca8 100644 --- a/core/services/pipeline/task.jsonparse.go +++ b/core/services/pipeline/task.jsonparse.go @@ -4,11 +4,11 @@ import ( "bytes" "context" "encoding/json" + "errors" "math/big" "strings" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -40,20 +40,20 @@ func (t *JSONParseTask) Type() TaskType { func (t *JSONParseTask) Run(_ context.Context, l logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var sep StringParam - err = errors.Wrap(ResolveParam(&sep, From(t.Separator)), "separator") + err = pkgerrors.Wrap(ResolveParam(&sep, From(t.Separator)), "separator") var ( path = NewJSONPathParam(string(sep)) data BytesParam lax BoolParam ) - err = multierr.Combine(err, - errors.Wrap(ResolveParam(&path, From(VarExpr(t.Path, vars), t.Path)), "path"), - errors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), Input(inputs, 0))), "data"), - errors.Wrap(ResolveParam(&lax, From(NonemptyString(t.Lax), false)), "lax"), + err = errors.Join(err, + pkgerrors.Wrap(ResolveParam(&path, From(VarExpr(t.Path, vars), t.Path)), "path"), + pkgerrors.Wrap(ResolveParam(&data, From(VarExpr(t.Data, vars), Input(inputs, 0))), "data"), + pkgerrors.Wrap(ResolveParam(&lax, From(NonemptyString(t.Lax), false)), "lax"), ) if err != nil { return Result{Error: err}, runInfo @@ -76,19 +76,19 @@ func (t *JSONParseTask) Run(_ context.Context, l logger.Logger, vars Vars, input decoded = nil break } else if !exists { - return Result{Error: errors.Wrapf(ErrKeypathNotFound, `could not resolve path ["%v"] in %s`, strings.Join(path, `","`), data)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrKeypathNotFound, `could not resolve path ["%v"] in %s`, strings.Join(path, `","`), data)}, runInfo } case []interface{}: bigindex, ok := big.NewInt(0).SetString(part, 10) if !ok { - return Result{Error: errors.Wrapf(ErrKeypathNotFound, "JSONParse task error: %v is not a valid array index", part)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrKeypathNotFound, "JSONParse task error: %v is not a valid array index", part)}, runInfo } else if !bigindex.IsInt64() { if bool(lax) { decoded = nil break } - return Result{Error: errors.Wrapf(ErrKeypathNotFound, `could not resolve path ["%v"] in %s`, strings.Join(path, `","`), data)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrKeypathNotFound, `could not resolve path ["%v"] in %s`, strings.Join(path, `","`), data)}, runInfo } index := int(bigindex.Int64()) if index < 0 { @@ -100,18 +100,18 @@ func (t *JSONParseTask) Run(_ context.Context, l logger.Logger, vars Vars, input decoded = nil break } else if !exists { - return Result{Error: errors.Wrapf(ErrKeypathNotFound, `could not resolve path ["%v"] in %s`, strings.Join(path, `","`), data)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrKeypathNotFound, `could not resolve path ["%v"] in %s`, strings.Join(path, `","`), data)}, runInfo } decoded = d[index] default: - return Result{Error: errors.Wrapf(ErrKeypathNotFound, `could not resolve path ["%v"] in %s`, strings.Join(path, `","`), data)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrKeypathNotFound, `could not resolve path ["%v"] in %s`, strings.Join(path, `","`), data)}, runInfo } } decoded, err = reinterpetJsonNumbers(decoded) if err != nil { - return Result{Error: multierr.Combine(ErrBadInput, err)}, runInfo + return Result{Error: errors.Join(ErrBadInput, err)}, runInfo } return Result{Value: decoded}, runInfo diff --git a/core/services/pipeline/task.length.go b/core/services/pipeline/task.length.go index 5cf781c0847..74941150206 100644 --- a/core/services/pipeline/task.length.go +++ b/core/services/pipeline/task.length.go @@ -2,10 +2,10 @@ package pipeline import ( "context" + "errors" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -27,13 +27,13 @@ func (t *LengthTask) Type() TaskType { func (t *LengthTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var input BytesParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err != nil { return Result{Error: err}, runInfo diff --git a/core/services/pipeline/task.lessthan.go b/core/services/pipeline/task.lessthan.go index cfc755561fe..f6348e6c00a 100644 --- a/core/services/pipeline/task.lessthan.go +++ b/core/services/pipeline/task.lessthan.go @@ -2,9 +2,9 @@ package pipeline import ( "context" + "errors" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -29,7 +29,7 @@ func (t *LessThanTask) Type() TaskType { func (t *LessThanTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( @@ -37,9 +37,9 @@ func (t *LessThanTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs b DecimalParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&a, From(VarExpr(t.Left, vars), NonemptyString(t.Left), Input(inputs, 0))), "left"), - errors.Wrap(ResolveParam(&b, From(VarExpr(t.Right, vars), NonemptyString(t.Right))), "right"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&a, From(VarExpr(t.Left, vars), NonemptyString(t.Left), Input(inputs, 0))), "left"), + pkgerrors.Wrap(ResolveParam(&b, From(VarExpr(t.Right, vars), NonemptyString(t.Right))), "right"), ) if err != nil { return Result{Error: err}, runInfo diff --git a/core/services/pipeline/task.lowercase.go b/core/services/pipeline/task.lowercase.go index f2ea98b2efb..e9bd66ed118 100644 --- a/core/services/pipeline/task.lowercase.go +++ b/core/services/pipeline/task.lowercase.go @@ -2,10 +2,10 @@ package pipeline import ( "context" + "errors" "strings" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -27,13 +27,13 @@ func (t *LowercaseTask) Type() TaskType { func (t *LowercaseTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var input StringParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err != nil { return Result{Error: err}, runInfo diff --git a/core/services/pipeline/task.mean.go b/core/services/pipeline/task.mean.go index 48635a4c681..68135af10cd 100644 --- a/core/services/pipeline/task.mean.go +++ b/core/services/pipeline/task.mean.go @@ -2,10 +2,10 @@ package pipeline import ( "context" + "errors" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -35,10 +35,10 @@ func (t *MeanTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, input allowedFaults int faults int ) - err := multierr.Combine( - errors.Wrap(ResolveParam(&maybeAllowedFaults, From(t.AllowedFaults)), "allowedFaults"), - errors.Wrap(ResolveParam(&maybePrecision, From(VarExpr(t.Precision, vars), t.Precision)), "precision"), - errors.Wrap(ResolveParam(&valuesAndErrs, From(VarExpr(t.Values, vars), JSONWithVarExprs(t.Values, vars, true), Inputs(inputs))), "values"), + err := errors.Join( + pkgerrors.Wrap(ResolveParam(&maybeAllowedFaults, From(t.AllowedFaults)), "allowedFaults"), + pkgerrors.Wrap(ResolveParam(&maybePrecision, From(VarExpr(t.Precision, vars), t.Precision)), "precision"), + pkgerrors.Wrap(ResolveParam(&valuesAndErrs, From(VarExpr(t.Values, vars), JSONWithVarExprs(t.Values, vars, true), Inputs(inputs))), "values"), ) if err != nil { return Result{Error: err}, runInfo @@ -52,14 +52,14 @@ func (t *MeanTask) Run(ctx context.Context, lggr logger.Logger, vars Vars, input values, faults := valuesAndErrs.FilterErrors() if faults > allowedFaults { - return Result{Error: errors.Wrapf(ErrTooManyErrors, "Number of faulty inputs %v to mean task > number allowed faults %v", faults, allowedFaults)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrTooManyErrors, "Number of faulty inputs %v to mean task > number allowed faults %v", faults, allowedFaults)}, runInfo } else if len(values) == 0 { - return Result{Error: errors.Wrap(ErrWrongInputCardinality, "values")}, runInfo + return Result{Error: pkgerrors.Wrap(ErrWrongInputCardinality, "values")}, runInfo } err = decimalValues.UnmarshalPipelineParam(values) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "values: %v", err)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "values: %v", err)}, runInfo } total := decimal.NewFromInt(0) diff --git a/core/services/pipeline/task.median.go b/core/services/pipeline/task.median.go index 5ccf325c2cb..6a850457a98 100644 --- a/core/services/pipeline/task.median.go +++ b/core/services/pipeline/task.median.go @@ -2,11 +2,11 @@ package pipeline import ( "context" + "errors" "sort" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -34,9 +34,9 @@ func (t *MedianTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs [ allowedFaults int faults int ) - err := multierr.Combine( - errors.Wrap(ResolveParam(&maybeAllowedFaults, From(t.AllowedFaults)), "allowedFaults"), - errors.Wrap(ResolveParam(&valuesAndErrs, From(VarExpr(t.Values, vars), JSONWithVarExprs(t.Values, vars, true), Inputs(inputs))), "values"), + err := errors.Join( + pkgerrors.Wrap(ResolveParam(&maybeAllowedFaults, From(t.AllowedFaults)), "allowedFaults"), + pkgerrors.Wrap(ResolveParam(&valuesAndErrs, From(VarExpr(t.Values, vars), JSONWithVarExprs(t.Values, vars, true), Inputs(inputs))), "values"), ) if err != nil { return Result{Error: err}, runInfo @@ -50,9 +50,9 @@ func (t *MedianTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs [ values, faults := valuesAndErrs.FilterErrors() if faults > allowedFaults { - return Result{Error: errors.Wrapf(ErrTooManyErrors, "Number of faulty inputs %v to median task > number allowed faults %v", faults, allowedFaults)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrTooManyErrors, "Number of faulty inputs %v to median task > number allowed faults %v", faults, allowedFaults)}, runInfo } else if len(values) == 0 { - return Result{Error: errors.Wrap(ErrWrongInputCardinality, "no values to medianize")}, runInfo + return Result{Error: pkgerrors.Wrap(ErrWrongInputCardinality, "no values to medianize")}, runInfo } err = decimalValues.UnmarshalPipelineParam(values) diff --git a/core/services/pipeline/task.merge.go b/core/services/pipeline/task.merge.go index fc3d49a9b3b..eb9212953a9 100644 --- a/core/services/pipeline/task.merge.go +++ b/core/services/pipeline/task.merge.go @@ -2,9 +2,9 @@ package pipeline import ( "context" + "errors" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -27,16 +27,16 @@ func (t *MergeTask) Type() TaskType { func (t *MergeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( lMap MapParam rMap MapParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&lMap, From(VarExpr(t.Left, vars), JSONWithVarExprs(t.Left, vars, false), Input(inputs, 0))), "left-side"), - errors.Wrap(ResolveParam(&rMap, From(VarExpr(t.Right, vars), JSONWithVarExprs(t.Right, vars, false))), "right-side"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&lMap, From(VarExpr(t.Left, vars), JSONWithVarExprs(t.Left, vars, false), Input(inputs, 0))), "left-side"), + pkgerrors.Wrap(ResolveParam(&rMap, From(VarExpr(t.Right, vars), JSONWithVarExprs(t.Right, vars, false))), "right-side"), ) if err != nil { return Result{Error: err}, runInfo diff --git a/core/services/pipeline/task.mode.go b/core/services/pipeline/task.mode.go index f77f1637d97..1f6e14e556f 100644 --- a/core/services/pipeline/task.mode.go +++ b/core/services/pipeline/task.mode.go @@ -3,12 +3,12 @@ package pipeline import ( "context" "encoding/json" + "errors" "fmt" "math/big" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -38,9 +38,9 @@ func (t *ModeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []R allowedFaults int faults int ) - err := multierr.Combine( - errors.Wrap(ResolveParam(&maybeAllowedFaults, From(t.AllowedFaults)), "allowedFaults"), - errors.Wrap(ResolveParam(&valuesAndErrs, From(VarExpr(t.Values, vars), JSONWithVarExprs(t.Values, vars, true), Inputs(inputs))), "values"), + err := errors.Join( + pkgerrors.Wrap(ResolveParam(&maybeAllowedFaults, From(t.AllowedFaults)), "allowedFaults"), + pkgerrors.Wrap(ResolveParam(&valuesAndErrs, From(VarExpr(t.Values, vars), JSONWithVarExprs(t.Values, vars, true), Inputs(inputs))), "values"), ) if err != nil { return Result{Error: err}, runInfo @@ -54,9 +54,9 @@ func (t *ModeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []R values, faults := valuesAndErrs.FilterErrors() if faults > allowedFaults { - return Result{Error: errors.Wrapf(ErrTooManyErrors, "Number of faulty inputs %v to mode task > number allowed faults %v", faults, allowedFaults)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrTooManyErrors, "Number of faulty inputs %v to mode task > number allowed faults %v", faults, allowedFaults)}, runInfo } else if len(values) == 0 { - return Result{Error: errors.Wrap(ErrWrongInputCardinality, "values")}, runInfo + return Result{Error: pkgerrors.Wrap(ErrWrongInputCardinality, "values")}, runInfo } type entry struct { @@ -88,7 +88,7 @@ func (t *ModeTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []R default: bs, err := json.Marshal(v) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "could not json stringify value: %v", err)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "could not json stringify value: %v", err)}, runInfo } comparable = string(bs) } diff --git a/core/services/pipeline/task.multiply.go b/core/services/pipeline/task.multiply.go index b28cd0a9c92..a9b15d94ab9 100644 --- a/core/services/pipeline/task.multiply.go +++ b/core/services/pipeline/task.multiply.go @@ -2,10 +2,10 @@ package pipeline import ( "context" + "errors" "math" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -21,7 +21,7 @@ type MultiplyTask struct { var ( _ Task = (*MultiplyTask)(nil) - ErrMultiplyOverlow = errors.New("multiply overflow") + ErrMultiplyOverlow = pkgerrors.New("multiply overflow") ) func (t *MultiplyTask) Type() TaskType { @@ -31,7 +31,7 @@ func (t *MultiplyTask) Type() TaskType { func (t *MultiplyTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var ( @@ -39,9 +39,9 @@ func (t *MultiplyTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs b DecimalParam ) - err = multierr.Combine( - errors.Wrap(ResolveParam(&a, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), - errors.Wrap(ResolveParam(&b, From(VarExpr(t.Times, vars), NonemptyString(t.Times))), "times"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&a, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + pkgerrors.Wrap(ResolveParam(&b, From(VarExpr(t.Times, vars), NonemptyString(t.Times))), "times"), ) if err != nil { return Result{Error: err}, runInfo diff --git a/core/services/pipeline/task.sum.go b/core/services/pipeline/task.sum.go index 121a33a17f7..ccfd443f35c 100644 --- a/core/services/pipeline/task.sum.go +++ b/core/services/pipeline/task.sum.go @@ -2,10 +2,10 @@ package pipeline import ( "context" + "errors" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -33,9 +33,9 @@ func (t *SumTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Re allowedFaults int faults int ) - err := multierr.Combine( - errors.Wrap(ResolveParam(&maybeAllowedFaults, From(t.AllowedFaults)), "allowedFaults"), - errors.Wrap(ResolveParam(&valuesAndErrs, From(VarExpr(t.Values, vars), JSONWithVarExprs(t.Values, vars, true), Inputs(inputs))), "values"), + err := errors.Join( + pkgerrors.Wrap(ResolveParam(&maybeAllowedFaults, From(t.AllowedFaults)), "allowedFaults"), + pkgerrors.Wrap(ResolveParam(&valuesAndErrs, From(VarExpr(t.Values, vars), JSONWithVarExprs(t.Values, vars, true), Inputs(inputs))), "values"), ) if err != nil { return Result{Error: err}, runInfo @@ -49,14 +49,14 @@ func (t *SumTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Re values, faults := valuesAndErrs.FilterErrors() if faults > allowedFaults { - return Result{Error: errors.Wrapf(ErrTooManyErrors, "Number of faulty inputs %v to sum task > number allowed faults %v", faults, allowedFaults)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrTooManyErrors, "Number of faulty inputs %v to sum task > number allowed faults %v", faults, allowedFaults)}, runInfo } else if len(values) == 0 { - return Result{Error: errors.Wrap(ErrWrongInputCardinality, "values")}, runInfo + return Result{Error: pkgerrors.Wrap(ErrWrongInputCardinality, "values")}, runInfo } err = decimalValues.UnmarshalPipelineParam(values) if err != nil { - return Result{Error: errors.Wrapf(ErrBadInput, "values: %v", err)}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "values: %v", err)}, runInfo } sum := decimal.NewFromInt(0) diff --git a/core/services/pipeline/task.uppercase.go b/core/services/pipeline/task.uppercase.go index 9e1896fb9c2..39985969b68 100644 --- a/core/services/pipeline/task.uppercase.go +++ b/core/services/pipeline/task.uppercase.go @@ -2,10 +2,10 @@ package pipeline import ( "context" + "errors" "strings" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -27,13 +27,13 @@ func (t *UppercaseTask) Type() TaskType { func (t *UppercaseTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) { _, err := CheckInputs(inputs, 0, 1, 0) if err != nil { - return Result{Error: errors.Wrap(err, "task inputs")}, runInfo + return Result{Error: pkgerrors.Wrap(err, "task inputs")}, runInfo } var input StringParam - err = multierr.Combine( - errors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), + err = errors.Join( + pkgerrors.Wrap(ResolveParam(&input, From(VarExpr(t.Input, vars), NonemptyString(t.Input), Input(inputs, 0))), "input"), ) if err != nil { return Result{Error: err}, runInfo diff --git a/core/services/pipeline/task.vrf.go b/core/services/pipeline/task.vrf.go index 0a2ed4d003d..e2cabdcc0fe 100644 --- a/core/services/pipeline/task.vrf.go +++ b/core/services/pipeline/task.vrf.go @@ -4,13 +4,13 @@ import ( "bytes" "context" "encoding/hex" + "errors" "fmt" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/vrfkey" @@ -47,7 +47,7 @@ func (t *VRFTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Re } logValues, ok := inputs[0].Value.(map[string]interface{}) if !ok { - return Result{Error: errors.Wrap(ErrBadInput, "expected map input")}, runInfo + return Result{Error: pkgerrors.Wrap(ErrBadInput, "expected map input")}, runInfo } var ( pubKey BytesParam @@ -55,11 +55,11 @@ func (t *VRFTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Re requestBlockNumber Uint64Param topics HashSliceParam ) - err := multierr.Combine( - errors.Wrap(ResolveParam(&pubKey, From(VarExpr(t.PublicKey, vars))), "publicKey"), - errors.Wrap(ResolveParam(&requestBlockHash, From(VarExpr(t.RequestBlockHash, vars))), "requestBlockHash"), - errors.Wrap(ResolveParam(&requestBlockNumber, From(VarExpr(t.RequestBlockNumber, vars))), "requestBlockNumber"), - errors.Wrap(ResolveParam(&topics, From(VarExpr(t.Topics, vars))), "topics"), + err := errors.Join( + pkgerrors.Wrap(ResolveParam(&pubKey, From(VarExpr(t.PublicKey, vars))), "publicKey"), + pkgerrors.Wrap(ResolveParam(&requestBlockHash, From(VarExpr(t.RequestBlockHash, vars))), "requestBlockHash"), + pkgerrors.Wrap(ResolveParam(&requestBlockNumber, From(VarExpr(t.RequestBlockNumber, vars))), "requestBlockNumber"), + pkgerrors.Wrap(ResolveParam(&topics, From(VarExpr(t.Topics, vars))), "topics"), ) if err != nil { return Result{Error: err}, runInfo @@ -67,15 +67,15 @@ func (t *VRFTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Re requestKeyHash, ok := logValues["keyHash"].([32]byte) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid keyHash")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid keyHash")}, runInfo } requestPreSeed, ok := logValues["seed"].(*big.Int) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid preSeed")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid preSeed")}, runInfo } requestJobID, ok := logValues["jobID"].([32]byte) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid requestJobID")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid requestJobID")}, runInfo } pk, err := secp256k1.NewPublicKeyFromBytes(pubKey) if err != nil { diff --git a/core/services/pipeline/task.vrfv2.go b/core/services/pipeline/task.vrfv2.go index 2c2c85eaedf..a543d5e2bd2 100644 --- a/core/services/pipeline/task.vrfv2.go +++ b/core/services/pipeline/task.vrfv2.go @@ -4,13 +4,13 @@ import ( "bytes" "context" "encoding/hex" + "errors" "fmt" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/vrf_coordinator_v2" @@ -48,7 +48,7 @@ func (t *VRFTaskV2) Run(_ context.Context, lggr logger.Logger, vars Vars, inputs } logValues, ok := inputs[0].Value.(map[string]interface{}) if !ok { - return Result{Error: errors.Wrap(ErrBadInput, "expected map input")}, runInfo + return Result{Error: pkgerrors.Wrap(ErrBadInput, "expected map input")}, runInfo } var ( pubKey BytesParam @@ -56,11 +56,11 @@ func (t *VRFTaskV2) Run(_ context.Context, lggr logger.Logger, vars Vars, inputs requestBlockNumber Uint64Param topics HashSliceParam ) - err := multierr.Combine( - errors.Wrap(ResolveParam(&pubKey, From(VarExpr(t.PublicKey, vars))), "publicKey"), - errors.Wrap(ResolveParam(&requestBlockHash, From(VarExpr(t.RequestBlockHash, vars))), "requestBlockHash"), - errors.Wrap(ResolveParam(&requestBlockNumber, From(VarExpr(t.RequestBlockNumber, vars))), "requestBlockNumber"), - errors.Wrap(ResolveParam(&topics, From(VarExpr(t.Topics, vars))), "topics"), + err := errors.Join( + pkgerrors.Wrap(ResolveParam(&pubKey, From(VarExpr(t.PublicKey, vars))), "publicKey"), + pkgerrors.Wrap(ResolveParam(&requestBlockHash, From(VarExpr(t.RequestBlockHash, vars))), "requestBlockHash"), + pkgerrors.Wrap(ResolveParam(&requestBlockNumber, From(VarExpr(t.RequestBlockNumber, vars))), "requestBlockNumber"), + pkgerrors.Wrap(ResolveParam(&topics, From(VarExpr(t.Topics, vars))), "topics"), ) if err != nil { return Result{Error: err}, runInfo @@ -68,31 +68,31 @@ func (t *VRFTaskV2) Run(_ context.Context, lggr logger.Logger, vars Vars, inputs requestKeyHash, ok := logValues["keyHash"].([32]byte) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid keyHash")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid keyHash")}, runInfo } requestPreSeed, ok := logValues["preSeed"].(*big.Int) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid preSeed")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid preSeed")}, runInfo } requestId, ok := logValues["requestId"].(*big.Int) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid requestId")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid requestId")}, runInfo } subID, ok := logValues["subId"].(uint64) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid subId")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid subId")}, runInfo } callbackGasLimit, ok := logValues["callbackGasLimit"].(uint32) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid callbackGasLimit")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid callbackGasLimit")}, runInfo } numWords, ok := logValues["numWords"].(uint32) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid numWords")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid numWords")}, runInfo } sender, ok := logValues["sender"].(common.Address) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid sender")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid sender")}, runInfo } pk, err := secp256k1.NewPublicKeyFromBytes(pubKey) if err != nil { diff --git a/core/services/pipeline/task.vrfv2plus.go b/core/services/pipeline/task.vrfv2plus.go index c029af68cbe..e13ef021620 100644 --- a/core/services/pipeline/task.vrfv2plus.go +++ b/core/services/pipeline/task.vrfv2plus.go @@ -4,13 +4,13 @@ import ( "bytes" "context" "encoding/hex" + "errors" "fmt" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/vrf_coordinator_v2plus_interface" @@ -51,7 +51,7 @@ func (t *VRFTaskV2Plus) Run(_ context.Context, lggr logger.Logger, vars Vars, in } logValues, ok := inputs[0].Value.(map[string]interface{}) if !ok { - return Result{Error: errors.Wrap(ErrBadInput, "expected map input")}, runInfo + return Result{Error: pkgerrors.Wrap(ErrBadInput, "expected map input")}, runInfo } var ( pubKey BytesParam @@ -59,11 +59,11 @@ func (t *VRFTaskV2Plus) Run(_ context.Context, lggr logger.Logger, vars Vars, in requestBlockNumber Uint64Param topics HashSliceParam ) - err := multierr.Combine( - errors.Wrap(ResolveParam(&pubKey, From(VarExpr(t.PublicKey, vars))), "publicKey"), - errors.Wrap(ResolveParam(&requestBlockHash, From(VarExpr(t.RequestBlockHash, vars))), "requestBlockHash"), - errors.Wrap(ResolveParam(&requestBlockNumber, From(VarExpr(t.RequestBlockNumber, vars))), "requestBlockNumber"), - errors.Wrap(ResolveParam(&topics, From(VarExpr(t.Topics, vars))), "topics"), + err := errors.Join( + pkgerrors.Wrap(ResolveParam(&pubKey, From(VarExpr(t.PublicKey, vars))), "publicKey"), + pkgerrors.Wrap(ResolveParam(&requestBlockHash, From(VarExpr(t.RequestBlockHash, vars))), "requestBlockHash"), + pkgerrors.Wrap(ResolveParam(&requestBlockNumber, From(VarExpr(t.RequestBlockNumber, vars))), "requestBlockNumber"), + pkgerrors.Wrap(ResolveParam(&topics, From(VarExpr(t.Topics, vars))), "topics"), ) if err != nil { return Result{Error: err}, runInfo @@ -71,35 +71,35 @@ func (t *VRFTaskV2Plus) Run(_ context.Context, lggr logger.Logger, vars Vars, in requestKeyHash, ok := logValues["keyHash"].([32]byte) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid keyHash")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid keyHash")}, runInfo } requestPreSeed, ok := logValues["preSeed"].(*big.Int) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid preSeed")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid preSeed")}, runInfo } requestId, ok := logValues["requestId"].(*big.Int) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid requestId")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid requestId")}, runInfo } subID, ok := logValues["subId"].(*big.Int) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid subId")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid subId")}, runInfo } callbackGasLimit, ok := logValues["callbackGasLimit"].(uint32) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid callbackGasLimit")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid callbackGasLimit")}, runInfo } numWords, ok := logValues["numWords"].(uint32) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid numWords")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid numWords")}, runInfo } sender, ok := logValues["sender"].(common.Address) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid sender")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid sender")}, runInfo } extraArgs, ok := logValues["extraArgs"].([]byte) if !ok { - return Result{Error: errors.Wrapf(ErrBadInput, "invalid extraArgs")}, runInfo + return Result{Error: pkgerrors.Wrapf(ErrBadInput, "invalid extraArgs")}, runInfo } pk, err := secp256k1.NewPublicKeyFromBytes(pubKey) if err != nil { diff --git a/core/services/promreporter/prom_reporter.go b/core/services/promreporter/prom_reporter.go index a302a6fa220..4560d03ff32 100644 --- a/core/services/promreporter/prom_reporter.go +++ b/core/services/promreporter/prom_reporter.go @@ -3,6 +3,7 @@ package promreporter import ( "context" "database/sql" + "errors" "fmt" "math/big" "sync" @@ -11,10 +12,9 @@ import ( txmgrcommon "github.com/smartcontractkit/chainlink/v2/common/txmgr" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/txmgr" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink-common/pkg/utils/mailbox" @@ -158,7 +158,7 @@ func (pr *promReporter) eventLoop() { } pr.reportHeadMetrics(ctx, head) case <-time.After(pr.reportPeriod): - if err := errors.Wrap(pr.reportPipelineRunStats(ctx), "reportPipelineRunStats failed"); err != nil { + if err := pkgerrors.Wrap(pr.reportPipelineRunStats(ctx), "reportPipelineRunStats failed"); err != nil { pr.lggr.Errorw("Error reporting prometheus metrics", "err", err) } @@ -178,10 +178,10 @@ func (pr *promReporter) getTxm(evmChainID *big.Int) (txmgr.TxManager, error) { func (pr *promReporter) reportHeadMetrics(ctx context.Context, head *evmtypes.Head) { evmChainID := head.EVMChainID.ToInt() - err := multierr.Combine( - errors.Wrap(pr.reportPendingEthTxes(ctx, evmChainID), "reportPendingEthTxes failed"), - errors.Wrap(pr.reportMaxUnconfirmedAge(ctx, evmChainID), "reportMaxUnconfirmedAge failed"), - errors.Wrap(pr.reportMaxUnconfirmedBlocks(ctx, head), "reportMaxUnconfirmedBlocks failed"), + err := errors.Join( + pkgerrors.Wrap(pr.reportPendingEthTxes(ctx, evmChainID), "reportPendingEthTxes failed"), + pkgerrors.Wrap(pr.reportMaxUnconfirmedAge(ctx, evmChainID), "reportMaxUnconfirmedAge failed"), + pkgerrors.Wrap(pr.reportMaxUnconfirmedBlocks(ctx, head), "reportMaxUnconfirmedBlocks failed"), ) if err != nil && ctx.Err() == nil { @@ -246,10 +246,10 @@ func (pr *promReporter) reportPipelineRunStats(ctx context.Context) (err error) SELECT pipeline_run_id FROM pipeline_task_runs WHERE finished_at IS NULL `) if err != nil { - return errors.Wrap(err, "failed to query for pipeline_run_id") + return pkgerrors.Wrap(err, "failed to query for pipeline_run_id") } defer func() { - err = multierr.Combine(err, rows.Close()) + err = errors.Join(err, rows.Close()) }() pipelineTaskRunsQueued := 0 @@ -257,7 +257,7 @@ SELECT pipeline_run_id FROM pipeline_task_runs WHERE finished_at IS NULL for rows.Next() { var pipelineRunID int32 if err = rows.Scan(&pipelineRunID); err != nil { - return errors.Wrap(err, "unexpected error scanning row") + return pkgerrors.Wrap(err, "unexpected error scanning row") } pipelineTaskRunsQueued++ pipelineRunsQueuedSet[pipelineRunID] = struct{}{} diff --git a/core/services/relay/evm/functions.go b/core/services/relay/evm/functions.go index f1d652fd6f8..a9869f6f55e 100644 --- a/core/services/relay/evm/functions.go +++ b/core/services/relay/evm/functions.go @@ -3,17 +3,16 @@ package evm import ( "context" "encoding/json" + "errors" "fmt" "strings" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" - "go.uber.org/multierr" - ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -63,8 +62,8 @@ func (p *functionsProvider) Start(ctx context.Context) error { func (p *functionsProvider) Close() error { return p.StopOnce("FunctionsProvider", func() (err error) { - err = multierr.Combine(err, p.logPollerWrapper.Close()) - err = multierr.Combine(err, p.configWatcher.Close()) + err = errors.Join(err, p.logPollerWrapper.Close()) + err = errors.Join(err, p.configWatcher.Close()) return }) } @@ -104,7 +103,7 @@ func NewFunctionsProvider(chain legacyevm.Chain, rargs commontypes.RelayArgs, pa return nil, err } if !common.IsHexAddress(rargs.ContractID) { - return nil, errors.Errorf("invalid contractID, expected hex address") + return nil, pkgerrors.Errorf("invalid contractID, expected hex address") } var pluginConfig config.PluginConfig if err2 := json.Unmarshal(pargs.PluginConfig, &pluginConfig); err2 != nil { @@ -137,13 +136,13 @@ func NewFunctionsProvider(chain legacyevm.Chain, rargs commontypes.RelayArgs, pa func newFunctionsConfigProvider(pluginType functionsRelay.FunctionsPluginType, chain legacyevm.Chain, args commontypes.RelayArgs, fromBlock uint64, logPollerWrapper evmRelayTypes.LogPollerWrapper, lggr logger.Logger) (*configWatcher, error) { if !common.IsHexAddress(args.ContractID) { - return nil, errors.Errorf("invalid contractID, expected hex address") + return nil, pkgerrors.Errorf("invalid contractID, expected hex address") } routerContractAddress := common.HexToAddress(args.ContractID) contractABI, err := abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorMetaData.ABI)) if err != nil { - return nil, errors.Wrap(err, "could not get contract ABI JSON") + return nil, pkgerrors.Wrap(err, "could not get contract ABI JSON") } cp, err := functionsRelay.NewFunctionsConfigPoller(pluginType, chain.LogPoller(), lggr) @@ -166,23 +165,23 @@ func newFunctionsContractTransmitter(contractVersion uint32, rargs commontypes.R var fromAddresses []common.Address sendingKeys := relayConfig.SendingKeys if !relayConfig.EffectiveTransmitterID.Valid { - return nil, errors.New("EffectiveTransmitterID must be specified") + return nil, pkgerrors.New("EffectiveTransmitterID must be specified") } effectiveTransmitterAddress := common.HexToAddress(relayConfig.EffectiveTransmitterID.String) sendingKeysLength := len(sendingKeys) if sendingKeysLength == 0 { - return nil, errors.New("no sending keys provided") + return nil, pkgerrors.New("no sending keys provided") } // If we are using multiple sending keys, then a forwarder is needed to rotate transmissions. // Ensure that this forwarder is not set to a local sending key, and ensure our sending keys are enabled. for _, s := range sendingKeys { if sendingKeysLength > 1 && s == effectiveTransmitterAddress.String() { - return nil, errors.New("the transmitter is a local sending key with transaction forwarding enabled") + return nil, pkgerrors.New("the transmitter is a local sending key with transaction forwarding enabled") } if err := ethKeystore.CheckEnabled(common.HexToAddress(s), configWatcher.chain.Config().EVM().ChainID()); err != nil { - return nil, errors.Wrap(err, "one of the sending keys given is not enabled") + return nil, pkgerrors.Wrap(err, "one of the sending keys given is not enabled") } fromAddresses = append(fromAddresses, common.HexToAddress(s)) } @@ -213,7 +212,7 @@ func newFunctionsContractTransmitter(contractVersion uint32, rargs commontypes.R ) if err != nil { - return nil, errors.Wrap(err, "failed to create transmitter") + return nil, pkgerrors.Wrap(err, "failed to create transmitter") } functionsTransmitter, err := functionsRelay.NewFunctionsContractTransmitter( diff --git a/core/services/relay/evm/relayer_extender.go b/core/services/relay/evm/relayer_extender.go index 83f03b47f9e..2fd1ee6f666 100644 --- a/core/services/relay/evm/relayer_extender.go +++ b/core/services/relay/evm/relayer_extender.go @@ -2,11 +2,11 @@ package evm import ( "context" + "errors" "fmt" "math/big" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/loop" commontypes "github.com/smartcontractkit/chainlink-common/pkg/types" @@ -16,7 +16,7 @@ import ( ) // ErrNoChains indicates that no EVM chains have been started -var ErrNoChains = errors.New("no EVM chains loaded") +var ErrNoChains = pkgerrors.New("no EVM chains loaded") type EVMChainRelayerExtender interface { loop.RelayerExt @@ -94,7 +94,7 @@ func (s *ChainRelayerExt) Chain() legacyevm.Chain { return s.chain } -var ErrCorruptEVMChain = errors.New("corrupt evm chain") +var ErrCorruptEVMChain = pkgerrors.New("corrupt evm chain") func (s *ChainRelayerExt) Start(ctx context.Context) error { return s.chain.Start(ctx) @@ -150,7 +150,7 @@ func NewChainRelayerExtenders(ctx context.Context, opts legacyevm.ChainRelayExte privOpts.Logger.Infow(fmt.Sprintf("Loading chain %s", cid), "evmChainID", cid) chain, err2 := legacyevm.NewTOMLChain(ctx, enabled[i], privOpts) if err2 != nil { - err = multierr.Combine(err, fmt.Errorf("failed to create chain %s: %w", cid, err2)) + err = errors.Join(err, fmt.Errorf("failed to create chain %s: %w", cid, err2)) continue } diff --git a/core/services/relay/grpc_provider_server.go b/core/services/relay/grpc_provider_server.go index 67bbb8c6c2a..29c7c834332 100644 --- a/core/services/relay/grpc_provider_server.go +++ b/core/services/relay/grpc_provider_server.go @@ -2,9 +2,9 @@ package relay import ( "context" + "errors" "net" - "go.uber.org/multierr" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" @@ -28,7 +28,7 @@ func (p *ProviderServer) Start(ctx context.Context) error { func (p *ProviderServer) Close() error { var err error for _, c := range p.conns { - err = multierr.Combine(err, c.Close()) + err = errors.Join(err, c.Close()) } p.s.Stop() return err diff --git a/core/services/vrf/v2/listener_v2_log_processor.go b/core/services/vrf/v2/listener_v2_log_processor.go index eebe9038c0c..221900f0029 100644 --- a/core/services/vrf/v2/listener_v2_log_processor.go +++ b/core/services/vrf/v2/listener_v2_log_processor.go @@ -4,6 +4,7 @@ import ( "cmp" "context" "database/sql" + "errors" "fmt" "math" "math/big" @@ -17,7 +18,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" "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/utils/hex" @@ -209,11 +210,11 @@ func (lsn *listenerV2) MaybeSubtractReservedLink(ctx context.Context, startBalan } else if vrfVersion == vrfcommon.V2 { metaField = txMetaFieldSubId } else { - return nil, errors.Errorf("unsupported vrf version %s", vrfVersion) + return nil, pkgerrors.Errorf("unsupported vrf version %s", vrfVersion) } txes, err := lsn.chain.TxManager().FindTxesByMetaFieldAndStates(ctx, metaField, subID.String(), reserveEthLinkQueryStates, chainID) - if err != nil && !errors.Is(err, sql.ErrNoRows) { + if err != nil && !pkgerrors.Is(err, sql.ErrNoRows) { return nil, fmt.Errorf("TXM FindTxesByMetaFieldAndStates failed: %w", err) } @@ -249,10 +250,10 @@ func (lsn *listenerV2) MaybeSubtractReservedEth(ctx context.Context, startBalanc // native payment is not supported for v2, so returning 0 reserved ETH return big.NewInt(0), nil } else { - return nil, errors.Errorf("unsupported vrf version %s", vrfVersion) + return nil, pkgerrors.Errorf("unsupported vrf version %s", vrfVersion) } txes, err := lsn.chain.TxManager().FindTxesByMetaFieldAndStates(ctx, metaField, subID.String(), reserveEthLinkQueryStates, chainID) - if err != nil && !errors.Is(err, sql.ErrNoRows) { + if err != nil && !pkgerrors.Is(err, sql.ErrNoRows) { return nil, fmt.Errorf("TXM FindTxesByMetaFieldAndStates failed: %w", err) } @@ -345,7 +346,7 @@ func (lsn *listenerV2) processRequestsPerSubBatchHelper( var unfulfilled []pendingRequest alreadyFulfilled, err := lsn.checkReqsFulfilled(ctx, l, chunk) - if errors.Is(err, context.Canceled) { + if pkgerrors.Is(err, context.Canceled) { l.Infow("Context canceled, stopping request processing", "err", err) return processed } else if err != nil { @@ -396,11 +397,11 @@ func (lsn *listenerV2) processRequestsPerSubBatchHelper( ll = ll.With("fromAddress", fromAddress) if p.err != nil { - if errors.Is(p.err, errBlockhashNotInStore{}) { + if pkgerrors.Is(p.err, errBlockhashNotInStore{}) { // Running the blockhash store feeder in backwards mode will be required to // resolve this. ll.Criticalw("Pipeline error", "err", p.err) - } else if errors.Is(p.err, errProofVerificationFailed{}) { + } else if pkgerrors.Is(p.err, errProofVerificationFailed{}) { // This occurs when the proof reverts in the simulation // This is almost always (if not always) due to a proof generated with an out-of-date // blockhash @@ -427,7 +428,7 @@ func (lsn *listenerV2) processRequestsPerSubBatchHelper( continue } - if startBalanceNoReserved.Cmp(p.fundsNeeded) < 0 && errors.Is(p.err, errPossiblyInsufficientFunds{}) { + if startBalanceNoReserved.Cmp(p.fundsNeeded) < 0 && pkgerrors.Is(p.err, errPossiblyInsufficientFunds{}) { ll.Infow("Insufficient balance to fulfill a request based on estimate, breaking", "err", p.err) outOfBalance = true @@ -554,14 +555,14 @@ func (lsn *listenerV2) enqueueForceFulfillment( fromAddress common.Address, ) (etx txmgr.Tx, err error) { if lsn.job.VRFSpec.VRFOwnerAddress == nil { - err = errors.New("vrf owner address not set in job spec, recreate job and provide it to force-fulfill") + err = pkgerrors.New("vrf owner address not set in job spec, recreate job and provide it to force-fulfill") return } if p.payload == "" { // should probably never happen // a critical log will be logged if this is the case in simulateFulfillment - err = errors.New("empty payload in vrfPipelineResult") + err = pkgerrors.New("empty payload in vrfPipelineResult") return } @@ -686,7 +687,7 @@ func (lsn *listenerV2) processRequestsPerSubHelper( var unfulfilled []pendingRequest alreadyFulfilled, err := lsn.checkReqsFulfilled(ctx, l, chunk) - if errors.Is(err, context.Canceled) { + if pkgerrors.Is(err, context.Canceled) { l.Infow("Context canceled, stopping request processing", "err", err) return processed } else if err != nil { @@ -726,11 +727,11 @@ func (lsn *listenerV2) processRequestsPerSubHelper( ll = ll.With("fromAddress", fromAddress) if p.err != nil { - if errors.Is(p.err, errBlockhashNotInStore{}) { + if pkgerrors.Is(p.err, errBlockhashNotInStore{}) { // Running the blockhash store feeder in backwards mode will be required to // resolve this. ll.Criticalw("Pipeline error", "err", p.err) - } else if errors.Is(p.err, errProofVerificationFailed{}) { + } else if pkgerrors.Is(p.err, errProofVerificationFailed{}) { // This occurs when the proof reverts in the simulation // This is almost always (if not always) due to a proof generated with an out-of-date // blockhash @@ -952,7 +953,7 @@ func (lsn *listenerV2) requestCommitmentPayload(requestID *big.Int) (payload []b } else if lsn.coordinator.Version() == vrfcommon.V2 { return coordinatorV2ABI.Pack("getCommitment", requestID) } - return nil, errors.Errorf("unsupported coordinator version: %s", lsn.coordinator.Version()) + return nil, pkgerrors.Errorf("unsupported coordinator version: %s", lsn.coordinator.Version()) } // checkReqsFulfilled returns a bool slice the same size of the given reqs slice @@ -1136,12 +1137,12 @@ func (lsn *listenerV2) simulateFulfillment( } // The call task will fail if there are insufficient funds if res.run.AllErrors.HasError() { - res.err = errors.WithStack(res.run.AllErrors.ToError()) + res.err = pkgerrors.WithStack(res.run.AllErrors.ToError()) if strings.Contains(res.err.Error(), "blockhash not found in store") { - res.err = multierr.Combine(res.err, errBlockhashNotInStore{}) + res.err = errors.Join(res.err, errBlockhashNotInStore{}) } else if isProofVerificationError(res.err.Error()) { - res.err = multierr.Combine(res.err, errProofVerificationFailed{}) + res.err = errors.Join(res.err, errProofVerificationFailed{}) } else if strings.Contains(res.err.Error(), "execution reverted") { // Even if the simulation fails, we want to get the // txData for the fulfillRandomWords call, in case @@ -1166,21 +1167,21 @@ func (lsn *listenerV2) simulateFulfillment( res.reqCommitment = NewRequestCommitment(m["requestCommitment"]) } } - res.err = multierr.Combine(res.err, errPossiblyInsufficientFunds{}) + res.err = errors.Join(res.err, errPossiblyInsufficientFunds{}) } return res } finalResult := trrs.FinalResult(lg) if len(finalResult.Values) != 1 { - res.err = errors.Errorf("unexpected number of outputs, expected 1, was %d", len(finalResult.Values)) + res.err = pkgerrors.Errorf("unexpected number of outputs, expected 1, was %d", len(finalResult.Values)) return res } // Run succeeded, we expect a byte array representing the billing amount b, ok := finalResult.Values[0].([]uint8) if !ok { - res.err = errors.New("expected []uint8 final result") + res.err = pkgerrors.New("expected []uint8 final result") return res } diff --git a/core/services/webhook/validate.go b/core/services/webhook/validate.go index 6066a863ff7..a62d4492f6f 100644 --- a/core/services/webhook/validate.go +++ b/core/services/webhook/validate.go @@ -1,9 +1,10 @@ package webhook import ( + "errors" + "github.com/pelletier/go-toml" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/services/job" "github.com/smartcontractkit/chainlink/v2/core/store/models" @@ -29,7 +30,7 @@ func ValidatedWebhookSpec(tomlString string, externalInitiatorManager ExternalIn return } if jb.Type != job.Webhook { - return jb, errors.Errorf("unsupported type %s", jb.Type) + return jb, pkgerrors.Errorf("unsupported type %s", jb.Type) } var tomlSpec TOMLWebhookSpec @@ -42,7 +43,7 @@ func ValidatedWebhookSpec(tomlString string, externalInitiatorManager ExternalIn for _, eiSpec := range tomlSpec.ExternalInitiators { ei, findErr := externalInitiatorManager.FindExternalInitiatorByName(eiSpec.Name) if findErr != nil { - err = multierr.Combine(err, errors.Wrapf(findErr, "unable to find external initiator named %s", eiSpec.Name)) + err = errors.Join(err, pkgerrors.Wrapf(findErr, "unable to find external initiator named %s", eiSpec.Name)) continue } eiWS := job.ExternalInitiatorWebhookSpec{ diff --git a/core/utils/files.go b/core/utils/files.go index 71b52a0ea0a..cdea5076288 100644 --- a/core/utils/files.go +++ b/core/utils/files.go @@ -1,6 +1,7 @@ package utils import ( + "errors" "fmt" "os" "regexp" @@ -8,8 +9,7 @@ import ( "strings" "syscall" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" ) // FileExists returns true if a file at the passed string exists. @@ -18,7 +18,7 @@ func FileExists(name string) (bool, error) { if os.IsNotExist(err) { return false, nil } - return false, errors.Wrapf(err, "failed to check if file exists %q", name) + return false, pkgerrors.Wrapf(err, "failed to check if file exists %q", name) } return true, nil } @@ -32,7 +32,7 @@ func TooPermissive(fileMode, maxAllowedPerms os.FileMode) bool { func IsFileOwnedByChainlink(fileInfo os.FileInfo) (bool, error) { stat, ok := fileInfo.Sys().(*syscall.Stat_t) if !ok { - return false, errors.Errorf("Unable to determine file owner of %s", fileInfo.Name()) + return false, pkgerrors.Errorf("Unable to determine file owner of %s", fileInfo.Name()) } return int(stat.Uid) == os.Getuid(), nil } @@ -53,7 +53,7 @@ func EnsureDirAndMaxPerms(path string, perms os.FileMode) error { return os.MkdirAll(path, perms) } else if !stat.IsDir() { // Path exists, but it's a file, so don't clobber - return errors.Errorf("%v already exists and is not a directory", path) + return pkgerrors.Errorf("%v already exists and is not a directory", path) } else if stat.Mode() != perms { // Dir exists, but wrong perms, so chmod return os.Chmod(path, stat.Mode()&perms) @@ -68,7 +68,7 @@ func WriteFileWithMaxPerms(path string, data []byte, perms os.FileMode) (err err if err != nil { return err } - defer func() { err = multierr.Combine(err, f.Close()) }() + defer func() { err = errors.Join(err, f.Close()) }() err = EnsureFileMaxPerms(f, perms) if err != nil { return @@ -97,7 +97,7 @@ func EnsureFilepathMaxPerms(filepath string, perms os.FileMode) (err error) { if err != nil { return err } - defer func() { err = multierr.Combine(err, dst.Close()) }() + defer func() { err = errors.Join(err, dst.Close()) }() return EnsureFileMaxPerms(dst, perms) } @@ -144,7 +144,7 @@ func (s *FileSize) UnmarshalText(bs []byte) error { lc := strings.ToLower(strings.TrimSpace(string(bs))) matches := fsregex.FindAllStringSubmatch(lc, -1) if len(matches) != 1 || len(matches[0]) != 3 || fmt.Sprintf("%s%s", matches[0][1], matches[0][2]) != lc { - return errors.Errorf(`bad filesize expression: "%v"`, string(bs)) + return pkgerrors.Errorf(`bad filesize expression: "%v"`, string(bs)) } var ( @@ -154,12 +154,12 @@ func (s *FileSize) UnmarshalText(bs []byte) error { value, err := strconv.ParseFloat(num, 64) if err != nil { - return errors.Errorf(`bad filesize value: "%v"`, string(bs)) + return pkgerrors.Errorf(`bad filesize value: "%v"`, string(bs)) } u, ok := fsUnitMap[unit] if !ok { - return errors.Errorf(`bad filesize unit: "%v"`, unit) + return pkgerrors.Errorf(`bad filesize unit: "%v"`, unit) } *s = FileSize(value * float64(u)) diff --git a/core/utils/http/http_allowed_ips.go b/core/utils/http/http_allowed_ips.go index 6432e4ff91d..ad0d1e8d59e 100644 --- a/core/utils/http/http_allowed_ips.go +++ b/core/utils/http/http_allowed_ips.go @@ -2,12 +2,12 @@ package http import ( "context" + "errors" "fmt" "net" "time" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -56,7 +56,7 @@ func isRestrictedIP(ip net.IP, cfg httpClientConfig) (bool, error) { blacklisted, err := isBlacklistedIP(ip, cfg) if err != nil { - return false, errors.Wrapf(err, "failed to check IP blacklist status") + return false, pkgerrors.Wrapf(err, "failed to check IP blacklist status") } return blacklisted, nil @@ -69,7 +69,7 @@ func isBlacklistedIP(ip net.IP, cfg httpClientConfig) (bool, error) { } ips, err := net.LookupIP(dbURL.Host) if err != nil { - return true, errors.Wrapf(err, "failed to lookup IP for DB URL") + return true, pkgerrors.Wrapf(err, "failed to lookup IP for DB URL") } for _, dbIP := range ips { if dbIP.Equal(ip) { @@ -79,7 +79,7 @@ func isBlacklistedIP(ip net.IP, cfg httpClientConfig) (bool, error) { return false, nil } -var ErrDisallowedIP = errors.New("disallowed IP") +var ErrDisallowedIP = pkgerrors.New("disallowed IP") // makeRestrictedDialContext returns a dialcontext function using the given arguments func makeRestrictedDialContext(cfg httpClientConfig, lggr logger.Logger) func(context.Context, string, string) (net.Conn, error) { @@ -101,8 +101,8 @@ func makeRestrictedDialContext(cfg httpClientConfig, lggr logger.Logger) func(co if restrict, rerr := isRestrictedIP(a.IP, cfg); rerr != nil { lggr.Errorw("Restricted IP check failed, this IP will be allowed", "ip", a.IP, "err", rerr) } else if restrict { - return nil, multierr.Combine( - errors.Wrapf(ErrDisallowedIP, "disallowed IP %s. Connections to local/private and multicast networks are disabled by default for security reasons", a.IP.String()), + return nil, errors.Join( + pkgerrors.Wrapf(ErrDisallowedIP, "disallowed IP %s. Connections to local/private and multicast networks are disabled by default for security reasons", a.IP.String()), con.Close()) } } diff --git a/core/web/eth_keys_controller.go b/core/web/eth_keys_controller.go index fe76e8863ef..1055872e9f1 100644 --- a/core/web/eth_keys_controller.go +++ b/core/web/eth_keys_controller.go @@ -2,6 +2,7 @@ package web import ( "context" + "errors" "io" "math/big" "net/http" @@ -24,8 +25,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/gin-gonic/gin" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" ) // ETHKeysController manages account keys @@ -70,7 +70,7 @@ func (ekc *ETHKeysController) formatETHKeyResponse() gin.HandlerFunc { r := createETHKeyResource(c, ekc, key.(ethkey.KeyV2), state.(ethkey.State)) jsonAPIResponse(c, r, "keys") } else { - err := errors.Errorf("error getting eth key and state: %v", c) + err := pkgerrors.Errorf("error getting eth key and state: %v", c) jsonAPIError(c, http.StatusInternalServerError, err) } } @@ -87,13 +87,13 @@ func (ekc *ETHKeysController) Index(c *gin.Context) { var err error keys, err = ethKeyStore.GetAll() if err != nil { - err = errors.Errorf("error getting unlocked keys: %v", err) + err = pkgerrors.Errorf("error getting unlocked keys: %v", err) jsonAPIError(c, http.StatusInternalServerError, err) return } states, err := ethKeyStore.GetStatesForKeys(keys) if err != nil { - err = errors.Errorf("error getting key states: %v", err) + err = pkgerrors.Errorf("error getting key states: %v", err) jsonAPIError(c, http.StatusInternalServerError, err) return } @@ -165,13 +165,13 @@ func (ekc *ETHKeysController) Delete(c *gin.Context) { keyID := c.Param("address") if !common.IsHexAddress(keyID) { - jsonAPIError(c, http.StatusBadRequest, errors.Errorf("invalid keyID: %s, must be hex address", keyID)) + jsonAPIError(c, http.StatusBadRequest, pkgerrors.Errorf("invalid keyID: %s, must be hex address", keyID)) return } key, err := ethKeyStore.Get(keyID) if err != nil { - if errors.Is(err, keystore.ErrKeyNotFound) { + if pkgerrors.Is(err, keystore.ErrKeyNotFound) { jsonAPIError(c, http.StatusNotFound, err) return } @@ -267,7 +267,7 @@ func (ekc *ETHKeysController) Chain(c *gin.Context) { keyID := c.Query("address") if !common.IsHexAddress(keyID) { - jsonAPIError(c, http.StatusBadRequest, errors.Errorf("invalid address: %s, must be hex address", keyID)) + jsonAPIError(c, http.StatusBadRequest, pkgerrors.Errorf("invalid address: %s, must be hex address", keyID)) return } address := common.HexToAddress((keyID)) @@ -282,7 +282,7 @@ func (ekc *ETHKeysController) Chain(c *gin.Context) { if abandonStr := c.Query("abandon"); abandonStr != "" { abandon, err = strconv.ParseBool(abandonStr) if err != nil { - jsonAPIError(c, http.StatusBadRequest, errors.Wrapf(err, "invalid value for abandon: expected boolean, got: %s", abandonStr)) + jsonAPIError(c, http.StatusBadRequest, pkgerrors.Wrapf(err, "invalid value for abandon: expected boolean, got: %s", abandonStr)) return } } @@ -291,7 +291,7 @@ func (ekc *ETHKeysController) Chain(c *gin.Context) { if abandon { var resetErr error err = chain.TxManager().Reset(address, abandon) - err = multierr.Combine(err, resetErr) + err = errors.Join(err, resetErr) if err != nil { if strings.Contains(err.Error(), "key state not found with address") { jsonAPIError(c, http.StatusNotFound, err) @@ -307,7 +307,7 @@ func (ekc *ETHKeysController) Chain(c *gin.Context) { var enabled bool enabled, err = strconv.ParseBool(enabledStr) if err != nil { - jsonAPIError(c, http.StatusBadRequest, errors.Wrap(err, "enabled must be bool")) + jsonAPIError(c, http.StatusBadRequest, pkgerrors.Wrap(err, "enabled must be bool")) return } @@ -348,7 +348,7 @@ func (ekc *ETHKeysController) getEthBalance(ctx context.Context, state ethkey.St chainID := state.EVMChainID.ToInt() chain, err := ekc.app.GetRelayers().LegacyEVMChains().Get(chainID.String()) if err != nil { - if !errors.Is(errors.Cause(err), evmrelay.ErrNoChains) { + if !pkgerrors.Is(pkgerrors.Cause(err), evmrelay.ErrNoChains) { ekc.lggr.Errorw("Failed to get EVM Chain", "chainID", chainID, "address", state.Address, "err", err) } return nil @@ -375,7 +375,7 @@ func (ekc *ETHKeysController) getLinkBalance(ctx context.Context, state ethkey.S chainID := state.EVMChainID.ToInt() chain, err := ekc.app.GetRelayers().LegacyEVMChains().Get(chainID.String()) if err != nil { - if !errors.Is(errors.Cause(err), evmrelay.ErrNoChains) { + if !pkgerrors.Is(pkgerrors.Cause(err), evmrelay.ErrNoChains) { ekc.lggr.Errorw("Failed to get EVM Chain", "chainID", chainID, "err", err) } } else { @@ -401,7 +401,7 @@ func (ekc *ETHKeysController) getKeyMaxGasPriceWei(state ethkey.State, keyAddres chainID := state.EVMChainID.ToInt() chain, err := ekc.app.GetRelayers().LegacyEVMChains().Get(chainID.String()) if err != nil { - if !errors.Is(errors.Cause(err), evmrelay.ErrNoChains) { + if !pkgerrors.Is(pkgerrors.Cause(err), evmrelay.ErrNoChains) { ekc.lggr.Errorw("Failed to get EVM Chain", "chainID", chainID, "err", err) } } else { @@ -415,10 +415,10 @@ func (ekc *ETHKeysController) getKeyMaxGasPriceWei(state ethkey.State, keyAddres func (ekc *ETHKeysController) getChain(c *gin.Context, chainIDstr string) (chain legacyevm.Chain, ok bool) { chain, err := getChain(ekc.app.GetRelayers().LegacyEVMChains(), chainIDstr) if err != nil { - if errors.Is(err, ErrInvalidChainID) || errors.Is(err, ErrMultipleChains) { + if pkgerrors.Is(err, ErrInvalidChainID) || pkgerrors.Is(err, ErrMultipleChains) { jsonAPIError(c, http.StatusBadRequest, err) return nil, false - } else if errors.Is(err, ErrMissingChainID) { + } else if pkgerrors.Is(err, ErrMissingChainID) { jsonAPIError(c, http.StatusNotFound, err) return nil, false } diff --git a/core/web/loader/getters.go b/core/web/loader/getters.go index 27a39181ff8..125192b632e 100644 --- a/core/web/loader/getters.go +++ b/core/web/loader/getters.go @@ -2,10 +2,10 @@ package loader import ( "context" + "errors" "github.com/graph-gophers/dataloader" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" commontypes "github.com/smartcontractkit/chainlink-common/pkg/types" @@ -18,7 +18,7 @@ import ( ) // ErrInvalidType indicates that results loaded is not the type expected -var ErrInvalidType = errors.New("invalid type") +var ErrInvalidType = pkgerrors.New("invalid type") // GetChainByID fetches the chain by it's id. func GetChainByID(ctx context.Context, id string) (*commontypes.ChainStatus, error) { @@ -86,9 +86,9 @@ func GetJobRunsByIDs(ctx context.Context, ids []int64) ([]pipeline.Run, error) { thunk := ldr.JobRunsByIDLoader.LoadMany(ctx, dataloader.NewKeysFromStrings(strIDs)) results, errs := thunk() if errs != nil { - merr := multierr.Combine(errs...) + merr := errors.Join(errs...) - return nil, errors.Wrap(merr, "errors fetching runs") + return nil, pkgerrors.Wrap(merr, "errors fetching runs") } runs := []pipeline.Run{} @@ -131,7 +131,7 @@ func GetLatestSpecByJobProposalID(ctx context.Context, jpID string) (*feeds.JobP specs, ok := result.([]feeds.JobProposalSpec) if !ok { - return nil, errors.Wrapf(ErrInvalidType, "Result : %T", result) + return nil, pkgerrors.Wrapf(ErrInvalidType, "Result : %T", result) } max := specs[0]