From 7d64b5189d7b84cc470feb3fb2b5f123ad0380fe Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Tue, 13 Feb 2024 13:39:27 -0600 Subject: [PATCH] golangci-lint: revive: add early-return; fix issues (#12017) --- .golangci.yml | 2 +- .../chains/evm/gas/block_history_estimator.go | 85 +++++++++---------- core/chains/evm/types/models.go | 47 +++++----- core/cmd/shell_local.go | 53 ++++++------ core/gethwrappers/abigen.go | 5 +- core/gethwrappers/go_generate_test.go | 5 +- core/gethwrappers/utils.go | 5 +- .../handler/keeper_verifiable_load.go | 7 +- core/scripts/common/polygonedge.go | 5 +- core/services/ocr2/delegate.go | 7 +- .../evmregistry/v21/payload_builder.go | 35 ++++---- .../ocr2vrf/coordinator/coordinator.go | 19 ++--- core/services/pipeline/common.go | 5 +- core/services/pipeline/runner.go | 5 +- core/services/pipeline/task_params.go | 6 +- .../evm/functions/contract_transmitter.go | 5 +- .../relay/evm/functions/logpoller_wrapper.go | 7 +- .../relay/evm/mercury/wsrpc/client.go | 16 ++-- .../vrf/v2/listener_v2_log_processor.go | 23 +++-- core/sessions/ldapauth/ldap.go | 16 ++-- core/web/cosmos_transfer_controller.go | 6 +- 21 files changed, 171 insertions(+), 193 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 3672692f599..71468b4975f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -71,7 +71,7 @@ linters-settings: - name: identical-branches - name: get-return # - name: flag-parameter - # - name: early-return + - name: early-return - name: defer - name: constant-logical-expr # - name: confusing-naming diff --git a/core/chains/evm/gas/block_history_estimator.go b/core/chains/evm/gas/block_history_estimator.go index dc95240fd42..5ac8ca5faf8 100644 --- a/core/chains/evm/gas/block_history_estimator.go +++ b/core/chains/evm/gas/block_history_estimator.go @@ -340,11 +340,10 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er // reverse order since we want to go highest -> lowest block number and bail out early for i := l - 1; i >= 0; i-- { block := blockHistory[i] - if block.Number >= broadcastBeforeBlockNum { - blocks = append(blocks, block) - } else { + if block.Number < broadcastBeforeBlockNum { break } + blocks = append(blocks, block) } var eip1559 bool switch attempt.TxType { @@ -364,27 +363,26 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er b.logger.AssumptionViolationw("unexpected error while verifying transaction inclusion", "err", err, "txHash", attempt.TxHash.String()) return nil } - if eip1559 { - sufficientFeeCap := true - for _, b := range blocks { - // feecap must >= tipcap+basefee for the block, otherwise there - // is no way this could have been included, and we must bail - // out of the check - attemptFeeCap := attempt.DynamicFee.FeeCap - attemptTipCap := attempt.DynamicFee.TipCap - if attemptFeeCap.Cmp(attemptTipCap.Add(b.BaseFeePerGas)) < 0 { - sufficientFeeCap = false - break - } - } - if sufficientFeeCap && attempt.DynamicFee.TipCap.Cmp(tipCap) > 0 { - return errors.Wrapf(commonfee.ErrConnectivity, "transaction %s has tip cap of %s, which is above percentile=%d%% (percentile tip cap: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.DynamicFee.TipCap, percentile, tipCap, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) - } - } else { + if !eip1559 { if attempt.GasPrice.Cmp(gasPrice) > 0 { return errors.Wrapf(commonfee.ErrConnectivity, "transaction %s has gas price of %s, which is above percentile=%d%% (percentile price: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.GasPrice, percentile, gasPrice, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) - } + continue + } + sufficientFeeCap := true + for _, b := range blocks { + // feecap must >= tipcap+basefee for the block, otherwise there + // is no way this could have been included, and we must bail + // out of the check + attemptFeeCap := attempt.DynamicFee.FeeCap + attemptTipCap := attempt.DynamicFee.TipCap + if attemptFeeCap.Cmp(attemptTipCap.Add(b.BaseFeePerGas)) < 0 { + sufficientFeeCap = false + break + } + } + if sufficientFeeCap && attempt.DynamicFee.TipCap.Cmp(tipCap) > 0 { + return errors.Wrapf(commonfee.ErrConnectivity, "transaction %s has tip cap of %s, which is above percentile=%d%% (percentile tip cap: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.DynamicFee.TipCap, percentile, tipCap, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) } } return nil @@ -560,20 +558,20 @@ func (b *BlockHistoryEstimator) Recalculate(head *evmtypes.Head) { b.setPercentileGasPrice(percentileGasPrice) promBlockHistoryEstimatorSetGasPrice.WithLabelValues(fmt.Sprintf("%v%%", percentile), b.chainID.String()).Set(float64(percentileGasPrice.Int64())) - if eip1559 { - float = new(big.Float).SetInt(percentileTipCap.ToInt()) - gwei, _ = big.NewFloat(0).Quo(float, big.NewFloat(1000000000)).Float64() - tipCapGwei := fmt.Sprintf("%.2f", gwei) - lggrFields = append(lggrFields, []interface{}{ - "tipCapWei", percentileTipCap, - "tipCapGwei", tipCapGwei, - }...) - lggr.Debugw(fmt.Sprintf("Setting new default prices, GasPrice: %v Gwei, TipCap: %v Gwei", gasPriceGwei, tipCapGwei), lggrFields...) - b.setPercentileTipCap(percentileTipCap) - promBlockHistoryEstimatorSetTipCap.WithLabelValues(fmt.Sprintf("%v%%", percentile), b.chainID.String()).Set(float64(percentileTipCap.Int64())) - } else { + if !eip1559 { lggr.Debugw(fmt.Sprintf("Setting new default gas price: %v Gwei", gasPriceGwei), lggrFields...) + return } + float = new(big.Float).SetInt(percentileTipCap.ToInt()) + gwei, _ = big.NewFloat(0).Quo(float, big.NewFloat(1000000000)).Float64() + tipCapGwei := fmt.Sprintf("%.2f", gwei) + lggrFields = append(lggrFields, []interface{}{ + "tipCapWei", percentileTipCap, + "tipCapGwei", tipCapGwei, + }...) + lggr.Debugw(fmt.Sprintf("Setting new default prices, GasPrice: %v Gwei, TipCap: %v Gwei", gasPriceGwei, tipCapGwei), lggrFields...) + b.setPercentileTipCap(percentileTipCap) + promBlockHistoryEstimatorSetTipCap.WithLabelValues(fmt.Sprintf("%v%%", percentile), b.chainID.String()).Set(float64(percentileTipCap.Int64())) } // FetchBlocks fetches block history leading up to the given head. @@ -774,21 +772,20 @@ func (b *BlockHistoryEstimator) getPricesFromBlocks(blocks []evmtypes.Block, eip for _, tx := range block.Transactions { if b.IsUsable(tx, block, b.config.ChainType(), b.eConfig.PriceMin(), b.logger) { gp := b.EffectiveGasPrice(block, tx) - if gp != nil { - gasPrices = append(gasPrices, gp) - } else { + if gp == nil { b.logger.Warnw("Unable to get gas price for tx", "tx", tx, "block", block) continue } - if eip1559 { - tc := b.EffectiveTipCap(block, tx) - if tc != nil { - tipCaps = append(tipCaps, tc) - } else { - b.logger.Warnw("Unable to get tip cap for tx", "tx", tx, "block", block) - continue - } + gasPrices = append(gasPrices, gp) + if !eip1559 { + continue + } + tc := b.EffectiveTipCap(block, tx) + if tc == nil { + b.logger.Warnw("Unable to get tip cap for tx", "tx", tx, "block", block) + continue } + tipCaps = append(tipCaps, tc) } } } diff --git a/core/chains/evm/types/models.go b/core/chains/evm/types/models.go index 44e150b6541..7db38fc6821 100644 --- a/core/chains/evm/types/models.go +++ b/core/chains/evm/types/models.go @@ -105,11 +105,10 @@ func (h *Head) IsInChain(blockHash common.Hash) bool { if h.Hash == blockHash { return true } - if h.Parent != nil { - h = h.Parent - } else { + if h.Parent == nil { break } + h = h.Parent } return false } @@ -121,11 +120,10 @@ func (h *Head) HashAtHeight(blockNum int64) common.Hash { if h.Number == blockNum { return h.Hash } - if h.Parent != nil { - h = h.Parent - } else { + if h.Parent == nil { break } + h = h.Parent } return common.Hash{} } @@ -138,15 +136,14 @@ func (h *Head) ChainLength() uint32 { l := uint32(1) for { - if h.Parent != nil { - l++ - if h == h.Parent { - panic("circular reference detected") - } - h = h.Parent - } else { + if h.Parent == nil { break } + l++ + if h == h.Parent { + panic("circular reference detected") + } + h = h.Parent } return l } @@ -157,14 +154,13 @@ func (h *Head) ChainHashes() []common.Hash { for { hashes = append(hashes, h.Hash) - if h.Parent != nil { - if h == h.Parent { - panic("circular reference detected") - } - h = h.Parent - } else { + if h.Parent == nil { break } + if h == h.Parent { + panic("circular reference detected") + } + h = h.Parent } return hashes } @@ -186,15 +182,14 @@ func (h *Head) ChainString() string { for { sb.WriteString(h.String()) - if h.Parent != nil { - if h == h.Parent { - panic("circular reference detected") - } - sb.WriteString("->") - h = h.Parent - } else { + if h.Parent == nil { break } + if h == h.Parent { + panic("circular reference detected") + } + sb.WriteString("->") + h = h.Parent } sb.WriteString("->nil") return sb.String() diff --git a/core/cmd/shell_local.go b/core/cmd/shell_local.go index b970b516413..350e6abf77d 100644 --- a/core/cmd/shell_local.go +++ b/core/cmd/shell_local.go @@ -1002,37 +1002,36 @@ func (s *Shell) CleanupChainTables(c *cli.Context) error { // some tables with evm_chain_id (mostly job specs) are in public schema tablesToDeleteFromQuery := `SELECT table_name, table_schema FROM information_schema.columns WHERE "column_name"=$1;` // Delete rows from each table based on the chain_id. - if strings.EqualFold("EVM", c.String("type")) { - rows, err := db.Query(tablesToDeleteFromQuery, "evm_chain_id") - if err != nil { - return err - } - defer rows.Close() + if !strings.EqualFold("EVM", c.String("type")) { + return s.errorOut(errors.New("unknown chain type")) + } + rows, err := db.Query(tablesToDeleteFromQuery, "evm_chain_id") + if err != nil { + return err + } + defer rows.Close() - var tablesToDeleteFrom []string - for rows.Next() { - var name string - var schema string - if err = rows.Scan(&name, &schema); err != nil { - return err - } - tablesToDeleteFrom = append(tablesToDeleteFrom, schema+"."+name) - } - if rows.Err() != nil { - return rows.Err() + var tablesToDeleteFrom []string + for rows.Next() { + var name string + var schema string + if err = rows.Scan(&name, &schema); err != nil { + return err } + tablesToDeleteFrom = append(tablesToDeleteFrom, schema+"."+name) + } + if rows.Err() != nil { + return rows.Err() + } - for _, tableName := range tablesToDeleteFrom { - query := fmt.Sprintf(`DELETE FROM %s WHERE "evm_chain_id"=$1;`, tableName) - _, err = db.Exec(query, c.String("id")) - if err != nil { - fmt.Printf("Error deleting rows containing evm_chain_id from %s: %v\n", tableName, err) - } else { - fmt.Printf("Rows with evm_chain_id %s deleted from %s.\n", c.String("id"), tableName) - } + for _, tableName := range tablesToDeleteFrom { + query := fmt.Sprintf(`DELETE FROM %s WHERE "evm_chain_id"=$1;`, tableName) + _, err = db.Exec(query, c.String("id")) + if err != nil { + fmt.Printf("Error deleting rows containing evm_chain_id from %s: %v\n", tableName, err) + } else { + fmt.Printf("Rows with evm_chain_id %s deleted from %s.\n", c.String("id"), tableName) } - } else { - return s.errorOut(errors.New("unknown chain type")) } return nil } diff --git a/core/gethwrappers/abigen.go b/core/gethwrappers/abigen.go index ed2558f4173..af085f30d9b 100644 --- a/core/gethwrappers/abigen.go +++ b/core/gethwrappers/abigen.go @@ -147,11 +147,10 @@ func getContractName(fileNode *ast.File) string { if len(n.Name) < 3 { return true } - if n.Name[len(n.Name)-3:] == "ABI" { - contractName = n.Name[:len(n.Name)-3] - } else { + if n.Name[len(n.Name)-3:] != "ABI" { return true } + contractName = n.Name[:len(n.Name)-3] } } return false diff --git a/core/gethwrappers/go_generate_test.go b/core/gethwrappers/go_generate_test.go index e0779c306c4..52d0f520dd7 100644 --- a/core/gethwrappers/go_generate_test.go +++ b/core/gethwrappers/go_generate_test.go @@ -138,11 +138,10 @@ func getProjectRoot(t *testing.T) (rootPath string) { root, err := os.Getwd() require.NoError(t, err, "could not get current working directory") for root != "/" { // Walk up path to find dir containing go.mod - if _, err := os.Stat(filepath.Join(root, "go.mod")); os.IsNotExist(err) { - root = filepath.Dir(root) - } else { + if _, err := os.Stat(filepath.Join(root, "go.mod")); !os.IsNotExist(err) { return root } + root = filepath.Dir(root) } t.Fatal("could not find project root") return diff --git a/core/gethwrappers/utils.go b/core/gethwrappers/utils.go index c9b61c9441a..277ebf8aaae 100644 --- a/core/gethwrappers/utils.go +++ b/core/gethwrappers/utils.go @@ -44,11 +44,10 @@ func GetProjectRoot() (rootPath string) { err) } for root != "/" { // Walk up path to find dir containing go.mod - if _, err := os.Stat(filepath.Join(root, "go.mod")); os.IsNotExist(err) { - root = filepath.Dir(root) - } else { + if _, err := os.Stat(filepath.Join(root, "go.mod")); !os.IsNotExist(err) { return root } + root = filepath.Dir(root) } Exit("could not find project root", nil) panic("can't get here") diff --git a/core/scripts/chaincli/handler/keeper_verifiable_load.go b/core/scripts/chaincli/handler/keeper_verifiable_load.go index aa62d820101..ee763e54f79 100644 --- a/core/scripts/chaincli/handler/keeper_verifiable_load.go +++ b/core/scripts/chaincli/handler/keeper_verifiable_load.go @@ -203,12 +203,11 @@ func (k *Keeper) fetchBucketData(v verifiableLoad, opts *bind.CallOpts, id *big. var err error for i := 0; i < retryNum; i++ { bucketDelays, err = v.GetBucketedDelays(opts, id, bucketNum) - if err != nil { - log.Printf("failed to get bucketed delays for upkeep id %s bucket %d: %v, retrying...", id.String(), bucketNum, err) - time.Sleep(retryDelay) - } else { + if err == nil { break } + log.Printf("failed to get bucketed delays for upkeep id %s bucket %d: %v, retrying...", id.String(), bucketNum, err) + time.Sleep(retryDelay) } var floatBucketDelays []float64 diff --git a/core/scripts/common/polygonedge.go b/core/scripts/common/polygonedge.go index e3cc7a52ad3..c91d76cce87 100644 --- a/core/scripts/common/polygonedge.go +++ b/core/scripts/common/polygonedge.go @@ -149,11 +149,10 @@ func GetIbftExtraClean(extra []byte) (cleanedExtra []byte, err error) { hexExtra := hex.EncodeToString(extra) prefix := "" for _, s := range hexExtra { - if s == '0' { - prefix = prefix + "0" - } else { + if s != '0' { break } + prefix = prefix + "0" } hexExtra = strings.TrimLeft(hexExtra, "0") diff --git a/core/services/ocr2/delegate.go b/core/services/ocr2/delegate.go index 870dfb6463c..c185ec6ddbe 100644 --- a/core/services/ocr2/delegate.go +++ b/core/services/ocr2/delegate.go @@ -491,12 +491,11 @@ func GetEVMEffectiveTransmitterID(jb *job.Job, chain legacyevm.Chain, lggr logge effectiveTransmitterID, err := chain.TxManager().GetForwarderForEOA(common.HexToAddress(spec.TransmitterID.String)) if err == nil { return effectiveTransmitterID.String(), nil - } else if spec.TransmitterID.Valid { - lggr.Warnw("Skipping forwarding for job, will fallback to default behavior", "job", jb.Name, "err", err) - // this shouldn't happen unless behaviour above was changed - } else { + } else if !spec.TransmitterID.Valid { return "", errors.New("failed to get forwarder address and transmitterID is not set") } + lggr.Warnw("Skipping forwarding for job, will fallback to default behavior", "job", jb.Name, "err", err) + // this shouldn't happen unless behaviour above was changed } return spec.TransmitterID.String, nil diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/payload_builder.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/payload_builder.go index 4854f517c46..7f29cb3b7ac 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/payload_builder.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/payload_builder.go @@ -33,27 +33,26 @@ func (b *payloadBuilder) BuildPayloads(ctx context.Context, proposals ...ocr2kee for i, proposal := range proposals { var payload ocr2keepers.UpkeepPayload - if b.upkeepList.IsActive(proposal.UpkeepID.BigInt()) { - b.lggr.Debugf("building payload for coordinated block proposal %+v", proposal) - var checkData []byte - var err error - switch core.GetUpkeepType(proposal.UpkeepID) { - case types.LogTrigger: - checkData, err = b.recoverer.GetProposalData(ctx, proposal) - if err != nil { - b.lggr.Warnw("failed to get log proposal data", "err", err, "upkeepID", proposal.UpkeepID, "trigger", proposal.Trigger) - continue - } - case types.ConditionTrigger: - // Empty checkData for conditionals - } - payload, err = core.NewUpkeepPayload(proposal.UpkeepID.BigInt(), proposal.Trigger, checkData) + if !b.upkeepList.IsActive(proposal.UpkeepID.BigInt()) { + b.lggr.Warnw("upkeep is not active, skipping", "upkeepID", proposal.UpkeepID) + continue + } + b.lggr.Debugf("building payload for coordinated block proposal %+v", proposal) + var checkData []byte + var err error + switch core.GetUpkeepType(proposal.UpkeepID) { + case types.LogTrigger: + checkData, err = b.recoverer.GetProposalData(ctx, proposal) if err != nil { - b.lggr.Warnw("error building upkeep payload", "err", err, "upkeepID", proposal.UpkeepID) + b.lggr.Warnw("failed to get log proposal data", "err", err, "upkeepID", proposal.UpkeepID, "trigger", proposal.Trigger) continue } - } else { - b.lggr.Warnw("upkeep is not active, skipping", "upkeepID", proposal.UpkeepID) + case types.ConditionTrigger: + // Empty checkData for conditionals + } + payload, err = core.NewUpkeepPayload(proposal.UpkeepID.BigInt(), proposal.Trigger, checkData) + if err != nil { + b.lggr.Warnw("error building upkeep payload", "err", err, "upkeepID", proposal.UpkeepID) continue } diff --git a/core/services/ocr2/plugins/ocr2vrf/coordinator/coordinator.go b/core/services/ocr2/plugins/ocr2vrf/coordinator/coordinator.go index 88d6544d8c4..803ed3450be 100644 --- a/core/services/ocr2/plugins/ocr2vrf/coordinator/coordinator.go +++ b/core/services/ocr2/plugins/ocr2vrf/coordinator/coordinator.go @@ -440,18 +440,17 @@ func (c *coordinator) ReportBlocks( // Fill blocks slice with valid requested blocks. blocks = []ocr2vrftypes.Block{} for block := range blocksRequested { - if c.coordinatorConfig.BatchGasLimit-currentBatchGasLimit >= c.coordinatorConfig.BlockGasOverhead { - _, redeemRandomnessRequested := redeemRandomnessBlocksRequested[block] - blocks = append(blocks, ocr2vrftypes.Block{ - Hash: blockhashesMapping[block.blockNumber], - Height: block.blockNumber, - ConfirmationDelay: block.confDelay, - ShouldStore: redeemRandomnessRequested, - }) - currentBatchGasLimit += c.coordinatorConfig.BlockGasOverhead - } else { + if c.coordinatorConfig.BatchGasLimit-currentBatchGasLimit < c.coordinatorConfig.BlockGasOverhead { break } + _, redeemRandomnessRequested := redeemRandomnessBlocksRequested[block] + blocks = append(blocks, ocr2vrftypes.Block{ + Hash: blockhashesMapping[block.blockNumber], + Height: block.blockNumber, + ConfirmationDelay: block.confDelay, + ShouldStore: redeemRandomnessRequested, + }) + currentBatchGasLimit += c.coordinatorConfig.BlockGasOverhead } c.lggr.Tracew("got elligible blocks", "blocks", blocks) diff --git a/core/services/pipeline/common.go b/core/services/pipeline/common.go index 1c8703e2eb1..da0e0d3c00b 100644 --- a/core/services/pipeline/common.go +++ b/core/services/pipeline/common.go @@ -673,11 +673,10 @@ func getJsonNumberValue(value json.Number) (interface{}, error) { } } else { f, err := value.Float64() - if err == nil { - result = f - } else { + if err != nil { return nil, pkgerrors.Errorf("failed to parse json.Value: %v", err) } + result = f } return result, nil diff --git a/core/services/pipeline/runner.go b/core/services/pipeline/runner.go index a432d9fec11..30a35598c3e 100644 --- a/core/services/pipeline/runner.go +++ b/core/services/pipeline/runner.go @@ -546,11 +546,10 @@ func (r *runner) Run(ctx context.Context, run *Run, l logger.Logger, saveSuccess // retain old UUID values for _, taskRun := range run.PipelineTaskRuns { task := pipeline.ByDotID(taskRun.DotID) - if task != nil && task.Base() != nil { - task.Base().uuid = taskRun.ID - } else { + if task == nil || task.Base() == nil { return false, pkgerrors.Errorf("failed to match a pipeline task for dot ID: %v", taskRun.DotID) } + task.Base().uuid = taskRun.ID } preinsert := pipeline.RequiresPreInsert() diff --git a/core/services/pipeline/task_params.go b/core/services/pipeline/task_params.go index 72d0d619429..61d3b8650ad 100644 --- a/core/services/pipeline/task_params.go +++ b/core/services/pipeline/task_params.go @@ -708,11 +708,11 @@ func (p *JSONPathParam) UnmarshalPipelineParam(val interface{}) error { ssp = v case []interface{}: for _, x := range v { - if as, is := x.(string); is { - ssp = append(ssp, as) - } else { + as, is := x.(string) + if !is { return ErrBadInput } + ssp = append(ssp, as) } case string: if len(v) == 0 { diff --git a/core/services/relay/evm/functions/contract_transmitter.go b/core/services/relay/evm/functions/contract_transmitter.go index 2a62db31a8c..78a5ff39bb7 100644 --- a/core/services/relay/evm/functions/contract_transmitter.go +++ b/core/services/relay/evm/functions/contract_transmitter.go @@ -125,7 +125,8 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. } var destinationContract common.Address - if oc.contractVersion == 1 { + switch oc.contractVersion { + case 1: oc.lggr.Debugw("FunctionsContractTransmitter: start", "reportLenBytes", len(report)) requests, err2 := oc.reportCodec.DecodeReport(report) if err2 != nil { @@ -152,7 +153,7 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. } } oc.lggr.Debugw("FunctionsContractTransmitter: ready", "nRequests", len(requests), "coordinatorContract", destinationContract.Hex()) - } else { + default: return fmt.Errorf("unsupported contract version: %d", oc.contractVersion) } payload, err := oc.contractABI.Pack("transmit", rawReportCtx, []byte(report), rs, ss, vs) diff --git a/core/services/relay/evm/functions/logpoller_wrapper.go b/core/services/relay/evm/functions/logpoller_wrapper.go index 7897e86310e..f11b6bee1e0 100644 --- a/core/services/relay/evm/functions/logpoller_wrapper.go +++ b/core/services/relay/evm/functions/logpoller_wrapper.go @@ -304,12 +304,11 @@ func (l *logPollerWrapper) filterPreviouslyDetectedEvents(logs []logpoller.Log, expiredRequests := 0 for _, detectedEvent := range detectedEvents.detectedEventsOrdered { expirationTime := time.Now().Add(-time.Second * time.Duration(l.logPollerCacheDurationSec)) - if detectedEvent.timeDetected.Before(expirationTime) { - delete(detectedEvents.isPreviouslyDetected, detectedEvent.requestId) - expiredRequests++ - } else { + if !detectedEvent.timeDetected.Before(expirationTime) { break } + delete(detectedEvents.isPreviouslyDetected, detectedEvent.requestId) + expiredRequests++ } detectedEvents.detectedEventsOrdered = detectedEvents.detectedEventsOrdered[expiredRequests:] l.lggr.Debugw("filterPreviouslyDetectedEvents: done", "filterType", filterType, "nLogs", len(logs), "nFilteredLogs", len(filteredLogs), "nExpiredRequests", expiredRequests, "previouslyDetectedCacheSize", len(detectedEvents.detectedEventsOrdered)) diff --git a/core/services/relay/evm/mercury/wsrpc/client.go b/core/services/relay/evm/mercury/wsrpc/client.go index c9533717757..d420a17a1a4 100644 --- a/core/services/relay/evm/mercury/wsrpc/client.go +++ b/core/services/relay/evm/mercury/wsrpc/client.go @@ -193,16 +193,16 @@ func (w *client) resetTransport() { b := utils.NewRedialBackoff() for { // Will block until successful dial, or context is canceled (i.e. on close) - if err := w.dial(ctx, wsrpc.WithBlock()); err != nil { - if ctx.Err() != nil { - w.logger.Debugw("ResetTransport exiting due to client Close", "err", err) - return - } - w.logger.Errorw("ResetTransport failed to redial", "err", err) - time.Sleep(b.Duration()) - } else { + err := w.dial(ctx, wsrpc.WithBlock()) + if err == nil { break } + if ctx.Err() != nil { + w.logger.Debugw("ResetTransport exiting due to client Close", "err", err) + return + } + w.logger.Errorw("ResetTransport failed to redial", "err", err) + time.Sleep(b.Duration()) } w.logger.Info("ResetTransport successfully redialled") } diff --git a/core/services/vrf/v2/listener_v2_log_processor.go b/core/services/vrf/v2/listener_v2_log_processor.go index eebe9038c0c..be9457d7cee 100644 --- a/core/services/vrf/v2/listener_v2_log_processor.go +++ b/core/services/vrf/v2/listener_v2_log_processor.go @@ -155,22 +155,21 @@ func (lsn *listenerV2) processPendingVRFRequests(ctx context.Context, pendingReq Context: ctx}, sID) if err != nil { - if strings.Contains(err.Error(), "execution reverted") { - // "execution reverted" indicates that the subscription no longer exists. - // We can no longer just mark these as processed and continue, - // since it could be that the subscription was canceled while there - // were still unfulfilled requests. - // The simplest approach to handle this is to enter the processRequestsPerSub - // loop rather than create a bunch of largely duplicated code - // to handle this specific situation, since we need to run the pipeline to get - // the VRF proof, abi-encode it, etc. - l.Warnw("Subscription not found - setting start balance to zero", "subID", subID, "err", err) - startLinkBalance = big.NewInt(0) - } else { + if !strings.Contains(err.Error(), "execution reverted") { // Most likely this is an RPC error, so we re-try later. l.Errorw("Unable to read subscription balance", "err", err) return } + // "execution reverted" indicates that the subscription no longer exists. + // We can no longer just mark these as processed and continue, + // since it could be that the subscription was canceled while there + // were still unfulfilled requests. + // The simplest approach to handle this is to enter the processRequestsPerSub + // loop rather than create a bunch of largely duplicated code + // to handle this specific situation, since we need to run the pipeline to get + // the VRF proof, abi-encode it, etc. + l.Warnw("Subscription not found - setting start balance to zero", "subID", subID, "err", err) + startLinkBalance = big.NewInt(0) } else { // Happy path - sub is active. startLinkBalance = sub.Balance() diff --git a/core/sessions/ldapauth/ldap.go b/core/sessions/ldapauth/ldap.go index 147f8bd2aed..fc0e76bb5c1 100644 --- a/core/sessions/ldapauth/ldap.go +++ b/core/sessions/ldapauth/ldap.go @@ -124,17 +124,15 @@ func (l *ldapAuthenticator) FindUser(email string) (sessions.User, error) { sql := "SELECT * FROM users WHERE lower(email) = lower($1)" return tx.Get(&foundLocalAdminUser, sql, email) }) - if checkErr != nil { - // If error is not nil, there was either an issue or no local users found - if !errors.Is(checkErr, sql.ErrNoRows) { - // If the error is not that no local user was found, log and exit - l.lggr.Errorf("error searching users table: %v", checkErr) - return sessions.User{}, errors.New("error Finding user") - } - } else { - // Error was nil, local user found. Return + if checkErr == nil { return foundLocalAdminUser, nil } + // If error is not nil, there was either an issue or no local users found + if !errors.Is(checkErr, sql.ErrNoRows) { + // If the error is not that no local user was found, log and exit + l.lggr.Errorf("error searching users table: %v", checkErr) + return sessions.User{}, errors.New("error Finding user") + } // First query for user "is active" property if defined usersActive, err := l.validateUsersActive([]string{email}) diff --git a/core/web/cosmos_transfer_controller.go b/core/web/cosmos_transfer_controller.go index 965f694fc1b..9b958346642 100644 --- a/core/web/cosmos_transfer_controller.go +++ b/core/web/cosmos_transfer_controller.go @@ -60,12 +60,12 @@ func (tc *CosmosTransfersController) Create(c *gin.Context) { } var gasToken string cfgs := tc.App.GetConfig().CosmosConfigs() - if i := slices.IndexFunc(cfgs, func(config *coscfg.TOMLConfig) bool { return *config.ChainID == tr.CosmosChainID }); i != -1 { - gasToken = cfgs[i].GasToken() - } else { + i := slices.IndexFunc(cfgs, func(config *coscfg.TOMLConfig) bool { return *config.ChainID == tr.CosmosChainID }) + if i == -1 { jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("no config for chain id: %s", tr.CosmosChainID)) return } + gasToken = cfgs[i].GasToken() //TODO move this inside? coin, err := denom.ConvertDecCoinToDenom(sdk.NewDecCoinFromDec(tr.Token, tr.Amount), gasToken)