From 558613d8558fd7899f06e8fdab814975dee8fd0a Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 18 Jan 2024 15:43:29 -0500 Subject: [PATCH 1/4] 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] From e23fc203e8b11dea3ca112d45268c9fe989a8a7f Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 18 Jan 2024 16:16:02 -0500 Subject: [PATCH 2/4] replace multierr.Append and multierr.AppendInto with errors.Join --- core/chains/evm/config/chain_scoped.go | 5 +- core/chains/evm/config/toml/config.go | 74 ++++++++--------- core/cmd/admin_commands.go | 13 ++- core/cmd/blocks_commands.go | 8 +- core/cmd/bridge_commands.go | 7 +- core/cmd/cosmos_transaction_commands.go | 3 +- core/cmd/csa_keys_commands.go | 32 ++++---- core/cmd/eth_keys_commands.go | 48 +++++------ core/cmd/evm_transaction_commands.go | 5 +- core/cmd/forwarders_commands.go | 14 ++-- core/cmd/jobs_commands.go | 20 ++--- core/cmd/keys_commands.go | 36 ++++---- core/cmd/ocr2_keys_commands.go | 38 ++++----- core/cmd/ocr_keys_commands.go | 36 ++++---- core/cmd/p2p_keys_commands.go | 36 ++++---- core/cmd/shell.go | 3 +- core/cmd/shell_local.go | 82 +++++++++---------- core/cmd/shell_remote.go | 58 ++++++------- core/cmd/solana_transaction_commands.go | 3 +- core/cmd/vrf_keys_commands.go | 38 ++++----- core/config/docs/docs.go | 9 +- core/config/toml/types.go | 79 +++++++++--------- core/gethwrappers/versions.go | 32 ++++---- core/services/blockhashstore/feeder.go | 16 ++-- core/services/blockheaderfeeder/delegate.go | 34 ++++---- core/services/chainlink/application.go | 15 ++-- core/services/chainlink/config.go | 28 +++---- core/services/chainlink/config_general.go | 3 +- core/services/gateway/connectionmanager.go | 3 +- .../ocr2keeper/evmregistry/v20/registry.go | 8 +- .../ocr2keeper/evmregistry/v21/registry.go | 13 ++- core/services/ocrcommon/validate.go | 9 +- core/services/telemetry/manager.go | 18 ++-- core/services/vrf/delegate.go | 32 ++++---- .../vrf/v2/listener_v2_log_listener.go | 6 +- .../vrf/v2/listener_v2_log_processor.go | 7 +- core/store/models/common.go | 22 ++--- core/utils/config/validate.go | 14 ++-- core/web/sessions_controller.go | 3 +- 39 files changed, 447 insertions(+), 463 deletions(-) diff --git a/core/chains/evm/config/chain_scoped.go b/core/chains/evm/config/chain_scoped.go index fb6df26b1ad..acd7aea7d26 100644 --- a/core/chains/evm/config/chain_scoped.go +++ b/core/chains/evm/config/chain_scoped.go @@ -1,11 +1,10 @@ package config import ( + "errors" "math/big" "time" - "go.uber.org/multierr" - ocr "github.com/smartcontractkit/libocr/offchainreporting" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting/types" @@ -57,7 +56,7 @@ func (c *ChainScoped) Validate() (err error) { DataSourceGracePeriod: c.EVM().OCR().ObservationGracePeriod(), } if ocrerr := ocr.SanityCheckLocalConfig(lc); ocrerr != nil { - err = multierr.Append(err, ocrerr) + err = errors.Join(err, ocrerr) } return } diff --git a/core/chains/evm/config/toml/config.go b/core/chains/evm/config/toml/config.go index 2348e648696..d314561bac6 100644 --- a/core/chains/evm/config/toml/config.go +++ b/core/chains/evm/config/toml/config.go @@ -1,6 +1,7 @@ package toml import ( + "errors" "fmt" "net/url" "slices" @@ -9,7 +10,6 @@ import ( "github.com/ethereum/go-ethereum/core/txpool/legacypool" "github.com/pelletier/go-toml/v2" "github.com/shopspring/decimal" - "go.uber.org/multierr" "gopkg.in/guregu/null.v4" commonassets "github.com/smartcontractkit/chainlink-common/pkg/assets" @@ -39,7 +39,7 @@ func (cs EVMConfigs) validateKeys() (err error) { chainIDs := commonconfig.UniqueStrings{} for i, c := range cs { if chainIDs.IsDupeFmt(c.ChainID) { - err = multierr.Append(err, commonconfig.NewErrDuplicate(fmt.Sprintf("%d.ChainID", i), c.ChainID.String())) + err = errors.Join(err, commonconfig.NewErrDuplicate(fmt.Sprintf("%d.ChainID", i), c.ChainID.String())) } } @@ -48,7 +48,7 @@ func (cs EVMConfigs) validateKeys() (err error) { for i, c := range cs { for j, n := range c.Nodes { if names.IsDupe(n.Name) { - err = multierr.Append(err, commonconfig.NewErrDuplicate(fmt.Sprintf("%d.Nodes.%d.Name", i, j), *n.Name)) + err = errors.Join(err, commonconfig.NewErrDuplicate(fmt.Sprintf("%d.Nodes.%d.Name", i, j), *n.Name)) } } } @@ -59,7 +59,7 @@ func (cs EVMConfigs) validateKeys() (err error) { for j, n := range c.Nodes { u := (*url.URL)(n.WSURL) if wsURLs.IsDupeFmt(u) { - err = multierr.Append(err, commonconfig.NewErrDuplicate(fmt.Sprintf("%d.Nodes.%d.WSURL", i, j), u.String())) + err = errors.Join(err, commonconfig.NewErrDuplicate(fmt.Sprintf("%d.Nodes.%d.WSURL", i, j), u.String())) } } } @@ -70,7 +70,7 @@ func (cs EVMConfigs) validateKeys() (err error) { for j, n := range c.Nodes { u := (*url.URL)(n.HTTPURL) if httpURLs.IsDupeFmt(u) { - err = multierr.Append(err, commonconfig.NewErrDuplicate(fmt.Sprintf("%d.Nodes.%d.HTTPURL", i, j), u.String())) + err = errors.Join(err, commonconfig.NewErrDuplicate(fmt.Sprintf("%d.Nodes.%d.HTTPURL", i, j), u.String())) } } } @@ -289,29 +289,29 @@ func (c *EVMConfig) SetFrom(f *EVMConfig) { func (c *EVMConfig) ValidateConfig() (err error) { if c.ChainID == nil { - err = multierr.Append(err, commonconfig.ErrMissing{Name: "ChainID", Msg: "required for all chains"}) + err = errors.Join(err, commonconfig.ErrMissing{Name: "ChainID", Msg: "required for all chains"}) } else if c.ChainID.String() == "" { - err = multierr.Append(err, commonconfig.ErrEmpty{Name: "ChainID", Msg: "required for all chains"}) + err = errors.Join(err, commonconfig.ErrEmpty{Name: "ChainID", Msg: "required for all chains"}) } else if must, ok := ChainTypeForID(c.ChainID); ok { // known chain id if c.ChainType == nil && must != "" { - err = multierr.Append(err, commonconfig.ErrMissing{Name: "ChainType", + err = errors.Join(err, commonconfig.ErrMissing{Name: "ChainType", Msg: fmt.Sprintf("only %q can be used with this chain id", must)}) } else if c.ChainType != nil && *c.ChainType != string(must) { if *c.ChainType == "" { - err = multierr.Append(err, commonconfig.ErrEmpty{Name: "ChainType", + err = errors.Join(err, commonconfig.ErrEmpty{Name: "ChainType", Msg: fmt.Sprintf("only %q can be used with this chain id", must)}) } else if must == "" { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "ChainType", Value: *c.ChainType, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "ChainType", Value: *c.ChainType, Msg: "must not be set with this chain id"}) } else { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "ChainType", Value: *c.ChainType, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "ChainType", Value: *c.ChainType, Msg: fmt.Sprintf("only %q can be used with this chain id", must)}) } } } if len(c.Nodes) == 0 { - err = multierr.Append(err, commonconfig.ErrMissing{Name: "Nodes", Msg: "must have at least one node"}) + err = errors.Join(err, commonconfig.ErrMissing{Name: "Nodes", Msg: "must have at least one node"}) } else { var hasPrimary bool for _, n := range c.Nodes { @@ -322,12 +322,12 @@ func (c *EVMConfig) ValidateConfig() (err error) { break } if !hasPrimary { - err = multierr.Append(err, commonconfig.ErrMissing{Name: "Nodes", + err = errors.Join(err, commonconfig.ErrMissing{Name: "Nodes", Msg: "must have at least one primary node with WSURL"}) } } - err = multierr.Append(err, c.Chain.ValidateConfig()) + err = errors.Join(err, c.Chain.ValidateConfig()) return } @@ -376,24 +376,24 @@ func (c *Chain) ValidateConfig() (err error) { chainType = config.ChainType(*c.ChainType) } if !chainType.IsValid() { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "ChainType", Value: *c.ChainType, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "ChainType", Value: *c.ChainType, Msg: config.ErrInvalidChainType.Error()}) } if c.GasEstimator.BumpTxDepth != nil && *c.GasEstimator.BumpTxDepth > *c.Transactions.MaxInFlight { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "GasEstimator.BumpTxDepth", Value: *c.GasEstimator.BumpTxDepth, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "GasEstimator.BumpTxDepth", Value: *c.GasEstimator.BumpTxDepth, Msg: "must be less than or equal to Transactions.MaxInFlight"}) } if *c.HeadTracker.HistoryDepth < *c.FinalityDepth { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "HeadTracker.HistoryDepth", Value: *c.HeadTracker.HistoryDepth, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "HeadTracker.HistoryDepth", Value: *c.HeadTracker.HistoryDepth, Msg: "must be equal to or greater than FinalityDepth"}) } if *c.FinalityDepth < 1 { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "FinalityDepth", Value: *c.FinalityDepth, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "FinalityDepth", Value: *c.FinalityDepth, Msg: "must be greater than or equal to 1"}) } if *c.MinIncomingConfirmations < 1 { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "MinIncomingConfirmations", Value: *c.MinIncomingConfirmations, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "MinIncomingConfirmations", Value: *c.MinIncomingConfirmations, Msg: "must be greater than or equal to 1"}) } return @@ -486,36 +486,36 @@ type GasEstimator struct { func (e *GasEstimator) ValidateConfig() (err error) { if uint64(*e.BumpPercent) < legacypool.DefaultConfig.PriceBump { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "BumpPercent", Value: *e.BumpPercent, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "BumpPercent", Value: *e.BumpPercent, Msg: fmt.Sprintf("may not be less than Geth's default of %d", legacypool.DefaultConfig.PriceBump)}) } if e.TipCapDefault.Cmp(e.TipCapMin) < 0 { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "TipCapDefault", Value: e.TipCapDefault, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "TipCapDefault", Value: e.TipCapDefault, Msg: "must be greater than or equal to TipCapMinimum"}) } if e.FeeCapDefault.Cmp(e.TipCapDefault) < 0 { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "FeeCapDefault", Value: e.TipCapDefault, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "FeeCapDefault", Value: e.TipCapDefault, Msg: "must be greater than or equal to TipCapDefault"}) } if *e.Mode == "FixedPrice" && *e.BumpThreshold == 0 && *e.EIP1559DynamicFees && e.FeeCapDefault.Cmp(e.PriceMax) != 0 { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "FeeCapDefault", Value: e.FeeCapDefault, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "FeeCapDefault", Value: e.FeeCapDefault, Msg: fmt.Sprintf("must be equal to PriceMax (%s) since you are using FixedPrice estimation with gas bumping disabled in "+ "EIP1559 mode - PriceMax will be used as the FeeCap for transactions instead of FeeCapDefault", e.PriceMax)}) } else if e.FeeCapDefault.Cmp(e.PriceMax) > 0 { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "FeeCapDefault", Value: e.FeeCapDefault, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "FeeCapDefault", Value: e.FeeCapDefault, Msg: fmt.Sprintf("must be less than or equal to PriceMax (%s)", e.PriceMax)}) } if e.PriceMin.Cmp(e.PriceDefault) > 0 { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "PriceMin", Value: e.PriceMin, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "PriceMin", Value: e.PriceMin, Msg: "must be less than or equal to PriceDefault"}) } if e.PriceMax.Cmp(e.PriceDefault) < 0 { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "PriceMax", Value: e.PriceMin, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "PriceMax", Value: e.PriceMin, Msg: "must be greater than or equal to PriceDefault"}) } if *e.Mode == "BlockHistory" && *e.BlockHistory.BlockHistorySize <= 0 { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "BlockHistory.BlockHistorySize", Value: *e.BlockHistory.BlockHistorySize, + err = errors.Join(err, commonconfig.ErrInvalid{Name: "BlockHistory.BlockHistorySize", Value: *e.BlockHistory.BlockHistorySize, Msg: "must be greater than or equal to 1 with BlockHistory Mode"}) } @@ -642,7 +642,7 @@ func (ks KeySpecificConfig) ValidateConfig() (err error) { for _, k := range ks { addr := k.Key.String() if _, ok := addrs[addr]; ok { - err = multierr.Append(err, commonconfig.NewErrDuplicate("Key", addr)) + err = errors.Join(err, commonconfig.NewErrDuplicate("Key", addr)) } else { addrs[addr] = struct{}{} } @@ -749,9 +749,9 @@ type Node struct { func (n *Node) ValidateConfig() (err error) { if n.Name == nil { - err = multierr.Append(err, commonconfig.ErrMissing{Name: "Name", Msg: "required for all nodes"}) + err = errors.Join(err, commonconfig.ErrMissing{Name: "Name", Msg: "required for all nodes"}) } else if *n.Name == "" { - err = multierr.Append(err, commonconfig.ErrEmpty{Name: "Name", Msg: "required for all nodes"}) + err = errors.Join(err, commonconfig.ErrEmpty{Name: "Name", Msg: "required for all nodes"}) } var sendOnly bool @@ -760,34 +760,34 @@ func (n *Node) ValidateConfig() (err error) { } if n.WSURL == nil { if !sendOnly { - err = multierr.Append(err, commonconfig.ErrMissing{Name: "WSURL", Msg: "required for primary nodes"}) + err = errors.Join(err, commonconfig.ErrMissing{Name: "WSURL", Msg: "required for primary nodes"}) } } else if n.WSURL.IsZero() { if !sendOnly { - err = multierr.Append(err, commonconfig.ErrEmpty{Name: "WSURL", Msg: "required for primary nodes"}) + err = errors.Join(err, commonconfig.ErrEmpty{Name: "WSURL", Msg: "required for primary nodes"}) } } else { switch n.WSURL.Scheme { case "ws", "wss": default: - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "WSURL", Value: n.WSURL.Scheme, Msg: "must be ws or wss"}) + err = errors.Join(err, commonconfig.ErrInvalid{Name: "WSURL", Value: n.WSURL.Scheme, Msg: "must be ws or wss"}) } } if n.HTTPURL == nil { - err = multierr.Append(err, commonconfig.ErrMissing{Name: "HTTPURL", Msg: "required for all nodes"}) + err = errors.Join(err, commonconfig.ErrMissing{Name: "HTTPURL", Msg: "required for all nodes"}) } else if n.HTTPURL.IsZero() { - err = multierr.Append(err, commonconfig.ErrEmpty{Name: "HTTPURL", Msg: "required for all nodes"}) + err = errors.Join(err, commonconfig.ErrEmpty{Name: "HTTPURL", Msg: "required for all nodes"}) } else { switch n.HTTPURL.Scheme { case "http", "https": default: - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "HTTPURL", Value: n.HTTPURL.Scheme, Msg: "must be http or https"}) + err = errors.Join(err, commonconfig.ErrInvalid{Name: "HTTPURL", Value: n.HTTPURL.Scheme, Msg: "must be http or https"}) } } if n.Order != nil && (*n.Order < 1 || *n.Order > 100) { - err = multierr.Append(err, commonconfig.ErrInvalid{Name: "Order", Value: *n.Order, Msg: "must be between 1 and 100"}) + err = errors.Join(err, commonconfig.ErrInvalid{Name: "Order", Value: *n.Order, Msg: "must be between 1 and 100"}) } else if n.Order == nil { z := int32(100) n.Order = &z diff --git a/core/cmd/admin_commands.go b/core/cmd/admin_commands.go index 799709ad205..a87ffa0a130 100644 --- a/core/cmd/admin_commands.go +++ b/core/cmd/admin_commands.go @@ -15,7 +15,6 @@ import ( "github.com/manyminds/api2go/jsonapi" "github.com/urfave/cli" - "go.uber.org/multierr" cutils "github.com/smartcontractkit/chainlink-common/pkg/utils" @@ -186,7 +185,7 @@ func (s *Shell) ListUsers(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -201,7 +200,7 @@ func (s *Shell) CreateUser(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() var links jsonapi.Links @@ -240,7 +239,7 @@ func (s *Shell) CreateUser(c *cli.Context) (err error) { } defer func() { if cerr := response.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -269,7 +268,7 @@ func (s *Shell) ChangeRole(c *cli.Context) (err error) { } defer func() { if cerr := response.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -289,7 +288,7 @@ func (s *Shell) DeleteUser(c *cli.Context) (err error) { } defer func() { if cerr := response.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -304,7 +303,7 @@ func (s *Shell) Status(c *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() diff --git a/core/cmd/blocks_commands.go b/core/cmd/blocks_commands.go index 72b0523e18d..74c24095072 100644 --- a/core/cmd/blocks_commands.go +++ b/core/cmd/blocks_commands.go @@ -2,13 +2,13 @@ package cmd import ( "bytes" + "errors" "fmt" "net/url" "strconv" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" ) func initBlocksSubCmds(s *Shell) []cli.Command { @@ -41,7 +41,7 @@ func initBlocksSubCmds(s *Shell) []cli.Command { func (s *Shell) ReplayFromBlock(c *cli.Context) (err error) { blockNumber := c.Int64("block-number") if blockNumber <= 0 { - return s.errorOut(errors.New("Must pass a positive value in '--block-number' parameter")) + return s.errorOut(pkgerrors.New("Must pass a positive value in '--block-number' parameter")) } v := url.Values{} @@ -64,7 +64,7 @@ func (s *Shell) ReplayFromBlock(c *cli.Context) (err error) { defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() diff --git a/core/cmd/bridge_commands.go b/core/cmd/bridge_commands.go index 398d466c43a..a0208eb738d 100644 --- a/core/cmd/bridge_commands.go +++ b/core/cmd/bridge_commands.go @@ -5,7 +5,6 @@ import ( "strconv" "github.com/urfave/cli" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" ) @@ -97,7 +96,7 @@ func (s *Shell) ShowBridge(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -121,7 +120,7 @@ func (s *Shell) CreateBridge(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -140,7 +139,7 @@ func (s *Shell) RemoveBridge(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() diff --git a/core/cmd/cosmos_transaction_commands.go b/core/cmd/cosmos_transaction_commands.go index 0e9febeb70c..1dfc60226a6 100644 --- a/core/cmd/cosmos_transaction_commands.go +++ b/core/cmd/cosmos_transaction_commands.go @@ -8,7 +8,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/urfave/cli" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/store/models/cosmos" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -121,7 +120,7 @@ func (s *Shell) CosmosSendNativeToken(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() diff --git a/core/cmd/csa_keys_commands.go b/core/cmd/csa_keys_commands.go index 1c0fe54ab09..ff8a50babb5 100644 --- a/core/cmd/csa_keys_commands.go +++ b/core/cmd/csa_keys_commands.go @@ -2,15 +2,15 @@ package cmd import ( "bytes" + "errors" "fmt" "io" "net/http" "net/url" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" cutils "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -114,7 +114,7 @@ func (s *Shell) ListCSAKeys(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -129,7 +129,7 @@ func (s *Shell) CreateCSAKey(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -139,16 +139,16 @@ func (s *Shell) CreateCSAKey(_ *cli.Context) (err error) { // ImportCSAKey imports and stores a CSA key. Path to key must be passed. func (s *Shell) ImportCSAKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -171,7 +171,7 @@ func (s *Shell) ImportCSAKey(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -181,22 +181,22 @@ func (s *Shell) ImportCSAKey(c *cli.Context) (err error) { // ExportCSAKey exports a CSA key. Key ID must be passed. func (s *Shell) ExportCSAKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -210,11 +210,11 @@ func (s *Shell) ExportCSAKey(c *cli.Context) (err error) { exportUrl.RawQuery = query.Encode() resp, err := s.HTTP.Post(s.ctx(), exportUrl.String(), nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -224,12 +224,12 @@ func (s *Shell) ExportCSAKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("🔑 Exported P2P key %s to %s\n", ID, filepath)) diff --git a/core/cmd/eth_keys_commands.go b/core/cmd/eth_keys_commands.go index 5adac3b382b..d4c3632e01c 100644 --- a/core/cmd/eth_keys_commands.go +++ b/core/cmd/eth_keys_commands.go @@ -3,6 +3,7 @@ package cmd import ( "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -10,9 +11,8 @@ import ( "os" "strings" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" cutils "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/store/models" @@ -183,7 +183,7 @@ func (s *Shell) ListETHKeys(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -212,7 +212,7 @@ func (s *Shell) CreateETHKey(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -223,7 +223,7 @@ func (s *Shell) CreateETHKey(c *cli.Context) (err error) { // address of key must be passed func (s *Shell) DeleteETHKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the address of the key to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the address of the key to be deleted")) } address := c.Args().Get(0) @@ -237,21 +237,21 @@ func (s *Shell) DeleteETHKey(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Failed to read request response")) + return s.errorOut(pkgerrors.Wrap(err, "Failed to read request response")) } var result *models.JSONAPIErrors err = json.Unmarshal(body, &result) if err != nil { - return s.errorOut(errors.Wrapf(err, "Unable to unmarshal json from body '%s'", string(body))) + return s.errorOut(pkgerrors.Wrapf(err, "Unable to unmarshal json from body '%s'", string(body))) } - return s.errorOut(errors.Errorf("Delete ETH key failed: %s", result.Error())) + return s.errorOut(pkgerrors.Errorf("Delete ETH key failed: %s", result.Error())) } return s.renderAPIResponse(resp, &EthKeyPresenter{}, fmt.Sprintf("🔑 Deleted ETH key: %s\n", address)) } @@ -260,16 +260,16 @@ func (s *Shell) DeleteETHKey(c *cli.Context) (err error) { // file path must be passed func (s *Shell) ImportETHKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -296,7 +296,7 @@ func (s *Shell) ImportETHKey(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -307,21 +307,21 @@ func (s *Shell) ImportETHKey(c *cli.Context) (err error) { // address must be passed func (s *Shell) ExportETHKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the address of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the address of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(newPassword) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } address := c.Args().Get(0) @@ -334,11 +334,11 @@ func (s *Shell) ExportETHKey(c *cli.Context) (err error) { exportUrl.RawQuery = query.Encode() resp, err := s.HTTP.Post(s.ctx(), exportUrl.String(), nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -348,12 +348,12 @@ func (s *Shell) ExportETHKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString("🔑 Exported ETH key " + address + " to " + filepath + "\n") @@ -377,7 +377,7 @@ func (s *Shell) UpdateChainEVMKey(c *cli.Context) (err error) { query.Set("abandon", abandon) if c.IsSet("enable") && c.IsSet("disable") { - return s.errorOut(errors.New("cannot set both --enable and --disable simultaneously")) + return s.errorOut(pkgerrors.New("cannot set both --enable and --disable simultaneously")) } else if c.Bool("enable") { query.Set("enabled", "true") } else if c.Bool("disable") { @@ -387,11 +387,11 @@ func (s *Shell) UpdateChainEVMKey(c *cli.Context) (err error) { chainURL.RawQuery = query.Encode() resp, err := s.HTTP.Post(s.ctx(), chainURL.String(), nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() diff --git a/core/cmd/evm_transaction_commands.go b/core/cmd/evm_transaction_commands.go index e1611021439..efd36c32a92 100644 --- a/core/cmd/evm_transaction_commands.go +++ b/core/cmd/evm_transaction_commands.go @@ -8,7 +8,6 @@ import ( "math/big" "github.com/urfave/cli" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" @@ -123,7 +122,7 @@ func (s *Shell) ShowTransaction(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -204,7 +203,7 @@ func (s *Shell) SendEther(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() diff --git a/core/cmd/forwarders_commands.go b/core/cmd/forwarders_commands.go index 2445be5bfec..ed63f3ba143 100644 --- a/core/cmd/forwarders_commands.go +++ b/core/cmd/forwarders_commands.go @@ -3,6 +3,7 @@ package cmd import ( "bytes" "encoding/json" + "errors" "fmt" "io" "math/big" @@ -10,9 +11,8 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" ubig "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big" "github.com/smartcontractkit/chainlink/v2/core/web" @@ -100,7 +100,7 @@ func (s *Shell) ListForwarders(c *cli.Context) (err error) { // DeleteForwarder deletes forwarder address from node db by id. func (s *Shell) DeleteForwarder(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("must pass the forwarder id to be archived")) + return s.errorOut(pkgerrors.New("must pass the forwarder id to be archived")) } resp, err := s.HTTP.Delete(s.ctx(), "/v2/nodes/evm/forwarders/"+c.Args().First()) if err != nil { @@ -122,7 +122,7 @@ func (s *Shell) TrackForwarder(c *cli.Context) (err error) { addressBytes, err := hexutil.Decode(addressHex) if err != nil { - return s.errorOut(errors.Wrap(err, "could not decode address")) + return s.errorOut(pkgerrors.Wrap(err, "could not decode address")) } address := gethCommon.BytesToAddress(addressBytes) @@ -131,7 +131,7 @@ func (s *Shell) TrackForwarder(c *cli.Context) (err error) { var ok bool chainID, ok = big.NewInt(0).SetString(chainIDStr, 10) if !ok { - return s.errorOut(errors.Wrap(err, "invalid evm-chain-id")) + return s.errorOut(pkgerrors.Wrap(err, "invalid evm-chain-id")) } } @@ -149,14 +149,14 @@ func (s *Shell) TrackForwarder(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() if resp.StatusCode >= 400 { body, rerr := io.ReadAll(resp.Body) if err != nil { - err = multierr.Append(err, rerr) + err = errors.Join(err, rerr) return s.errorOut(err) } fmt.Printf("Response: '%v', Status: %d\n", string(body), resp.StatusCode) diff --git a/core/cmd/jobs_commands.go b/core/cmd/jobs_commands.go index 1f9ca33c78e..4e98b3b03fa 100644 --- a/core/cmd/jobs_commands.go +++ b/core/cmd/jobs_commands.go @@ -3,14 +3,14 @@ package cmd import ( "bytes" "encoding/json" + "errors" "fmt" "io" "strings" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/services/pipeline" "github.com/smartcontractkit/chainlink/v2/core/web" @@ -209,7 +209,7 @@ func (s *Shell) ListJobs(c *cli.Context) (err error) { // ShowJob displays the details of a job func (s *Shell) ShowJob(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("must provide the id of the job")) + return s.errorOut(pkgerrors.New("must provide the id of the job")) } id := c.Args().First() resp, err := s.HTTP.Get(s.ctx(), "/v2/jobs/"+id) @@ -218,7 +218,7 @@ func (s *Shell) ShowJob(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -229,7 +229,7 @@ func (s *Shell) ShowJob(c *cli.Context) (err error) { // Valid input is a TOML string or a path to TOML file func (s *Shell) CreateJob(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("must pass in TOML or filepath")) + return s.errorOut(pkgerrors.New("must pass in TOML or filepath")) } tomlString, err := getTOMLString(c.Args().First()) @@ -250,14 +250,14 @@ func (s *Shell) CreateJob(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() if resp.StatusCode >= 400 { body, rerr := io.ReadAll(resp.Body) if err != nil { - err = multierr.Append(err, rerr) + err = errors.Join(err, rerr) return s.errorOut(err) } fmt.Printf("Response: '%v', Status: %d\n", string(body), resp.StatusCode) @@ -271,7 +271,7 @@ func (s *Shell) CreateJob(c *cli.Context) (err error) { // DeleteJob deletes a job func (s *Shell) DeleteJob(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("must pass the job id to be archived")) + return s.errorOut(pkgerrors.New("must pass the job id to be archived")) } resp, err := s.HTTP.Delete(s.ctx(), "/v2/jobs/"+c.Args().First()) if err != nil { @@ -289,7 +289,7 @@ func (s *Shell) DeleteJob(c *cli.Context) error { // TriggerPipelineRun triggers a job run based on a job ID func (s *Shell) TriggerPipelineRun(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the job id to trigger a run")) + return s.errorOut(pkgerrors.New("Must pass the job id to trigger a run")) } resp, err := s.HTTP.Post(s.ctx(), "/v2/jobs/"+c.Args().First()+"/runs", nil) if err != nil { @@ -297,7 +297,7 @@ func (s *Shell) TriggerPipelineRun(c *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() diff --git a/core/cmd/keys_commands.go b/core/cmd/keys_commands.go index 7408d168887..fe4419a11b5 100644 --- a/core/cmd/keys_commands.go +++ b/core/cmd/keys_commands.go @@ -2,15 +2,15 @@ package cmd import ( "bytes" + "errors" "fmt" "io" "net/http" "os" "strings" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -111,7 +111,7 @@ func (cli *keysClient[K, P, P2]) ListKeys(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -127,7 +127,7 @@ func (cli *keysClient[K, P, P2]) CreateKey(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -139,7 +139,7 @@ func (cli *keysClient[K, P, P2]) CreateKey(_ *cli.Context) (err error) { // key ID must be passed func (cli *keysClient[K, P, P2]) DeleteKey(c *cli.Context) (err error) { if !c.Args().Present() { - return cli.errorOut(errors.New("Must pass the key ID to be deleted")) + return cli.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) } id := c.Args().Get(0) @@ -158,7 +158,7 @@ func (cli *keysClient[K, P, P2]) DeleteKey(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -170,16 +170,16 @@ func (cli *keysClient[K, P, P2]) DeleteKey(c *cli.Context) (err error) { // path to key must be passed func (cli *keysClient[K, P, P2]) ImportKey(c *cli.Context) (err error) { if !c.Args().Present() { - return cli.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return cli.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return cli.errorOut(errors.New("Must specify --old-password/-p flag")) + return cli.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return cli.errorOut(errors.Wrap(err, "Could not read password file")) + return cli.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -195,7 +195,7 @@ func (cli *keysClient[K, P, P2]) ImportKey(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -207,21 +207,21 @@ func (cli *keysClient[K, P, P2]) ImportKey(c *cli.Context) (err error) { // key ID must be passed func (cli *keysClient[K, P, P2]) ExportKey(c *cli.Context) (err error) { if !c.Args().Present() { - return cli.errorOut(errors.New("Must pass the ID of the key to export")) + return cli.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return cli.errorOut(errors.New("Must specify --new-password/-p flag")) + return cli.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return cli.errorOut(errors.Wrap(err, "Could not read password file")) + return cli.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return cli.errorOut(errors.New("Must specify --output/-o flag")) + return cli.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -229,11 +229,11 @@ func (cli *keysClient[K, P, P2]) ExportKey(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := cli.HTTP.Post(cli.ctx(), cli.path+"/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return cli.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return cli.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -243,12 +243,12 @@ func (cli *keysClient[K, P, P2]) ExportKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return cli.errorOut(errors.Wrap(err, "Could not read response body")) + return cli.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0600) if err != nil { - return cli.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return cli.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("🔑 Exported %s key %s to %s\n", cli.typ, ID, filepath)) diff --git a/core/cmd/ocr2_keys_commands.go b/core/cmd/ocr2_keys_commands.go index 1d469024878..eb0e4b625e2 100644 --- a/core/cmd/ocr2_keys_commands.go +++ b/core/cmd/ocr2_keys_commands.go @@ -2,14 +2,14 @@ package cmd import ( "bytes" + "errors" "fmt" "io" "net/http" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" cutils "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/chaintype" @@ -133,7 +133,7 @@ func (s *Shell) ListOCR2KeyBundles(_ *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -145,7 +145,7 @@ func (s *Shell) ListOCR2KeyBundles(_ *cli.Context) error { func (s *Shell) CreateOCR2KeyBundle(c *cli.Context) error { if !c.Args().Present() { return s.errorOut( - errors.Errorf(`must pass the type to create, options are: %s`, chaintype.SupportedChainTypes.String()), + pkgerrors.Errorf(`must pass the type to create, options are: %s`, chaintype.SupportedChainTypes.String()), ) } chainType := c.Args().Get(0) @@ -155,7 +155,7 @@ func (s *Shell) CreateOCR2KeyBundle(c *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -166,7 +166,7 @@ func (s *Shell) CreateOCR2KeyBundle(c *cli.Context) error { // DeleteOCR2KeyBundle deletes an OCR2 key bundle func (s *Shell) DeleteOCR2KeyBundle(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the key ID to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) } id, err := models.Sha256HashFromHex(c.Args().Get(0)) if err != nil { @@ -188,7 +188,7 @@ func (s *Shell) DeleteOCR2KeyBundle(c *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -199,16 +199,16 @@ func (s *Shell) DeleteOCR2KeyBundle(c *cli.Context) error { // ImportOCR2Key imports OCR2 key bundle func (s *Shell) ImportOCR2Key(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -224,7 +224,7 @@ func (s *Shell) ImportOCR2Key(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -235,21 +235,21 @@ func (s *Shell) ImportOCR2Key(c *cli.Context) (err error) { // ExportOCR2Key exports an OCR2 key bundle by ID func (s *Shell) ExportOCR2Key(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -257,11 +257,11 @@ func (s *Shell) ExportOCR2Key(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/ocr2/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -271,12 +271,12 @@ func (s *Shell) ExportOCR2Key(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("Exported OCR key bundle %s to %s", ID, filepath)) diff --git a/core/cmd/ocr_keys_commands.go b/core/cmd/ocr_keys_commands.go index 399333bba93..0c47b62d6ce 100644 --- a/core/cmd/ocr_keys_commands.go +++ b/core/cmd/ocr_keys_commands.go @@ -2,14 +2,14 @@ package cmd import ( "bytes" + "errors" "fmt" "io" "net/http" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" cutils "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/store/models" @@ -114,7 +114,7 @@ func (s *Shell) ListOCRKeyBundles(_ *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -147,7 +147,7 @@ func (s *Shell) CreateOCRKeyBundle(_ *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -158,7 +158,7 @@ func (s *Shell) CreateOCRKeyBundle(_ *cli.Context) error { // DeleteOCR2KeyBundle deletes an OCR key bundle func (s *Shell) DeleteOCRKeyBundle(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the key ID to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) } id, err := models.Sha256HashFromHex(c.Args().Get(0)) if err != nil { @@ -180,7 +180,7 @@ func (s *Shell) DeleteOCRKeyBundle(c *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -191,16 +191,16 @@ func (s *Shell) DeleteOCRKeyBundle(c *cli.Context) error { // ImportOCR2Key imports OCR key bundle func (s *Shell) ImportOCRKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -216,7 +216,7 @@ func (s *Shell) ImportOCRKey(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -227,21 +227,21 @@ func (s *Shell) ImportOCRKey(c *cli.Context) (err error) { // ExportOCR2Key exports an OCR key bundle by ID func (s *Shell) ExportOCRKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -249,11 +249,11 @@ func (s *Shell) ExportOCRKey(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/ocr/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -263,12 +263,12 @@ func (s *Shell) ExportOCRKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("Exported OCR key bundle %s to %s", ID, filepath)) diff --git a/core/cmd/p2p_keys_commands.go b/core/cmd/p2p_keys_commands.go index da3bf412a04..001202269dc 100644 --- a/core/cmd/p2p_keys_commands.go +++ b/core/cmd/p2p_keys_commands.go @@ -2,14 +2,14 @@ package cmd import ( "bytes" + "errors" "fmt" "io" "net/http" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" cutils "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -131,7 +131,7 @@ func (s *Shell) ListP2PKeys(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -146,7 +146,7 @@ func (s *Shell) CreateP2PKey(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -157,7 +157,7 @@ func (s *Shell) CreateP2PKey(_ *cli.Context) (err error) { // key ID must be passed func (s *Shell) DeleteP2PKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the key ID to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) } id := c.Args().Get(0) @@ -176,7 +176,7 @@ func (s *Shell) DeleteP2PKey(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -187,16 +187,16 @@ func (s *Shell) DeleteP2PKey(c *cli.Context) (err error) { // path to key must be passed func (s *Shell) ImportP2PKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -212,7 +212,7 @@ func (s *Shell) ImportP2PKey(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -223,21 +223,21 @@ func (s *Shell) ImportP2PKey(c *cli.Context) (err error) { // key ID must be passed func (s *Shell) ExportP2PKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -245,11 +245,11 @@ func (s *Shell) ExportP2PKey(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/p2p/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -259,12 +259,12 @@ func (s *Shell) ExportP2PKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("🔑 Exported P2P key %s to %s\n", ID, filepath)) diff --git a/core/cmd/shell.go b/core/cmd/shell.go index 05081cdc314..7caa038548a 100644 --- a/core/cmd/shell.go +++ b/core/cmd/shell.go @@ -27,7 +27,6 @@ import ( "github.com/gin-gonic/gin" pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" "go.uber.org/zap/zapcore" "golang.org/x/sync/errgroup" @@ -714,7 +713,7 @@ func (d DiskCookieStore) Retrieve() (*http.Cookie, error) { if os.IsNotExist(err) { return nil, nil } - return nil, multierr.Append(errors.New("unable to retrieve credentials, you must first login through the CLI"), err) + return nil, errors.Join(errors.New("unable to retrieve credentials, you must first login through the CLI"), err) } header := http.Header{} header.Add("Cookie", string(b)) diff --git a/core/cmd/shell_local.go b/core/cmd/shell_local.go index b970b516413..625afb52b99 100644 --- a/core/cmd/shell_local.go +++ b/core/cmd/shell_local.go @@ -4,6 +4,7 @@ import ( "context" crand "crypto/rand" "database/sql" + "errors" "fmt" "log" "math/big" @@ -25,9 +26,8 @@ import ( "github.com/lib/pq" "github.com/kylelemons/godebug/diff" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" "golang.org/x/sync/errgroup" "gopkg.in/guregu/null.v4" @@ -54,7 +54,7 @@ import ( "github.com/smartcontractkit/chainlink/v2/internal/testdb" ) -var ErrProfileTooLong = errors.New("requested profile duration too large") +var ErrProfileTooLong = pkgerrors.New("requested profile duration too large") func initLocalSubCmds(s *Shell, safe bool) []cli.Command { return []cli.Command{ @@ -274,14 +274,14 @@ func (s *Shell) runNode(c *cli.Context) error { if passwordFile := c.String("password"); passwordFile != "" { p, err := utils.PasswordFromFile(passwordFile) if err != nil { - return errors.Wrap(err, "error reading password from file") + return pkgerrors.Wrap(err, "error reading password from file") } pwd = &p } if vrfPasswordFile := c.String("vrfpassword"); len(vrfPasswordFile) != 0 { p, err := utils.PasswordFromFile(vrfPasswordFile) if err != nil { - return errors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) + return pkgerrors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) } vrfpwd = &p } @@ -291,7 +291,7 @@ func (s *Shell) runNode(c *cli.Context) error { s.Config.LogConfiguration(lggr.Debugf, lggr.Warnf) if err := s.Config.Validate(); err != nil { - return errors.Wrap(err, "config validation failed") + return pkgerrors.Wrap(err, "config validation failed") } lggr.Infow(fmt.Sprintf("Starting Chainlink Node %s at commit %s", static.Version, static.Sha), "Version", static.Version, "SHA", static.Sha) @@ -348,7 +348,7 @@ func (s *Shell) runNode(c *cli.Context) error { // Try opening DB connection and acquiring DB locks at once if err := ldb.Open(rootCtx); err != nil { // If not successful, we know neither locks nor connection remains opened - return s.errorOut(errors.Wrap(err, "opening db")) + return s.errorOut(pkgerrors.Wrap(err, "opening db")) } defer lggr.ErrorIfFn(ldb.Close, "Error closing db") @@ -357,7 +357,7 @@ func (s *Shell) runNode(c *cli.Context) error { app, err := s.AppFactory.NewApplication(rootCtx, s.Config, s.Logger, ldb.DB()) if err != nil { - return s.errorOut(errors.Wrap(err, "fatal error instantiating application")) + return s.errorOut(pkgerrors.Wrap(err, "fatal error instantiating application")) } // Local shell initialization always uses local auth users table for admin auth @@ -365,7 +365,7 @@ func (s *Shell) runNode(c *cli.Context) error { keyStore := app.GetKeyStore() err = s.KeyStoreAuthenticator.authenticate(keyStore, s.Config.Password()) if err != nil { - return errors.Wrap(err, "error authenticating keystore") + return pkgerrors.Wrap(err, "error authenticating keystore") } legacyEVMChains := app.GetRelayers().LegacyEVMChains() @@ -380,7 +380,7 @@ func (s *Shell) runNode(c *cli.Context) error { lggr.Debugf("AutoCreateKey=true, will ensure EVM key for chain %s", ch.ID()) err2 := app.GetKeyStore().Eth().EnsureKeys(ch.ID()) if err2 != nil { - return errors.Wrap(err2, "failed to ensure keystore keys") + return pkgerrors.Wrap(err2, "failed to ensure keystore keys") } } else { lggr.Debugf("AutoCreateKey=false, will not ensure EVM key for chain %s", ch.ID()) @@ -391,7 +391,7 @@ func (s *Shell) runNode(c *cli.Context) error { if s.Config.OCR().Enabled() { err2 := app.GetKeyStore().OCR().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure ocr key") + return pkgerrors.Wrap(err2, "failed to ensure ocr key") } } if s.Config.OCR2().Enabled() { @@ -410,37 +410,37 @@ func (s *Shell) runNode(c *cli.Context) error { } err2 := app.GetKeyStore().OCR2().EnsureKeys(enabledChains...) if err2 != nil { - return errors.Wrap(err2, "failed to ensure ocr key") + return pkgerrors.Wrap(err2, "failed to ensure ocr key") } } if s.Config.P2P().Enabled() { err2 := app.GetKeyStore().P2P().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure p2p key") + return pkgerrors.Wrap(err2, "failed to ensure p2p key") } } if s.Config.CosmosEnabled() { err2 := app.GetKeyStore().Cosmos().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure cosmos key") + return pkgerrors.Wrap(err2, "failed to ensure cosmos key") } } if s.Config.SolanaEnabled() { err2 := app.GetKeyStore().Solana().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure solana key") + return pkgerrors.Wrap(err2, "failed to ensure solana key") } } if s.Config.StarkNetEnabled() { err2 := app.GetKeyStore().StarkNet().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure starknet key") + return pkgerrors.Wrap(err2, "failed to ensure starknet key") } } err2 := app.GetKeyStore().CSA().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure CSA key") + return pkgerrors.Wrap(err2, "failed to ensure CSA key") } if e := checkFilePermissions(lggr, s.Config.RootDir()); e != nil { @@ -449,14 +449,14 @@ func (s *Shell) runNode(c *cli.Context) error { var user sessions.User if user, err = NewFileAPIInitializer(c.String("api")).Initialize(authProviderORM, lggr); err != nil { - if !errors.Is(err, ErrNoCredentialFile) { - return errors.Wrap(err, "error creating api initializer") + if !pkgerrors.Is(err, ErrNoCredentialFile) { + return pkgerrors.Wrap(err, "error creating api initializer") } if user, err = s.FallbackAPIInitializer.Initialize(authProviderORM, lggr); err != nil { - if errors.Is(err, ErrorNoAPICredentialsAvailable) { - return errors.WithStack(err) + if pkgerrors.Is(err, ErrorNoAPICredentialsAvailable) { + return pkgerrors.WithStack(err) } - return errors.Wrap(err, "error creating fallback initializer") + return pkgerrors.Wrap(err, "error creating fallback initializer") } } @@ -466,7 +466,7 @@ func (s *Shell) runNode(c *cli.Context) error { // We do not try stopping any sub-services that might be started, // because the app will exit immediately upon return. // But LockedDB will be released by defer in above. - return errors.Wrap(err, "error starting app") + return pkgerrors.Wrap(err, "error starting app") } grp, grpCtx := errgroup.WithContext(rootCtx) @@ -474,7 +474,7 @@ func (s *Shell) runNode(c *cli.Context) error { grp.Go(func() error { <-grpCtx.Done() if errInternal := app.Stop(); errInternal != nil { - return errors.Wrap(errInternal, "error stopping app") + return pkgerrors.Wrap(errInternal, "error stopping app") } return nil }) @@ -483,7 +483,7 @@ func (s *Shell) runNode(c *cli.Context) error { grp.Go(func() error { errInternal := s.Runner.Run(grpCtx, app) - if errors.Is(errInternal, http.ErrServerClosed) { + if pkgerrors.Is(errInternal, http.ErrServerClosed) { errInternal = nil } // In tests we have custom runners that stop the app gracefully, @@ -566,7 +566,7 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { addressBytes, err := hexutil.Decode(addressHex) if err != nil { - return s.errorOut(errors.Wrap(err, "could not decode address")) + return s.errorOut(pkgerrors.Wrap(err, "could not decode address")) } address := gethCommon.BytesToAddress(addressBytes) @@ -575,20 +575,20 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { var ok bool chainID, ok = big.NewInt(0).SetString(chainIDStr, 10) if !ok { - return s.errorOut(errors.New("invalid evmChainID")) + return s.errorOut(pkgerrors.New("invalid evmChainID")) } } lggr := logger.Sugared(s.Logger.Named("RebroadcastTransactions")) db, err := pg.OpenUnlockedDB(s.Config.AppID(), s.Config.Database()) if err != nil { - return s.errorOut(errors.Wrap(err, "opening DB")) + return s.errorOut(pkgerrors.Wrap(err, "opening DB")) } defer lggr.ErrorIfFn(db.Close, "Error closing db") app, err := s.AppFactory.NewApplication(ctx, s.Config, lggr, db) if err != nil { - return s.errorOut(errors.Wrap(err, "fatal error instantiating application")) + return s.errorOut(pkgerrors.Wrap(err, "fatal error instantiating application")) } // TODO: BCF-2511 once the dust settles on BCF-2440/1 evaluate how the @@ -622,7 +622,7 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { err = keyStore.Unlock(s.Config.Password().Keystore()) if err != nil { - return s.errorOut(errors.Wrap(err, "error authenticating keystore")) + return s.errorOut(pkgerrors.Wrap(err, "error authenticating keystore")) } if err = keyStore.Eth().CheckEnabled(address, chain.ID()); err != nil { @@ -685,7 +685,7 @@ func (ps HealthCheckPresenters) RenderTable(rt RendererTable) error { return nil } -var errDBURLMissing = errors.New("You must set CL_DATABASE_URL env variable or provide a secrets TOML with Database.URL set. HINT: If you are running this to set up your local test database, try CL_DATABASE_URL=postgresql://postgres@localhost:5432/chainlink_test?sslmode=disable") +var errDBURLMissing = pkgerrors.New("You must set CL_DATABASE_URL env variable or provide a secrets TOML with Database.URL set. HINT: If you are running this to set up your local test database, try CL_DATABASE_URL=postgresql://postgres@localhost:5432/chainlink_test?sslmode=disable") // ConfigValidate validate the client configuration and pretty-prints results func (s *Shell) ConfigFileValidate(_ *cli.Context) error { @@ -817,7 +817,7 @@ func dropDanglingTestDBs(lggr logger.Logger, db *sqlx.DB) (err error) { wg.Wait() close(errCh) for gerr := range errCh { - err = multierr.Append(err, gerr) + err = errors.Join(err, gerr) } return } @@ -911,7 +911,7 @@ func (s *Shell) RollbackDatabase(c *cli.Context) error { arg := c.Args().First() numVersion, err := strconv.ParseInt(arg, 10, 64) if err != nil { - return s.errorOut(errors.Errorf("Unable to parse %v as integer", arg)) + return s.errorOut(pkgerrors.Errorf("Unable to parse %v as integer", arg)) } version = null.IntFrom(numVersion) } @@ -962,7 +962,7 @@ func (s *Shell) StatusDatabase(_ *cli.Context) error { // CreateMigration displays the database migration status func (s *Shell) CreateMigration(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("You must specify a migration name")) + return s.errorOut(pkgerrors.New("You must specify a migration name")) } db, err := newConnection(s.Config.Database()) if err != nil { @@ -995,7 +995,7 @@ func (s *Shell) CleanupChainTables(c *cli.Context) error { db, err := newConnection(cfg) if err != nil { - return s.errorOut(errors.Wrap(err, "error connecting to the database")) + return s.errorOut(pkgerrors.Wrap(err, "error connecting to the database")) } defer db.Close() @@ -1032,7 +1032,7 @@ func (s *Shell) CleanupChainTables(c *cli.Context) error { } } } else { - return s.errorOut(errors.New("unknown chain type")) + return s.errorOut(pkgerrors.New("unknown chain type")) } return nil } @@ -1065,7 +1065,7 @@ func dropAndCreateDB(parsed url.URL) (err error) { } defer func() { if cerr := db.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -1130,7 +1130,7 @@ func dumpSchema(dbURL url.URL) (string, error) { schema, err := cmd.Output() if err != nil { var ee *exec.ExitError - if errors.As(err, &ee) { + if pkgerrors.As(err, &ee) { return "", fmt.Errorf("failed to dump schema: %v\n%s", err, string(ee.Stderr)) } return "", fmt.Errorf("failed to dump schema: %v", err) @@ -1146,7 +1146,7 @@ func checkSchema(dbURL url.URL, prevSchema string) error { df := diff.Diff(prevSchema, newSchema) if len(df) > 0 { fmt.Println(df) - return errors.New("schema pre- and post- rollback does not match (ctrl+f for '+' or '-' to find the changed lines)") + return pkgerrors.New("schema pre- and post- rollback does not match (ctrl+f for '+' or '-' to find the changed lines)") } return nil } @@ -1158,13 +1158,13 @@ func insertFixtures(dbURL url.URL, pathToFixtures string) (err error) { } defer func() { if cerr := db.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() _, filename, _, ok := runtime.Caller(1) if !ok { - return errors.New("could not get runtime.Caller(1)") + return pkgerrors.New("could not get runtime.Caller(1)") } filepath := path.Join(path.Dir(filename), pathToFixtures) fixturesSQL, err := os.ReadFile(filepath) diff --git a/core/cmd/shell_remote.go b/core/cmd/shell_remote.go index aab4a94da6f..37a28ea53a5 100644 --- a/core/cmd/shell_remote.go +++ b/core/cmd/shell_remote.go @@ -3,6 +3,7 @@ package cmd import ( "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -15,10 +16,9 @@ import ( "github.com/manyminds/api2go/jsonapi" "github.com/mitchellh/go-homedir" "github.com/pelletier/go-toml" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/tidwall/gjson" "github.com/urfave/cli" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/logger" @@ -80,15 +80,15 @@ func initRemoteConfigSubCmds(s *Shell) []cli.Command { } var ( - errUnauthorized = errors.New(http.StatusText(http.StatusUnauthorized)) - errForbidden = errors.New(http.StatusText(http.StatusForbidden)) - errBadRequest = errors.New(http.StatusText(http.StatusBadRequest)) + errUnauthorized = pkgerrors.New(http.StatusText(http.StatusUnauthorized)) + errForbidden = pkgerrors.New(http.StatusText(http.StatusForbidden)) + errBadRequest = pkgerrors.New(http.StatusText(http.StatusBadRequest)) ) // CreateExternalInitiator adds an external initiator func (s *Shell) CreateExternalInitiator(c *cli.Context) (err error) { if c.NArg() != 1 && c.NArg() != 2 { - return s.errorOut(errors.New("create expects 1 - 2 arguments: a name and a url (optional)")) + return s.errorOut(pkgerrors.New("create expects 1 - 2 arguments: a name and a url (optional)")) } var request bridges.ExternalInitiatorRequest @@ -116,7 +116,7 @@ func (s *Shell) CreateExternalInitiator(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -128,7 +128,7 @@ func (s *Shell) CreateExternalInitiator(c *cli.Context) (err error) { // DeleteExternalInitiator removes an external initiator func (s *Shell) DeleteExternalInitiator(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the name of the external initiator to delete")) + return s.errorOut(pkgerrors.New("Must pass the name of the external initiator to delete")) } resp, err := s.HTTP.Delete(s.ctx(), "/v2/external_initiators/"+c.Args().First()) @@ -137,7 +137,7 @@ func (s *Shell) DeleteExternalInitiator(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() _, err = s.parseResponse(resp) @@ -161,7 +161,7 @@ func (s *Shell) getPage(requestURI string, page int, model interface{}) (err err } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -200,7 +200,7 @@ func (s *Shell) Logout(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() err = s.CookieAuthenticator.Logout() @@ -230,7 +230,7 @@ func (s *Shell) ChangePassword(_ *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -270,12 +270,12 @@ func getTOMLString(s string) (string, error) { func (s *Shell) parseResponse(resp *http.Response) ([]byte, error) { b, err := parseResponse(resp) - if errors.Is(err, errUnauthorized) { - return nil, s.errorOut(multierr.Append(err, fmt.Errorf("your credentials may be missing, invalid or you may need to login first using the CLI via 'chainlink admin login'"))) + if pkgerrors.Is(err, errUnauthorized) { + return nil, s.errorOut(errors.Join(err, fmt.Errorf("your credentials may be missing, invalid or you may need to login first using the CLI via 'chainlink admin login'"))) } - if errors.Is(err, errForbidden) { - return nil, s.errorOut(multierr.Append(err, fmt.Errorf("this action requires %s privileges. The current user %s has '%s' role and cannot perform this action, login with a user that has '%s' role via 'chainlink admin login'", resp.Header.Get("forbidden-required-role"), resp.Header.Get("forbidden-provided-email"), resp.Header.Get("forbidden-provided-role"), resp.Header.Get("forbidden-required-role")))) + if pkgerrors.Is(err, errForbidden) { + return nil, s.errorOut(errors.Join(err, fmt.Errorf("this action requires %s privileges. The current user %s has '%s' role and cannot perform this action, login with a user that has '%s' role via 'chainlink admin login'", resp.Header.Get("forbidden-required-role"), resp.Header.Get("forbidden-provided-email"), resp.Header.Get("forbidden-provided-role"), resp.Header.Get("forbidden-required-role")))) } if err != nil { return nil, s.errorOut(err) @@ -319,7 +319,7 @@ func (s *Shell) configV2Str(userOnly bool) (string, error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() respPayload, err := io.ReadAll(resp.Body) @@ -327,7 +327,7 @@ func (s *Shell) configV2Str(userOnly bool) (string, error) { return "", s.errorOut(err) } if resp.StatusCode != 200 { - return "", s.errorOut(errors.Errorf("got HTTP status %d: %s", resp.StatusCode, respPayload)) + return "", s.errorOut(pkgerrors.Errorf("got HTTP status %d: %s", resp.StatusCode, respPayload)) } var configV2Resource web.ConfigV2Resource err = web.ParseJSONAPIResponse(respPayload, &configV2Resource) @@ -357,7 +357,7 @@ func (s *Shell) SetLogLevel(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -370,7 +370,7 @@ func (s *Shell) SetLogLevel(c *cli.Context) (err error) { func (s *Shell) SetLogSQL(c *cli.Context) (err error) { // Enforces selection of --enable or --disable if !c.Bool("enable") && !c.Bool("disable") { - return s.errorOut(errors.New("Must set logSql --enabled || --disable")) + return s.errorOut(pkgerrors.New("Must set logSql --enabled || --disable")) } // Sets logSql to true || false based on the --enabled flag @@ -389,7 +389,7 @@ func (s *Shell) SetLogSQL(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -428,7 +428,7 @@ func fromFile(arg string) (*bytes.Buffer, error) { func (s *Shell) deserializeAPIResponse(resp *http.Response, dst interface{}, links *jsonapi.Links) error { b, err := s.parseResponse(resp) if err != nil { - return errors.Wrap(err, "parseResponse error") + return pkgerrors.Wrap(err, "parseResponse error") } if err = web.ParsePaginatedResponse(b, dst, links); err != nil { return s.errorOut(err) @@ -442,15 +442,15 @@ func parseErrorResponseBody(responseBody []byte) (string, error) { return "Empty error message", nil } - var errors models.JSONAPIErrors - err := json.Unmarshal(responseBody, &errors) - if err != nil || len(errors.Errors) == 0 { + var errs models.JSONAPIErrors + err := json.Unmarshal(responseBody, &errs) + if err != nil || len(errs.Errors) == 0 { return "", err } var errorDetails strings.Builder - errorDetails.WriteString(errors.Errors[0].Detail) - for _, errorDetail := range errors.Errors[1:] { + errorDetails.WriteString(errs.Errors[0].Detail) + for _, errorDetail := range errs.Errors[1:] { fmt.Fprintf(&errorDetails, "\n%s", errorDetail.Detail) } return errorDetails.String(), nil @@ -459,7 +459,7 @@ func parseErrorResponseBody(responseBody []byte) (string, error) { func parseResponse(resp *http.Response) ([]byte, error) { b, err := io.ReadAll(resp.Body) if err != nil { - return b, multierr.Append(errors.New(resp.Status), err) + return b, errors.Join(pkgerrors.New(resp.Status), err) } if resp.StatusCode == http.StatusUnauthorized { return b, errUnauthorized @@ -470,7 +470,7 @@ func parseResponse(resp *http.Response) ([]byte, error) { if err2 != nil { return b, err2 } - return b, errors.New(errorMessage) + return b, pkgerrors.New(errorMessage) } return b, err } diff --git a/core/cmd/solana_transaction_commands.go b/core/cmd/solana_transaction_commands.go index 7eaac7930a2..688cfa977c1 100644 --- a/core/cmd/solana_transaction_commands.go +++ b/core/cmd/solana_transaction_commands.go @@ -10,7 +10,6 @@ import ( solanaGo "github.com/gagliardetto/solana-go" pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/store/models/solana" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -112,7 +111,7 @@ func (s *Shell) SolanaSendSol(c *cli.Context) (err error) { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() diff --git a/core/cmd/vrf_keys_commands.go b/core/cmd/vrf_keys_commands.go index 32d32334af5..ab1f17c3b38 100644 --- a/core/cmd/vrf_keys_commands.go +++ b/core/cmd/vrf_keys_commands.go @@ -2,14 +2,14 @@ package cmd import ( "bytes" + "errors" "fmt" "io" "net/http" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/services/signatures/secp256k1" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -124,7 +124,7 @@ func (s *Shell) CreateVRFKey(_ *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -135,16 +135,16 @@ func (s *Shell) CreateVRFKey(_ *cli.Context) error { // ImportVRFKey reads a file into an EncryptedVRFKey in the db func (s *Shell) ImportVRFKey(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -160,7 +160,7 @@ func (s *Shell) ImportVRFKey(c *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -172,21 +172,21 @@ func (s *Shell) ImportVRFKey(c *cli.Context) error { // requested file path. func (s *Shell) ExportVRFKey(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID (compressed public key) of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID (compressed public key) of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } pk, err := getPublicKey(c) @@ -197,11 +197,11 @@ func (s *Shell) ExportVRFKey(c *cli.Context) error { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/vrf/export/"+pk.String()+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -211,12 +211,12 @@ func (s *Shell) ExportVRFKey(c *cli.Context) error { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("Exported VRF key %s to %s\n", pk.String(), filepath)) @@ -232,7 +232,7 @@ func (s *Shell) ExportVRFKey(c *cli.Context) error { // (no such protection for the V1 jobs exists). func (s *Shell) DeleteVRFKey(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the key ID (compressed public key) to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the key ID (compressed public key) to be deleted")) } id, err := getPublicKey(c) if err != nil { @@ -254,7 +254,7 @@ func (s *Shell) DeleteVRFKey(c *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() @@ -269,7 +269,7 @@ func getPublicKey(c *cli.Context) (secp256k1.PublicKey, error) { } publicKey, err := secp256k1.NewPublicKeyFromHex(pkHexString) if err != nil { - return secp256k1.PublicKey{}, errors.Wrap(err, "failed to parse public key") + return secp256k1.PublicKey{}, pkgerrors.Wrap(err, "failed to parse public key") } return publicKey, nil } @@ -282,7 +282,7 @@ func (s *Shell) ListVRFKeys(_ *cli.Context) error { } defer func() { if cerr := resp.Body.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() diff --git a/core/config/docs/docs.go b/core/config/docs/docs.go index df082465036..7c4fd0e3ff5 100644 --- a/core/config/docs/docs.go +++ b/core/config/docs/docs.go @@ -2,12 +2,11 @@ package docs import ( _ "embed" + "errors" "fmt" "log" "strings" - "go.uber.org/multierr" - "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -251,12 +250,12 @@ func parseTOMLDocs(s string) (items []fmt.Stringer, err error) { kv.name = currentTable.name + "." + kv.name } if len(kv.desc) == 0 { - err = multierr.Append(err, fmt.Errorf("%s: missing description", kv.name)) + err = errors.Join(err, fmt.Errorf("%s: missing description", kv.name)) } else if !strings.HasPrefix(kv.desc[0], shortName) { - err = multierr.Append(err, fmt.Errorf("%s: description does not begin with %q", kv.name, shortName)) + err = errors.Join(err, fmt.Errorf("%s: description does not begin with %q", kv.name, shortName)) } if !strings.HasSuffix(line, fieldDefault) && !strings.HasSuffix(line, fieldExample) { - err = multierr.Append(err, fmt.Errorf(`%s: is not one of %v`, kv.name, []string{fieldDefault, fieldExample})) + err = errors.Join(err, fmt.Errorf(`%s: is not one of %v`, kv.name, []string{fieldDefault, fieldExample})) } items = append(items, kv) diff --git a/core/config/toml/types.go b/core/config/toml/types.go index eae5b2f533a..7df9bc2303d 100644 --- a/core/config/toml/types.go +++ b/core/config/toml/types.go @@ -9,7 +9,6 @@ import ( "strings" "github.com/google/uuid" - "go.uber.org/multierr" "go.uber.org/zap/zapcore" ocrcommontypes "github.com/smartcontractkit/libocr/commontypes" @@ -95,7 +94,7 @@ func (c *Core) SetFrom(f *Core) { func (c *Core) ValidateConfig() (err error) { _, verr := parse.HomeDir(*c.RootDir) if err != nil { - err = multierr.Append(err, configutils.ErrInvalid{Name: "RootDir", Value: true, Msg: fmt.Sprintf("Failed to expand RootDir. Please use an explicit path: %s", verr)}) + err = errors.Join(err, configutils.ErrInvalid{Name: "RootDir", Value: true, Msg: fmt.Sprintf("Failed to expand RootDir. Please use an explicit path: %s", verr)}) } return err @@ -152,17 +151,17 @@ func (d *DatabaseSecrets) ValidateConfig() (err error) { func (d *DatabaseSecrets) validateConfig(buildMode string) (err error) { if d.URL == nil || (*url.URL)(d.URL).String() == "" { - err = multierr.Append(err, configutils.ErrEmpty{Name: "URL", Msg: "must be provided and non-empty"}) + err = errors.Join(err, configutils.ErrEmpty{Name: "URL", Msg: "must be provided and non-empty"}) } else if *d.AllowSimplePasswords && buildMode == build.Prod { - err = multierr.Append(err, configutils.ErrInvalid{Name: "AllowSimplePasswords", Value: true, Msg: "insecure configs are not allowed on secure builds"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "AllowSimplePasswords", Value: true, Msg: "insecure configs are not allowed on secure builds"}) } else if !*d.AllowSimplePasswords { if verr := validateDBURL((url.URL)(*d.URL)); verr != nil { - err = multierr.Append(err, configutils.ErrInvalid{Name: "URL", Value: "*****", Msg: dbURLPasswordComplexity(verr)}) + err = errors.Join(err, configutils.ErrInvalid{Name: "URL", Value: "*****", Msg: dbURLPasswordComplexity(verr)}) } } if d.BackupURL != nil && !*d.AllowSimplePasswords { if verr := validateDBURL((url.URL)(*d.BackupURL)); verr != nil { - err = multierr.Append(err, configutils.ErrInvalid{Name: "BackupURL", Value: "*****", Msg: dbURLPasswordComplexity(verr)}) + err = errors.Join(err, configutils.ErrInvalid{Name: "BackupURL", Value: "*****", Msg: dbURLPasswordComplexity(verr)}) } } return err @@ -188,15 +187,15 @@ func (d *DatabaseSecrets) SetFrom(f *DatabaseSecrets) (err error) { func (d *DatabaseSecrets) validateMerge(f *DatabaseSecrets) (err error) { if d.AllowSimplePasswords != nil && f.AllowSimplePasswords != nil { - err = multierr.Append(err, configutils.ErrOverride{Name: "AllowSimplePasswords"}) + err = errors.Join(err, configutils.ErrOverride{Name: "AllowSimplePasswords"}) } if d.BackupURL != nil && f.BackupURL != nil { - err = multierr.Append(err, configutils.ErrOverride{Name: "BackupURL"}) + err = errors.Join(err, configutils.ErrOverride{Name: "BackupURL"}) } if d.URL != nil && f.URL != nil { - err = multierr.Append(err, configutils.ErrOverride{Name: "URL"}) + err = errors.Join(err, configutils.ErrOverride{Name: "URL"}) } return err @@ -225,11 +224,11 @@ func (p *Passwords) SetFrom(f *Passwords) (err error) { func (p *Passwords) validateMerge(f *Passwords) (err error) { if p.Keystore != nil && f.Keystore != nil { - err = multierr.Append(err, configutils.ErrOverride{Name: "Keystore"}) + err = errors.Join(err, configutils.ErrOverride{Name: "Keystore"}) } if p.VRF != nil && f.VRF != nil { - err = multierr.Append(err, configutils.ErrOverride{Name: "VRF"}) + err = errors.Join(err, configutils.ErrOverride{Name: "VRF"}) } return err @@ -237,7 +236,7 @@ func (p *Passwords) validateMerge(f *Passwords) (err error) { func (p *Passwords) ValidateConfig() (err error) { if p.Keystore == nil || *p.Keystore == "" { - err = multierr.Append(err, configutils.ErrEmpty{Name: "Keystore", Msg: "must be provided and non-empty"}) + err = errors.Join(err, configutils.ErrEmpty{Name: "Keystore", Msg: "must be provided and non-empty"}) } return err } @@ -261,7 +260,7 @@ func (p *PyroscopeSecrets) SetFrom(f *PyroscopeSecrets) (err error) { func (p *PyroscopeSecrets) validateMerge(f *PyroscopeSecrets) (err error) { if p.AuthToken != nil && f.AuthToken != nil { - err = multierr.Append(err, configutils.ErrOverride{Name: "AuthToken"}) + err = errors.Join(err, configutils.ErrOverride{Name: "AuthToken"}) } return err @@ -286,7 +285,7 @@ func (p *PrometheusSecrets) SetFrom(f *PrometheusSecrets) (err error) { func (p *PrometheusSecrets) validateMerge(f *PrometheusSecrets) (err error) { if p.AuthToken != nil && f.AuthToken != nil { - err = multierr.Append(err, configutils.ErrOverride{Name: "AuthToken"}) + err = errors.Join(err, configutils.ErrOverride{Name: "AuthToken"}) } return err @@ -386,7 +385,7 @@ func (l *DatabaseLock) Mode() string { func (l *DatabaseLock) ValidateConfig() (err error) { if l.LeaseRefreshInterval.Duration() > l.LeaseDuration.Duration()/2 { - err = multierr.Append(err, configutils.ErrInvalid{Name: "LeaseRefreshInterval", Value: l.LeaseRefreshInterval.String(), + err = errors.Join(err, configutils.ErrInvalid{Name: "LeaseRefreshInterval", Value: l.LeaseRefreshInterval.String(), Msg: fmt.Sprintf("must be less than or equal to half of LeaseDuration (%s)", l.LeaseDuration.String())}) } return @@ -667,28 +666,28 @@ func (w *WebServer) ValidateConfig() (err error) { // Assert LDAP fields when AuthMethod set to LDAP if *w.LDAP.BaseDN == "" { - err = multierr.Append(err, configutils.ErrInvalid{Name: "LDAP.BaseDN", Msg: "LDAP BaseDN can not be empty"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.BaseDN", Msg: "LDAP BaseDN can not be empty"}) } if *w.LDAP.BaseUserAttr == "" { - err = multierr.Append(err, configutils.ErrInvalid{Name: "LDAP.BaseUserAttr", Msg: "LDAP BaseUserAttr can not be empty"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.BaseUserAttr", Msg: "LDAP BaseUserAttr can not be empty"}) } if *w.LDAP.UsersDN == "" { - err = multierr.Append(err, configutils.ErrInvalid{Name: "LDAP.UsersDN", Msg: "LDAP UsersDN can not be empty"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.UsersDN", Msg: "LDAP UsersDN can not be empty"}) } if *w.LDAP.GroupsDN == "" { - err = multierr.Append(err, configutils.ErrInvalid{Name: "LDAP.GroupsDN", Msg: "LDAP GroupsDN can not be empty"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.GroupsDN", Msg: "LDAP GroupsDN can not be empty"}) } if *w.LDAP.AdminUserGroupCN == "" { - err = multierr.Append(err, configutils.ErrInvalid{Name: "LDAP.AdminUserGroupCN", Msg: "LDAP AdminUserGroupCN can not be empty"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.AdminUserGroupCN", Msg: "LDAP AdminUserGroupCN can not be empty"}) } if *w.LDAP.EditUserGroupCN == "" { - err = multierr.Append(err, configutils.ErrInvalid{Name: "LDAP.RunUserGroupCN", Msg: "LDAP ReadUserGroupCN can not be empty"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.RunUserGroupCN", Msg: "LDAP ReadUserGroupCN can not be empty"}) } if *w.LDAP.RunUserGroupCN == "" { - err = multierr.Append(err, configutils.ErrInvalid{Name: "LDAP.RunUserGroupCN", Msg: "LDAP RunUserGroupCN can not be empty"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.RunUserGroupCN", Msg: "LDAP RunUserGroupCN can not be empty"}) } if *w.LDAP.ReadUserGroupCN == "" { - err = multierr.Append(err, configutils.ErrInvalid{Name: "LDAP.ReadUserGroupCN", Msg: "LDAP ReadUserGroupCN can not be empty"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.ReadUserGroupCN", Msg: "LDAP ReadUserGroupCN can not be empty"}) } return err } @@ -1257,17 +1256,17 @@ func (ins *Insecure) validateConfig(buildMode string) (err error) { return } if ins.DevWebServer != nil && *ins.DevWebServer { - err = multierr.Append(err, configutils.ErrInvalid{Name: "DevWebServer", Value: *ins.DevWebServer, Msg: "insecure configs are not allowed on secure builds"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "DevWebServer", Value: *ins.DevWebServer, Msg: "insecure configs are not allowed on secure builds"}) } // OCRDevelopmentMode is allowed on dev/test builds. if ins.OCRDevelopmentMode != nil && *ins.OCRDevelopmentMode && buildMode == build.Prod { - err = multierr.Append(err, configutils.ErrInvalid{Name: "OCRDevelopmentMode", Value: *ins.OCRDevelopmentMode, Msg: "insecure configs are not allowed on secure builds"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "OCRDevelopmentMode", Value: *ins.OCRDevelopmentMode, Msg: "insecure configs are not allowed on secure builds"}) } if ins.InfiniteDepthQueries != nil && *ins.InfiniteDepthQueries { - err = multierr.Append(err, configutils.ErrInvalid{Name: "InfiniteDepthQueries", Value: *ins.InfiniteDepthQueries, Msg: "insecure configs are not allowed on secure builds"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "InfiniteDepthQueries", Value: *ins.InfiniteDepthQueries, Msg: "insecure configs are not allowed on secure builds"}) } if ins.DisableRateLimiting != nil && *ins.DisableRateLimiting { - err = multierr.Append(err, configutils.ErrInvalid{Name: "DisableRateLimiting", Value: *ins.DisableRateLimiting, Msg: "insecure configs are not allowed on secure builds"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "DisableRateLimiting", Value: *ins.DisableRateLimiting, Msg: "insecure configs are not allowed on secure builds"}) } return err } @@ -1318,7 +1317,7 @@ func (m *MercuryTLS) setFrom(f *MercuryTLS) { func (m *MercuryTLS) ValidateConfig() (err error) { if *m.CertFile != "" { if !isValidFilePath(*m.CertFile) { - err = multierr.Append(err, configutils.ErrInvalid{Name: "CertFile", Value: *m.CertFile, Msg: "must be a valid file path"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "CertFile", Value: *m.CertFile, Msg: "must be a valid file path"}) } } return @@ -1374,7 +1373,7 @@ func (m *MercurySecrets) validateMerge(f *MercurySecrets) (err error) { if m.Credentials != nil && f.Credentials != nil { for k := range f.Credentials { if _, exists := m.Credentials[k]; exists { - err = multierr.Append(err, configutils.ErrOverride{Name: fmt.Sprintf("Credentials[\"%s\"]", k)}) + err = errors.Join(err, configutils.ErrOverride{Name: fmt.Sprintf("Credentials[\"%s\"]", k)}) } } } @@ -1386,19 +1385,19 @@ func (m *MercurySecrets) ValidateConfig() (err error) { urls := make(map[string]struct{}, len(m.Credentials)) for name, creds := range m.Credentials { if name == "" { - err = multierr.Append(err, configutils.ErrEmpty{Name: "Name", Msg: "must be provided and non-empty"}) + err = errors.Join(err, configutils.ErrEmpty{Name: "Name", Msg: "must be provided and non-empty"}) } if creds.URL == nil || creds.URL.URL() == nil { - err = multierr.Append(err, configutils.ErrMissing{Name: "URL", Msg: "must be provided and non-empty"}) + err = errors.Join(err, configutils.ErrMissing{Name: "URL", Msg: "must be provided and non-empty"}) continue } if creds.LegacyURL != nil && creds.LegacyURL.URL() == nil { - err = multierr.Append(err, configutils.ErrMissing{Name: "Legacy URL", Msg: "must be a valid URL"}) + err = errors.Join(err, configutils.ErrMissing{Name: "Legacy URL", Msg: "must be a valid URL"}) continue } s := creds.URL.URL().String() if _, exists := urls[s]; exists { - err = multierr.Append(err, configutils.NewErrDuplicate("URL", s)) + err = errors.Join(err, configutils.NewErrDuplicate("URL", s)) } urls[s] = struct{}{} } @@ -1424,7 +1423,7 @@ func (t *ThresholdKeyShareSecrets) SetFrom(f *ThresholdKeyShareSecrets) (err err func (t *ThresholdKeyShareSecrets) validateMerge(f *ThresholdKeyShareSecrets) (err error) { if t.ThresholdKeyShare != nil && f.ThresholdKeyShare != nil { - err = multierr.Append(err, configutils.ErrOverride{Name: "ThresholdKeyShare"}) + err = errors.Join(err, configutils.ErrOverride{Name: "ThresholdKeyShare"}) } return err @@ -1471,7 +1470,7 @@ func (t *Tracing) ValidateConfig() (err error) { if t.SamplingRatio != nil { if *t.SamplingRatio < 0 || *t.SamplingRatio > 1 { - err = multierr.Append(err, configutils.ErrInvalid{Name: "SamplingRatio", Value: *t.SamplingRatio, Msg: "must be between 0 and 1"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "SamplingRatio", Value: *t.SamplingRatio, Msg: "must be between 0 and 1"}) } } @@ -1480,18 +1479,18 @@ func (t *Tracing) ValidateConfig() (err error) { case "tls": // TLSCertPath must be set if t.TLSCertPath == nil { - err = multierr.Append(err, configutils.ErrMissing{Name: "TLSCertPath", Msg: "must be set when Tracing.Mode is tls"}) + err = errors.Join(err, configutils.ErrMissing{Name: "TLSCertPath", Msg: "must be set when Tracing.Mode is tls"}) } else { ok := isValidFilePath(*t.TLSCertPath) if !ok { - err = multierr.Append(err, configutils.ErrInvalid{Name: "TLSCertPath", Value: *t.TLSCertPath, Msg: "must be a valid file path"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "TLSCertPath", Value: *t.TLSCertPath, Msg: "must be a valid file path"}) } } case "unencrypted": // no-op default: // Mode must be either "tls" or "unencrypted" - err = multierr.Append(err, configutils.ErrInvalid{Name: "Mode", Value: *t.Mode, Msg: "must be either 'tls' or 'unencrypted'"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "Mode", Value: *t.Mode, Msg: "must be either 'tls' or 'unencrypted'"}) } } @@ -1499,12 +1498,12 @@ func (t *Tracing) ValidateConfig() (err error) { switch *t.Mode { case "tls": if !isValidURI(*t.CollectorTarget) { - err = multierr.Append(err, configutils.ErrInvalid{Name: "CollectorTarget", Value: *t.CollectorTarget, Msg: "must be a valid URI"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "CollectorTarget", Value: *t.CollectorTarget, Msg: "must be a valid URI"}) } case "unencrypted": // Unencrypted traces can not be sent to external networks if !isValidLocalURI(*t.CollectorTarget) { - err = multierr.Append(err, configutils.ErrInvalid{Name: "CollectorTarget", Value: *t.CollectorTarget, Msg: "must be a valid local URI"}) + err = errors.Join(err, configutils.ErrInvalid{Name: "CollectorTarget", Value: *t.CollectorTarget, Msg: "must be a valid local URI"}) } default: // no-op diff --git a/core/gethwrappers/versions.go b/core/gethwrappers/versions.go index acdefd06a59..34f5b4ea49d 100644 --- a/core/gethwrappers/versions.go +++ b/core/gethwrappers/versions.go @@ -2,6 +2,7 @@ package gethwrappers import ( "bufio" + "errors" "fmt" "os" "path/filepath" @@ -9,8 +10,7 @@ import ( "sort" "strings" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" ) // ContractVersion records information about the solidity compiler artifact a @@ -44,11 +44,11 @@ func dbPath() (path string, err error) { func versionsDBLineReader() (*bufio.Scanner, error) { versionsDBPath, err := dbPath() if err != nil { - return nil, errors.Wrapf(err, "could not construct versions DB path") + return nil, pkgerrors.Wrapf(err, "could not construct versions DB path") } versionsDBFile, err := os.Open(versionsDBPath) if err != nil { - return nil, errors.Wrapf(err, "could not open versions database") + return nil, pkgerrors.Wrapf(err, "could not open versions database") } return bufio.NewScanner(versionsDBFile), nil @@ -66,28 +66,28 @@ func ReadVersionsDB() (*IntegratedVersion, error) { for db.Scan() { line := strings.Fields(db.Text()) if !strings.HasSuffix(line[0], ":") { - return nil, errors.Errorf( + return nil, pkgerrors.Errorf( `each line in versions.txt should start with "$TOPIC:"`) } topic := stripTrailingColon(line[0], "") if topic == "GETH_VERSION" { if len(line) != 2 { - return nil, errors.Errorf("GETH_VERSION line should contain geth "+ + return nil, pkgerrors.Errorf("GETH_VERSION line should contain geth "+ "version, and only that: %s", line) } if rv.GethVersion != "" { - return nil, errors.Errorf("more than one geth version") + return nil, pkgerrors.Errorf("more than one geth version") } rv.GethVersion = line[1] } else { // It's a wrapper from a compiler artifact if len(line) != 4 { - return nil, errors.Errorf(`"%s" should have four elements `+ + return nil, pkgerrors.Errorf(`"%s" should have four elements `+ `": "`, db.Text()) } _, alreadyExists := rv.ContractVersions[topic] if alreadyExists { - return nil, errors.Errorf(`topic "%s" already mentioned`, topic) + return nil, pkgerrors.Errorf(`topic "%s" already mentioned`, topic) } rv.ContractVersions[topic] = ContractVersion{ AbiPath: line[1], BinaryPath: line[2], Hash: line[3], @@ -102,24 +102,24 @@ var stripTrailingColon = regexp.MustCompile(":$").ReplaceAllString func WriteVersionsDB(db *IntegratedVersion) (err error) { versionsDBPath, err := dbPath() if err != nil { - return errors.Wrap(err, "could not construct path to versions DB") + return pkgerrors.Wrap(err, "could not construct path to versions DB") } f, err := os.Create(versionsDBPath) if err != nil { - return errors.Wrapf(err, "while opening %s", versionsDBPath) + return pkgerrors.Wrapf(err, "while opening %s", versionsDBPath) } defer func() { if cerr := f.Close(); cerr != nil { - err = multierr.Append(err, cerr) + err = errors.Join(err, cerr) } }() gethLine := "GETH_VERSION: " + db.GethVersion + "\n" n, err := f.WriteString(gethLine) if err != nil { - return errors.Wrapf(err, "while recording geth version line") + return pkgerrors.Wrapf(err, "while recording geth version line") } if n != len(gethLine) { - return errors.Errorf("failed to write entire geth version line, %s", gethLine) + return pkgerrors.Errorf("failed to write entire geth version line, %s", gethLine) } var pkgNames []string for name := range db.ContractVersions { @@ -132,10 +132,10 @@ func WriteVersionsDB(db *IntegratedVersion) (err error) { vinfo.AbiPath, vinfo.BinaryPath, vinfo.Hash) n, err = f.WriteString(versionLine) if err != nil { - return errors.Wrapf(err, "while recording %s version line", name) + return pkgerrors.Wrapf(err, "while recording %s version line", name) } if n != len(versionLine) { - return errors.Errorf("failed to write entire version line %s", versionLine) + return pkgerrors.Errorf("failed to write entire version line %s", versionLine) } } return nil diff --git a/core/services/blockhashstore/feeder.go b/core/services/blockhashstore/feeder.go index 8cc607db9b3..2c139056f8b 100644 --- a/core/services/blockhashstore/feeder.go +++ b/core/services/blockhashstore/feeder.go @@ -2,13 +2,13 @@ package blockhashstore import ( "context" + "errors" "fmt" "sync" "time" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "golang.org/x/exp/maps" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller" @@ -111,7 +111,7 @@ func (f *Feeder) Run(ctx context.Context) error { latestBlock, err := f.latestBlock(ctx) if err != nil { f.lggr.Errorw("Failed to fetch current block number", "err", err) - return errors.Wrap(err, "fetching block number") + return pkgerrors.Wrap(err, "fetching block number") } fromBlock, toBlock := GetSearchWindow(int(latestBlock), f.waitBlocks, f.lookbackBlocks) @@ -145,7 +145,7 @@ func (f *Feeder) Run(ctx context.Context) error { f.lggr.Errorw("Failed to check if block is already stored, attempting to store anyway", "err", err, "block", block) - errs = multierr.Append(errs, errors.Wrap(err, "checking if stored")) + errs = errors.Join(errs, pkgerrors.Wrap(err, "checking if stored")) } else if stored { // IsStored() can be based on unfinalized blocks. Therefore, f.stored mapping is not updated f.lggr.Infow("Blockhash already stored", @@ -158,7 +158,7 @@ func (f *Feeder) Run(ctx context.Context) error { err = f.bhs.Store(ctx, block) if err != nil { f.lggr.Errorw("Failed to store block", "err", err, "block", block) - errs = multierr.Append(errs, errors.Wrap(err, "storing block")) + errs = errors.Join(errs, pkgerrors.Wrap(err, "storing block")) continue } @@ -216,7 +216,7 @@ func (f *Feeder) runTrusted( "err", err, "block", block) f.errsLock.Lock() - errs = multierr.Append(errs, errors.Wrap(err, "checking if stored")) + errs = errors.Join(errs, pkgerrors.Wrap(err, "checking if stored")) f.errsLock.Unlock() } else if stored { f.lggr.Infow("Blockhash already stored", @@ -250,7 +250,7 @@ func (f *Feeder) runTrusted( f.lggr.Errorw("Failed to get blocks range", "err", err, "blocks", batch) - errs = multierr.Append(errs, errors.Wrap(err, "log poller get blocks range")) + errs = errors.Join(errs, pkgerrors.Wrap(err, "log poller get blocks range")) return errs } @@ -285,7 +285,7 @@ func (f *Feeder) runTrusted( "latestBlock", latestBlock, "latestBlockhash", latestBlockhash, ) - errs = multierr.Append(errs, errors.Wrap(err, "checking if stored")) + errs = errors.Join(errs, pkgerrors.Wrap(err, "checking if stored")) return errs } for i, block := range blocksToStore { diff --git a/core/services/blockheaderfeeder/delegate.go b/core/services/blockheaderfeeder/delegate.go index 53f514cee27..9241e485a7d 100644 --- a/core/services/blockheaderfeeder/delegate.go +++ b/core/services/blockheaderfeeder/delegate.go @@ -2,11 +2,11 @@ package blockheaderfeeder import ( "context" + "errors" "fmt" "time" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink/v2/core/chains/legacyevm" @@ -51,7 +51,7 @@ func (d *Delegate) JobType() job.Type { // ServicesForSpec satisfies the job.Delegate interface. func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { if jb.BlockHeaderFeederSpec == nil { - return nil, errors.Errorf("Delegate expects a BlockHeaderFeederSpec to be present, got %+v", jb) + return nil, pkgerrors.Errorf("Delegate expects a BlockHeaderFeederSpec to be present, got %+v", jb) } chain, err := d.legacyChains.Get(jb.BlockHeaderFeederSpec.EVMChainID.String()) @@ -61,7 +61,7 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { } if !chain.Config().Feature().LogPoller() { - return nil, errors.New("log poller must be enabled to run blockheaderfeeder") + return nil, pkgerrors.New("log poller must be enabled to run blockheaderfeeder") } if jb.BlockHeaderFeederSpec.LookbackBlocks < int32(chain.Config().EVM().FinalityDepth()) { @@ -72,7 +72,7 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { keys, err := d.ks.EnabledKeysForChain(chain.ID()) if err != nil { - return nil, errors.Wrap(err, "getting sending keys") + return nil, pkgerrors.Wrap(err, "getting sending keys") } if len(keys) == 0 { return nil, fmt.Errorf("missing sending keys for chain ID: %v", chain.ID()) @@ -85,13 +85,13 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { bhs, err := blockhash_store.NewBlockhashStore( jb.BlockHeaderFeederSpec.BlockhashStoreAddress.Address(), chain.Client()) if err != nil { - return nil, errors.Wrap(err, "building BHS") + return nil, pkgerrors.Wrap(err, "building BHS") } batchBlockhashStore, err := batch_blockhash_store.NewBatchBlockhashStore( jb.BlockHeaderFeederSpec.BatchBlockhashStoreAddress.Address(), chain.Client()) if err != nil { - return nil, errors.Wrap(err, "building batch BHS") + return nil, pkgerrors.Wrap(err, "building batch BHS") } lp := chain.LogPoller() @@ -101,12 +101,12 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { if c, err = v1.NewVRFCoordinator( jb.BlockHeaderFeederSpec.CoordinatorV1Address.Address(), chain.Client()); err != nil { - return nil, errors.Wrap(err, "building V1 coordinator") + return nil, pkgerrors.Wrap(err, "building V1 coordinator") } var coord *blockhashstore.V1Coordinator coord, err = blockhashstore.NewV1Coordinator(c, lp) if err != nil { - return nil, errors.Wrap(err, "building V1 coordinator") + return nil, pkgerrors.Wrap(err, "building V1 coordinator") } coordinators = append(coordinators, coord) } @@ -115,12 +115,12 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { if c, err = v2.NewVRFCoordinatorV2( jb.BlockHeaderFeederSpec.CoordinatorV2Address.Address(), chain.Client()); err != nil { - return nil, errors.Wrap(err, "building V2 coordinator") + return nil, pkgerrors.Wrap(err, "building V2 coordinator") } var coord *blockhashstore.V2Coordinator coord, err = blockhashstore.NewV2Coordinator(c, lp) if err != nil { - return nil, errors.Wrap(err, "building V2 coordinator") + return nil, pkgerrors.Wrap(err, "building V2 coordinator") } coordinators = append(coordinators, coord) } @@ -129,19 +129,19 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { if c, err = v2plus.NewIVRFCoordinatorV2PlusInternal( jb.BlockHeaderFeederSpec.CoordinatorV2PlusAddress.Address(), chain.Client()); err != nil { - return nil, errors.Wrap(err, "building V2 plus coordinator") + return nil, pkgerrors.Wrap(err, "building V2 plus coordinator") } var coord *blockhashstore.V2PlusCoordinator coord, err = blockhashstore.NewV2PlusCoordinator(c, lp) if err != nil { - return nil, errors.Wrap(err, "building V2 plus coordinator") + return nil, pkgerrors.Wrap(err, "building V2 plus coordinator") } coordinators = append(coordinators, coord) } bpBHS, err := blockhashstore.NewBulletproofBHS(chain.Config().EVM().GasEstimator(), chain.Config().Database(), fromAddresses, chain.TxManager(), bhs, nil, chain.ID(), d.ks) if err != nil { - return nil, errors.Wrap(err, "building bulletproof bhs") + return nil, pkgerrors.Wrap(err, "building bulletproof bhs") } batchBHS, err := blockhashstore.NewBatchBHS( @@ -154,7 +154,7 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { d.logger, ) if err != nil { - return nil, errors.Wrap(err, "building batchBHS") + return nil, pkgerrors.Wrap(err, "building batchBHS") } log := d.logger.Named("BlockHeaderFeeder").With( @@ -177,7 +177,7 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { func(ctx context.Context) (uint64, error) { head, err := chain.Client().HeadByNumber(ctx, nil) if err != nil { - return 0, errors.Wrap(err, "getting chain head") + return 0, pkgerrors.Wrap(err, "getting chain head") } return uint64(head.Number), nil }, @@ -272,7 +272,7 @@ func (s *service) runFeeder() { func CheckFromAddressesExist(jb job.Job, gethks keystore.Eth) (err error) { for _, a := range jb.BlockHeaderFeederSpec.FromAddresses { _, err2 := gethks.Get(a.Hex()) - err = multierr.Append(err, err2) + err = errors.Join(err, err2) } return } diff --git a/core/services/chainlink/application.go b/core/services/chainlink/application.go index 7b4a9951460..ecb26e13f1c 100644 --- a/core/services/chainlink/application.go +++ b/core/services/chainlink/application.go @@ -14,7 +14,6 @@ import ( "github.com/google/uuid" "github.com/grafana/pyroscope-go" pkgerrors "github.com/pkg/errors" - "go.uber.org/multierr" "go.uber.org/zap/zapcore" "github.com/jmoiron/sqlx" @@ -595,7 +594,7 @@ func (app *ChainlinkApplication) stop() (err error) { return } if lerr := app.closeLogger(); lerr != nil { - err = multierr.Append(err, lerr) + err = errors.Join(err, lerr) } }() app.logger.Info("Gracefully exiting...") @@ -604,24 +603,24 @@ func (app *ChainlinkApplication) stop() (err error) { for i := len(app.srvcs) - 1; i >= 0; i-- { service := app.srvcs[i] app.logger.Debugw("Closing service...", "name", service.Name()) - err = multierr.Append(err, service.Close()) + err = errors.Join(err, service.Close()) } app.logger.Debug("Stopping SessionReaper...") - err = multierr.Append(err, app.SessionReaper.Stop()) + err = errors.Join(err, app.SessionReaper.Stop()) app.logger.Debug("Closing HealthChecker...") - err = multierr.Append(err, app.HealthChecker.Close()) + err = errors.Join(err, app.HealthChecker.Close()) if app.FeedsService != nil { app.logger.Debug("Closing Feeds Service...") - err = multierr.Append(err, app.FeedsService.Close()) + err = errors.Join(err, app.FeedsService.Close()) } if app.Nurse != nil { - err = multierr.Append(err, app.Nurse.Close()) + err = errors.Join(err, app.Nurse.Close()) } if app.profiler != nil { - err = multierr.Append(err, app.profiler.Stop()) + err = errors.Join(err, app.profiler.Stop()) } app.logger.Info("Exited all services") diff --git a/core/services/chainlink/config.go b/core/services/chainlink/config.go index 6cd2732ece8..dcbce6cb00c 100644 --- a/core/services/chainlink/config.go +++ b/core/services/chainlink/config.go @@ -4,8 +4,6 @@ import ( "errors" "fmt" - "go.uber.org/multierr" - gotoml "github.com/pelletier/go-toml/v2" coscfg "github.com/smartcontractkit/chainlink-cosmos/pkg/cosmos/config" @@ -56,7 +54,7 @@ func (c *Config) TOMLString() (string, error) { func (c *Config) warnings() (err error) { deprecationErr := c.deprecationWarnings() warningErr := c.valueWarnings() - err = multierr.Append(deprecationErr, warningErr) + err = errors.Join(deprecationErr, warningErr) _, list := utils.MultiErrorList(err) return list } @@ -66,7 +64,7 @@ func (c *Config) valueWarnings() (err error) { if c.Tracing.Enabled != nil && *c.Tracing.Enabled { if c.Tracing.Mode != nil && *c.Tracing.Mode == "unencrypted" { if c.Tracing.TLSCertPath != nil { - err = multierr.Append(err, config.ErrInvalid{Name: "Tracing.TLSCertPath", Value: *c.Tracing.TLSCertPath, Msg: "must be empty when Tracing.Mode is 'unencrypted'"}) + err = errors.Join(err, config.ErrInvalid{Name: "Tracing.TLSCertPath", Value: *c.Tracing.TLSCertPath, Msg: "must be empty when Tracing.Mode is 'unencrypted'"}) } } } @@ -129,19 +127,19 @@ func (c *Config) SetFrom(f *Config) (err error) { c.Core.SetFrom(&f.Core) if err1 := c.EVM.SetFrom(&f.EVM); err1 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err1, "EVM")) + err = errors.Join(err, config.NamedMultiErrorList(err1, "EVM")) } if err2 := c.Cosmos.SetFrom(&f.Cosmos); err2 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err2, "Cosmos")) + err = errors.Join(err, config.NamedMultiErrorList(err2, "Cosmos")) } if err3 := c.Solana.SetFrom(&f.Solana); err3 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err3, "Solana")) + err = errors.Join(err, config.NamedMultiErrorList(err3, "Solana")) } if err4 := c.Starknet.SetFrom(&f.Starknet); err4 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err4, "Starknet")) + err = errors.Join(err, config.NamedMultiErrorList(err4, "Starknet")) } _, err = utils.MultiErrorList(err) @@ -155,31 +153,31 @@ type Secrets struct { func (s *Secrets) SetFrom(f *Secrets) (err error) { if err2 := s.Database.SetFrom(&f.Database); err2 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err2, "Database")) + err = errors.Join(err, config.NamedMultiErrorList(err2, "Database")) } if err2 := s.Password.SetFrom(&f.Password); err2 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err2, "Password")) + err = errors.Join(err, config.NamedMultiErrorList(err2, "Password")) } if err2 := s.WebServer.SetFrom(&f.WebServer); err2 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err2, "WebServer")) + err = errors.Join(err, config.NamedMultiErrorList(err2, "WebServer")) } if err2 := s.Pyroscope.SetFrom(&f.Pyroscope); err2 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err2, "Pyroscope")) + err = errors.Join(err, config.NamedMultiErrorList(err2, "Pyroscope")) } if err2 := s.Prometheus.SetFrom(&f.Prometheus); err2 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err2, "Prometheus")) + err = errors.Join(err, config.NamedMultiErrorList(err2, "Prometheus")) } if err2 := s.Mercury.SetFrom(&f.Mercury); err2 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err2, "Mercury")) + err = errors.Join(err, config.NamedMultiErrorList(err2, "Mercury")) } if err2 := s.Threshold.SetFrom(&f.Threshold); err2 != nil { - err = multierr.Append(err, config.NamedMultiErrorList(err2, "Threshold")) + err = errors.Join(err, config.NamedMultiErrorList(err2, "Threshold")) } _, err = utils.MultiErrorList(err) diff --git a/core/services/chainlink/config_general.go b/core/services/chainlink/config_general.go index ce3ba3a3099..576c62a7927 100644 --- a/core/services/chainlink/config_general.go +++ b/core/services/chainlink/config_general.go @@ -11,7 +11,6 @@ import ( "time" pkgerrors "github.com/pkg/errors" - "go.uber.org/multierr" "go.uber.org/zap/zapcore" coscfg "github.com/smartcontractkit/chainlink-cosmos/pkg/cosmos/config" @@ -251,7 +250,7 @@ func validateEnv() (err error) { k := kv[:i] _, ok := os.LookupEnv(k) if ok { - err = multierr.Append(err, fmt.Errorf("environment variable %s must not be set: %v", k, v2.ErrUnsupported)) + err = errors.Join(err, fmt.Errorf("environment variable %s must not be set: %v", k, v2.ErrUnsupported)) } } return diff --git a/core/services/gateway/connectionmanager.go b/core/services/gateway/connectionmanager.go index 52734f9927f..49219c2108e 100644 --- a/core/services/gateway/connectionmanager.go +++ b/core/services/gateway/connectionmanager.go @@ -13,7 +13,6 @@ import ( "github.com/gorilla/websocket" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -175,7 +174,7 @@ func (m *connectionManager) StartHandshake(authHeader []byte) (attemptId string, m.lggr.Debug("StartHandshake") authHeaderElems, signer, err := network.UnpackSignedAuthHeader(authHeader) if err != nil { - return "", nil, multierr.Append(network.ErrAuthHeaderParse, err) + return "", nil, errors.Join(network.ErrAuthHeaderParse, err) } nodeAddress := "0x" + hex.EncodeToString(signer) donConnMgr, ok := m.dons[authHeaderElems.DonId] diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry.go index a6a2f40f855..31cd5b1807a 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry.go @@ -2,6 +2,7 @@ package evm import ( "context" + "errors" "fmt" "math/big" "strings" @@ -15,7 +16,6 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rpc" - "go.uber.org/multierr" ocr2keepers "github.com/smartcontractkit/chainlink-automation/pkg/v2" @@ -618,7 +618,7 @@ func (r *EvmRegistry) checkUpkeeps(ctx context.Context, keys []ocr2keepers.Upkee for i, req := range checkReqs { if req.Error != nil { r.lggr.Debugf("error encountered for key %s with message '%s' in check", keys[i], req.Error) - multierr.AppendInto(&multiErr, req.Error) + multiErr = errors.Join(multiErr, req.Error) } else { var err error r.lggr.Debugf("UnpackCheckResult key %s checkResult: %s", string(keys[i]), *checkResults[i]) @@ -684,7 +684,7 @@ func (r *EvmRegistry) simulatePerformUpkeeps(ctx context.Context, checkResults [ for i, req := range performReqs { if req.Error != nil { r.lggr.Debugf("error encountered for key %d|%s with message '%s' in simulate perform", checkResults[i].Block, checkResults[i].ID, req.Error) - multierr.AppendInto(&multiErr, req.Error) + multiErr = errors.Join(multiErr, req.Error) } else { simulatePerformSuccess, err := r.packer.UnpackPerformResult(*performResults[i]) if err != nil { @@ -750,7 +750,7 @@ func (r *EvmRegistry) getUpkeepConfigs(ctx context.Context, ids []*big.Int) ([]a for i, req := range uReqs { if req.Error != nil { r.lggr.Debugf("error encountered for config id %s with message '%s' in get config", ids[i], req.Error) - multierr.AppendInto(&multiErr, req.Error) + multiErr = errors.Join(multiErr, req.Error) } else { var err error results[i], err = r.packer.UnpackUpkeepResult(ids[i], *uResults[i]) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry.go index fd7bfa91d7f..0ae3007bcf0 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry.go @@ -2,7 +2,7 @@ package evm import ( "context" - goerrors "errors" + "errors" "fmt" "math/big" "net/http" @@ -18,8 +18,7 @@ import ( "github.com/ethereum/go-ethereum/common" coreTypes "github.com/ethereum/go-ethereum/core/types" "github.com/patrickmn/go-cache" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -324,7 +323,7 @@ func (r *EvmRegistry) refreshLogTriggerUpkeeps(ids []*big.Int) error { idBatch := ids[i:end] if batchErr := r.refreshLogTriggerUpkeepsBatch(idBatch); batchErr != nil { - multierr.AppendInto(&err, batchErr) + err = errors.Join(err, batchErr) } time.Sleep(500 * time.Millisecond) @@ -394,7 +393,7 @@ func (r *EvmRegistry) refreshLogTriggerUpkeepsBatch(logTriggerIDs []*big.Int) er logBlock = unpausedBlockNumbers[id.String()] } if err := r.updateTriggerConfig(id, config, logBlock); err != nil { - merr = goerrors.Join(merr, fmt.Errorf("failed to update trigger config for upkeep id %s: %w", id.String(), err)) + merr = errors.Join(merr, fmt.Errorf("failed to update trigger config for upkeep id %s: %w", id.String(), err)) } } @@ -592,7 +591,7 @@ func (r *EvmRegistry) updateTriggerConfig(id *big.Int, cfg []byte, logBlock uint if len(cfg) == 0 { fetched, err := r.fetchTriggerConfig(id) if err != nil { - return errors.Wrap(err, "failed to fetch log upkeep config") + return pkgerrors.Wrap(err, "failed to fetch log upkeep config") } cfg = fetched } @@ -607,7 +606,7 @@ func (r *EvmRegistry) updateTriggerConfig(id *big.Int, cfg []byte, logBlock uint UpkeepID: id, UpdateBlock: logBlock, }); err != nil { - return errors.Wrap(err, "failed to register log filter") + return pkgerrors.Wrap(err, "failed to register log filter") } r.lggr.Debugw("registered log filter", "upkeepID", id.String(), "cfg", parsed) default: diff --git a/core/services/ocrcommon/validate.go b/core/services/ocrcommon/validate.go index f7ebcf79466..dde5b137dae 100644 --- a/core/services/ocrcommon/validate.go +++ b/core/services/ocrcommon/validate.go @@ -1,9 +1,10 @@ package ocrcommon import ( + "errors" + "github.com/pelletier/go-toml" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" ) // CloneSet returns a copy of the input map. @@ -22,12 +23,12 @@ func ValidateExplicitlySetKeys(tree *toml.Tree, expected map[string]struct{}, no // top level keys only for _, k := range tree.Keys() { if _, ok := notExpected[k]; ok { - err = multierr.Append(err, errors.Errorf("unrecognised key for %s peer: %s", peerType, k)) + err = errors.Join(err, pkgerrors.Errorf("unrecognised key for %s peer: %s", peerType, k)) } delete(expected, k) } for missing := range expected { - err = multierr.Append(err, errors.Errorf("missing required key %s", missing)) + err = errors.Join(err, pkgerrors.Errorf("missing required key %s", missing)) } return err } diff --git a/core/services/telemetry/manager.go b/core/services/telemetry/manager.go index c457aca5bf8..5c76cfb349b 100644 --- a/core/services/telemetry/manager.go +++ b/core/services/telemetry/manager.go @@ -2,12 +2,12 @@ package telemetry import ( "context" + "errors" "net/url" "strings" "time" - "github.com/pkg/errors" - "go.uber.org/multierr" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/commontypes" @@ -118,7 +118,7 @@ func (m *Manager) Start(ctx context.Context) error { return m.StartOnce("TelemetryManager", func() error { var err error for _, e := range m.endpoints { - err = multierr.Append(err, e.client.Start(ctx)) + err = errors.Join(err, e.client.Start(ctx)) } return err }) @@ -127,7 +127,7 @@ func (m *Manager) Close() error { return m.StopOnce("TelemetryManager", func() error { var err error for _, e := range m.endpoints { - err = multierr.Append(err, e.client.Close()) + err = errors.Join(err, e.client.Close()) } return err }) @@ -166,23 +166,23 @@ func (m *Manager) GenMonitoringEndpoint(network string, chainID string, contract func (m *Manager) addEndpoint(e config.TelemetryIngressEndpoint) error { if e.Network() == "" && !m.legacyMode { - return errors.New("cannot add telemetry endpoint, network cannot be empty") + return pkgerrors.New("cannot add telemetry endpoint, network cannot be empty") } if e.ChainID() == "" && !m.legacyMode { - return errors.New("cannot add telemetry endpoint, chainID cannot be empty") + return pkgerrors.New("cannot add telemetry endpoint, chainID cannot be empty") } if e.URL() == nil { - return errors.New("cannot add telemetry endpoint, URL cannot be empty") + return pkgerrors.New("cannot add telemetry endpoint, URL cannot be empty") } if e.ServerPubKey() == "" { - return errors.New("cannot add telemetry endpoint, ServerPubKey cannot be empty") + return pkgerrors.New("cannot add telemetry endpoint, ServerPubKey cannot be empty") } if _, found := m.getEndpoint(e.Network(), e.ChainID()); found { - return errors.Errorf("cannot add telemetry endpoint for network %q and chainID %q, endpoint already exists", e.Network(), e.ChainID()) + return pkgerrors.Errorf("cannot add telemetry endpoint for network %q and chainID %q, endpoint already exists", e.Network(), e.ChainID()) } var tClient synchronization.TelemetryService diff --git a/core/services/vrf/delegate.go b/core/services/vrf/delegate.go index ecabbc09c71..971982c1031 100644 --- a/core/services/vrf/delegate.go +++ b/core/services/vrf/delegate.go @@ -1,14 +1,14 @@ package vrf import ( + "errors" "fmt" "time" "github.com/avast/retry-go/v4" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/theodesp/go-heaps/pairing" - "go.uber.org/multierr" "github.com/jmoiron/sqlx" @@ -74,7 +74,7 @@ func (d *Delegate) OnDeleteJob(job.Job, pg.Queryer) error { return nil } // ServicesForSpec satisfies the job.Delegate interface. func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { if jb.VRFSpec == nil || jb.PipelineSpec == nil { - return nil, errors.Errorf("vrf.Delegate expects a VRFSpec and PipelineSpec to be present, got %+v", jb) + return nil, pkgerrors.Errorf("vrf.Delegate expects a VRFSpec and PipelineSpec to be present, got %+v", jb) } pl, err := jb.PipelineSpec.ParsePipeline() if err != nil { @@ -103,7 +103,7 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { batchCoordinatorV2, err = batch_vrf_coordinator_v2.NewBatchVRFCoordinatorV2( jb.VRFSpec.BatchCoordinatorAddress.Address(), chain.Client()) if err != nil { - return nil, errors.Wrap(err, "create batch coordinator wrapper") + return nil, pkgerrors.Wrap(err, "create batch coordinator wrapper") } } @@ -113,7 +113,7 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { jb.VRFSpec.VRFOwnerAddress.Address(), chain.Client(), ) if err != nil { - return nil, errors.Wrap(err, "create vrf owner wrapper") + return nil, pkgerrors.Wrap(err, "create vrf owner wrapper") } } @@ -133,17 +133,17 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { } if !FromAddressMaxGasPricesAllEqual(jb, chain.Config().EVM().GasEstimator().PriceMaxKey) { - return nil, errors.New("key-specific max gas prices of all fromAddresses are not equal, please set them to equal values") + return nil, pkgerrors.New("key-specific max gas prices of all fromAddresses are not equal, please set them to equal values") } if err2 := CheckFromAddressMaxGasPrices(jb, chain.Config().EVM().GasEstimator().PriceMaxKey); err != nil { return nil, err2 } if vrfOwner != nil { - return nil, errors.New("VRF Owner is not supported for VRF V2 Plus") + return nil, pkgerrors.New("VRF Owner is not supported for VRF V2 Plus") } if jb.VRFSpec.CustomRevertsPipelineEnabled { - return nil, errors.New("Custom Reverted Txns Pipeline is not supported for VRF V2 Plus") + return nil, pkgerrors.New("Custom Reverted Txns Pipeline is not supported for VRF V2 Plus") } // Get the LINKNATIVEFEED address with retries @@ -155,12 +155,12 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { return err }, retry.Attempts(10), retry.Delay(500*time.Millisecond)) if err != nil { - return nil, errors.Wrap(err, "can't call LINKNATIVEFEED") + return nil, pkgerrors.Wrap(err, "can't call LINKNATIVEFEED") } aggregator, err2 := aggregator_v3_interface.NewAggregatorV3Interface(linkNativeFeedAddress, chain.Client()) if err2 != nil { - return nil, errors.Wrap(err2, "NewAggregatorV3Interface") + return nil, pkgerrors.Wrap(err2, "NewAggregatorV3Interface") } return []job.ServiceCtx{ @@ -192,7 +192,7 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { } if !FromAddressMaxGasPricesAllEqual(jb, chain.Config().EVM().GasEstimator().PriceMaxKey) { - return nil, errors.New("key-specific max gas prices of all fromAddresses are not equal, please set them to equal values") + return nil, pkgerrors.New("key-specific max gas prices of all fromAddresses are not equal, please set them to equal values") } if err2 := CheckFromAddressMaxGasPrices(jb, chain.Config().EVM().GasEstimator().PriceMaxKey); err != nil { @@ -208,11 +208,11 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { return err }, retry.Attempts(10), retry.Delay(500*time.Millisecond)) if err != nil { - return nil, errors.Wrap(err, "LINKETHFEED") + return nil, pkgerrors.Wrap(err, "LINKETHFEED") } aggregator, err := aggregator_v3_interface.NewAggregatorV3Interface(linkEthFeedAddress, chain.Client()) if err != nil { - return nil, errors.Wrap(err, "NewAggregatorV3Interface") + return nil, pkgerrors.Wrap(err, "NewAggregatorV3Interface") } if vrfOwner == nil { lV2.Infow("Running without VRFOwnerAddress set on the spec") @@ -264,7 +264,7 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { }}, nil } } - return nil, errors.New("invalid job spec expected a vrf task") + return nil, pkgerrors.New("invalid job spec expected a vrf task") } // CheckFromAddressesExist returns an error if and only if one of the addresses @@ -272,7 +272,7 @@ func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { func CheckFromAddressesExist(jb job.Job, gethks keystore.Eth) (err error) { for _, a := range jb.VRFSpec.FromAddresses { _, err2 := gethks.Get(a.Hex()) - err = multierr.Append(err, err2) + err = errors.Join(err, err2) } return } @@ -285,7 +285,7 @@ func CheckFromAddressMaxGasPrices(jb job.Job, keySpecificMaxGas keySpecificMaxGa if jb.VRFSpec.GasLanePrice != nil { for _, a := range jb.VRFSpec.FromAddresses { if keySpecific := keySpecificMaxGas(a.Address()); !keySpecific.Equal(jb.VRFSpec.GasLanePrice) { - err = multierr.Append(err, + err = errors.Join(err, fmt.Errorf( "key-specific max gas price of from address %s (%s) does not match gasLanePriceGWei (%s) specified in job spec", a.Hex(), keySpecific.String(), jb.VRFSpec.GasLanePrice.String())) diff --git a/core/services/vrf/v2/listener_v2_log_listener.go b/core/services/vrf/v2/listener_v2_log_listener.go index 07b4c2c3800..cbb892552e9 100644 --- a/core/services/vrf/v2/listener_v2_log_listener.go +++ b/core/services/vrf/v2/listener_v2_log_listener.go @@ -3,12 +3,12 @@ package v2 import ( "bytes" "context" + "errors" "fmt" "math/big" "time" "github.com/ethereum/go-ethereum/common" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/utils/mathutil" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller" @@ -281,7 +281,7 @@ func (lsn *listenerV2) getUnfulfilled(logs []logpoller.Log, ll logger.Logger) (u parsed, err2 := lsn.coordinator.ParseRandomWordsFulfilled(l.ToGethLog()) if err2 != nil { // should never happen - errs = multierr.Append(errs, err2) + errs = errors.Join(errs, err2) continue } fulfilled[parsed.RequestID().String()] = parsed @@ -289,7 +289,7 @@ func (lsn *listenerV2) getUnfulfilled(logs []logpoller.Log, ll logger.Logger) (u parsed, err2 := lsn.coordinator.ParseRandomWordsRequested(l.ToGethLog()) if err2 != nil { // should never happen - errs = multierr.Append(errs, err2) + errs = errors.Join(errs, err2) continue } keyHash := parsed.KeyHash() diff --git a/core/services/vrf/v2/listener_v2_log_processor.go b/core/services/vrf/v2/listener_v2_log_processor.go index 221900f0029..cd2abe3d350 100644 --- a/core/services/vrf/v2/listener_v2_log_processor.go +++ b/core/services/vrf/v2/listener_v2_log_processor.go @@ -19,7 +19,6 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rpc" pkgerrors "github.com/pkg/errors" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/utils/hex" txmgrcommon "github.com/smartcontractkit/chainlink/v2/common/txmgr" @@ -1003,21 +1002,21 @@ func (lsn *listenerV2) checkReqsFulfilled(ctx context.Context, l logger.Logger, var errs error for i, call := range calls { if call.Error != nil { - errs = multierr.Append(errs, fmt.Errorf("checking request %s with hash %s: %w", + errs = errors.Join(errs, fmt.Errorf("checking request %s with hash %s: %w", reqs[i].req.RequestID().String(), reqs[i].req.Raw().TxHash.String(), call.Error)) continue } rString, ok := call.Result.(*string) if !ok { - errs = multierr.Append(errs, + errs = errors.Join(errs, fmt.Errorf("unexpected result %+v on request %s with hash %s", call.Result, reqs[i].req.RequestID().String(), reqs[i].req.Raw().TxHash.String())) continue } result, err := hexutil.Decode(*rString) if err != nil { - errs = multierr.Append(errs, + errs = errors.Join(errs, fmt.Errorf("decoding batch call result %+v %s request %s with hash %s: %w", call.Result, *rString, reqs[i].req.RequestID().String(), reqs[i].req.Raw().TxHash.String(), err)) continue diff --git a/core/store/models/common.go b/core/store/models/common.go index e446481ff64..10d8322b02c 100644 --- a/core/store/models/common.go +++ b/core/store/models/common.go @@ -5,6 +5,7 @@ import ( "database/sql/driver" "encoding/hex" "encoding/json" + "errors" "fmt" "net/url" "regexp" @@ -12,10 +13,9 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/robfig/cron/v3" "github.com/tidwall/gjson" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big" @@ -181,7 +181,7 @@ func (c *Cron) UnmarshalJSON(b []byte) error { } if !strings.HasPrefix(s, "CRON_TZ=") { - return errors.New("Cron: specs must specify a time zone using CRON_TZ, e.g. 'CRON_TZ=UTC 5 * * * *'") + return pkgerrors.New("Cron: specs must specify a time zone using CRON_TZ, e.g. 'CRON_TZ=UTC 5 * * * *'") } _, err = CronParser.Parse(s) @@ -233,7 +233,7 @@ func (i *Interval) Scan(v interface{}) error { } asInt64, is := v.(int64) if !is { - return errors.Errorf("models.Interval#Scan() wanted int64, got %T", v) + return pkgerrors.Errorf("models.Interval#Scan() wanted int64, got %T", v) } *i = Interval(time.Duration(asInt64) * time.Nanosecond) return nil @@ -311,7 +311,7 @@ func Merge(inputs ...JSON) (JSON, error) { } case nil: default: - return JSON{}, errors.New("can only merge JSON objects") + return JSON{}, pkgerrors.New("can only merge JSON objects") } } @@ -385,7 +385,7 @@ func (s *Sha256Hash) UnmarshalText(bs []byte) (err error) { func (s *Sha256Hash) Scan(value interface{}) error { bytes, ok := value.([]byte) if !ok { - return errors.Errorf("Failed to unmarshal Sha256Hash value: %v", value) + return pkgerrors.Errorf("Failed to unmarshal Sha256Hash value: %v", value) } if s == nil { *s = Sha256Hash{} @@ -425,7 +425,7 @@ type ServiceHeaders []ServiceHeader func (sh *ServiceHeaders) UnmarshalText(input []byte) error { if sh == nil { - return errors.New("Cannot unmarshal to a nil receiver") + return pkgerrors.New("Cannot unmarshal to a nil receiver") } headers := string(input) @@ -436,7 +436,7 @@ func (sh *ServiceHeaders) UnmarshalText(input []byte) error { for _, header := range headerLines { keyValue := strings.Split(header, "||") if len(keyValue) != 2 { - return errors.Errorf("invalid headers provided for the audit logger. Value, single pair split on || required, got: %s", keyValue) + return pkgerrors.Errorf("invalid headers provided for the audit logger. Value, single pair split on || required, got: %s", keyValue) } h := ServiceHeader{ Header: keyValue[0], @@ -456,7 +456,7 @@ func (sh *ServiceHeaders) UnmarshalText(input []byte) error { func (sh *ServiceHeaders) MarshalText() ([]byte, error) { if sh == nil { - return nil, errors.New("Cannot marshal to a nil receiver") + return nil, pkgerrors.New("Cannot marshal to a nil receiver") } sb := strings.Builder{} @@ -487,11 +487,11 @@ var ( func (h ServiceHeader) Validate() (err error) { if !headerNameRegex.MatchString(h.Header) { - err = multierr.Append(err, errors.Errorf("invalid header name: %s", h.Header)) + err = errors.Join(err, pkgerrors.Errorf("invalid header name: %s", h.Header)) } if !headerValueRegex.MatchString(h.Value) { - err = multierr.Append(err, errors.Errorf("invalid header value: %s", h.Value)) + err = errors.Join(err, pkgerrors.Errorf("invalid header value: %s", h.Value)) } return } diff --git a/core/utils/config/validate.go b/core/utils/config/validate.go index 5fbae24ad53..0699809a92f 100644 --- a/core/utils/config/validate.go +++ b/core/utils/config/validate.go @@ -1,13 +1,13 @@ package config import ( + "errors" "fmt" "reflect" "strconv" "strings" "github.com/Masterminds/semver/v3" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/config" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -33,11 +33,11 @@ func validate(v reflect.Value, checkInterface bool) (err error) { if checkInterface { i := v.Interface() if vc, ok := i.(Validated); ok { - err = multierr.Append(err, vc.ValidateConfig()) + err = errors.Join(err, vc.ValidateConfig()) } else if v.CanAddr() { i = v.Addr().Interface() if vc, ok := i.(Validated); ok { - err = multierr.Append(err, vc.ValidateConfig()) + err = errors.Join(err, vc.ValidateConfig()) } } } @@ -72,9 +72,9 @@ func validate(v reflect.Value, checkInterface bool) (err error) { // skip the interface if Anonymous, since the parent struct inherits the methods if fe := validate(fv, !ft.Anonymous); fe != nil { if ft.Anonymous { - err = multierr.Append(err, fe) + err = errors.Join(err, fe) } else { - err = multierr.Append(err, NamedMultiErrorList(fe, ft.Name)) + err = errors.Join(err, NamedMultiErrorList(fe, ft.Name)) } } } @@ -91,7 +91,7 @@ func validate(v reflect.Value, checkInterface bool) (err error) { continue } if me := validate(mv, true); me != nil { - err = multierr.Append(err, NamedMultiErrorList(me, fmt.Sprintf("%s", mk.Interface()))) + err = errors.Join(err, NamedMultiErrorList(me, fmt.Sprintf("%s", mk.Interface()))) } } return @@ -105,7 +105,7 @@ func validate(v reflect.Value, checkInterface bool) (err error) { continue } if me := validate(iv, true); me != nil { - err = multierr.Append(err, NamedMultiErrorList(me, strconv.Itoa(i))) + err = errors.Join(err, NamedMultiErrorList(me, strconv.Itoa(i))) } } return diff --git a/core/web/sessions_controller.go b/core/web/sessions_controller.go index 23ecfd3b798..fb9e6dbf5e0 100644 --- a/core/web/sessions_controller.go +++ b/core/web/sessions_controller.go @@ -7,7 +7,6 @@ import ( "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" - "go.uber.org/multierr" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" @@ -60,7 +59,7 @@ func (sc *SessionsController) Create(c *gin.Context) { } if err := saveSessionID(session, sid); err != nil { - jsonAPIError(c, http.StatusInternalServerError, multierr.Append(errors.New("unable to save session id"), err)) + jsonAPIError(c, http.StatusInternalServerError, errors.Join(errors.New("unable to save session id"), err)) return } From 4b494306a13196853df31ba82ddca5904b4e08ed Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 18 Jan 2024 16:35:06 -0500 Subject: [PATCH 3/4] replace multierr with standard golang libary --- core/utils/config/validate.go | 2 +- core/utils/errors.go | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/core/utils/config/validate.go b/core/utils/config/validate.go index 0699809a92f..3f669a7f4b3 100644 --- a/core/utils/config/validate.go +++ b/core/utils/config/validate.go @@ -18,7 +18,7 @@ type Validated interface { // ValidateConfig returns nil if the config is valid, otherwise an error describing why it is invalid. // // For implementations: - // - Use package multierr to accumulate all errors, rather than returning the first encountered. + // - Use standard library errors package (errors#Join) to accumulate all errors, rather than returning the first encountered. // - If an anonymous field also implements ValidateConfig(), it must be called explicitly! ValidateConfig() error } diff --git a/core/utils/errors.go b/core/utils/errors.go index 3ed5e6b024d..f66eef397fb 100644 --- a/core/utils/errors.go +++ b/core/utils/errors.go @@ -3,8 +3,6 @@ package utils import ( "fmt" "strings" - - "go.uber.org/multierr" ) type multiErrorList []error @@ -14,7 +12,14 @@ func MultiErrorList(err error) (int, error) { if err == nil { return 0, nil } - errs := multierr.Errors(err) + + u, ok := err.(interface { + Unwrap() []error + }) + if !ok { + return 1, multiErrorList{err} + } + errs := u.Unwrap() return len(errs), multiErrorList(errs) } From 0c3060896c35c5d748a445299f583da64dcd9007 Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 18 Jan 2024 16:36:17 -0500 Subject: [PATCH 4/4] run make gomodtidy --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index a5aa4eb23dc..9a5a95f1ab4 100644 --- a/go.mod +++ b/go.mod @@ -88,7 +88,6 @@ require ( go.dedis.ch/fixbuf v1.0.3 go.dedis.ch/kyber/v3 v3.1.0 go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.46.1 - go.uber.org/multierr v1.11.0 go.uber.org/zap v1.26.0 golang.org/x/crypto v0.17.0 golang.org/x/exp v0.0.0-20231127185646-65229373498e @@ -309,6 +308,7 @@ require ( go.opentelemetry.io/otel/sdk v1.21.0 // indirect go.opentelemetry.io/otel/trace v1.21.0 // indirect go.opentelemetry.io/proto/otlp v1.0.0 // indirect + go.uber.org/multierr v1.11.0 // indirect go.uber.org/ratelimit v0.2.0 // indirect golang.org/x/arch v0.6.0 // indirect golang.org/x/mod v0.14.0 // indirect