diff --git a/common/client/multi_node.go b/common/client/multi_node.go index b946fb8fc2a..341586d9f0f 100644 --- a/common/client/multi_node.go +++ b/common/client/multi_node.go @@ -2,6 +2,7 @@ package client import ( "context" + "errors" "fmt" "math/big" "sync" @@ -22,7 +23,7 @@ var ( Name: "multi_node_states", Help: "The number of RPC nodes currently in the given state for the given chain", }, []string{"network", "chainId", "state"}) - ErroringNodeError = fmt.Errorf("no live nodes available") + ErroringNodeError = errors.New("no live nodes available") ) // MultiNode is a generalized multi node client interface that includes methods to interact with different chains. diff --git a/common/client/node.go b/common/client/node.go index 66161ac5d5f..859f42a96f0 100644 --- a/common/client/node.go +++ b/common/client/node.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net/url" + "strings" "sync" "time" @@ -162,14 +163,20 @@ func NewNode[ } func (n *node[CHAIN_ID, HEAD, RPC]) String() string { - s := fmt.Sprintf("(%s)%s", Primary.String(), n.name) + var s strings.Builder + s.WriteByte('(') + s.WriteString(Primary.String()) + s.WriteByte(')') + s.WriteString(n.name) if n.ws != nil { - s = s + fmt.Sprintf(":%s", n.ws.String()) + s.WriteByte(':') + s.WriteString(n.ws.String()) } if n.http != nil { - s = s + fmt.Sprintf(":%s", n.http.String()) + s.WriteByte(':') + s.WriteString(n.http.String()) } - return s + return s.String() } func (n *node[CHAIN_ID, HEAD, RPC]) ConfiguredChainID() (chainID CHAIN_ID) { diff --git a/common/client/node_fsm_test.go b/common/client/node_fsm_test.go index 93460d934a3..3d044978530 100644 --- a/common/client/node_fsm_test.go +++ b/common/client/node_fsm_test.go @@ -21,7 +21,7 @@ func (fm *fnMock) AssertNotCalled(t *testing.T) { } func (fm *fnMock) AssertCalled(t *testing.T) { - assert.Greater(t, fm.calls, 0) + assert.Positive(t, fm.calls) } func TestUnit_Node_StateTransitions(t *testing.T) { diff --git a/common/client/node_lifecycle_test.go b/common/client/node_lifecycle_test.go index 39c39e318ef..5a0a68acc47 100644 --- a/common/client/node_lifecycle_test.go +++ b/common/client/node_lifecycle_test.go @@ -1593,7 +1593,7 @@ func TestUnit_NodeLifecycle_outOfSyncWithPool(t *testing.T) { t.Run("skip if nLiveNodes is not configured", func(t *testing.T) { node := newTestNode(t, testNodeOpts{}) outOfSync, liveNodes := node.isOutOfSyncWithPool() - assert.Equal(t, false, outOfSync) + assert.False(t, outOfSync) assert.Equal(t, 0, liveNodes) }) t.Run("skip if syncThreshold is not configured", func(t *testing.T) { @@ -1601,7 +1601,7 @@ func TestUnit_NodeLifecycle_outOfSyncWithPool(t *testing.T) { poolInfo := newMockPoolChainInfoProvider(t) node.SetPoolChainInfoProvider(poolInfo) outOfSync, liveNodes := node.isOutOfSyncWithPool() - assert.Equal(t, false, outOfSync) + assert.False(t, outOfSync) assert.Equal(t, 0, liveNodes) }) t.Run("panics on invalid selection mode", func(t *testing.T) { diff --git a/common/client/node_selector.go b/common/client/node_selector.go index 372b521bb1c..8f0932743d6 100644 --- a/common/client/node_selector.go +++ b/common/client/node_selector.go @@ -1,8 +1,6 @@ package client import ( - "fmt" - "github.com/smartcontractkit/chainlink/v2/common/types" ) @@ -38,6 +36,6 @@ func newNodeSelector[ case NodeSelectionModePriorityLevel: return NewPriorityLevelNodeSelector[CHAIN_ID, RPC](nodes) default: - panic(fmt.Sprintf("unsupported NodeSelectionMode: %s", selectionMode)) + panic("unsupported NodeSelectionMode: " + selectionMode) } } diff --git a/common/client/node_selector_highest_head_test.go b/common/client/node_selector_highest_head_test.go index 9d85c688e05..0acf2b1f309 100644 --- a/common/client/node_selector_highest_head_test.go +++ b/common/client/node_selector_highest_head_test.go @@ -10,7 +10,7 @@ import ( func TestHighestHeadNodeSelectorName(t *testing.T) { selector := newNodeSelector[types.ID, RPCClient[types.ID, Head]](NodeSelectionModeHighestHead, nil) - assert.Equal(t, selector.Name(), NodeSelectionModeHighestHead) + assert.Equal(t, NodeSelectionModeHighestHead, selector.Name()) } func TestHighestHeadNodeSelector(t *testing.T) { diff --git a/common/client/node_selector_priority_level_test.go b/common/client/node_selector_priority_level_test.go index 67aac97be1b..6f337f13f12 100644 --- a/common/client/node_selector_priority_level_test.go +++ b/common/client/node_selector_priority_level_test.go @@ -10,7 +10,7 @@ import ( func TestPriorityLevelNodeSelectorName(t *testing.T) { selector := newNodeSelector[types.ID, RPCClient[types.ID, Head]](NodeSelectionModePriorityLevel, nil) - assert.Equal(t, selector.Name(), NodeSelectionModePriorityLevel) + assert.Equal(t, NodeSelectionModePriorityLevel, selector.Name()) } func TestPriorityLevelNodeSelector(t *testing.T) { diff --git a/common/client/node_selector_round_robin_test.go b/common/client/node_selector_round_robin_test.go index 189b58da9ea..01830f627a2 100644 --- a/common/client/node_selector_round_robin_test.go +++ b/common/client/node_selector_round_robin_test.go @@ -10,7 +10,7 @@ import ( func TestRoundRobinNodeSelectorName(t *testing.T) { selector := newNodeSelector[types.ID, RPCClient[types.ID, Head]](NodeSelectionModeRoundRobin, nil) - assert.Equal(t, selector.Name(), NodeSelectionModeRoundRobin) + assert.Equal(t, NodeSelectionModeRoundRobin, selector.Name()) } func TestRoundRobinNodeSelector(t *testing.T) { diff --git a/common/client/node_selector_total_difficulty_test.go b/common/client/node_selector_total_difficulty_test.go index 7cd5867ddca..36f806f4253 100644 --- a/common/client/node_selector_total_difficulty_test.go +++ b/common/client/node_selector_total_difficulty_test.go @@ -11,7 +11,7 @@ import ( func TestTotalDifficultyNodeSelectorName(t *testing.T) { selector := newNodeSelector[types.ID, RPCClient[types.ID, Head]](NodeSelectionModeTotalDifficulty, nil) - assert.Equal(t, selector.Name(), NodeSelectionModeTotalDifficulty) + assert.Equal(t, NodeSelectionModeTotalDifficulty, selector.Name()) } func TestTotalDifficultyNodeSelector(t *testing.T) { diff --git a/common/client/poller_test.go b/common/client/poller_test.go index 930b101751c..e2444d099fb 100644 --- a/common/client/poller_test.go +++ b/common/client/poller_test.go @@ -189,6 +189,6 @@ func Test_Poller_Unsubscribe(t *testing.T) { require.NoError(t, err) poller.Unsubscribe() - require.Equal(t, <-channel, nil) + require.Nil(t, <-channel) }) } diff --git a/common/headtracker/head_tracker.go b/common/headtracker/head_tracker.go index d309ced0cda..e82386281e2 100644 --- a/common/headtracker/head_tracker.go +++ b/common/headtracker/head_tracker.go @@ -150,7 +150,7 @@ func (ht *headTracker[HTH, S, ID, BLOCK_HASH]) handleInitialHead(ctx context.Con } if !latestFinalized.IsValid() { - return fmt.Errorf("latest finalized block is not valid") + return errors.New("latest finalized block is not valid") } latestChain, err := ht.headSaver.Load(ctx, latestFinalized.BlockNumber()) @@ -231,7 +231,7 @@ func (ht *headTracker[HTH, S, ID, BLOCK_HASH]) handleNewHead(ctx context.Context headWithChain := ht.headSaver.Chain(head.BlockHash()) if !headWithChain.IsValid() { - return fmt.Errorf("HeadTracker#handleNewHighestHead headWithChain was unexpectedly nil") + return errors.New("HeadTracker#handleNewHighestHead headWithChain was unexpectedly nil") } ht.backfillMB.Deliver(headWithChain) ht.broadcastMB.Deliver(headWithChain) @@ -327,7 +327,7 @@ func (ht *headTracker[HTH, S, ID, BLOCK_HASH]) LatestAndFinalizedBlock(ctx conte } if !latest.IsValid() { - err = fmt.Errorf("expected latest block to be valid") + err = errors.New("expected latest block to be valid") return } @@ -337,7 +337,7 @@ func (ht *headTracker[HTH, S, ID, BLOCK_HASH]) LatestAndFinalizedBlock(ctx conte return } if !finalized.IsValid() { - err = fmt.Errorf("expected finalized block to be valid") + err = errors.New("expected finalized block to be valid") return } @@ -373,7 +373,7 @@ func (ht *headTracker[HTH, S, ID, BLOCK_HASH]) calculateLatestFinalized(ctx cont } if !latestFinalized.IsValid() { - return latestFinalized, fmt.Errorf("failed to get valid latest finalized block") + return latestFinalized, errors.New("failed to get valid latest finalized block") } if ht.config.FinalizedBlockOffset() == 0 { diff --git a/common/txmgr/reaper.go b/common/txmgr/reaper.go index 0c797548b16..5a83742aa00 100644 --- a/common/txmgr/reaper.go +++ b/common/txmgr/reaper.go @@ -104,7 +104,7 @@ func (r *Reaper[CHAIN_ID]) ReapTxes(headNum int64) error { mark := time.Now() timeThreshold := mark.Add(-threshold) - r.log.Debugw(fmt.Sprintf("reaping old txes created before %s", timeThreshold.Format(time.RFC3339)), "ageThreshold", threshold, "timeThreshold", timeThreshold) + r.log.Debugw("reaping old txes created before "+timeThreshold.Format(time.RFC3339), "ageThreshold", threshold, "timeThreshold", timeThreshold) if err := r.store.ReapTxHistory(ctx, timeThreshold, r.chainID); err != nil { return err diff --git a/common/txmgr/txmgr.go b/common/txmgr/txmgr.go index 3776f62254c..358812db9ca 100644 --- a/common/txmgr/txmgr.go +++ b/common/txmgr/txmgr.go @@ -566,7 +566,7 @@ func (b *Txm[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) CreateTran // Calls forwarderMgr to get a proper forwarder for a given EOA. func (b *Txm[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) GetForwarderForEOA(ctx context.Context, eoa ADDR) (forwarder ADDR, err error) { if !b.txConfig.ForwardersEnabled() { - return forwarder, fmt.Errorf("forwarding is not enabled, to enable set Transactions.ForwardersEnabled =true") + return forwarder, errors.New("forwarding is not enabled, to enable set Transactions.ForwardersEnabled =true") } forwarder, err = b.fwdMgr.ForwarderFor(ctx, eoa) return @@ -575,7 +575,7 @@ func (b *Txm[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) GetForward // GetForwarderForEOAOCR2Feeds calls forwarderMgr to get a proper forwarder for a given EOA and checks if its set as a transmitter on the OCR2Aggregator contract. func (b *Txm[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) GetForwarderForEOAOCR2Feeds(ctx context.Context, eoa, ocr2Aggregator ADDR) (forwarder ADDR, err error) { if !b.txConfig.ForwardersEnabled() { - return forwarder, fmt.Errorf("forwarding is not enabled, to enable set Transactions.ForwardersEnabled =true") + return forwarder, errors.New("forwarding is not enabled, to enable set Transactions.ForwardersEnabled =true") } forwarder, err = b.fwdMgr.ForwarderForOCR2Feeds(ctx, eoa, ocr2Aggregator) return diff --git a/common/txmgr/types/tx.go b/common/txmgr/types/tx.go index b0bc2ca7025..f6d569e3182 100644 --- a/common/txmgr/types/tx.go +++ b/common/txmgr/types/tx.go @@ -7,6 +7,7 @@ import ( "fmt" "math/big" "slices" + "strconv" "strings" "time" @@ -247,7 +248,7 @@ func (e *Tx[CHAIN_ID, ADDR, TX_HASH, BLOCK_HASH, SEQ, FEE]) GetError() error { // GetID allows Tx to be used as jsonapi.MarshalIdentifier func (e *Tx[CHAIN_ID, ADDR, TX_HASH, BLOCK_HASH, SEQ, FEE]) GetID() string { - return fmt.Sprintf("%d", e.ID) + return strconv.FormatInt(e.ID, 10) } // GetMeta returns an Tx's meta in struct form, unmarshalling it from JSON first. diff --git a/core/bridges/cache_test.go b/core/bridges/cache_test.go index 832a7d5540a..4e88631f910 100644 --- a/core/bridges/cache_test.go +++ b/core/bridges/cache_test.go @@ -111,7 +111,7 @@ func TestBridgeCache_Type(t *testing.T) { btp.Confirmations = req.Confirmations }) require.NoError(t, cache.UpdateBridgeType(ctx, expected, btr)) - assert.Equal(t, btr.Confirmations, expected.Confirmations) + assert.Equal(t, expected.Confirmations, btr.Confirmations) result, err = cache.FindBridge(ctx, bridge) @@ -124,7 +124,7 @@ func TestBridgeCache_Type(t *testing.T) { // bridge type is removed from cache so call to find fallsback to the data store mORM.On("FindBridge", mock.Anything, bridge).Return(bridges.BridgeType{}, errors.New("not found")) _, err = cache.FindBridge(ctx, bridge) - require.NotNil(t, err) + require.Error(t, err) }) } diff --git a/core/bridges/orm_test.go b/core/bridges/orm_test.go index b85b6be00dd..2c9afbcd593 100644 --- a/core/bridges/orm_test.go +++ b/core/bridges/orm_test.go @@ -47,11 +47,11 @@ func TestORM_FindBridges(t *testing.T) { assert.NoError(t, orm.CreateBridgeType(ctx, &bt2)) bts, err := orm.FindBridges(ctx, []bridges.BridgeName{"bridge2", "bridge1"}) require.NoError(t, err) - require.Equal(t, 2, len(bts)) + require.Len(t, bts, 2) bts, err = orm.FindBridges(ctx, []bridges.BridgeName{"bridge1"}) require.NoError(t, err) - require.Equal(t, 1, len(bts)) + require.Len(t, bts, 1) require.Equal(t, "bridge1", bts[0].Name.String()) // One invalid bridge errors @@ -134,7 +134,7 @@ func TestORM_UpdateBridgeType(t *testing.T) { bs, count, err = orm.BridgeTypes(ctx, 0, 10) require.NoError(t, err) require.Equal(t, 0, count) - require.Len(t, bs, 0) + require.Empty(t, bs) } func TestORM_TestCachedResponse(t *testing.T) { diff --git a/core/capabilities/ccip/ccipevm/commitcodec.go b/core/capabilities/ccip/ccipevm/commitcodec.go index 31501ea96c4..e7f15664cc9 100644 --- a/core/capabilities/ccip/ccipevm/commitcodec.go +++ b/core/capabilities/ccip/ccipevm/commitcodec.go @@ -2,6 +2,7 @@ package ccipevm import ( "context" + "errors" "fmt" "math/big" @@ -96,7 +97,7 @@ func (c *CommitPluginCodecV1) Encode(ctx context.Context, report cciptypes.Commi func (c *CommitPluginCodecV1) Decode(ctx context.Context, bytes []byte) (cciptypes.CommitPluginReport, error) { method, ok := ccipEncodingUtilsABI.Methods["exposeCommitReport"] if !ok { - return cciptypes.CommitPluginReport{}, fmt.Errorf("missing method exposeCommitReport") + return cciptypes.CommitPluginReport{}, errors.New("missing method exposeCommitReport") } unpacked, err := method.Inputs.Unpack(bytes) diff --git a/core/capabilities/ccip/ccipevm/executecodec.go b/core/capabilities/ccip/ccipevm/executecodec.go index 6e32e422b07..11d6ef2c463 100644 --- a/core/capabilities/ccip/ccipevm/executecodec.go +++ b/core/capabilities/ccip/ccipevm/executecodec.go @@ -2,6 +2,7 @@ package ccipevm import ( "context" + "errors" "fmt" "strings" @@ -23,7 +24,7 @@ type ExecutePluginCodecV1 struct { func NewExecutePluginCodecV1() *ExecutePluginCodecV1 { abiParsed, err := abi.JSON(strings.NewReader(offramp.OffRampABI)) if err != nil { - panic(fmt.Errorf("parse multi offramp abi: %s", err)) + panic(fmt.Errorf("parse multi offramp abi: %w", err)) } methodInputs := abihelpers.MustGetMethodInputs("manuallyExecute", abiParsed) if len(methodInputs) == 0 { @@ -40,7 +41,7 @@ func (e *ExecutePluginCodecV1) Encode(ctx context.Context, report cciptypes.Exec for _, chainReport := range report.ChainReports { if chainReport.ProofFlagBits.IsEmpty() { - return nil, fmt.Errorf("proof flag bits are empty") + return nil, errors.New("proof flag bits are empty") } evmProofs := make([][32]byte, 0, len(chainReport.Proofs)) @@ -112,7 +113,7 @@ func (e *ExecutePluginCodecV1) Decode(ctx context.Context, encodedReport []byte) return cciptypes.ExecutePluginReport{}, fmt.Errorf("unpack encoded report: %w", err) } if len(unpacked) != 1 { - return cciptypes.ExecutePluginReport{}, fmt.Errorf("unpacked report is empty") + return cciptypes.ExecutePluginReport{}, errors.New("unpacked report is empty") } evmReportRaw := abi.ConvertType(unpacked[0], new([]offramp.InternalExecutionReport)) @@ -121,7 +122,7 @@ func (e *ExecutePluginCodecV1) Decode(ctx context.Context, encodedReport []byte) return cciptypes.ExecutePluginReport{}, fmt.Errorf("got an unexpected report type %T", unpacked[0]) } if evmReportPtr == nil { - return cciptypes.ExecutePluginReport{}, fmt.Errorf("evm report is nil") + return cciptypes.ExecutePluginReport{}, errors.New("evm report is nil") } evmReport := *evmReportPtr diff --git a/core/capabilities/ccip/ccipevm/msghasher_test.go b/core/capabilities/ccip/ccipevm/msghasher_test.go index dc0aa3a4b0e..ccc1515f121 100644 --- a/core/capabilities/ccip/ccipevm/msghasher_test.go +++ b/core/capabilities/ccip/ccipevm/msghasher_test.go @@ -3,6 +3,7 @@ package ccipevm import ( "context" cryptorand "crypto/rand" + "encoding/hex" "fmt" "math/big" "math/rand" @@ -81,7 +82,7 @@ func testHasherEVM2EVM(ctx context.Context, t *testing.T, d *testSetupData, evmE actualHash, err := evmMsgHasher.Hash(ctx, ccipMsg) require.NoError(t, err) - require.Equal(t, fmt.Sprintf("%x", expectedHash), strings.TrimPrefix(actualHash.String(), "0x")) + require.Equal(t, hex.EncodeToString(expectedHash[:]), strings.TrimPrefix(actualHash.String(), "0x")) } type evmExtraArgs struct { diff --git a/core/capabilities/ccip/ccipevm/rmncrypto.go b/core/capabilities/ccip/ccipevm/rmncrypto.go index 37b909dabe2..49ce2a71609 100644 --- a/core/capabilities/ccip/ccipevm/rmncrypto.go +++ b/core/capabilities/ccip/ccipevm/rmncrypto.go @@ -35,12 +35,12 @@ func init() { encodingUtilsABI, err = abi.JSON(strings.NewReader(encodingUtilsAbiRaw)) if err != nil { - panic(fmt.Errorf("failed to parse encoding utils ABI: %v", err)) + panic(fmt.Errorf("failed to parse encoding utils ABI: %w", err)) } addressEncodeABI, err = abi.JSON(strings.NewReader(addressEncodeAbiRaw)) if err != nil { - panic(fmt.Errorf("failed to parse address encode ABI: %v", err)) + panic(fmt.Errorf("failed to parse address encode ABI: %w", err)) } } @@ -88,10 +88,10 @@ func (r *EVMRMNCrypto) VerifyReportSignatures( signerAddresses []cciptypes.UnknownAddress, ) error { if sigs == nil { - return fmt.Errorf("no signatures provided") + return errors.New("no signatures provided") } if report.LaneUpdates == nil { - return fmt.Errorf("no lane updates provided") + return errors.New("no lane updates provided") } r.lggr.Debugw("Verifying RMN report signatures", @@ -149,7 +149,7 @@ func (r *EVMRMNCrypto) VerifyReportSignatures( // make sure that signers are ordered correctly (ASC addresses). if bytes.Compare(prevSignerAddr.Bytes(), recoveredAddress.Bytes()) == 1 { - return fmt.Errorf("signers are not ordered correctly") + return errors.New("signers are not ordered correctly") } prevSignerAddr = recoveredAddress @@ -166,7 +166,7 @@ func (r *EVMRMNCrypto) VerifyReportSignatures( } } if !found { - return fmt.Errorf("the recovered public key does not match any signer address, verification failed") + return errors.New("the recovered public key does not match any signer address, verification failed") } } @@ -187,13 +187,13 @@ func recoverAddressFromSig(v int, r, s [32]byte, hash []byte) (common.Address, e // Recover the public key bytes from the signature and message hash pubKeyBytes, err := crypto.Ecrecover(hash, sig) if err != nil { - return common.Address{}, fmt.Errorf("failed to recover public key: %v", err) + return common.Address{}, fmt.Errorf("failed to recover public key: %w", err) } // Convert the recovered public key to an ECDSA public key pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes) if err != nil { - return common.Address{}, fmt.Errorf("failed to unmarshal public key: %v", err) + return common.Address{}, fmt.Errorf("failed to unmarshal public key: %w", err) } // or SigToPub return crypto.PubkeyToAddress(*pubKey), nil diff --git a/core/capabilities/ccip/configs/evm/chain_writer.go b/core/capabilities/ccip/configs/evm/chain_writer.go index ada135aecd8..0f675dfcd40 100644 --- a/core/capabilities/ccip/configs/evm/chain_writer.go +++ b/core/capabilities/ccip/configs/evm/chain_writer.go @@ -1,6 +1,7 @@ package evm import ( + "errors" "fmt" "github.com/ethereum/go-ethereum/accounts/abi" @@ -24,13 +25,13 @@ func ChainWriterConfigRaw( execBatchGasLimit uint64, ) (evmrelaytypes.ChainWriterConfig, error) { if fromAddress == common.HexToAddress("0x0") { - return evmrelaytypes.ChainWriterConfig{}, fmt.Errorf("fromAddress cannot be zero") + return evmrelaytypes.ChainWriterConfig{}, errors.New("fromAddress cannot be zero") } if commitGasLimit == 0 { - return evmrelaytypes.ChainWriterConfig{}, fmt.Errorf("commitGasLimit must be greater than zero") + return evmrelaytypes.ChainWriterConfig{}, errors.New("commitGasLimit must be greater than zero") } if execBatchGasLimit == 0 { - return evmrelaytypes.ChainWriterConfig{}, fmt.Errorf("execBatchGasLimit must be greater than zero") + return evmrelaytypes.ChainWriterConfig{}, errors.New("execBatchGasLimit must be greater than zero") } return evmrelaytypes.ChainWriterConfig{ diff --git a/core/capabilities/ccip/oraclecreator/bootstrap.go b/core/capabilities/ccip/oraclecreator/bootstrap.go index 8dfe3e99ffb..2601b5c5acb 100644 --- a/core/capabilities/ccip/oraclecreator/bootstrap.go +++ b/core/capabilities/ccip/oraclecreator/bootstrap.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io" + "strconv" "sync" "time" @@ -152,7 +153,7 @@ func (i *bootstrapOracleCreator) Create(ctx context.Context, _ uint32, config cc } destChainFamily := chaintype.EVM - destRelayID := types.NewRelayID(string(destChainFamily), fmt.Sprintf("%d", chainID)) + destRelayID := types.NewRelayID(string(destChainFamily), strconv.FormatUint(chainID, 10)) oraclePeerIDs := make([]ragep2ptypes.PeerID, 0, len(config.Config.Nodes)) for _, n := range config.Config.Nodes { diff --git a/core/capabilities/ccip/oraclecreator/plugin.go b/core/capabilities/ccip/oraclecreator/plugin.go index d4c5596aeaf..cefd192b4bb 100644 --- a/core/capabilities/ccip/oraclecreator/plugin.go +++ b/core/capabilities/ccip/oraclecreator/plugin.go @@ -3,6 +3,7 @@ package oraclecreator import ( "context" "encoding/json" + "errors" "fmt" "io" "math/big" @@ -238,7 +239,7 @@ func (i *pluginOracleCreator) createFactoryAndTransmitter( if config.Config.PluginType == uint8(cctypes.PluginTypeCCIPCommit) { if !i.peerWrapper.IsStarted() { - return nil, nil, fmt.Errorf("peer wrapper is not started") + return nil, nil, errors.New("peer wrapper is not started") } i.lggr.Infow("creating rmn peer client", @@ -416,7 +417,7 @@ func decodeAndValidateOffchainConfig( ofc.commitOffchainConfig = &commitOffchainCfg } if !ofc.isValid() { - return offChainConfig{}, fmt.Errorf("invalid offchain config: both commit and exec configs are either set or unset") + return offChainConfig{}, errors.New("invalid offchain config: both commit and exec configs are either set or unset") } return ofc, nil } diff --git a/core/capabilities/ccip/validate/validate.go b/core/capabilities/ccip/validate/validate.go index 02e1cb5c8ee..ba4d2f9b846 100644 --- a/core/capabilities/ccip/validate/validate.go +++ b/core/capabilities/ccip/validate/validate.go @@ -1,6 +1,7 @@ package validate import ( + "errors" "fmt" "github.com/google/uuid" @@ -32,13 +33,13 @@ func ValidatedCCIPSpec(tomlString string) (jb job.Job, err error) { return job.Job{}, fmt.Errorf("the only supported type is currently 'ccip', got %s", jb.Type) } if jb.CCIPSpec.CapabilityLabelledName == "" { - return job.Job{}, fmt.Errorf("capabilityLabelledName must be set") + return job.Job{}, errors.New("capabilityLabelledName must be set") } if jb.CCIPSpec.CapabilityVersion == "" { - return job.Job{}, fmt.Errorf("capabilityVersion must be set") + return job.Job{}, errors.New("capabilityVersion must be set") } if jb.CCIPSpec.P2PKeyID == "" { - return job.Job{}, fmt.Errorf("p2pKeyID must be set") + return job.Job{}, errors.New("p2pKeyID must be set") } // ensure that the P2PV2Bootstrappers is in the right format. diff --git a/core/capabilities/compute/compute.go b/core/capabilities/compute/compute.go index 2ba5daefaa6..3102f2d2b61 100644 --- a/core/capabilities/compute/compute.go +++ b/core/capabilities/compute/compute.go @@ -3,6 +3,7 @@ package compute import ( "context" "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -107,7 +108,7 @@ func (c *Compute) UnregisterFromWorkflow(ctx context.Context, request capabiliti func generateID(binary []byte) string { id := sha256.Sum256(binary) - return fmt.Sprintf("%x", id) + return hex.EncodeToString(id[:]) } func (c *Compute) Execute(ctx context.Context, request capabilities.CapabilityRequest) (capabilities.CapabilityResponse, error) { diff --git a/core/capabilities/integration_tests/framework/don_configuration.go b/core/capabilities/integration_tests/framework/don_configuration.go index 2fd1afd6554..052a7d18a6c 100644 --- a/core/capabilities/integration_tests/framework/don_configuration.go +++ b/core/capabilities/integration_tests/framework/don_configuration.go @@ -1,6 +1,7 @@ package framework import ( + "errors" "fmt" commoncap "github.com/smartcontractkit/chainlink-common/pkg/capabilities" @@ -27,7 +28,7 @@ type NewDonConfigurationParams struct { func NewDonConfiguration(don NewDonConfigurationParams) (DonConfiguration, error) { if !(don.NumNodes >= int(3*don.F+1)) { - return DonConfiguration{}, fmt.Errorf("invalid configuration, number of nodes must be at least 3*F+1") + return DonConfiguration{}, errors.New("invalid configuration, number of nodes must be at least 3*F+1") } keyBundles, peerIDs, err := getKeyBundlesAndPeerIDs(don.NumNodes) diff --git a/core/capabilities/launcher.go b/core/capabilities/launcher.go index 51df7eeebfc..fa12f96838a 100644 --- a/core/capabilities/launcher.go +++ b/core/capabilities/launcher.go @@ -357,7 +357,7 @@ func (w *launcher) addToRegistryAndSetDispatcher(ctx context.Context, capability info, err := capabilities.NewRemoteCapabilityInfo( capabilityID, capability.CapabilityType, - fmt.Sprintf("Remote Capability for %s", capabilityID), + "Remote Capability for "+capabilityID, &don.DON, ) if err != nil { @@ -519,7 +519,7 @@ func (w *launcher) addReceiver(ctx context.Context, capability registrysyncer.Ca info, err := capabilities.NewRemoteCapabilityInfo( capID, capability.CapabilityType, - fmt.Sprintf("Remote Capability for %s", capability.ID), + "Remote Capability for "+capability.ID, &don.DON, ) if err != nil { diff --git a/core/capabilities/launcher_test.go b/core/capabilities/launcher_test.go index 167a2fcbd1b..0be06e18b69 100644 --- a/core/capabilities/launcher_test.go +++ b/core/capabilities/launcher_test.go @@ -773,7 +773,7 @@ func TestSyncer_IgnoresCapabilitiesForPrivateDON(t *testing.T) { defer launcher.Close() // Finally, assert that no services were added. - assert.Len(t, launcher.subServices, 0) + assert.Empty(t, launcher.subServices) } func TestLauncher_WiresUpClientsForPublicWorkflowDON(t *testing.T) { diff --git a/core/capabilities/registry.go b/core/capabilities/registry.go index 7038dcdb4b7..207257d4f55 100644 --- a/core/capabilities/registry.go +++ b/core/capabilities/registry.go @@ -161,22 +161,22 @@ func (r *Registry) Add(ctx context.Context, c capabilities.BaseCapability) error case capabilities.CapabilityTypeTrigger: _, ok := c.(capabilities.TriggerCapability) if !ok { - return fmt.Errorf("trigger capability does not satisfy TriggerCapability interface") + return errors.New("trigger capability does not satisfy TriggerCapability interface") } case capabilities.CapabilityTypeAction: _, ok := c.(capabilities.ActionCapability) if !ok { - return fmt.Errorf("action does not satisfy ActionCapability interface") + return errors.New("action does not satisfy ActionCapability interface") } case capabilities.CapabilityTypeConsensus: _, ok := c.(capabilities.ConsensusCapability) if !ok { - return fmt.Errorf("consensus capability does not satisfy ConsensusCapability interface") + return errors.New("consensus capability does not satisfy ConsensusCapability interface") } case capabilities.CapabilityTypeTarget: _, ok := c.(capabilities.TargetCapability) if !ok { - return fmt.Errorf("target capability does not satisfy TargetCapability interface") + return errors.New("target capability does not satisfy TargetCapability interface") } default: return fmt.Errorf("unknown capability type: %s", info.CapabilityType) diff --git a/core/capabilities/registry_test.go b/core/capabilities/registry_test.go index 89f366da04a..fabb039f40c 100644 --- a/core/capabilities/registry_test.go +++ b/core/capabilities/registry_test.go @@ -2,7 +2,6 @@ package capabilities_test import ( "context" - "errors" "fmt" "testing" @@ -86,7 +85,7 @@ func TestRegistry_NoDuplicateIDs(t *testing.T) { c2 := &mockCapability{CapabilityInfo: ci} err = r.Add(ctx, c2) - assert.True(t, errors.Is(err, coreCapabilities.ErrCapabilityAlreadyExists)) + assert.ErrorIs(t, err, coreCapabilities.ErrCapabilityAlreadyExists) } func TestRegistry_ChecksExecutionAPIByType(t *testing.T) { diff --git a/core/capabilities/streams/codec.go b/core/capabilities/streams/codec.go index d6918f0c739..d5c9f2f4c0d 100644 --- a/core/capabilities/streams/codec.go +++ b/core/capabilities/streams/codec.go @@ -22,18 +22,18 @@ var _ datastreams.ReportCodec = &codec{} func (c *codec) Unwrap(wrapped values.Value) ([]datastreams.FeedReport, error) { dest, err := datastreams.UnwrapStreamsTriggerEventToFeedReportList(wrapped) if err != nil { - return nil, fmt.Errorf("failed to unwrap: %v", err) + return nil, fmt.Errorf("failed to unwrap: %w", err) } for i, report := range dest { // decoding fields id, err2 := datastreams.NewFeedID(report.FeedID) if err2 != nil { - return nil, fmt.Errorf("malformed feed ID: %v", err2) + return nil, fmt.Errorf("malformed feed ID: %w", err2) } v3Codec := reportcodec.NewReportCodec(id.Bytes(), nil) decoded, err2 := v3Codec.Decode(report.FullReport) if err2 != nil { - return nil, fmt.Errorf("failed to decode: %v", err2) + return nil, fmt.Errorf("failed to decode: %w", err2) } if decoded.FeedId != id.Bytes() { return nil, fmt.Errorf("feed ID mismatch: FeedID: %s, FullReport.FeedId: %s", id, hex.EncodeToString(decoded.FeedId[:])) @@ -62,7 +62,7 @@ func (c *codec) Validate(report datastreams.FeedReport, allowedSigners [][]byte, for _, sig := range report.Signatures { signerPubkey, err2 := crypto.SigToPub(fullHash, sig) if err2 != nil { - return fmt.Errorf("malformed signer: %v", err2) + return fmt.Errorf("malformed signer: %w", err2) } signerAddr := crypto.PubkeyToAddress(*signerPubkey) if _, ok := signersMap[signerAddr]; !ok { diff --git a/core/capabilities/streams/codec_test.go b/core/capabilities/streams/codec_test.go index 13f4f299f8c..9a524633ec2 100644 --- a/core/capabilities/streams/codec_test.go +++ b/core/capabilities/streams/codec_test.go @@ -73,7 +73,7 @@ func TestCodec_WrapUnwrap(t *testing.T) { // correct reports but wrong signatures unwrapped, err := codec.Unwrap(wrapped) require.NoError(t, err) - require.Equal(t, 2, len(unwrapped)) + require.Len(t, unwrapped, 2) require.Equal(t, price1.Bytes(), unwrapped[0].BenchmarkPrice) require.Equal(t, price2.Bytes(), unwrapped[1].BenchmarkPrice) require.Equal(t, timestamp1, unwrapped[0].ObservationTimestamp) diff --git a/core/capabilities/streams/consensus_agg_test.go b/core/capabilities/streams/consensus_agg_test.go index 834889f2c31..f9e43baad37 100644 --- a/core/capabilities/streams/consensus_agg_test.go +++ b/core/capabilities/streams/consensus_agg_test.go @@ -48,7 +48,7 @@ func TestStreamsConsensusAggregator(t *testing.T) { newState := &datafeeds.DataFeedsOutcomeMetadata{} err = proto.Unmarshal(outcome.Metadata, newState) require.NoError(t, err) - require.Equal(t, P, len(newState.FeedInfo)) + require.Len(t, newState.FeedInfo, P) // run test aggregations startTs := time.Now().UnixMilli() diff --git a/core/capabilities/streams/trigger_test.go b/core/capabilities/streams/trigger_test.go index d5ab367252e..568840e3918 100644 --- a/core/capabilities/streams/trigger_test.go +++ b/core/capabilities/streams/trigger_test.go @@ -212,7 +212,7 @@ func newTriggerEvent(t *testing.T, reportList []datastreams.FeedReport, triggerE func validateLatestReports(t *testing.T, wrapped values.Value, expectedFeedsLen int, expectedPrice int, expectedTimestamp int) { triggerEvent := datastreams.StreamsTriggerEvent{} require.NoError(t, wrapped.UnwrapTo(&triggerEvent)) - require.Equal(t, expectedFeedsLen, len(triggerEvent.Payload)) + require.Len(t, triggerEvent.Payload, expectedFeedsLen) priceBig := big.NewInt(int64(expectedPrice)) for _, report := range triggerEvent.Payload { require.Equal(t, priceBig.Bytes(), report.BenchmarkPrice) diff --git a/core/capabilities/targets/write_target.go b/core/capabilities/targets/write_target.go index 09a0bbd2b36..b65711ccb51 100644 --- a/core/capabilities/targets/write_target.go +++ b/core/capabilities/targets/write_target.go @@ -5,6 +5,7 @@ import ( "context" "encoding/binary" "encoding/hex" + "errors" "fmt" "math/big" "strings" @@ -151,7 +152,7 @@ func evaluate(rawRequest capabilities.CapabilityRequest) (r Request, err error) r.Metadata = rawRequest.Metadata if rawRequest.Config == nil { - return r, fmt.Errorf("missing config field") + return r, errors.New("missing config field") } if err = rawRequest.Config.UnwrapTo(&r.Config); err != nil { @@ -163,7 +164,7 @@ func evaluate(rawRequest capabilities.CapabilityRequest) (r Request, err error) } if rawRequest.Inputs == nil { - return r, fmt.Errorf("missing inputs field") + return r, errors.New("missing inputs field") } // required field of target's config in the workflow spec diff --git a/core/capabilities/triggers/logevent/service.go b/core/capabilities/triggers/logevent/service.go index 8a59865e3f5..e6f6da36f62 100644 --- a/core/capabilities/triggers/logevent/service.go +++ b/core/capabilities/triggers/logevent/service.go @@ -108,7 +108,7 @@ func (s *TriggerService) RegisterTrigger(ctx context.Context, }) }) if !ok { - return nil, fmt.Errorf("cannot create new trigger since LogEventTriggerCapabilityService has been stopped") + return nil, errors.New("cannot create new trigger since LogEventTriggerCapabilityService has been stopped") } if err != nil { return nil, fmt.Errorf("create new trigger failed %w", err) diff --git a/core/capabilities/triggers/logevent/store.go b/core/capabilities/triggers/logevent/store.go index ac9d3741cd1..26616b570c8 100644 --- a/core/capabilities/triggers/logevent/store.go +++ b/core/capabilities/triggers/logevent/store.go @@ -69,7 +69,7 @@ func (cs *capabilitiesStore[T, Resp]) InsertIfNotExists(capabilityID string, fn } value, respCh, err := fn() if err != nil { - return nil, fmt.Errorf("error registering capability: %v", err) + return nil, fmt.Errorf("error registering capability: %w", err) } cs.capabilities[capabilityID] = value return respCh, nil diff --git a/core/capabilities/triggers/logevent/trigger.go b/core/capabilities/triggers/logevent/trigger.go index 334c3c3f30e..27154443040 100644 --- a/core/capabilities/triggers/logevent/trigger.go +++ b/core/capabilities/triggers/logevent/trigger.go @@ -97,7 +97,7 @@ func newLogEventTrigger(ctx context.Context, // Initialise a Log Event Trigger l := &logEventTrigger{ ch: callbackCh, - lggr: logger.Named(lggr, fmt.Sprintf("LogEventTrigger.%s", workflowID)), + lggr: logger.Named(lggr, "LogEventTrigger."+workflowID), reqConfig: reqConfig, contractReader: contractReader, @@ -154,7 +154,7 @@ func (l *logEventTrigger) listen() { Key: l.reqConfig.ContractEventName, Expressions: []query.Expression{ query.Confidence(primitives.Finalized), - query.Block(fmt.Sprintf("%d", l.startBlockNum), primitives.Gte), + query.Block(strconv.FormatUint(l.startBlockNum, 10), primitives.Gte), }, }, limitAndSort, diff --git a/core/capabilities/validation/validation_test.go b/core/capabilities/validation/validation_test.go index 205898652fd..5429e040b6d 100644 --- a/core/capabilities/validation/validation_test.go +++ b/core/capabilities/validation/validation_test.go @@ -7,8 +7,8 @@ import ( ) func TestIsValidWorkflowID(t *testing.T) { - require.NotNil(t, ValidateWorkflowOrExecutionID("too_short")) - require.NotNil(t, ValidateWorkflowOrExecutionID("nothex--95ef5e32deb99a10ee6804bc4af13855687559d7ff6552ac6dbb2ce0")) + require.Error(t, ValidateWorkflowOrExecutionID("too_short")) + require.Error(t, ValidateWorkflowOrExecutionID("nothex--95ef5e32deb99a10ee6804bc4af13855687559d7ff6552ac6dbb2ce0")) require.NoError(t, ValidateWorkflowOrExecutionID("15c631d295ef5e32deb99a10ee6804bc4af13855687559d7ff6552ac6dbb2ce0")) } diff --git a/core/capabilities/webapi/trigger/trigger.go b/core/capabilities/webapi/trigger/trigger.go index 712cf38a4cc..a07ba82d173 100644 --- a/core/capabilities/webapi/trigger/trigger.go +++ b/core/capabilities/webapi/trigger/trigger.go @@ -77,13 +77,13 @@ func (h *triggerConnectorHandler) processTrigger(ctx context.Context, gatewayID // Pass on the payload with the expectation that it's in an acceptable format for the executor wrappedPayload, err := values.WrapMap(payload) if err != nil { - return fmt.Errorf("error wrapping payload %s", err) + return fmt.Errorf("error wrapping payload %w", err) } topics := payload.Topics // empty topics is error for V1 if len(topics) == 0 { - return fmt.Errorf("empty Workflow Topics") + return errors.New("empty Workflow Topics") } // workflows that have matched topics @@ -123,7 +123,7 @@ func (h *triggerConnectorHandler) processTrigger(ctx context.Context, gatewayID } } if matchedWorkflows == 0 { - return fmt.Errorf("no Matching Workflow Topics") + return errors.New("no Matching Workflow Topics") } if fullyMatchedWorkflows > 0 { diff --git a/core/capabilities/webapi/trigger/trigger_test.go b/core/capabilities/webapi/trigger/trigger_test.go index 0c73e31fe62..dfd9a368907 100644 --- a/core/capabilities/webapi/trigger/trigger_test.go +++ b/core/capabilities/webapi/trigger/trigger_test.go @@ -188,7 +188,7 @@ func TestTriggerExecute(t *testing.T) { th.trigger.HandleGatewayMessage(ctx, "gateway1", gatewayRequest) received, chanErr := requireChanMsg(t, channel) - require.Equal(t, received.Event.TriggerType, TriggerType) + require.Equal(t, TriggerType, received.Event.TriggerType) require.NoError(t, chanErr) requireNoChanMsg(t, channel2) @@ -196,7 +196,7 @@ func TestTriggerExecute(t *testing.T) { var payload webapicap.TriggerRequestPayload unwrapErr := data.UnwrapTo(&payload) require.NoError(t, unwrapErr) - require.Equal(t, payload.Topics, []string{"daily_price_update"}) + require.Equal(t, []string{"daily_price_update"}, payload.Topics) }) t.Run("happy case single different topic 2 workflows.", func(t *testing.T) { @@ -210,20 +210,20 @@ func TestTriggerExecute(t *testing.T) { th.trigger.HandleGatewayMessage(ctx, "gateway1", gatewayRequest) sent := <-channel - require.Equal(t, sent.Event.TriggerType, TriggerType) + require.Equal(t, TriggerType, sent.Event.TriggerType) data := sent.Event.Outputs var payload webapicap.TriggerRequestPayload unwrapErr := data.UnwrapTo(&payload) require.NoError(t, unwrapErr) - require.Equal(t, payload.Topics, []string{"ad_hoc_price_update"}) + require.Equal(t, []string{"ad_hoc_price_update"}, payload.Topics) sent2 := <-channel2 - require.Equal(t, sent2.Event.TriggerType, TriggerType) + require.Equal(t, TriggerType, sent2.Event.TriggerType) data2 := sent2.Event.Outputs var payload2 webapicap.TriggerRequestPayload err2 := data2.UnwrapTo(&payload2) require.NoError(t, err2) - require.Equal(t, payload2.Topics, []string{"ad_hoc_price_update"}) + require.Equal(t, []string{"ad_hoc_price_update"}, payload2.Topics) }) t.Run("sad case empty topic 2 workflows", func(t *testing.T) { @@ -345,13 +345,13 @@ func TestTriggerExecute2WorkflowsSameTopicDifferentAllowLists(t *testing.T) { requireNoChanMsg(t, channel) received, chanErr := requireChanMsg(t, channel2) - require.Equal(t, received.Event.TriggerType, TriggerType) + require.Equal(t, TriggerType, received.Event.TriggerType) require.NoError(t, chanErr) data := received.Event.Outputs var payload webapicap.TriggerRequestPayload unwrapErr := data.UnwrapTo(&payload) require.NoError(t, unwrapErr) - require.Equal(t, payload.Topics, []string{"daily_price_update"}) + require.Equal(t, []string{"daily_price_update"}, payload.Topics) }) err = th.trigger.UnregisterTrigger(ctx, triggerReq) require.NoError(t, err) @@ -382,5 +382,5 @@ func TestRegisterUnregister(t *testing.T) { err = th.trigger.UnregisterTrigger(ctx, triggerReq) require.NoError(t, err) _, open := <-channel - require.Equal(t, open, false) + require.False(t, open) } diff --git a/core/chains/chain_kv_test.go b/core/chains/chain_kv_test.go index ababb2da3c3..664649752bf 100644 --- a/core/chains/chain_kv_test.go +++ b/core/chains/chain_kv_test.go @@ -23,12 +23,12 @@ func Test_ChainKV(t *testing.T) { assert.Nil(t, c) assert.ErrorIs(t, err, chains.ErrNoSuchChainID) - assert.Equal(t, kv.Len(), 0) - assert.Len(t, kv.Slice(), 0) + assert.Equal(t, 0, kv.Len()) + assert.Empty(t, kv.Slice()) cs, err := kv.List() assert.NoError(t, err) - assert.Len(t, cs, 0) + assert.Empty(t, cs) // test with one chain onechain := map[string]*testChainService{testChainID: testChain} @@ -37,7 +37,7 @@ func Test_ChainKV(t *testing.T) { assert.Equal(t, c, testChain) assert.NoError(t, err) - assert.Equal(t, kv.Len(), 1) + assert.Equal(t, 1, kv.Len()) assert.Len(t, kv.Slice(), 1) cs, err = kv.List() @@ -53,7 +53,7 @@ func Test_ChainKV(t *testing.T) { // List no such id cs, err = kv.List("no such id") assert.Error(t, err) - assert.Len(t, cs, 0) + assert.Empty(t, cs) } type testChainService struct { diff --git a/core/chains/evm/abi/selector_parser.go b/core/chains/evm/abi/selector_parser.go index 74683b0ed28..9bfd8b465d9 100644 --- a/core/chains/evm/abi/selector_parser.go +++ b/core/chains/evm/abi/selector_parser.go @@ -64,7 +64,7 @@ func parseIdentifier(unescapedSelector string) (string, string, error) { func parseElementaryType(unescapedSelector string) (string, string, error) { parsedType, rest, err := parseToken(unescapedSelector, false) if err != nil { - return "", "", fmt.Errorf("failed to parse elementary type: %v", err) + return "", "", fmt.Errorf("failed to parse elementary type: %w", err) } // handle arrays for len(rest) > 0 && rest[0] == '[' { @@ -100,7 +100,7 @@ func parseCompositeType(unescapedSelector string) ([]abi.ArgumentMarshaling, str parsedType, rest, err = parseType(rest[0:]) if err != nil { - return nil, "", fmt.Errorf("failed to parse type: %v", err) + return nil, "", fmt.Errorf("failed to parse type: %w", err) } // skip whitespace between name and identifier @@ -114,13 +114,13 @@ func parseCompositeType(unescapedSelector string) ([]abi.ArgumentMarshaling, str // attempt to parse name name, rest, err = parseIdentifier(rest) if err != nil { - return nil, "", fmt.Errorf("failed to parse name: %v", err) + return nil, "", fmt.Errorf("failed to parse name: %w", err) } } arg, err := assembleArg(name, parsedType) if err != nil { - return nil, "", fmt.Errorf("failed to parse type: %v", err) + return nil, "", fmt.Errorf("failed to parse type: %w", err) } result = append(result, arg) @@ -177,7 +177,7 @@ func assembleArg(name string, arg any) (abi.ArgumentMarshaling, error) { func ParseSelector(unescapedSelector string) (abi.SelectorMarshaling, error) { name, rest, err := parseIdentifier(unescapedSelector) if err != nil { - return abi.SelectorMarshaling{}, fmt.Errorf("failed to parse selector identifier '%s': %v", unescapedSelector, err) + return abi.SelectorMarshaling{}, fmt.Errorf("failed to parse selector identifier '%s': %w", unescapedSelector, err) } args := []abi.ArgumentMarshaling{} if len(rest) >= 2 && rest[0] == '(' && rest[1] == ')' { @@ -185,7 +185,7 @@ func ParseSelector(unescapedSelector string) (abi.SelectorMarshaling, error) { } else { args, rest, err = parseCompositeType(rest) if err != nil { - return abi.SelectorMarshaling{}, fmt.Errorf("failed to parse selector args '%s': %v", unescapedSelector, err) + return abi.SelectorMarshaling{}, fmt.Errorf("failed to parse selector args '%s': %w", unescapedSelector, err) } } if len(rest) > 0 { diff --git a/core/chains/evm/client/chain_client_test.go b/core/chains/evm/client/chain_client_test.go index 77e11db7a90..82c875034ba 100644 --- a/core/chains/evm/client/chain_client_test.go +++ b/core/chains/evm/client/chain_client_test.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "math/big" "net/http/httptest" "net/url" @@ -156,7 +155,7 @@ func TestEthClient_PendingNonceAt(t *testing.T) { require.NoError(t, err) var expected uint64 = 256 - require.Equal(t, result, expected) + require.Equal(t, expected, result) } func TestEthClient_BalanceAt(t *testing.T) { @@ -325,7 +324,7 @@ func TestEthClient_HeaderByNumber(t *testing.T) { `{"difficulty":"0xf3a00","extraData":"0xd883010503846765746887676f312e372e318664617277696e","gasLimit":"0xffc001","gasUsed":"0x0","hash":"0x41800b5c3f1717687d85fc9018faac0a6e90b39deaa0b99e7fe4fe796ddeb26a","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0xd1aeb42885a43b72b518182ef893125814811048","mixHash":"0x0f98b15f1a4901a7e9204f3c500a7bd527b3fb2c3340e12176a44b83e414a69e","nonce":"0x0ece08ea8c49dfd9","number":"0x1","parentHash":"0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x218","stateRoot":"0xc7b01007a10da045eacb90385887dd0c38fcb5db7393006bdde24b93873c334b","timestamp":"0x58318da2","totalDifficulty":"0x1f3a00","transactions":[],"transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","uncles":[]}`}, {"happy parity", expectedBlockNum, expectedBlockNum.Int64(), nil, `{"author":"0xd1aeb42885a43b72b518182ef893125814811048","difficulty":"0xf3a00","extraData":"0xd883010503846765746887676f312e372e318664617277696e","gasLimit":"0xffc001","gasUsed":"0x0","hash":"0x41800b5c3f1717687d85fc9018faac0a6e90b39deaa0b99e7fe4fe796ddeb26a","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0xd1aeb42885a43b72b518182ef893125814811048","mixHash":"0x0f98b15f1a4901a7e9204f3c500a7bd527b3fb2c3340e12176a44b83e414a69e","nonce":"0x0ece08ea8c49dfd9","number":"0x1","parentHash":"0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":["0xa00f98b15f1a4901a7e9204f3c500a7bd527b3fb2c3340e12176a44b83e414a69e","0x880ece08ea8c49dfd9"],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x218","stateRoot":"0xc7b01007a10da045eacb90385887dd0c38fcb5db7393006bdde24b93873c334b","timestamp":"0x58318da2","totalDifficulty":"0x1f3a00","transactions":[],"transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","uncles":[]}`}, - {"missing header", expectedBlockNum, 0, fmt.Errorf("RPCClient returned error (eth-primary-rpc-0): not found"), + {"missing header", expectedBlockNum, 0, errors.New("RPCClient returned error (eth-primary-rpc-0): not found"), `null`}, } @@ -350,7 +349,7 @@ func TestEthClient_HeaderByNumber(t *testing.T) { var blockNum hexutil.Big err := blockNum.UnmarshalText([]byte(blockNumStr)) if assert.NoError(t, err) && assert.Equal(t, test.expectedRequestBlock, blockNum.ToInt()) && - assert.Equal(t, false, arr[1].Bool()) { + assert.False(t, arr[1].Bool()) { resp.Result = test.rpcResp } return @@ -491,7 +490,7 @@ func TestEthClient_SendTransactionReturnCode(t *testing.T) { errType, err := ethClient.SendTransactionReturnCode(tests.Context(t), tx, fromAddress) assert.Error(t, err) - assert.Equal(t, errType, commonclient.Fatal) + assert.Equal(t, commonclient.Fatal, errType) }) t.Run("returns TransactionAlreadyKnown error type when error message is nonce too low", func(t *testing.T) { @@ -517,7 +516,7 @@ func TestEthClient_SendTransactionReturnCode(t *testing.T) { errType, err := ethClient.SendTransactionReturnCode(tests.Context(t), tx, fromAddress) assert.Error(t, err) - assert.Equal(t, errType, commonclient.TransactionAlreadyKnown) + assert.Equal(t, commonclient.TransactionAlreadyKnown, errType) }) t.Run("returns Successful error type when there is no error message", func(t *testing.T) { @@ -542,7 +541,7 @@ func TestEthClient_SendTransactionReturnCode(t *testing.T) { errType, err := ethClient.SendTransactionReturnCode(tests.Context(t), tx, fromAddress) assert.NoError(t, err) - assert.Equal(t, errType, commonclient.Successful) + assert.Equal(t, commonclient.Successful, errType) }) t.Run("returns Underpriced error type when transaction is terminally underpriced", func(t *testing.T) { @@ -568,7 +567,7 @@ func TestEthClient_SendTransactionReturnCode(t *testing.T) { errType, err := ethClient.SendTransactionReturnCode(tests.Context(t), tx, fromAddress) assert.Error(t, err) - assert.Equal(t, errType, commonclient.Underpriced) + assert.Equal(t, commonclient.Underpriced, errType) }) t.Run("returns Unsupported error type when error message is queue full", func(t *testing.T) { @@ -594,7 +593,7 @@ func TestEthClient_SendTransactionReturnCode(t *testing.T) { errType, err := ethClient.SendTransactionReturnCode(tests.Context(t), tx, fromAddress) assert.Error(t, err) - assert.Equal(t, errType, commonclient.Unsupported) + assert.Equal(t, commonclient.Unsupported, errType) }) t.Run("returns Retryable error type when there is a transaction gap", func(t *testing.T) { @@ -620,7 +619,7 @@ func TestEthClient_SendTransactionReturnCode(t *testing.T) { errType, err := ethClient.SendTransactionReturnCode(tests.Context(t), tx, fromAddress) assert.Error(t, err) - assert.Equal(t, errType, commonclient.Retryable) + assert.Equal(t, commonclient.Retryable, errType) }) t.Run("returns InsufficientFunds error type when the sender address doesn't have enough funds", func(t *testing.T) { @@ -646,7 +645,7 @@ func TestEthClient_SendTransactionReturnCode(t *testing.T) { errType, err := ethClient.SendTransactionReturnCode(tests.Context(t), tx, fromAddress) assert.Error(t, err) - assert.Equal(t, errType, commonclient.InsufficientFunds) + assert.Equal(t, commonclient.InsufficientFunds, errType) }) t.Run("returns ExceedsFeeCap error type when gas price is too high for the node", func(t *testing.T) { @@ -672,7 +671,7 @@ func TestEthClient_SendTransactionReturnCode(t *testing.T) { errType, err := ethClient.SendTransactionReturnCode(tests.Context(t), tx, fromAddress) assert.Error(t, err) - assert.Equal(t, errType, commonclient.ExceedsMaxFee) + assert.Equal(t, commonclient.ExceedsMaxFee, errType) }) t.Run("returns Unknown error type when the error can't be categorized", func(t *testing.T) { @@ -698,7 +697,7 @@ func TestEthClient_SendTransactionReturnCode(t *testing.T) { errType, err := ethClient.SendTransactionReturnCode(tests.Context(t), tx, fromAddress) assert.Error(t, err) - assert.Equal(t, errType, commonclient.Unknown) + assert.Equal(t, commonclient.Unknown, errType) }) } @@ -864,7 +863,7 @@ func TestEthClient_ErroringClient(t *testing.T) { tx := testutils.NewLegacyTransaction(uint64(42), testutils.NewAddress(), big.NewInt(142), 242, big.NewInt(342), []byte{1, 2, 3}) code, err := erroringClient.SendTransactionReturnCode(ctx, tx, common.Address{}) - require.Equal(t, code, commonclient.Unknown) + require.Equal(t, commonclient.Unknown, code) require.Equal(t, err, txSenderNotStarted) _, err = erroringClient.NonceAt(ctx, common.Address{}, nil) diff --git a/core/chains/evm/client/config_builder_test.go b/core/chains/evm/client/config_builder_test.go index 856242edada..0cf12235451 100644 --- a/core/chains/evm/client/config_builder_test.go +++ b/core/chains/evm/client/config_builder_test.go @@ -101,7 +101,7 @@ func TestNodeConfigs(t *testing.T) { }, } _, err := client.ParseTestNodeConfigs(nodeConfigs) - require.Nil(t, err) + require.NoError(t, err) }) t.Run("parsing missing http url fails", func(t *testing.T) { diff --git a/core/chains/evm/client/errors.go b/core/chains/evm/client/errors.go index bde97185580..ef19b4539f4 100644 --- a/core/chains/evm/client/errors.go +++ b/core/chains/evm/client/errors.go @@ -639,7 +639,7 @@ func ClassifySendError(err error, clientErrors config.ClientErrors, lggr logger. return commonclient.Retryable } if sendError.IsTxFeeExceedsCap(configErrors) { - lggr.Criticalw(fmt.Sprintf("Sending transaction failed: %s", label.RPCTxFeeCapConfiguredIncorrectlyWarning), + lggr.Criticalw("Sending transaction failed: "+label.RPCTxFeeCapConfiguredIncorrectlyWarning, "etx", tx, "err", sendError, "id", "RPCTxFeeCapExceeded", diff --git a/core/chains/evm/client/rpc_client.go b/core/chains/evm/client/rpc_client.go index 97046b4eff2..f466774d7dc 100644 --- a/core/chains/evm/client/rpc_client.go +++ b/core/chains/evm/client/rpc_client.go @@ -8,6 +8,7 @@ import ( "math/big" "net/url" "strconv" + "strings" "sync" "time" @@ -277,14 +278,20 @@ func (r *RPCClient) cancelInflightRequests() { } func (r *RPCClient) String() string { - s := fmt.Sprintf("(%s)%s", r.tier.String(), r.name) + var s strings.Builder + s.WriteByte('(') + s.WriteString(r.tier.String()) + s.WriteByte(')') + s.WriteString(r.name) if r.ws != nil { - s = s + fmt.Sprintf(":%s", r.ws.uri.Redacted()) + s.WriteByte(':') + s.WriteString(r.ws.uri.Redacted()) } if r.http != nil { - s = s + fmt.Sprintf(":%s", r.http.uri.Redacted()) + s.WriteByte(':') + s.WriteString(r.http.uri.Redacted()) } - return s + return s.String() } func (r *RPCClient) logResult( @@ -335,7 +342,7 @@ func (r *RPCClient) registerSub(sub ethereum.Subscription, stopInFLightCh chan s select { case <-stopInFLightCh: sub.Unsubscribe() - return fmt.Errorf("failed to register subscription - all in-flight requests were canceled") + return errors.New("failed to register subscription - all in-flight requests were canceled") default: } // TODO: BCI-3358 - delete sub when caller unsubscribes. @@ -688,7 +695,7 @@ func (r *RPCClient) astarLatestFinalizedBlock(ctx context.Context, result interf } if astarHead.Number == nil { - return r.wrapRPCClientError(fmt.Errorf("expected non empty head number of finalized block")) + return r.wrapRPCClientError(errors.New("expected non empty head number of finalized block")) } err = r.ethGetBlockByNumber(ctx, astarHead.Number.String(), result) diff --git a/core/chains/evm/client/rpc_client_test.go b/core/chains/evm/client/rpc_client_test.go index d5286e9acf0..e36e0050929 100644 --- a/core/chains/evm/client/rpc_client_test.go +++ b/core/chains/evm/client/rpc_client_test.go @@ -342,7 +342,7 @@ func TestRPCClient_SubscribeFilterLogs(t *testing.T) { // ws is optional when LogBroadcaster is disabled, however SubscribeFilterLogs will return error if ws is missing observedLggr := logger.Test(t) rpcClient := client.NewRPCClient(nodePoolCfg, observedLggr, nil, &url.URL{}, "rpc", 1, chainId, commonclient.Primary, commonclient.QueryTimeout, commonclient.QueryTimeout, "") - require.Nil(t, rpcClient.Dial(ctx)) + require.NoError(t, rpcClient.Dial(ctx)) _, err := rpcClient.SubscribeFilterLogs(ctx, ethereum.FilterQuery{}, make(chan types.Log)) require.Equal(t, errors.New("SubscribeFilterLogs is not allowed without ws url"), err) @@ -575,7 +575,7 @@ func TestRpcClientLargePayloadTimeout(t *testing.T) { require.NoError(t, rpc.Dial(ctx)) defer rpc.Close() err := testCase.Fn(ctx, rpc) - assert.True(t, errors.Is(err, context.DeadlineExceeded), fmt.Sprintf("Expected DedlineExceeded error, but got: %v", err)) + assert.ErrorIs(t, err, context.DeadlineExceeded, fmt.Sprintf("Expected DedlineExceeded error, but got: %v", err)) }) } } @@ -609,7 +609,7 @@ func TestAstarCustomFinality(t *testing.T) { assert.Fail(t, fmt.Sprintf("unexpected eth_getBlockByNumber param: %v", params.Array())) } default: - assert.Fail(t, fmt.Sprintf("unexpected method: %s", method)) + assert.Fail(t, "unexpected method: "+method) } return }).WSURL() diff --git a/core/chains/evm/client/simulated_backend_client.go b/core/chains/evm/client/simulated_backend_client.go index fd645203856..22c9378637a 100644 --- a/core/chains/evm/client/simulated_backend_client.go +++ b/core/chains/evm/client/simulated_backend_client.go @@ -163,7 +163,7 @@ func (c *SimulatedBackendClient) TokenBalance(ctx context.Context, address commo } err = balanceOfABI.UnpackIntoInterface(balance, "balanceOf", b) if err != nil { - return nil, fmt.Errorf("unable to unpack balance") + return nil, errors.New("unable to unpack balance") } return balance, nil } @@ -230,7 +230,7 @@ func (c *SimulatedBackendClient) blockNumber(ctx context.Context, number interfa return nil, nil } if n.Sign() < 0 { - return nil, fmt.Errorf("block number must be non-negative") + return nil, errors.New("block number must be non-negative") } return n, nil default: @@ -423,12 +423,12 @@ func (c *SimulatedBackendClient) SendTransaction(ctx context.Context, tx *types. if err != nil { sender, err = types.Sender(types.NewLondonSigner(big.NewInt(1337)), tx) if err != nil { - logger.Test(c.t).Panic(fmt.Errorf("invalid transaction: %v (tx: %#v)", err, tx)) + logger.Test(c.t).Panic(fmt.Errorf("invalid transaction: %w (tx: %#v)", err, tx)) } } pendingNonce, err := c.client.PendingNonceAt(ctx, sender) if err != nil { - panic(fmt.Errorf("unable to determine nonce for account %s: %v", sender.Hex(), err)) + panic(fmt.Errorf("unable to determine nonce for account %s: %w", sender.Hex(), err)) } // the simulated backend does not gracefully handle tx rebroadcasts (gas bumping) so just // ignore the situation where nonces are reused @@ -840,7 +840,7 @@ func toCallMsg(params map[string]interface{}) ethereum.CallMsg { var callMsg ethereum.CallMsg toAddr, err := interfaceToAddress(params["to"]) if err != nil { - panic(fmt.Errorf("unexpected 'to' parameter: %s", err)) + panic(fmt.Errorf("unexpected 'to' parameter: %w", err)) } callMsg.To = &toAddr @@ -849,7 +849,7 @@ func toCallMsg(params map[string]interface{}) ethereum.CallMsg { if value, ok := params["from"]; ok { addr, err := interfaceToAddress(value) if err != nil { - panic(fmt.Errorf("unexpected 'from' parameter: %s", err)) + panic(fmt.Errorf("unexpected 'from' parameter: %w", err)) } callMsg.From = addr @@ -923,13 +923,13 @@ func interfaceToAddress(value interface{}) (common.Address, error) { return *v, nil case string: if ok := common.IsHexAddress(v); !ok { - return common.Address{}, fmt.Errorf("string not formatted as a hex encoded evm address") + return common.Address{}, errors.New("string not formatted as a hex encoded evm address") } return common.HexToAddress(v), nil case *big.Int: if v.Uint64() > 0 || len(v.Bytes()) > 20 { - return common.Address{}, fmt.Errorf("invalid *big.Int; value must be larger than 0 with a byte length <= 20") + return common.Address{}, errors.New("invalid *big.Int; value must be larger than 0 with a byte length <= 20") } return common.BigToAddress(v), nil @@ -947,7 +947,7 @@ func interfaceToHash(value interface{}) (*common.Hash, error) { case string: b, err := hex.DecodeString(v) if err != nil || len(b) != 32 { - return nil, fmt.Errorf("string does not represent a 32-byte hexadecimal number") + return nil, errors.New("string does not represent a 32-byte hexadecimal number") } h := common.Hash(b) return &h, nil diff --git a/core/chains/evm/client/sub_forwarder_test.go b/core/chains/evm/client/sub_forwarder_test.go index 1bc0122603b..3299a05f83c 100644 --- a/core/chains/evm/client/sub_forwarder_test.go +++ b/core/chains/evm/client/sub_forwarder_test.go @@ -150,7 +150,7 @@ func TestSubscriptionErrorWrapper(t *testing.T) { sub := NewMockSubscription() const prefix = "RPC returned error" wrapper := newSubscriptionErrorWrapper(t, sub, prefix) - sub.Errors <- fmt.Errorf("error") + sub.Errors <- errors.New("error") wrapper.Unsubscribe() _, ok := <-wrapper.Err() @@ -161,7 +161,7 @@ func TestSubscriptionErrorWrapper(t *testing.T) { sub := NewMockSubscription() const prefix = "RPC returned error" wrapper := newSubscriptionErrorWrapper(t, sub, prefix) - sub.Errors <- fmt.Errorf("root error") + sub.Errors <- errors.New("root error") err, ok := <-wrapper.Err() assert.True(t, ok) diff --git a/core/chains/evm/client/tx_simulator_test.go b/core/chains/evm/client/tx_simulator_test.go index d82db154e04..10605ac4946 100644 --- a/core/chains/evm/client/tx_simulator_test.go +++ b/core/chains/evm/client/tx_simulator_test.go @@ -78,7 +78,7 @@ func TestSimulateTx_Default(t *testing.T) { Data: []byte("0x00"), } sendErr := client.SimulateTransaction(ctx, ethClient, logger.TestSugared(t), "", msg) - require.Equal(t, true, sendErr.IsTerminallyStuckConfigError(nil)) + require.True(t, sendErr.IsTerminallyStuckConfigError(nil)) }) t.Run("returns without error if simulation returns non-OOC error", func(t *testing.T) { @@ -108,6 +108,6 @@ func TestSimulateTx_Default(t *testing.T) { Data: []byte("0x00"), } sendErr := client.SimulateTransaction(ctx, ethClient, logger.TestSugared(t), "", msg) - require.Equal(t, false, sendErr.IsTerminallyStuckConfigError(nil)) + require.False(t, sendErr.IsTerminallyStuckConfigError(nil)) }) } diff --git a/core/chains/evm/config/config_test.go b/core/chains/evm/config/config_test.go index ab0d600efe0..5fec9ecd007 100644 --- a/core/chains/evm/config/config_test.go +++ b/core/chains/evm/config/config_test.go @@ -208,7 +208,7 @@ func TestChainScopedConfig(t *testing.T) { t.Run("LogBroadcasterEnabled", func(t *testing.T) { t.Run("turn on LogBroadcasterEnabled by default", func(t *testing.T) { - assert.Equal(t, true, cfg.EVM().LogBroadcasterEnabled()) + assert.True(t, cfg.EVM().LogBroadcasterEnabled()) }) t.Run("verify LogBroadcasterEnabled is set correctly", func(t *testing.T) { @@ -217,7 +217,7 @@ func TestChainScopedConfig(t *testing.T) { c.LogBroadcasterEnabled = ptr(val) }) - assert.Equal(t, false, cfg3.EVM().LogBroadcasterEnabled()) + assert.False(t, cfg3.EVM().LogBroadcasterEnabled()) }) }) @@ -280,7 +280,7 @@ func TestChainScopedConfig_GasEstimator(t *testing.T) { assert.Equal(t, assets.GWei(100), ge.FeeCapDefault()) assert.Equal(t, assets.NewWeiI(1), ge.TipCapDefault()) assert.Equal(t, assets.NewWeiI(1), ge.TipCapMin()) - assert.Equal(t, false, ge.EstimateLimit()) + assert.False(t, ge.EstimateLimit()) } func TestChainScopedConfig_BSCDefaults(t *testing.T) { @@ -352,9 +352,9 @@ func TestChainScopedConfig_HeadTracker(t *testing.T) { assert.Equal(t, uint32(100), ht.HistoryDepth()) assert.Equal(t, uint32(3), ht.MaxBufferSize()) assert.Equal(t, time.Second, ht.SamplingInterval()) - assert.Equal(t, true, ht.FinalityTagBypass()) + assert.True(t, ht.FinalityTagBypass()) assert.Equal(t, uint32(10000), ht.MaxAllowedFinalityDepth()) - assert.Equal(t, true, ht.PersistenceEnabled()) + assert.True(t, ht.PersistenceEnabled()) } func TestNodePoolConfig(t *testing.T) { diff --git a/core/chains/evm/config/toml/defaults.go b/core/chains/evm/config/toml/defaults.go index 6f03575056b..30b515d6e8d 100644 --- a/core/chains/evm/config/toml/defaults.go +++ b/core/chains/evm/config/toml/defaults.go @@ -3,7 +3,6 @@ package toml import ( "bytes" "embed" - "fmt" "io" "log" "os" @@ -83,7 +82,7 @@ func init() { } // use evm overrides specifically - evmDir := fmt.Sprintf("%s/evm", dir) + evmDir := dir + "/evm" // Read directory contents for evm only entries, err := os.ReadDir(evmDir) diff --git a/core/chains/evm/forwarders/forwarder_manager_test.go b/core/chains/evm/forwarders/forwarder_manager_test.go index 55f69f134b2..4a6fcd13ddf 100644 --- a/core/chains/evm/forwarders/forwarder_manager_test.go +++ b/core/chains/evm/forwarders/forwarder_manager_test.go @@ -85,7 +85,7 @@ func TestFwdMgr_MaybeForwardTransaction(t *testing.T) { require.NoError(t, err) lst, err := fwdMgr.ORM.FindForwardersByChain(ctx, ubig.Big(*testutils.FixtureChainID)) require.NoError(t, err) - require.Equal(t, len(lst), 1) + require.Len(t, lst, 1) require.Equal(t, lst[0].Address, forwarderAddr) require.NoError(t, fwdMgr.Start(testutils.Context(t))) @@ -147,7 +147,7 @@ func TestFwdMgr_AccountUnauthorizedToForward_SkipsForwarding(t *testing.T) { require.NoError(t, err) lst, err := fwdMgr.ORM.FindForwardersByChain(ctx, ubig.Big(*testutils.FixtureChainID)) require.NoError(t, err) - require.Equal(t, len(lst), 1) + require.Len(t, lst, 1) require.Equal(t, lst[0].Address, forwarderAddr) err = fwdMgr.Start(testutils.Context(t)) @@ -213,7 +213,7 @@ func TestFwdMgr_InvalidForwarderForOCR2FeedsStates(t *testing.T) { require.NoError(t, err) lst, err := fwdMgr.ORM.FindForwardersByChain(ctx, ubig.Big(*testutils.FixtureChainID)) require.NoError(t, err) - require.Equal(t, len(lst), 1) + require.Len(t, lst, 1) require.Equal(t, lst[0].Address, forwarderAddr) fwdMgr = forwarders.NewFwdMgr(db, evmClient, lp, lggr, evmcfg.EVM()) diff --git a/core/chains/evm/gas/arbitrum_estimator_test.go b/core/chains/evm/gas/arbitrum_estimator_test.go index b1e7efc887e..51d12e1cf9b 100644 --- a/core/chains/evm/gas/arbitrum_estimator_test.go +++ b/core/chains/evm/gas/arbitrum_estimator_test.go @@ -2,7 +2,7 @@ package gas_test import ( "bytes" - "fmt" + "encoding/hex" "math/big" "testing" @@ -80,7 +80,7 @@ func TestArbitrumEstimator(t *testing.T) { callMsg := args.Get(1).(ethereum.CallMsg) blockNumber := args.Get(2).(*big.Int) assert.Equal(t, rollups.ArbGasInfoAddress, callMsg.To.String()) - assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, fmt.Sprintf("%x", callMsg.Data)) + assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, hex.EncodeToString(callMsg.Data)) assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(zeros.Bytes(), nil) @@ -108,7 +108,7 @@ func TestArbitrumEstimator(t *testing.T) { callMsg := args.Get(1).(ethereum.CallMsg) blockNumber := args.Get(2).(*big.Int) assert.Equal(t, rollups.ArbGasInfoAddress, callMsg.To.String()) - assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, fmt.Sprintf("%x", callMsg.Data)) + assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, hex.EncodeToString(callMsg.Data)) assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(zeros.Bytes(), nil) @@ -135,7 +135,7 @@ func TestArbitrumEstimator(t *testing.T) { callMsg := args.Get(1).(ethereum.CallMsg) blockNumber := args.Get(2).(*big.Int) assert.Equal(t, rollups.ArbGasInfoAddress, callMsg.To.String()) - assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, fmt.Sprintf("%x", callMsg.Data)) + assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, hex.EncodeToString(callMsg.Data)) assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(zeros.Bytes(), nil) @@ -168,7 +168,7 @@ func TestArbitrumEstimator(t *testing.T) { callMsg := args.Get(1).(ethereum.CallMsg) blockNumber := args.Get(2).(*big.Int) assert.Equal(t, rollups.ArbGasInfoAddress, callMsg.To.String()) - assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, fmt.Sprintf("%x", callMsg.Data)) + assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, hex.EncodeToString(callMsg.Data)) assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(zeros.Bytes(), nil) @@ -225,7 +225,7 @@ func TestArbitrumEstimator(t *testing.T) { callMsg := args.Get(1).(ethereum.CallMsg) blockNumber := args.Get(2).(*big.Int) assert.Equal(t, rollups.ArbGasInfoAddress, callMsg.To.String()) - assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, fmt.Sprintf("%x", callMsg.Data)) + assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, hex.EncodeToString(callMsg.Data)) assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(b.Bytes(), nil) @@ -261,7 +261,7 @@ func TestArbitrumEstimator(t *testing.T) { callMsg := args.Get(1).(ethereum.CallMsg) blockNumber := args.Get(2).(*big.Int) assert.Equal(t, rollups.ArbGasInfoAddress, callMsg.To.String()) - assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, fmt.Sprintf("%x", callMsg.Data)) + assert.Equal(t, rollups.ArbGasInfo_getPricesInArbGas, hex.EncodeToString(callMsg.Data)) assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(b.Bytes(), nil) diff --git a/core/chains/evm/gas/block_history_estimator_test.go b/core/chains/evm/gas/block_history_estimator_test.go index e3df261f2cf..82458d84e17 100644 --- a/core/chains/evm/gas/block_history_estimator_test.go +++ b/core/chains/evm/gas/block_history_estimator_test.go @@ -107,8 +107,8 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { require.NoError(t, err) assert.Len(t, gas.GetRollingBlockHistory(bhe), 2) - assert.Equal(t, int(gas.GetRollingBlockHistory(bhe)[0].Number), 41) - assert.Equal(t, int(gas.GetRollingBlockHistory(bhe)[1].Number), 42) + assert.Equal(t, 41, int(gas.GetRollingBlockHistory(bhe)[0].Number)) + assert.Equal(t, 42, int(gas.GetRollingBlockHistory(bhe)[1].Number)) assert.Equal(t, assets.NewWeiI(420), gas.GetLatestBaseFee(bhe)) }) @@ -152,7 +152,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { require.NoError(t, err) require.Len(t, gas.GetRollingBlockHistory(bhe), 1) - assert.Equal(t, int(gas.GetRollingBlockHistory(bhe)[0].Number), 42) + assert.Equal(t, 42, int(gas.GetRollingBlockHistory(bhe)[0].Number)) assert.Equal(t, assets.NewWeiI(420), gas.GetLatestBaseFee(bhe)) }) @@ -419,7 +419,7 @@ func TestBlockHistoryEstimator_FetchBlocks(t *testing.T) { // 42 is missing because the fetch errored assert.Equal(t, 43, int(gas.GetRollingBlockHistory(bhe)[1].Number)) assert.Len(t, gas.GetRollingBlockHistory(bhe)[0].Transactions, 2) - assert.Len(t, gas.GetRollingBlockHistory(bhe)[1].Transactions, 0) + assert.Empty(t, gas.GetRollingBlockHistory(bhe)[1].Transactions) // On new fetch, rolls over the history and drops the old heads @@ -450,7 +450,7 @@ func TestBlockHistoryEstimator_FetchBlocks(t *testing.T) { assert.Equal(t, 43, int(gas.GetRollingBlockHistory(bhe)[1].Number)) assert.Equal(t, 44, int(gas.GetRollingBlockHistory(bhe)[2].Number)) assert.Len(t, gas.GetRollingBlockHistory(bhe)[0].Transactions, 1) - assert.Len(t, gas.GetRollingBlockHistory(bhe)[1].Transactions, 0) + assert.Empty(t, gas.GetRollingBlockHistory(bhe)[1].Transactions) assert.Len(t, gas.GetRollingBlockHistory(bhe)[2].Transactions, 1) }) @@ -695,7 +695,7 @@ func TestBlockHistoryEstimator_FetchBlocks(t *testing.T) { assert.Equal(t, 42, int(gas.GetRollingBlockHistory(bhe)[0].Number)) assert.Equal(t, 43, int(gas.GetRollingBlockHistory(bhe)[1].Number)) assert.Len(t, gas.GetRollingBlockHistory(bhe)[0].Transactions, 1) - assert.Len(t, gas.GetRollingBlockHistory(bhe)[1].Transactions, 0) + assert.Empty(t, gas.GetRollingBlockHistory(bhe)[1].Transactions) }) } @@ -1417,19 +1417,19 @@ func TestBlockHistoryEstimator_IsUsable(t *testing.T) { } t.Run("returns false if transaction has 0 gas limit", func(t *testing.T) { tx := evmtypes.Transaction{Type: 0x0, GasPrice: assets.NewWeiI(10), GasLimit: 0, Hash: utils.NewHash()} - assert.Equal(t, false, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) + assert.False(t, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) }) t.Run("returns false if transaction gas limit is nil and tx type is 0x0", func(t *testing.T) { tx := evmtypes.Transaction{Type: 0x0, GasPrice: nil, GasLimit: 42, Hash: utils.NewHash()} - assert.Equal(t, false, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) + assert.False(t, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) }) t.Run("returns false if transaction is of type 0x7e only on Optimism", func(t *testing.T) { tx := evmtypes.Transaction{Type: 0x7e, GasPrice: assets.NewWeiI(10), GasLimit: 42, Hash: utils.NewHash()} - assert.Equal(t, false, bhe.IsUsable(tx, block, chaintype.ChainOptimismBedrock, geCfg.PriceMin(), logger.Test(t))) + assert.False(t, bhe.IsUsable(tx, block, chaintype.ChainOptimismBedrock, geCfg.PriceMin(), logger.Test(t))) - assert.Equal(t, true, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) + assert.True(t, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) }) t.Run("returns false if transaction is of type 0x7c, 0x7b, or 0x7e only on Celo", func(t *testing.T) { @@ -1449,39 +1449,39 @@ func TestBlockHistoryEstimator_IsUsable(t *testing.T) { t.Run("returns false if transaction is of type 0x16 only on WeMix", func(t *testing.T) { tx := evmtypes.Transaction{Type: 0x16, GasPrice: assets.NewWeiI(10), GasLimit: 42, Hash: utils.NewHash()} - assert.Equal(t, false, bhe.IsUsable(tx, block, chaintype.ChainWeMix, geCfg.PriceMin(), logger.Test(t))) + assert.False(t, bhe.IsUsable(tx, block, chaintype.ChainWeMix, geCfg.PriceMin(), logger.Test(t))) }) t.Run("returns false if transaction has base fee higher than the gas price only on Celo", func(t *testing.T) { tx := evmtypes.Transaction{Type: 0x0, GasPrice: assets.NewWeiI(10), GasLimit: 42, Hash: utils.NewHash()} - assert.Equal(t, false, bhe.IsUsable(tx, block, chaintype.ChainCelo, geCfg.PriceMin(), logger.Test(t))) + assert.False(t, bhe.IsUsable(tx, block, chaintype.ChainCelo, geCfg.PriceMin(), logger.Test(t))) tx2 := evmtypes.Transaction{Type: 0x2, MaxPriorityFeePerGas: assets.NewWeiI(200), MaxFeePerGas: assets.NewWeiI(250), GasPrice: assets.NewWeiI(50), GasLimit: 42, Hash: utils.NewHash()} - assert.Equal(t, false, bhe.IsUsable(tx, block, chaintype.ChainCelo, geCfg.PriceMin(), logger.Test(t))) + assert.False(t, bhe.IsUsable(tx, block, chaintype.ChainCelo, geCfg.PriceMin(), logger.Test(t))) - assert.Equal(t, true, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) - assert.Equal(t, true, bhe.IsUsable(tx2, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) + assert.True(t, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) + assert.True(t, bhe.IsUsable(tx2, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) }) t.Run("returns false if transaction is of type 0x71 or 0xff only on zkSync", func(t *testing.T) { tx := evmtypes.Transaction{Type: 0x71, GasPrice: assets.NewWeiI(10), GasLimit: 42, Hash: utils.NewHash()} - assert.Equal(t, false, bhe.IsUsable(tx, block, chaintype.ChainZkSync, geCfg.PriceMin(), logger.Test(t))) + assert.False(t, bhe.IsUsable(tx, block, chaintype.ChainZkSync, geCfg.PriceMin(), logger.Test(t))) tx.Type = 0x02 - assert.Equal(t, true, bhe.IsUsable(tx, block, chaintype.ChainZkSync, geCfg.PriceMin(), logger.Test(t))) + assert.True(t, bhe.IsUsable(tx, block, chaintype.ChainZkSync, geCfg.PriceMin(), logger.Test(t))) tx.Type = 0xff - assert.Equal(t, false, bhe.IsUsable(tx, block, chaintype.ChainZkSync, geCfg.PriceMin(), logger.Test(t))) + assert.False(t, bhe.IsUsable(tx, block, chaintype.ChainZkSync, geCfg.PriceMin(), logger.Test(t))) - assert.Equal(t, true, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) + assert.True(t, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) }) t.Run("returns false if transaction is of type 0x7e only on Scroll", func(t *testing.T) { tx := evmtypes.Transaction{Type: 0x7e, GasPrice: assets.NewWeiI(10), GasLimit: 42, Hash: utils.NewHash()} - assert.Equal(t, false, bhe.IsUsable(tx, block, chaintype.ChainScroll, geCfg.PriceMin(), logger.Test(t))) + assert.False(t, bhe.IsUsable(tx, block, chaintype.ChainScroll, geCfg.PriceMin(), logger.Test(t))) - assert.Equal(t, true, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) + assert.True(t, bhe.IsUsable(tx, block, defaultChainType, geCfg.PriceMin(), logger.Test(t))) }) } diff --git a/core/chains/evm/gas/fee_history_estimator.go b/core/chains/evm/gas/fee_history_estimator.go index 211528a1a7d..8c0d1036446 100644 --- a/core/chains/evm/gas/fee_history_estimator.go +++ b/core/chains/evm/gas/fee_history_estimator.go @@ -2,6 +2,7 @@ package gas import ( "context" + "errors" "fmt" "math/big" "strconv" @@ -201,7 +202,7 @@ func (f *FeeHistoryEstimator) getGasPrice() (*assets.Wei, error) { f.gasPriceMu.RLock() defer f.gasPriceMu.RUnlock() if f.gasPrice == nil { - return f.gasPrice, fmt.Errorf("gas price not set") + return f.gasPrice, errors.New("gas price not set") } return f.gasPrice, nil } @@ -303,7 +304,7 @@ func (f *FeeHistoryEstimator) getDynamicPrice() (fee DynamicFee, err error) { f.dynamicPriceMu.RLock() defer f.dynamicPriceMu.RUnlock() if f.dynamicPrice.GasFeeCap == nil || f.dynamicPrice.GasTipCap == nil { - return fee, fmt.Errorf("dynamic price not set") + return fee, errors.New("dynamic price not set") } return f.dynamicPrice, nil } @@ -352,7 +353,7 @@ func (f *FeeHistoryEstimator) BumpDynamicFee(ctx context.Context, originalFee Dy f.refreshCh <- struct{}{} bumped, err = f.GetDynamicFee(ctx, maxPrice) }) { - return bumped, fmt.Errorf("estimator not started") + return bumped, errors.New("estimator not started") } return bumped, err } @@ -430,7 +431,7 @@ func (f *FeeHistoryEstimator) getPriorityFeeThreshold() (*assets.Wei, error) { f.priorityFeeThresholdMu.RLock() defer f.priorityFeeThresholdMu.RUnlock() if f.priorityFeeThreshold == nil { - return f.priorityFeeThreshold, fmt.Errorf("priorityFeeThreshold not set") + return f.priorityFeeThreshold, errors.New("priorityFeeThreshold not set") } return f.priorityFeeThreshold, nil } diff --git a/core/chains/evm/gas/fee_history_estimator_test.go b/core/chains/evm/gas/fee_history_estimator_test.go index 7d66b9375d7..21f2b0aa64d 100644 --- a/core/chains/evm/gas/fee_history_estimator_test.go +++ b/core/chains/evm/gas/fee_history_estimator_test.go @@ -509,7 +509,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { servicetest.RunHealthy(t, u) bumpedFee, err := u.BumpDynamicFee(tests.Context(t), originalFee, globalMaxPrice, nil) assert.NoError(t, err) - assert.Equal(t, assets.NewWeiI(0), (*assets.Wei)(maxPriorityFeePerGas)) + assert.Equal(t, (*assets.Wei)(maxPriorityFeePerGas), assets.NewWeiI(0)) assert.Equal(t, maxFeePerGas, bumpedFee.GasFeeCap) }) } diff --git a/core/chains/evm/gas/models.go b/core/chains/evm/gas/models.go index 2d6fe971d9c..90890f18a11 100644 --- a/core/chains/evm/gas/models.go +++ b/core/chains/evm/gas/models.go @@ -56,7 +56,7 @@ type feeEstimatorClient interface { func NewEstimator(lggr logger.Logger, ethClient feeEstimatorClient, chaintype chaintype.ChainType, chainID *big.Int, geCfg evmconfig.GasEstimator, clientsByChainID map[string]rollups.DAClient) (EvmFeeEstimator, error) { bh := geCfg.BlockHistory() s := geCfg.Mode() - lggr.Infow(fmt.Sprintf("Initializing EVM gas estimator in mode: %s", s), + lggr.Infow("Initializing EVM gas estimator in mode: "+s, "estimatorMode", s, "batchSize", bh.BatchSize(), "blockDelay", bh.BlockDelay(), diff --git a/core/chains/evm/gas/models_test.go b/core/chains/evm/gas/models_test.go index 3cc83ec7034..36794c3b4aa 100644 --- a/core/chains/evm/gas/models_test.go +++ b/core/chains/evm/gas/models_test.go @@ -245,8 +245,8 @@ func TestWrappedEvmEstimator(t *testing.T) { estimator := gas.NewEvmFeeEstimator(lggr, getEst, false, geCfg, nil) report := estimator.HealthReport() require.True(t, pkgerrors.Is(report[evmEstimatorKey], evmEstimatorError)) - require.Nil(t, report[oracleKey]) - require.NotNil(t, report[mockEstimatorName]) + require.NoError(t, report[oracleKey]) + require.Error(t, report[mockEstimatorName]) evmEstimator.On("L1Oracle").Return(oracle).Once() @@ -254,7 +254,7 @@ func TestWrappedEvmEstimator(t *testing.T) { report = estimator.HealthReport() require.True(t, pkgerrors.Is(report[evmEstimatorKey], evmEstimatorError)) require.True(t, pkgerrors.Is(report[oracleKey], oracleError)) - require.NotNil(t, report[mockEstimatorName]) + require.Error(t, report[mockEstimatorName]) }) t.Run("GetFee, estimate gas limit enabled, succeeds", func(t *testing.T) { diff --git a/core/chains/evm/gas/rollups/arbitrum_l1_oracle.go b/core/chains/evm/gas/rollups/arbitrum_l1_oracle.go index 3182d920178..092f40175c3 100644 --- a/core/chains/evm/gas/rollups/arbitrum_l1_oracle.go +++ b/core/chains/evm/gas/rollups/arbitrum_l1_oracle.go @@ -2,6 +2,7 @@ package rollups import ( "context" + "errors" "fmt" "math" "math/big" @@ -200,15 +201,15 @@ func (o *arbitrumL1Oracle) GasPrice(_ context.Context) (l1GasPrice *assets.Wei, o.l1GasPriceMu.RUnlock() }) if !ok { - return l1GasPrice, fmt.Errorf("L1GasOracle is not started; cannot estimate gas") + return l1GasPrice, errors.New("L1GasOracle is not started; cannot estimate gas") } if l1GasPrice == nil { - return l1GasPrice, fmt.Errorf("failed to get l1 gas price; gas price not set") + return l1GasPrice, errors.New("failed to get l1 gas price; gas price not set") } // Validate the price has been updated within the pollPeriod * 2 // Allowing double the poll period before declaring the price stale to give ample time for the refresh to process if time.Since(timestamp) > o.pollPeriod*2 { - return l1GasPrice, fmt.Errorf("gas price is stale") + return l1GasPrice, errors.New("gas price is stale") } return } diff --git a/core/chains/evm/gas/rollups/l1_oracle_test.go b/core/chains/evm/gas/rollups/l1_oracle_test.go index 9c36878a153..e999ff1b171 100644 --- a/core/chains/evm/gas/rollups/l1_oracle_test.go +++ b/core/chains/evm/gas/rollups/l1_oracle_test.go @@ -51,7 +51,7 @@ func TestL1Oracle(t *testing.T) { oracle, err := NewL1GasOracle(logger.Test(t), ethClient, chaintype.ChainArbitrum, daOracle, nil) require.NoError(t, err) assert.NotNil(t, oracle) - assert.Equal(t, oracle.Name(), "L1GasOracle(arbitrum)") + assert.Equal(t, "L1GasOracle(arbitrum)", oracle.Name()) }) t.Run("DAOracle config is not nil, but OracleType is empty, falls back to using chainType ZKSync", func(t *testing.T) { @@ -61,7 +61,7 @@ func TestL1Oracle(t *testing.T) { oracle, err := NewL1GasOracle(logger.Test(t), ethClient, chaintype.ChainZkSync, daOracle, nil) require.NoError(t, err) assert.NotNil(t, oracle) - assert.Equal(t, oracle.Name(), "L1GasOracle(zkSync)") + assert.Equal(t, "L1GasOracle(zkSync)", oracle.Name()) }) } diff --git a/core/chains/evm/gas/rollups/op_l1_oracle.go b/core/chains/evm/gas/rollups/op_l1_oracle.go index cd6f2347953..c5bf853051a 100644 --- a/core/chains/evm/gas/rollups/op_l1_oracle.go +++ b/core/chains/evm/gas/rollups/op_l1_oracle.go @@ -256,15 +256,15 @@ func (o *optimismL1Oracle) GasPrice(_ context.Context) (l1GasPrice *assets.Wei, o.l1GasPriceMu.RUnlock() }) if !ok { - return l1GasPrice, fmt.Errorf("L1GasOracle is not started; cannot estimate gas") + return l1GasPrice, errors.New("L1GasOracle is not started; cannot estimate gas") } if l1GasPrice == nil { - return l1GasPrice, fmt.Errorf("failed to get l1 gas price; gas price not set") + return l1GasPrice, errors.New("failed to get l1 gas price; gas price not set") } // Validate the price has been updated within the pollPeriod * 2 // Allowing double the poll period before declaring the price stale to give ample time for the refresh to process if time.Since(timestamp) > o.pollPeriod*2 { - return l1GasPrice, fmt.Errorf("gas price is stale") + return l1GasPrice, errors.New("gas price is stale") } return } diff --git a/core/chains/evm/gas/rollups/op_l1_oracle_test.go b/core/chains/evm/gas/rollups/op_l1_oracle_test.go index 75450d72522..a31b171684f 100644 --- a/core/chains/evm/gas/rollups/op_l1_oracle_test.go +++ b/core/chains/evm/gas/rollups/op_l1_oracle_test.go @@ -1,7 +1,7 @@ package rollups import ( - "fmt" + "errors" "math/big" "strings" "testing" @@ -74,7 +74,7 @@ func TestOPL1Oracle_ReadV1GasPrice(t *testing.T) { ethClient := mocks.NewL1OracleClient(t) ethClient.On("BatchCallContext", mock.Anything, mock.IsType([]rpc.BatchElem{})).Run(func(args mock.Arguments) { rpcElements := args.Get(1).([]rpc.BatchElem) - require.Equal(t, 2, len(rpcElements)) + require.Len(t, rpcElements, 2) for _, rE := range rpcElements { require.Equal(t, "eth_call", rE.Method) require.Equal(t, oracleAddress, rE.Args[0].(map[string]interface{})["to"]) @@ -84,12 +84,12 @@ func TestOPL1Oracle_ReadV1GasPrice(t *testing.T) { require.Equal(t, hexutil.Bytes(isEcotoneCalldata), rpcElements[1].Args[0].(map[string]interface{})["data"]) isUpgraded := "0x0000000000000000000000000000000000000000000000000000000000000000" if tc.isFjordError { - rpcElements[0].Error = fmt.Errorf("test error") + rpcElements[0].Error = errors.New("test error") } else { rpcElements[0].Result = &isUpgraded } if tc.isEcotoneError { - rpcElements[1].Error = fmt.Errorf("test error") + rpcElements[1].Error = errors.New("test error") } else { rpcElements[1].Result = &isUpgraded } @@ -136,7 +136,7 @@ func setupUpgradeCheck(t *testing.T, oracleAddress string, isFjord, isEcotone bo ethClient := mocks.NewL1OracleClient(t) ethClient.On("BatchCallContext", mock.Anything, mock.IsType([]rpc.BatchElem{})).Run(func(args mock.Arguments) { rpcElements := args.Get(1).([]rpc.BatchElem) - require.Equal(t, 2, len(rpcElements)) + require.Len(t, rpcElements, 2) for _, rE := range rpcElements { require.Equal(t, "eth_call", rE.Method) require.Equal(t, oracleAddress, rE.Args[0].(map[string]interface{})["to"]) @@ -185,7 +185,7 @@ func mockBatchContractCall(t *testing.T, ethClient *mocks.L1OracleClient, oracle ethClient.On("BatchCallContext", mock.Anything, mock.IsType([]rpc.BatchElem{})).Run(func(args mock.Arguments) { rpcElements := args.Get(1).([]rpc.BatchElem) - require.Equal(t, 5, len(rpcElements)) + require.Len(t, rpcElements, 5) for _, rE := range rpcElements { require.Equal(t, "eth_call", rE.Method) @@ -255,7 +255,7 @@ func TestOPL1Oracle_CalculateEcotoneGasPrice(t *testing.T) { t.Run("fetching Ecotone price but rpc parent call errors", func(t *testing.T) { ethClient := setupUpgradeCheck(t, oracleAddress, false, true) - ethClient.On("BatchCallContext", mock.Anything, mock.IsType([]rpc.BatchElem{})).Return(fmt.Errorf("revert")).Once() + ethClient.On("BatchCallContext", mock.Anything, mock.IsType([]rpc.BatchElem{})).Return(errors.New("revert")).Once() daOracle := CreateTestDAOracle(t, toml.DAOracleOPStack, oracleAddress, "") oracle, err := NewOpStackL1GasOracle(logger.Test(t), ethClient, chaintype.ChainOptimismBedrock, daOracle) @@ -270,7 +270,7 @@ func TestOPL1Oracle_CalculateEcotoneGasPrice(t *testing.T) { rpcElements := args.Get(1).([]rpc.BatchElem) res := common.BigToHash(baseFee).Hex() rpcElements[0].Result = &res - rpcElements[1].Error = fmt.Errorf("revert") + rpcElements[1].Error = errors.New("revert") }).Return(nil).Once() daOracle := CreateTestDAOracle(t, toml.DAOracleOPStack, oracleAddress, "") @@ -323,7 +323,7 @@ func TestOPL1Oracle_CalculateFjordGasPrice(t *testing.T) { t.Run("fetching Fjord price but rpc parent call errors", func(t *testing.T) { ethClient := setupUpgradeCheck(t, oracleAddress, true, true) - ethClient.On("BatchCallContext", mock.Anything, mock.IsType([]rpc.BatchElem{})).Return(fmt.Errorf("revert")).Once() + ethClient.On("BatchCallContext", mock.Anything, mock.IsType([]rpc.BatchElem{})).Return(errors.New("revert")).Once() daOracle := CreateTestDAOracle(t, toml.DAOracleOPStack, oracleAddress, "") oracle, err := NewOpStackL1GasOracle(logger.Test(t), ethClient, chaintype.ChainOptimismBedrock, daOracle) @@ -338,7 +338,7 @@ func TestOPL1Oracle_CalculateFjordGasPrice(t *testing.T) { rpcElements := args.Get(1).([]rpc.BatchElem) res := common.BigToHash(baseFee).Hex() rpcElements[0].Result = &res - rpcElements[1].Error = fmt.Errorf("revert") + rpcElements[1].Error = errors.New("revert") }).Return(nil).Once() daOracle := CreateTestDAOracle(t, toml.DAOracleOPStack, oracleAddress, "") diff --git a/core/chains/evm/gas/rollups/zkSync_l1_oracle.go b/core/chains/evm/gas/rollups/zkSync_l1_oracle.go index 6edfb8cd28b..d0d500c3c46 100644 --- a/core/chains/evm/gas/rollups/zkSync_l1_oracle.go +++ b/core/chains/evm/gas/rollups/zkSync_l1_oracle.go @@ -3,6 +3,7 @@ package rollups import ( "context" "encoding/hex" + "errors" "fmt" "math/big" "sync" @@ -163,15 +164,15 @@ func (o *zkSyncL1Oracle) GasPrice(_ context.Context) (l1GasPrice *assets.Wei, er o.l1GasPriceMu.RUnlock() }) if !ok { - return l1GasPrice, fmt.Errorf("L1GasOracle is not started; cannot estimate gas") + return l1GasPrice, errors.New("L1GasOracle is not started; cannot estimate gas") } if l1GasPrice == nil { - return l1GasPrice, fmt.Errorf("failed to get l1 gas price; gas price not set") + return l1GasPrice, errors.New("failed to get l1 gas price; gas price not set") } // Validate the price has been updated within the pollPeriod * 2 // Allowing double the poll period before declaring the price stale to give ample time for the refresh to process if time.Since(timestamp) > o.pollPeriod*2 { - return l1GasPrice, fmt.Errorf("gas price is stale") + return l1GasPrice, errors.New("gas price is stale") } return } diff --git a/core/chains/evm/headtracker/head_saver_test.go b/core/chains/evm/headtracker/head_saver_test.go index 20eb40e5ea0..2b576352970 100644 --- a/core/chains/evm/headtracker/head_saver_test.go +++ b/core/chains/evm/headtracker/head_saver_test.go @@ -140,7 +140,7 @@ func TestHeadSaver_Load(t *testing.T) { require.NotNil(t, latestHead) require.Equal(t, int64(5), latestHead.Number) require.Equal(t, uint32(5), latestHead.ChainLength()) - require.Greater(t, latestHead.EarliestHeadInChain().BlockNumber(), int64(0)) + require.Positive(t, latestHead.EarliestHeadInChain().BlockNumber()) } // load all from [h5-historyDepth, h5] diff --git a/core/chains/evm/headtracker/head_tracker_test.go b/core/chains/evm/headtracker/head_tracker_test.go index 140ab76aa41..3724187d6f8 100644 --- a/core/chains/evm/headtracker/head_tracker_test.go +++ b/core/chains/evm/headtracker/head_tracker_test.go @@ -3,7 +3,6 @@ package headtracker_test import ( "context" "errors" - "fmt" "math/big" "slices" "sync" @@ -68,10 +67,10 @@ func TestHeadTracker_New(t *testing.T) { Return(nil, mockEth.NewSub(t), nil) orm := headtracker.NewORM(*testutils.FixtureChainID, db) - assert.Nil(t, orm.IdempotentInsertHead(tests.Context(t), testutils.Head(1))) + assert.NoError(t, orm.IdempotentInsertHead(tests.Context(t), testutils.Head(1))) last := testutils.Head(16) - assert.Nil(t, orm.IdempotentInsertHead(tests.Context(t), last)) - assert.Nil(t, orm.IdempotentInsertHead(tests.Context(t), testutils.Head(10))) + assert.NoError(t, orm.IdempotentInsertHead(tests.Context(t), last)) + assert.NoError(t, orm.IdempotentInsertHead(tests.Context(t), testutils.Head(10))) evmcfg := testutils.NewTestChainScopedConfig(t, nil) ht := createHeadTracker(t, ethClient, evmcfg.EVM(), evmcfg.EVM().HeadTracker(), orm) @@ -95,11 +94,11 @@ func TestHeadTracker_MarkFinalized_MarksAndTrimsTable(t *testing.T) { orm := headtracker.NewORM(*testutils.FixtureChainID, db) for idx := 0; idx < 200; idx++ { - assert.Nil(t, orm.IdempotentInsertHead(tests.Context(t), testutils.Head(idx))) + assert.NoError(t, orm.IdempotentInsertHead(tests.Context(t), testutils.Head(idx))) } latest := testutils.Head(201) - assert.Nil(t, orm.IdempotentInsertHead(tests.Context(t), latest)) + assert.NoError(t, orm.IdempotentInsertHead(tests.Context(t), latest)) ht := createHeadTracker(t, ethClient, config.EVM(), config.EVM().HeadTracker(), orm) _, err := ht.headSaver.Load(tests.Context(t), latest.Number) @@ -162,7 +161,7 @@ func TestHeadTracker_Get(t *testing.T) { } if test.initial != nil { - assert.Nil(t, orm.IdempotentInsertHead(tests.Context(t), test.initial)) + assert.NoError(t, orm.IdempotentInsertHead(tests.Context(t), test.initial)) } ht := createHeadTracker(t, ethClient, config.EVM(), config.EVM().HeadTracker(), orm) @@ -462,7 +461,7 @@ func TestHeadTracker_ResubscribeOnSubscriptionError(t *testing.T) { g.Eventually(func() bool { report := ht.headTracker.HealthReport() return !slices.ContainsFunc(maps.Values(report), func(e error) bool { return e != nil }) - }, 5*time.Second, tests.TestInterval).Should(gomega.Equal(true)) + }, 5*time.Second, tests.TestInterval).Should(gomega.BeTrue()) // trigger reconnect loop headers.CloseCh() @@ -533,7 +532,7 @@ func TestHeadTracker_Start_LoadsLatestChain(t *testing.T) { h, err := orm.LatestHead(tests.Context(t)) require.NoError(t, err) require.NotNil(t, h) - assert.Equal(t, h.Number, int64(3)) + assert.Equal(t, int64(3), h.Number) } func TestHeadTracker_SwitchesToLongestChainWithHeadSamplingEnabled(t *testing.T) { @@ -1186,7 +1185,7 @@ func TestHeadTracker_LatestAndFinalizedBlock(t *testing.T) { htu := newHeadTrackerUniverse(t, opts{FinalityTagEnabled: true}) htu.ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(h13, nil).Once() const expectedError = "failed to get latest finalized block" - htu.ethClient.On("LatestFinalizedBlock", mock.Anything).Return(nil, fmt.Errorf(expectedError)).Once() + htu.ethClient.On("LatestFinalizedBlock", mock.Anything).Return(nil, errors.New(expectedError)).Once() _, _, err := htu.headTracker.LatestAndFinalizedBlock(ctx) require.ErrorContains(t, err, expectedError) @@ -1326,7 +1325,7 @@ func (u *headTrackerUniverse) Start(t *testing.T) { g.Eventually(func() bool { report := u.headBroadcaster.HealthReport() return !slices.ContainsFunc(maps.Values(report), func(e error) bool { return e != nil }) - }, 5*time.Second, tests.TestInterval).Should(gomega.Equal(true)) + }, 5*time.Second, tests.TestInterval).Should(gomega.BeTrue()) t.Cleanup(func() { u.Stop(t) diff --git a/core/chains/evm/headtracker/orm_test.go b/core/chains/evm/headtracker/orm_test.go index 225722e27e1..3c1ad2064ec 100644 --- a/core/chains/evm/headtracker/orm_test.go +++ b/core/chains/evm/headtracker/orm_test.go @@ -59,7 +59,7 @@ func TestORM_TrimOldHeads(t *testing.T) { require.NoError(t, err) // uncle block was loaded too - require.Equal(t, 6, len(heads)) + require.Len(t, heads, 6) for i := 0; i < 5; i++ { require.LessOrEqual(t, int64(5), heads[i].Number) } @@ -107,6 +107,6 @@ func TestORM_LatestHeads_NoRows(t *testing.T) { heads, err := orm.LatestHeads(tests.Context(t), 100) - require.Zero(t, len(heads)) + require.Empty(t, heads) require.NoError(t, err) } diff --git a/core/chains/evm/headtracker/simulated_head_tracker.go b/core/chains/evm/headtracker/simulated_head_tracker.go index 62bb4968c2f..09d0007dbc7 100644 --- a/core/chains/evm/headtracker/simulated_head_tracker.go +++ b/core/chains/evm/headtracker/simulated_head_tracker.go @@ -3,7 +3,6 @@ package headtracker import ( "context" "errors" - "fmt" "math/big" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" @@ -32,7 +31,7 @@ func (ht *simulatedHeadTracker) LatestAndFinalizedBlock(ctx context.Context) (*e } if latest == nil { - return nil, nil, fmt.Errorf("expected latest block to be valid") + return nil, nil, errors.New("expected latest block to be valid") } var finalizedBlock *evmtypes.Head @@ -43,11 +42,11 @@ func (ht *simulatedHeadTracker) LatestAndFinalizedBlock(ctx context.Context) (*e } if err != nil { - return nil, nil, fmt.Errorf("simulatedHeadTracker failed to get finalized block") + return nil, nil, errors.New("simulatedHeadTracker failed to get finalized block") } if finalizedBlock == nil { - return nil, nil, fmt.Errorf("expected finalized block to be valid") + return nil, nil, errors.New("expected finalized block to be valid") } return latest, finalizedBlock, nil diff --git a/core/chains/evm/log/integration_test.go b/core/chains/evm/log/integration_test.go index 05d9bf7d30c..c80cdf3c2c1 100644 --- a/core/chains/evm/log/integration_test.go +++ b/core/chains/evm/log/integration_test.go @@ -690,7 +690,7 @@ func TestBroadcaster_BroadcastsAtCorrectHeights(t *testing.T) { } assert.Equal(t, len(logsOnBlocks), len(expectedLogsOnBlocks)) - require.Equal(t, logsOnBlocks, expectedLogsOnBlocks) + require.Equal(t, expectedLogsOnBlocks, logsOnBlocks) } func TestBroadcaster_DeletesOldLogsAfterNumberOfHeads(t *testing.T) { @@ -735,13 +735,13 @@ func TestBroadcaster_DeletesOldLogsAfterNumberOfHeads(t *testing.T) { // the new listener should still receive 2 of the 3 logs helper.requireBroadcastCount(8) - require.Equal(t, 2, len(listener3.received.getUniqueLogs())) + require.Len(t, listener3.received.getUniqueLogs(), 2) helper.register(listener4, contract1, 1) <-cltest.SimulateIncomingHeads(t, blocks.Slice(9, 12), helper.lb) // but this one should receive none - require.Equal(t, 0, len(listener4.received.getUniqueLogs())) + require.Empty(t, listener4.received.getUniqueLogs()) } func TestBroadcaster_DeletesOldLogsOnlyAfterFinalityDepth(t *testing.T) { @@ -786,13 +786,13 @@ func TestBroadcaster_DeletesOldLogsOnlyAfterFinalityDepth(t *testing.T) { // the new listener should still receive 3 logs because of finality depth being higher than max NumConfirmations helper.requireBroadcastCount(9) - require.Equal(t, 3, len(listener3.received.getUniqueLogs())) + require.Len(t, listener3.received.getUniqueLogs(), 3) helper.register(listener4, contract1, 1) <-cltest.SimulateIncomingHeads(t, blocks.Slice(10, 12), helper.lb) // but this one should receive none - require.Equal(t, 0, len(listener4.received.getUniqueLogs())) + require.Empty(t, listener4.received.getUniqueLogs()) } func TestBroadcaster_FilterByTopicValues(t *testing.T) { diff --git a/core/chains/evm/log/registrations_test.go b/core/chains/evm/log/registrations_test.go index 8c0beaa9379..56f63183e5f 100644 --- a/core/chains/evm/log/registrations_test.go +++ b/core/chains/evm/log/registrations_test.go @@ -246,6 +246,6 @@ func TestUnit_Registrations_addSubscriber_removeSubscriber(t *testing.T) { needsResub = r.removeSubscriber(sub5) // Nothing left, need to refresh subscriptions assert.True(t, needsResub) - assert.Len(t, r.registeredSubs, 0) + assert.Empty(t, r.registeredSubs) }) } diff --git a/core/chains/evm/logpoller/log_poller.go b/core/chains/evm/logpoller/log_poller.go index 725fdbda63c..bcb26f481ac 100644 --- a/core/chains/evm/logpoller/log_poller.go +++ b/core/chains/evm/logpoller/log_poller.go @@ -1547,7 +1547,7 @@ func (lp *logPoller) FindLCA(ctx context.Context) (*LogPollerBlock, error) { } if latest == nil || oldest == nil { - return nil, fmt.Errorf("expected at least one block to be present in DB") + return nil, errors.New("expected at least one block to be present in DB") } lp.lggr.Debugf("Received request to find LCA. Searching in range [%d, %d]", oldest.BlockNumber, latest.BlockNumber) @@ -1611,7 +1611,7 @@ func (lp *logPoller) FindLCA(ctx context.Context) (*LogPollerBlock, error) { } if !found { - return nil, fmt.Errorf("failed to find LCA, this means that whole database LogPoller state was reorged out of chain or RPC/Core node is misconfigured") + return nil, errors.New("failed to find LCA, this means that whole database LogPoller state was reorged out of chain or RPC/Core node is misconfigured") } lcaBlockNumber := latest.BlockNumber - int64(lcaI) diff --git a/core/chains/evm/logpoller/log_poller_internal_test.go b/core/chains/evm/logpoller/log_poller_internal_test.go index 620bbf14f41..c96c776d9c5 100644 --- a/core/chains/evm/logpoller/log_poller_internal_test.go +++ b/core/chains/evm/logpoller/log_poller_internal_test.go @@ -80,7 +80,7 @@ func TestLogPoller_RegisterFilter(t *testing.T) { // We expect a zero Filter if nothing registered yet. f := lp.Filter(nil, nil, nil) - require.Equal(t, 1, len(f.Addresses)) + require.Len(t, f.Addresses, 1) assert.Equal(t, common.HexToAddress("0x0000000000000000000000000000000000000000"), f.Addresses[0]) err := lp.RegisterFilter(ctx, Filter{Name: "Emitter Log 1", EventSigs: []common.Hash{EmitterABI.Events["Log1"].ID}, Addresses: []common.Address{a1}}) @@ -114,7 +114,7 @@ func TestLogPoller_RegisterFilter(t *testing.T) { // Removing non-existence Filter should log error but return nil err = lp.UnregisterFilter(ctx, "Filter doesn't exist") require.NoError(t, err) - require.Equal(t, observedLogs.Len(), 1) + require.Equal(t, 1, observedLogs.Len()) require.Contains(t, observedLogs.TakeAll()[0].Entry.Message, "not found") // Check that all filters are still there @@ -137,16 +137,16 @@ func TestLogPoller_RegisterFilter(t *testing.T) { require.NoError(t, err) err = lp.UnregisterFilter(ctx, "Emitter Log 1") require.NoError(t, err) - assert.Len(t, lp.filters, 0) + assert.Empty(t, lp.filters) filters, err := lp.orm.LoadFilters(ctx) require.NoError(t, err) - assert.Len(t, filters, 0) + assert.Empty(t, filters) // Make sure cache was invalidated assert.Len(t, lp.Filter(nil, nil, nil).Addresses, 1) assert.Equal(t, lp.Filter(nil, nil, nil).Addresses[0], common.HexToAddress("0x0000000000000000000000000000000000000000")) assert.Len(t, lp.Filter(nil, nil, nil).Topics, 1) - assert.Len(t, lp.Filter(nil, nil, nil).Topics[0], 0) + assert.Empty(t, lp.Filter(nil, nil, nil).Topics[0]) } func TestLogPoller_ConvertLogs(t *testing.T) { @@ -561,7 +561,7 @@ func Test_latestBlockAndFinalityDepth(t *testing.T) { t.Run("headTracker returns an error", func(t *testing.T) { headTracker := htMocks.NewHeadTracker[*evmtypes.Head, common.Hash](t) const expectedError = "finalized block is not available yet" - headTracker.On("LatestAndFinalizedBlock", mock.Anything).Return(&evmtypes.Head{}, &evmtypes.Head{}, fmt.Errorf(expectedError)) + headTracker.On("LatestAndFinalizedBlock", mock.Anything).Return(&evmtypes.Head{}, &evmtypes.Head{}, errors.New(expectedError)) lp := NewLogPoller(nil, nil, lggr, headTracker, lpOpts) _, _, err := lp.latestBlocks(tests.Context(t)) diff --git a/core/chains/evm/logpoller/log_poller_test.go b/core/chains/evm/logpoller/log_poller_test.go index df688cd5e5c..24894c7152e 100644 --- a/core/chains/evm/logpoller/log_poller_test.go +++ b/core/chains/evm/logpoller/log_poller_test.go @@ -2,6 +2,7 @@ package logpoller_test import ( "context" + "errors" "fmt" "math" "math/big" @@ -102,7 +103,7 @@ func BenchmarkSelectLogsCreatedAfter(b *testing.B) { for i := 0; i < b.N; i++ { logs, err := o.SelectLogsCreatedAfter(ctx, address, event, searchDate, 500) - require.NotZero(b, len(logs)) + require.NotEmpty(b, logs) require.NoError(b, err) } } @@ -134,21 +135,21 @@ func TestPopulateLoadedDB(t *testing.T) { lgs, err1 := o.SelectLogsDataWordRange(ctx, address1, event1, 0, logpoller.EvmWord(50000), logpoller.EvmWord(50020), 0) require.NoError(t, err1) // 10 since every other log is for address1 - require.Equal(t, 10, len(lgs)) + require.Len(t, lgs, 10) }() func() { defer logRuntime(t, time.Now()) lgs, err1 := o.SelectIndexedLogs(ctx, address2, event1, 1, []common.Hash{logpoller.EvmWord(50000), logpoller.EvmWord(50020)}, 0) require.NoError(t, err1) - require.Equal(t, 2, len(lgs)) + require.Len(t, lgs, 2) }() func() { defer logRuntime(t, time.Now()) lgs, err1 := o.SelectIndexedLogsTopicRange(ctx, address1, event1, 1, logpoller.EvmWord(50000), logpoller.EvmWord(50020), 0) require.NoError(t, err1) - require.Equal(t, 10, len(lgs)) + require.Len(t, lgs, 10) }() } @@ -190,7 +191,7 @@ func TestLogPoller_Integration(t *testing.T) { // We should immediately have at least logs 4-7 logs, err := th.LogPoller.Logs(ctx, 4, 7, EmitterABI.Events["Log1"].ID, th.EmitterAddress1) require.NoError(t, err) - require.Equal(t, 4, len(logs)) + require.Len(t, logs, 4) // Once the backup poller runs we should also have the log from block 3 testutils.RequireEventually(t, func() bool { @@ -213,7 +214,7 @@ func TestLogPoller_Integration(t *testing.T) { // Still shouldn't have any Log2 logs yet logs, err = th.LogPoller.Logs(ctx, 2, 7, EmitterABI.Events["Log2"].ID, th.EmitterAddress1) require.NoError(t, err) - require.Len(t, logs, 0) + require.Empty(t, logs) // Replay only from block 4, so we should see logs in block 4,5,6,7 (4 logs) require.NoError(t, th.LogPoller.Replay(testutils.Context(t), 4)) @@ -221,7 +222,7 @@ func TestLogPoller_Integration(t *testing.T) { // We should immediately see 4 logs2 logs. logs, err = th.LogPoller.Logs(ctx, 2, 7, EmitterABI.Events["Log2"].ID, th.EmitterAddress1) require.NoError(t, err) - assert.Equal(t, 4, len(logs)) + assert.Len(t, logs, 4) assert.NoError(t, th.LogPoller.Close()) @@ -280,7 +281,7 @@ func Test_BackupLogPoller(t *testing.T) { filters, err := th.ORM.LoadFilters(ctx) require.NoError(t, err) - require.Equal(t, 1, len(filters)) + require.Len(t, filters, 1) require.Equal(t, filter1, filters["filter1"]) err = th.LogPoller.RegisterFilter(ctx, @@ -670,7 +671,7 @@ func TestLogPoller_BlockTimestamps(t *testing.T) { require.NoError(t, err) // Logs should have correct timestamps - require.NotZero(t, len(lg1)) + require.NotEmpty(t, lg1) b, _ := th.Client.BlockByHash(ctx, lg1[0].BlockHash) t.Log(len(lg1), lg1[0].BlockTimestamp.String()) assert.Equal(t, int64(b.Time()), lg1[0].BlockTimestamp.UTC().Unix(), time1) @@ -842,7 +843,7 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { // No logs. lgs, err := th.ORM.SelectLogsByBlockRange(testutils.Context(t), 1, 1) require.NoError(t, err) - assert.Equal(t, 0, len(lgs)) + assert.Empty(t, lgs) th.assertHaveCanonical(t, 1, 1) // Polling again should be a noop, since we are at the latest. @@ -868,7 +869,7 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { assert.Equal(t, int64(2), latest.BlockNumber) lgs, err = th.ORM.SelectLogsByBlockRange(testutils.Context(t), 1, 3) require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) assert.Equal(t, th.EmitterAddress1, lgs[0].Address) assert.Equal(t, latest.BlockHash, lgs[0].BlockHash) assert.Equal(t, latest.BlockTimestamp, lgs[0].BlockTimestamp) @@ -901,7 +902,7 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { assert.Equal(t, int64(3), latest.BlockNumber) lgs, err = th.ORM.SelectLogsByBlockRange(testutils.Context(t), 1, 3) require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000002`), lgs[0].Data) th.assertHaveCanonical(t, 1, 3) @@ -963,7 +964,7 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { assert.Equal(t, int64(7), newStart) lgs, err = th.ORM.SelectLogsByBlockRange(testutils.Context(t), 4, 6) require.NoError(t, err) - require.Equal(t, 3, len(lgs)) + require.Len(t, lgs, 3) assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000004`), lgs[0].Data) assert.Equal(t, th.EmitterAddress1, lgs[0].Address) assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000005`), lgs[1].Data) @@ -991,7 +992,7 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { assert.Equal(t, int64(11), newStart) lgs, err = th.ORM.SelectLogsByBlockRange(testutils.Context(t), 7, 9) require.NoError(t, err) - require.Equal(t, 3, len(lgs)) + require.Len(t, lgs, 3) assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000007`), lgs[0].Data) assert.Equal(t, int64(7), lgs[0].BlockNumber) assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000008`), lgs[1].Data) @@ -1178,7 +1179,7 @@ func TestLogPoller_PollAndSaveLogsDeepReorg(t *testing.T) { // Check that L1_1 has a proper data payload lgs, err := th.ORM.SelectLogsByBlockRange(testutils.Context(t), 2, 2) require.NoError(t, err) - require.NotZero(t, len(lgs)) + require.NotEmpty(t, lgs) assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000001`), lgs[0].Data) // Single block reorg and log poller not working for a while, mine blocks and progress with finalization @@ -1285,14 +1286,14 @@ func TestLogPoller_LoadFilters(t *testing.T) { t.Run("GetFilters", func(t *testing.T) { filters := th.LogPoller.GetFilters() - assert.Equal(t, 3, len(filters)) - assert.Equal(t, filters["first Filter"].Name, "first Filter") + assert.Len(t, filters, 3) + assert.Equal(t, "first Filter", filters["first Filter"].Name) assert.Equal(t, filters["first Filter"].EventSigs, filter1.EventSigs) assert.Equal(t, filters["first Filter"].Addresses, filter1.Addresses) - assert.Equal(t, filters["second Filter"].Name, "second Filter") + assert.Equal(t, "second Filter", filters["second Filter"].Name) assert.Equal(t, filters["second Filter"].EventSigs, filter2.EventSigs) assert.Equal(t, filters["second Filter"].Addresses, filter2.Addresses) - assert.Equal(t, filters["third Filter"].Name, "third Filter") + assert.Equal(t, "third Filter", filters["third Filter"].Name) assert.Equal(t, filters["third Filter"].EventSigs, filter3.EventSigs) assert.Equal(t, filters["third Filter"].Addresses, filter3.Addresses) }) @@ -1329,13 +1330,13 @@ func TestLogPoller_GetBlocks_Range(t *testing.T) { blockNums := []uint64{} blocks, err := th.LogPoller.GetBlocksRange(testutils.Context(t), blockNums) require.NoError(t, err) - assert.Equal(t, 0, len(blocks)) + assert.Empty(t, blocks) // LP retrieves block 1 blockNums = []uint64{1} blocks, err = th.LogPoller.GetBlocksRange(testutils.Context(t), blockNums) require.NoError(t, err) - assert.Equal(t, 1, len(blocks)) + assert.Len(t, blocks, 1) assert.Equal(t, 1, int(blocks[0].BlockNumber)) assert.Equal(t, 1, int(blocks[0].FinalizedBlockNumber)) @@ -1354,7 +1355,7 @@ func TestLogPoller_GetBlocks_Range(t *testing.T) { // getBlocksRange is able to retrieve block 2 by calling RPC rpcBlocks, err := th.LogPoller.GetBlocksRange(testutils.Context(t), blockNums) require.NoError(t, err) - assert.Equal(t, 1, len(rpcBlocks)) + assert.Len(t, rpcBlocks, 1) assert.Equal(t, 2, int(rpcBlocks[0].BlockNumber)) assert.Equal(t, 2, int(rpcBlocks[0].FinalizedBlockNumber)) @@ -1368,7 +1369,7 @@ func TestLogPoller_GetBlocks_Range(t *testing.T) { blockNums2 := []uint64{1, 3} rpcBlocks2, err := th.LogPoller.GetBlocksRange(testutils.Context(t), blockNums2) require.NoError(t, err) - assert.Equal(t, 2, len(rpcBlocks2)) + assert.Len(t, rpcBlocks2, 2) assert.Equal(t, 1, int(rpcBlocks2[0].BlockNumber)) assert.Equal(t, 3, int(rpcBlocks2[1].BlockNumber)) assert.Equal(t, 3, int(rpcBlocks2[1].FinalizedBlockNumber)) @@ -1382,7 +1383,7 @@ func TestLogPoller_GetBlocks_Range(t *testing.T) { // getBlocksRange should still be able to return block 2 by fetching from DB lpBlocks, err := th.LogPoller.GetBlocksRange(testutils.Context(t), blockNums) require.NoError(t, err) - assert.Equal(t, 1, len(lpBlocks)) + assert.Len(t, lpBlocks, 1) assert.Equal(t, rpcBlocks[0].BlockNumber, lpBlocks[0].BlockNumber) assert.Equal(t, rpcBlocks[0].BlockHash, lpBlocks[0].BlockHash) assert.Equal(t, rpcBlocks[0].FinalizedBlockNumber, lpBlocks[0].FinalizedBlockNumber) @@ -1649,7 +1650,7 @@ func TestTooManyLogResults(t *testing.T) { }) t.Run("Unrelated error are retried without adjusting size", func(t *testing.T) { - unrelatedError := fmt.Errorf("Unrelated to the size of the request") + unrelatedError := errors.New("Unrelated to the size of the request") head.Number = 500 finalized.Number = head.Number - lpOpts.FinalityDepth @@ -1672,9 +1673,9 @@ func TestTooManyLogResults(t *testing.T) { crit := obs.FilterLevelExact(zapcore.DPanicLevel).All() errors := obs.FilterLevelExact(zapcore.ErrorLevel).All() warns := obs.FilterLevelExact(zapcore.WarnLevel).All() - assert.Len(t, crit, 0) + assert.Empty(t, crit) require.Len(t, errors, 1) - assert.Equal(t, errors[0].Message, "Unable to query for logs") + assert.Equal(t, "Unable to query for logs", errors[0].Message) require.Len(t, warns, 1) assert.Contains(t, warns[0].Message, "retrying later") }) @@ -1735,7 +1736,7 @@ func Test_PollAndQueryFinalizedBlocks(t *testing.T) { evmtypes.Finalized, ) require.NoError(t, err) - require.Len(t, finalizedLogs, firstBatchLen, fmt.Sprintf("len(finalizedLogs) = %d, should have been %d", len(finalizedLogs), firstBatchLen)) + require.Len(t, finalizedLogs, firstBatchLen, "len(finalizedLogs) = %d, should have been %d", len(finalizedLogs), firstBatchLen) numberOfConfirmations := 1 logsByConfs, err := th.LogPoller.LogsDataWordGreaterThan( @@ -2002,7 +2003,7 @@ func TestFindLCA(t *testing.T) { require.ErrorContains(t, err, "aborted, FindLCA request cancelled") }) t.Run("Fails, if RPC returns an error", func(t *testing.T) { - expectedError := fmt.Errorf("failed to call RPC") + expectedError := errors.New("failed to call RPC") ec.On("HeadByHash", mock.Anything, latestBlockHash).Return(nil, expectedError).Once() _, err := lp.FindLCA(ctx) require.ErrorContains(t, err, expectedError.Error()) @@ -2039,7 +2040,7 @@ func TestFindLCA(t *testing.T) { Name: "None of the blocks exists on chain - returns an erro", Blocks: []block{{BN: 1, Exists: false}, {BN: 2, Exists: false}, {BN: 3, Exists: false}, {BN: 4, Exists: false}}, ExpectedBlockNumber: 0, - ExpectedError: fmt.Errorf("failed to find LCA, this means that whole database LogPoller state was reorged out of chain or RPC/Core node is misconfigured"), + ExpectedError: errors.New("failed to find LCA, this means that whole database LogPoller state was reorged out of chain or RPC/Core node is misconfigured"), }, { Name: "Only latest block does not exist", diff --git a/core/chains/evm/logpoller/observability_test.go b/core/chains/evm/logpoller/observability_test.go index 6ebc5b0cce0..72bb5c48a2f 100644 --- a/core/chains/evm/logpoller/observability_test.go +++ b/core/chains/evm/logpoller/observability_test.go @@ -1,7 +1,7 @@ package logpoller import ( - "fmt" + "errors" "math/big" "testing" "time" @@ -85,7 +85,7 @@ func TestMetricsAreProperlyPopulatedWithLabels(t *testing.T) { func TestNotPublishingDatasetSizeInCaseOfError(t *testing.T) { orm := createObservedORM(t, 420) - _, err := withObservedQueryAndResults(orm, "errorQuery", func() ([]string, error) { return nil, fmt.Errorf("error") }) + _, err := withObservedQueryAndResults(orm, "errorQuery", func() ([]string, error) { return nil, errors.New("error") }) require.Error(t, err) require.Equal(t, 1, counterFromHistogramByLabels(t, orm.queryDuration, "420", "errorQuery", "read")) @@ -95,7 +95,7 @@ func TestNotPublishingDatasetSizeInCaseOfError(t *testing.T) { func TestMetricsAreProperlyPopulatedForWrites(t *testing.T) { orm := createObservedORM(t, 420) require.NoError(t, withObservedExec(orm, "execQuery", create, func() error { return nil })) - require.Error(t, withObservedExec(orm, "execQuery", create, func() error { return fmt.Errorf("error") })) + require.Error(t, withObservedExec(orm, "execQuery", create, func() error { return errors.New("error") })) require.Equal(t, 2, counterFromHistogramByLabels(t, orm.queryDuration, "420", "execQuery", "create")) } diff --git a/core/chains/evm/logpoller/orm_test.go b/core/chains/evm/logpoller/orm_test.go index eeb6dfe3208..c2558877575 100644 --- a/core/chains/evm/logpoller/orm_test.go +++ b/core/chains/evm/logpoller/orm_test.go @@ -152,7 +152,7 @@ func TestORM_GetBlocks_From_Range(t *testing.T) { // Only non-existent blocks lpBlocks3, err := o1.GetBlocksRange(ctx, 15, 15) require.NoError(t, err) - assert.Len(t, lpBlocks3, 0) + assert.Empty(t, lpBlocks3) } func TestORM_GetBlocks_From_Range_Recent_Blocks(t *testing.T) { @@ -185,7 +185,7 @@ func TestORM_GetBlocks_From_Range_Recent_Blocks(t *testing.T) { // Only non-existent blocks lpBlocks3, err := o1.GetBlocksRange(ctx, 257, 257) require.NoError(t, err) - assert.Len(t, lpBlocks3, 0) + assert.Empty(t, lpBlocks3) } func TestORM(t *testing.T) { @@ -198,7 +198,7 @@ func TestORM(t *testing.T) { require.NoError(t, o1.InsertBlock(ctx, common.HexToHash("0x1234"), 10, time.Now(), 0)) b, err := o1.SelectBlockByHash(ctx, common.HexToHash("0x1234")) require.NoError(t, err) - assert.Equal(t, b.BlockNumber, int64(10)) + assert.Equal(t, int64(10), b.BlockNumber) assert.Equal(t, b.BlockHash.Bytes(), common.HexToHash("0x1234").Bytes()) assert.Equal(t, b.EvmChainId.String(), th.ChainID.String()) @@ -207,7 +207,7 @@ func TestORM(t *testing.T) { require.NoError(t, o2.InsertBlock(ctx, common.HexToHash("0x1235"), 12, time.Now(), 0)) b2, err := o2.SelectBlockByHash(ctx, common.HexToHash("0x1234")) require.NoError(t, err) - assert.Equal(t, b2.BlockNumber, int64(11)) + assert.Equal(t, int64(11), b2.BlockNumber) assert.Equal(t, b2.BlockHash.Bytes(), common.HexToHash("0x1234").Bytes()) assert.Equal(t, b2.EvmChainId.String(), th.ChainID2.String()) @@ -385,15 +385,15 @@ func TestORM(t *testing.T) { logs, err = o1.SelectLogsByBlockRange(ctx, 10, 10) require.NoError(t, err) - require.Equal(t, 1, len(logs)) + require.Len(t, logs, 1) assert.Equal(t, []byte("hello"), logs[0].Data) logs, err = o1.SelectLogs(ctx, 1, 1, common.HexToAddress("0x1234"), topic) require.NoError(t, err) - assert.Equal(t, 0, len(logs)) + assert.Empty(t, logs) logs, err = o1.SelectLogs(ctx, 10, 10, common.HexToAddress("0x1234"), topic) require.NoError(t, err) - require.Equal(t, 1, len(logs)) + require.Len(t, logs, 1) // With no blocks, should be an error _, err = o1.SelectLatestLogByEventSigWithConfs(ctx, topic, common.HexToAddress("0x1234"), 0) @@ -429,33 +429,33 @@ func TestORM(t *testing.T) { lgs, err := o1.SelectLatestLogEventSigsAddrsWithConfs(ctx, 0 /* startBlock */, []common.Address{common.HexToAddress("0x1234")}, []common.Hash{topic}, 0) require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) require.Equal(t, int64(11), lgs[0].BlockNumber) // should return two entries one for each address with the latest update lgs, err = o1.SelectLatestLogEventSigsAddrsWithConfs(ctx, 0 /* startBlock */, []common.Address{common.HexToAddress("0x1234"), common.HexToAddress("0x1235")}, []common.Hash{topic}, 0) require.NoError(t, err) - require.Equal(t, 2, len(lgs)) + require.Len(t, lgs, 2) // should return two entries one for each topic for addr 0x1234 lgs, err = o1.SelectLatestLogEventSigsAddrsWithConfs(ctx, 0 /* startBlock */, []common.Address{common.HexToAddress("0x1234")}, []common.Hash{topic, topic2}, 0) require.NoError(t, err) - require.Equal(t, 2, len(lgs)) + require.Len(t, lgs, 2) // should return 4 entries one for each (address,topic) combination lgs, err = o1.SelectLatestLogEventSigsAddrsWithConfs(ctx, 0 /* startBlock */, []common.Address{common.HexToAddress("0x1234"), common.HexToAddress("0x1235")}, []common.Hash{topic, topic2}, 0) require.NoError(t, err) - require.Equal(t, 4, len(lgs)) + require.Len(t, lgs, 4) // should return 3 entries of logs with atleast 1 confirmation lgs, err = o1.SelectLatestLogEventSigsAddrsWithConfs(ctx, 0 /* startBlock */, []common.Address{common.HexToAddress("0x1234"), common.HexToAddress("0x1235")}, []common.Hash{topic, topic2}, 1) require.NoError(t, err) - require.Equal(t, 3, len(lgs)) + require.Len(t, lgs, 3) // should return 2 entries of logs with atleast 2 confirmation lgs, err = o1.SelectLatestLogEventSigsAddrsWithConfs(ctx, 0 /* startBlock */, []common.Address{common.HexToAddress("0x1234"), common.HexToAddress("0x1235")}, []common.Hash{topic, topic2}, 2) require.NoError(t, err) - require.Equal(t, 2, len(lgs)) + require.Len(t, lgs, 2) require.NoError(t, o1.InsertBlock(ctx, common.HexToHash("0x1237"), 16, time.Now(), 0)) require.NoError(t, o1.InsertBlock(ctx, common.HexToHash("0x1238"), 17, time.Now(), 17)) @@ -544,7 +544,7 @@ func TestORM(t *testing.T) { require.NoError(t, err) logs, err = o1.SelectLogsByBlockRange(ctx, 1, latest.BlockNumber) require.NoError(t, err) - assert.Zero(t, len(logs)) + assert.Empty(t, logs) } func TestORM_SelectExcessLogs(t *testing.T) { @@ -676,7 +676,7 @@ func TestORM_SelectExcessLogs(t *testing.T) { ids, err := o1.SelectUnmatchedLogIDs(ctx, 0) require.NoError(t, err) - require.Len(t, ids, 0) + require.Empty(t, ids) // Number of excess logs eligible for pruning: // 2 of the 7 matching filter2 + 6 of the 7 matching filter12 but not filter2 = 8 total of 21 @@ -771,7 +771,7 @@ func TestLogPollerFilters(t *testing.T) { if len(filter.Topic4) > 0 { expectedCount *= len(filter.Topic4) } - assert.Equal(t, count, expectedCount) + assert.Equal(t, expectedCount, count) }) } @@ -844,21 +844,21 @@ func TestORM_IndexedLogs(t *testing.T) { lgs, err := o1.SelectIndexedLogs(ctx, addr, eventSig, 1, []common.Hash{logpoller.EvmWord(1)}, 0) require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) assert.Equal(t, logpoller.EvmWord(1).Bytes(), lgs[0].GetTopics()[1].Bytes()) lgs, err = o1.FilteredLogs(ctx, standardFilter(1, []uint64{1}).Expressions, limiter, "") require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) assert.Equal(t, logpoller.EvmWord(1).Bytes(), lgs[0].GetTopics()[1].Bytes()) lgs, err = o1.SelectIndexedLogs(ctx, addr, eventSig, 1, []common.Hash{logpoller.EvmWord(1), logpoller.EvmWord(2)}, 0) require.NoError(t, err) - assert.Equal(t, 2, len(lgs)) + assert.Len(t, lgs, 2) lgs, err = o1.FilteredLogs(ctx, standardFilter(1, []uint64{1, 2}).Expressions, limiter, "") require.NoError(t, err) - assert.Equal(t, 2, len(lgs)) + assert.Len(t, lgs, 2) blockRangeFilter := func(start, end string, topicIdx uint64, topicValues []uint64) []query.Expression { return []query.Expression{ @@ -872,27 +872,27 @@ func TestORM_IndexedLogs(t *testing.T) { lgs, err = o1.SelectIndexedLogsByBlockRange(ctx, 1, 1, addr, eventSig, 1, []common.Hash{logpoller.EvmWord(1)}) require.NoError(t, err) - assert.Equal(t, 1, len(lgs)) + assert.Len(t, lgs, 1) lgs, err = o1.FilteredLogs(ctx, blockRangeFilter("1", "1", 1, []uint64{1}), limiter, "") require.NoError(t, err) - assert.Equal(t, 1, len(lgs)) + assert.Len(t, lgs, 1) lgs, err = o1.SelectIndexedLogsByBlockRange(ctx, 1, 2, addr, eventSig, 1, []common.Hash{logpoller.EvmWord(2)}) require.NoError(t, err) - assert.Equal(t, 1, len(lgs)) + assert.Len(t, lgs, 1) lgs, err = o1.FilteredLogs(ctx, blockRangeFilter("1", "2", 1, []uint64{2}), limiter, "") require.NoError(t, err) - assert.Equal(t, 1, len(lgs)) + assert.Len(t, lgs, 1) lgs, err = o1.SelectIndexedLogsByBlockRange(ctx, 1, 2, addr, eventSig, 1, []common.Hash{logpoller.EvmWord(1)}) require.NoError(t, err) - assert.Equal(t, 1, len(lgs)) + assert.Len(t, lgs, 1) lgs, err = o1.FilteredLogs(ctx, blockRangeFilter("1", "2", 1, []uint64{1}), limiter, "") require.NoError(t, err) - assert.Equal(t, 1, len(lgs)) + assert.Len(t, lgs, 1) _, err = o1.SelectIndexedLogsByBlockRange(ctx, 1, 2, addr, eventSig, 0, []common.Hash{logpoller.EvmWord(1)}) require.Error(t, err) @@ -912,7 +912,7 @@ func TestORM_IndexedLogs(t *testing.T) { lgs, err = o1.SelectIndexedLogsTopicGreaterThan(ctx, addr, eventSig, 1, logpoller.EvmWord(2), 0) require.NoError(t, err) - assert.Equal(t, 2, len(lgs)) + assert.Len(t, lgs, 2) filter := query.KeyFilter{ Expressions: []query.Expression{ @@ -927,7 +927,7 @@ func TestORM_IndexedLogs(t *testing.T) { lgs, err = o1.FilteredLogs(ctx, filter.Expressions, limiter, "") require.NoError(t, err) - assert.Equal(t, 2, len(lgs)) + assert.Len(t, lgs, 2) rangeFilter := func(topicIdx uint64, min, max uint64) []query.Expression { return []query.Expression{ @@ -945,31 +945,31 @@ func TestORM_IndexedLogs(t *testing.T) { lgs, err = o1.SelectIndexedLogsTopicRange(ctx, addr, eventSig, 1, logpoller.EvmWord(3), logpoller.EvmWord(3), 0) require.NoError(t, err) - assert.Equal(t, 1, len(lgs)) + assert.Len(t, lgs, 1) assert.Equal(t, logpoller.EvmWord(3).Bytes(), lgs[0].GetTopics()[1].Bytes()) lgs, err = o1.FilteredLogs(ctx, rangeFilter(1, 3, 3), limiter, "") require.NoError(t, err) - assert.Equal(t, 1, len(lgs)) + assert.Len(t, lgs, 1) assert.Equal(t, logpoller.EvmWord(3).Bytes(), lgs[0].GetTopics()[1].Bytes()) lgs, err = o1.SelectIndexedLogsTopicRange(ctx, addr, eventSig, 1, logpoller.EvmWord(1), logpoller.EvmWord(3), 0) require.NoError(t, err) - assert.Equal(t, 3, len(lgs)) + assert.Len(t, lgs, 3) lgs, err = o1.FilteredLogs(ctx, rangeFilter(1, 1, 3), limiter, "") require.NoError(t, err) - assert.Equal(t, 3, len(lgs)) + assert.Len(t, lgs, 3) // Check confirmations work as expected. require.NoError(t, o1.InsertBlock(ctx, common.HexToHash("0x2"), 2, time.Now(), 0)) lgs, err = o1.SelectIndexedLogsTopicRange(ctx, addr, eventSig, 1, logpoller.EvmWord(4), logpoller.EvmWord(4), 1) require.NoError(t, err) - assert.Equal(t, 0, len(lgs)) + assert.Empty(t, lgs) require.NoError(t, o1.InsertBlock(ctx, common.HexToHash("0x3"), 3, time.Now(), 0)) lgs, err = o1.SelectIndexedLogsTopicRange(ctx, addr, eventSig, 1, logpoller.EvmWord(4), logpoller.EvmWord(4), 1) require.NoError(t, err) - assert.Equal(t, 1, len(lgs)) + assert.Len(t, lgs, 1) } func TestORM_SelectIndexedLogsByTxHash(t *testing.T) { @@ -1034,7 +1034,7 @@ func TestORM_SelectIndexedLogsByTxHash(t *testing.T) { retrievedLogs, err := o1.SelectIndexedLogsByTxHash(ctx, addr, eventSig, txHash) require.NoError(t, err) - require.Equal(t, 2, len(retrievedLogs)) + require.Len(t, retrievedLogs, 2) require.Equal(t, retrievedLogs[0].LogIndex, logs[0].LogIndex) require.Equal(t, retrievedLogs[1].LogIndex, logs[1].LogIndex) @@ -1050,7 +1050,7 @@ func TestORM_SelectIndexedLogsByTxHash(t *testing.T) { retrievedLogs, err = o1.FilteredLogs(ctx, filter.Expressions, limiter, "") require.NoError(t, err) - require.Equal(t, 2, len(retrievedLogs)) + require.Len(t, retrievedLogs, 2) require.Equal(t, retrievedLogs[0].LogIndex, logs[0].LogIndex) require.Equal(t, retrievedLogs[1].LogIndex, logs[1].LogIndex) } @@ -1107,55 +1107,55 @@ func TestORM_DataWords(t *testing.T) { // Outside range should fail. lgs, err := o1.SelectLogsDataWordRange(ctx, addr, eventSig, 0, logpoller.EvmWord(2), logpoller.EvmWord(2), 0) require.NoError(t, err) - require.Equal(t, 0, len(lgs)) + require.Empty(t, lgs) lgs, err = o1.FilteredLogs(ctx, wordFilter(0, 2, 2), limiter, "") require.NoError(t, err) - require.Equal(t, 0, len(lgs)) + require.Empty(t, lgs) // Range including log should succeed lgs, err = o1.SelectLogsDataWordRange(ctx, addr, eventSig, 0, logpoller.EvmWord(1), logpoller.EvmWord(2), 0) require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) lgs, err = o1.FilteredLogs(ctx, wordFilter(0, 1, 2), limiter, "") require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) // Range only covering log should succeed lgs, err = o1.SelectLogsDataWordRange(ctx, addr, eventSig, 0, logpoller.EvmWord(1), logpoller.EvmWord(1), 0) require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) lgs, err = o1.FilteredLogs(ctx, wordFilter(0, 1, 1), limiter, "") require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) // Cannot query for unconfirmed second log. lgs, err = o1.SelectLogsDataWordRange(ctx, addr, eventSig, 1, logpoller.EvmWord(3), logpoller.EvmWord(3), 0) require.NoError(t, err) - require.Equal(t, 0, len(lgs)) + require.Empty(t, lgs) lgs, err = o1.FilteredLogs(ctx, wordFilter(1, 3, 3), limiter, "") require.NoError(t, err) - require.Equal(t, 0, len(lgs)) + require.Empty(t, lgs) // Confirm it, then can query. require.NoError(t, o1.InsertBlock(ctx, common.HexToHash("0x2"), 2, time.Now(), 0)) lgs, err = o1.SelectLogsDataWordRange(ctx, addr, eventSig, 1, logpoller.EvmWord(3), logpoller.EvmWord(3), 0) require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) require.Equal(t, lgs[0].Data, append(logpoller.EvmWord(2).Bytes(), logpoller.EvmWord(3).Bytes()...)) lgs, err = o1.FilteredLogs(ctx, wordFilter(1, 3, 3), limiter, "") require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) require.Equal(t, lgs[0].Data, append(logpoller.EvmWord(2).Bytes(), logpoller.EvmWord(3).Bytes()...)) // Check greater than 1 yields both logs. lgs, err = o1.SelectLogsDataWordGreaterThan(ctx, addr, eventSig, 0, logpoller.EvmWord(1), 0) require.NoError(t, err) - assert.Equal(t, 2, len(lgs)) + assert.Len(t, lgs, 2) filter := []query.Expression{ logpoller.NewAddressFilter(addr), @@ -1168,7 +1168,7 @@ func TestORM_DataWords(t *testing.T) { lgs, err = o1.FilteredLogs(ctx, filter, limiter, "") require.NoError(t, err) - assert.Equal(t, 2, len(lgs)) + assert.Len(t, lgs, 2) } func TestORM_SelectLogsWithSigsByBlockRangeFilter(t *testing.T) { @@ -1425,7 +1425,7 @@ func TestLogPoller_Logs(t *testing.T) { // Select for all Addresses lgs, err := th.ORM.SelectLogsByBlockRange(ctx, 1, 3) require.NoError(t, err) - require.Equal(t, 6, len(lgs)) + require.Len(t, lgs, 6) assert.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000003", lgs[0].BlockHash.String()) assert.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000003", lgs[1].BlockHash.String()) assert.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000004", lgs[2].BlockHash.String()) @@ -1445,7 +1445,7 @@ func TestLogPoller_Logs(t *testing.T) { // Filter by Address and topic lgs, err = th.ORM.SelectLogs(ctx, 1, 3, address1, event1) require.NoError(t, err) - require.Equal(t, 2, len(lgs)) + require.Len(t, lgs, 2) assert.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000003", lgs[0].BlockHash.String()) assert.Equal(t, address1, lgs[0].Address) assert.Equal(t, event1.Bytes(), lgs[0].Topics[0]) @@ -1456,7 +1456,7 @@ func TestLogPoller_Logs(t *testing.T) { SortBy: []query.SortBy{query.NewSortBySequence(query.Asc)}, }, "") require.NoError(t, err) - require.Equal(t, 2, len(lgs)) + require.Len(t, lgs, 2) assert.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000003", lgs[0].BlockHash.String()) assert.Equal(t, address1, lgs[0].Address) assert.Equal(t, event1.Bytes(), lgs[0].Topics[0]) @@ -1466,7 +1466,7 @@ func TestLogPoller_Logs(t *testing.T) { // Filter by block lgs, err = th.ORM.SelectLogs(ctx, 2, 2, address2, event1) require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) assert.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000004", lgs[0].BlockHash.String()) assert.Equal(t, int64(1), lgs[0].LogIndex) assert.Equal(t, address2, lgs[0].Address) @@ -1476,7 +1476,7 @@ func TestLogPoller_Logs(t *testing.T) { SortBy: []query.SortBy{query.NewSortBySequence(query.Asc)}, }, "") require.NoError(t, err) - require.Equal(t, 1, len(lgs)) + require.Len(t, lgs, 1) assert.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000004", lgs[0].BlockHash.String()) assert.Equal(t, int64(1), lgs[0].LogIndex) assert.Equal(t, address2, lgs[0].Address) @@ -1591,7 +1591,7 @@ func TestSelectLogsWithSigsExcluding(t *testing.T) { // Should return nothing as requestID-A1 has been fulfilled logs, err = orm.SelectIndexedLogsWithSigsExcluding(ctx, requestSigA, responseSigA, 1, addressA, 0, 3, 0) require.NoError(t, err) - require.Len(t, logs, 0) + require.Empty(t, logs) // requestID-B1 should still be unfulfilled logs, err = orm.SelectIndexedLogsWithSigsExcluding(ctx, requestSigB, responseSigB, 1, addressB, 0, 3, 0) @@ -1695,7 +1695,7 @@ func TestSelectLogsWithSigsExcluding(t *testing.T) { // Should return no logs as the number of confirmations is not satisfied logs, err = orm.SelectIndexedLogsWithSigsExcluding(ctx, requestSigB, responseSigB, 3, addressC, 0, 4, 3) require.NoError(t, err) - require.Len(t, logs, 0) + require.Empty(t, logs) require.NoError(t, orm.InsertBlock(ctx, common.HexToHash("0x4"), 4, time.Now(), 0)) require.NoError(t, orm.InsertBlock(ctx, common.HexToHash("0x5"), 5, time.Now(), 0)) @@ -1724,7 +1724,7 @@ func TestSelectLogsWithSigsExcluding(t *testing.T) { // All logs for addressC should be fulfilled, query should return 0 logs logs, err = orm.SelectIndexedLogsWithSigsExcluding(ctx, requestSigB, responseSigB, 3, addressC, 0, 10, 0) require.NoError(t, err) - require.Len(t, logs, 0) + require.Empty(t, logs) // Should return 1 log as it does not satisfy the required number of confirmations logs, err = orm.SelectIndexedLogsWithSigsExcluding(ctx, requestSigB, responseSigB, 3, addressC, 0, 10, 3) @@ -1739,7 +1739,7 @@ func TestSelectLogsWithSigsExcluding(t *testing.T) { logs, err = orm.SelectIndexedLogsWithSigsExcluding(ctx, requestSigB, responseSigB, 3, addressC, 0, 10, 0) require.NoError(t, err) - require.Len(t, logs, 0) + require.Empty(t, logs) // AddressB should still have an unfulfilled log (requestID-B1) logs, err = orm.SelectIndexedLogsWithSigsExcluding(ctx, requestSigB, responseSigB, 1, addressB, 0, 3, 0) @@ -1756,7 +1756,7 @@ func TestSelectLogsWithSigsExcluding(t *testing.T) { // Should return nothing as requestID-B1 is before the block range logs, err = orm.SelectIndexedLogsWithSigsExcluding(ctx, requestSigB, responseSigB, 1, addressB, 2, 13, 0) require.NoError(t, err) - require.Len(t, logs, 0) + require.Empty(t, logs) } func TestSelectLatestBlockNumberEventSigsAddrsWithConfs(t *testing.T) { @@ -2026,7 +2026,7 @@ func TestNestedLogPollerBlocksQuery(t *testing.T) { // Empty logs when block are not persisted logs, err := th.ORM.SelectIndexedLogs(ctx, address, event, 1, []common.Hash{event}, evmtypes.Unconfirmed) require.NoError(t, err) - require.Len(t, logs, 0) + require.Empty(t, logs) // Persist block require.NoError(t, th.ORM.InsertBlock(ctx, utils.RandomHash(), 10, time.Now(), 0)) @@ -2039,7 +2039,7 @@ func TestNestedLogPollerBlocksQuery(t *testing.T) { // Empty logs when number of confirmations is too deep logs, err = th.ORM.SelectIndexedLogs(ctx, address, event, 1, []common.Hash{event}, evmtypes.Confirmations(4)) require.NoError(t, err) - require.Len(t, logs, 0) + require.Empty(t, logs) } func TestInsertLogsWithBlock(t *testing.T) { @@ -2114,7 +2114,7 @@ func TestInsertLogsWithBlock(t *testing.T) { assert.Error(t, insertError) assert.NoError(t, logsErr) - assert.Len(t, logs, 0) + assert.Empty(t, logs) assert.Error(t, blockErr) } else { @@ -2175,7 +2175,7 @@ func TestInsertLogsInTx(t *testing.T) { if tt.shouldRollback { assert.Error(t, insertErr) - assert.Len(t, logsFromDb, 0) + assert.Empty(t, logsFromDb) } else { assert.NoError(t, insertErr) assert.Len(t, logsFromDb, len(tt.logs)) @@ -2405,7 +2405,7 @@ func TestSelectOldestBlock(t *testing.T) { block, err := o1.SelectOldestBlock(ctx, 0) require.NoError(t, err) require.NotNil(t, block) - require.Equal(t, block.BlockNumber, int64(13)) + require.Equal(t, int64(13), block.BlockNumber) require.Equal(t, block.BlockHash, common.HexToHash("0x1233")) }) t.Run("Does not select blocks older than specified limit", func(t *testing.T) { @@ -2415,7 +2415,7 @@ func TestSelectOldestBlock(t *testing.T) { block, err := o1.SelectOldestBlock(ctx, 12) require.NoError(t, err) require.NotNil(t, block) - require.Equal(t, block.BlockNumber, int64(13)) + require.Equal(t, int64(13), block.BlockNumber) require.Equal(t, block.BlockHash, common.HexToHash("0x1233")) }) } diff --git a/core/chains/evm/logpoller/parser.go b/core/chains/evm/logpoller/parser.go index 9dfa00eaf3e..dbd5760c982 100644 --- a/core/chains/evm/logpoller/parser.go +++ b/core/chains/evm/logpoller/parser.go @@ -115,10 +115,7 @@ func (v *pgDSLParser) TxHash(p primitives.TxHash) { } func (v *pgDSLParser) VisitAddressFilter(p *addressFilter) { - v.expression = fmt.Sprintf( - "address = :%s", - v.args.withIndexedField("address", p.address), - ) + v.expression = "address = :" + v.args.withIndexedField("address", p.address) } func (v *pgDSLParser) VisitEventSigFilter(p *eventSigFilter) { @@ -311,7 +308,7 @@ func (v *pgDSLParser) orderClause(limiter query.LimitAndSort) (string, error) { } if len(sorting) == 0 { - return fmt.Sprintf("ORDER BY %s", defaultSort), nil + return "ORDER BY " + defaultSort, nil } sort := make([]string, len(sorting)) @@ -340,7 +337,7 @@ func (v *pgDSLParser) orderClause(limiter query.LimitAndSort) (string, error) { sort[idx] = fmt.Sprintf("%s %s", name, order) } - return fmt.Sprintf("ORDER BY %s", strings.Join(sort, ", ")), nil + return "ORDER BY " + strings.Join(sort, ", "), nil } func (v *pgDSLParser) limitClause(limiter query.LimitAndSort) string { diff --git a/core/chains/evm/monitor/balance.go b/core/chains/evm/monitor/balance.go index b6cb9adb875..56bebe34315 100644 --- a/core/chains/evm/monitor/balance.go +++ b/core/chains/evm/monitor/balance.go @@ -131,7 +131,7 @@ func (bm *balanceMonitor) promUpdateEthBalance(balance *assets.Eth, from gethCom balanceFloat, err := ApproximateFloat64(balance) if err != nil { - bm.eng.Error(fmt.Errorf("updatePrometheusEthBalance: %v", err)) + bm.eng.Error(fmt.Errorf("updatePrometheusEthBalance: %w", err)) return } @@ -173,7 +173,7 @@ func (w *worker) checkAccountBalance(ctx context.Context, address gethCommon.Add bal, err := w.bm.ethClient.BalanceAt(ctx, address, nil) if err != nil { - w.bm.eng.Errorw(fmt.Sprintf("BalanceMonitor: error getting balance for key %s", address.Hex()), + w.bm.eng.Errorw("BalanceMonitor: error getting balance for key "+address.Hex(), "err", err, "address", address, ) diff --git a/core/chains/evm/testutils/config_test.go b/core/chains/evm/testutils/config_test.go index 1f9d7be4445..f7ce2151a4c 100644 --- a/core/chains/evm/testutils/config_test.go +++ b/core/chains/evm/testutils/config_test.go @@ -17,5 +17,5 @@ func TestNewTestChainScopedConfigOverride(t *testing.T) { // Overrides values assert.Equal(t, uint32(100), c.EVM().FinalityDepth()) // fallback.toml values - assert.Equal(t, false, c.EVM().GasEstimator().EIP1559DynamicFees()) + assert.False(t, c.EVM().GasEstimator().EIP1559DynamicFees()) } diff --git a/core/chains/evm/txmgr/attempts_test.go b/core/chains/evm/txmgr/attempts_test.go index 1e9f4abc552..0b26dc49f76 100644 --- a/core/chains/evm/txmgr/attempts_test.go +++ b/core/chains/evm/txmgr/attempts_test.go @@ -1,7 +1,6 @@ package txmgr_test import ( - "fmt" "math/big" "testing" @@ -216,7 +215,7 @@ func TestTxm_NewLegacyAttempt(t *testing.T) { t.Run("verifies max gas price", func(t *testing.T) { _, _, err := cks.NewCustomTxAttempt(tests.Context(t), txmgr.Tx{FromAddress: addr}, gas.EvmFee{GasPrice: assets.NewWeiI(100)}, 100, 0x0, lggr) require.Error(t, err) - assert.Contains(t, err.Error(), fmt.Sprintf("specified gas price of 100 wei would exceed max configured gas price of 50 wei for key %s", addr.String())) + assert.Contains(t, err.Error(), "specified gas price of 100 wei would exceed max configured gas price of 50 wei for key "+addr.String()) }) } @@ -253,7 +252,7 @@ func TestTxm_NewPurgeAttempt(t *testing.T) { require.Equal(t, bumpedLegacy.String(), a.TxFee.GasPrice.String()) require.Nil(t, a.TxFee.GasTipCap) require.Nil(t, a.TxFee.GasFeeCap) - require.Equal(t, true, a.IsPurgeAttempt) + require.True(t, a.IsPurgeAttempt) require.Equal(t, []byte{}, a.Tx.EncodedPayload) require.Equal(t, *big.NewInt(0), a.Tx.Value) }) @@ -273,7 +272,7 @@ func TestTxm_NewPurgeAttempt(t *testing.T) { require.NotNil(t, a.TxFee.GasFeeCap) require.Equal(t, bumpedDynamicTip.String(), a.TxFee.GasTipCap.String()) require.Equal(t, bumpedDynamicFee.String(), a.TxFee.GasFeeCap.String()) - require.Equal(t, true, a.IsPurgeAttempt) + require.True(t, a.IsPurgeAttempt) require.Equal(t, []byte{}, a.Tx.EncodedPayload) require.Equal(t, *big.NewInt(0), a.Tx.Value) }) @@ -295,7 +294,7 @@ func TestTxm_NewPurgeAttempt(t *testing.T) { require.Equal(t, bumpedLegacy.String(), bumpAttempt.TxFee.GasPrice.String()) require.Nil(t, bumpAttempt.TxFee.GasTipCap) require.Nil(t, bumpAttempt.TxFee.GasFeeCap) - require.Equal(t, true, bumpAttempt.IsPurgeAttempt) + require.True(t, bumpAttempt.IsPurgeAttempt) require.Equal(t, []byte{}, bumpAttempt.Tx.EncodedPayload) require.Equal(t, *big.NewInt(0), bumpAttempt.Tx.Value) }) diff --git a/core/chains/evm/txmgr/broadcaster_test.go b/core/chains/evm/txmgr/broadcaster_test.go index 311f1aae648..806157a7097 100644 --- a/core/chains/evm/txmgr/broadcaster_test.go +++ b/core/chains/evm/txmgr/broadcaster_test.go @@ -353,7 +353,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Success(t *testing.T) { _, err = txmgr.GetGethSignedTx(attempt.SignedRawTx) require.NoError(t, err) assert.Equal(t, txmgrtypes.TxAttemptBroadcast, attempt.State) - require.Len(t, attempt.Receipts, 0) + require.Empty(t, attempt.Receipts) // Check laterEthTx and it's attempt // This was the later one sent so it has the higher nonce @@ -376,7 +376,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Success(t *testing.T) { _, err = txmgr.GetGethSignedTx(attempt.SignedRawTx) require.NoError(t, err) assert.Equal(t, txmgrtypes.TxAttemptBroadcast, attempt.State) - require.Len(t, attempt.Receipts, 0) + require.Empty(t, attempt.Receipts) }) rnd := int64(1000000000 + rand.Intn(5000)) @@ -427,7 +427,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Success(t *testing.T) { _, err = txmgr.GetGethSignedTx(attempt.SignedRawTx) require.NoError(t, err) assert.Equal(t, txmgrtypes.TxAttemptBroadcast, attempt.State) - require.Len(t, attempt.Receipts, 0) + require.Empty(t, attempt.Receipts) }) t.Run("transaction simulation", func(t *testing.T) { @@ -853,7 +853,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_ResumingFromCrash(t *testing.T) { assert.Nil(t, etx.InitialBroadcastAt) assert.True(t, etx.Error.Valid) assert.Equal(t, "exceeds block gas limit", etx.Error.String) - assert.Len(t, etx.TxAttempts, 0) + assert.Empty(t, etx.TxAttempts) }) t.Run("previous run assigned nonce and broadcast and is now in mempool", func(t *testing.T) { @@ -1111,7 +1111,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { require.Nil(t, etx.Sequence) assert.True(t, etx.Error.Valid) assert.Contains(t, etx.Error.String, "exceeds block gas limit") - assert.Len(t, etx.TxAttempts, 0) + assert.Empty(t, etx.TxAttempts) // Check that the key had its nonce reset var nonce evmtypes.Nonce @@ -1770,7 +1770,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_KeystoreErrors(t *testing.T) { require.NoError(t, err) assert.Equal(t, txmgrcommon.TxUnstarted, etx.State) - assert.Len(t, etx.TxAttempts, 0) + assert.Empty(t, etx.TxAttempts) // Check that the key did not have its nonce incremented var nonce evmtypes.Nonce diff --git a/core/chains/evm/txmgr/evm_tx_store_test.go b/core/chains/evm/txmgr/evm_tx_store_test.go index a05cf3f9010..c2836f61b9f 100644 --- a/core/chains/evm/txmgr/evm_tx_store_test.go +++ b/core/chains/evm/txmgr/evm_tx_store_test.go @@ -130,7 +130,7 @@ func TestORM(t *testing.T) { t.Run("InsertTx", func(t *testing.T) { etx = cltest.NewEthTx(fromAddress) require.NoError(t, orm.InsertTx(ctx, &etx)) - assert.Greater(t, int(etx.ID), 0) + assert.Positive(t, etx.ID) cltest.AssertCount(t, db, "evm.txes", 1) }) var attemptL txmgr.TxAttempt @@ -138,14 +138,14 @@ func TestORM(t *testing.T) { t.Run("InsertTxAttempt", func(t *testing.T) { attemptD = cltest.NewDynamicFeeEthTxAttempt(t, etx.ID) require.NoError(t, orm.InsertTxAttempt(ctx, &attemptD)) - assert.Greater(t, int(attemptD.ID), 0) + assert.Positive(t, attemptD.ID) cltest.AssertCount(t, db, "evm.tx_attempts", 1) attemptL = cltest.NewLegacyEthTxAttempt(t, etx.ID) attemptL.State = txmgrtypes.TxAttemptBroadcast attemptL.TxFee = gas.EvmFee{GasPrice: assets.NewWeiI(42)} require.NoError(t, orm.InsertTxAttempt(ctx, &attemptL)) - assert.Greater(t, int(attemptL.ID), 0) + assert.Positive(t, attemptL.ID) cltest.AssertCount(t, db, "evm.tx_attempts", 2) }) var r txmgr.Receipt @@ -154,7 +154,7 @@ func TestORM(t *testing.T) { id, err := orm.InsertReceipt(ctx, &r.Receipt) r.ID = id require.NoError(t, err) - assert.Greater(t, int(r.ID), 0) + assert.Positive(t, r.ID) cltest.AssertCount(t, db, "evm.receipts", 1) }) t.Run("FindTxWithAttempts", func(t *testing.T) { @@ -1482,7 +1482,7 @@ func TestORM_CountUnconfirmedTransactions(t *testing.T) { count, err := txStore.CountUnconfirmedTransactions(tests.Context(t), fromAddress, testutils.FixtureChainID) require.NoError(t, err) - assert.Equal(t, int(count), 3) + assert.Equal(t, 3, int(count)) } func TestORM_CountTransactionsByState(t *testing.T) { @@ -1502,7 +1502,7 @@ func TestORM_CountTransactionsByState(t *testing.T) { count, err := txStore.CountTransactionsByState(tests.Context(t), txmgrcommon.TxUnconfirmed, testutils.FixtureChainID) require.NoError(t, err) - assert.Equal(t, int(count), 3) + assert.Equal(t, 3, int(count)) } func TestORM_CountUnstartedTransactions(t *testing.T) { @@ -1522,7 +1522,7 @@ func TestORM_CountUnstartedTransactions(t *testing.T) { count, err := txStore.CountUnstartedTransactions(tests.Context(t), fromAddress, testutils.FixtureChainID) require.NoError(t, err) - assert.Equal(t, int(count), 2) + assert.Equal(t, 2, int(count)) } func TestORM_CheckTxQueueCapacity(t *testing.T) { @@ -1648,8 +1648,8 @@ func TestORM_CreateTransaction(t *testing.T) { }, ethClient.ConfiguredChainID()) assert.NoError(t, err) - assert.Greater(t, etx.ID, int64(0)) - assert.Equal(t, etx.State, txmgrcommon.TxUnstarted) + assert.Positive(t, etx.ID) + assert.Equal(t, txmgrcommon.TxUnstarted, etx.State) assert.Equal(t, gasLimit, etx.FeeLimit) assert.Equal(t, fromAddress, etx.FromAddress) assert.Equal(t, toAddress, etx.ToAddress) @@ -1662,7 +1662,7 @@ func TestORM_CreateTransaction(t *testing.T) { var dbEthTx txmgr.DbEthTx require.NoError(t, db.Get(&dbEthTx, `SELECT * FROM evm.txes ORDER BY id ASC LIMIT 1`)) - assert.Equal(t, dbEthTx.State, txmgrcommon.TxUnstarted) + assert.Equal(t, txmgrcommon.TxUnstarted, dbEthTx.State) assert.Equal(t, gasLimit, dbEthTx.GasLimit) assert.Equal(t, fromAddress, dbEthTx.FromAddress) assert.Equal(t, toAddress, dbEthTx.ToAddress) @@ -1705,7 +1705,7 @@ func TestORM_CreateTransaction(t *testing.T) { }, ethClient.ConfiguredChainID()) assert.NoError(t, err) - assert.Greater(t, etx.ID, int64(0)) + assert.Positive(t, etx.ID) assert.Equal(t, fromAddress, etx.FromAddress) assert.True(t, etx.SignalCallback) diff --git a/core/chains/evm/txmgr/finalizer.go b/core/chains/evm/txmgr/finalizer.go index bc496202cd6..4a7672cc21c 100644 --- a/core/chains/evm/txmgr/finalizer.go +++ b/core/chains/evm/txmgr/finalizer.go @@ -219,7 +219,7 @@ func (f *evmFinalizer) ProcessHead(ctx context.Context, head *evmtypes.Head) err func (f *evmFinalizer) processFinalizedHead(ctx context.Context, latestFinalizedHead *evmtypes.Head) error { // Cannot determine finality without a finalized head for comparison if latestFinalizedHead == nil || !latestFinalizedHead.IsValid() { - return fmt.Errorf("invalid latestFinalizedHead") + return errors.New("invalid latestFinalizedHead") } // Only continue processing if the latestFinalizedHead has not already been processed // Helps avoid unnecessary processing on every head if blocks are finalized in batches diff --git a/core/chains/evm/txmgr/nonce_tracker_test.go b/core/chains/evm/txmgr/nonce_tracker_test.go index 69f7fe50dd4..e2637389cce 100644 --- a/core/chains/evm/txmgr/nonce_tracker_test.go +++ b/core/chains/evm/txmgr/nonce_tracker_test.go @@ -2,7 +2,6 @@ package txmgr_test import ( "errors" - "fmt" "math/big" "testing" @@ -199,7 +198,7 @@ func TestNonceTracker_GetNextSequence(t *testing.T) { t.Run("fails to get sequence if address doesn't exist in map and is disabled", func(t *testing.T) { _, err := nonceTracker.GetNextSequence(ctx, addr) require.Error(t, err) - require.Contains(t, err.Error(), fmt.Sprintf("address disabled: %s", addr.Hex())) + require.Contains(t, err.Error(), "address disabled: "+addr.Hex()) }) t.Run("fails to get sequence if address is enabled, doesn't exist in map, and getSequenceForAddr fails", func(t *testing.T) { @@ -210,7 +209,7 @@ func TestNonceTracker_GetNextSequence(t *testing.T) { _, err := nonceTracker.GetNextSequence(ctx, addr) require.Error(t, err) - require.Contains(t, err.Error(), fmt.Sprintf("failed to find next sequence for address: %s", addr.Hex())) + require.Contains(t, err.Error(), "failed to find next sequence for address: "+addr.Hex()) }) t.Run("gets next sequence successfully if there is no entry in map but address is enabled and getSequenceForAddr is successful", func(t *testing.T) { diff --git a/core/chains/evm/txmgr/strategies_test.go b/core/chains/evm/txmgr/strategies_test.go index 4b04009fd24..e24e2f5a92a 100644 --- a/core/chains/evm/txmgr/strategies_test.go +++ b/core/chains/evm/txmgr/strategies_test.go @@ -23,7 +23,7 @@ func Test_SendEveryStrategy(t *testing.T) { ids, err := s.PruneQueue(tests.Context(t), nil) assert.NoError(t, err) - assert.Len(t, ids, 0) + assert.Empty(t, ids) } func Test_DropOldestStrategy_Subject(t *testing.T) { diff --git a/core/chains/evm/txmgr/stuck_tx_detector_test.go b/core/chains/evm/txmgr/stuck_tx_detector_test.go index c6a0f5a7a41..1693d4bb778 100644 --- a/core/chains/evm/txmgr/stuck_tx_detector_test.go +++ b/core/chains/evm/txmgr/stuck_tx_detector_test.go @@ -2,6 +2,7 @@ package txmgr_test import ( "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -55,7 +56,7 @@ func TestStuckTxDetector_Disabled(t *testing.T) { t.Run("returns empty list if auto-purge feature is disabled", func(t *testing.T) { txs, err := stuckTxDetector.DetectStuckTransactions(tests.Context(t), []common.Address{fromAddress}, 100) require.NoError(t, err) - require.Len(t, txs, 0) + require.Empty(t, txs) }) } @@ -99,7 +100,7 @@ func TestStuckTxDetector_LoadPurgeBlockNumMap(t *testing.T) { // Run detection logic on autoPurgeThreshold blocks past the latest broadcast attempt txs, err := stuckTxDetector.DetectStuckTransactions(ctx, enabledAddresses, blockNum) require.NoError(t, err) - require.Len(t, txs, 0) + require.Empty(t, txs) }) } @@ -121,7 +122,7 @@ func TestStuckTxDetector_FindPotentialStuckTxs(t *testing.T) { _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) stuckTxs, err := stuckTxDetector.FindUnconfirmedTxWithLowestNonce(ctx, []common.Address{fromAddress}) require.NoError(t, err) - require.Len(t, stuckTxs, 0) + require.Empty(t, stuckTxs) }) t.Run("returns 1 unconfirmed transaction for each unique from address", func(t *testing.T) { @@ -153,7 +154,7 @@ func TestStuckTxDetector_FindPotentialStuckTxs(t *testing.T) { mustInsertUnconfirmedEthTxWithBroadcastPurgeAttempt(t, txStore, 0, fromAddress) stuckTxs, err := stuckTxDetector.FindUnconfirmedTxWithLowestNonce(ctx, []common.Address{fromAddress}) require.NoError(t, err) - require.Len(t, stuckTxs, 0) + require.Empty(t, stuckTxs) }) t.Run("excludes transactions with a in-progress attempt", func(t *testing.T) { @@ -165,7 +166,7 @@ func TestStuckTxDetector_FindPotentialStuckTxs(t *testing.T) { require.NoError(t, txStore.InsertTxAttempt(ctx, &attempt)) stuckTxs, err := stuckTxDetector.FindUnconfirmedTxWithLowestNonce(ctx, []common.Address{fromAddress}) require.NoError(t, err) - require.Len(t, stuckTxs, 0) + require.Empty(t, stuckTxs) }) t.Run("excludes transactions with an insufficient funds attempt", func(t *testing.T) { @@ -177,7 +178,7 @@ func TestStuckTxDetector_FindPotentialStuckTxs(t *testing.T) { require.NoError(t, txStore.InsertTxAttempt(ctx, &attempt)) stuckTxs, err := stuckTxDetector.FindUnconfirmedTxWithLowestNonce(ctx, []common.Address{fromAddress}) require.NoError(t, err) - require.Len(t, stuckTxs, 0) + require.Empty(t, stuckTxs) }) } @@ -217,7 +218,7 @@ func TestStuckTxDetector_DetectStuckTransactionsHeuristic(t *testing.T) { // Run detection logic on the same block number as the latest broadcast attempt to stay within the autoPurgeThreshold txs, err := stuckTxDetector.DetectStuckTransactions(ctx, enabledAddresses, blockNum) require.NoError(t, err) - require.Len(t, txs, 0) + require.Empty(t, txs) }) t.Run("not stuck, Threshold amount of blocks have not passed since last purge", func(t *testing.T) { @@ -234,7 +235,7 @@ func TestStuckTxDetector_DetectStuckTransactionsHeuristic(t *testing.T) { // Run detection logic on autoPurgeThreshold blocks past the latest broadcast attempt txs, err := stuckTxDetector.DetectStuckTransactions(ctx, enabledAddresses, blockNum) require.NoError(t, err) - require.Len(t, txs, 0) + require.Empty(t, txs) }) t.Run("not stuck, MinAttempts amount of attempts have not been broadcasted", func(t *testing.T) { @@ -248,7 +249,7 @@ func TestStuckTxDetector_DetectStuckTransactionsHeuristic(t *testing.T) { // Run detection logic on autoPurgeThreshold blocks past the latest broadcast attempt txs, err := stuckTxDetector.DetectStuckTransactions(ctx, enabledAddresses, blockNum) require.NoError(t, err) - require.Len(t, txs, 0) + require.Empty(t, txs) }) t.Run("not stuck, transaction gas price is lower than market gas price", func(t *testing.T) { @@ -262,7 +263,7 @@ func TestStuckTxDetector_DetectStuckTransactionsHeuristic(t *testing.T) { // Run detection logic on autoPurgeThreshold blocks past the latest broadcast attempt txs, err := stuckTxDetector.DetectStuckTransactions(ctx, enabledAddresses, blockNum) require.NoError(t, err) - require.Len(t, txs, 0) + require.Empty(t, txs) }) t.Run("detects stuck transaction", func(t *testing.T) { @@ -285,7 +286,7 @@ func TestStuckTxDetector_DetectStuckTransactionsHeuristic(t *testing.T) { mustInsertUnconfirmedTxWithBroadcastAttemptsContainsEmptyBroadcastBeforeBlockNum(t, txStore, 0, fromAddress, autoPurgeMinAttempts, marketGasPrice.Add(oneGwei)) txs, err := stuckTxDetector.DetectStuckTransactions(ctx, enabledAddresses, blockNum) require.NoError(t, err) - require.Len(t, txs, 0) + require.Empty(t, txs) }) } @@ -332,7 +333,7 @@ func TestStuckTxDetector_DetectStuckTransactionsZircuit(t *testing.T) { txs, err := stuckTxDetector.DetectStuckTransactions(ctx, []common.Address{fromAddress}, blockNum) require.NoError(t, err) - require.Len(t, txs, 0) + require.Empty(t, txs) }) t.Run("returns fraud transactions identified", func(t *testing.T) { @@ -383,7 +384,7 @@ func TestStuckTxDetector_DetectStuckTransactionsZircuit(t *testing.T) { ethClient.On("BatchCallContext", mock.Anything, mock.MatchedBy(func(b []rpc.BatchElem) bool { return len(b) == 1 && cltest.BatchElemMatchesParams(b[0], attempts.Hash, "zirc_isQuarantined") - })).Return(fmt.Errorf("failed to fetch rpc")) + })).Return(errors.New("failed to fetch rpc")) txs, err := stuckTxDetector.DetectStuckTransactions(ctx, []common.Address{fromAddress}, blockNum) require.NoError(t, err) @@ -424,7 +425,7 @@ func TestStuckTxDetector_DetectStuckTransactionsZkEVM(t *testing.T) { txs, err := stuckTxDetector.DetectStuckTransactions(ctx, []common.Address{fromAddress}, blockNum) require.NoError(t, err) - require.Len(t, txs, 0) + require.Empty(t, txs) }) t.Run("returns stuck transactions discarded by chain", func(t *testing.T) { diff --git a/core/chains/evm/txmgr/txmgr_test.go b/core/chains/evm/txmgr/txmgr_test.go index 9ee2396846d..538e4be4ac3 100644 --- a/core/chains/evm/txmgr/txmgr_test.go +++ b/core/chains/evm/txmgr/txmgr_test.go @@ -147,8 +147,8 @@ func TestTxm_CreateTransaction(t *testing.T) { Strategy: strategy, }) assert.NoError(t, err) - assert.Greater(t, etx.ID, int64(0)) - assert.Equal(t, etx.State, txmgrcommon.TxUnstarted) + assert.Positive(t, etx.ID) + assert.Equal(t, txmgrcommon.TxUnstarted, etx.State) assert.Equal(t, gasLimit, etx.FeeLimit) assert.Equal(t, fromAddress, etx.FromAddress) assert.Equal(t, toAddress, etx.ToAddress) @@ -161,7 +161,7 @@ func TestTxm_CreateTransaction(t *testing.T) { var dbEtx txmgr.DbEthTx require.NoError(t, db.Get(&dbEtx, `SELECT * FROM evm.txes ORDER BY id ASC LIMIT 1`)) - assert.Equal(t, etx.State, txmgrcommon.TxUnstarted) + assert.Equal(t, txmgrcommon.TxUnstarted, etx.State) assert.Equal(t, gasLimit, etx.FeeLimit) assert.Equal(t, fromAddress, etx.FromAddress) assert.Equal(t, toAddress, etx.ToAddress) @@ -642,7 +642,7 @@ func TestTxm_GetTransactionStatus(t *testing.T) { t.Run("returns error if transaction not found", func(t *testing.T) { idempotencyKey := uuid.New().String() state, err := txm.GetTransactionStatus(ctx, idempotencyKey) - require.Error(t, err, fmt.Sprintf("failed to find transaction with IdempotencyKey: %s", idempotencyKey)) + require.Error(t, err, "failed to find transaction with IdempotencyKey: %s", idempotencyKey) require.Equal(t, commontypes.Unknown, state) }) diff --git a/core/chains/evm/types/models_test.go b/core/chains/evm/types/models_test.go index c06d683651a..f6432b38ae0 100644 --- a/core/chains/evm/types/models_test.go +++ b/core/chains/evm/types/models_test.go @@ -139,10 +139,10 @@ func TestHead_AsSlice(t *testing.T) { } h3.Parent.Store(h2) - assert.Len(t, (*evmtypes.Head)(nil).AsSlice(0), 0) - assert.Len(t, (*evmtypes.Head)(nil).AsSlice(1), 0) + assert.Empty(t, (*evmtypes.Head)(nil).AsSlice(0)) + assert.Empty(t, (*evmtypes.Head)(nil).AsSlice(1)) - assert.Len(t, h3.AsSlice(0), 0) + assert.Empty(t, h3.AsSlice(0)) assert.Equal(t, []*evmtypes.Head{h3}, h3.AsSlice(1)) assert.Equal(t, []*evmtypes.Head{h3, h2}, h3.AsSlice(2)) assert.Equal(t, []*evmtypes.Head{h3, h2, h1}, h3.AsSlice(3)) diff --git a/core/chains/evm/types/types_test.go b/core/chains/evm/types/types_test.go index f285849ce92..d02122a2205 100644 --- a/core/chains/evm/types/types_test.go +++ b/core/chains/evm/types/types_test.go @@ -203,12 +203,12 @@ func testHexArrayScan[T ScannableArrayType](t *testing.T, dest T, args HexArrayS err = dest.Scan(src1) require.NoError(t, err) - require.Equal(t, length(dest), 1) + require.Equal(t, 1, length(dest)) assert.Equal(t, get(dest, 0).Bytes(), b1) err = dest.Scan(src2) require.NoError(t, err) - require.Equal(t, length(dest), 3) + require.Equal(t, 3, length(dest)) assert.Equal(t, get(dest, 1).Bytes(), b2) assert.Equal(t, get(dest, 2).Bytes(), b2) diff --git a/core/chains/evm/utils/utils.go b/core/chains/evm/utils/utils.go index ac82dffea48..12bf493af72 100644 --- a/core/chains/evm/utils/utils.go +++ b/core/chains/evm/utils/utils.go @@ -3,6 +3,7 @@ package utils import ( "context" "crypto/rand" + "errors" "fmt" "math/big" "sync/atomic" @@ -67,7 +68,7 @@ func Bytes32ToSlice(a [32]byte) (r []byte) { // Uint256ToBytes is x represented as the bytes of a uint256 func Uint256ToBytes(x *big.Int) (uint256 []byte, err error) { if x.Cmp(MaxUint256) > 0 { - return nil, fmt.Errorf("too large to convert to uint256") + return nil, errors.New("too large to convert to uint256") } uint256 = common.LeftPadBytes(x.Bytes(), EVMWordByteLen) if x.Cmp(big.NewInt(0).SetBytes(uint256)) != 0 { @@ -129,7 +130,7 @@ var zero = big.NewInt(0) // CheckUint256 returns an error if n is out of bounds for a uint256 func CheckUint256(n *big.Int) error { if n.Cmp(zero) < 0 || n.Cmp(MaxUint256) >= 0 { - return fmt.Errorf("number out of range for uint256") + return errors.New("number out of range for uint256") } return nil } diff --git a/core/chains/evm/utils/utils_test.go b/core/chains/evm/utils/utils_test.go index 5798726f2dc..32708718f27 100644 --- a/core/chains/evm/utils/utils_test.go +++ b/core/chains/evm/utils/utils_test.go @@ -101,12 +101,12 @@ func TestClient_ParseEthereumAddress(t *testing.T) { no0xPrefix := address[2:] a2, err := parse(no0xPrefix) assert.NoError(t, err) - assert.True(t, a1 == a2) + assert.Equal(t, a1, a2) _, lowerErr := parse(strings.ToLower(address)) _, upperErr := parse(strings.ToUpper(address)) shouldBeError := multierr.Combine(lowerErr, upperErr) assert.Error(t, shouldBeError) - assert.True(t, strings.Contains(shouldBeError.Error(), no0xPrefix)) + assert.Contains(t, shouldBeError.Error(), no0xPrefix) } _, notHexErr := parse("0xCeci n'est pas une chaîne hexadécimale") assert.Error(t, notHexErr) diff --git a/core/cmd/admin_commands.go b/core/cmd/admin_commands.go index 0af851d2c06..f443145b495 100644 --- a/core/cmd/admin_commands.go +++ b/core/cmd/admin_commands.go @@ -289,7 +289,7 @@ func (s *Shell) DeleteUser(c *cli.Context) (err error) { return s.errorOut(errors.New("email flag is empty, must specify an email")) } - response, err := s.HTTP.Delete(s.ctx(), fmt.Sprintf("/v2/users/%s", email)) + response, err := s.HTTP.Delete(s.ctx(), "/v2/users/"+email) if err != nil { return s.errorOut(err) } @@ -323,7 +323,7 @@ func (s *Shell) Profile(c *cli.Context) error { seconds := c.Uint("seconds") baseDir := c.String("output_dir") - genDir := filepath.Join(baseDir, fmt.Sprintf("debuginfo-%s", time.Now().Format(time.RFC3339))) + genDir := filepath.Join(baseDir, "debuginfo-"+time.Now().Format(time.RFC3339)) if err := os.Mkdir(genDir, 0o755); err != nil { return s.errorOut(err) @@ -415,7 +415,7 @@ func (s *Shell) Profile(c *cli.Context) error { for err := range errs { merr = errors.Join(merr, err) } - return s.errorOut(fmt.Errorf("profile collection failed:\n%v", merr)) + return s.errorOut(fmt.Errorf("profile collection failed:\nwv", merr)) } return nil } diff --git a/core/cmd/app.go b/core/cmd/app.go index 8128d578238..230b045c470 100644 --- a/core/cmd/app.go +++ b/core/cmd/app.go @@ -46,7 +46,7 @@ func NewApp(s *Shell) *cli.App { }, cli.StringFlag{ Name: "admin-credentials-file", - Usage: fmt.Sprintf("optional, applies only in client mode when making remote API calls. If provided, `FILE` containing admin credentials will be used for logging in, allowing to avoid an additional login step. If `FILE` is missing, it will be ignored. Defaults to %s", filepath.Join("", "apicredentials")), + Usage: "optional, applies only in client mode when making remote API calls. If provided, `FILE` containing admin credentials will be used for logging in, allowing to avoid an additional login step. If `FILE` is missing, it will be ignored. Defaults to " + filepath.Join("", "apicredentials"), }, cli.StringFlag{ Name: "remote-node-url", @@ -222,7 +222,7 @@ func NewApp(s *Shell) *cli.App { }, }, Before: func(c *cli.Context) error { - errNoDuplicateFlags := fmt.Errorf("multiple commands with --config or --secrets flags. only one command may specify these flags. when secrets are used, they must be specific together in the same command") + errNoDuplicateFlags := errors.New("multiple commands with --config or --secrets flags. only one command may specify these flags. when secrets are used, they must be specific together in the same command") if c.IsSet("config") { if s.configFilesIsSet || s.secretsFileIsSet { return errNoDuplicateFlags diff --git a/core/cmd/aptos_keys_commands_test.go b/core/cmd/aptos_keys_commands_test.go index c88a8e539a8..5343e3ae601 100644 --- a/core/cmd/aptos_keys_commands_test.go +++ b/core/cmd/aptos_keys_commands_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "flag" - "fmt" "os" "testing" @@ -76,10 +75,10 @@ func TestShell_AptosKeys(t *testing.T) { key, err := app.GetKeyStore().Aptos().Create(ctx) require.NoError(t, err) requireAptosKeyCount(t, app, 1) - assert.Nil(t, cmd.NewAptosKeysClient(client).ListKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, cmd.NewAptosKeysClient(client).ListKeys(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) keys := *r.Renders[0].(*cmd.AptosKeyPresenters) - assert.True(t, key.PublicKeyStr() == keys[0].PubKey) + assert.Equal(t, key.PublicKeyStr(), keys[0].PubKey) }) t.Run("CreateAptosKey", func(tt *testing.T) { @@ -142,7 +141,7 @@ func TestShell_AptosKeys(t *testing.T) { set = flag.NewFlagSet("test Aptos export", 0) flagSetApplyFromAction(cmd.NewAptosKeysClient(client).ExportKey, set, "aptos") - require.NoError(tt, set.Parse([]string{fmt.Sprint(key.ID())})) + require.NoError(tt, set.Parse([]string{key.ID()})) require.NoError(tt, set.Set("new-password", "../internal/fixtures/incorrect_password.txt")) require.NoError(tt, set.Set("output", keyName)) diff --git a/core/cmd/blocks_commands.go b/core/cmd/blocks_commands.go index 158caf253ab..c91c45e2559 100644 --- a/core/cmd/blocks_commands.go +++ b/core/cmd/blocks_commands.go @@ -62,7 +62,7 @@ func (s *Shell) ReplayFromBlock(c *cli.Context) (err error) { v.Add("force", strconv.FormatBool(c.Bool("force"))) if c.IsSet("evm-chain-id") { - v.Add("evmChainID", fmt.Sprintf("%d", c.Int64("evm-chain-id"))) + v.Add("evmChainID", strconv.FormatInt(c.Int64("evm-chain-id"), 10)) } buf := bytes.NewBufferString("{}") @@ -113,14 +113,11 @@ func (s *Shell) FindLCA(c *cli.Context) (err error) { v := url.Values{} if c.IsSet("evm-chain-id") { - v.Add("evmChainID", fmt.Sprintf("%d", c.Int64("evm-chain-id"))) + v.Add("evmChainID", strconv.FormatInt(c.Int64("evm-chain-id"), 10)) } resp, err := s.HTTP.Get(s.ctx(), - fmt.Sprintf( - "/v2/find_lca?%s", - v.Encode(), - )) + "/v2/find_lca?"+v.Encode()) if err != nil { return s.errorOut(err) } diff --git a/core/cmd/bridge_commands_test.go b/core/cmd/bridge_commands_test.go index f05aac52cd9..0a2165d810b 100644 --- a/core/cmd/bridge_commands_test.go +++ b/core/cmd/bridge_commands_test.go @@ -84,9 +84,9 @@ func TestShell_IndexBridges(t *testing.T) { err = app.BridgeORM().CreateBridgeType(ctx, bt2) require.NoError(t, err) - require.Nil(t, client.IndexBridges(cltest.EmptyCLIContext())) + require.NoError(t, client.IndexBridges(cltest.EmptyCLIContext())) bridges := *r.Renders[0].(*cmd.BridgePresenters) - require.Equal(t, 2, len(bridges)) + require.Len(t, bridges, 2) p := bridges[0] assert.Equal(t, bt1.Name.String(), p.Name) assert.Equal(t, bt1.URL.String(), p.URL) @@ -157,7 +157,7 @@ func TestShell_CreateBridge(t *testing.T) { if test.errored { assert.Error(t, client.CreateBridge(c)) } else { - assert.Nil(t, client.CreateBridge(c)) + assert.NoError(t, client.CreateBridge(c)) } }) } diff --git a/core/cmd/cosmos_keys_commands_test.go b/core/cmd/cosmos_keys_commands_test.go index a0a211a1984..0f934a84624 100644 --- a/core/cmd/cosmos_keys_commands_test.go +++ b/core/cmd/cosmos_keys_commands_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "flag" - "fmt" "os" "testing" @@ -76,10 +75,10 @@ func TestShell_CosmosKeys(t *testing.T) { key, err := app.GetKeyStore().Cosmos().Create(ctx) require.NoError(t, err) requireCosmosKeyCount(t, app, 1) - assert.Nil(t, cmd.NewCosmosKeysClient(client).ListKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, cmd.NewCosmosKeysClient(client).ListKeys(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) keys := *r.Renders[0].(*cmd.CosmosKeyPresenters) - assert.True(t, key.PublicKeyStr() == keys[0].PubKey) + assert.Equal(t, key.PublicKeyStr(), keys[0].PubKey) }) t.Run("CreateCosmosKey", func(tt *testing.T) { @@ -142,7 +141,7 @@ func TestShell_CosmosKeys(t *testing.T) { set = flag.NewFlagSet("test Cosmos export", 0) flagSetApplyFromAction(cmd.NewCosmosKeysClient(client).ExportKey, set, "cosmos") - require.NoError(tt, set.Parse([]string{fmt.Sprint(key.ID())})) + require.NoError(tt, set.Parse([]string{key.ID()})) require.NoError(tt, set.Set("new-password", "../internal/fixtures/incorrect_password.txt")) require.NoError(tt, set.Set("output", keyName)) diff --git a/core/cmd/csa_keys_commands_test.go b/core/cmd/csa_keys_commands_test.go index 603e410e199..fa54becda49 100644 --- a/core/cmd/csa_keys_commands_test.go +++ b/core/cmd/csa_keys_commands_test.go @@ -3,7 +3,6 @@ package cmd_test import ( "bytes" "flag" - "fmt" "os" "testing" @@ -64,10 +63,10 @@ func TestShell_ListCSAKeys(t *testing.T) { client, r := app.NewShellAndRenderer() - assert.Nil(t, client.ListCSAKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, client.ListCSAKeys(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) keys := *r.Renders[0].(*cmd.CSAKeyPresenters) - assert.Equal(t, fmt.Sprintf("csa_%s", key.PublicKeyString()), keys[0].PubKey) + assert.Equal(t, "csa_"+key.PublicKeyString(), keys[0].PubKey) } func TestShell_CreateCSAKey(t *testing.T) { @@ -116,7 +115,7 @@ func TestShell_ImportExportCsaKey(t *testing.T) { set = flag.NewFlagSet("test CSA export", 0) flagSetApplyFromAction(client.ExportCSAKey, set, "") - require.NoError(t, set.Parse([]string{fmt.Sprint(key.ID())})) + require.NoError(t, set.Parse([]string{key.ID()})) require.NoError(t, set.Set("new-password", "../internal/fixtures/incorrect_password.txt")) require.NoError(t, set.Set("output", keyName)) @@ -146,6 +145,6 @@ func requireCSAKeyCount(t *testing.T, app chainlink.Application, length int) []c keys, err := app.GetKeyStore().CSA().GetAll() require.NoError(t, err) - require.Equal(t, length, len(keys)) + require.Len(t, keys, length) return keys } diff --git a/core/cmd/eth_keys_commands.go b/core/cmd/eth_keys_commands.go index 5adac3b382b..47b2e024c9d 100644 --- a/core/cmd/eth_keys_commands.go +++ b/core/cmd/eth_keys_commands.go @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "os" + "strconv" "strings" "github.com/pkg/errors" @@ -141,7 +142,7 @@ func (p *EthKeyPresenter) ToRow() []string { p.EVMChainID.String(), eth, link, - fmt.Sprintf("%v", p.Disabled), + strconv.FormatBool(p.Disabled), p.CreatedAt.String(), p.UpdatedAt.String(), gas, diff --git a/core/cmd/eth_keys_commands_test.go b/core/cmd/eth_keys_commands_test.go index 3442fee7e4a..682bc60e0a3 100644 --- a/core/cmd/eth_keys_commands_test.go +++ b/core/cmd/eth_keys_commands_test.go @@ -104,8 +104,8 @@ func TestShell_ListETHKeys(t *testing.T) { ) client, r := app.NewShellAndRenderer() - assert.Nil(t, client.ListETHKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, client.ListETHKeys(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) balances := *r.Renders[0].(*cmd.EthKeyPresenters) assert.Equal(t, app.Keys[0].Address.Hex(), balances[0].Address) assert.Equal(t, "0.000000000000000042", balances[0].EthBalance.String()) @@ -129,8 +129,8 @@ func TestShell_ListETHKeys_Error(t *testing.T) { ) client, r := app.NewShellAndRenderer() - assert.Nil(t, client.ListETHKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, client.ListETHKeys(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) balances := *r.Renders[0].(*cmd.EthKeyPresenters) assert.Equal(t, app.Keys[0].Address.Hex(), balances[0].Address) assert.Nil(t, balances[0].EthBalance) @@ -150,11 +150,11 @@ func TestShell_ListETHKeys_Disabled(t *testing.T) { client, r := app.NewShellAndRenderer() keys, err := app.KeyStore.Eth().GetAll(testutils.Context(t)) require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) k := keys[0] - assert.Nil(t, client.ListETHKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, client.ListETHKeys(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) balances := *r.Renders[0].(*cmd.EthKeyPresenters) assert.Equal(t, app.Keys[0].Address.Hex(), balances[0].Address) assert.Nil(t, balances[0].EthBalance) @@ -188,7 +188,7 @@ func TestShell_CreateETHKey(t *testing.T) { cltest.AssertCount(t, db, "evm.key_states", 1) // The initial funding key keys, err := app.KeyStore.Eth().GetAll(testutils.Context(t)) require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) id := big.NewInt(0) @@ -204,7 +204,7 @@ func TestShell_CreateETHKey(t *testing.T) { cltest.AssertCount(t, db, "evm.key_states", 2) keys, err = app.KeyStore.Eth().GetAll(testutils.Context(t)) require.NoError(t, err) - require.Equal(t, 2, len(keys)) + require.Len(t, keys, 2) } func TestShell_DeleteETHKey(t *testing.T) { diff --git a/core/cmd/evm_transaction_commands.go b/core/cmd/evm_transaction_commands.go index 28a4fa23a3b..c53674e0caa 100644 --- a/core/cmd/evm_transaction_commands.go +++ b/core/cmd/evm_transaction_commands.go @@ -78,7 +78,7 @@ func (p *EthTxPresenter) RenderTable(rt RendererTable) error { p.From.Hex(), p.Nonce, p.To.Hex(), - fmt.Sprint(p.State), + p.State, }) render(fmt.Sprintf("Ethereum Transaction %v", p.Hash.Hex()), table) @@ -97,7 +97,7 @@ func (ps EthTxPresenters) RenderTable(rt RendererTable) error { p.From.Hex(), p.GasPrice, p.SentAt, - fmt.Sprint(p.State), + p.State, }) } diff --git a/core/cmd/evm_transaction_commands_test.go b/core/cmd/evm_transaction_commands_test.go index 77374418a9d..858a4749276 100644 --- a/core/cmd/evm_transaction_commands_test.go +++ b/core/cmd/evm_transaction_commands_test.go @@ -46,7 +46,7 @@ func TestShell_IndexTransactions(t *testing.T) { assert.NoError(t, client.IndexTransactions(c)) renderedTxs := *r.Renders[0].(*cmd.EthTxPresenters) - assert.Equal(t, 1, len(renderedTxs)) + assert.Len(t, renderedTxs, 1) assert.Equal(t, attempt.Hash.String(), renderedTxs[0].Hash.Hex()) // page 2 which doesn't exist @@ -60,7 +60,7 @@ func TestShell_IndexTransactions(t *testing.T) { assert.NoError(t, client.IndexTransactions(c)) renderedTxs = *r.Renders[1].(*cmd.EthTxPresenters) - assert.Equal(t, 0, len(renderedTxs)) + assert.Empty(t, renderedTxs) } func TestShell_ShowTransaction(t *testing.T) { @@ -124,7 +124,7 @@ func TestShell_IndexTxAttempts(t *testing.T) { assert.NoError(t, client.IndexTxAttempts(c)) renderedAttempts = *r.Renders[1].(*cmd.EthTxPresenters) - assert.Equal(t, 0, len(renderedAttempts)) + assert.Empty(t, renderedAttempts) } func TestShell_SendEther_From_Txm(t *testing.T) { diff --git a/core/cmd/forwarders_commands_test.go b/core/cmd/forwarders_commands_test.go index dfd8272d8a4..f3997e771bb 100644 --- a/core/cmd/forwarders_commands_test.go +++ b/core/cmd/forwarders_commands_test.go @@ -86,9 +86,9 @@ func TestShell_TrackEVMForwarder(t *testing.T) { require.True(t, ok, "Expected Renders[0] to be *cmd.EVMForwarderPresenter, got %T", r.Renders[0]) // Assert fwdr is listed - require.Nil(t, client.ListForwarders(cltest.EmptyCLIContext())) + require.NoError(t, client.ListForwarders(cltest.EmptyCLIContext())) fwds := *r.Renders[1].(*cmd.EVMForwarderPresenters) - require.Equal(t, 1, len(fwds)) + require.Len(t, fwds, 1) assert.Equal(t, createOutput.ID, fwds[0].ID) // Delete fwdr @@ -101,10 +101,10 @@ func TestShell_TrackEVMForwarder(t *testing.T) { require.NoError(t, client.DeleteForwarder(c)) // Assert fwdr is not listed - require.Nil(t, client.ListForwarders(cltest.EmptyCLIContext())) + require.NoError(t, client.ListForwarders(cltest.EmptyCLIContext())) require.Len(t, r.Renders, 3) fwds = *r.Renders[2].(*cmd.EVMForwarderPresenters) - require.Equal(t, 0, len(fwds)) + require.Empty(t, fwds) } func TestShell_TrackEVMForwarder_BadAddress(t *testing.T) { diff --git a/core/cmd/jobs_commands_test.go b/core/cmd/jobs_commands_test.go index 77d2487509a..06a7a111355 100644 --- a/core/cmd/jobs_commands_test.go +++ b/core/cmd/jobs_commands_test.go @@ -326,9 +326,9 @@ func TestShell_ListFindJobs(t *testing.T) { createOutput, ok := r.Renders[0].(*cmd.JobPresenter) require.True(t, ok, "Expected Renders[0] to be *cmd.JobPresenter, got %T", r.Renders[0]) - require.Nil(t, client.ListJobs(cltest.EmptyCLIContext())) + require.NoError(t, client.ListJobs(cltest.EmptyCLIContext())) jobs := *r.Renders[1].(*cmd.JobPresenters) - require.Equal(t, 1, len(jobs)) + require.Len(t, jobs, 1) assert.Equal(t, createOutput.ID, jobs[0].ID) } diff --git a/core/cmd/ocr2_keys_commands.go b/core/cmd/ocr2_keys_commands.go index 1d469024878..049acd42513 100644 --- a/core/cmd/ocr2_keys_commands.go +++ b/core/cmd/ocr2_keys_commands.go @@ -149,7 +149,7 @@ func (s *Shell) CreateOCR2KeyBundle(c *cli.Context) error { ) } chainType := c.Args().Get(0) - resp, err := s.HTTP.Post(s.ctx(), fmt.Sprintf("/v2/keys/ocr2/%s", chainType), nil) + resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/ocr2/"+chainType, nil) if err != nil { return s.errorOut(err) } diff --git a/core/cmd/ocr2_keys_commands_test.go b/core/cmd/ocr2_keys_commands_test.go index c2fab273498..c3c0c17c34e 100644 --- a/core/cmd/ocr2_keys_commands_test.go +++ b/core/cmd/ocr2_keys_commands_test.go @@ -90,8 +90,8 @@ func TestShell_OCR2Keys(t *testing.T) { key, err := app.GetKeyStore().OCR2().Create(ctx, "evm") require.NoError(t, err) requireOCR2KeyCount(t, app, 1) - assert.Nil(t, client.ListOCR2KeyBundles(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, client.ListOCR2KeyBundles(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) output := *r.Renders[0].(*cmd.OCR2KeyBundlePresenters) require.Equal(t, key.ID(), output[0].ID) }) @@ -110,7 +110,7 @@ func TestShell_OCR2Keys(t *testing.T) { keys, err := app.GetKeyStore().OCR2().GetAll() require.NoError(t, err) require.Len(t, keys, 1) - require.Equal(t, 1, len(r.Renders)) + require.Len(t, r.Renders, 1) output := (*r.Renders[0].(*cmd.OCR2KeyBundlePresenter)) require.Equal(t, output.ID, keys[0].ID()) }) @@ -132,7 +132,7 @@ func TestShell_OCR2Keys(t *testing.T) { c := cli.NewContext(nil, set, nil) require.NoError(t, client.DeleteOCR2KeyBundle(c)) requireOCR2KeyCount(t, app, 0) - require.Equal(t, 1, len(r.Renders)) + require.Len(t, r.Renders, 1) output := *r.Renders[0].(*cmd.OCR2KeyBundlePresenter) assert.Equal(t, key.ID(), output.ID) }) diff --git a/core/cmd/ocr_keys_commands_test.go b/core/cmd/ocr_keys_commands_test.go index 42d7451edbe..cbe15fc7808 100644 --- a/core/cmd/ocr_keys_commands_test.go +++ b/core/cmd/ocr_keys_commands_test.go @@ -76,8 +76,8 @@ func TestShell_ListOCRKeyBundles(t *testing.T) { requireOCRKeyCount(t, app, 1) - assert.Nil(t, client.ListOCRKeyBundles(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, client.ListOCRKeyBundles(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) output := *r.Renders[0].(*cmd.OCRKeyBundlePresenters) require.Equal(t, key.ID(), output[0].ID) } @@ -96,7 +96,7 @@ func TestShell_CreateOCRKeyBundle(t *testing.T) { require.NoError(t, err) require.Len(t, keys, 1) - require.Equal(t, 1, len(r.Renders)) + require.Len(t, r.Renders, 1) output := *r.Renders[0].(*cmd.OCRKeyBundlePresenter) require.Equal(t, output.ID, keys[0].ID()) } @@ -124,7 +124,7 @@ func TestShell_DeleteOCRKeyBundle(t *testing.T) { require.NoError(t, client.DeleteOCRKeyBundle(c)) requireOCRKeyCount(t, app, 0) // Only fixture key remains - require.Equal(t, 1, len(r.Renders)) + require.Len(t, r.Renders, 1) output := *r.Renders[0].(*cmd.OCRKeyBundlePresenter) assert.Equal(t, key.ID(), output.ID) } diff --git a/core/cmd/p2p_keys_commands_test.go b/core/cmd/p2p_keys_commands_test.go index 12d22e7c16b..df267e08366 100644 --- a/core/cmd/p2p_keys_commands_test.go +++ b/core/cmd/p2p_keys_commands_test.go @@ -3,7 +3,6 @@ package cmd_test import ( "bytes" "flag" - "fmt" "os" "testing" @@ -72,10 +71,10 @@ func TestShell_ListP2PKeys(t *testing.T) { client, r := app.NewShellAndRenderer() - assert.Nil(t, client.ListP2PKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, client.ListP2PKeys(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) keys := *r.Renders[0].(*cmd.P2PKeyPresenters) - assert.True(t, key.PublicKeyHex() == keys[0].PubKey) + assert.Equal(t, key.PublicKeyHex(), keys[0].PubKey) } func TestShell_CreateP2PKey(t *testing.T) { @@ -151,7 +150,7 @@ func TestShell_ImportExportP2PKeyBundle(t *testing.T) { set = flag.NewFlagSet("test P2P export", 0) flagSetApplyFromAction(client.ExportP2PKey, set, "") - require.NoError(t, set.Parse([]string{fmt.Sprint(key.ID())})) + require.NoError(t, set.Parse([]string{key.ID()})) require.NoError(t, set.Set("new-password", "../internal/fixtures/incorrect_password.txt")) require.NoError(t, set.Set("output", keyName)) diff --git a/core/cmd/shell.go b/core/cmd/shell.go index 94664a3cf3d..ea0c744339c 100644 --- a/core/cmd/shell.go +++ b/core/cmd/shell.go @@ -536,7 +536,7 @@ type server struct { func (s *server) run(ip net.IP, port uint16, writeTimeout time.Duration) error { addr := fmt.Sprintf("%s:%d", ip.String(), port) - s.lggr.Infow(fmt.Sprintf("Listening and serving HTTP on %s", addr), "ip", ip, "port", port) + s.lggr.Infow("Listening and serving HTTP on "+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") @@ -544,7 +544,7 @@ func (s *server) run(ip net.IP, port uint16, writeTimeout time.Duration) error { func (s *server) runTLS(ip net.IP, port uint16, certFile, keyFile string, requestTimeout time.Duration) error { addr := fmt.Sprintf("%s:%d", ip.String(), port) - s.lggr.Infow(fmt.Sprintf("Listening and serving HTTPS on %s", addr), "ip", ip, "port", port) + s.lggr.Infow("Listening and serving HTTPS on "+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)") diff --git a/core/cmd/shell_local.go b/core/cmd/shell_local.go index 1fdc1a46d34..18babc150d7 100644 --- a/core/cmd/shell_local.go +++ b/core/cmd/shell_local.go @@ -652,14 +652,14 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { if c.IsSet("password") { pwd, err2 := utils.PasswordFromFile(c.String("password")) if err2 != nil { - return s.errorOut(fmt.Errorf("error reading password: %+v", err2)) + return s.errorOut(fmt.Errorf("error reading password: %+w", err2)) } s.Config.SetPasswords(&pwd, nil) } err = s.Config.Validate() if err != nil { - return s.errorOut(fmt.Errorf("error validating configuration: %+v", err)) + return s.errorOut(fmt.Errorf("error validating configuration: %+w", err)) } err = keyStore.Unlock(ctx, s.Config.Password().Keystore()) @@ -848,7 +848,7 @@ func dropDanglingTestDBs(lggr logger.Logger, db *sqlx.DB) (err error) { defer wg.Done() for dbname := range ch { lggr.Infof("Dropping old, dangling test database: %q", dbname) - gerr := cutils.JustError(db.Exec(fmt.Sprintf(`DROP DATABASE IF EXISTS %s`, dbname))) + gerr := cutils.JustError(db.Exec("DROP DATABASE IF EXISTS " + dbname)) errCh <- gerr } }() @@ -880,7 +880,7 @@ func randomizeTestDBSequences(db *sqlx.DB) error { schemas := pq.Array([]string{"public", "evm"}) seqRows, err := db.Query(`SELECT sequence_schema, sequence_name, minimum_value FROM information_schema.sequences WHERE sequence_schema IN ($1)`, schemas) if err != nil { - return fmt.Errorf("%s: error fetching sequences: %s", failedToRandomizeTestDBSequencesError{}, err) + return fmt.Errorf("%s: error fetching sequences: %w", failedToRandomizeTestDBSequencesError{}, err) } defer seqRows.Close() @@ -888,7 +888,7 @@ func randomizeTestDBSequences(db *sqlx.DB) error { var sequenceSchema, sequenceName string var minimumSequenceValue int64 if err = seqRows.Scan(&sequenceSchema, &sequenceName, &minimumSequenceValue); err != nil { - return fmt.Errorf("%s: failed scanning sequence rows: %s", failedToRandomizeTestDBSequencesError{}, err) + return fmt.Errorf("%s: failed scanning sequence rows: %w", failedToRandomizeTestDBSequencesError{}, err) } if sequenceName == "goose_migrations_id_seq" || sequenceName == "configurations_id_seq" { @@ -963,11 +963,11 @@ func (s *Shell) RollbackDatabase(c *cli.Context) error { db, err := newConnection(ctx, s.Config.Database()) if err != nil { - return fmt.Errorf("failed to initialize orm: %v", err) + return fmt.Errorf("failed to initialize orm: %w", err) } if err := migrate.Rollback(ctx, db.DB, version); err != nil { - return fmt.Errorf("migrateDB failed: %v", err) + return fmt.Errorf("migrateDB failed: %w", err) } return nil @@ -978,12 +978,12 @@ func (s *Shell) VersionDatabase(_ *cli.Context) error { ctx := s.ctx() db, err := newConnection(ctx, s.Config.Database()) if err != nil { - return fmt.Errorf("failed to initialize orm: %v", err) + return fmt.Errorf("failed to initialize orm: %w", err) } version, err := migrate.Current(ctx, db.DB) if err != nil { - return fmt.Errorf("migrateDB failed: %v", err) + return fmt.Errorf("migrateDB failed: %w", err) } s.Logger.Infof("Database version: %v", version) @@ -995,11 +995,11 @@ func (s *Shell) StatusDatabase(_ *cli.Context) error { ctx := s.ctx() db, err := newConnection(ctx, s.Config.Database()) if err != nil { - return fmt.Errorf("failed to initialize orm: %v", err) + return fmt.Errorf("failed to initialize orm: %w", err) } if err = migrate.Status(ctx, db.DB); err != nil { - return fmt.Errorf("Status failed: %v", err) + return fmt.Errorf("Status failed: %w", err) } return nil } @@ -1012,7 +1012,7 @@ func (s *Shell) CreateMigration(c *cli.Context) error { } db, err := newConnection(ctx, s.Config.Database()) if err != nil { - return fmt.Errorf("failed to initialize orm: %v", err) + return fmt.Errorf("failed to initialize orm: %w", err) } migrationType := c.String("type") @@ -1021,7 +1021,7 @@ func (s *Shell) CreateMigration(c *cli.Context) error { } if err = migrate.Create(db.DB, c.Args().First(), migrationType); err != nil { - return fmt.Errorf("Status failed: %v", err) + return fmt.Errorf("Status failed: %w", err) } return nil } @@ -1107,7 +1107,7 @@ func dropAndCreateDB(parsed url.URL, force bool) (err error) { parsed.Path = "/template1" db, err := sql.Open(string(pgcommon.Postgres), parsed.String()) if err != nil { - return fmt.Errorf("unable to open postgres database for creating test db: %+v", err) + return fmt.Errorf("unable to open postgres database for creating test db: %+w", err) } defer func() { if cerr := db.Close(); cerr != nil { @@ -1118,16 +1118,16 @@ func dropAndCreateDB(parsed url.URL, force bool) (err error) { // supports pg < 13. https://stackoverflow.com/questions/17449420/postgresql-unable-to-drop-database-because-of-some-auto-connections-to-db _, err = db.Exec(fmt.Sprintf("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '%s';", dbname)) if err != nil { - return fmt.Errorf("unable to terminate connections to postgres database: %v", err) + return fmt.Errorf("unable to terminate connections to postgres database: %w", err) } } _, err = db.Exec(fmt.Sprintf(`DROP DATABASE IF EXISTS "%s"`, dbname)) if err != nil { - return fmt.Errorf("unable to drop postgres database: %v", err) + return fmt.Errorf("unable to drop postgres database: %w", err) } _, err = db.Exec(fmt.Sprintf(`CREATE DATABASE "%s"`, dbname)) if err != nil { - return fmt.Errorf("unable to create postgres database: %v", err) + return fmt.Errorf("unable to create postgres database: %w", err) } return nil } @@ -1135,11 +1135,11 @@ func dropAndCreateDB(parsed url.URL, force bool) (err error) { func dropAndCreatePristineDB(db *sqlx.DB, template string) (err error) { _, err = db.Exec(fmt.Sprintf(`DROP DATABASE IF EXISTS "%s"`, testdb.PristineDBName)) if err != nil { - return fmt.Errorf("unable to drop postgres database: %v", err) + return fmt.Errorf("unable to drop postgres database: %w", err) } _, err = db.Exec(fmt.Sprintf(`CREATE DATABASE "%s" WITH TEMPLATE "%s"`, testdb.PristineDBName, template)) if err != nil { - return fmt.Errorf("unable to create postgres database: %v", err) + return fmt.Errorf("unable to create postgres database: %w", err) } return nil } @@ -1147,11 +1147,11 @@ func dropAndCreatePristineDB(db *sqlx.DB, template string) (err error) { func migrateDB(ctx context.Context, config dbConfig) error { db, err := newConnection(ctx, config) if err != nil { - return fmt.Errorf("failed to initialize orm: %v", err) + return fmt.Errorf("failed to initialize orm: %w", err) } if err = migrate.Migrate(ctx, db.DB); err != nil { - return fmt.Errorf("migrateDB failed: %v", err) + return fmt.Errorf("migrateDB failed: %w", err) } return db.Close() } @@ -1159,13 +1159,13 @@ func migrateDB(ctx context.Context, config dbConfig) error { func downAndUpDB(ctx context.Context, cfg dbConfig, baseVersionID int64) error { db, err := newConnection(ctx, cfg) if err != nil { - return fmt.Errorf("failed to initialize orm: %v", err) + return fmt.Errorf("failed to initialize orm: %w", err) } if err = migrate.Rollback(ctx, db.DB, null.IntFrom(baseVersionID)); err != nil { - return fmt.Errorf("test rollback failed: %v", err) + return fmt.Errorf("test rollback failed: %w", err) } if err = migrate.Migrate(ctx, db.DB); err != nil { - return fmt.Errorf("second migrateDB failed: %v", err) + return fmt.Errorf("second migrateDB failed: %w", err) } return db.Close() } @@ -1183,9 +1183,9 @@ func dumpSchema(dbURL url.URL) (string, error) { if err != nil { var ee *exec.ExitError if errors.As(err, &ee) { - return "", fmt.Errorf("failed to dump schema: %v\n%s", err, string(ee.Stderr)) + return "", fmt.Errorf("failed to dump schema: %w\n%s", err, string(ee.Stderr)) } - return "", fmt.Errorf("failed to dump schema: %v", err) + return "", fmt.Errorf("failed to dump schema: %w", err) } return string(schema), nil } @@ -1206,7 +1206,7 @@ func checkSchema(dbURL url.URL, prevSchema string) error { func insertFixtures(dbURL url.URL, pathToFixtures string) (err error) { db, err := sql.Open(string(pgcommon.Postgres), dbURL.String()) if err != nil { - return fmt.Errorf("unable to open postgres database for creating test db: %+v", err) + return fmt.Errorf("unable to open postgres database for creating test db: %+w", err) } defer func() { if cerr := db.Close(); cerr != nil { @@ -1245,7 +1245,7 @@ func (s *Shell) RemoveBlocks(c *cli.Context) error { cfg := s.Config err := cfg.Validate() if err != nil { - return s.errorOut(fmt.Errorf("error validating configuration: %+v", err)) + return s.errorOut(fmt.Errorf("error validating configuration: %+w", err)) } lggr := logger.Sugared(s.Logger.Named("RemoveBlocks")) diff --git a/core/cmd/shell_local_test.go b/core/cmd/shell_local_test.go index 7cdc8c21840..2b4b2a6356b 100644 --- a/core/cmd/shell_local_test.go +++ b/core/cmd/shell_local_test.go @@ -1,8 +1,8 @@ package cmd_test import ( + "errors" "flag" - "fmt" "math/big" "os" "strconv" @@ -553,7 +553,7 @@ func TestShell_RemoveBlocks(t *testing.T) { flagSetApplyFromAction(shell.RemoveBlocks, set, "") require.NoError(t, set.Set("start", "10000")) require.NoError(t, set.Set("evm-chain-id", "12")) - expectedError := fmt.Errorf("failed to delete log poller's data") + expectedError := errors.New("failed to delete log poller's data") app.On("DeleteLogPollerDataAfter", mock.Anything, big.NewInt(12), int64(10000)).Return(expectedError).Once() c := cli.NewContext(nil, set, nil) err := shell.RemoveBlocks(c) diff --git a/core/cmd/shell_remote.go b/core/cmd/shell_remote.go index 0aa3f3837dc..39e69f49d9a 100644 --- a/core/cmd/shell_remote.go +++ b/core/cmd/shell_remote.go @@ -72,7 +72,7 @@ func initRemoteConfigSubCmds(s *Shell) []cli.Command { Name: "validate", Usage: "DEPRECATED. Use `chainlink node validate`", Before: func(c *cli.Context) error { - return s.errorOut(fmt.Errorf("Deprecated, use `chainlink node validate`")) + return s.errorOut(errors.New("Deprecated, use `chainlink node validate`")) }, Hidden: true, }, @@ -263,7 +263,7 @@ func getTOMLString(s string) (string, error) { if os.IsNotExist(err) { return "", fmt.Errorf("invalid TOML or file not found '%s'", s) } else if err != nil { - return "", fmt.Errorf("error reading from file '%s': %v", s, err) + return "", fmt.Errorf("error reading from file '%s': %w", s, err) } return buf.String(), nil } @@ -271,7 +271,7 @@ 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'"))) + return nil, s.errorOut(multierr.Append(err, errors.New("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) { @@ -407,7 +407,7 @@ func getBufferFromJSON(s string) (*bytes.Buffer, error) { if os.IsNotExist(err) { return nil, fmt.Errorf("invalid JSON or file not found '%s'", s) } else if err != nil { - return nil, fmt.Errorf("error reading from file '%s': %v", s, err) + return nil, fmt.Errorf("error reading from file '%s': %w", s, err) } return buf, nil } diff --git a/core/cmd/shell_remote_test.go b/core/cmd/shell_remote_test.go index 0bf5067d364..c4e3243dd71 100644 --- a/core/cmd/shell_remote_test.go +++ b/core/cmd/shell_remote_test.go @@ -494,7 +494,7 @@ func TestShell_Profile(t *testing.T) { ents, err := os.ReadDir(tDir) require.NoError(t, err) - require.Greater(t, len(ents), 0, "ents %+v", ents) + require.NotEmpty(t, ents, "ents %+v", ents) } func TestShell_Profile_Unauthenticated(t *testing.T) { diff --git a/core/cmd/shell_test.go b/core/cmd/shell_test.go index e73e1d51f24..f7bcffb035b 100644 --- a/core/cmd/shell_test.go +++ b/core/cmd/shell_test.go @@ -410,7 +410,7 @@ func TestSetupSolanaRelayer(t *testing.T) { require.NotNil(t, relayers) require.Len(t, relayers, nEnabledChains) // no using plugin, so registry should be empty - require.Len(t, reg.List(), 0) + require.Empty(t, reg.List()) }) t.Run("plugin", func(t *testing.T) { @@ -536,7 +536,7 @@ func TestSetupStarkNetRelayer(t *testing.T) { require.NotNil(t, relayers) require.Len(t, relayers, nEnabledChains) // no using plugin, so registry should be empty - require.Len(t, reg.List(), 0) + require.Empty(t, reg.List()) }) t.Run("plugin", func(t *testing.T) { diff --git a/core/cmd/solana_keys_commands_test.go b/core/cmd/solana_keys_commands_test.go index 02b06f6596a..ca6c4678b8d 100644 --- a/core/cmd/solana_keys_commands_test.go +++ b/core/cmd/solana_keys_commands_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "flag" - "fmt" "os" "testing" @@ -76,10 +75,10 @@ func TestShell_SolanaKeys(t *testing.T) { key, err := app.GetKeyStore().Solana().Create(ctx) require.NoError(t, err) requireSolanaKeyCount(t, app, 1) - assert.Nil(t, cmd.NewSolanaKeysClient(client).ListKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, cmd.NewSolanaKeysClient(client).ListKeys(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) keys := *r.Renders[0].(*cmd.SolanaKeyPresenters) - assert.True(t, key.PublicKeyStr() == keys[0].PubKey) + assert.Equal(t, key.PublicKeyStr(), keys[0].PubKey) }) t.Run("CreateSolanaKey", func(tt *testing.T) { @@ -142,7 +141,7 @@ func TestShell_SolanaKeys(t *testing.T) { set = flag.NewFlagSet("test Solana export", 0) flagSetApplyFromAction(cmd.NewSolanaKeysClient(client).ExportKey, set, "solana") - require.NoError(tt, set.Parse([]string{fmt.Sprint(key.ID())})) + require.NoError(tt, set.Parse([]string{key.ID()})) require.NoError(tt, set.Set("new-password", "../internal/fixtures/incorrect_password.txt")) require.NoError(tt, set.Set("output", keyName)) diff --git a/core/cmd/starknet_keys_commands_test.go b/core/cmd/starknet_keys_commands_test.go index 4f4b0bf6b77..683a78cb3ee 100644 --- a/core/cmd/starknet_keys_commands_test.go +++ b/core/cmd/starknet_keys_commands_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "flag" - "fmt" "os" "testing" @@ -75,10 +74,10 @@ func TestShell_StarkNetKeys(t *testing.T) { key, err := app.GetKeyStore().StarkNet().Create(ctx) require.NoError(t, err) requireStarkNetKeyCount(t, app, 1) - assert.Nil(t, cmd.NewStarkNetKeysClient(client).ListKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + assert.NoError(t, cmd.NewStarkNetKeysClient(client).ListKeys(cltest.EmptyCLIContext())) + require.Len(t, r.Renders, 1) keys := *r.Renders[0].(*cmd.StarkNetKeyPresenters) - assert.True(t, key.StarkKeyStr() == keys[0].StarkKey) + assert.Equal(t, key.StarkKeyStr(), keys[0].StarkKey) }) t.Run("CreateStarkNetKey", func(tt *testing.T) { @@ -141,7 +140,7 @@ func TestShell_StarkNetKeys(t *testing.T) { set = flag.NewFlagSet("test StarkNet export", 0) flagSetApplyFromAction(cmd.NewStarkNetKeysClient(client).ExportKey, set, "starknet") - require.NoError(tt, set.Parse([]string{fmt.Sprint(key.ID())})) + require.NoError(tt, set.Parse([]string{key.ID()})) require.NoError(tt, set.Set("new-password", "../internal/fixtures/incorrect_password.txt")) require.NoError(tt, set.Set("output", keyName)) diff --git a/core/cmd/vrf_keys_commands.go b/core/cmd/vrf_keys_commands.go index 32d32334af5..fef62a2dec1 100644 --- a/core/cmd/vrf_keys_commands.go +++ b/core/cmd/vrf_keys_commands.go @@ -265,7 +265,7 @@ func (s *Shell) DeleteVRFKey(c *cli.Context) error { func getPublicKey(c *cli.Context) (secp256k1.PublicKey, error) { pkHexString := c.Args().Get(0) if pkHexString == "" { - return secp256k1.PublicKey{}, fmt.Errorf("must specify public key") + return secp256k1.PublicKey{}, errors.New("must specify public key") } publicKey, err := secp256k1.NewPublicKeyFromHex(pkHexString) if err != nil { diff --git a/core/cmd/vrf_keys_commands_test.go b/core/cmd/vrf_keys_commands_test.go index f912e861a64..0876a64bcbb 100644 --- a/core/cmd/vrf_keys_commands_test.go +++ b/core/cmd/vrf_keys_commands_test.go @@ -75,30 +75,30 @@ func TestShellVRF_CRUD(t *testing.T) { client, r := app.NewShellAndRenderer() require.NoError(t, client.ListVRFKeys(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + require.Len(t, r.Renders, 1) keys := *r.Renders[0].(*cmd.VRFKeyPresenters) // No keys yet - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) // Create a VRF key require.NoError(t, client.CreateVRFKey(cltest.EmptyCLIContext())) - require.Equal(t, 2, len(r.Renders)) + require.Len(t, r.Renders, 2) k1 := *r.Renders[1].(*cmd.VRFKeyPresenter) // List the key and ensure it matches require.NoError(t, client.ListVRFKeys(cltest.EmptyCLIContext())) - require.Equal(t, 3, len(r.Renders)) + require.Len(t, r.Renders, 3) keys = *r.Renders[2].(*cmd.VRFKeyPresenters) AssertKeysEqual(t, k1, keys[0]) // Create another key require.NoError(t, client.CreateVRFKey(cltest.EmptyCLIContext())) - require.Equal(t, 4, len(r.Renders)) + require.Len(t, r.Renders, 4) k2 := *r.Renders[3].(*cmd.VRFKeyPresenter) // Ensure the list is valid require.NoError(t, client.ListVRFKeys(cltest.EmptyCLIContext())) - require.Equal(t, 5, len(r.Renders)) + require.Len(t, r.Renders, 5) keys = *r.Renders[4].(*cmd.VRFKeyPresenters) require.Contains(t, []string{keys[0].ID, keys[1].ID}, k1.ID) require.Contains(t, []string{keys[0].ID, keys[1].ID}, k2.ID) @@ -115,13 +115,13 @@ func TestShellVRF_CRUD(t *testing.T) { err := client.DeleteVRFKey(c) require.NoError(t, err) // Should return the deleted key - require.Equal(t, 6, len(r.Renders)) + require.Len(t, r.Renders, 6) deletedKey := *r.Renders[5].(*cmd.VRFKeyPresenter) AssertKeysEqual(t, k2, deletedKey) // Should NOT be in the DB as archived allKeys, err := app.KeyStore.VRF().GetAll() require.NoError(t, err) - assert.Equal(t, 1, len(allKeys)) + assert.Len(t, allKeys, 1) } func TestVRF_ImportExport(t *testing.T) { @@ -134,7 +134,7 @@ func TestVRF_ImportExport(t *testing.T) { // Create a key (encrypted with cltest.VRFPassword) require.NoError(t, client.CreateVRFKey(cltest.EmptyCLIContext())) - require.Equal(t, 1, len(r.Renders)) + require.Len(t, r.Renders, 1) k1 := *r.Renders[0].(*cmd.VRFKeyPresenter) t.Log(k1.Compressed) @@ -177,7 +177,7 @@ func TestVRF_ImportExport(t *testing.T) { // Should succeed require.NoError(t, client.ImportVRFKey(importCli)) require.NoError(t, client.ListVRFKeys(cltest.EmptyCLIContext())) - require.Equal(t, 4, len(r.Renders)) + require.Len(t, r.Renders, 4) keys := *r.Renders[3].(*cmd.VRFKeyPresenters) AssertKeysEqualNoTimestamps(t, k1, keys[0]) } diff --git a/core/config/docs/docs_test.go b/core/config/docs/docs_test.go index 9fca08ee99b..2f51ae4d630 100644 --- a/core/config/docs/docs_test.go +++ b/core/config/docs/docs_test.go @@ -52,7 +52,7 @@ func TestDoc(t *testing.T) { docDefaults.ChainType = nil // clean up KeySpecific as a special case - require.Equal(t, 1, len(docDefaults.KeySpecific)) + require.Len(t, docDefaults.KeySpecific, 1) ks := evmcfg.KeySpecific{Key: new(types.EIP55Address), GasEstimator: evmcfg.KeySpecificGasEstimator{PriceMax: new(assets.Wei)}} require.Equal(t, ks, docDefaults.KeySpecific[0]) diff --git a/core/config/toml/types.go b/core/config/toml/types.go index 620f7d96eee..a7cdba834ab 100644 --- a/core/config/toml/types.go +++ b/core/config/toml/types.go @@ -150,12 +150,12 @@ func validateDBURL(dbURI url.URL) error { // fallback to user info userInfo := dbURI.User if userInfo == nil { - return fmt.Errorf("DB URL must be authenticated; plaintext URLs are not allowed") + return errors.New("DB URL must be authenticated; plaintext URLs are not allowed") } var pwSet bool pw, pwSet = userInfo.Password() if !pwSet { - return fmt.Errorf("DB URL must be authenticated; password is required") + return errors.New("DB URL must be authenticated; password is required") } } diff --git a/core/config/toml/types_test.go b/core/config/toml/types_test.go index 9c3fd1d02df..8b6d626f6df 100644 --- a/core/config/toml/types_test.go +++ b/core/config/toml/types_test.go @@ -101,7 +101,7 @@ func Test_validateDBURL(t *testing.T) { url := testutils.MustParseURL(t, test.url) err := validateDBURL(*url) if test.wantErr == "" { - assert.Nil(t, err) + assert.NoError(t, err) } else { assert.EqualError(t, err, test.wantErr) } diff --git a/core/gethwrappers/generation/generate_events_mock/create_events_mock_contract.go b/core/gethwrappers/generation/generate_events_mock/create_events_mock_contract.go index 0c72cfc00c6..b0bdbb3a6d6 100644 --- a/core/gethwrappers/generation/generate_events_mock/create_events_mock_contract.go +++ b/core/gethwrappers/generation/generate_events_mock/create_events_mock_contract.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "strconv" "strings" "text/template" @@ -107,7 +108,7 @@ func extractEventsAndStructs(abiJSON []byte) ([]SolEvent, []SolStruct, error) { for i, input := range item.Inputs { if input.Name == "" { - input.Name = "param" + fmt.Sprintf("%d", i+1) + input.Name = "param" + strconv.Itoa(i+1) } if input.Type == "tuple" && strings.Contains(input.InternalType, "struct") { internalType := strings.TrimPrefix(input.InternalType, "struct ") diff --git a/core/gethwrappers/go_generate_test.go b/core/gethwrappers/go_generate_test.go index 1066149278f..2fbbfe8abfc 100644 --- a/core/gethwrappers/go_generate_test.go +++ b/core/gethwrappers/go_generate_test.go @@ -52,8 +52,7 @@ func TestCheckContractHashesFromLastGoGenerate(t *testing.T) { // Just check that LinkToken details haven't changed (they never ought to) linkDetails, err := os.ReadFile(filepath.Join(getProjectRoot(t), "contracts/LinkToken.json")) require.NoError(t, err, "could not read link contract details") - require.Equal(t, fmt.Sprintf("%x", sha256.Sum256(linkDetails)), - "27c0e17a79553fccc63a4400c6bbe415ff710d9cc7c25757bff0f7580205c922", + require.Equal(t, "27c0e17a79553fccc63a4400c6bbe415ff710d9cc7c25757bff0f7580205c922", fmt.Sprintf("%x", sha256.Sum256(linkDetails)), "should never differ!") } diff --git a/core/internal/cltest/cltest.go b/core/internal/cltest/cltest.go index a55c57cc9a2..60ddecd4841 100644 --- a/core/internal/cltest/cltest.go +++ b/core/internal/cltest/cltest.go @@ -818,7 +818,7 @@ func ParseJSONAPIResponse(t testing.TB, resp *http.Response, resource interface{ input := ParseResponseBody(t, resp) err := jsonapi.Unmarshal(input, resource) if err != nil { - return fmt.Errorf("web: unable to unmarshal data, %+v", err) + return fmt.Errorf("web: unable to unmarshal data, %+w", err) } return nil @@ -1535,7 +1535,7 @@ func AssertCountStays(t testing.TB, ds sqlutil.DataSource, tableName string, wan var count int64 var err error g.Consistently(func() int64 { - err = ds.GetContext(ctx, &count, fmt.Sprintf(`SELECT count(*) FROM %s`, tableName)) + err = ds.GetContext(ctx, &count, "SELECT count(*) FROM "+tableName) assert.NoError(t, err) return count }, AssertNoActionTimeout, DBPollingInterval).Should(gomega.Equal(want)) @@ -1567,7 +1567,7 @@ func ClearDBTables(t *testing.T, db *sqlx.DB, tables ...string) { require.NoError(t, err) for _, table := range tables { - _, err = tx.Exec(fmt.Sprintf("DELETE FROM %s", table)) + _, err = tx.Exec("DELETE FROM " + table) require.NoError(t, err) } diff --git a/core/internal/cltest/factories.go b/core/internal/cltest/factories.go index 9b076185d66..7261fef37c9 100644 --- a/core/internal/cltest/factories.go +++ b/core/internal/cltest/factories.go @@ -82,13 +82,13 @@ func NewBridgeType(t testing.TB, opts BridgeOpts) (*bridges.BridgeTypeAuthentica if opts.Name != "" { btr.Name = bridges.MustParseBridgeName(opts.Name) } else { - btr.Name = bridges.MustParseBridgeName(fmt.Sprintf("test_bridge_%s", rnd)) + btr.Name = bridges.MustParseBridgeName("test_bridge_" + rnd) } if opts.URL != "" { btr.URL = WebURL(t, opts.URL) } else { - btr.URL = WebURL(t, fmt.Sprintf("https://bridge.example.com/api?%s", rnd)) + btr.URL = WebURL(t, "https://bridge.example.com/api?"+rnd) } bta, bt, err := bridges.NewBridgeType(btr) diff --git a/core/internal/features/features_test.go b/core/internal/features/features_test.go index 88305403f2b..3e0d3e83f01 100644 --- a/core/internal/features/features_test.go +++ b/core/internal/features/features_test.go @@ -1025,7 +1025,7 @@ observationSource = """ } metaLock.Lock() defer metaLock.Unlock() - assert.Len(t, expectedMeta, 0, "expected metadata %v", expectedMeta) + assert.Empty(t, expectedMeta, "expected metadata %v", expectedMeta) }) } } @@ -1255,7 +1255,7 @@ observationSource = """ } metaLock.Lock() defer metaLock.Unlock() - assert.Len(t, expectedMeta, 0, "expected metadata %v", expectedMeta) + assert.Empty(t, expectedMeta, "expected metadata %v", expectedMeta) }) } @@ -1393,13 +1393,13 @@ func triggerAllKeys(t *testing.T, app *cltest.TestApplication) { func assertPricesUint256(t *testing.T, usd, eur, jpy *big.Int, consumer *multiwordconsumer_wrapper.MultiWordConsumer) { haveUsd, err := consumer.UsdInt(nil) require.NoError(t, err) - assert.True(t, usd.Cmp(haveUsd) == 0) + assert.Equal(t, usd.Cmp(haveUsd), 0) haveEur, err := consumer.EurInt(nil) require.NoError(t, err) - assert.True(t, eur.Cmp(haveEur) == 0) + assert.Equal(t, eur.Cmp(haveEur), 0) haveJpy, err := consumer.JpyInt(nil) require.NoError(t, err) - assert.True(t, jpy.Cmp(haveJpy) == 0) + assert.Equal(t, jpy.Cmp(haveJpy), 0) } func ptr[T any](v T) *T { return &v } @@ -1407,13 +1407,13 @@ func ptr[T any](v T) *T { return &v } func assertPipelineTaskRunsSuccessful(t testing.TB, runs []pipeline.TaskRun) { t.Helper() for i, run := range runs { - require.True(t, run.Error.IsZero(), fmt.Sprintf("pipeline.Task run failed (idx: %v, dotID: %v, error: '%v')", i, run.GetDotID(), run.Error.ValueOrZero())) + require.True(t, run.Error.IsZero(), "pipeline.Task run failed (idx: %v, dotID: %v, error: '%v')", i, run.GetDotID(), run.Error.ValueOrZero()) } } func assertPipelineTaskRunsErrored(t testing.TB, runs []pipeline.TaskRun) { t.Helper() for i, run := range runs { - require.False(t, run.Error.IsZero(), fmt.Sprintf("expected pipeline.Task run to have failed, but it succeeded (idx: %v, dotID: %v, output: '%v')", i, run.GetDotID(), run.Output)) + require.False(t, run.Error.IsZero(), "expected pipeline.Task run to have failed, but it succeeded (idx: %v, dotID: %v, output: '%v')", i, run.GetDotID(), run.Output) } } diff --git a/core/internal/features/ocr2/features_ocr2_test.go b/core/internal/features/ocr2/features_ocr2_test.go index 01c269d19e3..a5117a50b1e 100644 --- a/core/internal/features/ocr2/features_ocr2_test.go +++ b/core/internal/features/ocr2/features_ocr2_test.go @@ -259,7 +259,7 @@ updateInterval = "1m" metaLock.Lock() maps.Copy(em, expectedMeta) metaLock.Unlock() - assert.Len(t, em, 0, "expected metadata %v", em) + assert.Empty(t, em, "expected metadata %v", em) // Assert we can read the latest config digest and epoch after a report has been submitted. contractABI, err := abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorABI)) diff --git a/core/internal/testutils/logger.go b/core/internal/testutils/logger.go index d3d5cd3f3bc..f3db412c0db 100644 --- a/core/internal/testutils/logger.go +++ b/core/internal/testutils/logger.go @@ -20,7 +20,7 @@ func LoggerAssertMaxLevel(t *testing.T, lvl zapcore.Level) logger.Logger { } lggr, o := logger.TestLoggerObserved(t, lvl+1) t.Cleanup(func() { - assert.Empty(t, o.Len(), fmt.Sprintf("logger contains entries with levels above %q:\n%s", lvl, loggedEntries(o.All()))) + assert.Empty(t, o.Len(), "logger contains entries with levels above %q:\n%s", lvl, loggedEntries(o.All())) }) return lggr } diff --git a/core/internal/testutils/wasmtest/wasm.go b/core/internal/testutils/wasmtest/wasm.go index 056a40f56ce..b8de86f7344 100644 --- a/core/internal/testutils/wasmtest/wasm.go +++ b/core/internal/testutils/wasmtest/wasm.go @@ -2,7 +2,6 @@ package wasmtest import ( "bytes" - "fmt" "io" "os" "os/exec" @@ -13,7 +12,7 @@ import ( ) func CreateTestBinary(outputPath, path string, compress bool, t *testing.T) []byte { - cmd := exec.Command("go", "build", "-o", path, fmt.Sprintf("github.com/smartcontractkit/chainlink/v2/%s", outputPath)) // #nosec + cmd := exec.Command("go", "build", "-o", path, "github.com/smartcontractkit/chainlink/v2/"+outputPath) // #nosec cmd.Env = append(os.Environ(), "GOOS=wasip1", "GOARCH=wasm") output, err := cmd.CombinedOutput() diff --git a/core/logger/audit/audit_logger_test.go b/core/logger/audit/audit_logger_test.go index a28c35b129d..f3a41821b85 100644 --- a/core/logger/audit/audit_logger_test.go +++ b/core/logger/audit/audit_logger_test.go @@ -134,10 +134,10 @@ func TestCheckLoginAuditLog(t *testing.T) { deserialized := &LoginLogItem{} assert.NoError(t, json.Unmarshal([]byte(event.body), deserialized)) - assert.Equal(t, deserialized.Data.Email, cltest.APIEmailAdmin) - assert.Equal(t, deserialized.Env, "test") + assert.Equal(t, cltest.APIEmailAdmin, deserialized.Data.Email) + assert.Equal(t, "test", deserialized.Env) - assert.Equal(t, deserialized.EventID, "AUTH_LOGIN_SUCCESS_NO_2FA") + assert.Equal(t, "AUTH_LOGIN_SUCCESS_NO_2FA", deserialized.EventID) return case <-time.After(5 * time.Second): } diff --git a/core/logger/null_logger_test.go b/core/logger/null_logger_test.go index f36b7d7d622..6df99942647 100644 --- a/core/logger/null_logger_test.go +++ b/core/logger/null_logger_test.go @@ -51,6 +51,6 @@ func TestNullLogger(t *testing.T) { l.Panicw("msg") l.Fatalw("msg") l.Recover(nil) - assert.Nil(t, l.Sync()) + assert.NoError(t, l.Sync()) }) } diff --git a/core/logger/test_logger_test.go b/core/logger/test_logger_test.go index feafbc69c9e..38206a1d321 100644 --- a/core/logger/test_logger_test.go +++ b/core/logger/test_logger_test.go @@ -48,7 +48,7 @@ func TestTestLogger(t *testing.T) { assert.Equal(t, serviceName, log.LoggerName) assert.Equal(t, value, log.ContextMap()[key]) assert.Contains(t, log.Caller.String(), "core/logger/test_logger_test.go") - assert.Equal(t, log.Caller.Line, 41) + assert.Equal(t, 41, log.Caller.Line) const ( workerName = "WorkerName" diff --git a/core/null/int64_test.go b/core/null/int64_test.go index 7a692729614..a3cbadf4357 100644 --- a/core/null/int64_test.go +++ b/core/null/int64_test.go @@ -2,7 +2,6 @@ package null_test import ( "encoding/json" - "fmt" "math" "strconv" "testing" @@ -22,7 +21,7 @@ func TestInt64From(t *testing.T) { } for _, test := range tests { - t.Run(fmt.Sprintf("%d", test.input), func(t *testing.T) { + t.Run(strconv.FormatInt(test.input, 10), func(t *testing.T) { i := null.Int64From(test.input) assert.True(t, i.Valid) assert.Equal(t, test.input, i.Int64) diff --git a/core/null/uint32_test.go b/core/null/uint32_test.go index 4b7a6c56506..45a9cc223f1 100644 --- a/core/null/uint32_test.go +++ b/core/null/uint32_test.go @@ -2,7 +2,6 @@ package null_test import ( "encoding/json" - "fmt" "math" "strconv" "testing" @@ -22,7 +21,7 @@ func TestUint32From(t *testing.T) { } for _, test := range tests { - t.Run(fmt.Sprintf("%d", test.input), func(t *testing.T) { + t.Run(strconv.FormatUint(uint64(test.input), 10), func(t *testing.T) { i := null.Uint32From(test.input) assert.True(t, i.Valid) assert.Equal(t, test.input, i.Uint32) diff --git a/core/services/blockhashstore/feeder.go b/core/services/blockhashstore/feeder.go index e5367cba697..de812e0c604 100644 --- a/core/services/blockhashstore/feeder.go +++ b/core/services/blockhashstore/feeder.go @@ -2,7 +2,6 @@ package blockhashstore import ( "context" - "fmt" "sync" "time" @@ -87,7 +86,7 @@ func (f *Feeder) StartHeartbeats(ctx context.Context, timer Timer) { f.lggr.Infow("Not starting heartbeat blockhash using storeEarliest") return } - f.lggr.Infow(fmt.Sprintf("Starting heartbeat blockhash using storeEarliest every %s", f.heartbeatPeriod.String())) + f.lggr.Infow("Starting heartbeat blockhash using storeEarliest every " + f.heartbeatPeriod.String()) for { after := timer.After(f.heartbeatPeriod) select { diff --git a/core/services/blockhashstore/feeder_test.go b/core/services/blockhashstore/feeder_test.go index 5a35fe57593..74e5d340ebe 100644 --- a/core/services/blockhashstore/feeder_test.go +++ b/core/services/blockhashstore/feeder_test.go @@ -2,7 +2,6 @@ package blockhashstore import ( "context" - "fmt" "math/big" "testing" "time" @@ -10,6 +9,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "golang.org/x/exp/maps" @@ -273,7 +273,7 @@ func TestStartHeartbeats(t *testing.T) { t.Run("bhs_heartbeat_sad_path_store_earliest_err", func(t *testing.T) { expectedDuration := 600 * time.Second - expectedError := fmt.Errorf("insufficient gas") + expectedError := errors.New("insufficient gas") mockBHS := bhsmocks.NewBHS(t) mockLogger := logger.NewMockLogger(t) feeder := NewFeeder( @@ -339,8 +339,8 @@ func TestStartHeartbeats(t *testing.T) { mockTimer := bhsmocks.NewTimer(t) mockLogger.On("Infow", "Not starting heartbeat blockhash using storeEarliest").Once() require.Len(t, mockLogger.ExpectedCalls, 1) - require.Len(t, mockBHS.ExpectedCalls, 0) - require.Len(t, mockTimer.ExpectedCalls, 0) + require.Empty(t, mockBHS.ExpectedCalls) + require.Empty(t, mockTimer.ExpectedCalls) defer mockTimer.AssertExpectations(t) defer mockBHS.AssertExpectations(t) defer mockLogger.AssertExpectations(t) diff --git a/core/services/blockheaderfeeder/validate_test.go b/core/services/blockheaderfeeder/validate_test.go index 66413a615bd..9697eb96ece 100644 --- a/core/services/blockheaderfeeder/validate_test.go +++ b/core/services/blockheaderfeeder/validate_test.go @@ -132,7 +132,7 @@ getBlockhashesBatchSize = 20 storeBlockhashesBatchSize = 10 `, assertion: func(t *testing.T, os job.Job, err error) { - require.Equal(t, err.Error(), `at least one of "coordinatorV1Address", "coordinatorV2Address" and "coordinatorV2PlusAddress" must be set`) + require.Equal(t, `at least one of "coordinatorV1Address", "coordinatorV2Address" and "coordinatorV2PlusAddress" must be set`, err.Error()) }, }, { @@ -152,7 +152,7 @@ getBlockhashesBatchSize = 20 storeBlockhashesBatchSize = 10 `, assertion: func(t *testing.T, os job.Job, err error) { - require.Equal(t, err.Error(), `"blockhashStoreAddress" must be set`) + require.Equal(t, `"blockhashStoreAddress" must be set`, err.Error()) }, }, { @@ -172,7 +172,7 @@ getBlockhashesBatchSize = 20 storeBlockhashesBatchSize = 10 `, assertion: func(t *testing.T, os job.Job, err error) { - require.Equal(t, err.Error(), `"batchBlockhashStoreAddress" must be set`) + require.Equal(t, `"batchBlockhashStoreAddress" must be set`, err.Error()) }, }, { @@ -192,7 +192,7 @@ getBlockhashesBatchSize = 20 storeBlockhashesBatchSize = 10 `, assertion: func(t *testing.T, os job.Job, err error) { - require.Equal(t, err.Error(), `"evmChainID" must be set`) + require.Equal(t, `"evmChainID" must be set`, err.Error()) }, }, { @@ -213,7 +213,7 @@ getBlockhashesBatchSize = 20 storeBlockhashesBatchSize = 10 `, assertion: func(t *testing.T, os job.Job, err error) { - require.Equal(t, err.Error(), `"waitBlocks" must be greater than or equal to 256`) + require.Equal(t, `"waitBlocks" must be greater than or equal to 256`, err.Error()) }, }, { @@ -234,7 +234,7 @@ getBlockhashesBatchSize = 20 storeBlockhashesBatchSize = 10 `, assertion: func(t *testing.T, os job.Job, err error) { - require.Equal(t, err.Error(), `"lookbackBlocks" must be greater than 256`) + require.Equal(t, `"lookbackBlocks" must be greater than 256`, err.Error()) }, }, { @@ -255,7 +255,7 @@ getBlockhashesBatchSize = 20 storeBlockhashesBatchSize = 10 `, assertion: func(t *testing.T, os job.Job, err error) { - require.Equal(t, err.Error(), `"lookbackBlocks" must be greater than "waitBlocks"`) + require.Equal(t, `"lookbackBlocks" must be greater than "waitBlocks"`, err.Error()) }, }, } diff --git a/core/services/ccip/orm.go b/core/services/ccip/orm.go index 1942c68fef9..a8de3f3ced4 100644 --- a/core/services/ccip/orm.go +++ b/core/services/ccip/orm.go @@ -2,6 +2,7 @@ package ccip import ( "context" + "errors" "fmt" "time" @@ -38,7 +39,7 @@ var _ ORM = (*orm)(nil) func NewORM(ds sqlutil.DataSource, lggr logger.Logger) (ORM, error) { if ds == nil { - return nil, fmt.Errorf("datasource to CCIP NewORM cannot be nil") + return nil, errors.New("datasource to CCIP NewORM cannot be nil") } return &orm{ diff --git a/core/services/ccip/orm_test.go b/core/services/ccip/orm_test.go index a98b7736d8d..b42b12a32d0 100644 --- a/core/services/ccip/orm_test.go +++ b/core/services/ccip/orm_test.go @@ -122,7 +122,7 @@ func TestORM_EmptyGasPrices(t *testing.T) { orm, _ := setupORM(t) prices, err := orm.GetGasPricesByDestChain(ctx, 1) - assert.Equal(t, 0, len(prices)) + assert.Empty(t, prices) assert.NoError(t, err) } @@ -133,7 +133,7 @@ func TestORM_EmptyTokenPrices(t *testing.T) { orm, _ := setupORM(t) prices, err := orm.GetTokenPricesByDestChain(ctx, 1) - assert.Equal(t, 0, len(prices)) + assert.Empty(t, prices) assert.NoError(t, err) } @@ -177,7 +177,7 @@ func TestORM_InsertAndGetGasPrices(t *testing.T) { prices, err := orm.GetGasPricesByDestChain(ctx, destSelector) assert.NoError(t, err) // should return 1 price per source chain selector - assert.Equal(t, numSourceChainSelectors, len(prices)) + assert.Len(t, prices, numSourceChainSelectors) // verify getGasPrices returns prices of latest timestamp for _, price := range prices { @@ -198,7 +198,7 @@ func TestORM_InsertAndGetGasPrices(t *testing.T) { prices, err = orm.GetGasPricesByDestChain(ctx, destSelector) assert.NoError(t, err) - assert.Equal(t, numSourceChainSelectors, len(prices)) + assert.Len(t, prices, numSourceChainSelectors) for _, price := range prices { selector := price.SourceChainSelector @@ -280,7 +280,7 @@ func TestORM_InsertAndGetTokenPrices(t *testing.T) { prices, err := orm.GetTokenPricesByDestChain(ctx, destSelector) assert.NoError(t, err) // should return 1 price per source chain selector - assert.Equal(t, numAddresses, len(prices)) + assert.Len(t, prices, numAddresses) // verify getTokenPrices returns prices of latest timestamp for _, price := range prices { @@ -301,7 +301,7 @@ func TestORM_InsertAndGetTokenPrices(t *testing.T) { prices, err = orm.GetTokenPricesByDestChain(ctx, destSelector) assert.NoError(t, err) - assert.Equal(t, numAddresses, len(prices)) + assert.Len(t, prices, numAddresses) for _, price := range prices { addr := price.TokenAddr diff --git a/core/services/chainlink/application.go b/core/services/chainlink/application.go index 4004b86c341..2940d20876a 100644 --- a/core/services/chainlink/application.go +++ b/core/services/chainlink/application.go @@ -396,7 +396,7 @@ func NewApplication(opts ApplicationOpts) (Application, error) { legacyEVMChains := relayerChainInterops.LegacyEVMChains() if legacyEVMChains == nil { - return nil, fmt.Errorf("no evm chains found") + return nil, errors.New("no evm chains found") } srvcs = append(srvcs, mailMon) @@ -548,7 +548,7 @@ func NewApplication(opts ApplicationOpts) (Application, error) { peerWrapper = ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), opts.DS, globalLogger) srvcs = append(srvcs, peerWrapper) } else { - return nil, fmt.Errorf("P2P stack required for OCR or OCR2") + return nil, errors.New("P2P stack required for OCR or OCR2") } // If peer wrapper is initialized, Oracle Factory dependency will be available to standard capabilities @@ -1055,7 +1055,7 @@ func (app *ChainlinkApplication) FindLCA(ctx context.Context, chainID *big.Int) return nil, err } if !app.Config.Feature().LogPoller() { - return nil, fmt.Errorf("FindLCA is only available if LogPoller is enabled") + return nil, errors.New("FindLCA is only available if LogPoller is enabled") } lca, err := chain.LogPoller().FindLCA(ctx) @@ -1073,7 +1073,7 @@ func (app *ChainlinkApplication) DeleteLogPollerDataAfter(ctx context.Context, c return err } if !app.Config.Feature().LogPoller() { - return fmt.Errorf("DeleteLogPollerDataAfter is only available if LogPoller is enabled") + return errors.New("DeleteLogPollerDataAfter is only available if LogPoller is enabled") } err = chain.LogPoller().DeleteLogsAndBlocksAfter(ctx, start) diff --git a/core/services/chainlink/cfgtest/defaults.go b/core/services/chainlink/cfgtest/defaults.go index 01573f9baea..92557773b6d 100644 --- a/core/services/chainlink/cfgtest/defaults.go +++ b/core/services/chainlink/cfgtest/defaults.go @@ -42,7 +42,7 @@ func writeDefaults(r io.Reader, w *io.PipeWriter) { } } if err := s.Err(); err != nil { - w.CloseWithError(fmt.Errorf("failed to scan core defaults: %v", err)) + w.CloseWithError(fmt.Errorf("failed to scan core defaults: %w", err)) } } diff --git a/core/services/chainlink/config.go b/core/services/chainlink/config.go index 9f083ef89af..9f7c1b50835 100644 --- a/core/services/chainlink/config.go +++ b/core/services/chainlink/config.go @@ -415,7 +415,7 @@ var ErrInvalidSecrets = errors.New("invalid secrets") // Validate validates every consitutent secret and return an accumulated error func (s *Secrets) Validate() error { if err := commonconfig.Validate(s); err != nil { - return fmt.Errorf("%w: %s", ErrInvalidSecrets, err) + return fmt.Errorf("%w: %w", ErrInvalidSecrets, err) } return nil } @@ -437,7 +437,7 @@ func (s *Secrets) ValidateDB() error { s.setDefaults() v := &dbValidationType{s.Database} if err := commonconfig.Validate(v); err != nil { - return fmt.Errorf("%w: %s", ErrInvalidSecrets, err) + return fmt.Errorf("%w: %w", ErrInvalidSecrets, err) } return nil } diff --git a/core/services/chainlink/config_audit_logger_test.go b/core/services/chainlink/config_audit_logger_test.go index 38132120d4b..482968a14bc 100644 --- a/core/services/chainlink/config_audit_logger_test.go +++ b/core/services/chainlink/config_audit_logger_test.go @@ -15,7 +15,7 @@ func TestAuditLoggerConfig(t *testing.T) { auditConfig := cfg.AuditLogger() - require.Equal(t, true, auditConfig.Enabled()) + require.True(t, auditConfig.Enabled()) require.Equal(t, "event", auditConfig.JsonWrapperKey()) fUrl, err := auditConfig.ForwardToUrl() diff --git a/core/services/chainlink/config_database_test.go b/core/services/chainlink/config_database_test.go index f8f864f97ab..1a992e225e3 100644 --- a/core/services/chainlink/config_database_test.go +++ b/core/services/chainlink/config_database_test.go @@ -38,7 +38,7 @@ URL = "postgresql://doesnotexist:justtopassvalidationtests@localhost:5432/chainl assert.True(t, db.MigrateDatabase()) assert.Equal(t, pgcommon.Postgres, db.Dialect()) url := db.URL() - assert.NotEqual(t, url.String(), "") + assert.NotEqual(t, "", url.String()) lock := db.Lock() assert.Equal(t, "none", lock.LockingMode()) diff --git a/core/services/chainlink/config_flux_monitor_test.go b/core/services/chainlink/config_flux_monitor_test.go index f502a378f94..673c4465db7 100644 --- a/core/services/chainlink/config_flux_monitor_test.go +++ b/core/services/chainlink/config_flux_monitor_test.go @@ -17,5 +17,5 @@ func TestFluxMonitorConfig(t *testing.T) { fm := cfg.FluxMonitor() assert.Equal(t, uint32(100), fm.DefaultTransactionQueueDepth()) - assert.Equal(t, true, fm.SimulateTransactions()) + assert.True(t, fm.SimulateTransactions()) } diff --git a/core/services/chainlink/config_general.go b/core/services/chainlink/config_general.go index dd0dc87b59a..ddf552b8b9c 100644 --- a/core/services/chainlink/config_general.go +++ b/core/services/chainlink/config_general.go @@ -254,7 +254,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 = multierr.Append(err, fmt.Errorf("environment variable %s must not be set: %w", k, v2.ErrUnsupported)) } } return diff --git a/core/services/chainlink/config_general_test.go b/core/services/chainlink/config_general_test.go index 29393ee0fdd..99363db7904 100644 --- a/core/services/chainlink/config_general_test.go +++ b/core/services/chainlink/config_general_test.go @@ -28,7 +28,7 @@ func TestTOMLGeneralConfig_Defaults(t *testing.T) { assert.False(t, config.CosmosEnabled()) assert.False(t, config.SolanaEnabled()) assert.False(t, config.StarkNetEnabled()) - assert.Equal(t, false, config.JobPipeline().ExternalInitiatorsEnabled()) + assert.False(t, config.JobPipeline().ExternalInitiatorsEnabled()) assert.Equal(t, 15*time.Minute, config.WebServer().SessionTimeout().Duration()) } @@ -121,10 +121,10 @@ func TestConfig_LogSQL(t *testing.T) { require.NoError(t, err) config.SetLogSQL(true) - assert.Equal(t, config.Database().LogSQL(), true) + assert.True(t, config.Database().LogSQL()) config.SetLogSQL(false) - assert.Equal(t, config.Database().LogSQL(), false) + assert.False(t, config.Database().LogSQL()) } //go:embed testdata/mergingsecretsdata/secrets-database.toml diff --git a/core/services/chainlink/config_log_test.go b/core/services/chainlink/config_log_test.go index 3956375c7df..bc5828a2056 100644 --- a/core/services/chainlink/config_log_test.go +++ b/core/services/chainlink/config_log_test.go @@ -24,8 +24,8 @@ func TestLogConfig(t *testing.T) { assert.Equal(t, uint64(100*utils.GB), uint64(file.MaxSize())) assert.Equal(t, int64(17), file.MaxAgeDays()) assert.Equal(t, int64(9), file.MaxBackups()) - assert.Equal(t, true, log.UnixTimestamps()) - assert.Equal(t, true, log.JSONConsole()) + assert.True(t, log.UnixTimestamps()) + assert.True(t, log.JSONConsole()) assert.Equal(t, zapcore.Level(3), log.DefaultLevel()) assert.Equal(t, zapcore.Level(3), log.Level()) } diff --git a/core/services/chainlink/config_ocr2_test.go b/core/services/chainlink/config_ocr2_test.go index 5bf84934d13..54ef5dd8194 100644 --- a/core/services/chainlink/config_ocr2_test.go +++ b/core/services/chainlink/config_ocr2_test.go @@ -27,18 +27,18 @@ func TestOCR2Config(t *testing.T) { expectedContractSubscribeInterval, err := time.ParseDuration("1m0s") require.NoError(t, err) - require.Equal(t, true, ocr2Cfg.Enabled()) + require.True(t, ocr2Cfg.Enabled()) require.Equal(t, uint16(11), ocr2Cfg.ContractConfirmations()) require.Equal(t, expectedContractTransmitterTransmitTimeout, ocr2Cfg.ContractTransmitterTransmitTimeout()) require.Equal(t, expectedBlockchainTimeout, ocr2Cfg.BlockchainTimeout()) require.Equal(t, expectedDatabaseTimeout, ocr2Cfg.DatabaseTimeout()) require.Equal(t, expectedContractPollInterval, ocr2Cfg.ContractPollInterval()) require.Equal(t, expectedContractSubscribeInterval, ocr2Cfg.ContractSubscribeInterval()) - require.Equal(t, false, ocr2Cfg.SimulateTransactions()) - require.Equal(t, false, ocr2Cfg.TraceLogging()) + require.False(t, ocr2Cfg.SimulateTransactions()) + require.False(t, ocr2Cfg.TraceLogging()) require.Equal(t, uint32(1), ocr2Cfg.DefaultTransactionQueueDepth()) - require.Equal(t, false, ocr2Cfg.CaptureEATelemetry()) - require.Equal(t, true, ocr2Cfg.CaptureAutomationCustomTelemetry()) + require.False(t, ocr2Cfg.CaptureEATelemetry()) + require.True(t, ocr2Cfg.CaptureAutomationCustomTelemetry()) keyBundleID, err := ocr2Cfg.KeyBundleID() require.NoError(t, err) diff --git a/core/services/chainlink/config_ocr_test.go b/core/services/chainlink/config_ocr_test.go index 169fd0c7e0a..0a3038f1d34 100644 --- a/core/services/chainlink/config_ocr_test.go +++ b/core/services/chainlink/config_ocr_test.go @@ -25,15 +25,15 @@ func TestOCRConfig(t *testing.T) { expectedContractSubscribeInterval, err := time.ParseDuration("1m0s") require.NoError(t, err) - require.Equal(t, true, ocrCfg.Enabled()) + require.True(t, ocrCfg.Enabled()) require.Equal(t, expectedObservationTimeout, ocrCfg.ObservationTimeout()) require.Equal(t, expectedBlockchainTimeout, ocrCfg.BlockchainTimeout()) require.Equal(t, expectedContractPollInterval, ocrCfg.ContractPollInterval()) require.Equal(t, expectedContractSubscribeInterval, ocrCfg.ContractSubscribeInterval()) - require.Equal(t, true, ocrCfg.SimulateTransactions()) - require.Equal(t, false, ocrCfg.TraceLogging()) + require.True(t, ocrCfg.SimulateTransactions()) + require.False(t, ocrCfg.TraceLogging()) require.Equal(t, uint32(12), ocrCfg.DefaultTransactionQueueDepth()) - require.Equal(t, false, ocrCfg.CaptureEATelemetry()) + require.False(t, ocrCfg.CaptureEATelemetry()) keyBundleID, err := ocrCfg.KeyBundleID() require.NoError(t, err) diff --git a/core/services/chainlink/config_telemetry_ingress_test.go b/core/services/chainlink/config_telemetry_ingress_test.go index 64e85b5493e..75ab4bfaa05 100644 --- a/core/services/chainlink/config_telemetry_ingress_test.go +++ b/core/services/chainlink/config_telemetry_ingress_test.go @@ -26,7 +26,7 @@ func TestTelemetryIngressConfig(t *testing.T) { tec := cfg.TelemetryIngress().Endpoints() - assert.Equal(t, 1, len(tec)) + assert.Len(t, tec, 1) assert.Equal(t, "EVM", tec[0].Network()) assert.Equal(t, "1", tec[0].ChainID()) assert.Equal(t, "prom.test", tec[0].URL().String()) diff --git a/core/services/chainlink/relayer_chain_interoperators_test.go b/core/services/chainlink/relayer_chain_interoperators_test.go index a4bd8c168ba..f584b274c1c 100644 --- a/core/services/chainlink/relayer_chain_interoperators_test.go +++ b/core/services/chainlink/relayer_chain_interoperators_test.go @@ -348,7 +348,7 @@ func TestCoreRelayerChainInteroperators(t *testing.T) { allChainsStats, cnt, err := cr.ChainStatuses(testctx, 0, 0) assert.NoError(t, err) assert.Len(t, allChainsStats, expectedChainCnt) - assert.Equal(t, cnt, len(allChainsStats)) + assert.Len(t, allChainsStats, cnt) assert.Len(t, cr.Slice(), expectedChainCnt) // should be one relayer per chain and one service per relayer @@ -359,7 +359,7 @@ func TestCoreRelayerChainInteroperators(t *testing.T) { allNodeStats, cnt, err := cr.NodeStatuses(testctx, 0, 0) assert.NoError(t, err) assert.Len(t, allNodeStats, expectedNodeCnt) - assert.Equal(t, cnt, len(allNodeStats)) + assert.Len(t, allNodeStats, cnt) } gotRelayerNetworks := make(map[string]struct{}) @@ -410,9 +410,9 @@ func TestCoreRelayerChainInteroperators(t *testing.T) { nodesStats, cnt, err := interops.NodeStatuses(testctx, 0, 0) assert.NoError(t, err) assert.Len(t, nodesStats, expectedNodeCnt) - assert.Equal(t, cnt, len(nodesStats)) + assert.Len(t, nodesStats, cnt) } - assert.EqualValues(t, gotRelayerNetworks, tt.expectedRelayerNetworks) + assert.EqualValues(t, tt.expectedRelayerNetworks, gotRelayerNetworks) allRelayerIds := [][]types.RelayID{ tt.expectedEVMRelayerIds, diff --git a/core/services/chainlink/relayer_factory.go b/core/services/chainlink/relayer_factory.go index a1571663d5a..b0570c6404e 100644 --- a/core/services/chainlink/relayer_factory.go +++ b/core/services/chainlink/relayer_factory.go @@ -261,13 +261,13 @@ type CosmosFactoryConfig struct { func (c CosmosFactoryConfig) Validate() error { var err error if c.Keystore == nil { - err = errors.Join(err, fmt.Errorf("nil Keystore")) + err = errors.Join(err, errors.New("nil Keystore")) } if len(c.TOMLConfigs) == 0 { - err = errors.Join(err, fmt.Errorf("no CosmosConfigs provided")) + err = errors.Join(err, errors.New("no CosmosConfigs provided")) } if c.DS == nil { - err = errors.Join(err, fmt.Errorf("nil DataStore")) + err = errors.Join(err, errors.New("nil DataStore")) } if err != nil { diff --git a/core/services/cron/validate_test.go b/core/services/cron/validate_test.go index d701dd3d6a7..a5412971436 100644 --- a/core/services/cron/validate_test.go +++ b/core/services/cron/validate_test.go @@ -1,7 +1,6 @@ package cron_test import ( - "strings" "testing" "github.com/manyminds/api2go/jsonapi" @@ -56,7 +55,7 @@ ds -> ds_parse -> ds_multiply; `, assertion: func(t *testing.T, s job.Job, err error) { require.Error(t, err) - assert.True(t, strings.Contains(err.Error(), "cron schedule must specify a time zone using CRON_TZ")) + assert.Contains(t, err.Error(), "cron schedule must specify a time zone using CRON_TZ") }, }, { @@ -74,7 +73,7 @@ ds -> ds_parse -> ds_multiply; `, assertion: func(t *testing.T, s job.Job, err error) { require.Error(t, err) - assert.True(t, strings.Contains(err.Error(), "invalid cron schedule")) + assert.Contains(t, err.Error(), "invalid cron schedule") }, }, } diff --git a/core/services/directrequest/delegate.go b/core/services/directrequest/delegate.go index 844bd0a12c9..dde62ae0bf8 100644 --- a/core/services/directrequest/delegate.go +++ b/core/services/directrequest/delegate.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "reflect" + "strconv" "sync" "github.com/ethereum/go-ethereum/common" @@ -167,8 +168,8 @@ func (l *listener) Start(context.Context) error { l.shutdownWaitGroup.Done() }() - l.mailMon.Monitor(l.mbOracleRequests, "DirectRequest", "Requests", fmt.Sprint(l.job.PipelineSpec.JobID)) - l.mailMon.Monitor(l.mbOracleCancelRequests, "DirectRequest", "Cancel", fmt.Sprint(l.job.PipelineSpec.JobID)) + l.mailMon.Monitor(l.mbOracleRequests, "DirectRequest", "Requests", strconv.Itoa(int(l.job.PipelineSpec.JobID))) + l.mailMon.Monitor(l.mbOracleCancelRequests, "DirectRequest", "Cancel", strconv.Itoa(int(l.job.PipelineSpec.JobID))) return nil }) diff --git a/core/services/feeds/models_test.go b/core/services/feeds/models_test.go index d0d4382b055..ecf07797297 100644 --- a/core/services/feeds/models_test.go +++ b/core/services/feeds/models_test.go @@ -60,27 +60,27 @@ func Test_ToPluginType(t *testing.T) { pt, err := ToPluginType("commit") require.NoError(t, err) - assert.Equal(t, pt, PluginTypeCommit) + assert.Equal(t, PluginTypeCommit, pt) pt, err = ToPluginType("execute") require.NoError(t, err) - assert.Equal(t, pt, PluginTypeExecute) + assert.Equal(t, PluginTypeExecute, pt) pt, err = ToPluginType("median") require.NoError(t, err) - assert.Equal(t, pt, PluginTypeMedian) + assert.Equal(t, PluginTypeMedian, pt) pt, err = ToPluginType("mercury") require.NoError(t, err) - assert.Equal(t, pt, PluginTypeMercury) + assert.Equal(t, PluginTypeMercury, pt) pt, err = ToPluginType("rebalancer") require.NoError(t, err) - assert.Equal(t, pt, PluginTypeRebalancer) + assert.Equal(t, PluginTypeRebalancer, pt) pt, err = ToPluginType("xxx") require.Error(t, err) - assert.Equal(t, pt, PluginTypeUnknown) + assert.Equal(t, PluginTypeUnknown, pt) assert.EqualError(t, err, "unknown plugin type") } @@ -411,12 +411,12 @@ func Test_toMetrics(t *testing.T) { metrics := jpCounts.toMetrics() - assert.Equal(t, metrics, map[JobProposalStatus]float64{ + assert.Equal(t, map[JobProposalStatus]float64{ JobProposalStatusCancelled: 0, JobProposalStatusPending: 1, JobProposalStatusApproved: 2, JobProposalStatusRejected: 3, JobProposalStatusDeleted: 4, JobProposalStatusRevoked: 5, - }) + }, metrics) } diff --git a/core/services/feeds/orm_test.go b/core/services/feeds/orm_test.go index 30e738ff89e..fac50f619d0 100644 --- a/core/services/feeds/orm_test.go +++ b/core/services/feeds/orm_test.go @@ -94,14 +94,14 @@ func Test_ORM_CreateManager(t *testing.T) { exists, err := orm.ManagerExists(ctx, publicKey) require.NoError(t, err) - require.Equal(t, false, exists) + require.False(t, exists) id, err := orm.CreateManager(ctx, mgr) require.NoError(t, err) exists, err = orm.ManagerExists(ctx, publicKey) require.NoError(t, err) - require.Equal(t, true, exists) + require.True(t, exists) assert.NotZero(t, id) } @@ -181,7 +181,7 @@ func Test_ORM_ListManagersByIDs(t *testing.T) { mgrs, err := orm.ListManagersByIDs(ctx, []int64{id}) require.NoError(t, err) - require.Equal(t, 1, len(mgrs)) + require.Len(t, mgrs, 1) actual := mgrs[0] assert.Equal(t, id, actual.ID) @@ -674,7 +674,7 @@ func Test_ORM_CountJobProposalsByStatus(t *testing.T) { // Assert that the upserted job proposal is now pending update. jp, err := orm.GetJobProposal(ctx, jpID) require.NoError(t, err) - assert.Equal(t, true, jp.PendingUpdate) + assert.True(t, jp.PendingUpdate) counts, err := orm.CountJobProposalsByStatus(ctx) require.NoError(t, err) diff --git a/core/services/feeds/service_test.go b/core/services/feeds/service_test.go index d449d585401..26ffea5406f 100644 --- a/core/services/feeds/service_test.go +++ b/core/services/feeds/service_test.go @@ -1123,7 +1123,7 @@ func Test_Service_ProposeJob(t *testing.T) { }), ). Run(func(args mock.Arguments) { (args.Get(2).(*job.Job)).ID = 1 }). - Return(fmt.Errorf("error creating job")) + Return(errors.New("error creating job")) }, args: argsWF, wantID: 0, diff --git a/core/services/fluxmonitorv2/flux_monitor.go b/core/services/fluxmonitorv2/flux_monitor.go index b8154ab6797..1293f50e03d 100644 --- a/core/services/fluxmonitorv2/flux_monitor.go +++ b/core/services/fluxmonitorv2/flux_monitor.go @@ -7,6 +7,7 @@ import ( "math/big" mrand "math/rand" "reflect" + "strconv" "time" "github.com/ethereum/go-ethereum/common" @@ -200,10 +201,7 @@ func NewFromJobSpec( flags, err := NewFlags(cfg.FlagsContractAddress(), ethClient) logger.Sugared(lggr).ErrorIf(err, - fmt.Sprintf( - "Error creating Flags contract instance, check address: %s", - cfg.FlagsContractAddress(), - ), + "Error creating Flags contract instance, check address: "+cfg.FlagsContractAddress(), ) paymentChecker := &PaymentChecker{ @@ -591,7 +589,7 @@ func (fm *FluxMonitor) respondToNewRoundLog(ctx context.Context, log flux_aggreg }() newRoundLogger.Debug("NewRound log") - promfm.SetBigInt(promfm.SeenRound.WithLabelValues(fmt.Sprintf("%d", fm.spec.JobID)), log.RoundId) + promfm.SetBigInt(promfm.SeenRound.WithLabelValues(strconv.Itoa(int(fm.spec.JobID))), log.RoundId) // // NewRound answer submission logic: @@ -957,7 +955,7 @@ func (fm *FluxMonitor) pollIfEligible(ctx context.Context, pollReq PollRequestTy return } - jobID := fmt.Sprintf("%d", fm.spec.JobID) + jobID := strconv.Itoa(int(fm.spec.JobID)) latestAnswer := decimal.NewFromBigInt(roundState.LatestSubmission, 0) promfm.SetDecimal(promfm.SeenValue.WithLabelValues(jobID), answer) @@ -1022,10 +1020,10 @@ func (fm *FluxMonitor) isValidSubmission(ctx context.Context, l logger.Logger, a jobId := fm.spec.JobID jobName := fm.spec.JobName elapsed := time.Since(started) - pipeline.PromPipelineTaskExecutionTime.WithLabelValues(fmt.Sprintf("%d", jobId), jobName, "", job.FluxMonitor.String()).Set(float64(elapsed)) - pipeline.PromPipelineRunErrors.WithLabelValues(fmt.Sprintf("%d", jobId), jobName).Inc() - pipeline.PromPipelineRunTotalTimeToCompletion.WithLabelValues(fmt.Sprintf("%d", jobId), jobName).Set(float64(elapsed)) - pipeline.PromPipelineTasksTotalFinished.WithLabelValues(fmt.Sprintf("%d", jobId), jobName, "", job.FluxMonitor.String(), "", "error").Inc() + pipeline.PromPipelineTaskExecutionTime.WithLabelValues(strconv.Itoa(int(jobId)), jobName, "", job.FluxMonitor.String()).Set(float64(elapsed)) + pipeline.PromPipelineRunErrors.WithLabelValues(strconv.Itoa(int(jobId)), jobName).Inc() + pipeline.PromPipelineRunTotalTimeToCompletion.WithLabelValues(strconv.Itoa(int(jobId)), jobName).Set(float64(elapsed)) + pipeline.PromPipelineTasksTotalFinished.WithLabelValues(strconv.Itoa(int(jobId)), jobName, "", job.FluxMonitor.String(), "", "error").Inc() return false } diff --git a/core/services/fluxmonitorv2/flux_monitor_test.go b/core/services/fluxmonitorv2/flux_monitor_test.go index 150db269e45..1ffa7e6c161 100644 --- a/core/services/fluxmonitorv2/flux_monitor_test.go +++ b/core/services/fluxmonitorv2/flux_monitor_test.go @@ -784,7 +784,7 @@ func TestFluxMonitor_TriggerIdleTimeThreshold(t *testing.T) { } require.NoError(t, fm.Start(testutils.Context(t))) - require.Len(t, idleDurationOccured, 0, "no Job Runs created") + require.Empty(t, idleDurationOccured, "no Job Runs created") if tc.expectedToSubmit { g.Eventually(func() int { return len(idleDurationOccured) }, testutils.WaitTimeout(t)).Should(gomega.Equal(1)) @@ -817,7 +817,7 @@ func TestFluxMonitor_TriggerIdleTimeThreshold(t *testing.T) { fm.Close() if !tc.expectedToSubmit { - require.Len(t, idleDurationOccured, 0) + require.Empty(t, idleDurationOccured) } }) } @@ -1068,7 +1068,7 @@ func TestFluxMonitor_IdleTimerResetsOnNewRound(t *testing.T) { }, nil).Once().Run(func(args mock.Arguments) { initialPollOccurred <- struct{}{} }) - require.Len(t, idleDurationOccured, 0, "no Job Runs created") + require.Empty(t, idleDurationOccured, "no Job Runs created") g.Eventually(func() int { return len(initialPollOccurred) }, testutils.WaitTimeout(t)).Should(gomega.Equal(1)) // idleDuration 1 triggers using the same round id as the initial poll. This resets the idle timer diff --git a/core/services/fluxmonitorv2/integrations_test.go b/core/services/fluxmonitorv2/integrations_test.go index d30ff4479a8..9031d9ac6f1 100644 --- a/core/services/fluxmonitorv2/integrations_test.go +++ b/core/services/fluxmonitorv2/integrations_test.go @@ -287,7 +287,7 @@ func checkSubmission(t *testing.T, p answerParams, currentBalance int64, receipt require.Len(t, nrlogs, 1, "FluxAggregator did not emit correct NewRound "+ "log") } else { - assert.Len(t, cltest.GetLogs(t, nil, inrlogs), 0, "FluxAggregator emitted "+ + assert.Empty(t, cltest.GetLogs(t, nil, inrlogs), "FluxAggregator emitted "+ "unexpected NewRound log") } @@ -607,8 +607,8 @@ func TestFluxMonitor_Deviation(t *testing.T) { expMetaMu.Lock() defer expMetaMu.Unlock() assert.Len(t, expectedMeta, 2, "expected metadata %v", expectedMeta) - assert.Greater(t, expectedMeta["100"].count, 0, "Stored answer metadata does not contain 100 but contains: %v", expectedMeta) - assert.Greater(t, expectedMeta["103"].count, 0, "Stored answer metadata does not contain 103 but contains: %v", expectedMeta) + assert.Positive(t, expectedMeta["100"].count, "Stored answer metadata does not contain 100 but contains: %v", expectedMeta) + assert.Positive(t, expectedMeta["103"].count, "Stored answer metadata does not contain 103 but contains: %v", expectedMeta) assert.Greater(t, expectedMeta["103"].updatedAt, expectedMeta["100"].updatedAt) }) } diff --git a/core/services/fluxmonitorv2/validate_test.go b/core/services/fluxmonitorv2/validate_test.go index 81d9215bea8..1eb3c7c1b1e 100644 --- a/core/services/fluxmonitorv2/validate_test.go +++ b/core/services/fluxmonitorv2/validate_test.go @@ -1,7 +1,6 @@ package fluxmonitorv2 import ( - "regexp" "testing" "time" @@ -74,13 +73,13 @@ answer1 [type=median index=0]; assert.Equal(t, "0x3cCad4715152693fE3BC4460591e3D3Fbd071b42", j.FluxMonitorSpec.ContractAddress.String()) assert.Equal(t, tomlutils.Float32(0.5), spec.Threshold) assert.Equal(t, tomlutils.Float32(0), spec.AbsoluteThreshold) - assert.Equal(t, true, spec.IdleTimerDisabled) + assert.True(t, spec.IdleTimerDisabled) assert.Equal(t, 1*time.Minute, spec.PollTimerPeriod) - assert.Equal(t, false, spec.PollTimerDisabled) - assert.Equal(t, true, spec.DrumbeatEnabled) + assert.False(t, spec.PollTimerDisabled) + assert.True(t, spec.DrumbeatEnabled) assert.Equal(t, "@every 1m", spec.DrumbeatSchedule) assert.Equal(t, 10*time.Second, spec.DrumbeatRandomDelay) - assert.Equal(t, false, spec.PollTimerDisabled) + assert.False(t, spec.PollTimerDisabled) assert.Equal(t, assets.NewLinkFromJuels(1000000000000000000), spec.MinPayment) assert.NotZero(t, j.Pipeline) }, @@ -110,7 +109,7 @@ ds1 -> ds1_parse; assertion: func(t *testing.T, s job.Job, err error) { require.Nil(t, s.FluxMonitorSpec) require.Error(t, err) - assert.Regexp(t, regexp.MustCompile("^.*is not a valid EIP55 formatted address$"), err.Error()) + assert.Regexp(t, "^.*is not a valid EIP55 formatted address$", err.Error()) }, }, { diff --git a/core/services/functions/connector_handler.go b/core/services/functions/connector_handler.go index 75a3dca24f1..eff7bc69bab 100644 --- a/core/services/functions/connector_handler.go +++ b/core/services/functions/connector_handler.go @@ -14,6 +14,7 @@ import ( ethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" + "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -76,7 +77,7 @@ func InternalId(sender []byte, requestId []byte) RequestID { func NewFunctionsConnectorHandler(pluginConfig *config.PluginConfig, signerKey *ecdsa.PrivateKey, storage s4.Storage, allowlist fallow.OnchainAllowlist, rateLimiter *hc.RateLimiter, subscriptions fsub.OnchainSubscriptions, listener FunctionsListener, offchainTransmitter OffchainTransmitter, lggr logger.Logger) (*functionsConnectorHandler, error) { if signerKey == nil || storage == nil || allowlist == nil || rateLimiter == nil || subscriptions == nil || listener == nil || offchainTransmitter == nil { - return nil, fmt.Errorf("all dependencies must be non-nil") + return nil, errors.New("all dependencies must be non-nil") } allowedHeartbeatInitiators := make(map[string]struct{}) for _, initiator := range pluginConfig.AllowedHeartbeatInitiators { diff --git a/core/services/functions/connector_handler_test.go b/core/services/functions/connector_handler_test.go index a24139da58e..3417956ea75 100644 --- a/core/services/functions/connector_handler_test.go +++ b/core/services/functions/connector_handler_test.go @@ -129,7 +129,7 @@ func TestFunctionsConnectorHandler(t *testing.T) { connector.On("SendToGateway", ctx, "gw1", mock.Anything).Run(func(args mock.Arguments) { msg, ok := args[2].(*api.Message) require.True(t, ok) - require.Equal(t, `{"success":true,"rows":[{"slot_id":1,"version":1,"expiration":1},{"slot_id":2,"version":2,"expiration":2}]}`, string(msg.Body.Payload)) + require.JSONEq(t, `{"success":true,"rows":[{"slot_id":1,"version":1,"expiration":1},{"slot_id":2,"version":2,"expiration":2}]}`, string(msg.Body.Payload)) }).Return(nil).Once() handler.HandleGatewayMessage(ctx, "gw1", &msg) @@ -140,7 +140,7 @@ func TestFunctionsConnectorHandler(t *testing.T) { connector.On("SendToGateway", ctx, "gw1", mock.Anything).Run(func(args mock.Arguments) { msg, ok := args[2].(*api.Message) require.True(t, ok) - require.Equal(t, `{"success":false,"error_message":"Failed to list secrets: boom"}`, string(msg.Body.Payload)) + require.JSONEq(t, `{"success":false,"error_message":"Failed to list secrets: boom"}`, string(msg.Body.Payload)) }).Return(nil).Once() handler.HandleGatewayMessage(ctx, "gw1", &msg) @@ -196,7 +196,7 @@ func TestFunctionsConnectorHandler(t *testing.T) { connector.On("SendToGateway", ctx, "gw1", mock.Anything).Run(func(args mock.Arguments) { msg, ok := args[2].(*api.Message) require.True(t, ok) - require.Equal(t, `{"success":false,"error_message":"Failed to set secret: boom"}`, string(msg.Body.Payload)) + require.JSONEq(t, `{"success":false,"error_message":"Failed to set secret: boom"}`, string(msg.Body.Payload)) }).Return(nil).Once() handler.HandleGatewayMessage(ctx, "gw1", &msg) @@ -211,7 +211,7 @@ func TestFunctionsConnectorHandler(t *testing.T) { connector.On("SendToGateway", ctx, "gw1", mock.Anything).Run(func(args mock.Arguments) { msg, ok := args[2].(*api.Message) require.True(t, ok) - require.Equal(t, `{"success":false,"error_message":"Failed to set secret: wrong signature"}`, string(msg.Body.Payload)) + require.JSONEq(t, `{"success":false,"error_message":"Failed to set secret: wrong signature"}`, string(msg.Body.Payload)) }).Return(nil).Once() handler.HandleGatewayMessage(ctx, "gw1", &msg) @@ -225,7 +225,7 @@ func TestFunctionsConnectorHandler(t *testing.T) { connector.On("SendToGateway", ctx, "gw1", mock.Anything).Run(func(args mock.Arguments) { msg, ok := args[2].(*api.Message) require.True(t, ok) - require.Equal(t, `{"success":false,"error_message":"Bad request to set secret: invalid character 's' looking for beginning of object key string"}`, string(msg.Body.Payload)) + require.JSONEq(t, `{"success":false,"error_message":"Bad request to set secret: invalid character 's' looking for beginning of object key string"}`, string(msg.Body.Payload)) }).Return(nil).Once() handler.HandleGatewayMessage(ctx, "gw1", &msg) @@ -237,7 +237,7 @@ func TestFunctionsConnectorHandler(t *testing.T) { connector.On("SendToGateway", ctx, "gw1", mock.Anything).Run(func(args mock.Arguments) { msg, ok := args[2].(*api.Message) require.True(t, ok) - require.Equal(t, `{"success":false,"error_message":"user subscription has insufficient balance"}`, string(msg.Body.Payload)) + require.JSONEq(t, `{"success":false,"error_message":"user subscription has insufficient balance"}`, string(msg.Body.Payload)) }).Return(nil).Once() handler.HandleGatewayMessage(ctx, "gw1", &msg) diff --git a/core/services/functions/external_adapter_client_test.go b/core/services/functions/external_adapter_client_test.go index aab969a5050..de97eec5fdc 100644 --- a/core/services/functions/external_adapter_client_test.go +++ b/core/services/functions/external_adapter_client_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" @@ -33,7 +34,7 @@ func runFetcherTest(t *testing.T, adapterJSONResponse, expectedSecrets, expected if expectedError != nil { assert.Equal(t, expectedError.Error(), err.Error(), "Unexpected error") } else { - assert.Nil(t, err) + assert.NoError(t, err) } assert.Equal(t, expectedUserError, string(userError), "Unexpected userError") assert.Equal(t, expectedSecrets, string(encryptedSecrets), "Unexpected secrets") @@ -56,7 +57,7 @@ func runRequestTest(t *testing.T, adapterJSONResponse, expectedUserResult, expec if expectedError != nil { assert.Equal(t, expectedError.Error(), err.Error(), "Unexpected error") } else { - assert.Nil(t, err) + assert.NoError(t, err) } assert.Equal(t, expectedUserResult, string(userResult), "Unexpected user result") assert.Equal(t, expectedUserError, string(userError), "Unexpected user error") @@ -89,7 +90,7 @@ func TestFetchEncryptedSecrets_UnexpectedResponse(t *testing.T) { runFetcherTest(t, `{ "invalid": "invalid", "statusCode": 200 - }`, "", "", fmt.Errorf("error fetching encrypted secrets: external adapter response data was empty")) + }`, "", "", errors.New("error fetching encrypted secrets: external adapter response data was empty")) } func TestFetchEncryptedSecrets_FailedStatusCode(t *testing.T) { @@ -100,14 +101,14 @@ func TestFetchEncryptedSecrets_FailedStatusCode(t *testing.T) { "error": "0x616263646566" }, "statusCode": 400 - }`, "", "", fmt.Errorf("error fetching encrypted secrets: external adapter invalid StatusCode 400")) + }`, "", "", errors.New("error fetching encrypted secrets: external adapter invalid StatusCode 400")) } func TestFetchEncryptedSecrets_MissingData(t *testing.T) { runFetcherTest(t, `{ "result": "success", "statusCode": 200 - }`, "", "", fmt.Errorf("error fetching encrypted secrets: external adapter response data was empty")) + }`, "", "", errors.New("error fetching encrypted secrets: external adapter response data was empty")) } func TestFetchEncryptedSecrets_InvalidResponse(t *testing.T) { @@ -118,7 +119,7 @@ func TestFetchEncryptedSecrets_InvalidResponse(t *testing.T) { "error": "" }, "statusCode": 200 - }`, "", "", fmt.Errorf("error fetching encrypted secrets: error decoding result hex string: hex string must have 0x prefix")) + }`, "", "", errors.New("error fetching encrypted secrets: error decoding result hex string: hex string must have 0x prefix")) } func TestFetchEncryptedSecrets_InvalidUserError(t *testing.T) { @@ -129,7 +130,7 @@ func TestFetchEncryptedSecrets_InvalidUserError(t *testing.T) { "result": "" }, "statusCode": 200 - }`, "", "", fmt.Errorf("error fetching encrypted secrets: error decoding userError hex string: hex string must have 0x prefix")) + }`, "", "", errors.New("error fetching encrypted secrets: error decoding userError hex string: hex string must have 0x prefix")) } func TestFetchEncryptedSecrets_UnexpectedResult(t *testing.T) { @@ -140,7 +141,7 @@ func TestFetchEncryptedSecrets_UnexpectedResult(t *testing.T) { "error": "" }, "statusCode": 200 - }`, "", "", fmt.Errorf("error fetching encrypted secrets: unexpected result in response: 'unexpected'")) + }`, "", "", errors.New("error fetching encrypted secrets: unexpected result in response: 'unexpected'")) } func TestRunComputation_Success(t *testing.T) { @@ -151,7 +152,7 @@ func TestRunComputation_MissingData(t *testing.T) { runRequestTest(t, `{ "result": "success", "statusCode": 200 - }`, "", "", nil, fmt.Errorf("error running computation: external adapter response data was empty")) + }`, "", "", nil, errors.New("error running computation: external adapter response data was empty")) } func TestRunComputation_CorrectAdapterRequest(t *testing.T) { diff --git a/core/services/functions/listener.go b/core/services/functions/listener.go index 64c05a34c8d..56ddf97463c 100644 --- a/core/services/functions/listener.go +++ b/core/services/functions/listener.go @@ -300,10 +300,10 @@ func (l *functionsListener) HandleOffchainRequest(ctx context.Context, request * return fmt.Errorf("HandleOffchainRequest: invalid request ID length %d", len(request.RequestId)) } if len(request.SubscriptionOwner) != common.AddressLength || len(request.RequestInitiator) != common.AddressLength { - return fmt.Errorf("HandleOffchainRequest: SubscriptionOwner and RequestInitiator must be set to valid addresses") + return errors.New("HandleOffchainRequest: SubscriptionOwner and RequestInitiator must be set to valid addresses") } if request.Timestamp < uint64(time.Now().Unix()-int64(l.pluginConfig.RequestTimeoutSec)) { - return fmt.Errorf("HandleOffchainRequest: request timestamp is too old") + return errors.New("HandleOffchainRequest: request timestamp is too old") } var requestId RequestID diff --git a/core/services/functions/orm_test.go b/core/services/functions/orm_test.go index 859781dada7..6c423670346 100644 --- a/core/services/functions/orm_test.go +++ b/core/services/functions/orm_test.go @@ -1,7 +1,6 @@ package functions_test import ( - "errors" "testing" "time" @@ -100,7 +99,7 @@ func TestORM_CreateRequestsAndFindByID(t *testing.T) { newReq := &functions.Request{RequestID: id1, RequestTxHash: &txHash1, ReceivedAt: ts1} err := orm.CreateRequest(testutils.Context(t), newReq) require.Error(t, err) - require.True(t, errors.Is(err, functions.ErrDuplicateRequestID)) + require.ErrorIs(t, err, functions.ErrDuplicateRequestID) }) } @@ -249,7 +248,7 @@ func TestORM_FindOldestEntriesByState(t *testing.T) { ctx := testutils.Context(t) result, err := orm.FindOldestEntriesByState(ctx, functions.IN_PROGRESS, 2) require.NoError(t, err) - require.Equal(t, 2, len(result), "incorrect results length") + require.Len(t, result, 2, "incorrect results length") require.Equal(t, id1, result[0].RequestID, "incorrect results order") require.Equal(t, id2, result[1].RequestID, "incorrect results order") @@ -264,14 +263,14 @@ func TestORM_FindOldestEntriesByState(t *testing.T) { ctx := testutils.Context(t) result, err := orm.FindOldestEntriesByState(ctx, functions.IN_PROGRESS, 20) require.NoError(t, err) - require.Equal(t, 3, len(result), "incorrect results length") + require.Len(t, result, 3, "incorrect results length") }) t.Run("no matching entries", func(t *testing.T) { ctx := testutils.Context(t) result, err := orm.FindOldestEntriesByState(ctx, functions.RESULT_READY, 10) require.NoError(t, err) - require.Equal(t, 0, len(result), "incorrect results length") + require.Empty(t, result, "incorrect results length") }) } @@ -297,18 +296,18 @@ func TestORM_TimeoutExpiredResults(t *testing.T) { results, err := orm.TimeoutExpiredResults(ctx, now.Add(-35*time.Minute), 1) require.NoError(t, err) - require.Equal(t, 1, len(results), "not respecting limit") + require.Len(t, results, 1, "not respecting limit") require.Equal(t, ids[0], results[0], "incorrect results order") results, err = orm.TimeoutExpiredResults(ctx, now.Add(-15*time.Minute), 10) require.NoError(t, err) - require.Equal(t, 2, len(results), "incorrect results length") + require.Len(t, results, 2, "incorrect results length") require.Equal(t, ids[1], results[0], "incorrect results order") require.Equal(t, ids[3], results[1], "incorrect results order") results, err = orm.TimeoutExpiredResults(ctx, now.Add(-15*time.Minute), 10) require.NoError(t, err) - require.Equal(t, 0, len(results), "not idempotent") + require.Empty(t, results, "not idempotent") expectedFinalStates := []functions.RequestState{ functions.TIMED_OUT, @@ -320,7 +319,7 @@ func TestORM_TimeoutExpiredResults(t *testing.T) { for i, expectedState := range expectedFinalStates { req, err := orm.FindById(ctx, ids[i]) require.NoError(t, err) - require.Equal(t, req.State, expectedState, "incorrect state") + require.Equal(t, expectedState, req.State, "incorrect state") } } @@ -364,7 +363,7 @@ func TestORM_PruneOldestRequests(t *testing.T) { // verify only the newest one is left after pruning result, err := orm.FindOldestEntriesByState(ctx, functions.IN_PROGRESS, 20) require.NoError(t, err) - require.Equal(t, 1, len(result), "incorrect results length") + require.Len(t, result, 1, "incorrect results length") require.Equal(t, ids[4], result[0].RequestID, "incorrect results order") } @@ -388,5 +387,5 @@ func TestORM_PruneOldestRequests_Large(t *testing.T) { // verify there's 100 left result, err := orm.FindOldestEntriesByState(ctx, functions.IN_PROGRESS, 200) require.NoError(t, err) - require.Equal(t, 100, len(result), "incorrect results length") + require.Len(t, result, 100, "incorrect results length") } diff --git a/core/services/gateway/api/message_test.go b/core/services/gateway/api/message_test.go index 1f292db26b9..832171803ab 100644 --- a/core/services/gateway/api/message_test.go +++ b/core/services/gateway/api/message_test.go @@ -88,7 +88,7 @@ func TestMessage_MessageSignAndValidateSignature(t *testing.T) { err = msg.Sign(privateKey) require.NoError(t, err) - require.Equal(t, api.MessageSignatureHexEncodedLen, len(msg.Signature)) + require.Len(t, msg.Signature, api.MessageSignatureHexEncodedLen) // valid signer, err := msg.ExtractSigner() diff --git a/core/services/gateway/common/utils_test.go b/core/services/gateway/common/utils_test.go index f3ed6a0dfbb..0faf0d4a7d6 100644 --- a/core/services/gateway/common/utils_test.go +++ b/core/services/gateway/common/utils_test.go @@ -47,7 +47,7 @@ func TestUtils_BytesSignAndValidate(t *testing.T) { signature, err := common.SignData(privateKey, data) require.NoError(t, err) - require.Equal(t, 65, len(signature)) + require.Len(t, signature, 65) // valid signer, err := common.ExtractSigner(signature, data) diff --git a/core/services/gateway/connectionmanager.go b/core/services/gateway/connectionmanager.go index 7438b0042d2..f98ebb2bcad 100644 --- a/core/services/gateway/connectionmanager.go +++ b/core/services/gateway/connectionmanager.go @@ -266,7 +266,7 @@ func (m *donConnectionManager) SendToNode(ctx context.Context, nodeAddress strin } data, err := m.codec.EncodeRequest(msg) if err != nil { - return fmt.Errorf("error encoding request for node %s: %v", nodeAddress, err) + return fmt.Errorf("error encoding request for node %s: %w", nodeAddress, err) } nodeState := m.nodes[nodeAddress] if nodeState == nil { diff --git a/core/services/gateway/connector/connector.go b/core/services/gateway/connector/connector.go index cab123d4ce5..822fe241ca0 100644 --- a/core/services/gateway/connector/connector.go +++ b/core/services/gateway/connector/connector.go @@ -212,7 +212,7 @@ func (c *gatewayConnector) SignAndSendToGateway(ctx context.Context, gatewayID s err = c.SendToGateway(ctx, gatewayID, msg) if err != nil { - return fmt.Errorf("failed to send message to gateway %s: %v", gatewayID, err) + return fmt.Errorf("failed to send message to gateway %s: %w", gatewayID, err) } return nil } diff --git a/core/services/gateway/gateway_test.go b/core/services/gateway/gateway_test.go index 7a5457c788c..c4856bb5d7d 100644 --- a/core/services/gateway/gateway_test.go +++ b/core/services/gateway/gateway_test.go @@ -135,11 +135,11 @@ func TestGateway_CleanStartAndClose(t *testing.T) { } func requireJsonRPCResult(t *testing.T, response []byte, expectedId string, expectedResult string) { - require.Equal(t, fmt.Sprintf(`{"jsonrpc":"2.0","id":"%s","result":%s}`, expectedId, expectedResult), string(response)) + require.JSONEq(t, fmt.Sprintf(`{"jsonrpc":"2.0","id":"%s","result":%s}`, expectedId, expectedResult), string(response)) } func requireJsonRPCError(t *testing.T, response []byte, expectedId string, expectedCode int, expectedMsg string) { - require.Equal(t, fmt.Sprintf(`{"jsonrpc":"2.0","id":"%s","error":{"code":%d,"message":"%s"}}`, expectedId, expectedCode, expectedMsg), string(response)) + require.JSONEq(t, fmt.Sprintf(`{"jsonrpc":"2.0","id":"%s","error":{"code":%d,"message":"%s"}}`, expectedId, expectedCode, expectedMsg), string(response)) } func newGatewayWithMockHandler(t *testing.T) (gateway.Gateway, *handler_mocks.Handler) { diff --git a/core/services/gateway/handlers/capabilities/handler.go b/core/services/gateway/handlers/capabilities/handler.go index e1bdfdf8441..cd9407d3017 100644 --- a/core/services/gateway/handlers/capabilities/handler.go +++ b/core/services/gateway/handlers/capabilities/handler.go @@ -214,7 +214,7 @@ func (h *handler) HandleUserMessage(ctx context.Context, msg *api.Message, callb err := json.Unmarshal(body.Payload, &payload) if err != nil { h.lggr.Errorw("error decoding payload", "err", err) - callbackCh <- handlers.UserCallbackPayload{Msg: msg, ErrCode: api.UserMessageParseError, ErrMsg: fmt.Sprintf("error decoding payload %s", err.Error())} + callbackCh <- handlers.UserCallbackPayload{Msg: msg, ErrCode: api.UserMessageParseError, ErrMsg: "error decoding payload " + err.Error()} close(callbackCh) return nil } @@ -234,7 +234,7 @@ func (h *handler) HandleUserMessage(ctx context.Context, msg *api.Message, callb // TODO: apply allowlist and rate-limiting here if msg.Body.Method != MethodWebAPITrigger { h.lggr.Errorw("unsupported method", "method", body.Method) - callbackCh <- handlers.UserCallbackPayload{Msg: msg, ErrCode: api.HandlerError, ErrMsg: fmt.Sprintf("invalid method %s", msg.Body.Method)} + callbackCh <- handlers.UserCallbackPayload{Msg: msg, ErrCode: api.HandlerError, ErrMsg: "invalid method " + msg.Body.Method} close(callbackCh) return nil } diff --git a/core/services/gateway/handlers/capabilities/handler_test.go b/core/services/gateway/handlers/capabilities/handler_test.go index eb5d883ac14..1bfe470d7f3 100644 --- a/core/services/gateway/handlers/capabilities/handler_test.go +++ b/core/services/gateway/handlers/capabilities/handler_test.go @@ -161,7 +161,7 @@ func TestHandler_SendHTTPMessageToClient(t *testing.T) { }) t.Run("http client non-HTTP error", func(t *testing.T) { - httpClient.EXPECT().Send(mock.Anything, mock.Anything).Return(nil, fmt.Errorf("error while marshalling")).Once() + httpClient.EXPECT().Send(mock.Anything, mock.Anything).Return(nil, errors.New("error while marshalling")).Once() don.EXPECT().SendToNode(mock.Anything, nodes[0].Address, mock.MatchedBy(func(m *api.Message) bool { var payload Response @@ -263,7 +263,7 @@ func TestHandlerReceiveHTTPMessageFromClient(t *testing.T) { resp := <-ch require.Equal(t, handlers.UserCallbackPayload{Msg: msg, ErrCode: api.NoError, ErrMsg: ""}, resp) _, open := <-ch - require.Equal(t, open, false) + require.False(t, open) }) t.Run("sad case invalid method", func(t *testing.T) { @@ -274,7 +274,7 @@ func TestHandlerReceiveHTTPMessageFromClient(t *testing.T) { resp := <-ch require.Equal(t, handlers.UserCallbackPayload{Msg: invalidMsg, ErrCode: api.HandlerError, ErrMsg: "invalid method foo"}, resp) _, open := <-ch - require.Equal(t, open, false) + require.False(t, open) }) t.Run("sad case stale message", func(t *testing.T) { @@ -285,7 +285,7 @@ func TestHandlerReceiveHTTPMessageFromClient(t *testing.T) { resp := <-ch require.Equal(t, handlers.UserCallbackPayload{Msg: invalidMsg, ErrCode: api.HandlerError, ErrMsg: "stale message"}, resp) _, open := <-ch - require.Equal(t, open, false) + require.False(t, open) }) t.Run("sad case empty payload", func(t *testing.T) { @@ -296,7 +296,7 @@ func TestHandlerReceiveHTTPMessageFromClient(t *testing.T) { resp := <-ch require.Equal(t, handlers.UserCallbackPayload{Msg: invalidMsg, ErrCode: api.UserMessageParseError, ErrMsg: "error decoding payload field params in TriggerRequestPayload: required"}, resp) _, open := <-ch - require.Equal(t, open, false) + require.False(t, open) }) t.Run("sad case invalid payload", func(t *testing.T) { @@ -307,7 +307,7 @@ func TestHandlerReceiveHTTPMessageFromClient(t *testing.T) { resp := <-ch require.Equal(t, handlers.UserCallbackPayload{Msg: invalidMsg, ErrCode: api.UserMessageParseError, ErrMsg: "error decoding payload field params in TriggerRequestPayload: required"}, resp) _, open := <-ch - require.Equal(t, open, false) + require.False(t, open) }) // TODO: Validate Senders and rate limit chck, pending question in trigger about where senders and rate limits are validated } diff --git a/core/services/gateway/handlers/functions/allowlist/allowlist.go b/core/services/gateway/handlers/functions/allowlist/allowlist.go index 0beee599576..3b23156a352 100644 --- a/core/services/gateway/handlers/functions/allowlist/allowlist.go +++ b/core/services/gateway/handlers/functions/allowlist/allowlist.go @@ -102,7 +102,7 @@ func NewOnchainAllowlist(client evmclient.Client, config OnchainAllowlistConfig, contractV1, err := functions_router.NewFunctionsRouter(config.ContractAddress, client) if err != nil { - return nil, fmt.Errorf("unexpected error during functions_router.NewFunctionsRouter: %s", err) + return nil, fmt.Errorf("unexpected error during functions_router.NewFunctionsRouter: %w", err) } allowlist := &onchainAllowlist{ config: config, diff --git a/core/services/gateway/handlers/functions/allowlist/allowlist_test.go b/core/services/gateway/handlers/functions/allowlist/allowlist_test.go index b8735bbf8af..66efec0136c 100644 --- a/core/services/gateway/handlers/functions/allowlist/allowlist_test.go +++ b/core/services/gateway/handlers/functions/allowlist/allowlist_test.go @@ -3,7 +3,6 @@ package allowlist_test import ( "context" "encoding/hex" - "fmt" "math/big" "testing" "time" @@ -325,7 +324,7 @@ func TestExtractContractVersion(t *testing.T) { } var errInvalidVersion = func(v string) *string { - ev := fmt.Sprintf("version not found in string: %s", v) + ev := "version not found in string: " + v return &ev } diff --git a/core/services/gateway/handlers/functions/allowlist/orm_test.go b/core/services/gateway/handlers/functions/allowlist/orm_test.go index 388d47a769b..4e9c11fcbca 100644 --- a/core/services/gateway/handlers/functions/allowlist/orm_test.go +++ b/core/services/gateway/handlers/functions/allowlist/orm_test.go @@ -45,7 +45,7 @@ func TestORM_GetAllowedSenders(t *testing.T) { storedAllowedSenders := seedAllowedSenders(t, orm, 2) results, err := orm.GetAllowedSenders(ctx, 0, 1) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") require.Equal(t, storedAllowedSenders[0], results[0]) }) @@ -56,7 +56,7 @@ func TestORM_GetAllowedSenders(t *testing.T) { storedAllowedSenders := seedAllowedSenders(t, orm, 2) results, err := orm.GetAllowedSenders(ctx, 1, 5) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") require.Equal(t, storedAllowedSenders[1], results[0]) }) } @@ -74,7 +74,7 @@ func TestORM_CreateAllowedSenders(t *testing.T) { results, err := orm.GetAllowedSenders(ctx, 0, 1) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") require.Equal(t, expected, results[0]) }) @@ -91,7 +91,7 @@ func TestORM_CreateAllowedSenders(t *testing.T) { results, err := orm.GetAllowedSenders(ctx, 0, 5) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") require.Equal(t, expected, results[0]) }) @@ -105,7 +105,7 @@ func TestORM_CreateAllowedSenders(t *testing.T) { results, err := orm.GetAllowedSenders(ctx, 0, 2) require.NoError(t, err) - require.Equal(t, 2, len(results), "incorrect results length") + require.Len(t, results, 2, "incorrect results length") require.Equal(t, expected[0], results[0]) require.Equal(t, expected[1], results[1]) }) @@ -124,7 +124,7 @@ func TestORM_CreateAllowedSenders(t *testing.T) { results, err := orm.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 2, len(results), "incorrect results length") + require.Len(t, results, 2, "incorrect results length") require.Equal(t, expected[0], results[0]) require.Equal(t, expected[1], results[1]) }) @@ -154,7 +154,7 @@ func TestORM_DeleteAllowedSenders(t *testing.T) { results, err := orm.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 3, len(results), "incorrect results length") + require.Len(t, results, 3, "incorrect results length") require.Equal(t, add1, results[0]) err = orm.DeleteAllowedSenders(ctx, []common.Address{add1, add3}) @@ -162,7 +162,7 @@ func TestORM_DeleteAllowedSenders(t *testing.T) { results, err = orm.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") require.Equal(t, add2, results[0]) }) @@ -177,7 +177,7 @@ func TestORM_DeleteAllowedSenders(t *testing.T) { results, err := orm.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 2, len(results), "incorrect results length") + require.Len(t, results, 2, "incorrect results length") require.Equal(t, add1, results[0]) add3 := testutils.NewAddress() @@ -186,7 +186,7 @@ func TestORM_DeleteAllowedSenders(t *testing.T) { results, err = orm.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 2, len(results), "incorrect results length") + require.Len(t, results, 2, "incorrect results length") require.Equal(t, add1, results[0]) require.Equal(t, add2, results[1]) }) @@ -207,7 +207,7 @@ func TestORM_PurgeAllowedSenders(t *testing.T) { results, err := orm.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 3, len(results), "incorrect results length") + require.Len(t, results, 3, "incorrect results length") require.Equal(t, add1, results[0]) err = orm.PurgeAllowedSenders(ctx) @@ -215,7 +215,7 @@ func TestORM_PurgeAllowedSenders(t *testing.T) { results, err = orm.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 0, len(results), "incorrect results length") + require.Empty(t, results, "incorrect results length") }) t.Run("OK-purge_allowed_list_for_contract_address", func(t *testing.T) { @@ -229,7 +229,7 @@ func TestORM_PurgeAllowedSenders(t *testing.T) { results, err := orm1.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 2, len(results), "incorrect results length") + require.Len(t, results, 2, "incorrect results length") require.Equal(t, add1, results[0]) orm2, err := setupORM(t) @@ -241,7 +241,7 @@ func TestORM_PurgeAllowedSenders(t *testing.T) { results, err = orm2.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 2, len(results), "incorrect results length") + require.Len(t, results, 2, "incorrect results length") require.Equal(t, add3, results[0]) err = orm2.PurgeAllowedSenders(ctx) @@ -249,11 +249,11 @@ func TestORM_PurgeAllowedSenders(t *testing.T) { results, err = orm2.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 0, len(results), "incorrect results length") + require.Empty(t, results, "incorrect results length") results, err = orm1.GetAllowedSenders(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 2, len(results), "incorrect results length") + require.Len(t, results, 2, "incorrect results length") require.Equal(t, add1, results[0]) require.Equal(t, add2, results[1]) }) diff --git a/core/services/gateway/handlers/functions/handler.functions_test.go b/core/services/gateway/handlers/functions/handler.functions_test.go index b7abeed8a99..b2419bc0969 100644 --- a/core/services/gateway/handlers/functions/handler.functions_test.go +++ b/core/services/gateway/handlers/functions/handler.functions_test.go @@ -133,7 +133,7 @@ func TestFunctionsHandler_HandleUserMessage_SecretsSet(t *testing.T) { var payload functions.CombinedResponse require.NoError(t, json.Unmarshal(response.Msg.Body.Payload, &payload)) require.Equal(t, test.expectedGatewayResult, payload.Success) - require.Equal(t, test.expectedNodeMessageCount, len(payload.NodeResponses)) + require.Len(t, payload.NodeResponses, test.expectedNodeMessageCount) }() allowlist.On("Allow", common.HexToAddress(user.Address)).Return(true, nil) @@ -177,7 +177,7 @@ func TestFunctionsHandler_HandleUserMessage_Heartbeat(t *testing.T) { var payload functions.CombinedResponse require.NoError(t, json.Unmarshal(response.Msg.Body.Payload, &payload)) require.Equal(t, test.expectedGatewayResult, payload.Success) - require.Equal(t, test.expectedNodeMessageCount, len(payload.NodeResponses)) + require.Len(t, payload.NodeResponses, test.expectedNodeMessageCount) }() allowlist.On("Allow", common.HexToAddress(user.Address)).Return(true, nil) diff --git a/core/services/gateway/handlers/functions/subscriptions/orm_test.go b/core/services/gateway/handlers/functions/subscriptions/orm_test.go index e2d7cfe9f49..0afc2d78192 100644 --- a/core/services/gateway/handlers/functions/subscriptions/orm_test.go +++ b/core/services/gateway/handlers/functions/subscriptions/orm_test.go @@ -61,7 +61,7 @@ func TestORM_GetSubscriptions(t *testing.T) { storedSubscriptions := seedSubscriptions(t, orm, 2) results, err := orm.GetSubscriptions(ctx, 0, 1) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") require.Equal(t, storedSubscriptions[1], results[0]) }) @@ -72,7 +72,7 @@ func TestORM_GetSubscriptions(t *testing.T) { storedSubscriptions := seedSubscriptions(t, orm, 2) results, err := orm.GetSubscriptions(ctx, 1, 5) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") require.Equal(t, storedSubscriptions[0], results[0]) }) } @@ -100,7 +100,7 @@ func TestORM_UpsertSubscription(t *testing.T) { results, err := orm.GetSubscriptions(ctx, 0, 1) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") require.Equal(t, expected, results[0]) }) @@ -144,7 +144,7 @@ func TestORM_UpsertSubscription(t *testing.T) { results, err := orm.GetSubscriptions(ctx, 0, 5) require.NoError(t, err) - require.Equal(t, 2, len(results), "incorrect results length") + require.Len(t, results, 2, "incorrect results length") require.Equal(t, expectedNotUpdated, results[1]) require.Equal(t, expectedUpdated, results[0]) }) @@ -183,7 +183,7 @@ func TestORM_UpsertSubscription(t *testing.T) { results, err := orm.GetSubscriptions(ctx, 0, 5) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") require.Equal(t, subscription, results[0]) }) @@ -221,7 +221,7 @@ func TestORM_UpsertSubscription(t *testing.T) { results, err := orm1.GetSubscriptions(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") // should create a new subscription because it comes from a different router contract err = orm2.UpsertSubscription(ctx, subscription) @@ -229,11 +229,11 @@ func TestORM_UpsertSubscription(t *testing.T) { results, err = orm1.GetSubscriptions(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") results, err = orm2.GetSubscriptions(ctx, 0, 10) require.NoError(t, err) - require.Equal(t, 1, len(results), "incorrect results length") + require.Len(t, results, 1, "incorrect results length") }) } func Test_NewORM(t *testing.T) { diff --git a/core/services/gateway/handlers/functions/subscriptions/subscriptions.go b/core/services/gateway/handlers/functions/subscriptions/subscriptions.go index 568ce0708fa..ca18e58f998 100644 --- a/core/services/gateway/handlers/functions/subscriptions/subscriptions.go +++ b/core/services/gateway/handlers/functions/subscriptions/subscriptions.go @@ -64,7 +64,7 @@ func NewOnchainSubscriptions(client evmclient.Client, config OnchainSubscription } router, err := functions_router.NewFunctionsRouter(config.ContractAddress, client) if err != nil { - return nil, fmt.Errorf("unexpected error during functions_router.NewFunctionsRouter: %s", err) + return nil, fmt.Errorf("unexpected error during functions_router.NewFunctionsRouter: %w", err) } // if StoreBatchSize is not specified use the default value diff --git a/core/services/gateway/integration_tests/gateway_integration_test.go b/core/services/gateway/integration_tests/gateway_integration_test.go index 0ddf47bec04..47489490258 100644 --- a/core/services/gateway/integration_tests/gateway_integration_test.go +++ b/core/services/gateway/integration_tests/gateway_integration_test.go @@ -189,7 +189,7 @@ func TestIntegration_Gateway_NoFullNodes_BasicConnectionAndMessage(t *testing.T) require.NoError(t, respMsg.Validate()) require.Equal(t, strings.ToLower(nodeKeys.Address), respMsg.Body.Sender) require.Equal(t, messageId2, respMsg.Body.MessageId) - require.Equal(t, nodeResponsePayload, string(respMsg.Body.Payload)) + require.JSONEq(t, nodeResponsePayload, string(respMsg.Body.Payload)) } func newHttpRequestObject(t *testing.T, messageId string, userUrl string, signerKey *ecdsa.PrivateKey) *http.Request { diff --git a/core/services/headreporter/head_reporter_test.go b/core/services/headreporter/head_reporter_test.go index 304dd59a478..75be0a294b7 100644 --- a/core/services/headreporter/head_reporter_test.go +++ b/core/services/headreporter/head_reporter_test.go @@ -46,6 +46,6 @@ func Test_HeadReporterService(t *testing.T) { t.Run("has default report period", func(t *testing.T) { service := NewHeadReporterService(pgtest.NewSqlxDB(t), logger.TestLogger(t), NewMockHeadReporter(t)) - assert.Equal(t, service.reportPeriod, 15*time.Second) + assert.Equal(t, 15*time.Second, service.reportPeriod) }) } diff --git a/core/services/job/job_orm_test.go b/core/services/job/job_orm_test.go index 27223e0d706..4885e082007 100644 --- a/core/services/job/job_orm_test.go +++ b/core/services/job/job_orm_test.go @@ -186,8 +186,8 @@ func TestORM(t *testing.T) { require.NoError(t, err) require.Len(t, specErrors, 2) - assert.Equal(t, specErrors[0].Occurrences, uint(2)) - assert.Equal(t, specErrors[1].Occurrences, uint(1)) + assert.Equal(t, uint(2), specErrors[0].Occurrences) + assert.Equal(t, uint(1), specErrors[1].Occurrences) assert.True(t, specErrors[0].CreatedAt.Before(specErrors[0].UpdatedAt), "expected created_at (%s) to be before updated_at (%s)", specErrors[0].CreatedAt, specErrors[0].UpdatedAt) assert.Equal(t, specErrors[0].Description, ocrSpecError1) assert.Equal(t, specErrors[1].Description, ocrSpecError2) @@ -1078,7 +1078,7 @@ func Test_FindJobs(t *testing.T) { jobs, count, err2 := orm.FindJobs(testutils.Context(t), 0, 2) require.NoError(t, err2) require.Len(t, jobs, 2) - assert.Equal(t, count, 2) + assert.Equal(t, 2, count) expectedJobs := []job.Job{jb2, jb1} @@ -1091,7 +1091,7 @@ func Test_FindJobs(t *testing.T) { jobs, count, err2 := orm.FindJobs(testutils.Context(t), 0, 1) require.NoError(t, err2) require.Len(t, jobs, 1) - assert.Equal(t, count, 2) + assert.Equal(t, 2, count) expectedJobs := []job.Job{jb2} @@ -1219,7 +1219,7 @@ func Test_FindJob(t *testing.T) { assert.Equal(t, jb.ID, job.ID) assert.Equal(t, jb.Name, job.Name) - require.Greater(t, jb.PipelineSpecID, int32(0)) + require.Positive(t, jb.PipelineSpecID) require.NotNil(t, jb.PipelineSpec) require.NotNil(t, jb.OCROracleSpecID) require.NotNil(t, jb.OCROracleSpec) @@ -1233,7 +1233,7 @@ func Test_FindJob(t *testing.T) { assert.Equal(t, jb.ID, job.ID) assert.Equal(t, jb.Name, job.Name) - require.Greater(t, jb.PipelineSpecID, int32(0)) + require.Positive(t, jb.PipelineSpecID) require.NotNil(t, jb.PipelineSpec) require.NotNil(t, jb.OCROracleSpecID) require.NotNil(t, jb.OCROracleSpec) @@ -1333,7 +1333,7 @@ func Test_FindJobsByPipelineSpecIDs(t *testing.T) { assert.Equal(t, jb.ID, jbs[0].ID) assert.Equal(t, jb.Name, jbs[0].Name) - require.Greater(t, jbs[0].PipelineSpecID, int32(0)) + require.Positive(t, jbs[0].PipelineSpecID) require.Equal(t, jb.PipelineSpecID, jbs[0].PipelineSpecID) require.NotNil(t, jbs[0].PipelineSpec) }) @@ -1342,7 +1342,7 @@ func Test_FindJobsByPipelineSpecIDs(t *testing.T) { ctx := testutils.Context(t) jbs, err2 := orm.FindJobsByPipelineSpecIDs(ctx, []int32{-1}) require.NoError(t, err2) - assert.Len(t, jbs, 0) + assert.Empty(t, jbs) }) t.Run("with chainID disabled", func(t *testing.T) { @@ -1392,7 +1392,7 @@ func Test_FindPipelineRuns(t *testing.T) { ctx := testutils.Context(t) runs, count, err2 := orm.PipelineRuns(ctx, nil, 0, 10) require.NoError(t, err2) - assert.Equal(t, count, 0) + assert.Equal(t, 0, count) assert.Empty(t, runs) }) @@ -1403,7 +1403,7 @@ func Test_FindPipelineRuns(t *testing.T) { runs, count, err2 := orm.PipelineRuns(ctx, nil, 0, 10) require.NoError(t, err2) - assert.Equal(t, count, 1) + assert.Equal(t, 1, count) actual := runs[0] // Test pipeline run fields @@ -1455,7 +1455,7 @@ func Test_PipelineRunsByJobID(t *testing.T) { ctx := testutils.Context(t) runs, count, err2 := orm.PipelineRuns(ctx, &jb.ID, 0, 10) require.NoError(t, err2) - assert.Equal(t, count, 0) + assert.Equal(t, 0, count) assert.Empty(t, runs) }) @@ -1677,7 +1677,7 @@ func Test_FindPipelineRunByID(t *testing.T) { t.Run("with no pipeline run", func(t *testing.T) { ctx := testutils.Context(t) run, err2 := orm.FindPipelineRunByID(ctx, -1) - assert.Equal(t, run, pipeline.Run{}) + assert.Equal(t, pipeline.Run{}, run) require.ErrorIs(t, err2, sql.ErrNoRows) }) @@ -1733,8 +1733,8 @@ func Test_FindJobWithoutSpecErrors(t *testing.T) { jbWithErrors, err := orm.FindJob(testutils.Context(t), jobSpec.ID) require.NoError(t, err) - assert.Equal(t, len(jb.JobSpecErrors), 0) - assert.Equal(t, len(jbWithErrors.JobSpecErrors), 2) + assert.Empty(t, jb.JobSpecErrors) + assert.Len(t, jbWithErrors.JobSpecErrors, 2) } func Test_FindSpecErrorsByJobIDs(t *testing.T) { @@ -1769,7 +1769,7 @@ func Test_FindSpecErrorsByJobIDs(t *testing.T) { specErrs, err := orm.FindSpecErrorsByJobIDs(ctx, []int32{jobSpec.ID}) require.NoError(t, err) - assert.Equal(t, len(specErrs), 2) + assert.Len(t, specErrs, 2) } func Test_CountPipelineRunsByJobID(t *testing.T) { @@ -2008,7 +2008,7 @@ func Test_ORM_FindJobByWorkflow_Multiple(t *testing.T) { assert.EqualValues(t, j.WorkflowSpec.WorkflowID, s.WorkflowID) assert.EqualValues(t, j.WorkflowSpec.WorkflowOwner, s.WorkflowOwner) assert.EqualValues(t, j.WorkflowSpec.WorkflowName, s.WorkflowName) - assert.Equal(t, j.WorkflowSpec.SpecType, job.YamlSpec) + assert.Equal(t, job.YamlSpec, j.WorkflowSpec.SpecType) } }) } diff --git a/core/services/job/kv_orm_test.go b/core/services/job/kv_orm_test.go index f943a4bb6b4..4e3a42cc1ba 100644 --- a/core/services/job/kv_orm_test.go +++ b/core/services/job/kv_orm_test.go @@ -2,7 +2,7 @@ package job_test import ( "context" - "fmt" + "strconv" "testing" "github.com/stretchr/testify/assert" @@ -49,7 +49,7 @@ func TestJobKVStore(t *testing.T) { } for i, insertBytes := range values { - testKey := "test_key_" + fmt.Sprint(i) + testKey := "test_key_" + strconv.Itoa(i) require.NoError(t, kvStore.Store(ctx, testKey, insertBytes)) var readBytes []byte diff --git a/core/services/job/models.go b/core/services/job/models.go index 26d563c7ac8..44b1e836956 100644 --- a/core/services/job/models.go +++ b/core/services/job/models.go @@ -261,7 +261,7 @@ type PipelineRun struct { } func (pr PipelineRun) GetID() string { - return fmt.Sprintf("%v", pr.ID) + return strconv.FormatInt(pr.ID, 10) } func (pr *PipelineRun) SetID(value string) error { @@ -297,7 +297,7 @@ type OCROracleSpec struct { // GetID is a getter function that returns the ID of the spec. func (s OCROracleSpec) GetID() string { - return fmt.Sprintf("%v", s.ID) + return strconv.Itoa(int(s.ID)) } // SetID is a setter function that sets the ID of the spec. @@ -426,7 +426,7 @@ func (s *OCR2OracleSpec) getChainID() (string, error) { func (s *OCR2OracleSpec) getChainIdFromRelayConfig() (string, error) { v, exists := s.RelayConfig["chainID"] if !exists { - return "", fmt.Errorf("chainID does not exist") + return "", errors.New("chainID does not exist") } switch t := v.(type) { case string: @@ -445,7 +445,7 @@ func (s *OCR2OracleSpec) getChainIdFromRelayConfig() (string, error) { // GetID is a getter function that returns the ID of the spec. func (s OCR2OracleSpec) GetID() string { - return fmt.Sprintf("%v", s.ID) + return strconv.Itoa(int(s.ID)) } // SetID is a setter function that sets the ID of the spec. @@ -474,7 +474,7 @@ type WebhookSpec struct { } func (w WebhookSpec) GetID() string { - return fmt.Sprintf("%v", w.ID) + return strconv.Itoa(int(w.ID)) } func (w *WebhookSpec) SetID(value string) error { @@ -506,7 +506,7 @@ type CronSpec struct { } func (s CronSpec) GetID() string { - return fmt.Sprintf("%v", s.ID) + return strconv.Itoa(int(s.ID)) } func (s *CronSpec) SetID(value string) error { @@ -813,7 +813,7 @@ type GatewaySpec struct { } func (s GatewaySpec) GetID() string { - return fmt.Sprintf("%v", s.ID) + return strconv.Itoa(int(s.ID)) } func (s *GatewaySpec) SetID(value string) error { @@ -1017,7 +1017,7 @@ type StandardCapabilitiesSpec struct { } func (w *StandardCapabilitiesSpec) GetID() string { - return fmt.Sprintf("%v", w.ID) + return strconv.Itoa(int(w.ID)) } func (w *StandardCapabilitiesSpec) SetID(value string) error { diff --git a/core/services/job/orm.go b/core/services/job/orm.go index cfd8060d60c..f4f53018d22 100644 --- a/core/services/job/orm.go +++ b/core/services/job/orm.go @@ -1363,7 +1363,7 @@ func (o *orm) PipelineRuns(ctx context.Context, jobID *int32, offset, size int) filter = fmt.Sprintf("JOIN job_pipeline_specs USING(pipeline_spec_id) WHERE job_pipeline_specs.job_id = %d", *jobID) } err = o.transact(ctx, false, func(tx *orm) error { - sql := fmt.Sprintf(`SELECT count(*) FROM pipeline_runs %s`, filter) + sql := "SELECT count(*) FROM pipeline_runs " + filter if err = tx.ds.QueryRowxContext(ctx, sql).Scan(&count); err != nil { return errors.Wrap(err, "error counting runs") } diff --git a/core/services/job/runner_integration_test.go b/core/services/job/runner_integration_test.go index 7856c4f151f..a36f9d423a7 100644 --- a/core/services/job/runner_integration_test.go +++ b/core/services/job/runner_integration_test.go @@ -131,8 +131,8 @@ func TestRunner(t *testing.T) { results := taskResults.FinalResult() require.Len(t, results.Values, 2) require.GreaterOrEqual(t, len(results.FatalErrors), 2) - assert.Nil(t, results.FatalErrors[0]) - assert.Nil(t, results.FatalErrors[1]) + assert.NoError(t, results.FatalErrors[0]) + assert.NoError(t, results.FatalErrors[1]) require.GreaterOrEqual(t, len(results.AllErrors), 2) assert.Equal(t, "6225.6", results.Values[0].(decimal.Decimal).String()) assert.Equal(t, "Hal Finney", results.Values[1].(string)) @@ -182,13 +182,13 @@ func TestRunner(t *testing.T) { // Should not be able to delete a bridge in use. jids, err := jobORM.FindJobIDsWithBridge(ctx, bridge.Name.String()) require.NoError(t, err) - require.Equal(t, 1, len(jids)) + require.Len(t, jids, 1) // But if we delete the job, then we can. require.NoError(t, jobORM.DeleteJob(ctx, jb.ID, jb.Type)) jids, err = jobORM.FindJobIDsWithBridge(ctx, bridge.Name.String()) require.NoError(t, err) - require.Equal(t, 0, len(jids)) + require.Empty(t, jids) }) t.Run("referencing a non-existent bridge should error", func(t *testing.T) { @@ -665,7 +665,7 @@ answer1 [type=median index=0]; se = []job.SpecError{} err = db.Select(&se, `SELECT * FROM job_spec_errors`) require.NoError(t, err) - require.Len(t, se, 0) + require.Empty(t, se) // TODO: This breaks the txdb connection, failing subsequent tests. Resolve in the future // Noop once the job is gone. @@ -708,7 +708,7 @@ answer1 [type=median index=0]; require.NoError(t, err) results = taskResults.FinalResult() assert.Equal(t, 10.1, results.Values[0]) - assert.Nil(t, results.FatalErrors[0]) + assert.NoError(t, results.FatalErrors[0]) // Job specified task timeout should fail. jb = makeMinimalHTTPOracleSpec(t, db, config, cltest.NewEIP55Address().String(), transmitterAddress.Hex(), cltest.DefaultOCRKeyBundleID, serv.URL, "") @@ -720,7 +720,7 @@ answer1 [type=median index=0]; _, taskResults, err = runner.ExecuteAndInsertFinishedRun(testutils.Context(t), *jb.PipelineSpec, pipeline.NewVarsFrom(nil), true) require.NoError(t, err) resultsNoFatalErrs := taskResults.FinalResult() - assert.NotNil(t, resultsNoFatalErrs.FatalErrors[0]) + assert.Error(t, resultsNoFatalErrs.FatalErrors[0]) }) t.Run("deleting jobs", func(t *testing.T) { @@ -741,7 +741,7 @@ answer1 [type=median index=0]; require.NoError(t, err) results := taskResults.FinalResult() assert.Len(t, results.Values, 1) - assert.Nil(t, results.FatalErrors[0]) + assert.NoError(t, results.FatalErrors[0]) assert.Equal(t, "4242", results.Values[0].(decimal.Decimal).String()) // Delete the job diff --git a/core/services/job/spawner.go b/core/services/job/spawner.go index cc45320de10..e9475385fbf 100644 --- a/core/services/job/spawner.go +++ b/core/services/job/spawner.go @@ -128,7 +128,7 @@ func (js *spawner) startAllServices(ctx context.Context) { // TODO: rename to find AllJobs specs, _, err := js.orm.FindJobs(ctx, 0, math.MaxUint32) if err != nil { - werr := fmt.Errorf("couldn't fetch unclaimed jobs: %v", err) + werr := fmt.Errorf("couldn't fetch unclaimed jobs: %w", err) js.lggr.Critical(werr.Error()) js.SvcErrBuffer.Append(werr) return diff --git a/core/services/job/spawner_test.go b/core/services/job/spawner_test.go index b8144ef86f8..5b697dbce8d 100644 --- a/core/services/job/spawner_test.go +++ b/core/services/job/spawner_test.go @@ -286,7 +286,7 @@ func TestSpawner_CreateJobDeleteJob(t *testing.T) { lggr := logger.TestLogger(t) legacyChains := evmtest.NewLegacyChains(t, testopts) - assert.Equal(t, legacyChains.Len(), 1) + assert.Equal(t, 1, legacyChains.Len()) chain := evmtest.MustGetDefaultChain(t, legacyChains) evmRelayer, err := evmrelayer.NewRelayer(ctx, lggr, chain, evmrelayer.RelayerOpts{ diff --git a/core/services/job/util.go b/core/services/job/util.go index 143dfed7e45..3a0668156ea 100644 --- a/core/services/job/util.go +++ b/core/services/job/util.go @@ -7,8 +7,8 @@ import ( ) var ( - ErrNoChainFromSpec = fmt.Errorf("could not get chain from spec") - ErrNoSendingKeysFromSpec = fmt.Errorf("could not get sending keys from spec") + ErrNoChainFromSpec = errors.New("could not get chain from spec") + ErrNoSendingKeysFromSpec = errors.New("could not get sending keys from spec") ) // SendingKeysForJob parses the job spec and retrieves the sending keys found. diff --git a/core/services/job/wasm_file_spec_factory.go b/core/services/job/wasm_file_spec_factory.go index eb952a47c89..3284d693984 100644 --- a/core/services/job/wasm_file_spec_factory.go +++ b/core/services/job/wasm_file_spec_factory.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "crypto/sha256" + "encoding/hex" "errors" "fmt" "io" @@ -108,7 +109,7 @@ func (w WasmFileSpecFactory) sha(wasm, config []byte) string { sum := sha256.New() sum.Write(wasm) sum.Write(config) - return fmt.Sprintf("%x", sum.Sum(nil)) + return hex.EncodeToString(sum.Sum(nil)) } var _ WorkflowSpecFactory = (*WasmFileSpecFactory)(nil) diff --git a/core/services/job/wasm_file_spec_factory_test.go b/core/services/job/wasm_file_spec_factory_test.go index bf078a8026e..8160998d093 100644 --- a/core/services/job/wasm_file_spec_factory_test.go +++ b/core/services/job/wasm_file_spec_factory_test.go @@ -3,7 +3,7 @@ package job_test import ( "bytes" "crypto/sha256" - "fmt" + "encoding/hex" "os" "os/exec" "strings" @@ -48,7 +48,7 @@ func TestWasmFileSpecFactory(t *testing.T) { expectedSha := sha256.New() expectedSha.Write(rawBinary) expectedSha.Write(config) - require.Equal(t, fmt.Sprintf("%x", expectedSha.Sum(nil)), actualSha) + require.Equal(t, hex.EncodeToString(expectedSha.Sum(nil)), actualSha) require.Equal(t, *expected, actual) @@ -71,7 +71,7 @@ func TestWasmFileSpecFactory(t *testing.T) { expectedSha := sha256.New() expectedSha.Write(rawBinary) expectedSha.Write(config) - require.Equal(t, fmt.Sprintf("%x", expectedSha.Sum(nil)), actualSha) + require.Equal(t, hex.EncodeToString(expectedSha.Sum(nil)), actualSha) require.Equal(t, *expected, actual) diff --git a/core/services/job/yaml_spec_factory_test.go b/core/services/job/yaml_spec_factory_test.go index 91b1257a6b6..e309db97d1c 100644 --- a/core/services/job/yaml_spec_factory_test.go +++ b/core/services/job/yaml_spec_factory_test.go @@ -75,7 +75,7 @@ func TestYamlSpecFactory_GetSpec(t *testing.T) { require.Equal(t, expected, actual) assert.Equal(t, fmt.Sprintf("%x", sha256.Sum256([]byte(anyYamlSpec))), actualSha) - assert.Equal(t, anyYamlSpec, string(raw)) + assert.YAMLEq(t, anyYamlSpec, string(raw)) } func TestYamlSpecFactory_Config(t *testing.T) { diff --git a/core/services/keeper/integration_test.go b/core/services/keeper/integration_test.go index 221bbd343b6..a789ce4c65b 100644 --- a/core/services/keeper/integration_test.go +++ b/core/services/keeper/integration_test.go @@ -314,7 +314,7 @@ func TestKeeperEthIntegration(t *testing.T) { // This happens in case we start a pipeline run before previous perform tx is committed to chain require.GreaterOrEqual(t, len(runs), 3) prr := webpresenters.NewPipelineRunResource(runs[0], logger.TestLogger(t)) - require.Equal(t, 1, len(prr.Outputs)) + require.Len(t, prr.Outputs, 1) require.Nil(t, prr.Outputs[0]) }) } @@ -462,7 +462,7 @@ func TestKeeperForwarderEthIntegration(t *testing.T) { require.NoError(t, err2) return upkeepCfg.LastKeeper } - require.Equal(t, lastKeeper(), common.Address{}) + require.Equal(t, common.Address{}, lastKeeper()) err = app.JobSpawner().StartService(ctx, jb) require.NoError(t, err) diff --git a/core/services/keeper/orm_test.go b/core/services/keeper/orm_test.go index 2bc5f0de940..4b5456653fe 100644 --- a/core/services/keeper/orm_test.go +++ b/core/services/keeper/orm_test.go @@ -81,7 +81,7 @@ func TestKeeperDB_Registries(t *testing.T) { existingRegistries, err := orm.Registries(ctx) require.NoError(t, err) - require.Equal(t, 2, len(existingRegistries)) + require.Len(t, existingRegistries, 2) } func TestKeeperDB_RegistryByContractAddress(t *testing.T) { @@ -212,12 +212,12 @@ func TestKeeperDB_NewEligibleUpkeeps_GracePeriod(t *testing.T) { require.NoError(t, db.Get(&upkeep, `UPDATE upkeep_registrations SET last_keeper_index = 0, last_run_block_height = 10 RETURNING *`)) list0, err := orm.EligibleUpkeepsForRegistry(ctx, registry.ContractAddress, 21, 100, fmt.Sprintf("%b", evmutils.NewHash().Big())) // none eligible require.NoError(t, err) - require.Equal(t, 0, len(list0), "should be 0 as all last perform was done by current node") + require.Empty(t, list0, "should be 0 as all last perform was done by current node") // once passed grace period list1, err := orm.EligibleUpkeepsForRegistry(ctx, registry.ContractAddress, 121, 100, fmt.Sprintf("%b", evmutils.NewHash().Big())) // none eligible require.NoError(t, err) - require.NotEqual(t, 0, len(list1), "should get some eligible upkeeps now that they are outside grace period") + require.NotEmpty(t, list1, "should get some eligible upkeeps now that they are outside grace period") } func TestKeeperDB_EligibleUpkeeps_TurnsRandom(t *testing.T) { @@ -284,7 +284,7 @@ func TestKeeperDB_NewEligibleUpkeeps_SkipIfLastPerformedByCurrentKeeper(t *testi require.NoError(t, db.Get(&upkeep, `UPDATE upkeep_registrations SET last_keeper_index = 0 RETURNING *`)) list0, err := orm.EligibleUpkeepsForRegistry(ctx, registry.ContractAddress, 21, 100, fmt.Sprintf("%b", evmutils.NewHash().Big())) // none eligible require.NoError(t, err) - require.Equal(t, 0, len(list0), "should be 0 as all last perform was done by current node") + require.Empty(t, list0, "should be 0 as all last perform was done by current node") } func TestKeeperDB_NewEligibleUpkeeps_CoverBuddy(t *testing.T) { @@ -331,7 +331,7 @@ func TestKeeperDB_NewEligibleUpkeeps_FirstTurn(t *testing.T) { // last keeper index is null to simulate a normal first run listKpr0, err := orm.EligibleUpkeepsForRegistry(ctx, registry.ContractAddress, 21, 100, binaryHash) // someone eligible only kpr0 turn require.NoError(t, err) - require.NotEqual(t, 0, len(listKpr0), "kpr0 should have some eligible as a normal turn") + require.NotEmpty(t, listKpr0, "kpr0 should have some eligible as a normal turn") } func TestKeeperDB_NewEligibleUpkeeps_FiltersByRegistry(t *testing.T) { @@ -355,8 +355,8 @@ func TestKeeperDB_NewEligibleUpkeeps_FiltersByRegistry(t *testing.T) { list2, err := orm.EligibleUpkeepsForRegistry(ctx, registry2.ContractAddress, 20, 100, binaryHash) require.NoError(t, err) - assert.Equal(t, 1, len(list1)) - assert.Equal(t, 1, len(list2)) + assert.Len(t, list1, 1) + assert.Len(t, list2, 1) } func TestKeeperDB_AllUpkeepIDsForRegistry(t *testing.T) { @@ -369,7 +369,7 @@ func TestKeeperDB_AllUpkeepIDsForRegistry(t *testing.T) { upkeepIDs, err := orm.AllUpkeepIDsForRegistry(ctx, registry.ID) require.NoError(t, err) // No upkeeps returned - require.Len(t, upkeepIDs, 0) + require.Empty(t, upkeepIDs) upkeep := newUpkeep(registry, 3) err = orm.UpsertUpkeep(ctx, &upkeep) @@ -422,22 +422,22 @@ func TestKeeperDB_NewSetLastRunInfoForUpkeepOnJob(t *testing.T) { // update rowsAffected, err := orm.SetLastRunInfoForUpkeepOnJob(ctx, j.ID, upkeep.UpkeepID, 100, registry.FromAddress) require.NoError(t, err) - require.Equal(t, rowsAffected, int64(1)) + require.Equal(t, int64(1), rowsAffected) assertLastRunHeight(t, db, upkeep, 100, 0) // update to lower block height not allowed rowsAffected, err = orm.SetLastRunInfoForUpkeepOnJob(ctx, j.ID, upkeep.UpkeepID, 0, registry.FromAddress) require.NoError(t, err) - require.Equal(t, rowsAffected, int64(0)) + require.Equal(t, int64(0), rowsAffected) assertLastRunHeight(t, db, upkeep, 100, 0) // update to same block height allowed rowsAffected, err = orm.SetLastRunInfoForUpkeepOnJob(ctx, j.ID, upkeep.UpkeepID, 100, types.EIP55AddressFromAddress(evmutils.ZeroAddress)) require.NoError(t, err) - require.Equal(t, rowsAffected, int64(1)) + require.Equal(t, int64(1), rowsAffected) assertLastRunHeight(t, db, upkeep, 100, 1) // update to higher block height allowed rowsAffected, err = orm.SetLastRunInfoForUpkeepOnJob(ctx, j.ID, upkeep.UpkeepID, 101, registry.FromAddress) require.NoError(t, err) - require.Equal(t, rowsAffected, int64(1)) + require.Equal(t, int64(1), rowsAffected) assertLastRunHeight(t, db, upkeep, 101, 0) } diff --git a/core/services/keeper/registry1_1_synchronizer_test.go b/core/services/keeper/registry1_1_synchronizer_test.go index 61482208e5c..07e8c6a792f 100644 --- a/core/services/keeper/registry1_1_synchronizer_test.go +++ b/core/services/keeper/registry1_1_synchronizer_test.go @@ -159,7 +159,7 @@ func Test_RegistrySynchronizer1_1_FullSync(t *testing.T) { err := db.Get(&upkeep, `SELECT * FROM upkeep_registrations`) require.NoError(t, err) return upkeep.LastKeeperIndex.Valid - }, testutils.WaitTimeout(t), cltest.DBPollingInterval).Should(gomega.Equal(true)) + }, testutils.WaitTimeout(t), cltest.DBPollingInterval).Should(gomega.BeTrue()) g.Eventually(func() int64 { var upkeep keeper.UpkeepRegistration err := db.Get(&upkeep, `SELECT * FROM upkeep_registrations`) diff --git a/core/services/keeper/registry1_2_synchronizer_test.go b/core/services/keeper/registry1_2_synchronizer_test.go index a62e27b8759..cd30e303293 100644 --- a/core/services/keeper/registry1_2_synchronizer_test.go +++ b/core/services/keeper/registry1_2_synchronizer_test.go @@ -177,7 +177,7 @@ func Test_RegistrySynchronizer1_2_FullSync(t *testing.T) { err := db.Get(&upkeep, `SELECT * FROM upkeep_registrations`) require.NoError(t, err) return upkeep.LastKeeperIndex.Valid - }, testutils.WaitTimeout(t), cltest.DBPollingInterval).Should(gomega.Equal(true)) + }, testutils.WaitTimeout(t), cltest.DBPollingInterval).Should(gomega.BeTrue()) g.Eventually(func() int64 { var upkeep keeper.UpkeepRegistration err := db.Get(&upkeep, `SELECT * FROM upkeep_registrations`) diff --git a/core/services/keeper/registry1_3_synchronizer_test.go b/core/services/keeper/registry1_3_synchronizer_test.go index 7ebbbc25469..84c8fb59a3c 100644 --- a/core/services/keeper/registry1_3_synchronizer_test.go +++ b/core/services/keeper/registry1_3_synchronizer_test.go @@ -182,7 +182,7 @@ func Test_RegistrySynchronizer1_3_FullSync(t *testing.T) { err := db.Get(&upkeep, `SELECT * FROM upkeep_registrations`) require.NoError(t, err) return upkeep.LastKeeperIndex.Valid - }, testutils.WaitTimeout(t), cltest.DBPollingInterval).Should(gomega.Equal(true)) + }, testutils.WaitTimeout(t), cltest.DBPollingInterval).Should(gomega.BeTrue()) g.Eventually(func() int64 { var upkeep keeper.UpkeepRegistration err := db.Get(&upkeep, `SELECT * FROM upkeep_registrations`) diff --git a/core/services/keeper/registry_synchronizer_core.go b/core/services/keeper/registry_synchronizer_core.go index e578e126cd9..464a004953f 100644 --- a/core/services/keeper/registry_synchronizer_core.go +++ b/core/services/keeper/registry_synchronizer_core.go @@ -2,7 +2,7 @@ package keeper import ( "context" - "fmt" + "strconv" "sync" "time" @@ -95,7 +95,7 @@ func (rs *RegistrySynchronizer) Start(context.Context) error { <-rs.chStop }() - rs.mailMon.Monitor(rs.mbLogs, "RegistrySynchronizer", "Logs", fmt.Sprint(rs.job.ID)) + rs.mailMon.Monitor(rs.mbLogs, "RegistrySynchronizer", "Logs", strconv.Itoa(int(rs.job.ID))) return nil }) diff --git a/core/services/keeper/registry_synchronizer_process_logs.go b/core/services/keeper/registry_synchronizer_process_logs.go index 5aaddb6f1e4..aaf697d064d 100644 --- a/core/services/keeper/registry_synchronizer_process_logs.go +++ b/core/services/keeper/registry_synchronizer_process_logs.go @@ -230,7 +230,7 @@ func (rs *RegistrySynchronizer) handleUpkeepPaused(ctx context.Context, broadcas if err != nil { return errors.Wrap(err, "unable to batch delete upkeeps") } - rs.logger.Debugw(fmt.Sprintf("paused upkeep %s", pausedUpkeepId.String()), "txHash", broadcast.RawLog().TxHash.Hex()) + rs.logger.Debugw("paused upkeep "+pausedUpkeepId.String(), "txHash", broadcast.RawLog().TxHash.Hex()) return nil } @@ -251,7 +251,7 @@ func (rs *RegistrySynchronizer) handleUpkeepUnpaused(ctx context.Context, broadc if err != nil { return errors.Wrapf(err, "failed to sync upkeep, log: %s", broadcast.String()) } - rs.logger.Debugw(fmt.Sprintf("unpaused upkeep %s", unpausedUpkeepId.String()), "txHash", broadcast.RawLog().TxHash.Hex()) + rs.logger.Debugw("unpaused upkeep "+unpausedUpkeepId.String(), "txHash", broadcast.RawLog().TxHash.Hex()) return nil } @@ -273,6 +273,6 @@ func (rs *RegistrySynchronizer) handleUpkeepCheckDataUpdated(ctx context.Context return errors.Wrapf(err, "unable to update check data for upkeep %s", updateLog.UpkeepID.String()) } - rs.logger.Debugw(fmt.Sprintf("updated check data for upkeep %s", updateLog.UpkeepID.String()), "txHash", broadcast.RawLog().TxHash.Hex()) + rs.logger.Debugw("updated check data for upkeep "+updateLog.UpkeepID.String(), "txHash", broadcast.RawLog().TxHash.Hex()) return nil } diff --git a/core/services/keeper/registry_synchronizer_sync_test.go b/core/services/keeper/registry_synchronizer_sync_test.go index 7cc1c5a11cc..2d28fca2fb1 100644 --- a/core/services/keeper/registry_synchronizer_sync_test.go +++ b/core/services/keeper/registry_synchronizer_sync_test.go @@ -23,7 +23,7 @@ type GetUpkeepFailure struct{} var errGetUpkeep = errors.New("chain connection error example") func (g *GetUpkeepFailure) GetUpkeep(opts *bind.CallOpts, id *big.Int) (*UpkeepConfig, error) { - return nil, fmt.Errorf("%w [%s]: getConfig v1.%d", ErrContractCallFailure, errGetUpkeep, RegistryVersion_1_2) + return nil, fmt.Errorf("%w [%w]: getConfig v1.%d", ErrContractCallFailure, errGetUpkeep, RegistryVersion_1_2) } func TestSyncUpkeepWithCallback_UpkeepNotFound(t *testing.T) { diff --git a/core/services/keeper/upkeep_executer_test.go b/core/services/keeper/upkeep_executer_test.go index e7156272e6e..f538bd2f1ad 100644 --- a/core/services/keeper/upkeep_executer_test.go +++ b/core/services/keeper/upkeep_executer_test.go @@ -334,12 +334,12 @@ func Test_UpkeepExecuter_PerformsUpkeep_Error(t *testing.T) { head := newHead() executer.OnNewLongestChain(testutils.Context(t), &head) - g.Eventually(wasCalled.Load).Should(gomega.Equal(true)) + g.Eventually(wasCalled.Load).Should(gomega.BeTrue()) txStore := txmgr.NewTxStore(db, logger.TestLogger(t)) txes, err := txStore.GetAllTxes(testutils.Context(t)) require.NoError(t, err) - require.Len(t, txes, 0) + require.Empty(t, txes) } func ptr[T any](t T) *T { return &t } diff --git a/core/services/keystore/aptos_test.go b/core/services/keystore/aptos_test.go index 9a2764adff6..72c2707bb1f 100644 --- a/core/services/keystore/aptos_test.go +++ b/core/services/keystore/aptos_test.go @@ -32,7 +32,7 @@ func Test_AptosKeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -87,14 +87,14 @@ func Test_AptosKeyStore_E2E(t *testing.T) { assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) _, err = ks.Delete(ctx, newKey.ID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) _, err = ks.Get(newKey.ID()) require.Error(t, err) }) @@ -110,7 +110,7 @@ func Test_AptosKeyStore_E2E(t *testing.T) { keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) }) t.Run("sign tx", func(t *testing.T) { diff --git a/core/services/keystore/cosmos_test.go b/core/services/keystore/cosmos_test.go index cad6dd67654..02bc2245447 100644 --- a/core/services/keystore/cosmos_test.go +++ b/core/services/keystore/cosmos_test.go @@ -32,7 +32,7 @@ func Test_CosmosKeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -86,14 +86,14 @@ func Test_CosmosKeyStore_E2E(t *testing.T) { assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) _, err = ks.Delete(ctx, newKey.ID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) _, err = ks.Get(newKey.ID()) require.Error(t, err) }) @@ -109,6 +109,6 @@ func Test_CosmosKeyStore_E2E(t *testing.T) { keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) }) } diff --git a/core/services/keystore/csa_test.go b/core/services/keystore/csa_test.go index 84d79798011..281cd0933c5 100644 --- a/core/services/keystore/csa_test.go +++ b/core/services/keystore/csa_test.go @@ -33,7 +33,7 @@ func Test_CSAKeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -111,12 +111,12 @@ func Test_CSAKeyStore_E2E(t *testing.T) { require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) keys, err = ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) _, err = ks.Get(newKey.ID()) require.Error(t, err) @@ -153,7 +153,7 @@ func Test_CSAKeyStore_E2E(t *testing.T) { keys, err2 := ks.GetAll() assert.NoError(t, err2) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) require.Equal(t, newKey.ID(), keys[0].ID()) require.Equal(t, newKey.Version, keys[0].Version) require.Equal(t, newKey.PublicKey, keys[0].PublicKey) @@ -165,7 +165,7 @@ func Test_CSAKeyStore_E2E(t *testing.T) { keys, err := ks.GetAll() assert.NoError(t, err) - assert.Equal(t, 0, len(keys)) + assert.Empty(t, keys) err = keyStore.CSA().EnsureKey(ctx) assert.NoError(t, err) @@ -174,6 +174,6 @@ func Test_CSAKeyStore_E2E(t *testing.T) { assert.NoError(t, err) require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) }) } diff --git a/core/services/keystore/eth.go b/core/services/keystore/eth.go index f69bbec28d2..fb15ec259e1 100644 --- a/core/services/keystore/eth.go +++ b/core/services/keystore/eth.go @@ -116,7 +116,7 @@ func (ks *eth) Create(ctx context.Context, chainIDs ...*big.Int) (ethkey.KeyV2, return ethkey.KeyV2{}, errors.Wrap(err, "unable to add eth key") } ks.notify() - ks.logger.Infow(fmt.Sprintf("Created EVM key with ID %s", key.Address.Hex()), "address", key.Address.Hex(), "evmChainIDs", chainIDs) + ks.logger.Infow("Created EVM key with ID "+key.Address.Hex(), "address", key.Address.Hex(), "evmChainIDs", chainIDs) return key, err } @@ -143,7 +143,7 @@ func (ks *eth) EnsureKeys(ctx context.Context, chainIDs ...*big.Int) (err error) if err != nil { return fmt.Errorf("failed to add key %s for chain %s: %w", newKey.Address, chainID, err) } - ks.logger.Infow(fmt.Sprintf("Created EVM key with ID %s", newKey.Address.Hex()), "address", newKey.Address.Hex(), "evmChainID", chainID) + ks.logger.Infow("Created EVM key with ID "+newKey.Address.Hex(), "address", newKey.Address.Hex(), "evmChainID", chainID) } return nil @@ -508,7 +508,7 @@ func (ks *eth) XXXTestingOnlySetState(ctx context.Context, state ethkey.State) { } existingState, exists := ks.keyStates.ChainIDKeyID[state.EVMChainID.String()][state.KeyID()] if !exists { - panic(fmt.Sprintf("key not found with ID %s", state.KeyID())) + panic("key not found with ID " + state.KeyID()) } *existingState = state sql := `UPDATE evm.key_states SET address = :address, is_disabled = :is_disabled, evm_chain_id = :evm_chain_id, updated_at = NOW() diff --git a/core/services/keystore/eth_test.go b/core/services/keystore/eth_test.go index 1b3ac10afc4..e1f7f921c97 100644 --- a/core/services/keystore/eth_test.go +++ b/core/services/keystore/eth_test.go @@ -51,7 +51,7 @@ func Test_EthKeyStore(t *testing.T) { require.NoError(t, err) retrievedKeys, err := ethKeyStore.GetAll(ctx) require.NoError(t, err) - require.Equal(t, 1, len(retrievedKeys)) + require.Len(t, retrievedKeys, 1) require.Equal(t, key.Address, retrievedKeys[0].Address) foundKey, err := ethKeyStore.Get(ctx, key.Address.Hex()) require.NoError(t, err) @@ -67,14 +67,14 @@ func Test_EthKeyStore(t *testing.T) { require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) retrievedKeys, err = ethKeyStore.GetAll(ctx) require.NoError(t, err) - require.Equal(t, 1, len(retrievedKeys)) + require.Len(t, retrievedKeys, 1) require.Equal(t, key.Address, retrievedKeys[0].Address) // adds 2nd key _, err = ethKeyStore.Create(ctx, &cltest.FixtureChainID) require.NoError(t, err) retrievedKeys, err = ethKeyStore.GetAll(ctx) require.NoError(t, err) - require.Equal(t, 2, len(retrievedKeys)) + require.Len(t, retrievedKeys, 2) }) t.Run("GetAll ordering", func(t *testing.T) { @@ -88,7 +88,7 @@ func Test_EthKeyStore(t *testing.T) { } retrievedKeys, err := ethKeyStore.GetAll(ctx) require.NoError(t, err) - require.Equal(t, 5, len(retrievedKeys)) + require.Len(t, retrievedKeys, 5) sort.Slice(keys, func(i, j int) bool { return keys[i].Cmp(keys[j]) < 0 }) @@ -104,7 +104,7 @@ func Test_EthKeyStore(t *testing.T) { require.NoError(t, err) retrievedKeys, err := ethKeyStore.GetAll(ctx) require.NoError(t, err) - require.Equal(t, 0, len(retrievedKeys)) + require.Empty(t, retrievedKeys) cltest.AssertCount(t, db, statesTableName, 0) }) @@ -124,7 +124,7 @@ func Test_EthKeyStore(t *testing.T) { require.NoError(t, err) retrievedKeys, err := ethKeyStore.GetAll(ctx) require.NoError(t, err) - require.Equal(t, 0, len(retrievedKeys)) + require.Empty(t, retrievedKeys) cltest.AssertCount(t, db, statesTableName, 0) }) @@ -136,7 +136,7 @@ func Test_EthKeyStore(t *testing.T) { sendingKeys1, err := ethKeyStore.EnabledKeysForChain(ctx, testutils.FixtureChainID) assert.NoError(t, err) - require.Equal(t, 1, len(sendingKeys1)) + require.Len(t, sendingKeys1, 1) cltest.AssertCount(t, db, statesTableName, 1) err = ethKeyStore.EnsureKeys(ctx, &cltest.FixtureChainID) @@ -144,7 +144,7 @@ func Test_EthKeyStore(t *testing.T) { sendingKeys2, err := ethKeyStore.EnabledKeysForChain(ctx, testutils.FixtureChainID) assert.NoError(t, err) - require.Equal(t, 1, len(sendingKeys2)) + require.Len(t, sendingKeys2, 1) require.Equal(t, sendingKeys1, sendingKeys2) }) @@ -206,7 +206,7 @@ func Test_EthKeyStore(t *testing.T) { enabledAddresses, err = ethKeyStore.EnabledAddressesForChain(ctx, testutils.FixtureChainID) require.NoError(t, err) - assert.Len(t, enabledAddresses, 0) + assert.Empty(t, enabledAddresses) enabledAddresses, err = ethKeyStore.EnabledAddressesForChain(ctx, big.NewInt(1337)) require.NoError(t, err) assert.Len(t, enabledAddresses, 1) @@ -406,7 +406,7 @@ func Test_EthKeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll(ctx) require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -453,12 +453,12 @@ func Test_EthKeyStore_E2E(t *testing.T) { ks.XXXTestingOnlyAdd(ctx, newKey) keys, err := ks.GetAll(ctx) require.NoError(t, err) - assert.Equal(t, 1, len(keys)) + assert.Len(t, keys, 1) _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) keys, err = ks.GetAll(ctx) require.NoError(t, err) - assert.Equal(t, 0, len(keys)) + assert.Empty(t, keys) _, err = ks.Get(ctx, newKey.ID()) assert.Error(t, err) _, err = ks.Delete(ctx, newKey.ID()) @@ -510,7 +510,7 @@ func Test_EthKeyStore_E2E(t *testing.T) { chainStates, err = ks.GetStatesForChain(ctx, testutils.SimulatedChainID) require.NoError(t, err) - assert.Len(t, chainStates, 0) + assert.Empty(t, chainStates) }) }) } @@ -536,7 +536,7 @@ func Test_EthKeyStore_SubscribeToKeyChanges(t *testing.T) { func() bool { return count.Load() >= expected }, 10*time.Second, 100*time.Millisecond, - fmt.Sprintf("insufficient number of callbacks triggered. Expected %d, got %d", expected, count.Load()), + "insufficient number of callbacks triggered. Expected %d, got %d", expected, count.Load(), ) } @@ -601,7 +601,7 @@ func Test_EthKeyStore_Enable(t *testing.T) { require.NoError(t, ks.Enable(ctx, k.Address, testutils.SimulatedChainID)) key, err := ks.GetState(ctx, k.Address.Hex(), testutils.SimulatedChainID) require.NoError(t, err) - require.Equal(t, key.Disabled, false) + require.False(t, key.Disabled) }) t.Run("creates key, deletes it unsafely and then enable creates it again", func(t *testing.T) { @@ -613,7 +613,7 @@ func Test_EthKeyStore_Enable(t *testing.T) { require.NoError(t, ks.Enable(ctx, k.Address, testutils.SimulatedChainID)) key, err := ks.GetState(ctx, k.Address.Hex(), testutils.SimulatedChainID) require.NoError(t, err) - require.Equal(t, key.Disabled, false) + require.False(t, key.Disabled) }) t.Run("creates key and enables it if it exists in the keystore, but is missing from key states db table", func(t *testing.T) { @@ -622,7 +622,7 @@ func Test_EthKeyStore_Enable(t *testing.T) { require.NoError(t, ks.Enable(ctx, k.Address, testutils.SimulatedChainID)) key, err := ks.GetState(ctx, k.Address.Hex(), testutils.SimulatedChainID) require.NoError(t, err) - require.Equal(t, key.Disabled, false) + require.False(t, key.Disabled) }) t.Run("errors if key is not present in keystore", func(t *testing.T) { @@ -745,10 +745,10 @@ func Test_EthKeyStore_Delete(t *testing.T) { assert.Len(t, keys, 2) _, err = ks.GetState(ctx, addr1.Hex(), testutils.FixtureChainID) require.Error(t, err) - assert.Contains(t, err.Error(), fmt.Sprintf("state not found for eth key ID %s", addr1.Hex())) + assert.Contains(t, err.Error(), "state not found for eth key ID "+addr1.Hex()) _, err = ks.GetState(ctx, addr1.Hex(), testutils.SimulatedChainID) require.Error(t, err) - assert.Contains(t, err.Error(), fmt.Sprintf("state not found for eth key ID %s", addr1.Hex())) + assert.Contains(t, err.Error(), "state not found for eth key ID "+addr1.Hex()) _, err = ks.GetState(ctx, addr2.Hex(), testutils.FixtureChainID) require.NoError(t, err) } @@ -824,7 +824,7 @@ func Test_EthKeyStore_CheckEnabled(t *testing.T) { addr := utils.RandomAddress() err := ks.CheckEnabled(ctx, addr, testutils.FixtureChainID) assert.Error(t, err) - require.Contains(t, err.Error(), fmt.Sprintf("no eth key exists with address %s", addr.Hex())) + require.Contains(t, err.Error(), "no eth key exists with address "+addr.Hex()) }) t.Run("returns error when key exists but has never been enabled (no state) for the given chain", func(t *testing.T) { @@ -856,7 +856,7 @@ func Test_EthKeyStore_Disable(t *testing.T) { require.NoError(t, ks.Disable(ctx, k.Address, testutils.SimulatedChainID)) key, err := ks.GetState(ctx, k.Address.Hex(), testutils.SimulatedChainID) require.NoError(t, err) - require.Equal(t, key.Disabled, true) + require.True(t, key.Disabled) }) t.Run("creates key and enables it if it exists in the keystore, but is missing from key states db table", func(t *testing.T) { @@ -865,7 +865,7 @@ func Test_EthKeyStore_Disable(t *testing.T) { require.NoError(t, ks.Disable(ctx, k.Address, testutils.SimulatedChainID)) key, err := ks.GetState(ctx, k.Address.Hex(), testutils.SimulatedChainID) require.NoError(t, err) - require.Equal(t, key.Disabled, true) + require.True(t, key.Disabled) }) t.Run("errors if key is not present in keystore", func(t *testing.T) { diff --git a/core/services/keystore/keys/aptoskey/key_test.go b/core/services/keystore/keys/aptoskey/key_test.go index 277a30eb9f3..6df73d84e8f 100644 --- a/core/services/keystore/keys/aptoskey/key_test.go +++ b/core/services/keystore/keys/aptoskey/key_test.go @@ -12,6 +12,6 @@ func TestAptosKey(t *testing.T) { bytes, err := hex.DecodeString("f0d07ab448018b2754475f9a3b580218b0675a1456aad96ad607c7bbd7d9237b") require.NoError(t, err) k := Raw(bytes).Key() - assert.Equal(t, k.PublicKeyStr(), "2acd605efc181e2af8a0b8c0686a5e12578efa1253d15a235fa5e5ad970c4b29") - assert.Equal(t, k.Account(), "69d8b07f5945185873c622ea66873b0e1fb921de7b94d904d3ef9be80770682e") + assert.Equal(t, "2acd605efc181e2af8a0b8c0686a5e12578efa1253d15a235fa5e5ad970c4b29", k.PublicKeyStr()) + assert.Equal(t, "69d8b07f5945185873c622ea66873b0e1fb921de7b94d904d3ef9be80770682e", k.Account()) } diff --git a/core/services/keystore/keys/ocr2key/offchain_keyring_test.go b/core/services/keystore/keys/ocr2key/offchain_keyring_test.go index c64850fab21..0f6e4fac4d5 100644 --- a/core/services/keystore/keys/ocr2key/offchain_keyring_test.go +++ b/core/services/keystore/keys/ocr2key/offchain_keyring_test.go @@ -42,7 +42,7 @@ func TestOffchainKeyring_NaclBoxSealAnonymous_ShortCiphertext(t *testing.T) { shortMessage := []byte("short") _, err = kr.NaclBoxOpenAnonymous(shortMessage) - assert.Equal(t, err.Error(), "ciphertext too short") + assert.Equal(t, "ciphertext too short", err.Error()) } func TestOffchainKeyring_NaclBoxSealAnonymous_FailedDecryption(t *testing.T) { @@ -52,7 +52,7 @@ func TestOffchainKeyring_NaclBoxSealAnonymous_FailedDecryption(t *testing.T) { invalid := []byte("invalidEncryptedMessage") _, err = kr.NaclBoxOpenAnonymous(invalid) - assert.Equal(t, err.Error(), "decryption failed") + assert.Equal(t, "decryption failed", err.Error()) } func naclBoxSealAnonymous(t *testing.T, peerPublicKey [curve25519.PointSize]byte, plaintext []byte) []byte { diff --git a/core/services/keystore/keys/ocrkey/off_chain_public_key_test.go b/core/services/keystore/keys/ocrkey/off_chain_public_key_test.go index fedc526befb..372ca8b273b 100644 --- a/core/services/keystore/keys/ocrkey/off_chain_public_key_test.go +++ b/core/services/keystore/keys/ocrkey/off_chain_public_key_test.go @@ -21,7 +21,7 @@ func TestOCR_OffchainPublicKey_MarshalJSON(t *testing.T) { result, err := json.Marshal(pubKey) assert.NoError(t, err) - assert.Equal(t, pubKeyJSON, string(result)) + assert.JSONEq(t, pubKeyJSON, string(result)) } func TestOCR_OffchainPublicKey_UnmarshalJSON_Happy(t *testing.T) { diff --git a/core/services/keystore/keys/starkkey/ocr2key_test.go b/core/services/keystore/keys/starkkey/ocr2key_test.go index 69436e5ce7f..81ab3bba185 100644 --- a/core/services/keystore/keys/starkkey/ocr2key_test.go +++ b/core/services/keystore/keys/starkkey/ocr2key_test.go @@ -179,7 +179,7 @@ func TestStarknetKeyring_Marshal(t *testing.T) { kr2 := OCR2Key{} err = kr2.Unmarshal(m) require.NoError(t, err) - assert.True(t, kr1.priv.Cmp(kr2.priv) == 0) + assert.Equal(t, kr1.priv.Cmp(kr2.priv), 0) // Invalid seed size should error require.Error(t, kr2.Unmarshal([]byte{0x01})) diff --git a/core/services/keystore/keys/starkkey/utils.go b/core/services/keystore/keys/starkkey/utils.go index d8706ba9dbc..9d0de7567a9 100644 --- a/core/services/keystore/keys/starkkey/utils.go +++ b/core/services/keystore/keys/starkkey/utils.go @@ -2,11 +2,11 @@ package starkkey import ( "crypto/rand" - "fmt" "io" "math/big" "github.com/NethermindEth/starknet.go/curve" + "github.com/pkg/errors" ) // constants @@ -32,7 +32,7 @@ func GenerateKey(material io.Reader) (k Key, err error) { } if !curve.Curve.IsOnCurve(k.pub.X, k.pub.Y) { - return k, fmt.Errorf("key gen is not on stark curve") + return k, errors.New("key gen is not on stark curve") } return k, nil diff --git a/core/services/keystore/keys/vrfkey/crypto.go b/core/services/keystore/keys/vrfkey/crypto.go index fe105d13f11..b91c1228cc0 100644 --- a/core/services/keystore/keys/vrfkey/crypto.go +++ b/core/services/keystore/keys/vrfkey/crypto.go @@ -1,6 +1,7 @@ package vrfkey import ( + "errors" "fmt" "math/big" @@ -27,7 +28,7 @@ var ( Generator = Secp256k1Curve.Point().Base() eulersCriterionPower = bm.Div(bm.Sub(FieldSize, bm.One), bm.Two) sqrtPower = bm.Div(bm.Add(FieldSize, bm.One), bm.Four) - ErrCGammaEqualsSHash = fmt.Errorf("pick a different nonce; c*gamma = s*hash, with this one") + ErrCGammaEqualsSHash = errors.New("pick a different nonce; c*gamma = s*hash, with this one") // hashToCurveHashPrefix is domain-separation tag for initial HashToCurve hash. // Corresponds to HASH_TO_CURVE_HASH_PREFIX in VRF.sol. hashToCurveHashPrefix = common.BigToHash(bm.One).Bytes() @@ -144,7 +145,7 @@ func checkCGammaNotEqualToSHash(c *big.Int, gamma kyber.Point, s *big.Int, func HashToCurve(p kyber.Point, input *big.Int, ordinates func(x *big.Int), ) (kyber.Point, error) { if !(secp256k1.ValidPublicKey(p) && input.BitLen() <= 256 && input.Cmp(bm.Zero) >= 0) { - return nil, fmt.Errorf("bad input to vrf.HashToCurve") + return nil, errors.New("bad input to vrf.HashToCurve") } x := FieldHash(append(hashToCurveHashPrefix, append(secp256k1.LongMarshal(p), utils.Uint256ToBytes32(input)...)...)) diff --git a/core/services/keystore/keys/vrfkey/key_v2.go b/core/services/keystore/keys/vrfkey/key_v2.go index 786bd39b3f0..00331f8195b 100644 --- a/core/services/keystore/keys/vrfkey/key_v2.go +++ b/core/services/keystore/keys/vrfkey/key_v2.go @@ -72,7 +72,7 @@ func (key KeyV2) Raw() Raw { func (key KeyV2) GenerateProofWithNonce(seed, nonce *big.Int) (Proof, error) { secretKey := secp256k1.ScalarToHash(*key.k).Big() if !(secp256k1.RepresentsScalar(secretKey) && seed.BitLen() <= 256) { - return Proof{}, fmt.Errorf("badly-formatted key or seed") + return Proof{}, errors.New("badly-formatted key or seed") } skAsScalar := secp256k1.IntToScalar(secretKey) publicKey := Secp256k1Curve.Point().Mul(skAsScalar, nil) @@ -152,7 +152,7 @@ func keyFromScalar(k kyber.Scalar) (KeyV2, error) { } var publicKey secp256k1.PublicKey if l := copy(publicKey[:], rawPublicKey); l != secp256k1.CompressedPublicKeyLength { - panic(fmt.Errorf("failed to copy correct length in serialized public key")) + panic(errors.New("failed to copy correct length in serialized public key")) } return KeyV2{ k: &k, diff --git a/core/services/keystore/keys/vrfkey/proof.go b/core/services/keystore/keys/vrfkey/proof.go index b7f9032255b..d97fc06723e 100644 --- a/core/services/keystore/keys/vrfkey/proof.go +++ b/core/services/keystore/keys/vrfkey/proof.go @@ -1,6 +1,7 @@ package vrfkey import ( + "errors" "fmt" "math/big" @@ -43,7 +44,7 @@ func (p *Proof) WellFormed() bool { // given publicKey and seed, and no error was encountered func (p *Proof) VerifyVRFProof() (bool, error) { if !p.WellFormed() { - return false, fmt.Errorf("badly-formatted proof") + return false, errors.New("badly-formatted proof") } h, err := HashToCurve(p.PublicKey, p.Seed, func(*big.Int) {}) if err != nil { @@ -51,7 +52,7 @@ func (p *Proof) VerifyVRFProof() (bool, error) { } err = checkCGammaNotEqualToSHash(p.C, p.Gamma, p.S, h) if err != nil { - return false, fmt.Errorf("c*γ = s*hash (disallowed in solidity verifier)") + return false, errors.New("c*γ = s*hash (disallowed in solidity verifier)") } // publicKey = secretKey*Generator. See GenerateProof for u, v, m, s // c*secretKey*Generator + (m - c*secretKey)*Generator = m*Generator = u diff --git a/core/services/keystore/master_test.go b/core/services/keystore/master_test.go index e41a7a771ae..7902ef75b5e 100644 --- a/core/services/keystore/master_test.go +++ b/core/services/keystore/master_test.go @@ -1,7 +1,6 @@ package keystore_test import ( - "fmt" "testing" "github.com/stretchr/testify/require" @@ -21,7 +20,7 @@ func TestMasterKeystore_Unlock_Save(t *testing.T) { const tableName = "encrypted_key_rings" reset := func() { keyStore.ResetXXXTestOnly() - _, err := db.Exec(fmt.Sprintf("DELETE FROM %s", tableName)) + _, err := db.Exec("DELETE FROM " + tableName) require.NoError(t, err) } diff --git a/core/services/keystore/models_test.go b/core/services/keystore/models_test.go index a828fbbf4f6..53b5e08554e 100644 --- a/core/services/keystore/models_test.go +++ b/core/services/keystore/models_test.go @@ -59,19 +59,19 @@ func TestKeyRing_Encrypt_Decrypt(t *testing.T) { decryptedKeyRing, err := encryptedKr.Decrypt(password) require.NoError(t, err) // compare cosmos keys - require.Equal(t, 2, len(decryptedKeyRing.Cosmos)) + require.Len(t, decryptedKeyRing.Cosmos, 2) require.Equal(t, originalKeyRing.Cosmos[tk1.ID()].PublicKey(), decryptedKeyRing.Cosmos[tk1.ID()].PublicKey()) require.Equal(t, originalKeyRing.Cosmos[tk2.ID()].PublicKey(), decryptedKeyRing.Cosmos[tk2.ID()].PublicKey()) // compare csa keys - require.Equal(t, 2, len(decryptedKeyRing.CSA)) + require.Len(t, decryptedKeyRing.CSA, 2) require.Equal(t, originalKeyRing.CSA[csa1.ID()].PublicKey, decryptedKeyRing.CSA[csa1.ID()].PublicKey) require.Equal(t, originalKeyRing.CSA[csa2.ID()].PublicKey, decryptedKeyRing.CSA[csa2.ID()].PublicKey) // compare eth keys - require.Equal(t, 2, len(decryptedKeyRing.Eth)) + require.Len(t, decryptedKeyRing.Eth, 2) require.Equal(t, originalKeyRing.Eth[eth1.ID()].Address, decryptedKeyRing.Eth[eth1.ID()].Address) require.Equal(t, originalKeyRing.Eth[eth2.ID()].Address, decryptedKeyRing.Eth[eth2.ID()].Address) // compare ocr keys - require.Equal(t, 2, len(decryptedKeyRing.OCR)) + require.Len(t, decryptedKeyRing.OCR, 2) require.Equal(t, originalKeyRing.OCR[ocr[0].ID()].OnChainSigning.X, decryptedKeyRing.OCR[ocr[0].ID()].OnChainSigning.X) require.Equal(t, originalKeyRing.OCR[ocr[0].ID()].OnChainSigning.Y, decryptedKeyRing.OCR[ocr[0].ID()].OnChainSigning.Y) require.Equal(t, originalKeyRing.OCR[ocr[0].ID()].OnChainSigning.D, decryptedKeyRing.OCR[ocr[0].ID()].OnChainSigning.D) @@ -91,16 +91,16 @@ func TestKeyRing_Encrypt_Decrypt(t *testing.T) { require.Equal(t, originalKeyRing.OCR2[id].ChainType(), decryptedKeyRing.OCR2[id].ChainType()) } // compare p2p keys - require.Equal(t, 2, len(decryptedKeyRing.P2P)) + require.Len(t, decryptedKeyRing.P2P, 2) require.Equal(t, originalKeyRing.P2P[p2p1.ID()].PublicKeyHex(), decryptedKeyRing.P2P[p2p1.ID()].PublicKeyHex()) require.Equal(t, originalKeyRing.P2P[p2p1.ID()].PeerID(), decryptedKeyRing.P2P[p2p1.ID()].PeerID()) require.Equal(t, originalKeyRing.P2P[p2p2.ID()].PublicKeyHex(), decryptedKeyRing.P2P[p2p2.ID()].PublicKeyHex()) require.Equal(t, originalKeyRing.P2P[p2p2.ID()].PeerID(), decryptedKeyRing.P2P[p2p2.ID()].PeerID()) // compare solana keys - require.Equal(t, 2, len(decryptedKeyRing.Solana)) + require.Len(t, decryptedKeyRing.Solana, 2) require.Equal(t, originalKeyRing.Solana[sol1.ID()].GetPublic(), decryptedKeyRing.Solana[sol1.ID()].GetPublic()) // compare vrf keys - require.Equal(t, 2, len(decryptedKeyRing.VRF)) + require.Len(t, decryptedKeyRing.VRF, 2) require.Equal(t, originalKeyRing.VRF[vrf1.ID()].PublicKey, decryptedKeyRing.VRF[vrf1.ID()].PublicKey) require.Equal(t, originalKeyRing.VRF[vrf2.ID()].PublicKey, decryptedKeyRing.VRF[vrf2.ID()].PublicKey) }) @@ -131,7 +131,7 @@ func TestKeyRing_Encrypt_Decrypt(t *testing.T) { newRawJson, _ := json.Marshal(allKeys) err = originalKeyRing.LegacyKeys.StoreUnsupported(newRawJson, originalKeyRing) require.NoError(t, err) - require.Equal(t, originalKeyRing.LegacyKeys.legacyRawKeys.len(), 6) + require.Equal(t, 6, originalKeyRing.LegacyKeys.legacyRawKeys.len()) marshalledRawKeyRingJson, err := json.Marshal(originalKeyRing.raw()) require.NoError(t, err) unloadedKeysJson, err := originalKeyRing.LegacyKeys.UnloadUnsupported(marshalledRawKeyRingJson) @@ -141,7 +141,7 @@ func TestKeyRing_Encrypt_Decrypt(t *testing.T) { require.NoError(t, err) // Check if keys where added to the raw json - require.Equal(t, shouldHaveAllKeys["foo"], []string{"bar", "biz"}) + require.Equal(t, []string{"bar", "biz"}, shouldHaveAllKeys["foo"]) require.Contains(t, shouldHaveAllKeys["OCR2"], newOCR2Key1.Raw().String()) require.Contains(t, shouldHaveAllKeys["OCR2"], newOCR2Key2.Raw().String()) require.Contains(t, shouldHaveAllKeys["P2P"], newP2PKey1.Raw().String()) diff --git a/core/services/keystore/ocr2_test.go b/core/services/keystore/ocr2_test.go index 7288b86d1d1..8f7995860ed 100644 --- a/core/services/keystore/ocr2_test.go +++ b/core/services/keystore/ocr2_test.go @@ -33,7 +33,7 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -64,7 +64,7 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { // validate no keys exist for chain keys, err := ks.GetAllOfType(chain) require.NoError(t, err) - require.Len(t, keys, 0) + require.Empty(t, keys) _, err = ks.Create(ctx, chain) require.NoError(t, err) @@ -78,7 +78,7 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { require.Len(t, keys, 1) continue } - require.Len(t, keys, 0) + require.Empty(t, keys) } } }) @@ -128,14 +128,14 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) err = ks.Delete(ctx, newKey.ID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) _, err = ks.Get(newKey.ID()) require.Error(t, err) } @@ -158,7 +158,7 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { for _, chain := range chaintype.SupportedChainTypes { keys, err := ks.GetAllOfType(chain) assert.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) } }) @@ -170,31 +170,31 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { keys, err := ks.GetAll() assert.NoError(t, err) - require.Equal(t, 1, len(keys)) - require.Equal(t, keys[0].ChainType(), chaintype.EVM) + require.Len(t, keys, 1) + require.Equal(t, chaintype.EVM, keys[0].ChainType()) err = ks.EnsureKeys(ctx, chaintype.Cosmos) assert.NoError(t, err) keys, err = ks.GetAll() assert.NoError(t, err) - require.Equal(t, 2, len(keys)) + require.Len(t, keys, 2) cosmosKeys, err := ks.GetAllOfType(chaintype.Cosmos) assert.NoError(t, err) - require.Equal(t, 1, len(cosmosKeys)) - require.Equal(t, cosmosKeys[0].ChainType(), chaintype.Cosmos) + require.Len(t, cosmosKeys, 1) + require.Equal(t, chaintype.Cosmos, cosmosKeys[0].ChainType()) err = ks.EnsureKeys(ctx, chaintype.StarkNet) assert.NoError(t, err) keys, err = ks.GetAll() assert.NoError(t, err) - require.Equal(t, 3, len(keys)) + require.Len(t, keys, 3) straknetKeys, err := ks.GetAllOfType(chaintype.StarkNet) assert.NoError(t, err) - require.Equal(t, 1, len(straknetKeys)) - require.Equal(t, straknetKeys[0].ChainType(), chaintype.StarkNet) + require.Len(t, straknetKeys, 1) + require.Equal(t, chaintype.StarkNet, straknetKeys[0].ChainType()) }) } diff --git a/core/services/keystore/ocr_test.go b/core/services/keystore/ocr_test.go index b7a7b127f21..f3ad841c8d0 100644 --- a/core/services/keystore/ocr_test.go +++ b/core/services/keystore/ocr_test.go @@ -31,7 +31,7 @@ func Test_OCRKeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -86,14 +86,14 @@ func Test_OCRKeyStore_E2E(t *testing.T) { assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) - assert.Equal(t, 1, len(keys)) + assert.Len(t, keys, 1) _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) _, err = ks.Delete(ctx, newKey.ID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) - assert.Equal(t, 0, len(keys)) + assert.Empty(t, keys) _, err = ks.Get(newKey.ID()) assert.Error(t, err) }) @@ -107,7 +107,7 @@ func Test_OCRKeyStore_E2E(t *testing.T) { require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) }) t.Run("imports a key exported from a v1 keystore", func(t *testing.T) { diff --git a/core/services/keystore/p2p_test.go b/core/services/keystore/p2p_test.go index d18179d1f80..02745c5154d 100644 --- a/core/services/keystore/p2p_test.go +++ b/core/services/keystore/p2p_test.go @@ -35,7 +35,7 @@ func Test_P2PKeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -96,14 +96,14 @@ func Test_P2PKeyStore_E2E(t *testing.T) { assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) _, err = ks.Delete(ctx, newKey.PeerID()) require.NoError(t, err) _, err = ks.Delete(ctx, newKey.PeerID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) _, err = ks.Get(newKey.PeerID()) require.Error(t, err) }) @@ -116,14 +116,14 @@ func Test_P2PKeyStore_E2E(t *testing.T) { keys, err := ks.GetAll() assert.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) err = ks.EnsureKey(ctx) assert.NoError(t, err) keys, err = ks.GetAll() assert.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) }) t.Run("GetOrFirst", func(t *testing.T) { diff --git a/core/services/keystore/solana_test.go b/core/services/keystore/solana_test.go index 7355404d093..f4a5714aa44 100644 --- a/core/services/keystore/solana_test.go +++ b/core/services/keystore/solana_test.go @@ -32,7 +32,7 @@ func Test_SolanaKeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -87,14 +87,14 @@ func Test_SolanaKeyStore_E2E(t *testing.T) { assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) _, err = ks.Delete(ctx, newKey.ID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) _, err = ks.Get(newKey.ID()) require.Error(t, err) }) @@ -110,7 +110,7 @@ func Test_SolanaKeyStore_E2E(t *testing.T) { keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) }) t.Run("sign tx", func(t *testing.T) { diff --git a/core/services/keystore/starknet.go b/core/services/keystore/starknet.go index 1aa213b86e9..5ef822407d4 100644 --- a/core/services/keystore/starknet.go +++ b/core/services/keystore/starknet.go @@ -191,5 +191,5 @@ func (lk *StarknetLooppSigner) Sign(ctx context.Context, id string, hash []byte) // TODO what is this supposed to return for starknet? func (lk *StarknetLooppSigner) Accounts(ctx context.Context) ([]string, error) { - return nil, fmt.Errorf("unimplemented") + return nil, errors.New("unimplemented") } diff --git a/core/services/keystore/starknet_test.go b/core/services/keystore/starknet_test.go index aa610124531..ff4f91e050c 100644 --- a/core/services/keystore/starknet_test.go +++ b/core/services/keystore/starknet_test.go @@ -2,10 +2,10 @@ package keystore_test import ( "context" - "fmt" "math/big" "testing" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -40,7 +40,7 @@ func Test_StarkNetKeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -87,12 +87,12 @@ func Test_StarkNetKeyStore_E2E(t *testing.T) { require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) keys, err = ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) _, err = ks.Get(newKey.ID()) require.Error(t, err) }) @@ -108,7 +108,7 @@ func Test_StarkNetKeyStore_E2E(t *testing.T) { keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) }) } @@ -130,7 +130,7 @@ func TestStarknetSigner(t *testing.T) { require.NoError(t, err) }) t.Run("key doesn't exists", func(t *testing.T) { - baseKs.On("Get", mock.Anything).Return(starkkey.Key{}, fmt.Errorf("key doesn't exist")) + baseKs.On("Get", mock.Anything).Return(starkkey.Key{}, errors.New("key doesn't exist")) signed, err := lk.Sign(testutils.Context(t), "not an address", nil) require.Nil(t, signed) require.Error(t, err) diff --git a/core/services/keystore/vrf_test.go b/core/services/keystore/vrf_test.go index 4b77377d5e8..3df9101492f 100644 --- a/core/services/keystore/vrf_test.go +++ b/core/services/keystore/vrf_test.go @@ -34,7 +34,7 @@ func Test_VRFKeyStore_E2E(t *testing.T) { defer reset() keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) }) t.Run("errors when getting non-existent ID", func(t *testing.T) { @@ -81,12 +81,12 @@ func Test_VRFKeyStore_E2E(t *testing.T) { require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) - require.Equal(t, 1, len(keys)) + require.Len(t, keys, 1) _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) keys, err = ks.GetAll() require.NoError(t, err) - require.Equal(t, 0, len(keys)) + require.Empty(t, keys) _, err = ks.Get(newKey.ID()) require.Error(t, err) }) diff --git a/core/services/llo/cleanup_test.go b/core/services/llo/cleanup_test.go index 9f00c09d8b3..477749fb143 100644 --- a/core/services/llo/cleanup_test.go +++ b/core/services/llo/cleanup_test.go @@ -87,10 +87,10 @@ func Test_Cleanup(t *testing.T) { t.Run("removes transmissions", func(t *testing.T) { trs, err := torm1.Get(ctx, srvURL1) require.NoError(t, err) - assert.Len(t, trs, 0) + assert.Empty(t, trs) trs, err = torm1.Get(ctx, srvURL2) require.NoError(t, err) - assert.Len(t, trs, 0) + assert.Empty(t, trs) trs, err = torm2.Get(ctx, srvURL1) require.NoError(t, err) diff --git a/core/services/llo/data_source.go b/core/services/llo/data_source.go index 2afe9e090a3..121a3f7cdd6 100644 --- a/core/services/llo/data_source.go +++ b/core/services/llo/data_source.go @@ -5,6 +5,7 @@ import ( "fmt" "slices" "sort" + "strconv" "sync" "time" @@ -120,7 +121,7 @@ func (d *dataSource) Observe(ctx context.Context, streamValues llo.StreamValues, mu.Lock() errs = append(errs, ErrObservationFailed{streamID: streamID, reason: fmt.Sprintf("missing stream: %d", streamID)}) mu.Unlock() - promMissingStreamCount.WithLabelValues(fmt.Sprintf("%d", streamID)).Inc() + promMissingStreamCount.WithLabelValues(strconv.FormatUint(uint64(streamID), 10)).Inc() return } run, trrs, err := stream.Run(ctx) @@ -128,7 +129,7 @@ func (d *dataSource) Observe(ctx context.Context, streamValues llo.StreamValues, mu.Lock() errs = append(errs, ErrObservationFailed{inner: err, run: run, streamID: streamID, reason: "pipeline run failed"}) mu.Unlock() - promObservationErrorCount.WithLabelValues(fmt.Sprintf("%d", streamID)).Inc() + promObservationErrorCount.WithLabelValues(strconv.FormatUint(uint64(streamID), 10)).Inc() // TODO: Consolidate/reduce telemetry. We should send all observation results in a single packet // https://smartcontract-it.atlassian.net/browse/MERC-6290 d.t.EnqueueV3PremiumLegacy(run, trrs, streamID, opts, nil, err) diff --git a/core/services/llo/data_source_test.go b/core/services/llo/data_source_test.go index 932c4c0c73a..651758e341c 100644 --- a/core/services/llo/data_source_test.go +++ b/core/services/llo/data_source_test.go @@ -164,7 +164,7 @@ func Test_DataSource(t *testing.T) { assert.Equal(t, 1, int(pkt.streamID)) assert.Equal(t, opts, pkt.opts) assert.Equal(t, "2181", pkt.val.(*llo.Decimal).String()) - assert.Nil(t, pkt.err) + assert.NoError(t, pkt.err) }) }) } diff --git a/core/services/llo/delegate.go b/core/services/llo/delegate.go index 0c7d539427e..0946cca67b6 100644 --- a/core/services/llo/delegate.go +++ b/core/services/llo/delegate.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "strconv" "github.com/prometheus/client_golang/prometheus" ocrcommontypes "github.com/smartcontractkit/libocr/commontypes" @@ -128,7 +129,7 @@ func (d *delegate) Start(ctx context.Context) error { psrrc := NewPluginScopedRetirementReportCache(d.cfg.RetirementReportCache, d.cfg.OnchainKeyring, d.cfg.RetirementReportCodec) for i, configTracker := range d.cfg.ContractConfigTrackers { - lggr := logger.Named(d.cfg.Logger, fmt.Sprintf("%d", i)) + lggr := logger.Named(d.cfg.Logger, strconv.Itoa(i)) switch i { case 0: lggr = logger.With(lggr, "instanceType", "Blue") diff --git a/core/services/llo/mercurytransmitter/orm_test.go b/core/services/llo/mercurytransmitter/orm_test.go index 73d5760a9a3..2f169ccdc7d 100644 --- a/core/services/llo/mercurytransmitter/orm_test.go +++ b/core/services/llo/mercurytransmitter/orm_test.go @@ -59,7 +59,7 @@ func TestORM(t *testing.T) { result, err = orm.Get(ctx, sURL) require.NoError(t, err) - require.Len(t, result, 0) + require.Empty(t, result) }) t.Run("Prune", func(t *testing.T) { err := orm.Insert(ctx, transmissions) @@ -84,6 +84,6 @@ func TestORM(t *testing.T) { require.NoError(t, err) result, err = orm.Get(ctx, sURL) require.NoError(t, err) - require.Len(t, result, 0) + require.Empty(t, result) }) } diff --git a/core/services/llo/mercurytransmitter/persistence_manager_test.go b/core/services/llo/mercurytransmitter/persistence_manager_test.go index b05de429ade..6978faf2d60 100644 --- a/core/services/llo/mercurytransmitter/persistence_manager_test.go +++ b/core/services/llo/mercurytransmitter/persistence_manager_test.go @@ -47,7 +47,7 @@ func TestPersistenceManager(t *testing.T) { result, err = pm2.Load(ctx) require.NoError(t, err) - assert.Len(t, result, 0) + assert.Empty(t, result) }) } diff --git a/core/services/llo/mercurytransmitter/queue_test.go b/core/services/llo/mercurytransmitter/queue_test.go index d19d140d6be..2bcc28e4980 100644 --- a/core/services/llo/mercurytransmitter/queue_test.go +++ b/core/services/llo/mercurytransmitter/queue_test.go @@ -40,13 +40,13 @@ func Test_Queue(t *testing.T) { require.True(t, ok) } report := transmitQueue.HealthReport() - assert.Nil(t, report[transmitQueue.Name()]) + assert.NoError(t, report[transmitQueue.Name()]) }) t.Run("transmit queue is more than 50% full", func(t *testing.T) { transmitQueue.Push(testTransmissions[2]) report := transmitQueue.HealthReport() - assert.Equal(t, report[transmitQueue.Name()].Error(), "transmit priority queue is greater than 50% full (4/7)") + assert.Equal(t, "transmit priority queue is greater than 50% full (4/7)", report[transmitQueue.Name()].Error()) }) t.Run("transmit queue pops the highest priority transmission", func(t *testing.T) { diff --git a/core/services/llo/mercurytransmitter/server.go b/core/services/llo/mercurytransmitter/server.go index 3ce2b0a4b4a..11fb9296ad2 100644 --- a/core/services/llo/mercurytransmitter/server.go +++ b/core/services/llo/mercurytransmitter/server.go @@ -123,7 +123,7 @@ type QueueConfig interface { func newServer(lggr logger.Logger, verboseLogging bool, cfg QueueConfig, client wsrpc.Client, orm ORM, serverURL string) *server { pm := NewPersistenceManager(lggr, orm, serverURL, int(cfg.TransmitQueueMaxSize()), flushDeletesFrequency, pruneFrequency) - donIDStr := fmt.Sprintf("%d", pm.DonID()) + donIDStr := strconv.FormatUint(uint64(pm.DonID()), 10) var codecLggr logger.Logger if verboseLogging { codecLggr = lggr diff --git a/core/services/llo/mercurytransmitter/transmitter_test.go b/core/services/llo/mercurytransmitter/transmitter_test.go index fabc9bb0d0e..fae667c385d 100644 --- a/core/services/llo/mercurytransmitter/transmitter_test.go +++ b/core/services/llo/mercurytransmitter/transmitter_test.go @@ -75,7 +75,7 @@ func Test_Transmitter_Transmit(t *testing.T) { require.NoError(t, err) // ensure it was added to the queue - require.Equal(t, mt.servers[sURL].q.(*transmitQueue).pq.Len(), 1) + require.Equal(t, 1, mt.servers[sURL].q.(*transmitQueue).pq.Len()) assert.Equal(t, &Transmission{ ServerURL: sURL, ConfigDigest: digest, @@ -83,7 +83,7 @@ func Test_Transmitter_Transmit(t *testing.T) { Report: report, Sigs: sigs, }, mt.servers[sURL].q.(*transmitQueue).pq.Pop().(*Transmission)) - require.Equal(t, mt.servers[sURL2].q.(*transmitQueue).pq.Len(), 1) + require.Equal(t, 1, mt.servers[sURL2].q.(*transmitQueue).pq.Len()) assert.Equal(t, &Transmission{ ServerURL: sURL2, ConfigDigest: digest, @@ -91,7 +91,7 @@ func Test_Transmitter_Transmit(t *testing.T) { Report: report, Sigs: sigs, }, mt.servers[sURL2].q.(*transmitQueue).pq.Pop().(*Transmission)) - require.Equal(t, mt.servers[sURL3].q.(*transmitQueue).pq.Len(), 1) + require.Equal(t, 1, mt.servers[sURL3].q.(*transmitQueue).pq.Len()) assert.Equal(t, &Transmission{ ServerURL: sURL3, ConfigDigest: digest, diff --git a/core/services/llo/onchain_channel_definition_cache.go b/core/services/llo/onchain_channel_definition_cache.go index 461c309a73a..e56d4cf1ca5 100644 --- a/core/services/llo/onchain_channel_definition_cache.go +++ b/core/services/llo/onchain_channel_definition_cache.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "database/sql" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -121,7 +122,7 @@ type HTTPClient interface { } func filterName(addr common.Address, donID uint32) string { - return logpoller.FilterName("OCR3 LLO ChannelDefinitionCachePoller", addr.String(), fmt.Sprintf("%d", donID)) + return logpoller.FilterName("OCR3 LLO ChannelDefinitionCachePoller", addr.String(), strconv.FormatUint(uint64(donID), 10)) } func NewChannelDefinitionCache(lggr logger.Logger, orm ChannelDefinitionCacheORM, client HTTPClient, lp logpoller.LogPoller, addr common.Address, donID uint32, fromBlock int64, options ...Option) llotypes.ChannelDefinitionCache { @@ -393,7 +394,7 @@ func (c *channelDefinitionCache) fetchChannelDefinitions(ctx context.Context, ur Client: c.client, Request: request, Config: clhttp.HTTPRequestConfig{SizeLimit: c.httpLimit}, - Logger: c.lggr.Named("HTTPRequest").With("url", url, "expectedSHA", fmt.Sprintf("%x", expectedSha)), + Logger: c.lggr.Named("HTTPRequest").With("url", url, "expectedSHA", hex.EncodeToString(expectedSha[:])), } reader, statusCode, _, err := httpRequest.SendRequestReader() @@ -491,7 +492,7 @@ func (c *channelDefinitionCache) failedPersistLoop() { } case <-c.chStop: // Try one final persist with a short-ish timeout, then return - ctx, cancel = context.WithTimeout(context.Background(), 1*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() if memoryVersion, persistedVersion, err := c.persist(ctx); err != nil { c.lggr.Errorw("Failed to persist channel definitions on shutdown", "err", err, "memoryVersion", memoryVersion, "persistedVersion", persistedVersion) diff --git a/core/services/nurse_test.go b/core/services/nurse_test.go index ed6f6872dc9..be387d5e74a 100644 --- a/core/services/nurse_test.go +++ b/core/services/nurse_test.go @@ -112,7 +112,7 @@ func TestNurse(t *testing.T) { require.NoError(t, err) n, err := wc.Write([]byte("junk")) require.NoError(t, err) - require.Greater(t, n, 0) + require.Positive(t, n) require.NoError(t, wc.Close()) wc, err = nrse.createFile(time.Now(), "testgz", false) @@ -127,12 +127,12 @@ func TestNurse(t *testing.T) { testutils.AssertEventually(t, func() bool { return profileExists(t, nrse, traceProfName) }) n2, err := nrse.totalProfileBytes() require.NoError(t, err) - require.Greater(t, n2, uint64(0)) + require.Positive(t, n2) } func profileExists(t *testing.T, nrse *Nurse, typ string) bool { profiles, err := nrse.listProfiles() - require.Nil(t, err) + require.NoError(t, err) for _, p := range profiles { if strings.Contains(p.Name(), typ) { return true diff --git a/core/services/ocr/contract_tracker.go b/core/services/ocr/contract_tracker.go index 618567f0bdb..c496c1f8c13 100644 --- a/core/services/ocr/contract_tracker.go +++ b/core/services/ocr/contract_tracker.go @@ -2,7 +2,7 @@ package ocr import ( "context" - "fmt" + "strconv" "strings" "sync" "time" @@ -167,7 +167,7 @@ func (t *OCRContractTracker) Start(ctx context.Context) error { t.wg.Add(1) go t.processLogs() - t.mailMon.Monitor(t.configsMB, "OCRContractTracker", "Configs", fmt.Sprint(t.jobID)) + t.mailMon.Monitor(t.configsMB, "OCRContractTracker", "Configs", strconv.Itoa(int(t.jobID))) return nil }) @@ -455,7 +455,7 @@ func getEventTopic(name string) gethCommon.Hash { } event, exists := abi.Events[name] if !exists { - panic(fmt.Sprintf("abi.Events was missing %s", name)) + panic("abi.Events was missing " + name) } return event.ID } diff --git a/core/services/ocr/database_test.go b/core/services/ocr/database_test.go index e22b592da76..ed7ed8886c9 100644 --- a/core/services/ocr/database_test.go +++ b/core/services/ocr/database_test.go @@ -287,7 +287,7 @@ func Test_DB_PendingTransmissions(t *testing.T) { // No keys for this oracleSpecID yet m, err = odb2.PendingTransmissionsWithConfigDigest(testutils.Context(t), configDigest) require.NoError(t, err) - require.Len(t, m, 0) + require.Empty(t, m) }) t.Run("deletes pending transmission by key", func(t *testing.T) { diff --git a/core/services/ocr2/database_test.go b/core/services/ocr2/database_test.go index 7e6b492a2db..222c7db4ca1 100644 --- a/core/services/ocr2/database_test.go +++ b/core/services/ocr2/database_test.go @@ -344,7 +344,7 @@ func Test_DB_PendingTransmissions(t *testing.T) { // No keys for this oracleSpecID yet m, err = db2.PendingTransmissionsWithConfigDigest(testutils.Context(t), configDigest) require.NoError(t, err) - require.Len(t, m, 0) + require.Empty(t, m) }) t.Run("deletes pending transmission by key", func(t *testing.T) { diff --git a/core/services/ocr2/delegate.go b/core/services/ocr2/delegate.go index 13094fefb1a..ba93d2e6822 100644 --- a/core/services/ocr2/delegate.go +++ b/core/services/ocr2/delegate.go @@ -557,7 +557,7 @@ func GetEVMEffectiveTransmitterID(ctx context.Context, jb *job.Job, chain legacy // ForwardingAllowed cannot be set with Mercury, so this should always be false for mercury jobs if jb.ForwardingAllowed { if chain == nil { - return "", fmt.Errorf("job forwarding requires non-nil chain") + return "", errors.New("job forwarding requires non-nil chain") } var err error @@ -690,18 +690,18 @@ func (d *Delegate) newServicesGenericPlugin( ps, err2 := loop.NewProviderServer(provider, types.OCR2PluginType(pCfg.ProviderType), d.lggr) if err2 != nil { - return nil, fmt.Errorf("cannot start EVM provider server: %s", err2) + return nil, fmt.Errorf("cannot start EVM provider server: %w", err2) } providerClientConn, err2 = ps.GetConn() if err2 != nil { - return nil, fmt.Errorf("cannot connect to EVM provider server: %s", err) + return nil, fmt.Errorf("cannot connect to EVM provider server: %w", err) } srvs = append(srvs, ps) } pc, err := json.Marshal(pCfg.Config) if err != nil { - return nil, fmt.Errorf("cannot dump plugin config to string before sending to plugin: %s", err) + return nil, fmt.Errorf("cannot dump plugin config to string before sending to plugin: %w", err) } pluginConfig := core.ReportingPluginServiceConfig{ @@ -1598,7 +1598,7 @@ func (d *Delegate) newServicesOCR2Functions( func (d *Delegate) newServicesCCIPCommit(ctx context.Context, lggr logger.SugaredLogger, jb job.Job, bootstrapPeers []commontypes.BootstrapperLocator, kb ocr2key.KeyBundle, ocrDB *db, lc ocrtypes.LocalConfig, transmitterID string) ([]job.ServiceCtx, error) { spec := jb.OCR2OracleSpec if spec.Relay != relay.NetworkEVM { - return nil, fmt.Errorf("non evm chains are not supported for CCIP commit") + return nil, errors.New("non evm chains are not supported for CCIP commit") } dstRid, err := spec.RelayID() if err != nil { @@ -1664,7 +1664,7 @@ func newCCIPCommitPluginBytes(isSourceProvider bool, sourceStartBlock uint64, de func (d *Delegate) ccipCommitGetDstProvider(ctx context.Context, jb job.Job, pluginJobSpecConfig ccipconfig.CommitPluginJobSpecConfig, transmitterID string) (types.CCIPCommitProvider, error) { spec := jb.OCR2OracleSpec if spec.Relay != relay.NetworkEVM { - return nil, fmt.Errorf("non evm chains are not supported for CCIP commit") + return nil, errors.New("non evm chains are not supported for CCIP commit") } dstRid, err := spec.RelayID() @@ -1699,7 +1699,7 @@ func (d *Delegate) ccipCommitGetDstProvider(ctx context.Context, jb job.Job, plu } dstProvider, ok := provider.(types.CCIPCommitProvider) if !ok { - return nil, fmt.Errorf("could not coerce PluginProvider to CCIPCommitProvider") + return nil, errors.New("could not coerce PluginProvider to CCIPCommitProvider") } return dstProvider, nil @@ -1755,7 +1755,7 @@ func (d *Delegate) ccipCommitGetSrcProvider(ctx context.Context, jb job.Job, plu } srcProvider, ok := provider.(types.CCIPCommitProvider) if !ok { - return nil, 0, fmt.Errorf("could not coerce PluginProvider to CCIPCommitProvider") + return nil, 0, errors.New("could not coerce PluginProvider to CCIPCommitProvider") } return @@ -1764,7 +1764,7 @@ func (d *Delegate) ccipCommitGetSrcProvider(ctx context.Context, jb job.Job, plu func (d *Delegate) newServicesCCIPExecution(ctx context.Context, lggr logger.SugaredLogger, jb job.Job, bootstrapPeers []commontypes.BootstrapperLocator, kb ocr2key.KeyBundle, ocrDB *db, lc ocrtypes.LocalConfig, transmitterID string) ([]job.ServiceCtx, error) { spec := jb.OCR2OracleSpec if spec.Relay != relay.NetworkEVM { - return nil, fmt.Errorf("non evm chains are not supported for CCIP execution") + return nil, errors.New("non evm chains are not supported for CCIP execution") } dstRid, err := spec.RelayID() @@ -1824,7 +1824,7 @@ func (d *Delegate) newServicesCCIPExecution(ctx context.Context, lggr logger.Sug func (d *Delegate) ccipExecGetDstProvider(ctx context.Context, jb job.Job, pluginJobSpecConfig ccipconfig.ExecPluginJobSpecConfig, transmitterID string) (types.CCIPExecProvider, error) { spec := jb.OCR2OracleSpec if spec.Relay != relay.NetworkEVM { - return nil, fmt.Errorf("non evm chains are not supported for CCIP execution") + return nil, errors.New("non evm chains are not supported for CCIP execution") } dstRid, err := spec.RelayID() @@ -1859,7 +1859,7 @@ func (d *Delegate) ccipExecGetDstProvider(ctx context.Context, jb job.Job, plugi } dstProvider, ok := provider.(types.CCIPExecProvider) if !ok { - return nil, fmt.Errorf("could not coerce PluginProvider to CCIPExecProvider") + return nil, errors.New("could not coerce PluginProvider to CCIPExecProvider") } return dstProvider, nil diff --git a/core/services/ocr2/delegate_test.go b/core/services/ocr2/delegate_test.go index 04693061880..1651aef665f 100644 --- a/core/services/ocr2/delegate_test.go +++ b/core/services/ocr2/delegate_test.go @@ -46,7 +46,7 @@ func TestGetEVMEffectiveTransmitterID(t *testing.T) { txManager := txmmocks.NewMockEvmTxManager(t) legacyChains := evmtest.NewLegacyChains(t, evmtest.TestChainOpts{DB: db, GeneralConfig: config, KeyStore: keyStore.Eth(), TxManager: txManager}) - require.True(t, legacyChains.Len() > 0) + require.Positive(t, legacyChains.Len()) type testCase struct { name string diff --git a/core/services/ocr2/plugins/ccip/abihelpers/abi_helpers.go b/core/services/ocr2/plugins/ccip/abihelpers/abi_helpers.go index d0ad5642d94..9c0fcdb386f 100644 --- a/core/services/ocr2/plugins/ccip/abihelpers/abi_helpers.go +++ b/core/services/ocr2/plugins/ccip/abihelpers/abi_helpers.go @@ -16,7 +16,7 @@ import ( func MustGetEventID(name string, abi2 abi.ABI) common.Hash { event, ok := abi2.Events[name] if !ok { - panic(fmt.Sprintf("missing event %s", name)) + panic("missing event " + name) } return event.ID } @@ -24,7 +24,7 @@ func MustGetEventID(name string, abi2 abi.ABI) common.Hash { func MustGetEventInputs(name string, abi2 abi.ABI) abi.Arguments { m, ok := abi2.Events[name] if !ok { - panic(fmt.Sprintf("missing event %s", name)) + panic("missing event " + name) } return m.Inputs } @@ -32,7 +32,7 @@ func MustGetEventInputs(name string, abi2 abi.ABI) abi.Arguments { func MustGetMethodInputs(name string, abi2 abi.ABI) abi.Arguments { m, ok := abi2.Methods[name] if !ok { - panic(fmt.Sprintf("missing method %s", name)) + panic("missing method " + name) } return m.Inputs } @@ -163,7 +163,7 @@ func getABI(abiStr string, operationType uint8) (*abi.ABI, error) { case DECODE: operationStr = "outputs" default: - return nil, fmt.Errorf("invalid operation type") + return nil, errors.New("invalid operation type") } inDef := fmt.Sprintf(`[{ "name" : "method", "type": "function", "%s": %s}]`, operationStr, abiStr) diff --git a/core/services/ocr2/plugins/ccip/ccipcommit/factory_test.go b/core/services/ocr2/plugins/ccip/ccipcommit/factory_test.go index 44c63ec87e6..171a376a024 100644 --- a/core/services/ocr2/plugins/ccip/ccipcommit/factory_test.go +++ b/core/services/ocr2/plugins/ccip/ccipcommit/factory_test.go @@ -100,5 +100,5 @@ func TestNewReportingPluginRetriesUntilSuccess(t *testing.T) { // Assert that NewReportingPlugin succeeds despite many transient internal failures (mocked out above) _, _, err := factory.NewReportingPlugin(ctx, reportingConfig) - assert.Equal(t, nil, err) + assert.NoError(t, err) } diff --git a/core/services/ocr2/plugins/ccip/ccipcommit/initializers.go b/core/services/ocr2/plugins/ccip/ccipcommit/initializers.go index 771fdd322f3..e81de9c90fc 100644 --- a/core/services/ocr2/plugins/ccip/ccipcommit/initializers.go +++ b/core/services/ocr2/plugins/ccip/ccipcommit/initializers.go @@ -8,6 +8,8 @@ import ( "strings" "time" + "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ccip/internal/pricegetter" "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ccip/internal/rpclib" @@ -79,7 +81,7 @@ func NewCommitServices(ctx context.Context, ds sqlutil.DataSource, srcProvider c } else { // Use dynamic price getter. if pluginConfig.PriceGetterConfig == nil { - return nil, fmt.Errorf("priceGetterConfig is nil") + return nil, errors.New("priceGetterConfig is nil") } // Build price getter clients for all chains specified in the aggregator configurations. diff --git a/core/services/ocr2/plugins/ccip/ccipcommit/ocr2.go b/core/services/ocr2/plugins/ccip/ccipcommit/ocr2.go index 55caf88f1c7..1e1b9b34887 100644 --- a/core/services/ocr2/plugins/ccip/ccipcommit/ocr2.go +++ b/core/services/ocr2/plugins/ccip/ccipcommit/ocr2.go @@ -543,7 +543,7 @@ func (r *CommitReportingPlugin) buildReport(ctx context.Context, lggr logger.Log lggr.Warn("No messages found in interval", "minSeqNr", interval.Min, "maxSeqNr", interval.Max) - return cciptypes.CommitStoreReport{}, fmt.Errorf("tried building a tree without leaves") + return cciptypes.CommitStoreReport{}, errors.New("tried building a tree without leaves") } leaves := make([][32]byte, 0, len(sendRequests)) diff --git a/core/services/ocr2/plugins/ccip/ccipcommit/ocr2_test.go b/core/services/ocr2/plugins/ccip/ccipcommit/ocr2_test.go index 93d8de9f892..4d99de40f42 100644 --- a/core/services/ocr2/plugins/ccip/ccipcommit/ocr2_test.go +++ b/core/services/ocr2/plugins/ccip/ccipcommit/ocr2_test.go @@ -3,7 +3,6 @@ package ccipcommit import ( "context" "encoding/json" - "fmt" "math/big" "math/rand" "slices" @@ -719,7 +718,7 @@ func TestCommitReportingPlugin_observePriceUpdates(t *testing.T) { mockPriceService := ccipdbmocks.NewPriceService(t) var psError error if tc.psError { - psError = fmt.Errorf("price service error") + psError = errors.New("price service error") } mockPriceService.On("GetGasAndTokenPrices", ctx, destChainSelector).Return( tc.psGasPricesResult, diff --git a/core/services/ocr2/plugins/ccip/ccipexec/batching_test.go b/core/services/ocr2/plugins/ccip/ccipexec/batching_test.go index 0fd23496974..868d4ec95f1 100644 --- a/core/services/ocr2/plugins/ccip/ccipexec/batching_test.go +++ b/core/services/ocr2/plugins/ccip/ccipexec/batching_test.go @@ -858,13 +858,13 @@ func runBatchingStrategyTests(t *testing.T, strategy BatchingStrategy, available // Utility function to run common assertions func runAssertions(t *testing.T, tc testCase, seqNrs []ccip.ObservedMessage, execStates []messageExecStatus) { if tc.expectedSeqNrs == nil { - assert.Len(t, seqNrs, 0) + assert.Empty(t, seqNrs) } else { assert.Equal(t, tc.expectedSeqNrs, seqNrs) } if tc.expectedStates == nil { - assert.Len(t, execStates, 0) + assert.Empty(t, execStates) } else { assert.Equal(t, tc.expectedStates, execStates) } diff --git a/core/services/ocr2/plugins/ccip/ccipexec/factory_test.go b/core/services/ocr2/plugins/ccip/ccipexec/factory_test.go index fe5e0ab1e23..31f8f9a29b1 100644 --- a/core/services/ocr2/plugins/ccip/ccipexec/factory_test.go +++ b/core/services/ocr2/plugins/ccip/ccipexec/factory_test.go @@ -65,5 +65,5 @@ func TestNewReportingPluginRetriesUntilSuccess(t *testing.T) { // Assert that NewReportingPlugin succeeds despite many transient internal failures (mocked out above) _, _, err := factory.NewReportingPlugin(ctx, reportingConfig) - assert.Equal(t, nil, err) + assert.NoError(t, err) } diff --git a/core/services/ocr2/plugins/ccip/ccipexec/inflight_test.go b/core/services/ocr2/plugins/ccip/ccipexec/inflight_test.go index 2a91457ef4f..c08a49b43dd 100644 --- a/core/services/ocr2/plugins/ccip/ccipexec/inflight_test.go +++ b/core/services/ocr2/plugins/ccip/ccipexec/inflight_test.go @@ -23,7 +23,7 @@ func TestInflightReportsContainer_add(t *testing.T) { }) require.Error(t, err) require.Equal(t, "report is already in flight", err.Error()) - require.Equal(t, 1, len(container.getAll())) + require.Len(t, container.getAll(), 1) } func TestInflightReportsContainer_expire(t *testing.T) { @@ -35,8 +35,8 @@ func TestInflightReportsContainer_expire(t *testing.T) { }) require.NoError(t, err) container.reports[0].createdAt = time.Now().Add(-time.Second * 5) - require.Equal(t, 1, len(container.getAll())) + require.Len(t, container.getAll(), 1) container.expire(lggr) - require.Equal(t, 0, len(container.getAll())) + require.Empty(t, container.getAll()) } diff --git a/core/services/ocr2/plugins/ccip/ccipexec/initializers.go b/core/services/ocr2/plugins/ccip/ccipexec/initializers.go index 7826f6058fe..e0eee543700 100644 --- a/core/services/ocr2/plugins/ccip/ccipexec/initializers.go +++ b/core/services/ocr2/plugins/ccip/ccipexec/initializers.go @@ -7,6 +7,8 @@ import ( "math/big" "time" + "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink-common/pkg/types" "github.com/Masterminds/semver/v3" @@ -50,7 +52,7 @@ var defaultNewReportingPluginRetryConfig = ccipdata.RetryConfig{InitialDelay: ti func NewExecServices(ctx context.Context, lggr logger.Logger, jb job.Job, srcProvider types.CCIPExecProvider, dstProvider types.CCIPExecProvider, srcChainID int64, dstChainID int64, new bool, argsNoPlugin libocr2.OCR2OracleArgs, logError func(string)) ([]job.ServiceCtx, error) { if jb.OCR2OracleSpec == nil { - return nil, fmt.Errorf("spec is nil") + return nil, errors.New("spec is nil") } spec := jb.OCR2OracleSpec var pluginConfig ccipconfig.ExecPluginJobSpecConfig diff --git a/core/services/ocr2/plugins/ccip/ccipexec/ocr2.go b/core/services/ocr2/plugins/ccip/ccipexec/ocr2.go index 4a09cf37b45..503458c51c1 100644 --- a/core/services/ocr2/plugins/ccip/ccipexec/ocr2.go +++ b/core/services/ocr2/plugins/ccip/ccipexec/ocr2.go @@ -624,7 +624,7 @@ func (r *ExecutionReportingPlugin) ShouldTransmitAcceptedReport(ctx context.Cont func (r *ExecutionReportingPlugin) isStaleReport(ctx context.Context, messages []cciptypes.EVM2EVMMessage) (bool, error) { if len(messages) == 0 { - return true, fmt.Errorf("messages are empty") + return true, errors.New("messages are empty") } // If the first message is executed already, this execution report is stale. diff --git a/core/services/ocr2/plugins/ccip/ccipexec/ocr2_test.go b/core/services/ocr2/plugins/ccip/ccipexec/ocr2_test.go index ff6371fa2ce..e1cb18bffee 100644 --- a/core/services/ocr2/plugins/ccip/ccipexec/ocr2_test.go +++ b/core/services/ocr2/plugins/ccip/ccipexec/ocr2_test.go @@ -331,13 +331,13 @@ func TestExecutionReportingPlugin_ShouldAcceptFinalizedReport(t *testing.T) { should, err := plugin.ShouldAcceptFinalizedReport(testutils.Context(t), ocrtypes.ReportTimestamp{}, encodedReport) require.NoError(t, err) - assert.Equal(t, true, should) + assert.True(t, should) mockedExecState.Return(uint8(cciptypes.ExecutionStateSuccess), nil).Once() should, err = plugin.ShouldAcceptFinalizedReport(testutils.Context(t), ocrtypes.ReportTimestamp{}, encodedReport) require.NoError(t, err) - assert.Equal(t, false, should) + assert.False(t, should) } func TestExecutionReportingPlugin_ShouldTransmitAcceptedReport(t *testing.T) { @@ -380,12 +380,12 @@ func TestExecutionReportingPlugin_ShouldTransmitAcceptedReport(t *testing.T) { should, err := plugin.ShouldTransmitAcceptedReport(testutils.Context(t), ocrtypes.ReportTimestamp{}, encodedReport) require.NoError(t, err) - assert.Equal(t, true, should) + assert.True(t, should) mockedExecState.Return(uint8(cciptypes.ExecutionStateFailure), nil).Once() should, err = plugin.ShouldTransmitAcceptedReport(testutils.Context(t), ocrtypes.ReportTimestamp{}, encodedReport) require.NoError(t, err) - assert.Equal(t, false, should) + assert.False(t, should) } func TestExecutionReportingPlugin_buildReport(t *testing.T) { @@ -1229,7 +1229,7 @@ func Test_selectReportsToFillBatch(t *testing.T) { for _, r := range unexpiredReportsBatches { flatten = append(flatten, r...) } - assert.Equal(t, tt.expectedReports, len(flatten)) + assert.Len(t, flatten, tt.expectedReports) if tt.expectedBatches > 0 { assert.Equal(t, reports, flatten) } else { @@ -1408,7 +1408,7 @@ func TestExecutionReportingPlugin_ensurePriceRegistrySynchronization(t *testing. p.onRampReader = mockOnRampReader mockOnRampReader.On("SourcePriceRegistryAddress", mock.Anything).Return(sourcePriceRegistryAddress1, nil).Once() - require.Equal(t, nil, p.sourcePriceRegistry) + require.Nil(t, p.sourcePriceRegistry) err := p.ensurePriceRegistrySynchronization(context.Background()) require.NoError(t, err) require.Equal(t, mockPriceRegistryReader1, p.sourcePriceRegistry) diff --git a/core/services/ocr2/plugins/ccip/config/config.go b/core/services/ocr2/plugins/ccip/config/config.go index a24a6edfd13..32308cf1a17 100644 --- a/core/services/ocr2/plugins/ccip/config/config.go +++ b/core/services/ocr2/plugins/ccip/config/config.go @@ -74,22 +74,22 @@ func (c *DynamicPriceGetterConfig) UnmarshalJSON(data []byte) error { func (c *DynamicPriceGetterConfig) Validate() error { for addr, v := range c.AggregatorPrices { if addr == utils.ZeroAddress { - return fmt.Errorf("token address is zero") + return errors.New("token address is zero") } if v.AggregatorContractAddress == utils.ZeroAddress { - return fmt.Errorf("aggregator contract address is zero") + return errors.New("aggregator contract address is zero") } if v.ChainID == 0 { - return fmt.Errorf("chain id is zero") + return errors.New("chain id is zero") } } for addr, v := range c.StaticPrices { if addr == utils.ZeroAddress { - return fmt.Errorf("token address is zero") + return errors.New("token address is zero") } if v.ChainID == 0 { - return fmt.Errorf("chain id is zero") + return errors.New("chain id is zero") } } diff --git a/core/services/ocr2/plugins/ccip/config/config_test.go b/core/services/ocr2/plugins/ccip/config/config_test.go index e6207aa2231..f32c9a0c547 100644 --- a/core/services/ocr2/plugins/ccip/config/config_test.go +++ b/core/services/ocr2/plugins/ccip/config/config_test.go @@ -2,11 +2,11 @@ package config import ( "encoding/json" - "fmt" "math/big" "testing" "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" @@ -73,7 +73,7 @@ func TestCommitConfig(t *testing.T) { }, }, }, - expectedValidationError: fmt.Errorf("aggregator contract address is zero"), + expectedValidationError: errors.New("aggregator contract address is zero"), }, { name: "missing chain ID", @@ -101,7 +101,7 @@ func TestCommitConfig(t *testing.T) { }, }, }, - expectedValidationError: fmt.Errorf("chain id is zero"), + expectedValidationError: errors.New("chain id is zero"), }, } @@ -193,7 +193,7 @@ func TestUSDCValidate(t *testing.T) { for _, tc := range testcases { tc := tc - t.Run(fmt.Sprintf("error = %s", tc.err), func(t *testing.T) { + t.Run("error = "+tc.err, func(t *testing.T) { t.Parallel() err := tc.config.ValidateUSDCConfig() if tc.err != "" { diff --git a/core/services/ocr2/plugins/ccip/integration_test.go b/core/services/ocr2/plugins/ccip/integration_test.go index b116a470363..54972b06707 100644 --- a/core/services/ocr2/plugins/ccip/integration_test.go +++ b/core/services/ocr2/plugins/ccip/integration_test.go @@ -378,12 +378,12 @@ func TestIntegration_CCIP(t *testing.T) { // delete v1 jobs for _, node := range ccipTH.Nodes { id := node.FindJobIDForContract(t, commitStoreV1.Address()) - require.Greater(t, id, int32(0)) + require.Positive(t, id) t.Logf("deleting job %d", id) err = node.App.DeleteJob(context.Background(), id) require.NoError(t, err) id = node.FindJobIDForContract(t, offRampV1.Address()) - require.Greater(t, id, int32(0)) + require.Positive(t, id) t.Logf("deleting job %d", id) err = node.App.DeleteJob(context.Background(), id) require.NoError(t, err) diff --git a/core/services/ocr2/plugins/ccip/internal/cache/chain_health_test.go b/core/services/ocr2/plugins/ccip/internal/cache/chain_health_test.go index ccdc7c4b22f..2b4b4c89636 100644 --- a/core/services/ocr2/plugins/ccip/internal/cache/chain_health_test.go +++ b/core/services/ocr2/plugins/ccip/internal/cache/chain_health_test.go @@ -3,7 +3,6 @@ package cache import ( "context" "errors" - "fmt" "sync" "testing" "time" @@ -48,7 +47,7 @@ func Test_RMNStateCaching(t *testing.T) { assert.NoError(t, err) healthy, err = chainState.IsHealthy(ctx) - assert.Nil(t, err) + assert.NoError(t, err) assert.False(t, healthy) // Chain is not cursed, but previous curse should be "sticky" even when force refreshing @@ -59,7 +58,7 @@ func Test_RMNStateCaching(t *testing.T) { assert.NoError(t, err) healthy, err = chainState.IsHealthy(ctx) - assert.Nil(t, err) + assert.NoError(t, err) assert.False(t, healthy) } @@ -216,7 +215,7 @@ func Test_RefreshingInBackground(t *testing.T) { assertHealthy(t, chainState, false) // Commit store error - mockCommitStore.set(false, fmt.Errorf("commit store error")) + mockCommitStore.set(false, errors.New("commit store error")) assertError(t, chainState) // Commit store is back @@ -228,7 +227,7 @@ func Test_RefreshingInBackground(t *testing.T) { assertHealthy(t, chainState, false) // OnRamp error - mockOnRamp.set(false, fmt.Errorf("onramp error")) + mockOnRamp.set(false, errors.New("onramp error")) assertError(t, chainState) // All back in healthy state diff --git a/core/services/ocr2/plugins/ccip/internal/cache/observed_chain_health_test.go b/core/services/ocr2/plugins/ccip/internal/cache/observed_chain_health_test.go index 19583a37c70..ec78f085e06 100644 --- a/core/services/ocr2/plugins/ccip/internal/cache/observed_chain_health_test.go +++ b/core/services/ocr2/plugins/ccip/internal/cache/observed_chain_health_test.go @@ -1,7 +1,7 @@ package cache import ( - "fmt" + "errors" "testing" "github.com/ethereum/go-ethereum/common" @@ -20,7 +20,7 @@ var address = cciptypes.Address(common.HexToAddress("0x1234567890123456789012345 func Test_ObservedChainStateSkipErrors(t *testing.T) { mockedHealthcheck := mocks.NewChainHealthcheck(t) - mockedHealthcheck.On("IsHealthy", mock.Anything).Return(false, fmt.Errorf("error")) + mockedHealthcheck.On("IsHealthy", mock.Anything).Return(false, errors.New("error")) observedChainState := NewObservedChainHealthCheck( mockedHealthcheck, diff --git a/core/services/ocr2/plugins/ccip/internal/ccipcommon/shortcuts_test.go b/core/services/ocr2/plugins/ccip/internal/ccipcommon/shortcuts_test.go index 6f1cdb4a6af..58961207576 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipcommon/shortcuts_test.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipcommon/shortcuts_test.go @@ -1,7 +1,7 @@ package ccipcommon import ( - "fmt" + "errors" "math/rand" "strconv" "testing" @@ -114,9 +114,9 @@ func TestIsTxRevertError(t *testing.T) { expectedOutput bool }{ {name: "empty", inputError: nil, expectedOutput: false}, - {name: "non-revert error", inputError: fmt.Errorf("nothing"), expectedOutput: false}, - {name: "geth error", inputError: fmt.Errorf("execution reverted"), expectedOutput: true}, - {name: "nethermind error", inputError: fmt.Errorf("VM execution error"), expectedOutput: true}, + {name: "non-revert error", inputError: errors.New("nothing"), expectedOutput: false}, + {name: "geth error", inputError: errors.New("execution reverted"), expectedOutput: true}, + {name: "nethermind error", inputError: errors.New("VM execution error"), expectedOutput: true}, } for _, tc := range testCases { @@ -139,20 +139,20 @@ func TestRetryUntilSuccess(t *testing.T) { numCalls++ numAttempts-- if numAttempts > 0 { - return numCalls, fmt.Errorf("") + return numCalls, errors.New("") } return numCalls, nil } // Assert that RetryUntilSuccess returns the expected value when fn returns success on the 5th attempt numCalls, err := RetryUntilSuccess(fn, initialDelay, maxDelay) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, 5, numCalls) // Assert that RetryUntilSuccess returns the expected value when fn returns success on the 8th attempt numAttempts = 8 numCalls = 0 numCalls, err = RetryUntilSuccess(fn, initialDelay, maxDelay) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, 8, numCalls) } diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/commit_store_reader_test.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/commit_store_reader_test.go index 0f234bab8a6..6d580e0a17b 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/commit_store_reader_test.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/commit_store_reader_test.go @@ -284,7 +284,7 @@ func TestCommitStoreReaders(t *testing.T) { reps, err := cr.GetCommitReportMatchingSeqNum(ctx, rep.Interval.Max+1, 0) require.NoError(t, err) - assert.Len(t, reps, 0) + assert.Empty(t, reps) reps, err = cr.GetCommitReportMatchingSeqNum(ctx, rep.Interval.Max, 0) require.NoError(t, err) @@ -304,7 +304,7 @@ func TestCommitStoreReaders(t *testing.T) { reps, err = cr.GetCommitReportMatchingSeqNum(ctx, rep.Interval.Min-1, 0) require.NoError(t, err) - require.Len(t, reps, 0) + require.Empty(t, reps) // Sanity reps, err = cr.GetAcceptedCommitReportsGteTimestamp(ctx, time.Unix(0, 0), 0) @@ -318,7 +318,7 @@ func TestCommitStoreReaders(t *testing.T) { // Until we detect the config, we'll have empty offchain config c1, err := cr.OffchainConfig(ctx) require.NoError(t, err) - assert.Equal(t, c1, cciptypes.CommitOffchainConfig{}) + assert.Equal(t, cciptypes.CommitOffchainConfig{}, c1) newPr, err := cr.ChangeConfig(ctx, configs[v][0], configs[v][1]) require.NoError(t, err) assert.Equal(t, ccipcalc.EvmAddrToGeneric(prs[v]), newPr) @@ -331,7 +331,7 @@ func TestCommitStoreReaders(t *testing.T) { require.NoError(t, err) gp, err := gpe.GetGasPrice(ctx) require.NoError(t, err) - assert.True(t, gp.Cmp(big.NewInt(0)) > 0) + assert.Positive(t, gp.Cmp(big.NewInt(0))) }) } } diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/price_registry_reader_test.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/price_registry_reader_test.go index 1b9ecc128a7..5e09c6dc23f 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/price_registry_reader_test.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/price_registry_reader_test.go @@ -174,7 +174,7 @@ func testPriceRegistryReader(t *testing.T, th priceRegReaderTH, pr ccipdata.Pric // Note unsupported chain selector simply returns an empty set not an error gasUpdates, err := pr.GetGasPriceUpdatesCreatedAfter(ctx, 1e6, time.Unix(0, 0), 0) require.NoError(t, err) - assert.Len(t, gasUpdates, 0) + assert.Empty(t, gasUpdates) for i, ts := range th.blockTs { // Should see all updates >= ts. @@ -210,7 +210,7 @@ func testPriceRegistryReader(t *testing.T, th priceRegReaderTH, pr ccipdata.Pric // Empty token set should return empty set no error. gotEmpty, err := pr.GetTokenPrices(ctx, []cciptypes.Address{}) require.NoError(t, err) - assert.Len(t, gotEmpty, 0) + assert.Empty(t, gotEmpty) // We expect latest token prices to apply allTokenUpdates, err := pr.GetTokenPriceUpdatesCreatedAfter(ctx, time.Unix(0, 0), 0) diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/usdc_reader.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/usdc_reader.go index 792e2eb7253..4e2c12236cb 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/usdc_reader.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/usdc_reader.go @@ -85,7 +85,7 @@ func (u *USDCReaderImpl) GetUSDCMessagePriorToLogIndexInTx(ctx context.Context, var lpLogs []logpoller.Log // fetch all the usdc logs for the provided tx hash - k := fmt.Sprintf("usdc-%s", txHash) // custom prefix to avoid key collision if someone re-uses the cache + k := "usdc-" + txHash // custom prefix to avoid key collision if someone re-uses the cache if rawLogs, foundInMem := u.shortLivedInMemLogs.Get(k); foundInMem { inMemLogs, ok := rawLogs.([]logpoller.Log) if !ok { diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/usdc_reader_internal_test.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/usdc_reader_internal_test.go index a54a1ad09a0..fd148ed8628 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/usdc_reader_internal_test.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/usdc_reader_internal_test.go @@ -1,7 +1,6 @@ package ccipdata import ( - "fmt" "testing" "time" @@ -120,7 +119,7 @@ func TestLogPollerClient_GetUSDCMessagePriorToLogIndexInTx(t *testing.T) { ).Return([]logpoller.Log{}, nil) usdcMessageData, err := u.GetUSDCMessagePriorToLogIndexInTx(ctx, ccipLogIndex, 0, txHash.String()) - assert.Errorf(t, err, fmt.Sprintf("no USDC message found prior to log index %d in tx %s", ccipLogIndex, txHash.Hex())) + assert.Errorf(t, err, "no USDC message found prior to log index %d in tx %s", ccipLogIndex, txHash.Hex()) assert.Nil(t, usdcMessageData) lp.AssertExpectations(t) diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/commit_store.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/commit_store.go index 2d772e3bd0a..94b1e45837f 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/commit_store.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/commit_store.go @@ -247,11 +247,11 @@ func (c *CommitStore) ChangeConfig(_ context.Context, onchainConfig []byte, offc defer c.configMu.Unlock() if c.estimator == nil { - return "", fmt.Errorf("this CommitStore estimator is nil. SetGasEstimator should be called before ChangeConfig") + return "", errors.New("this CommitStore estimator is nil. SetGasEstimator should be called before ChangeConfig") } if c.sourceMaxGasPrice == nil { - return "", fmt.Errorf("this CommitStore sourceMaxGasPrice is nil. SetSourceMaxGasPrice should be called before ChangeConfig") + return "", errors.New("this CommitStore sourceMaxGasPrice is nil. SetSourceMaxGasPrice should be called before ChangeConfig") } c.gasPriceEstimator = prices.NewDAGasPriceEstimator( diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/commit_store_test.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/commit_store_test.go index e0771f33cb9..1c9cac6a745 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/commit_store_test.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/commit_store_test.go @@ -52,7 +52,7 @@ func TestCommitReportEncoding(t *testing.T) { encodedReport, err := c.EncodeCommitReport(ctx, report) require.NoError(t, err) - assert.Greater(t, len(encodedReport), 0) + assert.NotEmpty(t, encodedReport) decodedReport, err := c.DecodeCommitReport(ctx, encodedReport) require.NoError(t, err) diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/offramp.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/offramp.go index e8017016690..48a638ead7e 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/offramp.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/offramp.go @@ -163,7 +163,7 @@ type OffRamp struct { func (o *OffRamp) GetStaticConfig(ctx context.Context) (cciptypes.OffRampStaticConfig, error) { if o.offRampV120 == nil { - return cciptypes.OffRampStaticConfig{}, fmt.Errorf("offramp not initialized") + return cciptypes.OffRampStaticConfig{}, errors.New("offramp not initialized") } c, err := o.offRampV120.GetStaticConfig(&bind.CallOpts{Context: ctx}) if err != nil { diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/offramp_reader_unit_test.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/offramp_reader_unit_test.go index 15c91235b92..cb6e81ad67b 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/offramp_reader_unit_test.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/offramp_reader_unit_test.go @@ -2,12 +2,12 @@ package v1_2_0 import ( "encoding/binary" - "fmt" "math/rand" "slices" "testing" "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -47,7 +47,7 @@ func TestOffRampGetDestinationTokensFromSourceTokens(t *testing.T) { { name: "rpc error", outputChangeFn: func(outputs []rpclib.DataAndErr) []rpclib.DataAndErr { - outputs[2].Err = fmt.Errorf("some error") + outputs[2].Err = errors.New("some error") return outputs }, expErr: true, diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/onramp.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/onramp.go index 52f241a30a6..a588b301bf0 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/onramp.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/onramp.go @@ -9,6 +9,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/hashutil" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -124,7 +125,7 @@ func (o *OnRamp) Address(context.Context) (cciptypes.Address, error) { func (o *OnRamp) GetDynamicConfig(context.Context) (cciptypes.OnRampDynamicConfig, error) { if o.onRamp == nil { - return cciptypes.OnRampDynamicConfig{}, fmt.Errorf("onramp not initialized") + return cciptypes.OnRampDynamicConfig{}, errors.New("onramp not initialized") } config, err := o.onRamp.GetDynamicConfig(&bind.CallOpts{}) if err != nil { diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/test_helpers.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/test_helpers.go index fb991be59da..df0f95536b1 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/test_helpers.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_2_0/test_helpers.go @@ -17,7 +17,7 @@ import ( // ApplyPriceRegistryUpdate is a helper function used in tests only. func ApplyPriceRegistryUpdate(t *testing.T, user *bind.TransactOpts, addr common.Address, ec client.Client, gasPrices []cciptypes.GasPrice, tokenPrices []cciptypes.TokenPrice) common.Hash { - require.True(t, len(gasPrices) <= 2) + require.LessOrEqual(t, len(gasPrices), 2) pr, err := fee_quoter.NewFeeQuoter(addr, ec) require.NoError(t, err) o, err := pr.Owner(nil) diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_5_0/onramp.go b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_5_0/onramp.go index da41d116bc8..971527996db 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_5_0/onramp.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdata/v1_5_0/onramp.go @@ -9,6 +9,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/hashutil" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -128,7 +129,7 @@ func (o *OnRamp) Address(context.Context) (cciptypes.Address, error) { func (o *OnRamp) GetDynamicConfig(context.Context) (cciptypes.OnRampDynamicConfig, error) { if o.onRamp == nil { - return cciptypes.OnRampDynamicConfig{}, fmt.Errorf("onramp not initialized") + return cciptypes.OnRampDynamicConfig{}, errors.New("onramp not initialized") } config, err := o.onRamp.GetDynamicConfig(&bind.CallOpts{}) if err != nil { diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdb/price_service.go b/core/services/ocr2/plugins/ccip/internal/ccipdb/price_service.go index b5e8853d67c..bd5e77da73d 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdb/price_service.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdb/price_service.go @@ -2,6 +2,7 @@ package db import ( "context" + "errors" "fmt" "math/big" "slices" @@ -272,7 +273,7 @@ func (p *priceService) observeGasPriceUpdates( lggr logger.Logger, ) (sourceGasPriceUSD *big.Int, err error) { if p.gasPriceEstimator == nil { - return nil, fmt.Errorf("gasPriceEstimator is not set yet") + return nil, errors.New("gasPriceEstimator is not set yet") } // Include wrapped native to identify the source native USD price, notice USD is in 1e18 scale, i.e. $1 = 1e18 @@ -292,7 +293,7 @@ func (p *priceService) observeGasPriceUpdates( return nil, err } if sourceGasPrice == nil { - return nil, fmt.Errorf("missing gas price") + return nil, errors.New("missing gas price") } sourceGasPriceUSD, err = p.gasPriceEstimator.DenoteInUSD(ctx, sourceGasPrice, sourceNativePriceUSD) if err != nil { @@ -320,7 +321,7 @@ func (p *priceService) observeTokenPriceUpdates( lggr logger.Logger, ) (tokenPricesUSD map[cciptypes.Address]*big.Int, err error) { if p.destPriceRegistryReader == nil { - return nil, fmt.Errorf("destPriceRegistry is not set yet") + return nil, errors.New("destPriceRegistry is not set yet") } rawTokenPricesUSD, err := p.priceGetter.GetJobSpecTokenPricesUSD(ctx) if err != nil { @@ -383,7 +384,7 @@ func (p *priceService) observeTokenPriceUpdates( } if len(destTokensDecimals) != len(finalDestTokens) { - return nil, fmt.Errorf("mismatched token decimals and tokens") + return nil, errors.New("mismatched token decimals and tokens") } tokenPricesUSD = make(map[cciptypes.Address]*big.Int, len(rawTokenPricesUSD)) diff --git a/core/services/ocr2/plugins/ccip/internal/ccipdb/price_service_test.go b/core/services/ocr2/plugins/ccip/internal/ccipdb/price_service_test.go index d76044b2256..0013fc90e0b 100644 --- a/core/services/ocr2/plugins/ccip/internal/ccipdb/price_service_test.go +++ b/core/services/ocr2/plugins/ccip/internal/ccipdb/price_service_test.go @@ -2,6 +2,7 @@ package db import ( "context" + "errors" "fmt" "math/big" "reflect" @@ -67,7 +68,7 @@ func TestPriceService_writeGasPrices(t *testing.T) { var gasPricesError error if tc.gasPriceError { - gasPricesError = fmt.Errorf("gas prices error") + gasPricesError = errors.New("gas prices error") } mockOrm := ccipmocks.NewORM(t) @@ -138,7 +139,7 @@ func TestPriceService_writeTokenPrices(t *testing.T) { var tokenPricesError error if tc.tokenPriceError { - tokenPricesError = fmt.Errorf("token prices error") + tokenPricesError = errors.New("token prices error") } mockOrm := ccipmocks.NewORM(t) @@ -200,7 +201,7 @@ func TestPriceService_observeGasPriceUpdates(t *testing.T) { name: "price getter returned an error", sourceNativeToken: sourceNativeToken, priceGetterRespData: nil, - priceGetterRespErr: fmt.Errorf("some random network error"), + priceGetterRespErr: errors.New("some random network error"), expErr: true, }, { @@ -273,7 +274,7 @@ func TestPriceService_observeGasPriceUpdates(t *testing.T) { return } assert.NoError(t, err) - assert.True(t, tc.expSourceGasPriceUSD.Cmp(sourceGasPriceUSD) == 0) + assert.Equal(t, tc.expSourceGasPriceUSD.Cmp(sourceGasPriceUSD), 0) }) } } @@ -349,7 +350,7 @@ func TestPriceService_observeTokenPriceUpdates(t *testing.T) { }, sourceNativeToken: tokens[0], priceGetterRespData: nil, - priceGetterRespErr: fmt.Errorf("some random network error"), + priceGetterRespErr: errors.New("some random network error"), expErr: true, }, { @@ -461,7 +462,7 @@ func TestPriceService_observeTokenPriceUpdates(t *testing.T) { destPriceReg := ccipdatamocks.NewPriceRegistryReader(t) if tc.expDecimalErr { - destPriceReg.On("GetTokensDecimals", mock.Anything, finalDestTokens).Return([]uint8{}, fmt.Errorf("Token not found")).Maybe() + destPriceReg.On("GetTokensDecimals", mock.Anything, finalDestTokens).Return([]uint8{}, errors.New("Token not found")).Maybe() } else { destPriceReg.On("GetTokensDecimals", mock.Anything, finalDestTokens).Return(destDecimals, nil).Maybe() } @@ -687,12 +688,12 @@ func TestPriceService_GetGasAndTokenPrices(t *testing.T) { mockOrm := ccipmocks.NewORM(t) if tc.gasPriceError { - mockOrm.On("GetGasPricesByDestChain", ctx, destChainSelector).Return(nil, fmt.Errorf("gas prices error")).Once() + mockOrm.On("GetGasPricesByDestChain", ctx, destChainSelector).Return(nil, errors.New("gas prices error")).Once() } else { mockOrm.On("GetGasPricesByDestChain", ctx, destChainSelector).Return(tc.ormGasPricesResult, nil).Once() } if tc.tokenPriceError { - mockOrm.On("GetTokenPricesByDestChain", ctx, destChainSelector).Return(nil, fmt.Errorf("token prices error")).Once() + mockOrm.On("GetTokenPricesByDestChain", ctx, destChainSelector).Return(nil, errors.New("token prices error")).Once() } else { mockOrm.On("GetTokenPricesByDestChain", ctx, destChainSelector).Return(tc.ormTokenPricesResult, nil).Once() } diff --git a/core/services/ocr2/plugins/ccip/internal/observability/metrics_test.go b/core/services/ocr2/plugins/ccip/internal/observability/metrics_test.go index 3d84acf9616..9f4b9a0ee6e 100644 --- a/core/services/ocr2/plugins/ccip/internal/observability/metrics_test.go +++ b/core/services/ocr2/plugins/ccip/internal/observability/metrics_test.go @@ -1,7 +1,7 @@ package observability import ( - "fmt" + "errors" "testing" "github.com/prometheus/client_golang/prometheus" @@ -49,7 +49,7 @@ func TestMetricsSendFromContractDirectly(t *testing.T) { chainId := int64(420) mockedOfframp := ccipdatamocks.NewOffRampReader(t) - mockedOfframp.On("GetTokens", ctx).Return(cciptypes.OffRampTokens{}, fmt.Errorf("execution error")) + mockedOfframp.On("GetTokens", ctx).Return(cciptypes.OffRampTokens{}, errors.New("execution error")) observedOfframp := NewObservedOffRampReader(mockedOfframp, chainId, "plugin") @@ -83,5 +83,5 @@ func successfulContract() (string, error) { } func failedContract() (string, error) { - return "", fmt.Errorf("just error") + return "", errors.New("just error") } diff --git a/core/services/ocr2/plugins/ccip/internal/observability/onramp_observed_test.go b/core/services/ocr2/plugins/ccip/internal/observability/onramp_observed_test.go index 1918f632b94..f485a675ca9 100644 --- a/core/services/ocr2/plugins/ccip/internal/observability/onramp_observed_test.go +++ b/core/services/ocr2/plugins/ccip/internal/observability/onramp_observed_test.go @@ -81,7 +81,7 @@ func TestOnRampObservedMethods(t *testing.T) { } func testMethod(t *testing.T, method reflect.Method, methodCalls map[string]MethodCall, excludedMethods []string, reader *mocks.OnRampReader, observed ObservedOnRampReader) { - t.Run(fmt.Sprintf("observability_wrapper_%s", method.Name), func(t *testing.T) { + t.Run("observability_wrapper_"+method.Name, func(t *testing.T) { // Skip excluded methods. for _, em := range excludedMethods { if method.Name == em { diff --git a/core/services/ocr2/plugins/ccip/internal/pricegetter/evm_test.go b/core/services/ocr2/plugins/ccip/internal/pricegetter/evm_test.go index 78de2699688..049ac2ec9b2 100644 --- a/core/services/ocr2/plugins/ccip/internal/pricegetter/evm_test.go +++ b/core/services/ocr2/plugins/ccip/internal/pricegetter/evm_test.go @@ -127,7 +127,7 @@ func TestDynamicPriceGetterWithEmptyInput(t *testing.T) { require.NoError(t, err) // Ensure all expected prices are present. - assert.True(t, len(prices) == len(expectedTokens)) + assert.Equal(t, len(prices), len(expectedTokens)) // Check prices are matching expected result. for tk, expectedPrice := range expectedTokens { if prices[cciptypes.Address(tk.String())] == nil { diff --git a/core/services/ocr2/plugins/ccip/internal/pricegetter/pipeline_test.go b/core/services/ocr2/plugins/ccip/internal/pricegetter/pipeline_test.go index e71d5402503..7e4629ebd17 100644 --- a/core/services/ocr2/plugins/ccip/internal/pricegetter/pipeline_test.go +++ b/core/services/ocr2/plugins/ccip/internal/pricegetter/pipeline_test.go @@ -61,10 +61,10 @@ func TestDataSource(t *testing.T) { // Ask for all prices present in spec. prices, err := priceGetter.GetJobSpecTokenPricesUSD(ctx) require.NoError(t, err) - assert.Equal(t, prices, map[cciptypes.Address]*big.Int{ + assert.Equal(t, map[cciptypes.Address]*big.Int{ linkTokenAddress: big.NewInt(0).Mul(big.NewInt(200), big.NewInt(1000000000000000000)), usdcTokenAddress: big.NewInt(0).Mul(big.NewInt(1000), big.NewInt(1000000000000000000)), - }) + }, prices) // Specifically ask for all prices pricesWithInput, errWithInput := priceGetter.TokenPricesUSD(ctx, []cciptypes.Address{ @@ -72,10 +72,10 @@ func TestDataSource(t *testing.T) { usdcTokenAddress, }) require.NoError(t, errWithInput) - assert.Equal(t, pricesWithInput, map[cciptypes.Address]*big.Int{ + assert.Equal(t, map[cciptypes.Address]*big.Int{ linkTokenAddress: big.NewInt(0).Mul(big.NewInt(200), big.NewInt(1000000000000000000)), usdcTokenAddress: big.NewInt(0).Mul(big.NewInt(1000), big.NewInt(1000000000000000000)), - }) + }, pricesWithInput) // Ask a non-existent price. _, err = priceGetter.TokenPricesUSD(ctx, []cciptypes.Address{ @@ -86,9 +86,9 @@ func TestDataSource(t *testing.T) { // Ask only one price prices, err = priceGetter.TokenPricesUSD(ctx, []cciptypes.Address{linkTokenAddress}) require.NoError(t, err) - assert.Equal(t, prices, map[cciptypes.Address]*big.Int{ + assert.Equal(t, map[cciptypes.Address]*big.Int{ linkTokenAddress: big.NewInt(0).Mul(big.NewInt(200), big.NewInt(1000000000000000000)), - }) + }, prices) } func TestParsingDifferentFormats(t *testing.T) { @@ -159,7 +159,7 @@ func TestParsingDifferentFormats(t *testing.T) { require.Error(t, err) } else { require.NoError(t, err) - require.Equal(t, prices[ccipcalc.EvmAddrToGeneric(address)], tt.expectedValue) + require.Equal(t, tt.expectedValue, prices[ccipcalc.EvmAddrToGeneric(address)]) } }) } diff --git a/core/services/ocr2/plugins/ccip/internal/rpclib/evm.go b/core/services/ocr2/plugins/ccip/internal/rpclib/evm.go index 6c4aabb4355..05299d4c8c8 100644 --- a/core/services/ocr2/plugins/ccip/internal/rpclib/evm.go +++ b/core/services/ocr2/plugins/ccip/internal/rpclib/evm.go @@ -283,7 +283,7 @@ func (c EvmCall) String() string { func EVMCallsToString(calls []EvmCall) string { callString := "" for _, call := range calls { - callString += fmt.Sprintf("%s\n", call.String()) + callString += call.String() + "\n" } return callString } diff --git a/core/services/ocr2/plugins/ccip/internal/rpclib/evm_test.go b/core/services/ocr2/plugins/ccip/internal/rpclib/evm_test.go index 46b41723af3..296d4ca82f7 100644 --- a/core/services/ocr2/plugins/ccip/internal/rpclib/evm_test.go +++ b/core/services/ocr2/plugins/ccip/internal/rpclib/evm_test.go @@ -203,7 +203,7 @@ func TestParseOutput(t *testing.T) { }, { name: "has err", - dataAndErr: rpclib.DataAndErr{Outputs: []any{"abc"}, Err: fmt.Errorf("some err")}, + dataAndErr: rpclib.DataAndErr{Outputs: []any{"abc"}, Err: errors.New("some err")}, outputIdx: 0, expErr: true, }, diff --git a/core/services/ocr2/plugins/ccip/observations_test.go b/core/services/ocr2/plugins/ccip/observations_test.go index c39be8e5a2c..dd27328b50c 100644 --- a/core/services/ocr2/plugins/ccip/observations_test.go +++ b/core/services/ocr2/plugins/ccip/observations_test.go @@ -28,7 +28,7 @@ func TestObservationFilter(t *testing.T) { b1, err := obs1.Marshal() require.NoError(t, err) nonEmpty := GetParsableObservations[CommitObservation](lggr, []types.AttributedObservation{{Observation: b1}, {Observation: []byte{}}}) - require.Equal(t, 1, len(nonEmpty)) + require.Len(t, nonEmpty, 1) assert.Equal(t, nonEmpty[0].Interval, obs1.Interval) } @@ -63,7 +63,7 @@ func TestObservationCompat_MultiChainGas(t *testing.T) { observations := GetParsableObservations[CommitObservation](logger.TestLogger(t), []types.AttributedObservation{{Observation: bL}, {Observation: bN}}) - assert.Equal(t, 2, len(observations)) + assert.Len(t, observations, 2) assert.Equal(t, observations[0], observations[1]) } @@ -91,7 +91,7 @@ func TestCommitObservationJsonDeserialization(t *testing.T) { }` observations := GetParsableObservations[CommitObservation](logger.TestLogger(t), []types.AttributedObservation{{Observation: []byte(json)}}) - assert.Equal(t, 1, len(observations)) + assert.Len(t, observations, 1) assert.Equal(t, expectedObservation, observations[0]) } @@ -109,7 +109,7 @@ func TestCommitObservationMarshal(t *testing.T) { b, err := obs.Marshal() require.NoError(t, err) - assert.Equal(t, `{"interval":{"Min":1,"Max":12},"tokensPerFeeCoin":{"0xaaaaaa":1},"sourceGasPrice":3,"sourceGasPriceUSDPerChain":{"123":3}}`, string(b)) + assert.JSONEq(t, `{"interval":{"Min":1,"Max":12},"tokensPerFeeCoin":{"0xaaaaaa":1},"sourceGasPrice":3,"sourceGasPriceUSDPerChain":{"123":3}}`, string(b)) // Make sure that the call to Marshal did not alter the original observation object. assert.Len(t, obs.TokenPricesUSD, 1) @@ -141,8 +141,8 @@ func TestExecutionObservationJsonDeserialization(t *testing.T) { }` observations := GetParsableObservations[ExecutionObservation](logger.TestLogger(t), []types.AttributedObservation{{Observation: []byte(json)}}) - assert.Equal(t, 1, len(observations)) - assert.Equal(t, 2, len(observations[0].Messages)) + assert.Len(t, observations, 1) + assert.Len(t, observations[0].Messages, 2) assert.Equal(t, expectedObservation, observations[0]) } @@ -265,7 +265,7 @@ func TestCommitObservationJsonSerializationDeserialization(t *testing.T) { observations := GetParsableObservations[CommitObservation](logger.TestLogger(t), []types.AttributedObservation{ {Observation: []byte(jsonEncoded)}, }) - assert.Equal(t, 1, len(observations)) + assert.Len(t, observations, 1) assert.Equal(t, expectedObservation, observations[0]) backToJson, err := expectedObservation.Marshal() @@ -279,7 +279,7 @@ func TestCommitObservationJsonSerializationDeserialization(t *testing.T) { observations = GetParsableObservations[CommitObservation](logger.TestLogger(t), []types.AttributedObservation{ {Observation: []byte(jsonEncoded)}, }) - assert.Equal(t, 1, len(observations)) + assert.Len(t, observations, 1) assert.Equal(t, expectedObservation, observations[0]) } diff --git a/core/services/ocr2/plugins/ccip/prices/da_price_estimator_test.go b/core/services/ocr2/plugins/ccip/prices/da_price_estimator_test.go index 2772042f68d..66a9572745e 100644 --- a/core/services/ocr2/plugins/ccip/prices/da_price_estimator_test.go +++ b/core/services/ocr2/plugins/ccip/prices/da_price_estimator_test.go @@ -145,7 +145,7 @@ func TestDAPriceEstimator_DenoteInUSD(t *testing.T) { gasPrice, err := g.DenoteInUSD(ctx, tc.gasPrice, tc.nativePrice) assert.NoError(t, err) - assert.True(t, tc.expPrice.Cmp(gasPrice) == 0) + assert.Equal(t, tc.expPrice.Cmp(gasPrice), 0) }) } } @@ -231,7 +231,7 @@ func TestDAPriceEstimator_Median(t *testing.T) { gasPrice, err := g.Median(ctx, tc.gasPrices) assert.NoError(t, err) - assert.True(t, tc.expMedian.Cmp(gasPrice) == 0) + assert.Equal(t, tc.expMedian.Cmp(gasPrice), 0) }) } } diff --git a/core/services/ocr2/plugins/ccip/prices/exec_price_estimator_test.go b/core/services/ocr2/plugins/ccip/prices/exec_price_estimator_test.go index b8f6fa978db..27251c35a03 100644 --- a/core/services/ocr2/plugins/ccip/prices/exec_price_estimator_test.go +++ b/core/services/ocr2/plugins/ccip/prices/exec_price_estimator_test.go @@ -143,7 +143,7 @@ func TestExecPriceEstimator_DenoteInUSD(t *testing.T) { gasPrice, err := g.DenoteInUSD(ctx, tc.gasPrice, tc.nativePrice) assert.NoError(t, err) - assert.True(t, tc.expPrice.Cmp(gasPrice) == 0) + assert.Equal(t, tc.expPrice.Cmp(gasPrice), 0) }) } } @@ -195,7 +195,7 @@ func TestExecPriceEstimator_Median(t *testing.T) { gasPrice, err := g.Median(ctx, tc.gasPrices) assert.NoError(t, err) - assert.True(t, tc.expMedian.Cmp(gasPrice) == 0) + assert.Equal(t, tc.expMedian.Cmp(gasPrice), 0) }) } } diff --git a/core/services/ocr2/plugins/ccip/proxycommitstore.go b/core/services/ocr2/plugins/ccip/proxycommitstore.go index b06f957bd58..ac46a033773 100644 --- a/core/services/ocr2/plugins/ccip/proxycommitstore.go +++ b/core/services/ocr2/plugins/ccip/proxycommitstore.go @@ -2,13 +2,14 @@ package ccip import ( "context" - "fmt" "io" "math/big" "time" "go.uber.org/multierr" + "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/gas" cciptypes "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" @@ -121,13 +122,13 @@ func (p *ProviderProxyCommitStoreReader) VerifyExecutionReport(ctx context.Conte // SetGasEstimator is invalid on ProviderProxyCommitStoreReader. The provider based impl's do not have SetGasEstimator // defined, so this serves no purpose other than satisfying an interface. func (p *ProviderProxyCommitStoreReader) SetGasEstimator(ctx context.Context, gpe gas.EvmFeeEstimator) error { - return fmt.Errorf("invalid usage of ProviderProxyCommitStoreReader") + return errors.New("invalid usage of ProviderProxyCommitStoreReader") } // SetSourceMaxGasPrice is invalid on ProviderProxyCommitStoreReader. The provider based impl's do not have SetSourceMaxGasPrice // defined, so this serves no purpose other than satisfying an interface. func (p *ProviderProxyCommitStoreReader) SetSourceMaxGasPrice(ctx context.Context, sourceMaxGasPrice *big.Int) error { - return fmt.Errorf("invalid usage of ProviderProxyCommitStoreReader") + return errors.New("invalid usage of ProviderProxyCommitStoreReader") } func (p *ProviderProxyCommitStoreReader) Close() error { diff --git a/core/services/ocr2/plugins/ccip/testhelpers/ccip_contracts.go b/core/services/ocr2/plugins/ccip/testhelpers/ccip_contracts.go index c2fec2903e8..42133a8b0f0 100644 --- a/core/services/ocr2/plugins/ccip/testhelpers/ccip_contracts.go +++ b/core/services/ocr2/plugins/ccip/testhelpers/ccip_contracts.go @@ -1378,7 +1378,7 @@ func (args *ManualExecArgs) ApproxDestStartBlock(ctx context.Context) error { for closestBlockHdr.Time > sendTxTime { closestBlockNum = closestBlockNum - blockOffset if closestBlockNum <= 0 { - return fmt.Errorf("approx destination blocknumber not found") + return errors.New("approx destination blocknumber not found") } closestBlockHdr, err = args.DestChain.HeaderByNumber(ctx, new(big.Int).SetUint64(closestBlockNum)) if err != nil { @@ -1420,22 +1420,22 @@ func (args *ManualExecArgs) ExecuteManually(ctx context.Context) (*types.Transac if args.SourceChainID == 0 || args.DestChainID == 0 || args.DestUser == nil { - return nil, fmt.Errorf("chain ids and owners are mandatory for source and dest chain") + return nil, errors.New("chain ids and owners are mandatory for source and dest chain") } if !common.IsHexAddress(args.CommitStore) || !common.IsHexAddress(args.OffRamp) || !common.IsHexAddress(args.OnRamp) { - return nil, fmt.Errorf("contract addresses must be valid hex address") + return nil, errors.New("contract addresses must be valid hex address") } if args.SendReqTxHash == "" { - return nil, fmt.Errorf("tx hash of ccip-send request are required") + return nil, errors.New("tx hash of ccip-send request are required") } if args.SourceStartBlock == nil { - return nil, fmt.Errorf("must provide the value of source block in/after which ccip-send tx was included") + return nil, errors.New("must provide the value of source block in/after which ccip-send tx was included") } if args.SeqNr == 0 { if args.SendReqLogIndex == 0 { - return nil, fmt.Errorf("must provide the value of log index of ccip-send request") + return nil, errors.New("must provide the value of log index of ccip-send request") } // locate seq nr from CCIPSendRequested log seqNr, err := args.FindSeqNrFromCCIPSendRequested() @@ -1485,7 +1485,7 @@ func (args *ManualExecArgs) execute(report *commit_store.CommitStoreCommitReport } leafHasher := v1_2_0.NewLeafHasher(args.SourceChainID, args.DestChainID, common.HexToAddress(args.OnRamp), mctx, onRampContract) if leafHasher == nil { - return nil, fmt.Errorf("unable to create leaf hasher") + return nil, errors.New("unable to create leaf hasher") } var leaves [][32]byte @@ -1578,7 +1578,7 @@ func (args *ManualExecArgs) execute(report *commit_store.CommitStoreCommitReport return nil, err } if tree.Root() != report.MerkleRoot { - return nil, fmt.Errorf("root doesn't match") + return nil, errors.New("root doesn't match") } proof, err := tree.Prove([]int{prove}) diff --git a/core/services/ocr2/plugins/ccip/testhelpers/integration/jobspec.go b/core/services/ocr2/plugins/ccip/testhelpers/integration/jobspec.go index a520580e614..f40357f7a3d 100644 --- a/core/services/ocr2/plugins/ccip/testhelpers/integration/jobspec.go +++ b/core/services/ocr2/plugins/ccip/testhelpers/integration/jobspec.go @@ -3,6 +3,7 @@ package integrationtesthelpers import ( "bytes" "crypto/sha256" + "errors" "fmt" "text/template" "time" @@ -185,7 +186,7 @@ type CCIPJobSpecParams struct { func (params CCIPJobSpecParams) Validate() error { if params.CommitStore == common.HexToAddress("0x0") { - return fmt.Errorf("must set commit store address") + return errors.New("must set commit store address") } return nil } @@ -196,7 +197,7 @@ func (params CCIPJobSpecParams) ValidateCommitJobSpec() error { return commonErr } if params.OffRamp == common.HexToAddress("0x0") { - return fmt.Errorf("OffRamp cannot be empty for execution job") + return errors.New("OffRamp cannot be empty for execution job") } // Validate token prices config // NB: only validate the dynamic price getter config if present since we could also be using the pipeline instead. @@ -215,7 +216,7 @@ func (params CCIPJobSpecParams) ValidateExecJobSpec() error { return commonErr } if params.OffRamp == common.HexToAddress("0x0") { - return fmt.Errorf("OffRamp cannot be empty for execution job") + return errors.New("OffRamp cannot be empty for execution job") } return nil } diff --git a/core/services/ocr2/plugins/ccip/tokendata/bgworker.go b/core/services/ocr2/plugins/ccip/tokendata/bgworker.go index bc5aba557e6..a97f4061ac4 100644 --- a/core/services/ocr2/plugins/ccip/tokendata/bgworker.go +++ b/core/services/ocr2/plugins/ccip/tokendata/bgworker.go @@ -2,7 +2,7 @@ package tokendata import ( "context" - "fmt" + "errors" "strconv" "sync" "time" @@ -119,7 +119,7 @@ func (w *BackgroundWorker) GetMsgTokenData(ctx context.Context, msg cciptypes.EV return nil, r.Err } if r.TokenAmountIndex < 0 || r.TokenAmountIndex >= len(msg.TokenAmounts) { - return nil, fmt.Errorf("token data index inconsistency") + return nil, errors.New("token data index inconsistency") } tokenDatas[r.TokenAmountIndex] = r.Data } diff --git a/core/services/ocr2/plugins/ccip/tokendata/bgworker_test.go b/core/services/ocr2/plugins/ccip/tokendata/bgworker_test.go index 5d505363ac7..bc31bd75733 100644 --- a/core/services/ocr2/plugins/ccip/tokendata/bgworker_test.go +++ b/core/services/ocr2/plugins/ccip/tokendata/bgworker_test.go @@ -2,6 +2,7 @@ package tokendata_test import ( "context" + "errors" "fmt" "math/rand" "testing" @@ -73,8 +74,8 @@ func TestBackgroundWorker(t *testing.T) { assert.NoError(t, err) assert.Equal(t, tokenData[msg.TokenAmounts[0].Token], b[0]) } - assert.True(t, time.Since(tStart) < 600*time.Millisecond) - assert.True(t, time.Since(tStart) > 200*time.Millisecond) + assert.Less(t, time.Since(tStart), 600*time.Millisecond) + assert.Greater(t, time.Since(tStart), 200*time.Millisecond) tStart = time.Now() for _, msg := range msgs { @@ -82,7 +83,7 @@ func TestBackgroundWorker(t *testing.T) { assert.NoError(t, err) assert.Equal(t, tokenData[msg.TokenAmounts[0].Token], b[0]) } - assert.True(t, time.Since(tStart) < 200*time.Millisecond) + assert.Less(t, time.Since(tStart), 200*time.Millisecond) w.AddJobsFromMsgs(ctx, msgs) // same messages are added but they should already be in cache tStart = time.Now() @@ -91,7 +92,7 @@ func TestBackgroundWorker(t *testing.T) { assert.NoError(t, err) assert.Equal(t, tokenData[msg.TokenAmounts[0].Token], b[0]) } - assert.True(t, time.Since(tStart) < 200*time.Millisecond) + assert.Less(t, time.Since(tStart), 200*time.Millisecond) require.NoError(t, w.Close()) } @@ -127,7 +128,7 @@ func TestBackgroundWorker_RetryOnErrors(t *testing.T) { // reader2 returns an error rdr2.On("ReadTokenData", mock.Anything, msgs[1], 0). - Return(nil, fmt.Errorf("some err")).Once() + Return(nil, errors.New("some err")).Once() w.AddJobsFromMsgs(ctx, msgs) // processing of the messages should have started at this point diff --git a/core/services/ocr2/plugins/ccip/tokendata/usdc/usdc.go b/core/services/ocr2/plugins/ccip/tokendata/usdc/usdc.go index aaa6086fbc9..f80e88691b8 100644 --- a/core/services/ocr2/plugins/ccip/tokendata/usdc/usdc.go +++ b/core/services/ocr2/plugins/ccip/tokendata/usdc/usdc.go @@ -166,7 +166,7 @@ func NewUSDCTokenDataReaderWithHttpClient( // configured. func (s *TokenDataReader) ReadTokenData(ctx context.Context, msg cciptypes.EVM2EVMOnRampCCIPSendRequestedWithMeta, tokenIndex int) ([]byte, error) { if tokenIndex < 0 || tokenIndex >= len(msg.TokenAmounts) { - return nil, fmt.Errorf("token index out of bounds") + return nil, errors.New("token index out of bounds") } if s.inCoolDownPeriod() { diff --git a/core/services/ocr2/plugins/ccip/tokendata/usdc/usdc_test.go b/core/services/ocr2/plugins/ccip/tokendata/usdc/usdc_test.go index 786e88a6322..64273ffe7bd 100644 --- a/core/services/ocr2/plugins/ccip/tokendata/usdc/usdc_test.go +++ b/core/services/ocr2/plugins/ccip/tokendata/usdc/usdc_test.go @@ -255,7 +255,7 @@ func TestGetUSDCMessageBody(t *testing.T) { }, }, 0) require.NoError(t, err) - require.Equal(t, body, expectedBody) + require.Equal(t, expectedBody, body) usdcReader.AssertNumberOfCalls(t, "GetUSDCMessagePriorToLogIndexInTx", 1) } diff --git a/core/services/ocr2/plugins/functions/aggregation.go b/core/services/ocr2/plugins/functions/aggregation.go index 7ae00532f3f..cd0fe86a594 100644 --- a/core/services/ocr2/plugins/functions/aggregation.go +++ b/core/services/ocr2/plugins/functions/aggregation.go @@ -6,6 +6,8 @@ import ( "fmt" "sort" + "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/functions/config" "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/functions/encoding" ) @@ -16,7 +18,7 @@ func CanAggregate(N int, F int, observations []*encoding.ProcessedRequest) bool func Aggregate(aggMethod config.AggregationMethod, observations []*encoding.ProcessedRequest) (*encoding.ProcessedRequest, error) { if len(observations) == 0 { - return nil, fmt.Errorf("empty observation list passed for aggregation") + return nil, errors.New("empty observation list passed for aggregation") } var errored []*encoding.ProcessedRequest var successful []*encoding.ProcessedRequest diff --git a/core/services/ocr2/plugins/functions/encoding/abi_codec.go b/core/services/ocr2/plugins/functions/encoding/abi_codec.go index bbf624d4b29..a4c5e0e762a 100644 --- a/core/services/ocr2/plugins/functions/encoding/abi_codec.go +++ b/core/services/ocr2/plugins/functions/encoding/abi_codec.go @@ -41,11 +41,11 @@ func SliceToByte32(slice []byte) ([32]byte, error) { func getReportTypesV1() (abi.Arguments, error) { bytes32ArrType, err := abi.NewType("bytes32[]", "", []abi.ArgumentMarshaling{}) if err != nil { - return nil, fmt.Errorf("unable to create an ABI type object for bytes32[]") + return nil, errors.New("unable to create an ABI type object for bytes32[]") } bytesArrType, err := abi.NewType("bytes[]", "", []abi.ArgumentMarshaling{}) if err != nil { - return nil, fmt.Errorf("unable to create an ABI type object for bytes[]") + return nil, errors.New("unable to create an ABI type object for bytes[]") } return abi.Arguments([]abi.Argument{ {Name: "ids", Type: bytes32ArrType}, diff --git a/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go b/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go index 98aea240134..d4bdc9c4bca 100644 --- a/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go +++ b/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go @@ -508,10 +508,10 @@ func mockEALambdaExecutionResponse(t *testing.T, request map[string]any) []byte require.Equal(t, functions.LocationInline, int(data["codeLocation"].(float64))) if len(request["nodeProvidedSecrets"].(string)) > 0 { require.Equal(t, functions.LocationRemote, int(data["secretsLocation"].(float64))) - require.Equal(t, fmt.Sprintf(`{"0x0":"%s"}`, DefaultSecretsBase64), request["nodeProvidedSecrets"].(string)) + require.JSONEq(t, fmt.Sprintf(`{"0x0":"%s"}`, DefaultSecretsBase64), request["nodeProvidedSecrets"].(string)) } args := data["args"].([]interface{}) - require.Equal(t, 2, len(args)) + require.Len(t, args, 2) require.Equal(t, DefaultArg1, args[0].(string)) require.Equal(t, DefaultArg2, args[1].(string)) source := data["source"].(string) diff --git a/core/services/ocr2/plugins/functions/reporting_test.go b/core/services/ocr2/plugins/functions/reporting_test.go index 581e2de70b0..b0b07f502f8 100644 --- a/core/services/ocr2/plugins/functions/reporting_test.go +++ b/core/services/ocr2/plugins/functions/reporting_test.go @@ -143,7 +143,7 @@ func TestFunctionsReporting_Query(t *testing.T) { queryProto := &encoding.Query{} err = proto.Unmarshal(q, queryProto) require.NoError(t, err) - require.Equal(t, 2, len(queryProto.RequestIDs)) + require.Len(t, queryProto.RequestIDs, 2) require.Equal(t, reqs[0].RequestID[:], queryProto.RequestIDs[0]) require.Equal(t, reqs[1].RequestID[:], queryProto.RequestIDs[1]) } @@ -163,7 +163,7 @@ func TestFunctionsReporting_Query_HandleCoordinatorMismatch(t *testing.T) { queryProto := &encoding.Query{} err = proto.Unmarshal(q, queryProto) require.NoError(t, err) - require.Equal(t, 1, len(queryProto.RequestIDs)) + require.Len(t, queryProto.RequestIDs, 1) require.Equal(t, reqs[0].RequestID[:], queryProto.RequestIDs[0]) // reqs[1] should be excluded from this query because it has a different coordinator address } @@ -196,7 +196,7 @@ func TestFunctionsReporting_Observation(t *testing.T) { observationProto := &encoding.Observation{} err = proto.Unmarshal(obs, observationProto) require.NoError(t, err) - require.Equal(t, len(observationProto.ProcessedRequests), 2) + require.Len(t, observationProto.ProcessedRequests, 2) require.Equal(t, observationProto.ProcessedRequests[0].RequestID, req1.RequestID[:]) require.Equal(t, observationProto.ProcessedRequests[0].Result, []byte("abc")) require.Equal(t, observationProto.ProcessedRequests[1].RequestID, req3.RequestID[:]) @@ -225,7 +225,7 @@ func TestFunctionsReporting_Observation_IncorrectQuery(t *testing.T) { observationProto := &encoding.Observation{} err = proto.Unmarshal(obs, observationProto) require.NoError(t, err) - require.Equal(t, len(observationProto.ProcessedRequests), 1) + require.Len(t, observationProto.ProcessedRequests, 1) require.Equal(t, observationProto.ProcessedRequests[0].RequestID, req1.RequestID[:]) require.Equal(t, observationProto.ProcessedRequests[0].Result, []byte("abc")) } @@ -258,7 +258,7 @@ func TestFunctionsReporting_Report(t *testing.T) { decoded, err := codec.DecodeReport(reportBytes) require.NoError(t, err) - require.Equal(t, 2, len(decoded)) + require.Len(t, decoded, 2) require.Equal(t, reqId1[:], decoded[0].RequestID) require.Equal(t, compResult, decoded[0].Result) require.Equal(t, []byte{}, decoded[0].Error) @@ -291,7 +291,7 @@ func TestFunctionsReporting_Report_WithGasLimitAndMetadata(t *testing.T) { decoded, err := codec.DecodeReport(reportBytes) require.NoError(t, err) - require.Equal(t, 2, len(decoded)) + require.Len(t, decoded, 2) require.Equal(t, reqId1[:], decoded[0].RequestID) require.Equal(t, compResult, decoded[0].Result) @@ -331,7 +331,7 @@ func TestFunctionsReporting_Report_HandleCoordinatorMismatch(t *testing.T) { decoded, err := codec.DecodeReport(reportBytes) require.NoError(t, err) - require.Equal(t, 2, len(decoded)) + require.Len(t, decoded, 2) require.Equal(t, reqId1[:], decoded[0].RequestID) require.Equal(t, reqId3[:], decoded[1].RequestID) @@ -362,7 +362,7 @@ func TestFunctionsReporting_Report_CallbackGasLimitExceeded(t *testing.T) { decoded, err := codec.DecodeReport(reportBytes) require.NoError(t, err) // Gas limit is set to 200k per report so we can only fit the first request - require.Equal(t, 1, len(decoded)) + require.Len(t, decoded, 1) require.Equal(t, reqId1[:], decoded[0].RequestID) require.Equal(t, compResult, decoded[0].Result) require.Equal(t, []byte{}, decoded[0].Error) @@ -395,7 +395,7 @@ func TestFunctionsReporting_Report_DeterministicOrderOfRequests(t *testing.T) { decoded, err := codec.DecodeReport(reportBytes1) require.NoError(t, err) - require.Equal(t, 3, len(decoded)) + require.Len(t, decoded, 3) } func TestFunctionsReporting_Report_IncorrectObservation(t *testing.T) { diff --git a/core/services/ocr2/plugins/generic/relayerset_test.go b/core/services/ocr2/plugins/generic/relayerset_test.go index cd9d28ffd60..7a1123f455b 100644 --- a/core/services/ocr2/plugins/generic/relayerset_test.go +++ b/core/services/ocr2/plugins/generic/relayerset_test.go @@ -27,12 +27,12 @@ func TestRelayerSet_List(t *testing.T) { relayers, err := relayerSet.List(context.Background()) assert.NoError(t, err) - assert.Equal(t, len(relayers), 3) + assert.Len(t, relayers, 3) relayers, err = relayerSet.List(context.Background(), types.RelayID{Network: "N1", ChainID: "C1"}, types.RelayID{Network: "N3", ChainID: "C3"}) assert.NoError(t, err) - assert.Equal(t, len(relayers), 2) + assert.Len(t, relayers, 2) _, ok := relayers[types.RelayID{Network: "N1", ChainID: "C1"}] assert.True(t, ok) @@ -56,7 +56,7 @@ func TestRelayerSet_Get(t *testing.T) { assert.NoError(t, err) _, err = relayerSet.Get(context.Background(), types.RelayID{Network: "N4", ChainID: "C4"}) - assert.NotNil(t, err) + assert.Error(t, err) } func TestRelayerSet_NewPluginProvider(t *testing.T) { diff --git a/core/services/ocr2/plugins/llo/config/config.go b/core/services/ocr2/plugins/llo/config/config.go index ca272b73d55..7baf729b405 100644 --- a/core/services/ocr2/plugins/llo/config/config.go +++ b/core/services/ocr2/plugins/llo/config/config.go @@ -104,7 +104,7 @@ func validateURL(rawServerURL string) error { if schemeRegexp.MatchString(rawServerURL) { normalizedURI = rawServerURL } else { - normalizedURI = fmt.Sprintf("wss://%s", rawServerURL) + normalizedURI = "wss://" + rawServerURL } uri, err := url.ParseRequestURI(normalizedURI) if err != nil { diff --git a/core/services/ocr2/plugins/llo/helpers_test.go b/core/services/ocr2/plugins/llo/helpers_test.go index 9cd8742ffa8..0b22ef7cdb5 100644 --- a/core/services/ocr2/plugins/llo/helpers_test.go +++ b/core/services/ocr2/plugins/llo/helpers_test.go @@ -336,7 +336,7 @@ func createBridge(t *testing.T, name string, i int, p decimal.Decimal, borm brid bridge := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { b, err := io.ReadAll(req.Body) require.NoError(t, err) - require.Equal(t, `{"data":{"data":"foo"}}`, string(b)) + require.JSONEq(t, `{"data":{"data":"foo"}}`, string(b)) res.WriteHeader(http.StatusOK) val := p.String() diff --git a/core/services/ocr2/plugins/llo/integration_test.go b/core/services/ocr2/plugins/llo/integration_test.go index 0491c29b39c..fd0ecc81e0f 100644 --- a/core/services/ocr2/plugins/llo/integration_test.go +++ b/core/services/ocr2/plugins/llo/integration_test.go @@ -844,7 +844,7 @@ func setupNodes(t *testing.T, nNodes int, backend evmtypes.Backend, clientCSAKey oracles = append(oracles, confighelper.OracleIdentityExtra{ OracleIdentity: confighelper.OracleIdentity{ OnchainPublicKey: offchainPublicKey, - TransmitAccount: ocr2types.Account(fmt.Sprintf("%x", transmitter[:])), + TransmitAccount: ocr2types.Account(hex.EncodeToString(transmitter[:])), OffchainPublicKey: kb.OffchainPublicKey(), PeerID: peerID, }, diff --git a/core/services/ocr2/plugins/llo/onchain_channel_definition_cache_integration_test.go b/core/services/ocr2/plugins/llo/onchain_channel_definition_cache_integration_test.go index e94301cf98d..e2f89cab758 100644 --- a/core/services/ocr2/plugins/llo/onchain_channel_definition_cache_integration_test.go +++ b/core/services/ocr2/plugins/llo/onchain_channel_definition_cache_integration_test.go @@ -2,6 +2,7 @@ package llo_test import ( "bytes" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -269,7 +270,7 @@ func Test_ChannelDefinitionCache_Integration(t *testing.T) { assert.Equal(t, uint32(3), fields["version"]) assert.Equal(t, "http://example.com/foo3", fields["url"]) - assert.Equal(t, fmt.Sprintf("%x", sampleDefinitionsSHA), fields["sha"]) + assert.Equal(t, hex.EncodeToString(sampleDefinitionsSHA[:]), fields["sha"]) assert.Equal(t, donID, fields["donID"]) assert.Equal(t, sampleDefinitions, cdc.Definitions()) @@ -352,7 +353,7 @@ func Test_ChannelDefinitionCache_Integration(t *testing.T) { assert.Equal(t, uint32(5), fields["version"]) assert.Equal(t, "http://example.com/foo5", fields["url"]) - assert.Equal(t, fmt.Sprintf("%x", sampleDefinitionsSHA), fields["sha"]) + assert.Equal(t, hex.EncodeToString(sampleDefinitionsSHA[:]), fields["sha"]) assert.Equal(t, donID, fields["donID"]) assert.Equal(t, sampleDefinitions, cdc.Definitions()) diff --git a/core/services/ocr2/plugins/median/config/config_test.go b/core/services/ocr2/plugins/median/config/config_test.go index 544258eebcf..9bb850448be 100644 --- a/core/services/ocr2/plugins/median/config/config_test.go +++ b/core/services/ocr2/plugins/median/config/config_test.go @@ -1,7 +1,7 @@ package config import ( - "fmt" + "errors" "testing" "time" @@ -20,9 +20,9 @@ func TestValidatePluginConfig(t *testing.T) { t.Run("pipeline validation", func(t *testing.T) { for _, tc := range []testCase{ - {"empty pipeline", "", models.Interval(time.Minute), fmt.Errorf("invalid juelsPerFeeCoinSource pipeline: empty pipeline")}, - {"blank pipeline", " ", models.Interval(time.Minute), fmt.Errorf("invalid juelsPerFeeCoinSource pipeline: empty pipeline")}, - {"foo pipeline", "foo", models.Interval(time.Minute), fmt.Errorf("invalid juelsPerFeeCoinSource pipeline: UnmarshalTaskFromMap: unknown task type: \"\"")}, + {"empty pipeline", "", models.Interval(time.Minute), errors.New("invalid juelsPerFeeCoinSource pipeline: empty pipeline")}, + {"blank pipeline", " ", models.Interval(time.Minute), errors.New("invalid juelsPerFeeCoinSource pipeline: empty pipeline")}, + {"foo pipeline", "foo", models.Interval(time.Minute), errors.New("invalid juelsPerFeeCoinSource pipeline: UnmarshalTaskFromMap: unknown task type: \"\"")}, } { t.Run(tc.name, func(t *testing.T) { pc := PluginConfig{JuelsPerFeeCoinPipeline: tc.pipeline} @@ -33,8 +33,8 @@ func TestValidatePluginConfig(t *testing.T) { t.Run("cache duration validation", func(t *testing.T) { for _, tc := range []testCase{ - {"cache duration below minimum", `ds1 [type=bridge name=voter_turnout];`, models.Interval(time.Second * 29), fmt.Errorf("juelsPerFeeCoinSourceCache update interval: 29s is below 30 second minimum")}, - {"cache duration above maximum", `ds1 [type=bridge name=voter_turnout];`, models.Interval(time.Minute*20 + time.Second), fmt.Errorf("juelsPerFeeCoinSourceCache update interval: 20m1s is above 20 minute maximum")}, + {"cache duration below minimum", `ds1 [type=bridge name=voter_turnout];`, models.Interval(time.Second * 29), errors.New("juelsPerFeeCoinSourceCache update interval: 29s is below 30 second minimum")}, + {"cache duration above maximum", `ds1 [type=bridge name=voter_turnout];`, models.Interval(time.Minute*20 + time.Second), errors.New("juelsPerFeeCoinSourceCache update interval: 20m1s is above 20 minute maximum")}, } { t.Run(tc.name, func(t *testing.T) { pc := PluginConfig{JuelsPerFeeCoinPipeline: tc.pipeline, JuelsPerFeeCoinCache: &JuelsPerFeeCoinCache{UpdateInterval: tc.cacheDuration}} @@ -51,7 +51,7 @@ func TestValidatePluginConfig(t *testing.T) { } { t.Run(s.name, func(t *testing.T) { pc := PluginConfig{JuelsPerFeeCoinPipeline: s.pipeline} - assert.Nil(t, pc.ValidatePluginConfig()) + assert.NoError(t, pc.ValidatePluginConfig()) }) } }) diff --git a/core/services/ocr2/plugins/mercury/config/config.go b/core/services/ocr2/plugins/mercury/config/config.go index 40854bd8c0a..55321f60878 100644 --- a/core/services/ocr2/plugins/mercury/config/config.go +++ b/core/services/ocr2/plugins/mercury/config/config.go @@ -45,7 +45,7 @@ func validateURL(rawServerURL string) error { if schemeRegexp.MatchString(rawServerURL) { normalizedURI = rawServerURL } else { - normalizedURI = fmt.Sprintf("wss://%s", rawServerURL) + normalizedURI = "wss://" + rawServerURL } uri, err := url.ParseRequestURI(normalizedURI) if err != nil { diff --git a/core/services/ocr2/plugins/mercury/integration_test.go b/core/services/ocr2/plugins/mercury/integration_test.go index a8039768d2d..b39b11ff584 100644 --- a/core/services/ocr2/plugins/mercury/integration_test.go +++ b/core/services/ocr2/plugins/mercury/integration_test.go @@ -12,6 +12,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "strconv" "strings" "sync/atomic" "testing" @@ -224,7 +225,7 @@ func integration_MercuryV1(t *testing.T) { oracles = append(oracles, confighelper.OracleIdentityExtra{ OracleIdentity: confighelper.OracleIdentity{ OnchainPublicKey: offchainPublicKey, - TransmitAccount: ocr2types.Account(fmt.Sprintf("%x", transmitter[:])), + TransmitAccount: ocr2types.Account(hex.EncodeToString(transmitter[:])), OffchainPublicKey: kb.OffchainPublicKey(), PeerID: peerID, }, @@ -241,7 +242,7 @@ func integration_MercuryV1(t *testing.T) { bridge := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { b, herr := io.ReadAll(req.Body) require.NoError(t, herr) - require.Equal(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) + require.JSONEq(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) r := rand.Int63n(101) if r > pError.Load() { @@ -405,7 +406,7 @@ func integration_MercuryV1(t *testing.T) { assert.GreaterOrEqual(t, currentBlock.Time(), reportElems["currentBlockTimestamp"].(uint64)) assert.NotEqual(t, common.Hash{}, common.Hash(reportElems["currentBlockHash"].([32]uint8))) assert.LessOrEqual(t, int(reportElems["validFromBlockNum"].(uint64)), int(reportElems["currentBlockNum"].(uint64))) - assert.Less(t, int64(0), int64(reportElems["validFromBlockNum"].(uint64))) + assert.Positive(t, reportElems["validFromBlockNum"].(uint64)) t.Logf("oracle %x reported for feed %s (0x%x)", req.pk, feed.name, feed.id) @@ -581,7 +582,7 @@ func integration_MercuryV2(t *testing.T) { oracles = append(oracles, confighelper.OracleIdentityExtra{ OracleIdentity: confighelper.OracleIdentity{ OnchainPublicKey: offchainPublicKey, - TransmitAccount: ocr2types.Account(fmt.Sprintf("%x", transmitter[:])), + TransmitAccount: ocr2types.Account(hex.EncodeToString(transmitter[:])), OffchainPublicKey: kb.OffchainPublicKey(), PeerID: peerID, }, @@ -598,7 +599,7 @@ func integration_MercuryV2(t *testing.T) { bridge := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { b, herr := io.ReadAll(req.Body) require.NoError(t, herr) - require.Equal(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) + require.JSONEq(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) r := rand.Int63n(101) if r > pError.Load() { @@ -871,7 +872,7 @@ func integration_MercuryV3(t *testing.T) { oracles = append(oracles, confighelper.OracleIdentityExtra{ OracleIdentity: confighelper.OracleIdentity{ OnchainPublicKey: offchainPublicKey, - TransmitAccount: ocr2types.Account(fmt.Sprintf("%x", transmitter[:])), + TransmitAccount: ocr2types.Account(hex.EncodeToString(transmitter[:])), OffchainPublicKey: kb.OffchainPublicKey(), PeerID: peerID, }, @@ -888,7 +889,7 @@ func integration_MercuryV3(t *testing.T) { bridge := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { b, herr := io.ReadAll(req.Body) require.NoError(t, herr) - require.Equal(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) + require.JSONEq(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) r := rand.Int63n(101) if r > pError.Load() { @@ -1167,7 +1168,7 @@ func integration_MercuryV4(t *testing.T) { oracles = append(oracles, confighelper.OracleIdentityExtra{ OracleIdentity: confighelper.OracleIdentity{ OnchainPublicKey: offchainPublicKey, - TransmitAccount: ocr2types.Account(fmt.Sprintf("%x", transmitter[:])), + TransmitAccount: ocr2types.Account(hex.EncodeToString(transmitter[:])), OffchainPublicKey: kb.OffchainPublicKey(), PeerID: peerID, }, @@ -1184,7 +1185,7 @@ func integration_MercuryV4(t *testing.T) { bridge := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { b, herr := io.ReadAll(req.Body) require.NoError(t, herr) - require.Equal(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) + require.JSONEq(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) r := rand.Int63n(101) if r > pError.Load() { @@ -1194,7 +1195,7 @@ func integration_MercuryV4(t *testing.T) { if p != nil { val = decimal.NewFromBigInt(p, 0).Div(decimal.NewFromInt(multiplier)).Add(decimal.NewFromInt(int64(i)).Div(decimal.NewFromInt(100))).String() } else { - val = fmt.Sprintf("%d", marketStatus) + val = strconv.FormatUint(uint64(marketStatus), 10) } resp := fmt.Sprintf(`{"result": %s}`, val) diff --git a/core/services/ocr2/plugins/mercury/plugin.go b/core/services/ocr2/plugins/mercury/plugin.go index b0983e55c89..7608bcf7cd2 100644 --- a/core/services/ocr2/plugins/mercury/plugin.go +++ b/core/services/ocr2/plugins/mercury/plugin.go @@ -83,7 +83,7 @@ func NewServices( var pluginConfig config.PluginConfig if len(jb.OCR2OracleSpec.PluginConfig) == 0 { if !enableTriggerCapability { - return nil, fmt.Errorf("at least one transmission option must be configured") + return nil, errors.New("at least one transmission option must be configured") } } else { err := json.Unmarshal(jb.OCR2OracleSpec.PluginConfig.Bytes(), &pluginConfig) diff --git a/core/services/ocr2/plugins/ocr2keeper/config.go b/core/services/ocr2/plugins/ocr2keeper/config.go index ec56f9c6993..e339f80bb27 100644 --- a/core/services/ocr2/plugins/ocr2keeper/config.go +++ b/core/services/ocr2/plugins/ocr2keeper/config.go @@ -2,7 +2,7 @@ package ocr2keeper import ( "encoding/json" - "fmt" + "errors" "time" ) @@ -64,23 +64,23 @@ type PluginConfig struct { func ValidatePluginConfig(cfg PluginConfig) error { if cfg.CacheExpiration < 0 { - return fmt.Errorf("cache expiration cannot be less than zero") + return errors.New("cache expiration cannot be less than zero") } if cfg.CacheEvictionInterval < 0 { - return fmt.Errorf("cache eviction interval cannot be less than zero") + return errors.New("cache eviction interval cannot be less than zero") } if cfg.CacheEvictionInterval > 0 && cfg.CacheEvictionInterval.Value() < time.Second { - return fmt.Errorf("cache eviction interval should be more than every second") + return errors.New("cache eviction interval should be more than every second") } if cfg.MaxServiceWorkers < 0 { - return fmt.Errorf("max service workers cannot be less than zero") + return errors.New("max service workers cannot be less than zero") } if cfg.ServiceQueueLength < 0 { - return fmt.Errorf("service queue length cannot be less than zero") + return errors.New("service queue length cannot be less than zero") } return nil diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/abi.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/abi.go index 98aeed66787..4e227f411f9 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/abi.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/abi.go @@ -1,6 +1,7 @@ package evm import ( + "errors" "fmt" "math/big" "strings" @@ -157,7 +158,7 @@ func (rp *evmRegistryPackerV2_0) UnpackTransmitTxInput(raw []byte) ([]ocr2keeper } if b, ok = out[1].([]byte); !ok { - return nil, fmt.Errorf("unexpected value type in transaction") + return nil, errors.New("unexpected value type in transaction") } if decoded, err = enc.DecodeReport(b); err != nil { diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/abi_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/abi_test.go index 7bbbf4d7e32..ebf8bf5b1a3 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/abi_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/abi_test.go @@ -17,22 +17,22 @@ import ( func TestUnpackTransmitTxInput(t *testing.T) { registryABI, err := abi.JSON(strings.NewReader(keeper_registry_wrapper2_0.KeeperRegistryABI)) - assert.Nil(t, err) + assert.NoError(t, err) packer := &evmRegistryPackerV2_0{abi: registryABI} decodedReport, err := packer.UnpackTransmitTxInput(hexutil.MustDecode("0x00011a04d404e571ead64b2f08cfae623a0d96b9beb326c20e322001cbbd344700000000000000000000000000000000000000000000000000000000000d580e35681c68a0426c30f4686e837c0cd7864200f48dbfe48c80c51f92aa5ac607b300000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000002e00000000000000000000000000000000000000000000000000000000000000360000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000000000773594000000000000000000000000000000000000000000000000000010fb9cd2f34a00000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000001de1256139081c6b165a3aee0432f605d3dee0e6087ea53b46ca9478c253ea9c8000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000827075c4bacd41884f60c2ca7af3630400bedd92ad7ad0ba4e1f000e70297de0573e180000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000a8c0000000000000000000000000000000000000000000000000000000000086470000000000000000000000000000000000000000000000000000000000000000326e2b521089d44f1457ae51b3f8d76e8577e08c4af9374bdc62aebbfad081a78a13941ab209ad44a905ee0fd704a46b2ebc022dcb60659bed87342fd94dadb70827af523f59c7c9bb8dcc77e959b0476869612e8cf84e63a2e9a5617290633f70000000000000000000000000000000000000000000000000000000000000003723d77998618c5959396115fc61380215e0395f68c18a6cf0647c3e759ee013040c2967fdd369aac59b464f931dacd7b8863498757eda53a9f6a4b6150f2dbe640771f3c242c297265c36c5e78f4c660ae74dcd1f5bda8687b6afed3d3f27e0d")) - assert.Nil(t, err) + assert.NoError(t, err) // We expect one upkeep ID in the report at block number var expectedBlock uint32 = 8548469 expectedID, _ := new(big.Int).SetString("100445849710294316610676143149039812931260394722330855891004881602834541226440", 10) - assert.Equal(t, len(decodedReport), 1) + assert.Len(t, decodedReport, 1) rpt, ok := decodedReport[0].(EVMAutomationUpkeepResult20) assert.True(t, ok) - assert.Equal(t, rpt.Block, expectedBlock) + assert.Equal(t, expectedBlock, rpt.Block) assert.Equal(t, rpt.ID.String(), expectedID.String()) } @@ -53,11 +53,11 @@ func TestUnpackTransmitTxInputErrors(t *testing.T) { for _, test := range tests { t.Run(test.Name, func(t *testing.T) { abi, err := abi.JSON(strings.NewReader(keeper_registry_wrapper2_0.KeeperRegistryABI)) - assert.Nil(t, err) + assert.NoError(t, err) packer := &evmRegistryPackerV2_0{abi: abi} _, err = packer.UnpackTransmitTxInput(hexutil.MustDecode(test.RawData)) - assert.NotNil(t, err) + assert.Error(t, err) }) } } @@ -65,7 +65,7 @@ func TestUnpackTransmitTxInputErrors(t *testing.T) { func TestUnpackCheckResults(t *testing.T) { registryABI, err := abi.JSON(strings.NewReader(keeper_registry_wrapper2_0.KeeperRegistryABI)) if err != nil { - assert.Nil(t, err) + assert.NoError(t, err) } upkeepId, _ := new(big.Int).SetString("1843548457736589226156809205796175506139185429616502850435279853710366065936", 10) @@ -117,7 +117,7 @@ func TestUnpackCheckResults(t *testing.T) { t.Run(test.Name, func(t *testing.T) { packer := &evmRegistryPackerV2_0{abi: registryABI} rs, err := packer.UnpackCheckResult(test.UpkeepKey, test.RawData) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, test.ExpectedResult, rs) }) } @@ -126,7 +126,7 @@ func TestUnpackCheckResults(t *testing.T) { func TestUnpackPerformResult(t *testing.T) { registryABI, err := abi.JSON(strings.NewReader(keeper_registry_wrapper2_0.KeeperRegistryABI)) if err != nil { - assert.Nil(t, err) + assert.NoError(t, err) } tests := []struct { @@ -142,7 +142,7 @@ func TestUnpackPerformResult(t *testing.T) { t.Run(test.Name, func(t *testing.T) { packer := &evmRegistryPackerV2_0{abi: registryABI} rs, err := packer.UnpackPerformResult(test.RawData) - assert.Nil(t, err) + assert.NoError(t, err) assert.True(t, rs) }) } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/encoder.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/encoder.go index aa98fd44cec..b5a3f55e07e 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/encoder.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/encoder.go @@ -1,6 +1,7 @@ package evm import ( + "errors" "fmt" "math/big" "reflect" @@ -24,7 +25,7 @@ var ( {Name: "performData", Type: "bytes"}, } PerformDataArr, _ = abi.NewType("tuple(uint32,bytes32,bytes)[]", "", PerformDataMarshalingArgs) - ErrUnexpectedResult = fmt.Errorf("unexpected result struct") + ErrUnexpectedResult = errors.New("unexpected result struct") packFn = reportArgs.Pack unpackIntoMapFn = reportArgs.UnpackIntoMap mKeys = []string{"fastGasWei", "linkNative", "upkeepIds", "wrappedPerformDatas"} @@ -70,7 +71,7 @@ func (enc EVMAutomationEncoder20) EncodeReport(toReport []ocr2keepers.UpkeepResu for i, result := range toReport { res, ok := result.(EVMAutomationUpkeepResult20) if !ok { - return nil, fmt.Errorf("unexpected upkeep result struct") + return nil, errors.New("unexpected upkeep result struct") } // only take these values from the first result @@ -118,7 +119,7 @@ func (enc EVMAutomationEncoder20) DecodeReport(report []byte) ([]ocr2keepers.Upk ) if upkeepIds, ok = m[mKeys[2]].([]*big.Int); !ok { - return res, fmt.Errorf("upkeep ids of incorrect type in report") + return res, errors.New("upkeep ids of incorrect type in report") } // TODO: a type assertion on `wrappedPerform` did not work, even with the @@ -134,19 +135,19 @@ func (enc EVMAutomationEncoder20) DecodeReport(report []byte) ([]ocr2keepers.Upk }) if !ok { - return res, fmt.Errorf("performs of incorrect structure in report") + return res, errors.New("performs of incorrect structure in report") } if len(upkeepIds) != len(performs) { - return res, fmt.Errorf("upkeep ids and performs should have matching length") + return res, errors.New("upkeep ids and performs should have matching length") } if wei, ok = m[mKeys[0]].(*big.Int); !ok { - return res, fmt.Errorf("fast gas as wrong type") + return res, errors.New("fast gas as wrong type") } if link, ok = m[mKeys[1]].(*big.Int); !ok { - return res, fmt.Errorf("link native as wrong type") + return res, errors.New("link native as wrong type") } res = make([]ocr2keepers.UpkeepResult, len(upkeepIds)) @@ -173,7 +174,7 @@ func (enc EVMAutomationEncoder20) Eligible(result ocr2keepers.UpkeepResult) (boo res, ok := result.(EVMAutomationUpkeepResult20) if !ok { tp := reflect.TypeOf(result) - return false, fmt.Errorf("%s: name: %s, kind: %s", ErrUnexpectedResult, tp.Name(), tp.Kind()) + return false, fmt.Errorf("%w: name: %s, kind: %s", ErrUnexpectedResult, tp.Name(), tp.Kind()) } return res.Eligible, nil @@ -200,7 +201,7 @@ func (enc EVMAutomationEncoder20) KeysFromReport(b []byte) ([]ocr2keepers.Upkeep for _, result := range results { res, ok := result.(EVMAutomationUpkeepResult20) if !ok { - return nil, fmt.Errorf("unexpected result struct") + return nil, errors.New("unexpected result struct") } str := fmt.Sprintf("%d%s%s", res.Block, separator, res.ID) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/encoder_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/encoder_test.go index f77b823bb36..86433516b96 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/encoder_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/encoder_test.go @@ -15,7 +15,7 @@ func TestEVMAutomationEncoder20(t *testing.T) { t.Run("encoding an empty list of upkeep results returns a nil byte array", func(t *testing.T) { b, err := encoder.EncodeReport([]ocr2keepers.UpkeepResult{}) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, b, []byte(nil)) }) @@ -39,12 +39,12 @@ func TestEVMAutomationEncoder20(t *testing.T) { ExecuteGas: 10, } b, err := encoder.EncodeReport([]ocr2keepers.UpkeepResult{upkeepResult}) - assert.Nil(t, err) + assert.NoError(t, err) assert.Len(t, b, 416) t.Run("successfully decodes a report with a single upkeep result", func(t *testing.T) { upkeeps, err := encoder.DecodeReport(b) - assert.Nil(t, err) + assert.NoError(t, err) assert.Len(t, upkeeps, 1) upkeep := upkeeps[0].(EVMAutomationUpkeepResult20) @@ -71,7 +71,7 @@ func TestEVMAutomationEncoder20(t *testing.T) { upkeeps, err := encoder.DecodeReport(b) assert.Error(t, err, "failed to unpack into map") - assert.Len(t, upkeeps, 0) + assert.Empty(t, upkeeps) }) t.Run("an error is returned when an expected key is missing from the map", func(t *testing.T) { @@ -83,7 +83,7 @@ func TestEVMAutomationEncoder20(t *testing.T) { upkeeps, err := encoder.DecodeReport(b) assert.Error(t, err, "decoding error") - assert.Len(t, upkeeps, 0) + assert.Empty(t, upkeeps) }) t.Run("an error is returned when the third element of the map is not a slice of big.Int", func(t *testing.T) { @@ -95,7 +95,7 @@ func TestEVMAutomationEncoder20(t *testing.T) { upkeeps, err := encoder.DecodeReport(b) assert.Error(t, err, "upkeep ids of incorrect type in report") - assert.Len(t, upkeeps, 0) + assert.Empty(t, upkeeps) }) t.Run("an error is returned when the fourth element of the map is not a struct of perform data", func(t *testing.T) { @@ -107,7 +107,7 @@ func TestEVMAutomationEncoder20(t *testing.T) { upkeeps, err := encoder.DecodeReport(b) assert.Error(t, err, "performs of incorrect structure in report") - assert.Len(t, upkeeps, 0) + assert.Empty(t, upkeeps) }) t.Run("an error is returned when the upkeep ids and performDatas are of different lengths", func(t *testing.T) { @@ -135,7 +135,7 @@ func TestEVMAutomationEncoder20(t *testing.T) { upkeeps, err := encoder.DecodeReport(b) assert.Error(t, err, "upkeep ids and performs should have matching length") - assert.Len(t, upkeeps, 0) + assert.Empty(t, upkeeps) }) t.Run("an error is returned when the first element of the map is not a big int", func(t *testing.T) { @@ -147,7 +147,7 @@ func TestEVMAutomationEncoder20(t *testing.T) { upkeeps, err := encoder.DecodeReport(b) assert.Error(t, err, "fast gas as wrong type") - assert.Len(t, upkeeps, 0) + assert.Empty(t, upkeeps) }) t.Run("an error is returned when the second element of the map is not a big int", func(t *testing.T) { @@ -159,7 +159,7 @@ func TestEVMAutomationEncoder20(t *testing.T) { upkeeps, err := encoder.DecodeReport(b) assert.Error(t, err, "link native as wrong type") - assert.Len(t, upkeeps, 0) + assert.Empty(t, upkeeps) }) }) @@ -189,7 +189,7 @@ func TestEVMAutomationEncoder20(t *testing.T) { ExecuteGas: 20, } b, err := encoder.EncodeReport([]ocr2keepers.UpkeepResult{upkeepResult0, upkeepResult1}) - assert.Nil(t, err) + assert.NoError(t, err) assert.Len(t, b, 640) }) @@ -216,6 +216,6 @@ func TestEVMAutomationEncoder20(t *testing.T) { } b, err := encoder.EncodeReport([]ocr2keepers.UpkeepResult{upkeepResult0}) assert.Errorf(t, err, "pack failed: failed to pack report data") - assert.Len(t, b, 0) + assert.Empty(t, b) }) } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/head.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/head.go index 78983173558..57d4c2a8b1c 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/head.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/head.go @@ -2,7 +2,7 @@ package evm import ( "context" - "fmt" + "strconv" ocr2keepers "github.com/smartcontractkit/chainlink-automation/pkg/v2" @@ -52,5 +52,5 @@ func (w *headWrapper) OnNewLongestChain(ctx context.Context, head *evmtypes.Head bl = head.Number } - send(w.c, ocr2keepers.BlockKey(fmt.Sprintf("%d", bl))) + send(w.c, ocr2keepers.BlockKey(strconv.FormatInt(bl, 10))) } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/log_provider.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/log_provider.go index 1764fb7e7c3..7e709290ec2 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/log_provider.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/log_provider.go @@ -2,7 +2,9 @@ package evm import ( "context" + "errors" "fmt" + "strconv" "strings" "sync" "time" @@ -64,7 +66,7 @@ func NewLogProvider( abi, err := abi.JSON(strings.NewReader(registry.KeeperRegistryABI)) if err != nil { - return nil, fmt.Errorf("%w: %s", ErrABINotParsable, err) + return nil, fmt.Errorf("%w: %w", ErrABINotParsable, err) } // Add log filters for the log poller so that it can poll and find the logs that @@ -444,11 +446,11 @@ func (c *LogProvider) getCheckBlockNumberFromTxHash(ctx context.Context, txHash // TODO: the log provider should be in the evm package for isolation res, ok := upkeep.(EVMAutomationUpkeepResult20) if !ok { - return "", fmt.Errorf("unexpected type") + return "", errors.New("unexpected type") } if res.ID.String() == string(id) { - bl := fmt.Sprintf("%d", res.Block) + bl := strconv.FormatUint(uint64(res.Block), 10) c.txCheckBlockCache.Set(cacheKey, bl, pluginutils.DefaultCacheExpiration) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry.go index 9e9ac23ffeb..401424da085 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry.go @@ -2,8 +2,10 @@ package evm import ( "context" + "errors" "fmt" "math/big" + "strconv" "strings" "sync" "time" @@ -44,14 +46,14 @@ const ( ) var ( - ErrLogReadFailure = fmt.Errorf("failure reading logs") - ErrHeadNotAvailable = fmt.Errorf("head not available") - ErrRegistryCallFailure = fmt.Errorf("registry chain call failure") - ErrBlockKeyNotParsable = fmt.Errorf("block identifier not parsable") - ErrUpkeepKeyNotParsable = fmt.Errorf("upkeep key not parsable") - ErrInitializationFailure = fmt.Errorf("failed to initialize registry") - ErrContextCancelled = fmt.Errorf("context was cancelled") - ErrABINotParsable = fmt.Errorf("error parsing abi") + ErrLogReadFailure = errors.New("failure reading logs") + ErrHeadNotAvailable = errors.New("head not available") + ErrRegistryCallFailure = errors.New("registry chain call failure") + ErrBlockKeyNotParsable = errors.New("block identifier not parsable") + ErrUpkeepKeyNotParsable = errors.New("upkeep key not parsable") + ErrInitializationFailure = errors.New("failed to initialize registry") + ErrContextCancelled = errors.New("context was cancelled") + ErrABINotParsable = errors.New("error parsing abi") ActiveUpkeepIDBatchSize int64 = 1000 FetchUpkeepConfigBatchSize = 50 separator = "|" @@ -73,7 +75,7 @@ type LatestBlockGetter interface { func NewEVMRegistryService(addr common.Address, client legacyevm.Chain, lggr logger.Logger) (*EvmRegistry, error) { keeperRegistryABI, err := abi.JSON(strings.NewReader(keeper_registry_wrapper2_0.KeeperRegistryABI)) if err != nil { - return nil, fmt.Errorf("%w: %s", ErrABINotParsable, err) + return nil, fmt.Errorf("%w: %w", ErrABINotParsable, err) } registry, err := keeper_registry_wrapper2_0.NewKeeperRegistry(addr, client.Client()) @@ -319,7 +321,7 @@ func (r *EvmRegistry) initialize(ctx context.Context) error { // get active upkeep ids from contract ids, err := r.getLatestIDsFromContract(startupCtx) if err != nil { - return fmt.Errorf("failed to get ids from contract: %s", err) + return fmt.Errorf("failed to get ids from contract: %w", err) } var offset int @@ -331,7 +333,7 @@ func (r *EvmRegistry) initialize(ctx context.Context) error { actives, err := r.getUpkeepConfigs(startupCtx, ids[offset:offset+batch]) if err != nil { - return fmt.Errorf("failed to get configs for id batch (length '%d'): %s", batch, err) + return fmt.Errorf("failed to get configs for id batch (length '%d'): %w", batch, err) } for _, active := range actives { @@ -357,7 +359,7 @@ func (r *EvmRegistry) pollLogs(ctx context.Context) error { var err error if end, err = r.poller.LatestBlock(ctx); err != nil { - return fmt.Errorf("%w: %s", ErrHeadNotAvailable, err) + return fmt.Errorf("%w: %w", ErrHeadNotAvailable, err) } r.mu.Lock() @@ -379,7 +381,7 @@ func (r *EvmRegistry) pollLogs(ctx context.Context) error { upkeepStateEvents, r.addr, ); err != nil { - return fmt.Errorf("%w: %s", ErrLogReadFailure, err) + return fmt.Errorf("%w: %w", ErrLogReadFailure, err) } for _, log := range logs { @@ -485,7 +487,7 @@ func (r *EvmRegistry) getLatestIDsFromContract(ctx context.Context) ([]*big.Int, if err != nil { n := "latest" if opts.BlockNumber != nil { - n = fmt.Sprintf("%d", opts.BlockNumber.Int64()) + n = strconv.FormatInt(opts.BlockNumber.Int64(), 10) } return nil, fmt.Errorf("%w: failed to get contract state at block number '%s'", err, n) @@ -556,15 +558,15 @@ func splitKey(key ocr2keepers.UpkeepKey) (*big.Int, *big.Int, error) { parts := strings.Split(string(key), separator) if len(parts) != 2 { - return nil, nil, fmt.Errorf("unsplittable key") + return nil, nil, errors.New("unsplittable key") } if block, ok = new(big.Int).SetString(parts[0], 10); !ok { - return nil, nil, fmt.Errorf("could not get block from key") + return nil, nil, errors.New("could not get block from key") } if id, ok = new(big.Int).SetString(parts[1], 10); !ok { - return nil, nil, fmt.Errorf("could not get id from key") + return nil, nil, errors.New("could not get id from key") } return block, id, nil @@ -727,12 +729,12 @@ func (r *EvmRegistry) getUpkeepConfigs(ctx context.Context, ids []*big.Int) ([]a for i, id := range ids { opts, err := r.buildCallOpts(ctx, nil) if err != nil { - return nil, fmt.Errorf("failed to get call opts: %s", err) + return nil, fmt.Errorf("failed to get call opts: %w", err) } payload, err := r.abi.Pack("getUpkeep", id) if err != nil { - return nil, fmt.Errorf("failed to pack id with abi: %s", err) + return nil, fmt.Errorf("failed to pack id with abi: %w", err) } args := []interface{}{ @@ -757,7 +759,7 @@ func (r *EvmRegistry) getUpkeepConfigs(ctx context.Context, ids []*big.Int) ([]a } if err := r.client.BatchCallContext(ctx, uReqs); err != nil { - return nil, fmt.Errorf("rpc error: %s", err) + return nil, fmt.Errorf("rpc error: %w", err) } var ( @@ -773,7 +775,7 @@ func (r *EvmRegistry) getUpkeepConfigs(ctx context.Context, ids []*big.Int) ([]a var err error results[i], err = r.packer.UnpackUpkeepResult(ids[i], *uResults[i]) if err != nil { - return nil, fmt.Errorf("failed to unpack result: %s", err) + return nil, fmt.Errorf("failed to unpack result: %w", err) } } } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry_test.go index 8100980dd6b..945d18227a9 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v20/registry_test.go @@ -1,7 +1,7 @@ package evm import ( - "fmt" + "errors" "math/big" "testing" "time" @@ -60,7 +60,7 @@ func TestGetActiveUpkeepKeys(t *testing.T) { if test.ExpectedErr != nil { assert.ErrorIs(t, err, test.ExpectedErr) } else { - assert.Nil(t, err) + assert.NoError(t, err) } if len(test.ExpectedKeys) > 0 { @@ -100,7 +100,7 @@ func TestPollLogs(t *testing.T) { OutputErr error }{ OutputBlock: 0, - OutputErr: fmt.Errorf("test error output"), + OutputErr: errors.New("test error output"), }, }, { @@ -151,7 +151,7 @@ func TestPollLogs(t *testing.T) { InputStart: 250, InputEnd: 500, OutputLogs: []logpoller.Log{}, - OutputErr: fmt.Errorf("test output error"), + OutputErr: errors.New("test output error"), }, }, { @@ -212,7 +212,7 @@ func TestPollLogs(t *testing.T) { if test.ExpectedErr != nil { assert.ErrorIs(t, err, test.ExpectedErr) } else { - assert.Nil(t, err) + assert.NoError(t, err) } var outputLogCount int diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/autotelemetry21/custom_telemetry_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/autotelemetry21/custom_telemetry_test.go index 5fce8718cba..384a57bd631 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/autotelemetry21/custom_telemetry_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/autotelemetry21/custom_telemetry_test.go @@ -32,9 +32,9 @@ func TestNewAutomationCustomTelemetryService(t *testing.T) { t.Errorf("Expected no error, but got: %v", err) } service.monitoringEndpoint.SendLog([]byte("test")) - assert.Equal(t, me.LogCount(), 1) + assert.Equal(t, 1, me.LogCount()) service.monitoringEndpoint.SendLog([]byte("test2")) - assert.Equal(t, me.LogCount(), 2) + assert.Equal(t, 2, me.LogCount()) service.Close() } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/block_subscriber_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/block_subscriber_test.go index bdcc37dc6bb..7be330106e9 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/block_subscriber_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/block_subscriber_test.go @@ -1,11 +1,11 @@ package evm import ( - "fmt" "testing" "time" "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -33,14 +33,14 @@ func TestBlockSubscriber_Subscribe(t *testing.T) { bs.blockHistorySize = historySize bs.blockSize = blockSize subId, _, err := bs.Subscribe() - assert.Nil(t, err) - assert.Equal(t, subId, 1) + assert.NoError(t, err) + assert.Equal(t, 1, subId) subId, _, err = bs.Subscribe() - assert.Nil(t, err) - assert.Equal(t, subId, 2) + assert.NoError(t, err) + assert.Equal(t, 2, subId) subId, _, err = bs.Subscribe() - assert.Nil(t, err) - assert.Equal(t, subId, 3) + assert.NoError(t, err) + assert.Equal(t, 3, subId) } func TestBlockSubscriber_Unsubscribe(t *testing.T) { @@ -52,13 +52,13 @@ func TestBlockSubscriber_Unsubscribe(t *testing.T) { bs.blockHistorySize = historySize bs.blockSize = blockSize subId, _, err := bs.Subscribe() - assert.Nil(t, err) - assert.Equal(t, subId, 1) + assert.NoError(t, err) + assert.Equal(t, 1, subId) subId, _, err = bs.Subscribe() - assert.Nil(t, err) - assert.Equal(t, subId, 2) + assert.NoError(t, err) + assert.Equal(t, 2, subId) err = bs.Unsubscribe(1) - assert.Nil(t, err) + assert.NoError(t, err) } func TestBlockSubscriber_Unsubscribe_Failure(t *testing.T) { @@ -70,7 +70,7 @@ func TestBlockSubscriber_Unsubscribe_Failure(t *testing.T) { bs.blockHistorySize = historySize bs.blockSize = blockSize err := bs.Unsubscribe(2) - assert.Equal(t, err.Error(), "subscriber 2 does not exist") + assert.Equal(t, "subscriber 2 does not exist", err.Error()) } func TestBlockSubscriber_GetBlockRange(t *testing.T) { @@ -85,7 +85,7 @@ func TestBlockSubscriber_GetBlockRange(t *testing.T) { }{ { Name: "failed to get latest block", - LatestBlockErr: fmt.Errorf("failed to get latest block"), + LatestBlockErr: errors.New("failed to get latest block"), }, { Name: "get block range", @@ -125,7 +125,7 @@ func TestBlockSubscriber_InitializeBlocks(t *testing.T) { }{ { Name: "failed to get latest block", - Error: fmt.Errorf("failed to get log poller blocks"), + Error: errors.New("failed to get log poller blocks"), }, { Name: "get block range", @@ -305,7 +305,7 @@ func TestBlockSubscriber_Start(t *testing.T) { bs.blockHistorySize = historySize bs.blockSize = blockSize err := bs.Start(testutils.Context(t)) - assert.Nil(t, err) + assert.NoError(t, err) h97 := evmtypes.Head{ Number: 97, @@ -346,7 +346,7 @@ func TestBlockSubscriber_Start(t *testing.T) { // add 1 subscriber subId1, c1, err := bs.Subscribe() - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, 1, subId1) h101 := &evmtypes.Head{ @@ -379,7 +379,7 @@ func TestBlockSubscriber_Start(t *testing.T) { // add 2nd subscriber subId2, c2, err := bs.Subscribe() - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, 2, subId2) // re-org happens diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/payload.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/payload.go index 15f11f526ac..78dcb1b58d7 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/payload.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/payload.go @@ -2,7 +2,7 @@ package core import ( "encoding/hex" - "fmt" + "errors" "math/big" "github.com/ethereum/go-ethereum/crypto" @@ -11,7 +11,7 @@ import ( ) var ( - ErrInvalidUpkeepID = fmt.Errorf("invalid upkeepID") + ErrInvalidUpkeepID = errors.New("invalid upkeepID") ) func UpkeepWorkID(uid ocr2keepers.UpkeepIdentifier, trigger ocr2keepers.Trigger) string { diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/trigger.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/trigger.go index 1118fa736d2..7429525c6d3 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/trigger.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/trigger.go @@ -1,6 +1,7 @@ package core import ( + "errors" "fmt" "math/big" "strings" @@ -14,7 +15,7 @@ import ( type triggerWrapper = ac.IAutomationV21PlusCommonLogTrigger -var ErrABINotParsable = fmt.Errorf("error parsing abi") +var ErrABINotParsable = errors.New("error parsing abi") // PackTrigger packs the trigger data according to the upkeep type of the given id. it will remove the first 4 bytes of function selector. func PackTrigger(id *big.Int, trig triggerWrapper) ([]byte, error) { @@ -24,7 +25,7 @@ func PackTrigger(id *big.Int, trig triggerWrapper) ([]byte, error) { // construct utils abi utilsABI, err := abi.JSON(strings.NewReader(ac.AutomationCompatibleUtilsABI)) if err != nil { - return nil, fmt.Errorf("%w: %s", ErrABINotParsable, err) + return nil, fmt.Errorf("%w: %w", ErrABINotParsable, err) } // pack trigger based on upkeep type @@ -62,7 +63,7 @@ func UnpackTrigger(id *big.Int, raw []byte) (triggerWrapper, error) { // construct utils abi utilsABI, err := abi.JSON(strings.NewReader(ac.AutomationCompatibleUtilsABI)) if err != nil { - return triggerWrapper{}, fmt.Errorf("%w: %s", ErrABINotParsable, err) + return triggerWrapper{}, fmt.Errorf("%w: %w", ErrABINotParsable, err) } upkeepType, ok := getUpkeepTypeFromBigInt(id) @@ -77,7 +78,7 @@ func UnpackTrigger(id *big.Int, raw []byte) (triggerWrapper, error) { } converted, ok := abi.ConvertType(unpacked[0], new(ac.IAutomationV21PlusCommonConditionalTrigger)).(*ac.IAutomationV21PlusCommonConditionalTrigger) if !ok { - return triggerWrapper{}, fmt.Errorf("failed to convert type") + return triggerWrapper{}, errors.New("failed to convert type") } triggerW := triggerWrapper{ BlockNum: converted.BlockNum, @@ -91,7 +92,7 @@ func UnpackTrigger(id *big.Int, raw []byte) (triggerWrapper, error) { } converted, ok := abi.ConvertType(unpacked[0], new(ac.IAutomationV21PlusCommonLogTrigger)).(*ac.IAutomationV21PlusCommonLogTrigger) if !ok { - return triggerWrapper{}, fmt.Errorf("failed to convert type") + return triggerWrapper{}, errors.New("failed to convert type") } triggerW := triggerWrapper{ BlockNum: converted.BlockNum, diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/utils_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/utils_test.go index 443a639505a..079338fcd3b 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/utils_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core/utils_test.go @@ -1,7 +1,7 @@ package core import ( - "fmt" + "errors" "math/big" "testing" @@ -35,7 +35,7 @@ func TestUtils_GetTxBlock(t *testing.T) { { name: "failure - eth call error", txHash: common.HexToHash("0xc48fbf05edaf18f6aaa7de24de28528546b874bb03728d624ca407b8fed582a3"), - ethCallError: fmt.Errorf("eth call failed"), + ethCallError: errors.New("eth call failed"), }, { name: "failure - tx does not exist", diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/encoder.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/encoder.go index cbd0a7eb214..c2828a45b1e 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/encoder.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/encoder.go @@ -1,6 +1,7 @@ package encoding import ( + "errors" "fmt" "math/big" @@ -13,7 +14,7 @@ import ( ) var ( - ErrEmptyResults = fmt.Errorf("empty results; cannot encode") + ErrEmptyResults = errors.New("empty results; cannot encode") ) type reportEncoder struct { diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/encoder_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/encoder_test.go index 600dc851728..08ce0805bb0 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/encoder_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/encoder_test.go @@ -95,11 +95,11 @@ func TestReportEncoder_EncodeExtract(t *testing.T) { return } - assert.Nil(t, err) + assert.NoError(t, err) assert.Len(t, b, tc.reportSize) results, err := encoder.Extract(b) - assert.Nil(t, err) + assert.NoError(t, err) assert.Len(t, results, len(tc.results)) for i, r := range results { diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/packer.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/packer.go index dde0d24f1ba..22caf9f44d0 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/packer.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/packer.go @@ -1,6 +1,7 @@ package encoding import ( + "errors" "fmt" "math/big" @@ -34,14 +35,14 @@ func (p *abiPacker) UnpackCheckResult(payload ocr2keepers.UpkeepPayload, raw str if err != nil { // decode failed, not retryable return GetIneligibleCheckResultWithoutPerformData(payload, UpkeepFailureReasonNone, PackUnpackDecodeFailed, false), - fmt.Errorf("upkeepId %s failed to decode checkUpkeep result %s: %s", payload.UpkeepID.String(), raw, err) + fmt.Errorf("upkeepId %s failed to decode checkUpkeep result %s: %w", payload.UpkeepID.String(), raw, err) } out, err := p.autoV2CommonABI.Methods["checkUpkeep"].Outputs.UnpackValues(b) if err != nil { // unpack failed, not retryable return GetIneligibleCheckResultWithoutPerformData(payload, UpkeepFailureReasonNone, PackUnpackDecodeFailed, false), - fmt.Errorf("upkeepId %s failed to unpack checkUpkeep result %s: %s", payload.UpkeepID.String(), raw, err) + fmt.Errorf("upkeepId %s failed to unpack checkUpkeep result %s: %w", payload.UpkeepID.String(), raw, err) } result := ocr2keepers.CheckResult{ @@ -91,7 +92,7 @@ func (p *abiPacker) UnpackLogTriggerConfig(raw []byte) (ac.IAutomationV21PlusCom converted, ok := abi.ConvertType(out[0], new(ac.IAutomationV21PlusCommonLogTriggerConfig)).(*ac.IAutomationV21PlusCommonLogTriggerConfig) if !ok { - return cfg, fmt.Errorf("failed to convert type during UnpackLogTriggerConfig") + return cfg, errors.New("failed to convert type during UnpackLogTriggerConfig") } return *converted, nil } @@ -113,7 +114,7 @@ func (p *abiPacker) UnpackReport(raw []byte) (ac.IAutomationV21PlusCommonReport, } converted, ok := abi.ConvertType(unpacked[0], new(ac.IAutomationV21PlusCommonReport)).(*ac.IAutomationV21PlusCommonReport) if !ok { - return ac.IAutomationV21PlusCommonReport{}, fmt.Errorf("failed to convert type") + return ac.IAutomationV21PlusCommonReport{}, errors.New("failed to convert type") } report := ac.IAutomationV21PlusCommonReport{ FastGasWei: converted.FastGasWei, diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/packer_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/packer_test.go index 3a3cf843024..8f69264056d 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/packer_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding/packer_test.go @@ -109,7 +109,7 @@ func TestPacker_PackReport(t *testing.T) { assert.Equal(t, tc.wantErr.Error(), err.Error()) } else { assert.NoError(t, err) - assert.Equal(t, tc.wantBytes, len(bytes)) + assert.Len(t, bytes, tc.wantBytes) } }) } @@ -192,7 +192,7 @@ func TestPacker_UnpackCheckResults(t *testing.T) { if test.ExpectedError != nil { assert.Equal(t, test.ExpectedError.Error(), err.Error()) } else { - assert.Nil(t, err) + assert.NoError(t, err) } assert.Equal(t, test.ExpectedResult.UpkeepID, rs.UpkeepID) assert.Equal(t, test.ExpectedResult.Eligible, rs.Eligible) @@ -220,7 +220,7 @@ func TestPacker_UnpackPerformResult(t *testing.T) { t.Run(test.Name, func(t *testing.T) { packer := NewAbiPacker() state, rs, err := packer.UnpackPerformResult(test.RawData) - assert.Nil(t, err) + assert.NoError(t, err) assert.True(t, rs) assert.Equal(t, test.State, state) }) @@ -287,5 +287,5 @@ func TestPacker_PackReport_UnpackReport(t *testing.T) { require.NoError(t, err) assert.Equal(t, report, report2) expected := "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000002600000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000006400000000000000000000000000000000000000000000000000000000000000c800000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000040102030400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000405060708000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000004050607080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040102030400000000000000000000000000000000000000000000000000000000" - assert.Equal(t, hexutil.Encode(res), expected) + assert.Equal(t, expected, hexutil.Encode(res)) } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/block_time_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/block_time_test.go index 683ba378940..1f1795ab892 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/block_time_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/block_time_test.go @@ -1,7 +1,7 @@ package logprovider import ( - "fmt" + "errors" "testing" "time" @@ -30,11 +30,11 @@ func TestBlockTimeResolver_BlockTime(t *testing.T) { "latest block err", 10, 0, - fmt.Errorf("test err"), + errors.New("test err"), nil, nil, 0, - fmt.Errorf("test err"), + errors.New("test err"), }, { "block range err", @@ -42,9 +42,9 @@ func TestBlockTimeResolver_BlockTime(t *testing.T) { 20, nil, nil, - fmt.Errorf("test err"), + errors.New("test err"), 0, - fmt.Errorf("test err"), + errors.New("test err"), }, { "2 sec block time", diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/buffer_v1_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/buffer_v1_test.go index 4c46b9b3fea..a334f4a5183 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/buffer_v1_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/buffer_v1_test.go @@ -24,11 +24,11 @@ func TestLogEventBufferV1(t *testing.T) { logpoller.Log{BlockNumber: 2, TxHash: common.HexToHash("0x1"), LogIndex: 2}, ) results, remaining := buf.Dequeue(int64(1), 2, true) - require.Equal(t, 2, len(results)) + require.Len(t, results, 2) require.Equal(t, 2, remaining) - require.True(t, results[0].ID.Cmp(results[1].ID) != 0) + require.NotEqual(t, results[0].ID.Cmp(results[1].ID), 0) results, remaining = buf.Dequeue(int64(1), 2, true) - require.Equal(t, 0, len(results)) + require.Empty(t, results) require.Equal(t, 0, remaining) } @@ -355,7 +355,7 @@ func TestLogEventBufferV1_UpkeepQueue(t *testing.T) { require.Equal(t, 1, added) require.Equal(t, 1, q.sizeOfRange(1, 20)) logs, remaining := q.dequeue(19, 21, 10) - require.Equal(t, 1, len(logs)) + require.Len(t, logs, 1) require.Equal(t, 0, remaining) }) @@ -381,7 +381,7 @@ func TestLogEventBufferV1_UpkeepQueue(t *testing.T) { require.Equal(t, 3, added) logs, remaining := q.dequeue(19, 21, 2) - require.Equal(t, 2, len(logs)) + require.Len(t, logs, 2) require.Equal(t, 1, remaining) }) } @@ -437,7 +437,7 @@ func TestLogEventBufferV1_UpkeepQueue_clean(t *testing.T) { require.Equal(t, 2, q.sizeOfRange(1, 18)) q.lock.Lock() defer q.lock.Unlock() - require.Equal(t, 2, len(q.states)) + require.Len(t, q.states, 2) }) } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/integration_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/integration_test.go index b5bf6c2cc4a..fe0d435a5c8 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/integration_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/integration_test.go @@ -144,8 +144,8 @@ func TestIntegration_LogEventProvider_UpdateConfig(t *testing.T) { lp.PollAndSaveLogs(ctx, 1) // Ensure log poller has a latest block _, addrs, contracts := deployUpkeepCounter(ctx, t, 1, ethClient, backend, carrol, logProvider) lp.PollAndSaveLogs(ctx, int64(5)) - require.Equal(t, 1, len(contracts)) - require.Equal(t, 1, len(addrs)) + require.Len(t, contracts, 1) + require.Len(t, addrs, 1) t.Run("update filter config", func(t *testing.T) { upkeepID := evmregistry21.GenUpkeepID(types.LogTrigger, "111") diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider.go index 50b2ebc0d06..7f99db21185 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider.go @@ -30,8 +30,8 @@ import ( var ( LogProviderServiceName = "LogEventProvider" - ErrHeadNotAvailable = fmt.Errorf("head not available") - ErrBlockLimitExceeded = fmt.Errorf("block limit exceeded") + ErrHeadNotAvailable = errors.New("head not available") + ErrBlockLimitExceeded = errors.New("block limit exceeded") // AllowedLogsPerUpkeep is the maximum number of logs allowed per upkeep every single call. AllowedLogsPerUpkeep = 5 @@ -203,7 +203,7 @@ func (p *logEventProvider) HealthReport() map[string]error { func (p *logEventProvider) GetLatestPayloads(ctx context.Context) ([]ocr2keepers.UpkeepPayload, error) { latest, err := p.poller.LatestBlock(ctx) if err != nil { - return nil, fmt.Errorf("%w: %s", ErrHeadNotAvailable, err) + return nil, fmt.Errorf("%w: %w", ErrHeadNotAvailable, err) } prommetrics.AutomationLogProviderLatestBlock.Set(float64(latest.BlockNumber)) payloads := p.getLogsFromBuffer(latest.BlockNumber) @@ -308,7 +308,7 @@ func (p *logEventProvider) ReadLogs(pctx context.Context, ids ...*big.Int) error latest, err := p.poller.LatestBlock(ctx) if err != nil { - return fmt.Errorf("%w: %s", ErrHeadNotAvailable, err) + return fmt.Errorf("%w: %w", ErrHeadNotAvailable, err) } if latest.BlockNumber == 0 { return fmt.Errorf("%w: %s", ErrHeadNotAvailable, "latest block is 0") diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider_life_cycle_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider_life_cycle_test.go index 26e989c7466..1b43e9ee976 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider_life_cycle_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider_life_cycle_test.go @@ -1,7 +1,7 @@ package logprovider import ( - "fmt" + "errors" "math/big" "testing" @@ -174,7 +174,7 @@ func TestEventLogProvider_RefreshActiveUpkeeps(t *testing.T) { newIds, err := p.RefreshActiveUpkeeps(ctx) require.NoError(t, err) - require.Len(t, newIds, 0) + require.Empty(t, newIds) mp.On("HasFilter", p.filterName(core.GenUpkeepID(types.LogTrigger, "2222").BigInt())).Return(true) newIds, err = p.RefreshActiveUpkeeps( ctx, @@ -210,7 +210,7 @@ func TestLogEventProvider_ValidateLogTriggerConfig(t *testing.T) { FilterSelector: 0, Topic0: eventSig, }, - fmt.Errorf("invalid contract address: zeroed"), + errors.New("invalid contract address: zeroed"), }, { "invalid topic0", @@ -218,7 +218,7 @@ func TestLogEventProvider_ValidateLogTriggerConfig(t *testing.T) { ContractAddress: contractAddress, FilterSelector: 0, }, - fmt.Errorf("invalid topic0: zeroed"), + errors.New("invalid topic0: zeroed"), }, { "success", @@ -227,7 +227,7 @@ func TestLogEventProvider_ValidateLogTriggerConfig(t *testing.T) { FilterSelector: 8, Topic0: eventSig, }, - fmt.Errorf("invalid filter selector: larger or equal to 8"), + errors.New("invalid filter selector: larger or equal to 8"), }, } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider_test.go index 9536a24ce06..96cbdde763a 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/provider_test.go @@ -5,6 +5,7 @@ import ( "fmt" "math/big" "runtime" + "strconv" "testing" "time" @@ -31,16 +32,16 @@ func TestLogEventProvider_GetFilters(t *testing.T) { t.Run("no filters", func(t *testing.T) { filters := p.getFilters(0, big.NewInt(0)) require.Len(t, filters, 1) - require.Equal(t, len(filters[0].addr), 0) + require.Empty(t, filters[0].addr) }) t.Run("has filter with lower lastPollBlock", func(t *testing.T) { filters := p.getFilters(0, f.upkeepID) require.Len(t, filters, 1) - require.Greater(t, len(filters[0].addr), 0) + require.NotEmpty(t, filters[0].addr) filters = p.getFilters(10, f.upkeepID) require.Len(t, filters, 1) - require.Greater(t, len(filters[0].addr), 0) + require.NotEmpty(t, filters[0].addr) }) t.Run("has filter with higher lastPollBlock", func(t *testing.T) { @@ -50,7 +51,7 @@ func TestLogEventProvider_GetFilters(t *testing.T) { filters := p.getFilters(1, f.upkeepID) require.Len(t, filters, 1) - require.Equal(t, len(filters[0].addr), 0) + require.Empty(t, filters[0].addr) }) t.Run("has filter with higher configUpdateBlock", func(t *testing.T) { @@ -60,7 +61,7 @@ func TestLogEventProvider_GetFilters(t *testing.T) { filters := p.getFilters(1, f.upkeepID) require.Len(t, filters, 1) - require.Equal(t, len(filters[0].addr), 0) + require.Empty(t, filters[0].addr) }) } @@ -270,7 +271,7 @@ func TestLogEventProvider_ReadLogs(t *testing.T) { } func newEntry(p *logEventProvider, i int, args ...string) (LogTriggerConfig, upkeepFilter) { - idBytes := append(common.LeftPadBytes([]byte{1}, 16), []byte(fmt.Sprintf("%d", i))...) + idBytes := append(common.LeftPadBytes([]byte{1}, 16), []byte(strconv.Itoa(i))...) id := ocr2keepers.UpkeepIdentifier{} copy(id[:], idBytes) uid := id.BigInt() @@ -332,7 +333,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { payloads, err := provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 0, len(payloads)) + assert.Empty(t, payloads) }) t.Run("a single log for a single upkeep gets dequeued", func(t *testing.T) { @@ -354,7 +355,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { payloads, err := provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 1, len(payloads)) + assert.Len(t, payloads, 1) }) t.Run("a log per upkeep for 4 upkeeps across 4 blocks (2 separate block windows) is dequeued, for a total of 4 payloads", func(t *testing.T) { @@ -379,7 +380,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { payloads, err := provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 4, len(payloads)) + assert.Len(t, payloads, 4) }) t.Run("100 logs are dequeued for a single upkeep, 1 log for every block window across 100 blocks followed by best effort", func(t *testing.T) { @@ -405,7 +406,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { payloads, err := provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 100, len(payloads)) + assert.Len(t, payloads, 100) assert.Equal(t, 0, countRemainingLogs(buffer.queues["1"].logs)) }) @@ -435,7 +436,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { payloads, err := provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 100, len(payloads)) + assert.Len(t, payloads, 100) assert.Equal(t, 50, countRemainingLogs(buffer.queues["1"].logs)) assert.Equal(t, 50, countRemainingLogs(buffer.queues["2"].logs)) @@ -449,7 +450,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { // the second dequeue call will retrieve the remaining 100 logs and exhaust the queues payloads, err = provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 100, len(payloads)) + assert.Len(t, payloads, 100) assert.Equal(t, 0, countRemainingLogs(buffer.queues["1"].logs)) assert.Equal(t, 0, countRemainingLogs(buffer.queues["2"].logs)) @@ -486,7 +487,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { payloads, err := provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 100, len(payloads)) + assert.Len(t, payloads, 100) windowCount := remainingBlockWindowCounts(buffer.queues, 4) @@ -494,7 +495,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { payloads, err = provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 100, len(payloads)) + assert.Len(t, payloads, 100) // upkeep 1 has had the minimum number of logs dequeued on the latest (incomplete) window assert.Equal(t, 1, buffer.queues["1"].dequeued[100]) @@ -504,7 +505,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { // the third dequeue call will retrieve the remaining 100 logs and exhaust the queues payloads, err = provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 4, len(payloads)) + assert.Len(t, payloads, 4) assert.Equal(t, 0, countRemainingLogs(buffer.queues["1"].logs)) assert.Equal(t, 0, countRemainingLogs(buffer.queues["2"].logs)) @@ -545,7 +546,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { payloads, err := provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 100, len(payloads)) + assert.Len(t, payloads, 100) windowCount := remainingBlockWindowCounts(buffer.queues, 4) @@ -562,7 +563,7 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { // the second dequeue call will retrieve the remaining 100 logs and exhaust the queues payloads, err = provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 100, len(payloads)) + assert.Len(t, payloads, 100) windowCount = remainingBlockWindowCounts(buffer.queues, 4) @@ -618,11 +619,11 @@ func TestLogEventProvider_GetLatestPayloads(t *testing.T) { // perform two dequeues payloads, err := provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 100, len(payloads)) + assert.Len(t, payloads, 100) payloads, err = provider.GetLatestPayloads(ctx) assert.NoError(t, err) - assert.Equal(t, 100, len(payloads)) + assert.Len(t, payloads, 100) assert.Equal(t, 40, countRemainingLogs(buffer.queues["1"].logs)) assert.Equal(t, 10, countRemainingLogs(buffer.queues["2"].logs)) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/recoverer.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/recoverer.go index 984856bf3cd..375062867f4 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/recoverer.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/recoverer.go @@ -286,7 +286,7 @@ func (r *logRecoverer) getLogTriggerCheckData(ctx context.Context, proposal ocr2 func (r *logRecoverer) GetRecoveryProposals(ctx context.Context) ([]ocr2keepers.UpkeepPayload, error) { latestBlock, err := r.poller.LatestBlock(ctx) if err != nil { - return nil, fmt.Errorf("%w: %s", ErrHeadNotAvailable, err) + return nil, fmt.Errorf("%w: %w", ErrHeadNotAvailable, err) } r.lock.Lock() @@ -330,7 +330,7 @@ func (r *logRecoverer) GetRecoveryProposals(ctx context.Context) ([]ocr2keepers. func (r *logRecoverer) recover(ctx context.Context) error { latest, err := r.poller.LatestBlock(ctx) if err != nil { - return fmt.Errorf("%w: %s", ErrHeadNotAvailable, err) + return fmt.Errorf("%w: %w", ErrHeadNotAvailable, err) } start, offsetBlock := r.getRecoveryWindow(latest.BlockNumber) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/recoverer_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/recoverer_test.go index 65a05b2537e..28478d81f72 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/recoverer_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/recoverer_test.go @@ -2,7 +2,6 @@ package logprovider import ( "context" - "fmt" "math" "math/big" "sort" @@ -248,13 +247,13 @@ func TestLogRecoverer_Recover(t *testing.T) { "latest block error", 200, 0, - fmt.Errorf("test error"), + errors.New("test error"), []upkeepFilter{}, []ocr2keepers.UpkeepState{}, nil, []logpoller.Log{}, nil, - fmt.Errorf("test error"), + errors.New("test error"), []string{}, []int64{}, }, @@ -273,7 +272,7 @@ func TestLogRecoverer_Recover(t *testing.T) { }, }, nil, - fmt.Errorf("test error"), + errors.New("test error"), []logpoller.Log{ { BlockNumber: 2, @@ -304,7 +303,7 @@ func TestLogRecoverer_Recover(t *testing.T) { []ocr2keepers.UpkeepState{}, nil, []logpoller.Log{}, - fmt.Errorf("test error"), + errors.New("test error"), nil, []string{}, []int64{0}, @@ -437,7 +436,7 @@ func TestLogRecoverer_Recover(t *testing.T) { filters := filterStore.GetFilters(func(f upkeepFilter) bool { return f.upkeepID.String() == active.upkeepID.String() }) - require.Equal(t, 1, len(filters)) + require.Len(t, filters, 1) require.Equal(t, tc.lastRePollBlocks[i], filters[0].lastRePollBlock) } @@ -467,10 +466,10 @@ func TestLogRecoverer_SelectFilterBatch(t *testing.T) { recoverer, _, _, _ := setupTestRecoverer(t, time.Millisecond*50, int64(100)) batch := recoverer.selectFilterBatch(filters) - require.Equal(t, recoveryBatchSize, len(batch)) + require.Len(t, batch, recoveryBatchSize) batch = recoverer.selectFilterBatch(filters[:recoveryBatchSize/2]) - require.Equal(t, recoveryBatchSize/2, len(batch)) + require.Len(t, batch, recoveryBatchSize/2) } func TestLogRecoverer_getFilterBatch(t *testing.T) { @@ -516,7 +515,7 @@ func TestLogRecoverer_getFilterBatch(t *testing.T) { recoverer, filterStore, _, _ := setupTestRecoverer(t, time.Millisecond*50, int64(100)) filterStore.AddActiveUpkeeps(tc.filters...) batch := recoverer.getFilterBatch(tc.offsetBlock) - require.Equal(t, tc.want, len(batch)) + require.Len(t, batch, tc.want) }) } } @@ -1178,7 +1177,7 @@ func TestLogRecoverer_pending(t *testing.T) { } r.lock.Lock() defer r.lock.Unlock() - require.Equal(t, 0, len(r.pending)) + require.Empty(t, r.pending) }) } } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/mercury_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/mercury_test.go index 43587f3fe11..9fadd29608d 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/mercury_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/mercury_test.go @@ -144,7 +144,7 @@ func TestPacker_UnpackGetUpkeepPrivilegeConfig(t *testing.T) { assert.NoError(t, err, "packed data should unmarshal using json encoding") assert.Equal(t, []byte(`{"mercuryEnabled":true}`), b) } else { - assert.NotNil(t, err, "error expected from unpack function") + assert.Error(t, err, "error expected from unpack function") } }) } @@ -184,7 +184,7 @@ func TestPacker_PackGetUpkeepPrivilegeConfig(t *testing.T) { assert.Equal(t, test.raw, b, "raw bytes for output should match expected") } else { - assert.NotNil(t, err, "error expected from packing function") + assert.Error(t, err, "error expected from packing function") } }) } @@ -235,7 +235,7 @@ func TestPacker_UnpackCheckCallbackResult(t *testing.T) { if test.ErrorString != "" { assert.EqualError(t, err, test.ErrorString+hexutil.Encode(test.CallbackResp)) } else { - assert.Nil(t, err) + assert.NoError(t, err) } assert.Equal(t, test.UpkeepNeeded, needed) assert.Equal(t, test.PerformData, pd) @@ -278,7 +278,7 @@ func TestPacker_PackUserCheckErrorHandler(t *testing.T) { assert.Equal(t, test.rawOutput, b, "raw bytes for output should match expected") } else { - assert.NotNil(t, err, "error expected from packing function") + assert.Error(t, err, "error expected from packing function") } }) } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/streams/streams.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/streams/streams.go index 17005939219..95d5b40c175 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/streams/streams.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/streams/streams.go @@ -3,9 +3,11 @@ package streams import ( "context" "encoding/json" + "errors" "fmt" "math/big" "net/http" + "strconv" "sync" "time" @@ -329,24 +331,24 @@ func (s *streams) AllowedToUseMercury(opts *bind.CallOpts, upkeepId *big.Int) (s } if err = s.client.CallContext(opts.Context, &resultBytes, "eth_call", args, hexutil.EncodeBig(opts.BlockNumber)); err != nil { - return encoding.RpcFlakyFailure, encoding.UpkeepFailureReasonNone, true, false, fmt.Errorf("failed to get upkeep privilege config: %v", err) + return encoding.RpcFlakyFailure, encoding.UpkeepFailureReasonNone, true, false, fmt.Errorf("failed to get upkeep privilege config: %w", err) } var upkeepPrivilegeConfigBytes []byte upkeepPrivilegeConfigBytes, err = s.packer.UnpackGetUpkeepPrivilegeConfig(resultBytes) if err != nil { - return encoding.PackUnpackDecodeFailed, encoding.UpkeepFailureReasonNone, false, false, fmt.Errorf("failed to get upkeep privilege config: %v", err) + return encoding.PackUnpackDecodeFailed, encoding.UpkeepFailureReasonNone, false, false, fmt.Errorf("failed to get upkeep privilege config: %w", err) } if len(upkeepPrivilegeConfigBytes) == 0 { s.mercuryConfig.SetUpkeepAllowed(upkeepId.String(), false, cache.DefaultExpiration) - return encoding.NoPipelineError, encoding.UpkeepFailureReasonMercuryAccessNotAllowed, false, false, fmt.Errorf("upkeep privilege config is empty") + return encoding.NoPipelineError, encoding.UpkeepFailureReasonMercuryAccessNotAllowed, false, false, errors.New("upkeep privilege config is empty") } var privilegeConfig UpkeepPrivilegeConfig if err = json.Unmarshal(upkeepPrivilegeConfigBytes, &privilegeConfig); err != nil { - return encoding.PrivilegeConfigUnmarshalError, encoding.UpkeepFailureReasonNone, false, false, fmt.Errorf("failed to unmarshal privilege config: %v", err) + return encoding.PrivilegeConfigUnmarshalError, encoding.UpkeepFailureReasonNone, false, false, fmt.Errorf("failed to unmarshal privilege config: %w", err) } s.mercuryConfig.SetUpkeepAllowed(upkeepId.String(), privilegeConfig.MercuryEnabled, cache.DefaultExpiration) @@ -372,7 +374,7 @@ func (s *streams) buildCallOpts(ctx context.Context, block *big.Int) *bind.CallO // generatePluginRetryKey returns a plugin retry cache key func generatePluginRetryKey(workID string, block uint64) string { - return workID + "|" + fmt.Sprintf("%d", block) + return workID + "|" + strconv.FormatUint(block, 10) } func (s *streams) Close() error { diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/streams/streams_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/streams/streams_test.go index 517cfcb4e1e..8d5b1eab337 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/streams/streams_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/streams/streams_test.go @@ -239,9 +239,9 @@ func TestStreams_CheckErrorHandler(t *testing.T) { defer s.Close() userPayload, err := s.packer.PackUserCheckErrorHandler(tt.errCode, tt.lookup.ExtraData) - require.Nil(t, err) + require.NoError(t, err) payload, err := s.abi.Pack("executeCallback", tt.lookup.UpkeepId, userPayload) - require.Nil(t, err) + require.NoError(t, err) args := map[string]interface{}{ "from": zeroAddress, @@ -397,7 +397,7 @@ func TestStreams_CheckCallback(t *testing.T) { s := setupStreams(t) defer s.Close() payload, err := s.abi.Pack("checkCallback", tt.lookup.UpkeepId, values, tt.lookup.ExtraData) - require.Nil(t, err) + require.NoError(t, err) args := map[string]interface{}{ "from": zeroAddress, "to": s.registry.Address().Hex(), @@ -427,7 +427,7 @@ func TestStreams_AllowedToUseMercury(t *testing.T) { cached bool allowed bool ethCallErr error - err error + errMsg string state encoding.PipelineExecutionState reason encoding.UpkeepFailureReason registry streamRegistry @@ -486,7 +486,7 @@ func TestStreams_AllowedToUseMercury(t *testing.T) { }, { name: "failure - cannot unmarshal privilege config", - err: fmt.Errorf("failed to unmarshal privilege config: invalid character '\\x00' looking for beginning of value"), + errMsg: "failed to unmarshal privilege config: invalid character '\\x00' looking for beginning of value", state: encoding.PrivilegeConfigUnmarshalError, config: []byte{0, 1}, registry: &mockRegistry{ @@ -501,9 +501,9 @@ func TestStreams_AllowedToUseMercury(t *testing.T) { { name: "failure - flaky RPC", retryable: true, - err: fmt.Errorf("failed to get upkeep privilege config: flaky RPC"), + errMsg: "failed to get upkeep privilege config: flaky RPC", state: encoding.RpcFlakyFailure, - ethCallErr: fmt.Errorf("flaky RPC"), + ethCallErr: errors.New("flaky RPC"), registry: &mockRegistry{ GetUpkeepPrivilegeConfigFn: func(opts *bind.CallOpts, upkeepId *big.Int) ([]byte, error) { return nil, errors.New("flaky RPC") @@ -515,7 +515,7 @@ func TestStreams_AllowedToUseMercury(t *testing.T) { }, { name: "failure - empty upkeep privilege config", - err: fmt.Errorf("upkeep privilege config is empty"), + errMsg: "upkeep privilege config is empty", reason: encoding.UpkeepFailureReasonMercuryAccessNotAllowed, config: []byte{}, registry: &mockRegistry{ @@ -544,12 +544,12 @@ func TestStreams_AllowedToUseMercury(t *testing.T) { s.mercuryConfig = mc if !tt.cached { - if tt.err != nil { + if tt.errMsg != "" { bContractCfg, err := s.abi.Methods["getUpkeepPrivilegeConfig"].Outputs.PackValues([]interface{}{tt.config}) - require.Nil(t, err) + require.NoError(t, err) payload, err := s.abi.Pack("getUpkeepPrivilegeConfig", upkeepId) - require.Nil(t, err) + require.NoError(t, err) args := map[string]interface{}{ "to": s.registry.Address().Hex(), @@ -565,13 +565,13 @@ func TestStreams_AllowedToUseMercury(t *testing.T) { } else { cfg := UpkeepPrivilegeConfig{MercuryEnabled: tt.allowed} bCfg, err := json.Marshal(cfg) - require.Nil(t, err) + require.NoError(t, err) bContractCfg, err := s.abi.Methods["getUpkeepPrivilegeConfig"].Outputs.PackValues([]interface{}{bCfg}) - require.Nil(t, err) + require.NoError(t, err) payload, err := s.abi.Pack("getUpkeepPrivilegeConfig", upkeepId) - require.Nil(t, err) + require.NoError(t, err) args := map[string]interface{}{ "to": s.registry.Address().Hex(), @@ -591,7 +591,9 @@ func TestStreams_AllowedToUseMercury(t *testing.T) { } state, reason, retryable, allowed, err := s.AllowedToUseMercury(opts, upkeepId) - assert.Equal(t, tt.err, err) + if tt.errMsg != "" { + assert.ErrorContains(t, err, tt.errMsg) + } assert.Equal(t, tt.allowed, allowed) assert.Equal(t, tt.state, state) assert.Equal(t, tt.reason, reason) @@ -882,13 +884,13 @@ func TestStreams_StreamsLookup(t *testing.T) { if !tt.cachedAdminCfg && !tt.hasError { cfg := UpkeepPrivilegeConfig{MercuryEnabled: tt.hasPermission} bCfg, err := json.Marshal(cfg) - require.Nil(t, err) + require.NoError(t, err) bContractCfg, err := s.abi.Methods["getUpkeepPrivilegeConfig"].Outputs.PackValues([]interface{}{bCfg}) - require.Nil(t, err) + require.NoError(t, err) payload, err := s.abi.Pack("getUpkeepPrivilegeConfig", upkeepId) - require.Nil(t, err) + require.NoError(t, err) args := map[string]interface{}{ "to": s.registry.Address().Hex(), @@ -911,7 +913,7 @@ func TestStreams_StreamsLookup(t *testing.T) { mr1 := v03.MercuryV03Response{ Reports: []v03.MercuryV03Report{{FullReport: tt.blobs["0x4554482d5553442d415242495452554d2d544553544e45540000000000000000"]}, {FullReport: tt.blobs["0x4254432d5553442d415242495452554d2d544553544e45540000000000000000"]}}} b1, err := json.Marshal(mr1) - assert.Nil(t, err) + assert.NoError(t, err) resp1 := &http.Response{ StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader(b1)), @@ -924,14 +926,14 @@ func TestStreams_StreamsLookup(t *testing.T) { mr1 := v02.MercuryV02Response{ChainlinkBlob: tt.blobs["0x4554482d5553442d415242495452554d2d544553544e45540000000000000000"]} b1, err := json.Marshal(mr1) - assert.Nil(t, err) + assert.NoError(t, err) resp1 := &http.Response{ StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader(b1)), } mr2 := v02.MercuryV02Response{ChainlinkBlob: tt.blobs["0x4254432d5553442d415242495452554d2d544553544e45540000000000000000"]} b2, err := json.Marshal(mr2) - assert.Nil(t, err) + assert.NoError(t, err) resp2 := &http.Response{ StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader(b2)), @@ -949,7 +951,7 @@ func TestStreams_StreamsLookup(t *testing.T) { if tt.callbackNeeded { payload, err := s.abi.Pack("checkCallback", upkeepId, tt.values, tt.extraData) - require.Nil(t, err) + require.NoError(t, err) args := map[string]interface{}{ "from": zeroAddress, "to": s.registry.Address().Hex(), diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v02/request.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v02/request.go index 4adef132aab..c61f860d0ac 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v02/request.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v02/request.go @@ -207,7 +207,7 @@ func (c *client) singleFeedRequest(ctx context.Context, ch chan<- mercury.Mercur return nil } - prommetrics.AutomationStreamsResponses.WithLabelValues(prommetrics.StreamsVersion02, fmt.Sprintf("%d", httpResponse.StatusCode)).Inc() + prommetrics.AutomationStreamsResponses.WithLabelValues(prommetrics.StreamsVersion02, strconv.Itoa(httpResponse.StatusCode)).Inc() switch httpResponse.StatusCode { case http.StatusNotFound, http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: // Considered as pipeline error, but if retry attempts go over threshold, is changed upstream to ErrCode @@ -267,7 +267,7 @@ func (c *client) singleFeedRequest(ctx context.Context, ch chan<- mercury.Mercur }, // only retry when the error is 404 Not Found, 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout retry.RetryIf(func(err error) bool { - return err.Error() == fmt.Sprintf("%d", http.StatusNotFound) || err.Error() == fmt.Sprintf("%d", http.StatusInternalServerError) || err.Error() == fmt.Sprintf("%d", http.StatusBadGateway) || err.Error() == fmt.Sprintf("%d", http.StatusServiceUnavailable) || err.Error() == fmt.Sprintf("%d", http.StatusGatewayTimeout) + return err.Error() == strconv.Itoa(http.StatusNotFound) || err.Error() == strconv.Itoa(http.StatusInternalServerError) || err.Error() == strconv.Itoa(http.StatusBadGateway) || err.Error() == strconv.Itoa(http.StatusServiceUnavailable) || err.Error() == strconv.Itoa(http.StatusGatewayTimeout) }), retry.Context(ctx), retry.Delay(retryDelay), diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v02/v02_request_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v02/v02_request_test.go index 2abe9c9717a..43144e70ce5 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v02/v02_request_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v02/v02_request_test.go @@ -319,7 +319,7 @@ func TestV02_SingleFeedRequest(t *testing.T) { mr := MercuryV02Response{ChainlinkBlob: tt.blob} b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) if tt.responseBytes != "" { b = []byte(tt.responseBytes) @@ -375,8 +375,8 @@ func TestV02_SingleFeedRequest(t *testing.T) { assert.Equal(t, [][]byte(nil), m.Bytes) } else { blobBytes, err := hexutil.Decode(tt.blob) - assert.Nil(t, err) - assert.Nil(t, m.Error) + assert.NoError(t, err) + assert.NoError(t, m.Error) assert.Equal(t, [][]byte{blobBytes}, m.Bytes) } }) @@ -595,7 +595,7 @@ func TestV02_DoMercuryRequestV02(t *testing.T) { for _, blob := range tt.mockChainlinkBlobs { mr := MercuryV02Response{ChainlinkBlob: blob} b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: tt.mockHttpStatusCode, @@ -641,7 +641,7 @@ func TestV02_DoMercuryRequestV02_MultipleFeedsSuccess(t *testing.T) { for i := 0; i <= 3; i++ { mr := MercuryV02Response{ChainlinkBlob: "0x00066dfcd1ed2d95b18c948dbc5bd64c687afe93e4ca7d663ddec14c20090ad80000000000000000000000000000000000000000000000000000000000081401000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000002200000000000000000000000000000000000000000000000000000000000000280000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001204554482d5553442d415242495452554d2d544553544e455400000000000000000000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000289ad8d367000000000000000000000000000000000000000000000000000000289acf0b38000000000000000000000000000000000000000000000000000000289b3da40000000000000000000000000000000000000000000000000000000000018ae7ce74d9fa252a8983976eab600dc7590c778d04813430841bc6e765c34cd81a168d00000000000000000000000000000000000000000000000000000000018ae7cb0000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000000000000260412b94e525ca6cedc9f544fd86f77606d52fe731a5d069dbe836a8bfc0fb8c911963b0ae7a14971f3b4621bffb802ef0605392b9a6c89c7fab1df8633a5ade00000000000000000000000000000000000000000000000000000000000000024500c2f521f83fba5efc2bf3effaaedde43d0a4adff785c1213b712a3aed0d8157642a84324db0cf9695ebd27708d4608eb0337e0dd87b0e43f0fa70c700d911"} b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: http.StatusOK, @@ -663,7 +663,7 @@ func TestV02_DoMercuryRequestV02_MultipleFeedsSuccess(t *testing.T) { } state, _, errCode, retryable, retryInterval, _ := c.DoRequest(testutils.Context(t), lookup, automationTypes.ConditionTrigger, pluginRetryKey) - assert.Equal(t, false, retryable) + assert.False(t, retryable) assert.Equal(t, 0*time.Second, retryInterval) assert.Equal(t, encoding.ErrCodeNil, errCode) assert.Equal(t, encoding.NoPipelineError, state) @@ -682,7 +682,7 @@ func TestV02_DoMercuryRequestV02_Timeout(t *testing.T) { mr := MercuryV02Response{ChainlinkBlob: "0x00066dfcd1ed2d95b18c948dbc5bd64c687afe93e4ca7d663ddec14c20090ad80000000000000000000000000000000000000000000000000000000000081401000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000002200000000000000000000000000000000000000000000000000000000000000280000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001204554482d5553442d415242495452554d2d544553544e455400000000000000000000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000289ad8d367000000000000000000000000000000000000000000000000000000289acf0b38000000000000000000000000000000000000000000000000000000289b3da40000000000000000000000000000000000000000000000000000000000018ae7ce74d9fa252a8983976eab600dc7590c778d04813430841bc6e765c34cd81a168d00000000000000000000000000000000000000000000000000000000018ae7cb0000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000000000000260412b94e525ca6cedc9f544fd86f77606d52fe731a5d069dbe836a8bfc0fb8c911963b0ae7a14971f3b4621bffb802ef0605392b9a6c89c7fab1df8633a5ade00000000000000000000000000000000000000000000000000000000000000024500c2f521f83fba5efc2bf3effaaedde43d0a4adff785c1213b712a3aed0d8157642a84324db0cf9695ebd27708d4608eb0337e0dd87b0e43f0fa70c700d911"} b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: http.StatusOK, @@ -716,8 +716,8 @@ func TestV02_DoMercuryRequestV02_Timeout(t *testing.T) { start := time.Now() state, values, errCode, retryable, retryInterval, _ := c.DoRequest(testutils.Context(t), lookup, automationTypes.ConditionTrigger, pluginRetryKey) elapsed := time.Since(start) - assert.True(t, elapsed < serverTimeout) - assert.Equal(t, false, retryable) + assert.Less(t, elapsed, serverTimeout) + assert.False(t, retryable) assert.Equal(t, 0*time.Second, retryInterval) assert.Equal(t, encoding.ErrCodeStreamsTimeout, errCode) assert.Equal(t, encoding.NoPipelineError, state) @@ -738,7 +738,7 @@ func TestV02_DoMercuryRequestV02_OneFeedSuccessOneFeedPipelineError(t *testing.T // First request success mr := MercuryV02Response{ChainlinkBlob: "0x00066dfcd1ed2d95b18c948dbc5bd64c687afe93e4ca7d663ddec14c20090ad80000000000000000000000000000000000000000000000000000000000081401000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000002200000000000000000000000000000000000000000000000000000000000000280000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001204554482d5553442d415242495452554d2d544553544e455400000000000000000000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000289ad8d367000000000000000000000000000000000000000000000000000000289acf0b38000000000000000000000000000000000000000000000000000000289b3da40000000000000000000000000000000000000000000000000000000000018ae7ce74d9fa252a8983976eab600dc7590c778d04813430841bc6e765c34cd81a168d00000000000000000000000000000000000000000000000000000000018ae7cb0000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000000000000260412b94e525ca6cedc9f544fd86f77606d52fe731a5d069dbe836a8bfc0fb8c911963b0ae7a14971f3b4621bffb802ef0605392b9a6c89c7fab1df8633a5ade00000000000000000000000000000000000000000000000000000000000000024500c2f521f83fba5efc2bf3effaaedde43d0a4adff785c1213b712a3aed0d8157642a84324db0cf9695ebd27708d4608eb0337e0dd87b0e43f0fa70c700d911"} b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: http.StatusOK, @@ -765,7 +765,7 @@ func TestV02_DoMercuryRequestV02_OneFeedSuccessOneFeedPipelineError(t *testing.T } state, values, errCode, retryable, retryInterval, _ := c.DoRequest(testutils.Context(t), lookup, automationTypes.LogTrigger, pluginRetryKey) - assert.Equal(t, true, retryable) + assert.True(t, retryable) assert.Equal(t, 1*time.Second, retryInterval) assert.Equal(t, encoding.ErrCodeStreamsServiceUnavailable, errCode) assert.Equal(t, encoding.MercuryFlakyFailure, state) @@ -786,7 +786,7 @@ func TestV02_DoMercuryRequestV02_OneFeedSuccessOneFeedErrCode(t *testing.T) { // First request success mr := MercuryV02Response{ChainlinkBlob: "0x00066dfcd1ed2d95b18c948dbc5bd64c687afe93e4ca7d663ddec14c20090ad80000000000000000000000000000000000000000000000000000000000081401000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000002200000000000000000000000000000000000000000000000000000000000000280000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001204554482d5553442d415242495452554d2d544553544e455400000000000000000000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000289ad8d367000000000000000000000000000000000000000000000000000000289acf0b38000000000000000000000000000000000000000000000000000000289b3da40000000000000000000000000000000000000000000000000000000000018ae7ce74d9fa252a8983976eab600dc7590c778d04813430841bc6e765c34cd81a168d00000000000000000000000000000000000000000000000000000000018ae7cb0000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000000000000260412b94e525ca6cedc9f544fd86f77606d52fe731a5d069dbe836a8bfc0fb8c911963b0ae7a14971f3b4621bffb802ef0605392b9a6c89c7fab1df8633a5ade00000000000000000000000000000000000000000000000000000000000000024500c2f521f83fba5efc2bf3effaaedde43d0a4adff785c1213b712a3aed0d8157642a84324db0cf9695ebd27708d4608eb0337e0dd87b0e43f0fa70c700d911"} b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: http.StatusOK, @@ -814,7 +814,7 @@ func TestV02_DoMercuryRequestV02_OneFeedSuccessOneFeedErrCode(t *testing.T) { state, values, errCode, retryable, retryInterval, _ := c.DoRequest(testutils.Context(t), lookup, automationTypes.LogTrigger, pluginRetryKey) assert.Equal(t, [][]byte(nil), values) - assert.Equal(t, false, retryable) + assert.False(t, retryable) assert.Equal(t, 0*time.Second, retryInterval) assert.Equal(t, encoding.ErrCodeStreamsBadResponse, errCode) assert.Equal(t, encoding.NoPipelineError, state) @@ -834,7 +834,7 @@ func TestV02_DoMercuryRequestV02_OneFeedSuccessOneFeedPipelineErrorConvertedErro // First request success mr := MercuryV02Response{ChainlinkBlob: "0x00066dfcd1ed2d95b18c948dbc5bd64c687afe93e4ca7d663ddec14c20090ad80000000000000000000000000000000000000000000000000000000000081401000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000002200000000000000000000000000000000000000000000000000000000000000280000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001204554482d5553442d415242495452554d2d544553544e455400000000000000000000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000289ad8d367000000000000000000000000000000000000000000000000000000289acf0b38000000000000000000000000000000000000000000000000000000289b3da40000000000000000000000000000000000000000000000000000000000018ae7ce74d9fa252a8983976eab600dc7590c778d04813430841bc6e765c34cd81a168d00000000000000000000000000000000000000000000000000000000018ae7cb0000000000000000000000000000000000000000000000000000000064891c98000000000000000000000000000000000000000000000000000000000000000260412b94e525ca6cedc9f544fd86f77606d52fe731a5d069dbe836a8bfc0fb8c911963b0ae7a14971f3b4621bffb802ef0605392b9a6c89c7fab1df8633a5ade00000000000000000000000000000000000000000000000000000000000000024500c2f521f83fba5efc2bf3effaaedde43d0a4adff785c1213b712a3aed0d8157642a84324db0cf9695ebd27708d4608eb0337e0dd87b0e43f0fa70c700d911"} b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: http.StatusOK, @@ -861,7 +861,7 @@ func TestV02_DoMercuryRequestV02_OneFeedSuccessOneFeedPipelineErrorConvertedErro } state, values, errCode, retryable, retryInterval, _ := c.DoRequest(testutils.Context(t), lookup, automationTypes.ConditionTrigger, pluginRetryKey) - assert.Equal(t, false, retryable) + assert.False(t, retryable) assert.Equal(t, 0*time.Second, retryInterval) assert.Equal(t, encoding.ErrCodeStreamsStatusGatewayTimeout, errCode) assert.Equal(t, encoding.NoPipelineError, state) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v03/request.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v03/request.go index 16892c88a59..97c601a196b 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v03/request.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v03/request.go @@ -181,7 +181,7 @@ func (c *client) multiFeedsRequest(ctx context.Context, ch chan<- mercury.Mercur } c.lggr.Infof("at timestamp %s upkeep %s received status code %d from mercury v0.3", sl.Time.String(), sl.UpkeepId.String(), resp.StatusCode) - prommetrics.AutomationStreamsResponses.WithLabelValues(prommetrics.StreamsVersion03, fmt.Sprintf("%d", resp.StatusCode)).Inc() + prommetrics.AutomationStreamsResponses.WithLabelValues(prommetrics.StreamsVersion03, strconv.Itoa(resp.StatusCode)).Inc() switch resp.StatusCode { case http.StatusUnauthorized: c.lggr.Errorf("at timestamp %s upkeep %s received status code %d from mercury v0.3, most likely this is caused by unauthorized upkeep", sl.Time.String(), sl.UpkeepId.String(), resp.StatusCode) @@ -278,7 +278,7 @@ func (c *client) multiFeedsRequest(ctx context.Context, ch chan<- mercury.Mercur }, // only retry when the error is 206 Partial Content, 404 Not Found, 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout retry.RetryIf(func(err error) bool { - return err.Error() == fmt.Sprintf("%d", http.StatusPartialContent) || err.Error() == fmt.Sprintf("%d", http.StatusNotFound) || err.Error() == fmt.Sprintf("%d", http.StatusInternalServerError) || err.Error() == fmt.Sprintf("%d", http.StatusBadGateway) || err.Error() == fmt.Sprintf("%d", http.StatusServiceUnavailable) || err.Error() == fmt.Sprintf("%d", http.StatusGatewayTimeout) + return err.Error() == strconv.Itoa(http.StatusPartialContent) || err.Error() == strconv.Itoa(http.StatusNotFound) || err.Error() == strconv.Itoa(http.StatusInternalServerError) || err.Error() == strconv.Itoa(http.StatusBadGateway) || err.Error() == strconv.Itoa(http.StatusServiceUnavailable) || err.Error() == strconv.Itoa(http.StatusGatewayTimeout) }), retry.Context(retryCtx), retry.Delay(retryDelay), diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v03/v03_request_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v03/v03_request_test.go index 022fd8a1e46..5690c418b42 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v03/v03_request_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/v03/v03_request_test.go @@ -153,7 +153,7 @@ func TestV03_DoMercuryRequestV03(t *testing.T) { } b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: tt.mockHttpStatusCode, Body: io.NopCloser(bytes.NewReader(b)), @@ -202,7 +202,7 @@ func TestV03_DoMercuryRequestV03_MultipleFeedsSuccess(t *testing.T) { }, } b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: http.StatusOK, @@ -225,7 +225,7 @@ func TestV03_DoMercuryRequestV03_MultipleFeedsSuccess(t *testing.T) { } state, _, errCode, retryable, retryInterval, _ := c.DoRequest(testutils.Context(t), lookup, automationTypes.ConditionTrigger, pluginRetryKey) - assert.Equal(t, false, retryable) + assert.False(t, retryable) assert.Equal(t, 0*time.Second, retryInterval) assert.Equal(t, encoding.ErrCodeNil, errCode) assert.Equal(t, encoding.NoPipelineError, state) @@ -254,7 +254,7 @@ func TestV03_DoMercuryRequestV03_Timeout(t *testing.T) { }, } b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: http.StatusOK, @@ -281,8 +281,8 @@ func TestV03_DoMercuryRequestV03_Timeout(t *testing.T) { start := time.Now() state, values, errCode, retryable, retryInterval, _ := c.DoRequest(testutils.Context(t), lookup, automationTypes.ConditionTrigger, pluginRetryKey) elapsed := time.Since(start) - assert.True(t, elapsed < serverTimeout) - assert.Equal(t, false, retryable) + assert.Less(t, elapsed, serverTimeout) + assert.False(t, retryable) assert.Equal(t, 0*time.Second, retryInterval) assert.Equal(t, encoding.ErrCodeStreamsTimeout, errCode) assert.Equal(t, encoding.NoPipelineError, state) @@ -312,7 +312,7 @@ func TestV03_DoMercuryRequestV03_OneFeedSuccessOneFeedPipelineError(t *testing.T }, } b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: http.StatusOK, @@ -339,7 +339,7 @@ func TestV03_DoMercuryRequestV03_OneFeedSuccessOneFeedPipelineError(t *testing.T } state, values, errCode, retryable, retryInterval, _ := c.DoRequest(testutils.Context(t), lookup, automationTypes.LogTrigger, pluginRetryKey) - assert.Equal(t, true, retryable) + assert.True(t, retryable) assert.Equal(t, 1*time.Second, retryInterval) assert.Equal(t, encoding.ErrCodeStreamsBadGateway, errCode) assert.Equal(t, encoding.MercuryFlakyFailure, state) @@ -369,7 +369,7 @@ func TestV03_DoMercuryRequestV03_OneFeedSuccessOneFeedErrCode(t *testing.T) { }, } b, err := json.Marshal(mr) - assert.Nil(t, err) + assert.NoError(t, err) resp := &http.Response{ StatusCode: http.StatusOK, @@ -389,7 +389,7 @@ func TestV03_DoMercuryRequestV03_OneFeedSuccessOneFeedErrCode(t *testing.T) { }, } b, err = json.Marshal(invalidResponse) - assert.Nil(t, err) + assert.NoError(t, err) resp = &http.Response{ StatusCode: http.StatusOK, @@ -411,7 +411,7 @@ func TestV03_DoMercuryRequestV03_OneFeedSuccessOneFeedErrCode(t *testing.T) { state, values, errCode, retryable, retryInterval, _ := c.DoRequest(testutils.Context(t), lookup, automationTypes.LogTrigger, pluginRetryKey) assert.Equal(t, [][]byte(nil), values) - assert.Equal(t, false, retryable) + assert.False(t, retryable) assert.Equal(t, 0*time.Second, retryInterval) assert.Equal(t, encoding.ErrCodeStreamsBadResponse, errCode) assert.Equal(t, encoding.NoPipelineError, state) @@ -827,7 +827,7 @@ func TestV03_MultiFeedRequest(t *testing.T) { hc := new(MockHttpClient) b, err := json.Marshal(tt.response) - assert.Nil(t, err) + assert.NoError(t, err) if tt.retryNumber == 0 { resp := &http.Response{ @@ -838,13 +838,13 @@ func TestV03_MultiFeedRequest(t *testing.T) { } else if tt.retryNumber < totalAttempt { if tt.firstResponse != nil && tt.response != nil { b0, err := json.Marshal(tt.firstResponse) - assert.Nil(t, err) + assert.NoError(t, err) resp0 := &http.Response{ StatusCode: tt.statusCode, Body: io.NopCloser(bytes.NewReader(b0)), } b1, err := json.Marshal(tt.response) - assert.Nil(t, err) + assert.NoError(t, err) resp1 := &http.Response{ StatusCode: tt.lastStatusCode, Body: io.NopCloser(bytes.NewReader(b1)), @@ -888,7 +888,7 @@ func TestV03_MultiFeedRequest(t *testing.T) { assert.Equal(t, tt.errorMessage, m.Error.Error()) assert.Equal(t, [][]byte(nil), m.Bytes) } else { - assert.Nil(t, m.Error) + assert.NoError(t, m.Error) var reports [][]byte for _, rsp := range tt.response.Reports { b, _ := hexutil.Decode(rsp.FullReport) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry.go index 25bd7a445e4..0bbaacdd37a 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry.go @@ -6,6 +6,7 @@ import ( "fmt" "math/big" "net/http" + "strconv" "strings" "sync" "time" @@ -51,11 +52,11 @@ const ( var ( RegistryServiceName = "AutomationRegistry" - ErrLogReadFailure = fmt.Errorf("failure reading logs") - ErrHeadNotAvailable = fmt.Errorf("head not available") - ErrInitializationFailure = fmt.Errorf("failed to initialize registry") - ErrContextCancelled = fmt.Errorf("context was cancelled") - ErrABINotParsable = fmt.Errorf("error parsing abi") + ErrLogReadFailure = errors.New("failure reading logs") + ErrHeadNotAvailable = errors.New("head not available") + ErrInitializationFailure = errors.New("failed to initialize registry") + ErrContextCancelled = errors.New("context was cancelled") + ErrABINotParsable = errors.New("error parsing abi") ActiveUpkeepIDBatchSize int64 = 1000 // This is the interval at which active upkeep list is fully refreshed from chain refreshInterval = 15 * time.Minute @@ -288,7 +289,7 @@ func (r *EvmRegistry) refreshActiveUpkeeps(ctx context.Context) error { // get active upkeep ids from contract ids, err := r.getLatestIDsFromContract(ctx) if err != nil { - return fmt.Errorf("failed to get active upkeep ids from contract during refresh: %s", err) + return fmt.Errorf("failed to get active upkeep ids from contract during refresh: %w", err) } r.active.Reset(ids...) @@ -409,7 +410,7 @@ func (r *EvmRegistry) pollUpkeepStateLogs(ctx context.Context) error { var err error if end, err = r.poller.LatestBlock(ctx); err != nil { - return fmt.Errorf("%w: %s", ErrHeadNotAvailable, err) + return fmt.Errorf("%w: %w", ErrHeadNotAvailable, err) } r.mu.Lock() @@ -430,7 +431,7 @@ func (r *EvmRegistry) pollUpkeepStateLogs(ctx context.Context) error { upkeepStateEvents, r.addr, ); err != nil { - return fmt.Errorf("%w: %s", ErrLogReadFailure, err) + return fmt.Errorf("%w: %w", ErrLogReadFailure, err) } for _, log := range logs { @@ -555,7 +556,7 @@ func (r *EvmRegistry) getLatestIDsFromContract(ctx context.Context) ([]*big.Int, if err != nil { n := "latest" if opts.BlockNumber != nil { - n = fmt.Sprintf("%d", opts.BlockNumber.Int64()) + n = strconv.FormatInt(opts.BlockNumber.Int64(), 10) } return nil, fmt.Errorf("%w: failed to get contract state at block number '%s'", err, n) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_check_pipeline.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_check_pipeline.go index 6927f5ba4ca..149909fbbc8 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_check_pipeline.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_check_pipeline.go @@ -2,6 +2,7 @@ package evm import ( "context" + "errors" "fmt" "math/big" "strings" @@ -37,7 +38,7 @@ func (r *EvmRegistry) CheckUpkeeps(ctx context.Context, keys ...ocr2keepers.Upke if keys[i].Trigger.BlockNumber == 0 { // check block was not populated, use latest latest := r.bs.latestBlock.Load() if latest == nil { - return nil, fmt.Errorf("no latest block available") + return nil, errors.New("no latest block available") } copy(keys[i].Trigger.BlockHash[:], latest.Hash[:]) keys[i].Trigger.BlockNumber = latest.Number diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_check_pipeline_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_check_pipeline_test.go index cb014e1d3ec..05cc23631e4 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_check_pipeline_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_check_pipeline_test.go @@ -2,7 +2,6 @@ package evm import ( "context" - "fmt" "math/big" "strings" "sync/atomic" @@ -12,6 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rpc" "github.com/patrickmn/go-cache" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -202,7 +202,7 @@ func TestRegistry_VerifyCheckBlock(t *testing.T) { } if tc.makeEthCall { client := new(evmClientMocks.Client) - client.On("BlockByNumber", mock.Anything, tc.checkBlock).Return(nil, fmt.Errorf("error")) + client.On("BlockByNumber", mock.Anything, tc.checkBlock).Return(nil, errors.New("error")) e.client = client } @@ -269,7 +269,7 @@ func TestRegistry_VerifyLogExists(t *testing.T) { state: encoding.RpcFlakyFailure, retryable: true, makeEthCall: true, - ethCallErr: fmt.Errorf("error"), + ethCallErr: errors.New("error"), }, { name: "log block no longer exists", @@ -495,7 +495,7 @@ func TestRegistry_CheckUpkeeps(t *testing.T) { }, }, ethCallErrors: map[string]error{ - uid1.String(): fmt.Errorf("error"), + uid1.String(): errors.New("error"), }, }, } @@ -646,7 +646,7 @@ func TestRegistry_SimulatePerformUpkeeps(t *testing.T) { })).Return(nil). Run(func(args mock.Arguments) { be := args.Get(1).([]rpc.BatchElem) - be[0].Error = fmt.Errorf("error") + be[0].Error = errors.New("error") res := "0x0001" be[1].Result = res }).Once() @@ -671,9 +671,9 @@ func setupEVMRegistry(t *testing.T) *EvmRegistry { lggr := logger.Test(t) addr := common.HexToAddress("0x6cA639822c6C241Fa9A7A6b5032F6F7F1C513CAD") keeperRegistryABI, err := abi.JSON(strings.NewReader(ac.IAutomationV21PlusCommonABI)) - require.Nil(t, err, "need registry abi") + require.NoError(t, err, "need registry abi") streamsLookupCompatibleABI, err := abi.JSON(strings.NewReader(streams_lookup_compatible_interface.StreamsLookupCompatibleInterfaceABI)) - require.Nil(t, err, "need mercury abi") + require.NoError(t, err, "need mercury abi") var logPoller logpoller.LogPoller mockReg := mocks.NewRegistry(t) mockHttpClient := mocks.NewHttpClient(t) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_test.go index 1a3f103dd10..921a94cc4bf 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/registry_test.go @@ -3,8 +3,8 @@ package evm import ( "context" "errors" - "fmt" "math/big" + "strconv" "testing" "time" @@ -102,7 +102,7 @@ func TestPollLogs(t *testing.T) { OutputErr error }{ OutputBlock: 0, - OutputErr: fmt.Errorf("test error output"), + OutputErr: errors.New("test error output"), }, }, { @@ -153,7 +153,7 @@ func TestPollLogs(t *testing.T) { InputStart: 250, InputEnd: 500, OutputLogs: []logpoller.Log{}, - OutputErr: fmt.Errorf("test output error"), + OutputErr: errors.New("test output error"), }, }, { @@ -214,7 +214,7 @@ func TestPollLogs(t *testing.T) { if test.ExpectedErr != nil { assert.ErrorIs(t, err, test.ExpectedErr) } else { - assert.Nil(t, err) + assert.NoError(t, err) } var outputLogCount int @@ -263,7 +263,7 @@ func TestRegistry_refreshLogTriggerUpkeeps(t *testing.T) { logEventProvider: &mockLogEventProvider{ RefreshActiveUpkeepsFn: func(ctx context.Context, ids ...*big.Int) ([]*big.Int, error) { // of the ids specified in the test, only one is a valid log trigger upkeep - assert.Equal(t, 1, len(ids)) + assert.Len(t, ids, 1) return ids, nil }, }, @@ -288,7 +288,7 @@ func TestRegistry_refreshLogTriggerUpkeeps(t *testing.T) { logEventProvider: &mockLogEventProvider{ RefreshActiveUpkeepsFn: func(ctx context.Context, ids ...*big.Int) ([]*big.Int, error) { // of the ids specified in the test, only one is a valid log trigger upkeep - assert.Equal(t, 1, len(ids)) + assert.Len(t, ids, 1) return ids, nil }, }, @@ -313,7 +313,7 @@ func TestRegistry_refreshLogTriggerUpkeeps(t *testing.T) { logEventProvider: &mockLogEventProvider{ RefreshActiveUpkeepsFn: func(ctx context.Context, ids ...*big.Int) ([]*big.Int, error) { // of the ids specified in the test, only one is a valid log trigger upkeep - assert.Equal(t, 1, len(ids)) + assert.Len(t, ids, 1) return ids, nil }, }, @@ -342,7 +342,7 @@ func TestRegistry_refreshLogTriggerUpkeeps(t *testing.T) { logEventProvider: &mockLogEventProvider{ RefreshActiveUpkeepsFn: func(ctx context.Context, ids ...*big.Int) ([]*big.Int, error) { // of the ids specified in the test, only one is a valid log trigger upkeep - assert.Equal(t, 1, len(ids)) + assert.Len(t, ids, 1) return ids, nil }, RegisterFilterFn: func(ctx context.Context, opts logprovider.FilterOptions) error { @@ -396,7 +396,7 @@ func TestRegistry_refreshLogTriggerUpkeeps(t *testing.T) { logEventProvider: &mockLogEventProvider{ RefreshActiveUpkeepsFn: func(ctx context.Context, ids ...*big.Int) ([]*big.Int, error) { // of the ids specified in the test, only two are a valid log trigger upkeep - assert.Equal(t, 2, len(ids)) + assert.Len(t, ids, 2) return ids, nil }, RegisterFilterFn: func(ctx context.Context, opts logprovider.FilterOptions) error { @@ -442,13 +442,13 @@ func TestRegistry_refreshLogTriggerUpkeeps(t *testing.T) { ids: func() []*big.Int { res := []*big.Int{} for i := 0; i < logTriggerRefreshBatchSize*3; i++ { - res = append(res, core.GenUpkeepID(types2.LogTrigger, fmt.Sprintf("%d", i)).BigInt()) + res = append(res, core.GenUpkeepID(types2.LogTrigger, strconv.Itoa(i)).BigInt()) } return res }(), logEventProvider: &mockLogEventProvider{ RefreshActiveUpkeepsFn: func(ctx context.Context, ids ...*big.Int) ([]*big.Int, error) { - assert.Equal(t, logTriggerRefreshBatchSize, len(ids)) + assert.Len(t, ids, logTriggerRefreshBatchSize) return ids, nil }, RegisterFilterFn: func(ctx context.Context, opts logprovider.FilterOptions) error { @@ -494,14 +494,14 @@ func TestRegistry_refreshLogTriggerUpkeeps(t *testing.T) { ids: func() []*big.Int { res := []*big.Int{} for i := 0; i < logTriggerRefreshBatchSize+3; i++ { - res = append(res, core.GenUpkeepID(types2.LogTrigger, fmt.Sprintf("%d", i)).BigInt()) + res = append(res, core.GenUpkeepID(types2.LogTrigger, strconv.Itoa(i)).BigInt()) } return res }(), logEventProvider: &mockLogEventProvider{ RefreshActiveUpkeepsFn: func(ctx context.Context, ids ...*big.Int) ([]*big.Int, error) { if len(ids) != logTriggerRefreshBatchSize { - assert.Equal(t, 3, len(ids)) + assert.Len(t, ids, 3) } return ids, nil }, diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/transmit/encoding.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/transmit/encoding.go index c77e01dc847..a2930968d90 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/transmit/encoding.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/transmit/encoding.go @@ -1,6 +1,7 @@ package transmit import ( + "errors" "fmt" "math/big" @@ -54,7 +55,7 @@ func defaultLogParser(registry *ac.IAutomationV21PlusCommon, log logpoller.Log) default: return transmitEventLog{}, fmt.Errorf("unknown log type: %v", l) } - return transmitEventLog{}, fmt.Errorf("log with bad structure") + return transmitEventLog{}, errors.New("log with bad structure") } // transmitEventLog is a wrapper around logpoller.Log and the parsed log diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeep_provider.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeep_provider.go index 01f136aaa6b..72f09d49868 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeep_provider.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeep_provider.go @@ -2,7 +2,7 @@ package evm import ( "context" - "fmt" + "errors" "github.com/smartcontractkit/chainlink-automation/pkg/v3/types" ocr2keepers "github.com/smartcontractkit/chainlink-common/pkg/types/automation" @@ -30,7 +30,7 @@ func NewUpkeepProvider(activeUpkeeps ActiveUpkeepList, bs *BlockSubscriber, lp l func (p *upkeepProvider) GetActiveUpkeeps(_ context.Context) ([]ocr2keepers.UpkeepPayload, error) { latestBlock := p.bs.latestBlock.Load() if latestBlock == nil { - return nil, fmt.Errorf("no latest block found when fetching active upkeeps") + return nil, errors.New("no latest block found when fetching active upkeeps") } var payloads []ocr2keepers.UpkeepPayload for _, uid := range p.activeUpkeeps.View(types.ConditionTrigger) { diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/orm_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/orm_test.go index 894e3b0ef33..a59055563cc 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/orm_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/orm_test.go @@ -46,5 +46,5 @@ func TestInsertSelectDelete(t *testing.T) { states, err = orm.SelectStatesByWorkIDs(ctx, []string{"0x1"}) require.NoError(t, err, "no error expected from select") - require.Len(t, states, 0, "records return should be empty since records were deleted") + require.Empty(t, states, "records return should be empty since records were deleted") } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/scanner_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/scanner_test.go index dad9273aabc..401714658e4 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/scanner_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/scanner_test.go @@ -1,7 +1,7 @@ package upkeepstate import ( - "fmt" + "errors" "sort" "testing" @@ -42,7 +42,7 @@ func TestPerformedEventsScanner(t *testing.T) { []string{"111"}, []logpoller.Log{}, []string{}, - fmt.Errorf("test-error"), + errors.New("test-error"), true, }, { @@ -152,7 +152,7 @@ func TestPerformedEventsScanner_Batch(t *testing.T) { ) require.NoError(t, err) - require.Equal(t, 2, len(ids)) + require.Len(t, ids, 2) sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store.go index 27cac24a9fe..482982b2aee 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store.go @@ -2,7 +2,7 @@ package upkeepstate import ( "context" - "fmt" + "errors" "io" "math/big" "sync" @@ -101,7 +101,7 @@ func NewUpkeepStateStore(orm ORM, lggr logger.Logger, scanner PerformedLogsScann func (u *upkeepStateStore) Start(pctx context.Context) error { return u.StartOnce(UpkeepStateStoreServiceName, func() error { if err := u.scanner.Start(pctx); err != nil { - return fmt.Errorf("failed to start scanner") + return errors.New("failed to start scanner") } u.lggr.Debug("Starting upkeep state store") diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store_test.go index c65a34598cc..4b3511a7606 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store_test.go @@ -2,7 +2,7 @@ package upkeepstate import ( "context" - "fmt" + "errors" "math/big" "sync" "testing" @@ -140,7 +140,7 @@ func TestUpkeepStateStore(t *testing.T) { }, workIDsSelect: []string{"0x1", "0x2"}, workIDsFromScanner: []string{"0x2", "0x222"}, - errScanner: fmt.Errorf("test error"), + errScanner: errors.New("test error"), errored: true, }, { @@ -157,7 +157,7 @@ func TestUpkeepStateStore(t *testing.T) { }, workIDsSelect: []string{"0x1", "0x2"}, workIDsFromScanner: []string{"0x2", "0x222"}, - errDB: fmt.Errorf("test error"), + errDB: errors.New("test error"), errored: true, }, } diff --git a/core/services/ocr2/plugins/ocr2keeper/integration_21_test.go b/core/services/ocr2/plugins/ocr2keeper/integration_21_test.go index e941044e91a..cb0cff91306 100644 --- a/core/services/ocr2/plugins/ocr2keeper/integration_21_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/integration_21_test.go @@ -5,6 +5,7 @@ import ( crand "crypto/rand" "encoding/hex" "encoding/json" + "errors" "fmt" "math/big" "net/http" @@ -224,7 +225,7 @@ func TestIntegration_KeeperPluginLogUpkeep(t *testing.T) { commit() ids, addrs, contracts := deployUpkeeps(t, backend, carrol, steve, linkToken, registry, upkeeps) - require.Equal(t, upkeeps, len(ids)) + require.Len(t, ids, upkeeps) require.Equal(t, len(ids), len(contracts)) require.Equal(t, len(ids), len(addrs)) @@ -1156,7 +1157,7 @@ func (c *feedLookupUpkeepController) EmitEvents( require.True(t, eventEmitted, "event expected on backend") if !eventEmitted { - return fmt.Errorf("event was not emitted") + return errors.New("event was not emitted") } afterEmit() diff --git a/core/services/ocr2/plugins/s4/integration_test.go b/core/services/ocr2/plugins/s4/integration_test.go index 5148ea6e26d..b6e75300bfd 100644 --- a/core/services/ocr2/plugins/s4/integration_test.go +++ b/core/services/ocr2/plugins/s4/integration_test.go @@ -291,7 +291,7 @@ func TestS4Integration_Expired(t *testing.T) { for i := 0; i < don.size; i++ { snapshot, err := don.orms[i].GetSnapshot(ctx, s4_svc.NewFullAddressRange()) require.NoError(t, err) - require.Len(t, snapshot, 0) + require.Empty(t, snapshot) } } diff --git a/core/services/ocr2/plugins/s4/plugin_test.go b/core/services/ocr2/plugins/s4/plugin_test.go index 12fac8a070b..3690eff0c7d 100644 --- a/core/services/ocr2/plugins/s4/plugin_test.go +++ b/core/services/ocr2/plugins/s4/plugin_test.go @@ -217,7 +217,7 @@ func TestPlugin_ShouldAcceptFinalizedReport(t *testing.T) { should, err := plugin.ShouldAcceptFinalizedReport(testutils.Context(t), types.ReportTimestamp{}, report) assert.NoError(t, err) assert.False(t, should) - assert.Equal(t, 10, len(ormRows)) + assert.Len(t, ormRows, 10) compareRows(t, rows, ormRows) }) @@ -248,7 +248,7 @@ func TestPlugin_ShouldAcceptFinalizedReport(t *testing.T) { should, err := plugin.ShouldAcceptFinalizedReport(testutils.Context(t), types.ReportTimestamp{}, report) assert.NoError(t, err) assert.False(t, should) - assert.Equal(t, 0, len(ormRows)) + assert.Empty(t, ormRows) }) } diff --git a/core/services/ocr2/plugins/threshold/decryption_queue_test.go b/core/services/ocr2/plugins/threshold/decryption_queue_test.go index a017b883b3d..afa2f2b706b 100644 --- a/core/services/ocr2/plugins/threshold/decryption_queue_test.go +++ b/core/services/ocr2/plugins/threshold/decryption_queue_test.go @@ -2,7 +2,6 @@ package threshold import ( "context" - "errors" "reflect" "testing" "time" @@ -52,7 +51,7 @@ func Test_decryptionQueue_Decrypt_CiphertextIdTooLarge(t *testing.T) { ctx := testutils.Context(t) _, err := dq.Decrypt(ctx, []byte("largeCiphertextId"), []byte("ciphertext")) - assert.Equal(t, err.Error(), "ciphertextId too large") + assert.Equal(t, "ciphertextId too large", err.Error()) } func Test_decryptionQueue_Decrypt_EmptyCiphertextId(t *testing.T) { @@ -62,7 +61,7 @@ func Test_decryptionQueue_Decrypt_EmptyCiphertextId(t *testing.T) { ctx := testutils.Context(t) _, err := dq.Decrypt(ctx, []byte(""), []byte("ciphertext")) - assert.Equal(t, err.Error(), "ciphertextId is empty") + assert.Equal(t, "ciphertextId is empty", err.Error()) } func Test_decryptionQueue_Decrypt_CiphertextTooLarge(t *testing.T) { @@ -72,7 +71,7 @@ func Test_decryptionQueue_Decrypt_CiphertextTooLarge(t *testing.T) { ctx := testutils.Context(t) _, err := dq.Decrypt(ctx, []byte("1"), []byte("largeciphertext")) - assert.Equal(t, err.Error(), "ciphertext too large") + assert.Equal(t, "ciphertext too large", err.Error()) } func Test_decryptionQueue_Decrypt_EmptyCiphertext(t *testing.T) { @@ -82,7 +81,7 @@ func Test_decryptionQueue_Decrypt_EmptyCiphertext(t *testing.T) { ctx := testutils.Context(t) _, err := dq.Decrypt(ctx, []byte("1"), []byte("")) - assert.Equal(t, err.Error(), "ciphertext is empty") + assert.Equal(t, "ciphertext is empty", err.Error()) } func Test_decryptionQueue_Decrypt_DuplicateCiphertextId(t *testing.T) { @@ -93,13 +92,13 @@ func Test_decryptionQueue_Decrypt_DuplicateCiphertextId(t *testing.T) { go func() { _, err := dq.Decrypt(ctx, []byte("1"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("1")) _, err := dq.Decrypt(ctx, []byte("1"), []byte("encrypted")) - assert.Equal(t, err.Error(), "ciphertextId must be unique") + assert.Equal(t, "ciphertextId must be unique", err.Error()) } func Test_decryptionQueue_Decrypt_ContextCancelled(t *testing.T) { @@ -110,7 +109,7 @@ func Test_decryptionQueue_Decrypt_ContextCancelled(t *testing.T) { defer cancel() _, err := dq.Decrypt(ctx, []byte("2"), []byte("encrypted")) - assert.Equal(t, err.Error(), "context provided by caller was cancelled") + assert.Equal(t, "context provided by caller was cancelled", err.Error()) } func Test_decryptionQueue_Decrypt_QueueFull(t *testing.T) { @@ -122,7 +121,7 @@ func Test_decryptionQueue_Decrypt_QueueFull(t *testing.T) { go func() { _, err := dq.Decrypt(ctx1, []byte("4"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("4")) @@ -131,7 +130,7 @@ func Test_decryptionQueue_Decrypt_QueueFull(t *testing.T) { defer cancel2() _, err := dq.Decrypt(ctx2, []byte("3"), []byte("encrypted")) - assert.Equal(t, err.Error(), "queue is full") + assert.Equal(t, "queue is full", err.Error()) } func Test_decryptionQueue_GetRequests(t *testing.T) { @@ -143,7 +142,7 @@ func Test_decryptionQueue_GetRequests(t *testing.T) { go func() { _, err := dq.Decrypt(ctx1, []byte("5"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("5")) @@ -153,7 +152,7 @@ func Test_decryptionQueue_GetRequests(t *testing.T) { go func() { _, err := dq.Decrypt(ctx2, []byte("6"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("6")) @@ -177,7 +176,7 @@ func Test_decryptionQueue_GetCiphertext(t *testing.T) { go func() { _, err := dq.Decrypt(ctx, []byte("7"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("7")) @@ -194,7 +193,7 @@ func Test_decryptionQueue_GetCiphertext_CiphertextNotFound(t *testing.T) { dq := NewDecryptionQueue(3, 1000, 64, testutils.WaitTimeout(t), lggr) _, err := dq.GetCiphertext([]byte{0xa5}) - assert.True(t, errors.Is(err, decryptionPlugin.ErrNotFound)) + assert.ErrorIs(t, err, decryptionPlugin.ErrNotFound) } func Test_decryptionQueue_Decrypt_DecryptCalledAfterReadyResult(t *testing.T) { @@ -224,7 +223,7 @@ func Test_decryptionQueue_ReadyResult_ExpireRequest(t *testing.T) { defer cancel() _, err := dq.Decrypt(ctx, []byte("9"), []byte("encrypted")) - assert.Equal(t, err.Error(), "context provided by caller was cancelled") + assert.Equal(t, "context provided by caller was cancelled", err.Error()) } func Test_decryptionQueue_Decrypt_CleanupSuccessfulRequest(t *testing.T) { @@ -243,7 +242,7 @@ func Test_decryptionQueue_Decrypt_CleanupSuccessfulRequest(t *testing.T) { defer cancel2() _, err2 := dq.Decrypt(ctx2, []byte("10"), []byte("encrypted")) - assert.Equal(t, err2.Error(), "context provided by caller was cancelled") + assert.Equal(t, "context provided by caller was cancelled", err2.Error()) } func Test_decryptionQueue_Decrypt_UserErrorDuringDecryption(t *testing.T) { @@ -259,7 +258,7 @@ func Test_decryptionQueue_Decrypt_UserErrorDuringDecryption(t *testing.T) { ctx := testutils.Context(t) _, err := dq.Decrypt(ctx, ciphertextId, []byte("encrypted")) - assert.Equal(t, err.Error(), "pending decryption request for ciphertextId 0x120f was closed without a response") + assert.Equal(t, "pending decryption request for ciphertextId 0x120f was closed without a response", err.Error()) } func Test_decryptionQueue_Decrypt_HandleClosedChannelWithoutPlaintextResponse(t *testing.T) { @@ -275,7 +274,7 @@ func Test_decryptionQueue_Decrypt_HandleClosedChannelWithoutPlaintextResponse(t ctx := testutils.Context(t) _, err := dq.Decrypt(ctx, ciphertextId, []byte("encrypted")) - assert.Equal(t, err.Error(), "pending decryption request for ciphertextId 0x00ff was closed without a response") + assert.Equal(t, "pending decryption request for ciphertextId 0x00ff was closed without a response", err.Error()) } func Test_decryptionQueue_GetRequests_RequestsCountLimit(t *testing.T) { @@ -287,7 +286,7 @@ func Test_decryptionQueue_GetRequests_RequestsCountLimit(t *testing.T) { go func() { _, err := dq.Decrypt(ctx1, []byte("11"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("11")) @@ -297,7 +296,7 @@ func Test_decryptionQueue_GetRequests_RequestsCountLimit(t *testing.T) { go func() { _, err := dq.Decrypt(ctx2, []byte("12"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("12")) @@ -307,7 +306,7 @@ func Test_decryptionQueue_GetRequests_RequestsCountLimit(t *testing.T) { go func() { _, err := dq.Decrypt(ctx3, []byte("13"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("13")) @@ -331,7 +330,7 @@ func Test_decryptionQueue_GetRequests_TotalBytesLimit(t *testing.T) { go func() { _, err := dq.Decrypt(ctx1, []byte("11"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("11")) @@ -341,7 +340,7 @@ func Test_decryptionQueue_GetRequests_TotalBytesLimit(t *testing.T) { go func() { _, err := dq.Decrypt(ctx2, []byte("12"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("12")) @@ -351,7 +350,7 @@ func Test_decryptionQueue_GetRequests_TotalBytesLimit(t *testing.T) { go func() { _, err := dq.Decrypt(ctx3, []byte("13"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("13")) @@ -374,7 +373,7 @@ func Test_decryptionQueue_GetRequests_PendingRequestQueueShorterThanRequestCount go func() { _, err := dq.Decrypt(ctx, []byte("11"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("11")) @@ -396,7 +395,7 @@ func Test_decryptionQueue_GetRequests_ExpiredRequest(t *testing.T) { go func() { _, err := dq.Decrypt(ctx, []byte("11"), []byte("encrypted")) - require.Equal(t, err.Error(), "context provided by caller was cancelled") + require.Equal(t, "context provided by caller was cancelled", err.Error()) }() waitForPendingRequestToBeAdded(t, dq, []byte("11")) diff --git a/core/services/ocr2/validate/validate.go b/core/services/ocr2/validate/validate.go index 27a5a885369..6b49238798c 100644 --- a/core/services/ocr2/validate/validate.go +++ b/core/services/ocr2/validate/validate.go @@ -348,7 +348,7 @@ func validateOCR2CCIPCommitSpec(jsonConfig job.JSONConfig) error { emptyPipeline := strings.Trim(cfg.TokenPricesUSDPipeline, "\n\t ") == "" emptyPriceGetter := cfg.PriceGetterConfig == nil if emptyPipeline && emptyPriceGetter { - return fmt.Errorf("either tokenPricesUSDPipeline or priceGetterConfig must be set") + return errors.New("either tokenPricesUSDPipeline or priceGetterConfig must be set") } if !emptyPipeline && !emptyPriceGetter { return fmt.Errorf("only one of tokenPricesUSDPipeline or priceGetterConfig must be set: %s and %v", cfg.TokenPricesUSDPipeline, cfg.PriceGetterConfig) diff --git a/core/services/ocrcommon/adapters.go b/core/services/ocrcommon/adapters.go index c27a276669b..d75df06f2fa 100644 --- a/core/services/ocrcommon/adapters.go +++ b/core/services/ocrcommon/adapters.go @@ -110,7 +110,7 @@ func MarshalMultichainPublicKey(ost map[string]ocrtypes.OnchainPublicKey) (ocrty } length := len(pubKey) if length < 0 || length > math.MaxUint16 { - return nil, fmt.Errorf("pubKey doesn't fit into uint16") + return nil, errors.New("pubKey doesn't fit into uint16") } if err = binary.Write(buf, binary.LittleEndian, uint16(length)); err != nil { return nil, err @@ -189,7 +189,7 @@ func (a *OCR3OnchainKeyringMultiChainAdapter) getKeyBundleFromInfo(info []byte) unmarshalledInfo := new(structpb.Struct) err := proto.Unmarshal(info, unmarshalledInfo) if err != nil { - return "", nil, fmt.Errorf("failed to unmarshal report info: %v", err) + return "", nil, fmt.Errorf("failed to unmarshal report info: %w", err) } infoMap := unmarshalledInfo.AsMap() keyBundleName, ok := infoMap["keyBundleName"] @@ -210,7 +210,7 @@ func (a *OCR3OnchainKeyringMultiChainAdapter) getKeyBundleFromInfo(info []byte) func (a *OCR3OnchainKeyringMultiChainAdapter) Sign(digest ocrtypes.ConfigDigest, seqNr uint64, r ocr3types.ReportWithInfo[[]byte]) (signature []byte, err error) { _, kb, err := a.getKeyBundleFromInfo(r.Info) if err != nil { - return nil, fmt.Errorf("sign: failed to get key bundle from report info: %v", err) + return nil, fmt.Errorf("sign: failed to get key bundle from report info: %w", err) } return kb.Sign(ocrtypes.ReportContext{ ReportTimestamp: ocrtypes.ReportTimestamp{ diff --git a/core/services/ocrcommon/data_source_test.go b/core/services/ocrcommon/data_source_test.go index 1626976b5be..b5b0a353a51 100644 --- a/core/services/ocrcommon/data_source_test.go +++ b/core/services/ocrcommon/data_source_test.go @@ -2,8 +2,8 @@ package ocrcommon_test import ( "encoding/json" - "fmt" "math/big" + "strconv" "testing" "time" @@ -87,16 +87,16 @@ func Test_CachedInMemoryDataSourceErrHandling(t *testing.T) { mockVal := int64(1) // Test if Observe notices that cache updater failed and can refresh the cache on its own // 1. Set initial value - changeResultValue(runner, fmt.Sprint(mockVal), false, true) + changeResultValue(runner, strconv.FormatInt(mockVal, 10), false, true) time.Sleep(time.Millisecond * 100) val, err := dsCache.Observe(testutils.Context(t), types.ReportTimestamp{}) require.NoError(t, err) assert.Equal(t, mockVal, val.Int64()) // 2. Set values again, but make it error in updater - changeResultValue(runner, fmt.Sprint(mockVal+1), true, true) + changeResultValue(runner, strconv.FormatInt(mockVal+1, 10), true, true) time.Sleep(time.Second*2 + time.Millisecond*100) // 3. Set value in between updates and call Observe (shouldn't flake because of huge wait time) - changeResultValue(runner, fmt.Sprint(mockVal+2), false, false) + changeResultValue(runner, strconv.FormatInt(mockVal+2, 10), false, false) val, err = dsCache.Observe(testutils.Context(t), types.ReportTimestamp{}) require.NoError(t, err) assert.Equal(t, mockVal+2, val.Int64()) @@ -187,7 +187,7 @@ func Test_InMemoryDataSourceWithProm(t *testing.T) { val, err := ds.Observe(testutils.Context(t), types.ReportTimestamp{}) require.NoError(t, err) - assert.Equal(t, jsonParseTaskValue, val.String()) // returns expected value after pipeline run + assert.JSONEq(t, jsonParseTaskValue, val.String()) // returns expected value after pipeline run assert.Equal(t, cast.ToFloat64(jsonParseTaskValue), promtestutil.ToFloat64(ocrcommon.PromOcrMedianValues)) assert.Equal(t, cast.ToFloat64(jsonParseTaskValue), promtestutil.ToFloat64(ocrcommon.PromBridgeJsonParseValues)) } diff --git a/core/services/ocrcommon/discoverer_database_test.go b/core/services/ocrcommon/discoverer_database_test.go index 16c6d26a42d..2448be29d67 100644 --- a/core/services/ocrcommon/discoverer_database_test.go +++ b/core/services/ocrcommon/discoverer_database_test.go @@ -3,7 +3,6 @@ package ocrcommon_test import ( "crypto/ed25519" "crypto/rand" - "fmt" "testing" ragep2ptypes "github.com/smartcontractkit/libocr/ragep2p/types" @@ -47,7 +46,7 @@ func Test_DiscovererDatabase(t *testing.T) { ctx := testutils.Context(t) - t.Run(fmt.Sprintf("%s StoreAnnouncement writes a value", tt.name), func(t *testing.T) { + t.Run(tt.name+" StoreAnnouncement writes a value", func(t *testing.T) { ann := []byte{1, 2, 3} err := dd1.StoreAnnouncement(ctx, "remote1", ann) assert.NoError(t, err) @@ -63,7 +62,7 @@ func Test_DiscovererDatabase(t *testing.T) { assert.NoError(t, err) }) - t.Run(fmt.Sprintf("%s ReadAnnouncements reads values filtered by given peerIDs", tt.name), func(t *testing.T) { + t.Run(tt.name+" ReadAnnouncements reads values filtered by given peerIDs", func(t *testing.T) { announcements, err := dd1.ReadAnnouncements(ctx, []string{"remote1", "remote2"}) require.NoError(t, err) @@ -78,7 +77,7 @@ func Test_DiscovererDatabase(t *testing.T) { assert.Equal(t, []byte{4, 5, 6}, announcements["remote1"]) }) - t.Run(fmt.Sprintf("%s is scoped to local peer ID", tt.name), func(t *testing.T) { + t.Run(tt.name+" is scoped to local peer ID", func(t *testing.T) { ann := []byte{10, 11, 12} err := dd2.StoreAnnouncement(ctx, "remote1", ann) assert.NoError(t, err) @@ -94,7 +93,7 @@ func Test_DiscovererDatabase(t *testing.T) { assert.Equal(t, []byte{4, 5, 6}, announcements["remote1"]) }) - t.Run(fmt.Sprintf("%s persists data across restarts", tt.name), func(t *testing.T) { + t.Run(tt.name+" persists data across restarts", func(t *testing.T) { dd3 := ocrcommon.NewOCRDiscovererDatabase(db, localPeerID1.Raw()) announcements, err := dd3.ReadAnnouncements(ctx, []string{"remote1"}) diff --git a/core/services/ocrcommon/prom.go b/core/services/ocrcommon/prom.go index 011c47a2675..725cd121c73 100644 --- a/core/services/ocrcommon/prom.go +++ b/core/services/ocrcommon/prom.go @@ -1,7 +1,7 @@ package ocrcommon import ( - "fmt" + "strconv" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -38,7 +38,7 @@ func promSetBridgeParseMetrics(ds *inMemoryDataSource, trrs *pipeline.TaskRunRes if nextTask != nil && nextTask.Task.Type() == pipeline.TaskTypeJSONParse { fetchedValue := cast.ToFloat64(nextTask.Result.Value) - PromBridgeJsonParseValues.WithLabelValues(fmt.Sprintf("%d", ds.jb.ID), ds.jb.Name.String, trr.Task.(*pipeline.BridgeTask).Name, trr.Task.DotID()).Set(fetchedValue) + PromBridgeJsonParseValues.WithLabelValues(strconv.Itoa(int(ds.jb.ID)), ds.jb.Name.String, trr.Task.(*pipeline.BridgeTask).Name, trr.Task.DotID()).Set(fetchedValue) } } } @@ -60,5 +60,5 @@ func promSetFinalResultMetrics(ds *inMemoryDataSource, finalResult *pipeline.Fin return } finalResultFloat, _ := finalResultDecimal.Float64() - PromOcrMedianValues.WithLabelValues(fmt.Sprintf("%d", ds.jb.ID), ds.jb.Name.String).Set(finalResultFloat) + PromOcrMedianValues.WithLabelValues(strconv.Itoa(int(ds.jb.ID)), ds.jb.Name.String).Set(finalResultFloat) } diff --git a/core/services/ocrcommon/telemetry.go b/core/services/ocrcommon/telemetry.go index 5e4a65180d5..5eeb9515924 100644 --- a/core/services/ocrcommon/telemetry.go +++ b/core/services/ocrcommon/telemetry.go @@ -608,7 +608,7 @@ func getPricesFromBridgeTaskByTelemetryField(lggr logger.Logger, bridgeTask pipe for _, trr := range tasksWithTags { attributes, err := parseTelemetryAttributes(trr.Task.TaskTags()) if err != nil { - lggr.Warnw(fmt.Sprintf("found telemetry attributes but cannot them, taskTags=%s", trr.Task.TaskTags()), "err", err) + lggr.Warnw("found telemetry attributes but cannot them, taskTags="+trr.Task.TaskTags(), "err", err) continue } @@ -640,7 +640,7 @@ func parsePriceFromTask(lggr logger.Logger, trr pipeline.TaskRunResult) float64 } val, err := getResultFloat64(&trr) if err != nil { - lggr.Warnw(fmt.Sprintf("cannot parse EA telemetry price to float64, DOT id %s", trr.Task.DotID()), "task_type", trr.Task.Type(), "task_tags", trr.Task.TaskTags(), "err", err) + lggr.Warnw("cannot parse EA telemetry price to float64, DOT id "+trr.Task.DotID(), "task_type", trr.Task.Type(), "task_tags", trr.Task.TaskTags(), "err", err) } return val } diff --git a/core/services/ocrcommon/telemetry_test.go b/core/services/ocrcommon/telemetry_test.go index 4c8f0eb1127..62a5232a951 100644 --- a/core/services/ocrcommon/telemetry_test.go +++ b/core/services/ocrcommon/telemetry_test.go @@ -167,10 +167,10 @@ func TestGetChainID(t *testing.T) { func TestParseEATelemetry(t *testing.T) { ea, err := parseEATelemetry([]byte(bridgeResponse)) assert.NoError(t, err) - assert.Equal(t, ea.DataSource, "data-source-name") - assert.Equal(t, ea.ProviderRequestedTimestamp, int64(92233720368547760)) + assert.Equal(t, "data-source-name", ea.DataSource) + assert.Equal(t, int64(92233720368547760), ea.ProviderRequestedTimestamp) assert.Equal(t, ea.ProviderReceivedTimestamp, int64(-92233720368547760)) - assert.Equal(t, ea.ProviderDataStreamEstablished, int64(1)) + assert.Equal(t, int64(1), ea.ProviderDataStreamEstablished) assert.Equal(t, ea.ProviderIndicatedTime, int64(-123456789)) _, err = parseEATelemetry(nil) @@ -384,8 +384,8 @@ func TestGetObservation(t *testing.T) { } obs := e.getObservation(&pipeline.FinalResult{}) - assert.Equal(t, obs, int64(0)) - assert.Equal(t, logs.Len(), 1) + assert.Equal(t, int64(0), obs) + assert.Equal(t, 1, logs.Len()) assert.Contains(t, logs.All()[0].Message, "cannot get singular result") finalResult := &pipeline.FinalResult{ @@ -394,7 +394,7 @@ func TestGetObservation(t *testing.T) { FatalErrors: []error{nil}, } obs = e.getObservation(finalResult) - assert.Equal(t, obs, int64(123456)) + assert.Equal(t, int64(123456), obs) } func TestCollectAndSend(t *testing.T) { @@ -457,7 +457,7 @@ func TestCollectAndSend(t *testing.T) { } wg.Wait() - assert.Equal(t, logs.Len(), 2) + assert.Equal(t, 2, logs.Len()) assert.Contains(t, logs.All()[0].Message, "cannot parse bridge response from bridge task") badTrrs = &pipeline.TaskRunResults{ @@ -726,31 +726,31 @@ func TestShouldCollectEnhancedTelemetryMercury(t *testing.T) { }, } - require.Equal(t, ShouldCollectEnhancedTelemetryMercury(j), true) + require.True(t, ShouldCollectEnhancedTelemetryMercury(j)) j.OCR2OracleSpec.CaptureEATelemetry = false - require.Equal(t, ShouldCollectEnhancedTelemetryMercury(j), false) + require.False(t, ShouldCollectEnhancedTelemetryMercury(j)) j.OCR2OracleSpec.CaptureEATelemetry = true j.Type = job.Type(pipeline.CronJobType) - require.Equal(t, ShouldCollectEnhancedTelemetryMercury(j), false) + require.False(t, ShouldCollectEnhancedTelemetryMercury(j)) } func TestParseBridgeRequestData(t *testing.T) { - require.Equal(t, parseBridgeRequestData("", 2), bridgeRequestData{}) + require.Equal(t, bridgeRequestData{}, parseBridgeRequestData("", 2)) reqData := `{"data":{"to":"LINK","from":"USD"}}` - require.Equal(t, parseBridgeRequestData(reqData, 2), bridgeRequestData{AssetSymbol: "USD/LINK"}) + require.Equal(t, bridgeRequestData{AssetSymbol: "USD/LINK"}, parseBridgeRequestData(reqData, 2)) reqData = `{"data":{"to":"LINK","from":"USD","market":"forex"}}` - require.Equal(t, parseBridgeRequestData(reqData, 2), bridgeRequestData{AssetSymbol: "USD/LINK"}) + require.Equal(t, bridgeRequestData{AssetSymbol: "USD/LINK"}, parseBridgeRequestData(reqData, 2)) reqData = `{"data":{"endpoint":"market-status","market":"forex"}}` - require.Equal(t, parseBridgeRequestData(reqData, 4), bridgeRequestData{AssetSymbol: "forex", IsMarketStatus: true}) + require.Equal(t, bridgeRequestData{AssetSymbol: "forex", IsMarketStatus: true}, parseBridgeRequestData(reqData, 4)) reqData = `{"data":{"market":"metals"}}` - require.Equal(t, parseBridgeRequestData(reqData, 4), bridgeRequestData{AssetSymbol: "metals", IsMarketStatus: true}) + require.Equal(t, bridgeRequestData{AssetSymbol: "metals", IsMarketStatus: true}, parseBridgeRequestData(reqData, 4)) viewFunctionReqData := `{"data":{"address":"0x12345678", "signature": "function stEthPerToken() view returns (int256)"}}` - require.Equal(t, parseBridgeRequestData(viewFunctionReqData, 3), bridgeRequestData{AssetSymbol: "0x12345678"}) + require.Equal(t, bridgeRequestData{AssetSymbol: "0x12345678"}, parseBridgeRequestData(viewFunctionReqData, 3)) } func getViewFunctionTaskRunResults() pipeline.TaskRunResults { @@ -1218,5 +1218,5 @@ func TestCollectMercuryEnhancedTelemetryV4(t *testing.T) { chDone <- struct{}{} // Verify that no other telemetry is sent. - require.Len(t, sentMessageCh, 0) + require.Empty(t, sentMessageCh) } diff --git a/core/services/p2p/wrapper/wrapper.go b/core/services/p2p/wrapper/wrapper.go index 1f898b91d7d..0157f991f4d 100644 --- a/core/services/p2p/wrapper/wrapper.go +++ b/core/services/p2p/wrapper/wrapper.go @@ -3,6 +3,7 @@ package wrapper import ( "context" "crypto/ed25519" + "errors" "fmt" "github.com/prometheus/client_golang/prometheus" @@ -131,7 +132,7 @@ func (e *peerWrapper) Name() string { func (e *peerWrapper) Sign(msg []byte) ([]byte, error) { if e.privateKey == nil { - return nil, fmt.Errorf("private key not set") + return nil, errors.New("private key not set") } return ed25519.Sign(e.privateKey, msg), nil } diff --git a/core/services/periodicbackup/backup.go b/core/services/periodicbackup/backup.go index b1bcf40ee32..7a90fa68ead 100644 --- a/core/services/periodicbackup/backup.go +++ b/core/services/periodicbackup/backup.go @@ -172,7 +172,7 @@ func (backup *databaseBackup) runBackup(version string) (*backupResult, error) { if backup.mode == config.DatabaseBackupModeLite { for _, table := range excludedDataFromTables { - args = append(args, fmt.Sprintf("--exclude-table-data=%s", table)) + args = append(args, "--exclude-table-data="+table) } } diff --git a/core/services/periodicbackup/backup_test.go b/core/services/periodicbackup/backup_test.go index b9ca9476a06..6e7f93d1857 100644 --- a/core/services/periodicbackup/backup_test.go +++ b/core/services/periodicbackup/backup_test.go @@ -43,7 +43,7 @@ func TestPeriodicBackup_RunBackup(t *testing.T) { file, err := os.Stat(result.path) require.NoError(t, err, "error not nil when checking for output file") - assert.Greater(t, file.Size(), int64(0)) + assert.Positive(t, file.Size()) assert.Equal(t, file.Size(), result.size) assert.Contains(t, result.path, "backup/cl_backup_0.9.9") assert.NotContains(t, result.pgDumpArguments, "--exclude-table-data=pipeline_task_runs") @@ -62,7 +62,7 @@ func TestPeriodicBackup_RunBackupInLiteMode(t *testing.T) { file, err := os.Stat(result.path) require.NoError(t, err, "error not nil when checking for output file") - assert.Greater(t, file.Size(), int64(0)) + assert.Positive(t, file.Size()) assert.Equal(t, file.Size(), result.size) assert.Contains(t, result.path, "backup/cl_backup_0.9.9") assert.Contains(t, result.pgDumpArguments, "--exclude-table-data=pipeline_task_runs") @@ -81,7 +81,7 @@ func TestPeriodicBackup_RunBackupWithoutVersion(t *testing.T) { file, err := os.Stat(result.path) require.NoError(t, err, "error not nil when checking for output file") - assert.Greater(t, file.Size(), int64(0)) + assert.Positive(t, file.Size()) assert.Equal(t, file.Size(), result.size) assert.Contains(t, result.path, "backup/cl_backup_unset") } @@ -116,7 +116,7 @@ func TestPeriodicBackup_AlternativeOutputDir(t *testing.T) { file, err := os.Stat(result.path) require.NoError(t, err, "error not nil when checking for output file") - assert.Greater(t, file.Size(), int64(0)) + assert.Positive(t, file.Size()) assert.Contains(t, result.path, "/alternative/cl_backup_0.9.9.dump") } diff --git a/core/services/pipeline/common_test.go b/core/services/pipeline/common_test.go index ed7998b79e3..615f52b97ae 100644 --- a/core/services/pipeline/common_test.go +++ b/core/services/pipeline/common_test.go @@ -22,7 +22,7 @@ func TestAtrributesAttribute(t *testing.T) { p, err := pipeline.Parse(a) require.NoError(t, err) task := p.Tasks[0] - assert.Equal(t, "{\"attribute1\":\"value1\", \"attribute2\":42}", task.TaskTags()) + assert.JSONEq(t, "{\"attribute1\":\"value1\", \"attribute2\":42}", task.TaskTags()) } func TestTimeoutAttribute(t *testing.T) { @@ -33,14 +33,14 @@ func TestTimeoutAttribute(t *testing.T) { require.NoError(t, err) timeout, set := p.Tasks[0].TaskTimeout() assert.Equal(t, cltest.MustParseDuration(t, "10s"), timeout) - assert.Equal(t, true, set) + assert.True(t, set) a = `ds1 [type=http method=GET url="https://chain.link/voter_turnout/USA-2020" requestData=<{"hi": "hello"}>];` p, err = pipeline.Parse(a) require.NoError(t, err) timeout, set = p.Tasks[0].TaskTimeout() assert.Equal(t, cltest.MustParseDuration(t, "0s"), timeout) - assert.Equal(t, false, set) + assert.False(t, set) } func TestTaskHTTPUnmarshal(t *testing.T) { @@ -64,7 +64,7 @@ func TestTaskAnyUnmarshal(t *testing.T) { require.Len(t, p.Tasks, 1) _, ok := p.Tasks[0].(*pipeline.AnyTask) require.True(t, ok) - require.Equal(t, true, p.Tasks[0].Base().FailEarly) + require.True(t, p.Tasks[0].Base().FailEarly) } func TestRetryUnmarshal(t *testing.T) { @@ -213,7 +213,7 @@ func TestCheckInputs(t *testing.T) { outputs, err := pipeline.CheckInputs(test.pr, test.minLen, test.maxLen, test.maxErrors) if test.err == nil { assert.NoError(t, err) - assert.Equal(t, test.outputsLen, len(outputs)) + assert.Len(t, outputs, test.outputsLen) } else { assert.Equal(t, test.err, errors.Cause(err)) } @@ -317,13 +317,13 @@ func TestGetNextTaskOf(t *testing.T) { firstTask := trrs[0] nextTask := trrs.GetNextTaskOf(firstTask) - assert.Equal(t, nextTask.Task.ID(), 2) + assert.Equal(t, 2, nextTask.Task.ID()) nextTask = trrs.GetNextTaskOf(*nextTask) - assert.Equal(t, nextTask.Task.ID(), 3) + assert.Equal(t, 3, nextTask.Task.ID()) nextTask = trrs.GetNextTaskOf(*nextTask) - assert.Equal(t, nextTask.Task.ID(), 4) + assert.Equal(t, 4, nextTask.Task.ID()) nextTask = trrs.GetNextTaskOf(*nextTask) assert.Empty(t, nextTask) @@ -382,7 +382,7 @@ func TestGetDescendantTasks(t *testing.T) { BaseTask: pipeline.NewBaseTask(0, "taskWithRepeats", nil, nil, 0), } descendents := taskWithRepeats.GetDescendantTasks() - assert.Len(t, descendents, 0) + assert.Empty(t, descendents) }) t.Run("GetDescendantTasks with empty list of output tasks", func(t *testing.T) { @@ -391,6 +391,6 @@ func TestGetDescendantTasks(t *testing.T) { BaseTask: pipeline.NewBaseTask(0, "taskWithRepeats", nil, []pipeline.Task{}, 0), } descendents := taskWithRepeats.GetDescendantTasks() - assert.Len(t, descendents, 0) + assert.Empty(t, descendents) }) } diff --git a/core/services/pipeline/models.go b/core/services/pipeline/models.go index fa1a2605f03..1509f668660 100644 --- a/core/services/pipeline/models.go +++ b/core/services/pipeline/models.go @@ -71,7 +71,7 @@ type Run struct { } func (r Run) GetID() string { - return fmt.Sprintf("%v", r.ID) + return strconv.FormatInt(r.ID, 10) } func (r *Run) SetID(value string) error { diff --git a/core/services/pipeline/models_test.go b/core/services/pipeline/models_test.go index e32dea26275..788d129c4d5 100644 --- a/core/services/pipeline/models_test.go +++ b/core/services/pipeline/models_test.go @@ -17,15 +17,15 @@ import ( func TestRun_Status(t *testing.T) { t.Parallel() - assert.Equal(t, pipeline.RunStatusUnknown.Finished(), false) - assert.Equal(t, pipeline.RunStatusRunning.Finished(), false) - assert.Equal(t, pipeline.RunStatusCompleted.Finished(), true) - assert.Equal(t, pipeline.RunStatusErrored.Finished(), true) + assert.False(t, pipeline.RunStatusUnknown.Finished()) + assert.False(t, pipeline.RunStatusRunning.Finished()) + assert.True(t, pipeline.RunStatusCompleted.Finished()) + assert.True(t, pipeline.RunStatusErrored.Finished()) - assert.Equal(t, pipeline.RunStatusUnknown.Errored(), false) - assert.Equal(t, pipeline.RunStatusRunning.Errored(), false) - assert.Equal(t, pipeline.RunStatusCompleted.Errored(), false) - assert.Equal(t, pipeline.RunStatusErrored.Errored(), true) + assert.False(t, pipeline.RunStatusUnknown.Errored()) + assert.False(t, pipeline.RunStatusRunning.Errored()) + assert.False(t, pipeline.RunStatusCompleted.Errored()) + assert.True(t, pipeline.RunStatusErrored.Errored()) now := null.TimeFrom(time.Now()) diff --git a/core/services/pipeline/orm_test.go b/core/services/pipeline/orm_test.go index f3d529d87e6..6cd792df588 100644 --- a/core/services/pipeline/orm_test.go +++ b/core/services/pipeline/orm_test.go @@ -360,7 +360,7 @@ func Test_PipelineORM_StoreRun_ShouldUpsert(t *testing.T) { restart, err := orm.StoreRun(ctx, run) require.NoError(t, err) // no new data, so we don't need a restart - require.Equal(t, false, restart) + require.False(t, restart) // the run is paused require.Equal(t, pipeline.RunStatusSuspended, run.State) @@ -368,7 +368,7 @@ func Test_PipelineORM_StoreRun_ShouldUpsert(t *testing.T) { require.NoError(t, err) run = &r // this is an incomplete run, so partial results should be present (regardless of saveSuccessfulTaskRuns) - require.Equal(t, 2, len(run.PipelineTaskRuns)) + require.Len(t, run.PipelineTaskRuns, 2) // and ds1 is not finished task := run.ByDotID("ds1") require.NotNil(t, task) @@ -391,7 +391,7 @@ func Test_PipelineORM_StoreRun_ShouldUpsert(t *testing.T) { restart, err = orm.StoreRun(ctx, run) require.NoError(t, err) // no new data, so we don't need a restart - require.Equal(t, false, restart) + require.False(t, restart) // the run is paused require.Equal(t, pipeline.RunStatusSuspended, run.State) @@ -399,7 +399,7 @@ func Test_PipelineORM_StoreRun_ShouldUpsert(t *testing.T) { require.NoError(t, err) run = &r // this is an incomplete run, so partial results should be present (regardless of saveSuccessfulTaskRuns) - require.Equal(t, 2, len(run.PipelineTaskRuns)) + require.Len(t, run.PipelineTaskRuns, 2) // and ds1 is finished task = run.ByDotID("ds1") require.NotNil(t, task) @@ -463,13 +463,13 @@ func Test_PipelineORM_StoreRun_DetectsRestarts(t *testing.T) { restart, err := orm.StoreRun(ctx, run) require.NoError(t, err) // new data available! immediately restart the run - require.Equal(t, true, restart) + require.True(t, restart) // the run is still in progress require.Equal(t, pipeline.RunStatusRunning, run.State) // confirm we now contain the latest restart data merged with local task data ds1 := run.ByDotID("ds1") - require.Equal(t, ds1.Output.Val, int64(2)) + require.Equal(t, int64(2), ds1.Output.Val) require.True(t, ds1.FinishedAt.Valid) } @@ -535,8 +535,8 @@ func Test_PipelineORM_StoreRun_UpdateTaskRunResult(t *testing.T) { r, start, err := orm.UpdateTaskRunResult(ctx, ds1_id, pipeline.Result{Value: "foo"}) run = &r require.NoError(t, err) - assert.Greater(t, run.ID, int64(0)) - assert.Greater(t, run.PipelineSpec.ID, int32(0)) // Make sure it actually loaded everything + assert.Positive(t, run.ID) + assert.Positive(t, run.PipelineSpec.ID) // Make sure it actually loaded everything require.Len(t, run.PipelineTaskRuns, 3) // assert that run should be in "running" state @@ -587,7 +587,7 @@ func Test_PipelineORM_DeleteRun(t *testing.T) { restart, err := orm.StoreRun(ctx, run) require.NoError(t, err) // no new data, so we don't need a restart - require.Equal(t, false, restart) + require.False(t, restart) // the run is paused require.Equal(t, pipeline.RunStatusSuspended, run.State) @@ -629,7 +629,7 @@ func Test_PipelineORM_DeleteRunsOlderThan(t *testing.T) { restart, err := orm.StoreRun(ctx, run) assert.NoError(t, err) // no new data, so we don't need a restart - assert.Equal(t, false, restart) + assert.False(t, restart) runsIds = append(runsIds, run.ID) } @@ -903,7 +903,7 @@ func Test_Prune(t *testing.T) { porm.Prune(tests.Context(t), jobID2) cnt := pgtest.MustCount(t, db, "SELECT count(*) FROM pipeline_runs WHERE pipeline_spec_id = $1 AND state = $2", ps1.ID, pipeline.RunStatusCompleted) - assert.Equal(t, cnt, 20) + assert.Equal(t, 20, cnt) cnt = pgtest.MustCount(t, db, "SELECT count(*) FROM pipeline_runs WHERE pipeline_spec_id = $1 AND state = $2", ps2.ID, pipeline.RunStatusCompleted) assert.Equal(t, 2, cnt) diff --git a/core/services/pipeline/runner.go b/core/services/pipeline/runner.go index 2194cb8be46..2394a61bac8 100644 --- a/core/services/pipeline/runner.go +++ b/core/services/pipeline/runner.go @@ -2,10 +2,12 @@ package pipeline import ( "context" + "encoding/hex" "fmt" "io" "net/http" "sort" + "strconv" "sync" "time" @@ -425,7 +427,7 @@ func (r *runner) run(ctx context.Context, pipeline *Pipeline, run *Run, vars Var // NOTE: runTime can be very long now because it'll include suspend runTime = run.FinishedAt.Time.Sub(run.CreatedAt) - PromPipelineRunTotalTimeToCompletion.WithLabelValues(fmt.Sprintf("%d", run.PipelineSpec.JobID), run.PipelineSpec.JobName).Set(float64(runTime)) + PromPipelineRunTotalTimeToCompletion.WithLabelValues(strconv.Itoa(int(run.PipelineSpec.JobID)), run.PipelineSpec.JobName).Set(float64(runTime)) } // Update run results @@ -475,7 +477,7 @@ func (r *runner) run(ctx context.Context, pipeline *Pipeline, run *Run, vars Var if run.HasFatalErrors() { run.State = RunStatusErrored - PromPipelineRunErrors.WithLabelValues(fmt.Sprintf("%d", run.PipelineSpec.JobID), run.PipelineSpec.JobName).Inc() + PromPipelineRunErrors.WithLabelValues(strconv.Itoa(int(run.PipelineSpec.JobID)), run.PipelineSpec.JobName).Inc() } else { run.State = RunStatusCompleted } @@ -569,7 +571,7 @@ func (r *runner) executeTaskRun(ctx context.Context, spec Spec, taskRun *memoryT switch v := result.Value.(type) { case []byte: loggerFields = append(loggerFields, "resultString", fmt.Sprintf("%q", v)) - loggerFields = append(loggerFields, "resultHex", fmt.Sprintf("%x", v)) + loggerFields = append(loggerFields, "resultHex", hex.EncodeToString(v)) } if r.config.VerboseLogging() { l.Tracew("Pipeline task completed", loggerFields...) @@ -594,7 +596,7 @@ func (r *runner) executeTaskRun(ctx context.Context, spec Spec, taskRun *memoryT func logTaskRunToPrometheus(trr TaskRunResult, spec Spec) { elapsed := trr.FinishedAt.Time.Sub(trr.CreatedAt) - PromPipelineTaskExecutionTime.WithLabelValues(fmt.Sprintf("%d", spec.JobID), spec.JobName, trr.Task.DotID(), string(trr.Task.Type())).Set(float64(elapsed)) + PromPipelineTaskExecutionTime.WithLabelValues(strconv.Itoa(int(spec.JobID)), spec.JobName, trr.Task.DotID(), string(trr.Task.Type())).Set(float64(elapsed)) var status string if trr.Result.Error != nil { status = "error" @@ -607,7 +609,7 @@ func logTaskRunToPrometheus(trr TaskRunResult, spec Spec) { bridgeName = bridgeTask.Name } - PromPipelineTasksTotalFinished.WithLabelValues(fmt.Sprintf("%d", spec.JobID), spec.JobName, trr.Task.DotID(), string(trr.Task.Type()), bridgeName, status).Inc() + PromPipelineTasksTotalFinished.WithLabelValues(strconv.Itoa(int(spec.JobID)), spec.JobName, trr.Task.DotID(), string(trr.Task.Type()), bridgeName, status).Inc() } // ExecuteAndInsertFinishedRun executes a run in memory then inserts the finished run/task run records, returning the final result diff --git a/core/services/pipeline/runner_test.go b/core/services/pipeline/runner_test.go index 9b7a21d939b..3badb1f5913 100644 --- a/core/services/pipeline/runner_test.go +++ b/core/services/pipeline/runner_test.go @@ -111,11 +111,11 @@ ds5 [type=http method="GET" url="%s" index=2] require.Len(t, finalResults.AllErrors, 12) require.Len(t, finalResults.FatalErrors, 3) assert.Equal(t, "9650000000000000000000", finalResults.Values[0].(decimal.Decimal).String()) - assert.Nil(t, finalResults.FatalErrors[0]) + assert.NoError(t, finalResults.FatalErrors[0]) assert.Equal(t, "foo-index-1", finalResults.Values[1].(string)) - assert.Nil(t, finalResults.FatalErrors[1]) + assert.NoError(t, finalResults.FatalErrors[1]) assert.Equal(t, "bar-index-2", finalResults.Values[2].(string)) - assert.Nil(t, finalResults.FatalErrors[2]) + assert.NoError(t, finalResults.FatalErrors[2]) var errorResults []pipeline.TaskRunResult for _, trr := range trrs { @@ -414,7 +414,7 @@ func Test_PipelineRunner_CBORParse(t *testing.T) { require.Len(t, finalResults.Values, 1) assert.Equal(t, make(map[string]interface{}), finalResults.Values[0]) require.Len(t, finalResults.FatalErrors, 1) - assert.Nil(t, finalResults.FatalErrors[0]) + assert.NoError(t, finalResults.FatalErrors[0]) }) t.Run("standard mode, string value", func(t *testing.T) { @@ -441,7 +441,7 @@ func Test_PipelineRunner_CBORParse(t *testing.T) { require.Len(t, finalResults.Values, 1) assert.Equal(t, "foo", finalResults.Values[0]) require.Len(t, finalResults.FatalErrors, 1) - assert.Nil(t, finalResults.FatalErrors[0]) + assert.NoError(t, finalResults.FatalErrors[0]) }) } @@ -589,8 +589,8 @@ a->b1->c; a->b2->c;`, }, pipeline.NewVarsFrom(input)) require.NoError(t, err) - require.Equal(t, 4, len(trrs)) - assert.Equal(t, false, trrs.FinalResult().HasFatalErrors()) + require.Len(t, trrs, 4) + assert.False(t, trrs.FinalResult().HasFatalErrors()) // a = 4 // (b1 = 8) + (b2 = 12) @@ -615,9 +615,9 @@ a->b1; a->b2;`, }, pipeline.NewVarsFrom(input)) require.NoError(t, err) - require.Equal(t, 3, len(trrs)) + require.Len(t, trrs, 3) result := trrs.FinalResult() - assert.Equal(t, false, result.HasFatalErrors()) + assert.False(t, result.HasFatalErrors()) assert.Equal(t, mustDecimal(t, "8").String(), result.Values[0].(decimal.Decimal).String()) assert.Equal(t, mustDecimal(t, "12").String(), result.Values[1].(decimal.Decimal).String()) @@ -708,7 +708,7 @@ ds5 [type=http method="GET" url="%s" index=2] incomplete, err := r.Run(testutils.Context(t), run, false, nil) require.NoError(t, err) require.Len(t, run.PipelineTaskRuns, 9) // 3 tasks are suspended: ds1_parse, ds1_multiply, median. ds1 is present, but contains ErrPending - require.Equal(t, true, incomplete) // still incomplete + require.True(t, incomplete) // still incomplete // TODO: test a pending run that's not marked async=true, that is not allowed @@ -716,7 +716,7 @@ ds5 [type=http method="GET" url="%s" index=2] orm.On("StoreRun", mock.Anything, mock.AnythingOfType("*pipeline.Run")).Return(false, nil).Once() incomplete, err = r.Run(testutils.Context(t), run, false, nil) require.NoError(t, err) - require.Equal(t, true, incomplete) // still incomplete + require.True(t, incomplete) // still incomplete // Now simulate a new result coming in task := run.ByDotID("ds1") @@ -729,9 +729,9 @@ ds5 [type=http method="GET" url="%s" index=2] orm.On("StoreRun", mock.Anything, mock.AnythingOfType("*pipeline.Run")).Return(false, nil).Once() incomplete, err = r.Run(testutils.Context(t), run, false, nil) require.NoError(t, err) - require.Equal(t, false, incomplete) // done + require.False(t, incomplete) // done require.Len(t, run.PipelineTaskRuns, 12) - require.Equal(t, false, incomplete) // run is complete + require.False(t, incomplete) // run is complete require.Len(t, run.Outputs.Val, 3) require.Len(t, run.FatalErrors, 3) @@ -850,7 +850,7 @@ ds5 [type=http method="GET" url="%s" index=2] incomplete, err := r.Run(testutils.Context(t), run, false, nil) require.NoError(t, err) require.Len(t, run.PipelineTaskRuns, 12) - require.Equal(t, false, incomplete) // run is complete + require.False(t, incomplete) // run is complete require.Len(t, run.Outputs.Val, 3) require.Len(t, run.FatalErrors, 3) @@ -887,8 +887,8 @@ a [type=lowercase input="$(first)"] `, }, pipeline.NewVarsFrom(input)) require.NoError(t, err) - require.Equal(t, 1, len(trrs)) - assert.Equal(t, false, trrs.FinalResult().HasFatalErrors()) + require.Len(t, trrs, 1) + assert.False(t, trrs.FinalResult().HasFatalErrors()) result, err := trrs.FinalResult().SingularResult() require.NoError(t, err) @@ -909,8 +909,8 @@ a [type=uppercase input="$(first)"] `, }, pipeline.NewVarsFrom(input)) require.NoError(t, err) - require.Equal(t, 1, len(trrs)) - assert.Equal(t, false, trrs.FinalResult().HasFatalErrors()) + require.Len(t, trrs, 1) + assert.False(t, trrs.FinalResult().HasFatalErrors()) result, err := trrs.FinalResult().SingularResult() require.NoError(t, err) @@ -931,8 +931,8 @@ a [type=hexdecode input="$(astring)"] `, }, pipeline.NewVarsFrom(input)) require.NoError(t, err) - require.Equal(t, 1, len(trrs)) - assert.Equal(t, false, trrs.FinalResult().HasFatalErrors()) + require.Len(t, trrs, 1) + assert.False(t, trrs.FinalResult().HasFatalErrors()) result, err := trrs.FinalResult().SingularResult() require.NoError(t, err) @@ -956,8 +956,8 @@ en->de `, }, pipeline.NewVarsFrom(input)) require.NoError(t, err) - require.Equal(t, 2, len(trrs)) - assert.Equal(t, false, trrs.FinalResult().HasFatalErrors()) + require.Len(t, trrs, 2) + assert.False(t, trrs.FinalResult().HasFatalErrors()) result, err := trrs.FinalResult().SingularResult() require.NoError(t, err) @@ -978,8 +978,8 @@ a [type=base64decode input="$(astring)"] `, }, pipeline.NewVarsFrom(input)) require.NoError(t, err) - require.Equal(t, 1, len(trrs)) - assert.Equal(t, false, trrs.FinalResult().HasFatalErrors()) + require.Len(t, trrs, 1) + assert.False(t, trrs.FinalResult().HasFatalErrors()) result, err := trrs.FinalResult().SingularResult() require.NoError(t, err) @@ -1003,8 +1003,8 @@ en->de `, }, pipeline.NewVarsFrom(input)) require.NoError(t, err) - require.Equal(t, 2, len(trrs)) - assert.Equal(t, false, trrs.FinalResult().HasFatalErrors()) + require.Len(t, trrs, 2) + assert.False(t, trrs.FinalResult().HasFatalErrors()) result, err := trrs.FinalResult().SingularResult() require.NoError(t, err) diff --git a/core/services/pipeline/scheduler_test.go b/core/services/pipeline/scheduler_test.go index eaedfb453a2..e81236d50ff 100644 --- a/core/services/pipeline/scheduler_test.go +++ b/core/services/pipeline/scheduler_test.go @@ -99,7 +99,7 @@ func TestScheduler(t *testing.T) { assertion: func(t *testing.T, p Pipeline, results map[int]TaskRunResult) { result := results[p.ByDotID("a").ID()] // a has no errors - require.Equal(t, nil, result.Result.Error) + require.NoError(t, result.Result.Error) require.Equal(t, 1, result.Result.Value) require.Equal(t, uint(2), result.Attempts) }, diff --git a/core/services/pipeline/task.base64decode_test.go b/core/services/pipeline/task.base64decode_test.go index 23d02e2dec8..b786d3fc7e3 100644 --- a/core/services/pipeline/task.base64decode_test.go +++ b/core/services/pipeline/task.base64decode_test.go @@ -1,7 +1,6 @@ package pipeline_test import ( - "fmt" "testing" "github.com/stretchr/testify/assert" @@ -48,7 +47,7 @@ func TestBase64DecodeTask(t *testing.T) { assertOK(task.Run(testutils.Context(t), logger.TestLogger(t), vars, []pipeline.Result{{Value: test.input}})) }) t.Run("without vars through input param", func(t *testing.T) { - inputStr := fmt.Sprintf("%v", test.input) + inputStr := test.input if inputStr == "" { // empty input parameter is indistinguishable from not providing it at all // in that case the task will use an input defined by the job DAG diff --git a/core/services/pipeline/task.bridge_test.go b/core/services/pipeline/task.bridge_test.go index cd81f8656fd..724dfbe002e 100644 --- a/core/services/pipeline/task.bridge_test.go +++ b/core/services/pipeline/task.bridge_test.go @@ -748,7 +748,7 @@ func TestBridgeTask_Meta(t *testing.T) { mp := map[string]interface{}{"meta": metaDataForBridge} res, _ := task.Run(testutils.Context(t), logger.TestLogger(t), pipeline.NewVarsFrom(map[string]interface{}{"jobRun": mp}), nil) - assert.Nil(t, res.Error) + assert.NoError(t, res.Error) assert.True(t, httpCalled.Load()) } @@ -1011,7 +1011,7 @@ func TestBridgeTask_Headers(t *testing.T) { result, runInfo := task.Run(testutils.Context(t), logger.TestLogger(t), pipeline.NewVarsFrom(nil), nil) assert.False(t, runInfo.IsPending) assert.Equal(t, `{"fooresponse": 1}`, result.Value) - assert.Nil(t, result.Error) + assert.NoError(t, result.Error) assert.Equal(t, append(standardHeaders, "X-Header-1", "foo", "X-Header-2", "bar"), allHeaders(headers)) }) @@ -1032,7 +1032,7 @@ func TestBridgeTask_Headers(t *testing.T) { result, runInfo := task.Run(testutils.Context(t), logger.TestLogger(t), pipeline.NewVarsFrom(nil), nil) assert.False(t, runInfo.IsPending) - assert.NotNil(t, result.Error) + assert.Error(t, result.Error) assert.Equal(t, `headers must have an even number of elements`, result.Error.Error()) assert.Nil(t, result.Value) }) @@ -1054,7 +1054,7 @@ func TestBridgeTask_Headers(t *testing.T) { result, runInfo := task.Run(testutils.Context(t), logger.TestLogger(t), pipeline.NewVarsFrom(nil), nil) assert.False(t, runInfo.IsPending) assert.Equal(t, `{"fooresponse": 1}`, result.Value) - assert.Nil(t, result.Error) + assert.NoError(t, result.Error) assert.Equal(t, []string{"Content-Length", "38", "Content-Type", "footype", "User-Agent", "Go-http-client/1.1", "X-Header-1", "foo", "X-Header-2", "bar"}, allHeaders(headers)) }) @@ -1253,7 +1253,7 @@ ds [type=bridge name="adapter-error-bridge" timeout="50ms" requestData="{\"data\ bridge := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { b, herr := io.ReadAll(req.Body) require.NoError(t, herr) - require.Equal(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) + require.JSONEq(t, `{"data":{"from":"ETH","to":"USD"}}`, string(b)) res.WriteHeader(http.StatusInternalServerError) resp := `{"error": {"name":"AdapterLWBAError", "message": "bid ask violation detected"}}` diff --git a/core/services/pipeline/task.conditional_test.go b/core/services/pipeline/task.conditional_test.go index 8fdf33370dc..e21522f1fc5 100644 --- a/core/services/pipeline/task.conditional_test.go +++ b/core/services/pipeline/task.conditional_test.go @@ -40,10 +40,10 @@ func TestConditionalTask(t *testing.T) { assert.False(t, runInfo.IsRetryable) if test.expectErr { require.Error(t, result.Error) - require.Equal(t, nil, result.Value) + require.Nil(t, result.Value) } else { require.NoError(t, result.Error) - require.Equal(t, true, result.Value.(bool)) + require.True(t, result.Value.(bool)) } }) t.Run("with vars", func(t *testing.T) { @@ -60,10 +60,10 @@ func TestConditionalTask(t *testing.T) { assert.False(t, runInfo.IsRetryable) if test.expectErr { require.Error(t, result.Error) - require.Equal(t, nil, result.Value) + require.Nil(t, result.Value) } else { require.NoError(t, result.Error) - require.Equal(t, true, result.Value.(bool)) + require.True(t, result.Value.(bool)) } }) }) diff --git a/core/services/pipeline/task.divide_test.go b/core/services/pipeline/task.divide_test.go index e13f4512794..aca85daebdf 100644 --- a/core/services/pipeline/task.divide_test.go +++ b/core/services/pipeline/task.divide_test.go @@ -4,6 +4,7 @@ import ( "fmt" "math" "reflect" + "strconv" "testing" "github.com/pkg/errors" @@ -184,7 +185,7 @@ func TestDivideTask_Overflow(t *testing.T) { BaseTask: pipeline.NewBaseTask(0, "task", nil, nil, 0), Input: "$(a)", Divisor: "$(b)", - Precision: fmt.Sprintf("%d", math.MaxInt32), + Precision: strconv.Itoa(math.MaxInt32), } vars := pipeline.NewVarsFrom(map[string]interface{}{ diff --git a/core/services/pipeline/task.eth_abi_encode_test.go b/core/services/pipeline/task.eth_abi_encode_test.go index 013d37a3754..0a98c451a83 100644 --- a/core/services/pipeline/task.eth_abi_encode_test.go +++ b/core/services/pipeline/task.eth_abi_encode_test.go @@ -1,7 +1,6 @@ package pipeline_test import ( - "fmt" "math" "math/big" "testing" @@ -527,7 +526,7 @@ func TestETHABIEncode_EncodeIntegers(t *testing.T) { } } else { require.NoError(t, result.Error) - assert.Equal(t, test.expected, result.Value, fmt.Sprintf("test: %s", test.name)) + assert.Equal(t, test.expected, result.Value, "test: %s", test.name) } }) } @@ -591,7 +590,7 @@ func TestETHABIEncode_EncodeIntegers_Overflow(t *testing.T) { } } else { require.NoError(t, result.Error) - assert.Equal(t, test.expected, result.Value, fmt.Sprintf("test: %s", test.name)) + assert.Equal(t, test.expected, result.Value, "test: %s", test.name) } }) } diff --git a/core/services/pipeline/task.hexdecode_test.go b/core/services/pipeline/task.hexdecode_test.go index 43591b96622..26609717db0 100644 --- a/core/services/pipeline/task.hexdecode_test.go +++ b/core/services/pipeline/task.hexdecode_test.go @@ -1,7 +1,6 @@ package pipeline_test import ( - "fmt" "testing" "github.com/stretchr/testify/assert" @@ -50,7 +49,7 @@ func TestHexDecodeTask(t *testing.T) { assertOK(task.Run(testutils.Context(t), logger.TestLogger(t), vars, []pipeline.Result{{Value: test.input}})) }) t.Run("without vars through input param", func(t *testing.T) { - inputStr := fmt.Sprintf("%v", test.input) + inputStr := test.input if inputStr == "" { // empty input parameter is indistinguishable from not providing it at all // in that case the task will use an input defined by the job DAG diff --git a/core/services/pipeline/task.http_test.go b/core/services/pipeline/task.http_test.go index 8d1571e6333..9a1bad13f04 100644 --- a/core/services/pipeline/task.http_test.go +++ b/core/services/pipeline/task.http_test.go @@ -361,7 +361,7 @@ func TestHTTPTask_Headers(t *testing.T) { result, runInfo := task.Run(testutils.Context(t), logger.TestLogger(t), pipeline.NewVarsFrom(nil), nil) assert.False(t, runInfo.IsPending) assert.Equal(t, `{"fooresponse": 1}`, result.Value) - assert.Nil(t, result.Error) + assert.NoError(t, result.Error) assert.Equal(t, append(standardHeaders, "X-Header-1", "foo", "X-Header-2", "bar"), allHeaders(headers)) }) @@ -376,7 +376,7 @@ func TestHTTPTask_Headers(t *testing.T) { result, runInfo := task.Run(testutils.Context(t), logger.TestLogger(t), pipeline.NewVarsFrom(nil), nil) assert.False(t, runInfo.IsPending) - assert.NotNil(t, result.Error) + assert.Error(t, result.Error) assert.Equal(t, `headers must have an even number of elements`, result.Error.Error()) assert.Nil(t, result.Value) }) @@ -407,7 +407,7 @@ func TestHTTPTask_Headers(t *testing.T) { result, runInfo := task.Run(testutils.Context(t), logger.TestLogger(t), pipeline.NewVarsFrom(nil), nil) assert.False(t, runInfo.IsPending) assert.Equal(t, `{"fooresponse": 3}`, result.Value) - assert.Nil(t, result.Error) + assert.NoError(t, result.Error) assert.Equal(t, []string{"Content-Length", "38", "Content-Type", "footype", "User-Agent", "Go-http-client/1.1", "X-Header-1", "foo", "X-Header-2", "bar"}, allHeaders(headers)) }) diff --git a/core/services/pipeline/task.lookup_test.go b/core/services/pipeline/task.lookup_test.go index 8110883c6bd..146acde0289 100644 --- a/core/services/pipeline/task.lookup_test.go +++ b/core/services/pipeline/task.lookup_test.go @@ -27,7 +27,7 @@ func Test_LookupTask(t *testing.T) { res, _ := task.Run(testutils.Context(t), logger.TestLogger(t), vars, inputs) assert.Equal(t, 42, res.Value) - assert.Nil(t, res.Error) + assert.NoError(t, res.Error) }) t.Run("returns nil if key is missing", func(t *testing.T) { task.Key = "qux" @@ -35,7 +35,7 @@ func Test_LookupTask(t *testing.T) { res, _ := task.Run(testutils.Context(t), logger.TestLogger(t), vars, inputs) - assert.Nil(t, res.Error) + assert.NoError(t, res.Error) assert.Nil(t, res.Value) }) t.Run("errors when input is not a map", func(t *testing.T) { diff --git a/core/services/pipeline/task.vrf.go b/core/services/pipeline/task.vrf.go index 0a2ed4d003d..6b7cdae154a 100644 --- a/core/services/pipeline/task.vrf.go +++ b/core/services/pipeline/task.vrf.go @@ -79,7 +79,7 @@ func (t *VRFTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Re } pk, err := secp256k1.NewPublicKeyFromBytes(pubKey) if err != nil { - return Result{Error: fmt.Errorf("failed to create PublicKey from bytes %v", err)}, runInfo + return Result{Error: fmt.Errorf("failed to create PublicKey from bytes %w", err)}, runInfo } pkh := pk.MustHash() // Validate the key against the spec diff --git a/core/services/pipeline/task.vrfv2.go b/core/services/pipeline/task.vrfv2.go index 2c2c85eaedf..c3a1c15f6f9 100644 --- a/core/services/pipeline/task.vrfv2.go +++ b/core/services/pipeline/task.vrfv2.go @@ -96,7 +96,7 @@ func (t *VRFTaskV2) Run(_ context.Context, lggr logger.Logger, vars Vars, inputs } pk, err := secp256k1.NewPublicKeyFromBytes(pubKey) if err != nil { - return Result{Error: fmt.Errorf("failed to create PublicKey from bytes %v", err)}, runInfo + return Result{Error: fmt.Errorf("failed to create PublicKey from bytes %w", err)}, runInfo } pkh := pk.MustHash() // Validate the key against the spec diff --git a/core/services/pipeline/task.vrfv2plus.go b/core/services/pipeline/task.vrfv2plus.go index 6bc299eeb6f..5b58c3c5cec 100644 --- a/core/services/pipeline/task.vrfv2plus.go +++ b/core/services/pipeline/task.vrfv2plus.go @@ -103,7 +103,7 @@ func (t *VRFTaskV2Plus) Run(_ context.Context, lggr logger.Logger, vars Vars, in } pk, err := secp256k1.NewPublicKeyFromBytes(pubKey) if err != nil { - return Result{Error: fmt.Errorf("failed to create PublicKey from bytes %v", err)}, runInfo + return Result{Error: fmt.Errorf("failed to create PublicKey from bytes %w", err)}, runInfo } pkh := pk.MustHash() // Validate the key against the spec diff --git a/core/services/registrysyncer/monitoring_test.go b/core/services/registrysyncer/monitoring_test.go index 30d773aa976..11a4017a3a9 100644 --- a/core/services/registrysyncer/monitoring_test.go +++ b/core/services/registrysyncer/monitoring_test.go @@ -16,5 +16,5 @@ func Test_InitMonitoringResources(t *testing.T) { func Test_SyncerMetricsLabeler(t *testing.T) { testSyncerMetricLabeler := syncerMetricLabeler{metrics.NewLabeler(), nil, nil} testSyncerMetricLabeler2 := testSyncerMetricLabeler.with("foo", "baz") - require.EqualValues(t, testSyncerMetricLabeler2.Labels["foo"], "baz") + require.EqualValues(t, "baz", testSyncerMetricLabeler2.Labels["foo"]) } diff --git a/core/services/registrysyncer/orm.go b/core/services/registrysyncer/orm.go index 7992f45413a..c21603ad290 100644 --- a/core/services/registrysyncer/orm.go +++ b/core/services/registrysyncer/orm.go @@ -3,6 +3,7 @@ package registrysyncer import ( "context" "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" "math/big" @@ -140,7 +141,7 @@ func (orm orm) AddLocalRegistry(ctx context.Context, localRegistry LocalRegistry _, err = tx.ExecContext( ctx, `INSERT INTO registry_syncer_states (data, data_hash) VALUES ($1, $2) ON CONFLICT (data_hash) DO NOTHING`, - localRegistryJSON, fmt.Sprintf("%x", hash[:]), + localRegistryJSON, hex.EncodeToString(hash[:]), ) if err != nil { return err diff --git a/core/services/registrysyncer/syncer_test.go b/core/services/registrysyncer/syncer_test.go index 33920c36a55..a4792107e2d 100644 --- a/core/services/registrysyncer/syncer_test.go +++ b/core/services/registrysyncer/syncer_test.go @@ -4,6 +4,7 @@ import ( "context" "crypto/rand" "encoding/json" + "errors" "fmt" "math/big" "sync" @@ -464,7 +465,7 @@ func TestSyncer_DBIntegration(t *testing.T) { factory := newContractReaderFactory(t, sim) syncerORM := newORM(t) - syncerORM.ormMock.On("LatestLocalRegistry", mock.Anything).Return(nil, fmt.Errorf("no state found")) + syncerORM.ormMock.On("LatestLocalRegistry", mock.Anything).Return(nil, errors.New("no state found")) syncerORM.ormMock.On("AddLocalRegistry", mock.Anything, mock.Anything).Return(nil) syncer, err := newTestSyncer(logger.TestLogger(t), func() (p2ptypes.PeerID, error) { return p2ptypes.PeerID{}, nil }, factory, regAddress.Hex(), syncerORM) require.NoError(t, err) diff --git a/core/services/relay/evm/cap_encoder.go b/core/services/relay/evm/cap_encoder.go index 713a9796dd2..7c0cc81d38a 100644 --- a/core/services/relay/evm/cap_encoder.go +++ b/core/services/relay/evm/cap_encoder.go @@ -7,6 +7,8 @@ import ( "encoding/json" "fmt" + "github.com/pkg/errors" + consensustypes "github.com/smartcontractkit/chainlink-common/pkg/capabilities/consensus/ocr3/types" commoncodec "github.com/smartcontractkit/chainlink-common/pkg/codec" commontypes "github.com/smartcontractkit/chainlink-common/pkg/types" @@ -116,7 +118,7 @@ func (c *capEncoder) Encode(ctx context.Context, input values.Map) ([]byte, erro } unwrappedMap, ok := unwrappedInput.(map[string]any) if !ok { - return nil, fmt.Errorf("expected unwrapped input to be a map") + return nil, errors.New("expected unwrapped input to be a map") } userPayload, err := c.codec.Encode(ctx, unwrappedMap, encoderName) if err != nil { @@ -143,7 +145,7 @@ func prependMetadataFields(meta consensustypes.Metadata, userPayload []byte) ([] // 1. Version (1 byte) if meta.Version > 255 { - return nil, fmt.Errorf("version must be between 0 and 255") + return nil, errors.New("version must be between 0 and 255") } result = append(result, byte(meta.Version)) diff --git a/core/services/relay/evm/capabilities/log_event_trigger_test.go b/core/services/relay/evm/capabilities/log_event_trigger_test.go index d248dbdc87f..0a864485400 100644 --- a/core/services/relay/evm/capabilities/log_event_trigger_test.go +++ b/core/services/relay/evm/capabilities/log_event_trigger_test.go @@ -142,7 +142,7 @@ func emitLogTxnAndWaitForLog(t *testing.T, // Verify if valid cursor is returned cursor, err := testutils.GetStrVal(output, "Cursor") require.NoError(t, err) - require.True(t, len(cursor) > 60) + require.Greater(t, len(cursor), 60) // Verify if Arg0 is correct actualLogVal, err := testutils.GetBigIntValL2(output, "Data", "Arg0") diff --git a/core/services/relay/evm/capabilities/testutils/chain_reader.go b/core/services/relay/evm/capabilities/testutils/chain_reader.go index 64fbf5fe720..8f895227367 100644 --- a/core/services/relay/evm/capabilities/testutils/chain_reader.go +++ b/core/services/relay/evm/capabilities/testutils/chain_reader.go @@ -2,6 +2,7 @@ package testutils import ( "encoding/json" + "errors" "fmt" "math/big" "testing" @@ -115,16 +116,16 @@ func WaitForLog(lggr logger.Logger, logCh <-chan commoncaps.TriggerResponse, tim *commoncaps.TriggerResponse, map[string]any, error) { select { case <-time.After(timeout): - return nil, nil, fmt.Errorf("timeout waiting for Log1 event from ContractReader") + return nil, nil, errors.New("timeout waiting for Log1 event from ContractReader") case log := <-logCh: lggr.Infow("Received log from ContractReader", "event", log.Event.ID) if log.Err != nil { - return nil, nil, fmt.Errorf("error listening for Log1 event from ContractReader: %v", log.Err) + return nil, nil, fmt.Errorf("error listening for Log1 event from ContractReader: %w", log.Err) } v := make(map[string]any) err := log.Event.Outputs.UnwrapTo(&v) if err != nil { - return nil, nil, fmt.Errorf("error unwrapping log to map: (log %v) %v", log.Event.Outputs, log.Err) + return nil, nil, fmt.Errorf("error unwrapping log to map: (log %v) %w", log.Event.Outputs, log.Err) } return &log, v, nil } diff --git a/core/services/relay/evm/ccip.go b/core/services/relay/evm/ccip.go index a06f60c6fd4..8ed1009385d 100644 --- a/core/services/relay/evm/ccip.go +++ b/core/services/relay/evm/ccip.go @@ -2,10 +2,11 @@ package evm import ( "context" - "fmt" "math/big" "time" + "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink-common/pkg/logger" cciptypes "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" @@ -67,11 +68,11 @@ func (i *IncompleteSourceCommitStoreReader) ChangeConfig(ctx context.Context, on } func (i *IncompleteSourceCommitStoreReader) DecodeCommitReport(ctx context.Context, report []byte) (cciptypes.CommitStoreReport, error) { - return cciptypes.CommitStoreReport{}, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return cciptypes.CommitStoreReport{}, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) EncodeCommitReport(ctx context.Context, report cciptypes.CommitStoreReport) ([]byte, error) { - return []byte{}, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return []byte{}, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } // GasPriceEstimator returns an ExecGasPriceEstimator to satisfy the GasPriceEstimatorCommit interface, @@ -82,35 +83,35 @@ func (i *IncompleteSourceCommitStoreReader) GasPriceEstimator(ctx context.Contex } func (i *IncompleteSourceCommitStoreReader) GetAcceptedCommitReportsGteTimestamp(ctx context.Context, ts time.Time, confirmations int) ([]cciptypes.CommitStoreReportWithTxMeta, error) { - return nil, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return nil, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) GetCommitReportMatchingSeqNum(ctx context.Context, seqNum uint64, confirmations int) ([]cciptypes.CommitStoreReportWithTxMeta, error) { - return nil, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return nil, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) GetCommitStoreStaticConfig(ctx context.Context) (cciptypes.CommitStoreStaticConfig, error) { - return cciptypes.CommitStoreStaticConfig{}, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return cciptypes.CommitStoreStaticConfig{}, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) GetExpectedNextSequenceNumber(ctx context.Context) (uint64, error) { - return 0, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return 0, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) GetLatestPriceEpochAndRound(ctx context.Context) (uint64, error) { - return 0, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return 0, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) IsBlessed(ctx context.Context, root [32]byte) (bool, error) { - return false, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return false, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) IsDestChainHealthy(ctx context.Context) (bool, error) { - return false, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return false, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) IsDown(ctx context.Context) (bool, error) { - return false, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return false, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) OffchainConfig(ctx context.Context) (cciptypes.CommitOffchainConfig, error) { @@ -118,11 +119,11 @@ func (i *IncompleteSourceCommitStoreReader) OffchainConfig(ctx context.Context) } func (i *IncompleteSourceCommitStoreReader) VerifyExecutionReport(ctx context.Context, report cciptypes.ExecReport) (bool, error) { - return false, fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return false, errors.New("invalid usage of IncompleteSourceCommitStoreReader") } func (i *IncompleteSourceCommitStoreReader) Close() error { - return fmt.Errorf("invalid usage of IncompleteSourceCommitStoreReader") + return errors.New("invalid usage of IncompleteSourceCommitStoreReader") } // IncompleteDestCommitStoreReader is an implementation of CommitStoreReader with all valid methods except @@ -143,7 +144,7 @@ func NewIncompleteDestCommitStoreReader(ctx context.Context, lggr logger.Logger, } func (i *IncompleteDestCommitStoreReader) ChangeConfig(ctx context.Context, onchainConfig []byte, offchainConfig []byte) (cciptypes.Address, error) { - return "", fmt.Errorf("invalid usage of IncompleteDestCommitStoreReader") + return "", errors.New("invalid usage of IncompleteDestCommitStoreReader") } func (i *IncompleteDestCommitStoreReader) DecodeCommitReport(ctx context.Context, report []byte) (cciptypes.CommitStoreReport, error) { @@ -155,7 +156,7 @@ func (i *IncompleteDestCommitStoreReader) EncodeCommitReport(ctx context.Context } func (i *IncompleteDestCommitStoreReader) GasPriceEstimator(ctx context.Context) (cciptypes.GasPriceEstimatorCommit, error) { - return nil, fmt.Errorf("invalid usage of IncompleteDestCommitStoreReader") + return nil, errors.New("invalid usage of IncompleteDestCommitStoreReader") } func (i *IncompleteDestCommitStoreReader) GetAcceptedCommitReportsGteTimestamp(ctx context.Context, ts time.Time, confirmations int) ([]cciptypes.CommitStoreReportWithTxMeta, error) { @@ -191,7 +192,7 @@ func (i *IncompleteDestCommitStoreReader) IsDown(ctx context.Context) (bool, err } func (i *IncompleteDestCommitStoreReader) OffchainConfig(ctx context.Context) (cciptypes.CommitOffchainConfig, error) { - return cciptypes.CommitOffchainConfig{}, fmt.Errorf("invalid usage of IncompleteDestCommitStoreReader") + return cciptypes.CommitOffchainConfig{}, errors.New("invalid usage of IncompleteDestCommitStoreReader") } func (i *IncompleteDestCommitStoreReader) VerifyExecutionReport(ctx context.Context, report cciptypes.ExecReport) (bool, error) { diff --git a/core/services/relay/evm/chain_components_test.go b/core/services/relay/evm/chain_components_test.go index 006236c060a..f9bcaf02c8b 100644 --- a/core/services/relay/evm/chain_components_test.go +++ b/core/services/relay/evm/chain_components_test.go @@ -67,7 +67,7 @@ func TestContractReaderEventsInitValidation(t *testing.T) { Configs: map[string]*types.ChainReaderDefinition{}, }, }, - expectedError: fmt.Errorf("failed to parse abi"), + expectedError: errors.New("failed to parse abi"), }, { name: "Conflicting polling filter definitions", diff --git a/core/services/relay/evm/chain_writer.go b/core/services/relay/evm/chain_writer.go index ab82a67084c..2ef3aa05df4 100644 --- a/core/services/relay/evm/chain_writer.go +++ b/core/services/relay/evm/chain_writer.go @@ -8,6 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" commonservices "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -34,7 +35,7 @@ var _ ChainWriterService = (*chainWriter)(nil) func NewChainWriterService(logger logger.Logger, client evmclient.Client, txm evmtxmgr.TxManager, estimator gas.EvmFeeEstimator, config types.ChainWriterConfig) (ChainWriterService, error) { if config.MaxGasPrice == nil { - return nil, fmt.Errorf("max gas price is required") + return nil, errors.New("max gas price is required") } w := chainWriter{ @@ -183,7 +184,7 @@ func (w *chainWriter) GetTransactionStatus(ctx context.Context, transactionID st // (if the chain doesn't support dynamic TXs) the legacy GasPrice is used. func (w *chainWriter) GetFeeComponents(ctx context.Context) (*commontypes.ChainFeeComponents, error) { if w.ge == nil { - return nil, fmt.Errorf("gas estimator not available") + return nil, errors.New("gas estimator not available") } fee, _, err := w.ge.GetFee(ctx, nil, 0, w.maxGasPrice, nil, nil) diff --git a/core/services/relay/evm/chain_writer_test.go b/core/services/relay/evm/chain_writer_test.go index 50ef2dd114e..45cfec4647a 100644 --- a/core/services/relay/evm/chain_writer_test.go +++ b/core/services/relay/evm/chain_writer_test.go @@ -1,11 +1,11 @@ package evm import ( - "fmt" "math/big" "testing" "github.com/google/uuid" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -133,7 +133,7 @@ func TestChainWriter(t *testing.T) { }) t.Run("Fails when GetFee returns an error", func(t *testing.T) { - expectedErr := fmt.Errorf("GetFee error") + expectedErr := errors.New("GetFee error") ge.On("GetFee", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(gas.EvmFee{ GasPrice: nil, DynamicFee: gas.DynamicFee{}, @@ -149,7 +149,7 @@ func TestChainWriter(t *testing.T) { }, uint64(0), nil).Once() ge.On("L1Oracle", mock.Anything).Return(l1Oracle).Once() - expectedErr := fmt.Errorf("l1Oracle error") + expectedErr := errors.New("l1Oracle error") l1Oracle.On("GasPrice", mock.Anything).Return(nil, expectedErr).Once() _, err = cw.GetFeeComponents(ctx) require.Equal(t, expectedErr, err) diff --git a/core/services/relay/evm/commit_provider.go b/core/services/relay/evm/commit_provider.go index 95d7371ab16..378679104f9 100644 --- a/core/services/relay/evm/commit_provider.go +++ b/core/services/relay/evm/commit_provider.go @@ -9,6 +9,7 @@ import ( "go.uber.org/multierr" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/pkg/errors" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -242,11 +243,11 @@ func (p *DstCommitProvider) Start(ctx context.Context) error { } func (p *SrcCommitProvider) NewPriceGetter(ctx context.Context) (priceGetter cciptypes.PriceGetter, err error) { - return nil, fmt.Errorf("can't construct a price getter from one relayer") + return nil, errors.New("can't construct a price getter from one relayer") } func (p *DstCommitProvider) NewPriceGetter(ctx context.Context) (priceGetter cciptypes.PriceGetter, err error) { - return nil, fmt.Errorf("can't construct a price getter from one relayer") + return nil, errors.New("can't construct a price getter from one relayer") } func (p *SrcCommitProvider) NewCommitStoreReader(ctx context.Context, commitStoreAddress cciptypes.Address) (commitStoreReader cciptypes.CommitStoreReader, err error) { @@ -273,11 +274,11 @@ func (p *SrcCommitProvider) NewOnRampReader(ctx context.Context, onRampAddress c } func (p *DstCommitProvider) NewOnRampReader(ctx context.Context, onRampAddress cciptypes.Address, sourceChainSelector uint64, destChainSelector uint64) (onRampReader cciptypes.OnRampReader, err error) { - return nil, fmt.Errorf("invalid: NewOnRampReader called for DstCommitProvider.NewOnRampReader should be called on SrcCommitProvider") + return nil, errors.New("invalid: NewOnRampReader called for DstCommitProvider.NewOnRampReader should be called on SrcCommitProvider") } func (p *SrcCommitProvider) NewOffRampReader(ctx context.Context, offRampAddr cciptypes.Address) (offRampReader cciptypes.OffRampReader, err error) { - return nil, fmt.Errorf("invalid: NewOffRampReader called for SrcCommitProvider. NewOffRampReader should be called on DstCommitProvider") + return nil, errors.New("invalid: NewOffRampReader called for SrcCommitProvider. NewOffRampReader should be called on DstCommitProvider") } func (p *DstCommitProvider) NewOffRampReader(ctx context.Context, offRampAddr cciptypes.Address) (offRampReader cciptypes.OffRampReader, err error) { @@ -286,7 +287,7 @@ func (p *DstCommitProvider) NewOffRampReader(ctx context.Context, offRampAddr cc } func (p *SrcCommitProvider) NewPriceRegistryReader(ctx context.Context, addr cciptypes.Address) (priceRegistryReader cciptypes.PriceRegistryReader, err error) { - return nil, fmt.Errorf("invalid: NewPriceRegistryReader called for SrcCommitProvider. NewOffRampReader should be called on DstCommitProvider") + return nil, errors.New("invalid: NewPriceRegistryReader called for SrcCommitProvider. NewOffRampReader should be called on DstCommitProvider") } func (p *DstCommitProvider) NewPriceRegistryReader(ctx context.Context, addr cciptypes.Address) (priceRegistryReader cciptypes.PriceRegistryReader, err error) { @@ -313,5 +314,5 @@ func (p *SrcCommitProvider) SourceNativeToken(ctx context.Context, sourceRouterA } func (p *DstCommitProvider) SourceNativeToken(ctx context.Context, sourceRouterAddr cciptypes.Address) (cciptypes.Address, error) { - return "", fmt.Errorf("invalid: SourceNativeToken called for DstCommitProvider. SourceNativeToken should be called on SrcCommitProvider") + return "", errors.New("invalid: SourceNativeToken called for DstCommitProvider. SourceNativeToken should be called on SrcCommitProvider") } diff --git a/core/services/relay/evm/evm.go b/core/services/relay/evm/evm.go index e60dbe1bfdb..31928c28e59 100644 --- a/core/services/relay/evm/evm.go +++ b/core/services/relay/evm/evm.go @@ -100,11 +100,11 @@ var _ commontypes.Relayer = &Relayer{} type UnimplementedOffchainConfigDigester struct{} func (e UnimplementedOffchainConfigDigester) ConfigDigest(ctx context.Context, config ocrtypes.ContractConfig) (ocrtypes.ConfigDigest, error) { - return ocrtypes.ConfigDigest{}, fmt.Errorf("unimplemented for this relayer") + return ocrtypes.ConfigDigest{}, errors.New("unimplemented for this relayer") } func (e UnimplementedOffchainConfigDigester) ConfigDigestPrefix(ctx context.Context) (ocrtypes.ConfigDigestPrefix, error) { - return 0, fmt.Errorf("unimplemented for this relayer") + return 0, errors.New("unimplemented for this relayer") } // [UnimplementedContractConfigTracker] satisfies the OCR ContractConfigTracker interface @@ -115,30 +115,30 @@ func (u UnimplementedContractConfigTracker) Notify() <-chan struct{} { } func (u UnimplementedContractConfigTracker) LatestConfigDetails(ctx context.Context) (changedInBlock uint64, configDigest ocrtypes.ConfigDigest, err error) { - return 0, ocrtypes.ConfigDigest{}, fmt.Errorf("unimplemented for this relayer") + return 0, ocrtypes.ConfigDigest{}, errors.New("unimplemented for this relayer") } func (u UnimplementedContractConfigTracker) LatestConfig(ctx context.Context, changedInBlock uint64) (ocrtypes.ContractConfig, error) { - return ocrtypes.ContractConfig{}, fmt.Errorf("unimplemented for this relayer") + return ocrtypes.ContractConfig{}, errors.New("unimplemented for this relayer") } func (u UnimplementedContractConfigTracker) LatestBlockHeight(ctx context.Context) (blockHeight uint64, err error) { - return 0, fmt.Errorf("unimplemented for this relayer") + return 0, errors.New("unimplemented for this relayer") } // [UnimplementedContractTransmitter] satisfies the OCR ContractTransmitter interface type UnimplementedContractTransmitter struct{} func (u UnimplementedContractTransmitter) Transmit(context.Context, ocrtypes.ReportContext, ocrtypes.Report, []ocrtypes.AttributedOnchainSignature) error { - return fmt.Errorf("unimplemented for this relayer") + return errors.New("unimplemented for this relayer") } func (u UnimplementedContractTransmitter) FromAccount(ctx context.Context) (ocrtypes.Account, error) { - return "", fmt.Errorf("unimplemented for this relayer") + return "", errors.New("unimplemented for this relayer") } func (u UnimplementedContractTransmitter) LatestConfigDigestAndEpoch(ctx context.Context) (configDigest ocrtypes.ConfigDigest, epoch uint32, err error) { - return ocrtypes.ConfigDigest{}, 0, fmt.Errorf("unimplemented for this relayer") + return ocrtypes.ConfigDigest{}, 0, errors.New("unimplemented for this relayer") } type Relayer struct { @@ -232,7 +232,7 @@ func NewRelayer(ctx context.Context, lggr logger.Logger, chain legacyevm.Chain, // Initialize write target capability if configuration is defined if wCfg.ForwarderAddress() != nil && wCfg.FromAddress() != nil { if wCfg.GasLimitDefault() == nil { - return nil, fmt.Errorf("unable to instantiate write target as default gas limit is not set") + return nil, errors.New("unable to instantiate write target as default gas limit is not set") } capability, err := NewWriteTarget(ctx, relayer, chain, *wCfg.GasLimitDefault(), lggr) @@ -857,7 +857,7 @@ func generateTransmitterFrom(ctx context.Context, rargs commontypes.RelayArgs, e func (r *Relayer) NewContractWriter(_ context.Context, config []byte) (commontypes.ContractWriter, error) { var cfg types.ChainWriterConfig if err := json.Unmarshal(config, &cfg); err != nil { - return nil, fmt.Errorf("failed to unmarshall chain writer config err: %s", err) + return nil, fmt.Errorf("failed to unmarshall chain writer config err: %w", err) } cfg.MaxGasPrice = r.chain.Config().EVM().GasEstimator().PriceMax() @@ -867,7 +867,7 @@ func (r *Relayer) NewContractWriter(_ context.Context, config []byte) (commontyp func (r *Relayer) NewContractReader(ctx context.Context, chainReaderConfig []byte) (commontypes.ContractReader, error) { cfg := &types.ChainReaderConfig{} if err := json.Unmarshal(chainReaderConfig, cfg); err != nil { - return nil, fmt.Errorf("failed to unmarshall chain reader config err: %s", err) + return nil, fmt.Errorf("failed to unmarshall chain reader config err: %w", err) } return NewChainReaderService(ctx, r.lggr, r.chain.LogPoller(), r.chain.HeadTracker(), r.chain.Client(), *cfg) diff --git a/core/services/relay/evm/exec_provider.go b/core/services/relay/evm/exec_provider.go index da190d20356..c656e3243b7 100644 --- a/core/services/relay/evm/exec_provider.go +++ b/core/services/relay/evm/exec_provider.go @@ -11,6 +11,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -162,7 +163,7 @@ func (s *SrcExecProvider) Codec() commontypes.Codec { } func (s *SrcExecProvider) GetTransactionStatus(ctx context.Context, transactionID string) (types.TransactionStatus, error) { - return 0, fmt.Errorf("invalid: GetTransactionStatus called on SrcExecProvider. It should only be called on DstExecProvider") + return 0, errors.New("invalid: GetTransactionStatus called on SrcExecProvider. It should only be called on DstExecProvider") } func (s *SrcExecProvider) NewCommitStoreReader(ctx context.Context, addr cciptypes.Address) (commitStoreReader cciptypes.CommitStoreReader, err error) { @@ -171,7 +172,7 @@ func (s *SrcExecProvider) NewCommitStoreReader(ctx context.Context, addr cciptyp } func (s *SrcExecProvider) NewOffRampReader(ctx context.Context, addr cciptypes.Address) (cciptypes.OffRampReader, error) { - return nil, fmt.Errorf("invalid: NewOffRampReader called on SrcExecProvider. Valid on DstExecProvider") + return nil, errors.New("invalid: NewOffRampReader called on SrcExecProvider. Valid on DstExecProvider") } func (s *SrcExecProvider) NewOnRampReader(ctx context.Context, onRampAddress cciptypes.Address, sourceChainSelector uint64, destChainSelector uint64) (onRampReader cciptypes.OnRampReader, err error) { @@ -209,7 +210,7 @@ func (s *SrcExecProvider) NewTokenDataReader(ctx context.Context, tokenAddress c } func (s *SrcExecProvider) NewTokenPoolBatchedReader(ctx context.Context, offRampAddr cciptypes.Address, sourceChainSelector uint64) (cciptypes.TokenPoolBatchedReader, error) { - return nil, fmt.Errorf("invalid: NewTokenPoolBatchedReader called on SrcExecProvider. It should only be called on DstExecProvdier") + return nil, errors.New("invalid: NewTokenPoolBatchedReader called on SrcExecProvider. It should only be called on DstExecProvdier") } func (s *SrcExecProvider) SourceNativeToken(ctx context.Context, sourceRouterAddr cciptypes.Address) (cciptypes.Address, error) { @@ -360,7 +361,7 @@ func (d *DstExecProvider) NewOffRampReader(ctx context.Context, offRampAddress c } func (d *DstExecProvider) NewOnRampReader(ctx context.Context, addr cciptypes.Address, sourceChainSelector uint64, destChainSelector uint64) (cciptypes.OnRampReader, error) { - return nil, fmt.Errorf("invalid: NewOnRampReader called on DstExecProvider. It should only be called on SrcExecProvider") + return nil, errors.New("invalid: NewOnRampReader called on DstExecProvider. It should only be called on SrcExecProvider") } func (d *DstExecProvider) NewPriceRegistryReader(ctx context.Context, addr cciptypes.Address) (priceRegistryReader cciptypes.PriceRegistryReader, err error) { @@ -370,7 +371,7 @@ func (d *DstExecProvider) NewPriceRegistryReader(ctx context.Context, addr ccipt } func (d *DstExecProvider) NewTokenDataReader(ctx context.Context, tokenAddress cciptypes.Address) (cciptypes.TokenDataReader, error) { - return nil, fmt.Errorf("invalid: NewTokenDataReader called on DstExecProvider. It should only be called on SrcExecProvider") + return nil, errors.New("invalid: NewTokenDataReader called on DstExecProvider. It should only be called on SrcExecProvider") } func (d *DstExecProvider) NewTokenPoolBatchedReader(ctx context.Context, offRampAddress cciptypes.Address, sourceChainSelector uint64) (tokenPoolBatchedReader cciptypes.TokenPoolBatchedReader, err error) { @@ -390,5 +391,5 @@ func (d *DstExecProvider) NewTokenPoolBatchedReader(ctx context.Context, offRamp } func (d *DstExecProvider) SourceNativeToken(ctx context.Context, addr cciptypes.Address) (cciptypes.Address, error) { - return "", fmt.Errorf("invalid: SourceNativeToken called on DstExecProvider. It should only be called on SrcExecProvider") + return "", errors.New("invalid: SourceNativeToken called on DstExecProvider. It should only be called on SrcExecProvider") } diff --git a/core/services/relay/evm/functions/logpoller_wrapper_test.go b/core/services/relay/evm/functions/logpoller_wrapper_test.go index 583e6617417..594bdfff75c 100644 --- a/core/services/relay/evm/functions/logpoller_wrapper_test.go +++ b/core/services/relay/evm/functions/logpoller_wrapper_test.go @@ -104,8 +104,8 @@ func TestLogPollerWrapper_SingleSubscriberEmptyEvents(t *testing.T) { subscriber.updates.Wait() reqs, resps, err := lpWrapper.LatestEvents(ctx) require.NoError(t, err) - require.Equal(t, 0, len(reqs)) - require.Equal(t, 0, len(resps)) + require.Empty(t, reqs) + require.Empty(t, resps) } func TestLogPollerWrapper_ErrorOnZeroAddresses(t *testing.T) { @@ -147,14 +147,14 @@ func TestLogPollerWrapper_LatestEvents_ReorgHandling(t *testing.T) { oracleRequests, _, err := lpWrapper.LatestEvents(ctx) require.NoError(t, err) - assert.Equal(t, 1, len(oracleRequests)) + assert.Len(t, oracleRequests, 1) oracleRequests, _, err = lpWrapper.LatestEvents(ctx) require.NoError(t, err) - assert.Equal(t, 0, len(oracleRequests)) + assert.Empty(t, oracleRequests) require.NoError(t, err) oracleRequests, _, err = lpWrapper.LatestEvents(ctx) require.NoError(t, err) - assert.Equal(t, 0, len(oracleRequests)) + assert.Empty(t, oracleRequests) } func TestLogPollerWrapper_FilterPreviouslyDetectedEvents_TruncatesLogs(t *testing.T) { @@ -170,9 +170,9 @@ func TestLogPollerWrapper_FilterPreviouslyDetectedEvents_TruncatesLogs(t *testin mockedDetectedEvents := detectedEvents{isPreviouslyDetected: make(map[[32]byte]struct{})} outputLogs := functionsLpWrapper.filterPreviouslyDetectedEvents(inputLogs, &mockedDetectedEvents, "request") - assert.Equal(t, maxLogsToProcess, len(outputLogs)) - assert.Equal(t, 1000, len(mockedDetectedEvents.detectedEventsOrdered)) - assert.Equal(t, 1000, len(mockedDetectedEvents.isPreviouslyDetected)) + assert.Len(t, outputLogs, maxLogsToProcess) + assert.Len(t, mockedDetectedEvents.detectedEventsOrdered, 1000) + assert.Len(t, mockedDetectedEvents.isPreviouslyDetected, 1000) } func TestLogPollerWrapper_FilterPreviouslyDetectedEvents_SkipsInvalidLog(t *testing.T) { @@ -185,9 +185,9 @@ func TestLogPollerWrapper_FilterPreviouslyDetectedEvents_SkipsInvalidLog(t *test functionsLpWrapper := lpWrapper.(*logPollerWrapper) outputLogs := functionsLpWrapper.filterPreviouslyDetectedEvents(inputLogs, &mockedDetectedEvents, "request") - assert.Equal(t, 0, len(outputLogs)) - assert.Equal(t, 0, len(mockedDetectedEvents.detectedEventsOrdered)) - assert.Equal(t, 0, len(mockedDetectedEvents.isPreviouslyDetected)) + assert.Empty(t, outputLogs) + assert.Empty(t, mockedDetectedEvents.detectedEventsOrdered) + assert.Empty(t, mockedDetectedEvents.isPreviouslyDetected) } func TestLogPollerWrapper_FilterPreviouslyDetectedEvents_FiltersPreviouslyDetectedEvent(t *testing.T) { @@ -211,10 +211,10 @@ func TestLogPollerWrapper_FilterPreviouslyDetectedEvents_FiltersPreviouslyDetect functionsLpWrapper := lpWrapper.(*logPollerWrapper) outputLogs := functionsLpWrapper.filterPreviouslyDetectedEvents(inputLogs, &mockedDetectedEvents, "request") - assert.Equal(t, 0, len(outputLogs)) + assert.Empty(t, outputLogs) // Ensure that expired events are removed from the cache - assert.Equal(t, 0, len(mockedDetectedEvents.detectedEventsOrdered)) - assert.Equal(t, 0, len(mockedDetectedEvents.isPreviouslyDetected)) + assert.Empty(t, mockedDetectedEvents.detectedEventsOrdered) + assert.Empty(t, mockedDetectedEvents.isPreviouslyDetected) } func TestLogPollerWrapper_UnregisterOldFiltersOnRouteUpgrade(t *testing.T) { diff --git a/core/services/relay/evm/llo/config_poller.go b/core/services/relay/evm/llo/config_poller.go index 1f328ab73c3..53c9bdb60f3 100644 --- a/core/services/relay/evm/llo/config_poller.go +++ b/core/services/relay/evm/llo/config_poller.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "database/sql" + "encoding/hex" "fmt" "math" "math/big" @@ -222,7 +223,7 @@ type FullConfigFromLog struct { func FullConfigFromProductionConfigSet(unpacked configurator.ConfiguratorProductionConfigSet) (FullConfigFromLog, error) { var transmitAccounts []ocrtypes.Account for _, addr := range unpacked.OffchainTransmitters { - transmitAccounts = append(transmitAccounts, ocrtypes.Account(fmt.Sprintf("%x", addr))) + transmitAccounts = append(transmitAccounts, ocrtypes.Account(hex.EncodeToString(addr[:]))) } var signers []ocrtypes.OnchainPublicKey for _, addr := range unpacked.Signers { @@ -254,7 +255,7 @@ func FullConfigFromProductionConfigSet(unpacked configurator.ConfiguratorProduct func FullConfigFromStagingConfigSet(unpacked configurator.ConfiguratorStagingConfigSet) (FullConfigFromLog, error) { var transmitAccounts []ocrtypes.Account for _, addr := range unpacked.OffchainTransmitters { - transmitAccounts = append(transmitAccounts, ocrtypes.Account(fmt.Sprintf("%x", addr))) + transmitAccounts = append(transmitAccounts, ocrtypes.Account(hex.EncodeToString(addr[:]))) } var signers []ocrtypes.OnchainPublicKey for _, addr := range unpacked.Signers { diff --git a/core/services/relay/evm/llo/offchain_config_digester.go b/core/services/relay/evm/llo/offchain_config_digester.go index 08356619a25..139b6ffa79e 100644 --- a/core/services/relay/evm/llo/offchain_config_digester.go +++ b/core/services/relay/evm/llo/offchain_config_digester.go @@ -5,7 +5,6 @@ import ( "crypto/ed25519" "encoding/binary" "encoding/hex" - "fmt" "math/big" "strings" @@ -82,7 +81,7 @@ func makeConfigDigestArgs() abi.Arguments { abi, err := abi.JSON(strings.NewReader(exposed_configurator.ExposedConfiguratorABI)) if err != nil { // assertion - panic(fmt.Sprintf("could not parse configurator ABI: %s", err.Error())) + panic("could not parse configurator ABI: " + err.Error()) } return abi.Methods["exposedConfigDigestFromConfigData"].Inputs } diff --git a/core/services/relay/evm/llo_provider.go b/core/services/relay/evm/llo_provider.go index ab7cac6da0c..e96efecfa7a 100644 --- a/core/services/relay/evm/llo_provider.go +++ b/core/services/relay/evm/llo_provider.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "math/big" + "strconv" "github.com/ethereum/go-ethereum/common" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -54,7 +55,7 @@ type lloProvider struct { } func lloProviderConfiguratorFilterName(addr common.Address, donID uint32) string { - return logpoller.FilterName("LLOProvider Configurator", addr.String(), fmt.Sprintf("%d", donID)) + return logpoller.FilterName("LLOProvider Configurator", addr.String(), strconv.FormatUint(uint64(donID), 10)) } func NewLLOProvider( diff --git a/core/services/relay/evm/mercury/config_digest.go b/core/services/relay/evm/mercury/config_digest.go index c7a6076c886..99d5f6bc41d 100644 --- a/core/services/relay/evm/mercury/config_digest.go +++ b/core/services/relay/evm/mercury/config_digest.go @@ -2,7 +2,6 @@ package mercury import ( "encoding/binary" - "fmt" "math/big" "strings" @@ -19,7 +18,7 @@ func makeConfigDigestArgs() abi.Arguments { abi, err := abi.JSON(strings.NewReader(exposed_verifier.ExposedVerifierABI)) if err != nil { // assertion - panic(fmt.Sprintf("could not parse aggregator ABI: %s", err.Error())) + panic("could not parse aggregator ABI: " + err.Error()) } return abi.Methods["exposedConfigDigestFromConfigData"].Inputs } diff --git a/core/services/relay/evm/mercury/config_poller.go b/core/services/relay/evm/mercury/config_poller.go index 7bb5d2af7b5..1f7dbb0c5ae 100644 --- a/core/services/relay/evm/mercury/config_poller.go +++ b/core/services/relay/evm/mercury/config_poller.go @@ -3,7 +3,7 @@ package mercury import ( "context" "database/sql" - "fmt" + "encoding/hex" "strings" "github.com/ethereum/go-ethereum/accounts/abi" @@ -62,7 +62,7 @@ func ConfigFromLog(logData []byte) (FullConfigFromLog, error) { var transmitAccounts []ocrtypes.Account for _, addr := range unpacked.OffchainTransmitters { - transmitAccounts = append(transmitAccounts, ocrtypes.Account(fmt.Sprintf("%x", addr))) + transmitAccounts = append(transmitAccounts, ocrtypes.Account(hex.EncodeToString(addr[:]))) } var signers []ocrtypes.OnchainPublicKey for _, addr := range unpacked.Signers { diff --git a/core/services/relay/evm/mercury/config_poller_test.go b/core/services/relay/evm/mercury/config_poller_test.go index 2eb6be25910..b8df238902a 100644 --- a/core/services/relay/evm/mercury/config_poller_test.go +++ b/core/services/relay/evm/mercury/config_poller_test.go @@ -1,7 +1,7 @@ package mercury import ( - "fmt" + "encoding/hex" "testing" "time" @@ -79,7 +79,7 @@ func TestMercuryConfigPoller(t *testing.T) { encodedTransmitter := make([]ocrtypes2.Account, n) for i := 0; i < n; i++ { offchainTransmitters[i] = oracles[i].OffchainPublicKey - encodedTransmitter[i] = ocrtypes2.Account(fmt.Sprintf("%x", oracles[i].OffchainPublicKey[:])) + encodedTransmitter[i] = ocrtypes2.Account(hex.EncodeToString(oracles[i].OffchainPublicKey[:])) } _, err = th.verifierContract.SetConfig(th.user, feedIDBytes, signerAddresses, offchainTransmitters, f, onchainConfig, offchainConfigVersion, offchainConfig, nil) diff --git a/core/services/relay/evm/mercury/orm_test.go b/core/services/relay/evm/mercury/orm_test.go index f3ff70cdced..2361402b78c 100644 --- a/core/services/relay/evm/mercury/orm_test.go +++ b/core/services/relay/evm/mercury/orm_test.go @@ -61,16 +61,16 @@ func TestORM(t *testing.T) { transmissions, err := orm.GetTransmitRequests(ctx, sURL, jobID) require.NoError(t, err) - require.Equal(t, transmissions, []*Transmission{ + require.Equal(t, []*Transmission{ {Req: &pb.TransmitRequest{Payload: reports[2]}, ReportCtx: reportContexts[2]}, {Req: &pb.TransmitRequest{Payload: reports[1]}, ReportCtx: reportContexts[1]}, {Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: reportContexts[0]}, - }) + }, transmissions) transmissions, err = orm.GetTransmitRequests(ctx, sURL2, jobID) require.NoError(t, err) - require.Equal(t, transmissions, []*Transmission{ + require.Equal(t, []*Transmission{ {Req: &pb.TransmitRequest{Payload: reports[3]}, ReportCtx: reportContexts[0]}, - }) + }, transmissions) l, err = orm.LatestReport(testutils.Context(t), feedID) require.NoError(t, err) @@ -83,10 +83,10 @@ func TestORM(t *testing.T) { transmissions, err = orm.GetTransmitRequests(ctx, sURL, jobID) require.NoError(t, err) - require.Equal(t, transmissions, []*Transmission{ + require.Equal(t, []*Transmission{ {Req: &pb.TransmitRequest{Payload: reports[2]}, ReportCtx: reportContexts[2]}, {Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: reportContexts[0]}, - }) + }, transmissions) l, err = orm.LatestReport(testutils.Context(t), feedID) require.NoError(t, err) @@ -98,10 +98,10 @@ func TestORM(t *testing.T) { transmissions, err = orm.GetTransmitRequests(ctx, sURL, jobID) require.NoError(t, err) - require.Equal(t, transmissions, []*Transmission{ + require.Equal(t, []*Transmission{ {Req: &pb.TransmitRequest{Payload: reports[2]}, ReportCtx: reportContexts[2]}, {Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: reportContexts[0]}, - }) + }, transmissions) // Test deleting multiple requests. err = orm.DeleteTransmitRequests(ctx, sURL, []*pb.TransmitRequest{ @@ -124,9 +124,9 @@ func TestORM(t *testing.T) { transmissions, err = orm.GetTransmitRequests(ctx, sURL, jobID) require.NoError(t, err) - require.Equal(t, transmissions, []*Transmission{ + require.Equal(t, []*Transmission{ {Req: &pb.TransmitRequest{Payload: reports[3]}, ReportCtx: reportContexts[3]}, - }) + }, transmissions) // Duplicate requests are ignored. err = orm.InsertTransmitRequest(ctx, []string{sURL}, &pb.TransmitRequest{Payload: reports[3]}, jobID, reportContexts[3]) @@ -136,9 +136,9 @@ func TestORM(t *testing.T) { transmissions, err = orm.GetTransmitRequests(ctx, sURL, jobID) require.NoError(t, err) - require.Equal(t, transmissions, []*Transmission{ + require.Equal(t, []*Transmission{ {Req: &pb.TransmitRequest{Payload: reports[3]}, ReportCtx: reportContexts[3]}, - }) + }, transmissions) l, err = orm.LatestReport(testutils.Context(t), feedID) require.NoError(t, err) @@ -178,17 +178,17 @@ func TestORM_InsertTransmitRequest_MultipleServerURLs(t *testing.T) { transmissions, err := orm.GetTransmitRequests(ctx, sURL, jobID) require.NoError(t, err) require.Len(t, transmissions, 1) - assert.Equal(t, transmissions[0], &Transmission{Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: reportContexts[0]}) + assert.Equal(t, &Transmission{Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: reportContexts[0]}, transmissions[0]) transmissions, err = orm.GetTransmitRequests(ctx, sURL2, jobID) require.NoError(t, err) require.Len(t, transmissions, 1) - assert.Equal(t, transmissions[0], &Transmission{Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: reportContexts[0]}) + assert.Equal(t, &Transmission{Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: reportContexts[0]}, transmissions[0]) transmissions, err = orm.GetTransmitRequests(ctx, sURL3, jobID) require.NoError(t, err) require.Len(t, transmissions, 1) - assert.Equal(t, transmissions[0], &Transmission{Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: reportContexts[0]}) + assert.Equal(t, &Transmission{Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: reportContexts[0]}, transmissions[0]) l, err := orm.LatestReport(testutils.Context(t), feedID) require.NoError(t, err) @@ -238,10 +238,10 @@ func TestORM_PruneTransmitRequests(t *testing.T) { transmissions, err := orm.GetTransmitRequests(ctx, sURL, jobID) require.NoError(t, err) - require.Equal(t, transmissions, []*Transmission{ + require.Equal(t, []*Transmission{ {Req: &pb.TransmitRequest{Payload: reports[1]}, ReportCtx: makeReportContext(1, 2)}, {Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: makeReportContext(1, 1)}, - }) + }, transmissions) // Max size equal to number of records, expect no-op err = orm.PruneTransmitRequests(ctx, sURL, jobID, 2) @@ -249,10 +249,10 @@ func TestORM_PruneTransmitRequests(t *testing.T) { transmissions, err = orm.GetTransmitRequests(ctx, sURL, jobID) require.NoError(t, err) - require.Equal(t, transmissions, []*Transmission{ + require.Equal(t, []*Transmission{ {Req: &pb.TransmitRequest{Payload: reports[1]}, ReportCtx: makeReportContext(1, 2)}, {Req: &pb.TransmitRequest{Payload: reports[0]}, ReportCtx: makeReportContext(1, 1)}, - }) + }, transmissions) // Max size is number of records + 1, but jobID differs, expect no-op err = orm.PruneTransmitRequests(ctx, sURL, -1, 2) diff --git a/core/services/relay/evm/mercury/persistence_manager_test.go b/core/services/relay/evm/mercury/persistence_manager_test.go index 1ba999614a6..3487f2f9d82 100644 --- a/core/services/relay/evm/mercury/persistence_manager_test.go +++ b/core/services/relay/evm/mercury/persistence_manager_test.go @@ -64,7 +64,7 @@ func TestPersistenceManager(t *testing.T) { transmissions, err = pm2.Load(ctx) require.NoError(t, err) - assert.Len(t, transmissions, 0) + assert.Empty(t, transmissions) }) } diff --git a/core/services/relay/evm/mercury/queue.go b/core/services/relay/evm/mercury/queue.go index a450d21af6e..9d48367a7a1 100644 --- a/core/services/relay/evm/mercury/queue.go +++ b/core/services/relay/evm/mercury/queue.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "strconv" "sync" "time" @@ -83,7 +84,7 @@ func NewTransmitQueue(lggr logger.Logger, serverURL, feedID string, maxlen int, maxlen, false, nil, - transmitQueueLoad.WithLabelValues(feedID, serverURL, fmt.Sprintf("%d", maxlen)), + transmitQueueLoad.WithLabelValues(feedID, serverURL, strconv.Itoa(maxlen)), } } diff --git a/core/services/relay/evm/mercury/queue_test.go b/core/services/relay/evm/mercury/queue_test.go index 8e5a0caf614..c9235119d02 100644 --- a/core/services/relay/evm/mercury/queue_test.go +++ b/core/services/relay/evm/mercury/queue_test.go @@ -77,13 +77,13 @@ func Test_Queue(t *testing.T) { require.True(t, ok) } report := transmitQueue.HealthReport() - assert.Nil(t, report[transmitQueue.Name()]) + assert.NoError(t, report[transmitQueue.Name()]) }) t.Run("transmit queue is more than 50% full", func(t *testing.T) { transmitQueue.Push(testTransmissions[2].tr, testTransmissions[2].ctx) report := transmitQueue.HealthReport() - assert.Equal(t, report[transmitQueue.Name()].Error(), "transmit priority queue is greater than 50% full (4/7)") + assert.Equal(t, "transmit priority queue is greater than 50% full (4/7)", report[transmitQueue.Name()].Error()) }) t.Run("transmit queue pops the highest priority transmission", func(t *testing.T) { diff --git a/core/services/relay/evm/mercury/transmitter.go b/core/services/relay/evm/mercury/transmitter.go index be500593bf3..5605b331ca4 100644 --- a/core/services/relay/evm/mercury/transmitter.go +++ b/core/services/relay/evm/mercury/transmitter.go @@ -9,6 +9,7 @@ import ( "io" "math/big" "sort" + "strconv" "sync" "time" @@ -273,7 +274,7 @@ func (s *server) runQueueLoop(stopCh services.StopChan, wg *sync.WaitGroup, feed s.transmitDuplicateCount.Inc() s.lggr.Debugw("Transmit report success; duplicate report", "payload", hexutil.Encode(t.Req.Payload), "response", res, "repts", t.ReportCtx.ReportTimestamp) default: - transmitServerErrorCount.WithLabelValues(feedIDHex, s.url, fmt.Sprintf("%d", res.Code)).Inc() + transmitServerErrorCount.WithLabelValues(feedIDHex, s.url, strconv.Itoa(int(res.Code))).Inc() s.lggr.Errorw("Transmit report failed; mercury server returned error", "response", res, "reportCtx", t.ReportCtx, "err", res.Error, "code", res.Code) } } diff --git a/core/services/relay/evm/mercury/transmitter_test.go b/core/services/relay/evm/mercury/transmitter_test.go index 70ee8fca74f..83fbde35222 100644 --- a/core/services/relay/evm/mercury/transmitter_test.go +++ b/core/services/relay/evm/mercury/transmitter_test.go @@ -61,7 +61,7 @@ func Test_MercuryTransmitter_Transmit(t *testing.T) { require.NoError(t, err) // ensure it was added to the queue - require.Equal(t, mt.servers[sURL].q.(*transmitQueue).pq.Len(), 1) + require.Equal(t, 1, mt.servers[sURL].q.(*transmitQueue).pq.Len()) assert.Subset(t, mt.servers[sURL].q.(*transmitQueue).pq.Pop().(*Transmission).Req.Payload, report) }) t.Run("v2 report transmission successfully enqueued", func(t *testing.T) { @@ -75,7 +75,7 @@ func Test_MercuryTransmitter_Transmit(t *testing.T) { require.NoError(t, err) // ensure it was added to the queue - require.Equal(t, mt.servers[sURL].q.(*transmitQueue).pq.Len(), 1) + require.Equal(t, 1, mt.servers[sURL].q.(*transmitQueue).pq.Len()) assert.Subset(t, mt.servers[sURL].q.(*transmitQueue).pq.Pop().(*Transmission).Req.Payload, report) }) t.Run("v3 report transmission successfully enqueued", func(t *testing.T) { @@ -89,7 +89,7 @@ func Test_MercuryTransmitter_Transmit(t *testing.T) { require.NoError(t, err) // ensure it was added to the queue - require.Equal(t, mt.servers[sURL].q.(*transmitQueue).pq.Len(), 1) + require.Equal(t, 1, mt.servers[sURL].q.(*transmitQueue).pq.Len()) assert.Subset(t, mt.servers[sURL].q.(*transmitQueue).pq.Pop().(*Transmission).Req.Payload, report) }) t.Run("v3 report transmission sent only to trigger service", func(t *testing.T) { @@ -104,7 +104,7 @@ func Test_MercuryTransmitter_Transmit(t *testing.T) { err = mt.Transmit(testutils.Context(t), sampleReportContext, report, sampleSigs) require.NoError(t, err) // queue is empty - require.Equal(t, mt.servers[sURL].q.(*transmitQueue).pq.Len(), 0) + require.Equal(t, 0, mt.servers[sURL].q.(*transmitQueue).pq.Len()) }) }) @@ -125,11 +125,11 @@ func Test_MercuryTransmitter_Transmit(t *testing.T) { require.NoError(t, err) // ensure it was added to the queue - require.Equal(t, mt.servers[sURL].q.(*transmitQueue).pq.Len(), 1) + require.Equal(t, 1, mt.servers[sURL].q.(*transmitQueue).pq.Len()) assert.Subset(t, mt.servers[sURL].q.(*transmitQueue).pq.Pop().(*Transmission).Req.Payload, report) - require.Equal(t, mt.servers[sURL2].q.(*transmitQueue).pq.Len(), 1) + require.Equal(t, 1, mt.servers[sURL2].q.(*transmitQueue).pq.Len()) assert.Subset(t, mt.servers[sURL2].q.(*transmitQueue).pq.Pop().(*Transmission).Req.Payload, report) - require.Equal(t, mt.servers[sURL3].q.(*transmitQueue).pq.Len(), 1) + require.Equal(t, 1, mt.servers[sURL3].q.(*transmitQueue).pq.Len()) assert.Subset(t, mt.servers[sURL3].q.(*transmitQueue).pq.Pop().(*Transmission).Req.Payload, report) }) } diff --git a/core/services/relay/evm/mercury/v1/data_source.go b/core/services/relay/evm/mercury/v1/data_source.go index 0b9b6727fcf..c892a6dcb9b 100644 --- a/core/services/relay/evm/mercury/v1/data_source.go +++ b/core/services/relay/evm/mercury/v1/data_source.go @@ -306,7 +306,7 @@ func (ds *datasource) setLatestBlocks(ctx context.Context, obs *v1types.Observat // TODO: remove with https://smartcontract-it.atlassian.net/browse/BCF-2209 if len(latestBlocks) == 0 { - obsErr := fmt.Errorf("no blocks available") + obsErr := errors.New("no blocks available") ds.zeroBlocksCounter.Inc() obs.CurrentBlockNum.Err = obsErr obs.CurrentBlockHash.Err = obsErr diff --git a/core/services/relay/evm/mercury/v1/data_source_test.go b/core/services/relay/evm/mercury/v1/data_source_test.go index 7f5117a0aa8..c176b6c63b1 100644 --- a/core/services/relay/evm/mercury/v1/data_source_test.go +++ b/core/services/relay/evm/mercury/v1/data_source_test.go @@ -2,6 +2,7 @@ package v1 import ( "context" + "encoding/hex" "fmt" "io" "math/big" @@ -244,7 +245,7 @@ func TestMercury_Observe(t *testing.T) { assert.NoError(t, obs.Ask.Err) assert.Equal(t, head.Number, obs.CurrentBlockNum.Val) assert.NoError(t, obs.CurrentBlockNum.Err) - assert.Equal(t, fmt.Sprintf("%x", head.Hash), fmt.Sprintf("%x", obs.CurrentBlockHash.Val)) + assert.Equal(t, fmt.Sprintf("%x", head.Hash), hex.EncodeToString(obs.CurrentBlockHash.Val)) assert.NoError(t, obs.CurrentBlockHash.Err) assert.Equal(t, uint64(head.Timestamp.Unix()), obs.CurrentBlockTimestamp.Val) assert.NoError(t, obs.CurrentBlockTimestamp.Err) @@ -268,7 +269,7 @@ func TestMercury_Observe(t *testing.T) { assert.EqualError(t, obs.Ask.Err, "task error 2") assert.Equal(t, head.Number, obs.CurrentBlockNum.Val) assert.NoError(t, obs.CurrentBlockNum.Err) - assert.Equal(t, fmt.Sprintf("%x", head.Hash), fmt.Sprintf("%x", obs.CurrentBlockHash.Val)) + assert.Equal(t, fmt.Sprintf("%x", head.Hash), hex.EncodeToString(obs.CurrentBlockHash.Val)) assert.NoError(t, obs.CurrentBlockHash.Err) assert.Equal(t, uint64(head.Timestamp.Unix()), obs.CurrentBlockTimestamp.Val) assert.NoError(t, obs.CurrentBlockTimestamp.Err) @@ -277,11 +278,11 @@ func TestMercury_Observe(t *testing.T) { assert.EqualError(t, obs.MaxFinalizedBlockNumber.Err, "fetchMaxFinalizedBlockNum=false") }) t.Run("makes partial observation using pipeline, if only some results have errored", func(t *testing.T) { - trrs[0].Result.Error = fmt.Errorf("task failed") + trrs[0].Result.Error = errors.New("task failed") trrs[1].Result.Value = "33" trrs[1].Result.Error = nil trrs[2].Result.Value = nil - trrs[2].Result.Error = fmt.Errorf("task failed") + trrs[2].Result.Error = errors.New("task failed") obs, err := ds.Observe(ctx, repts, false) assert.NoError(t, err) @@ -294,7 +295,7 @@ func TestMercury_Observe(t *testing.T) { assert.EqualError(t, obs.Ask.Err, "task failed") }) t.Run("returns error if at least one result is unparseable", func(t *testing.T) { - trrs[0].Result.Error = fmt.Errorf("task failed") + trrs[0].Result.Error = errors.New("task failed") trrs[1].Result.Value = "foo" trrs[1].Result.Error = nil trrs[2].Result.Value = "123456" @@ -325,7 +326,7 @@ func TestMercury_Observe(t *testing.T) { obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) - assert.Len(t, obs.LatestBlocks, 0) + assert.Empty(t, obs.LatestBlocks) ht2.AssertExpectations(t) }) @@ -389,7 +390,7 @@ func TestMercury_Observe(t *testing.T) { obs, err := ds.Observe(ctx, repts, true) assert.Error(t, err) - assert.Equal(t, obs, v1.Observation{}) + assert.Equal(t, v1.Observation{}, obs) }) }) } @@ -442,7 +443,7 @@ func TestMercury_SetLatestBlocks(t *testing.T) { assert.EqualError(t, obs.CurrentBlockHash.Err, "no blocks available") assert.EqualError(t, obs.CurrentBlockTimestamp.Err, "no blocks available") - assert.Len(t, obs.LatestBlocks, 0) + assert.Empty(t, obs.LatestBlocks) headTracker.AssertExpectations(t) }) } diff --git a/core/services/relay/evm/mercury/v1/reportcodec/report_codec_test.go b/core/services/relay/evm/mercury/v1/reportcodec/report_codec_test.go index f5e2c7453e8..a545a682c7c 100644 --- a/core/services/relay/evm/mercury/v1/reportcodec/report_codec_test.go +++ b/core/services/relay/evm/mercury/v1/reportcodec/report_codec_test.go @@ -59,14 +59,14 @@ func Test_ReportCodec(t *testing.T) { err = ReportTypes.UnpackIntoMap(reportElems, report) require.NoError(t, err) - assert.Equal(t, int(reportElems["observationsTimestamp"].(uint32)), 242) - assert.Equal(t, reportElems["benchmarkPrice"].(*big.Int).Int64(), int64(243)) - assert.Equal(t, reportElems["bid"].(*big.Int).Int64(), int64(244)) - assert.Equal(t, reportElems["ask"].(*big.Int).Int64(), int64(245)) - assert.Equal(t, reportElems["currentBlockNum"].(uint64), uint64(248)) + assert.Equal(t, 242, int(reportElems["observationsTimestamp"].(uint32))) + assert.Equal(t, int64(243), reportElems["benchmarkPrice"].(*big.Int).Int64()) + assert.Equal(t, int64(244), reportElems["bid"].(*big.Int).Int64()) + assert.Equal(t, int64(245), reportElems["ask"].(*big.Int).Int64()) + assert.Equal(t, uint64(248), reportElems["currentBlockNum"].(uint64)) assert.Equal(t, common.Hash(reportElems["currentBlockHash"].([32]byte)), common.BytesToHash(hash)) - assert.Equal(t, reportElems["currentBlockTimestamp"].(uint64), uint64(123)) - assert.Equal(t, reportElems["validFromBlockNum"].(uint64), uint64(46)) + assert.Equal(t, uint64(123), reportElems["currentBlockTimestamp"].(uint64)) + assert.Equal(t, uint64(46), reportElems["validFromBlockNum"].(uint64)) assert.Equal(t, types.Report{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf8, 0x55, 0x2c, 0x2c, 0xea, 0x3a, 0xb4, 0x3b, 0xae, 0x13, 0x7d, 0x89, 0xee, 0x61, 0x42, 0xa0, 0x1d, 0xb3, 0xae, 0x2b, 0x56, 0x78, 0xbc, 0x3c, 0x9b, 0xd5, 0xf5, 0x9, 0xf5, 0x37, 0xbe, 0xa5, 0x7b, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2e, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7b}, report) diff --git a/core/services/relay/evm/mercury/v2/data_source_test.go b/core/services/relay/evm/mercury/v2/data_source_test.go index 25716521d86..e45b93cbb1a 100644 --- a/core/services/relay/evm/mercury/v2/data_source_test.go +++ b/core/services/relay/evm/mercury/v2/data_source_test.go @@ -296,9 +296,9 @@ func Test_Datasource(t *testing.T) { obs, err := ds.Observe(ctx, repts, false) assert.NoError(t, err) - assert.Nil(t, obs.LinkPrice.Err) + assert.NoError(t, obs.LinkPrice.Err) assert.Equal(t, obs.LinkPrice.Val, v2.MissingPrice) - assert.Nil(t, obs.NativePrice.Err) + assert.NoError(t, obs.NativePrice.Err) assert.Equal(t, obs.NativePrice.Val, v2.MissingPrice) assert.Equal(t, big.NewInt(122), obs.BenchmarkPrice.Val) }) @@ -308,9 +308,9 @@ func Test_Datasource(t *testing.T) { assert.NoError(t, err) assert.Equal(t, obs.LinkPrice.Val, v2.MissingPrice) - assert.Nil(t, obs.LinkPrice.Err) + assert.NoError(t, obs.LinkPrice.Err) assert.Equal(t, obs.NativePrice.Val, v2.MissingPrice) - assert.Nil(t, obs.NativePrice.Err) + assert.NoError(t, obs.NativePrice.Err) }) }) }) diff --git a/core/services/relay/evm/mercury/v2/reportcodec/report_codec_test.go b/core/services/relay/evm/mercury/v2/reportcodec/report_codec_test.go index 809869282b7..e4eb87e2f4e 100644 --- a/core/services/relay/evm/mercury/v2/reportcodec/report_codec_test.go +++ b/core/services/relay/evm/mercury/v2/reportcodec/report_codec_test.go @@ -48,12 +48,12 @@ func Test_ReportCodec_BuildReport(t *testing.T) { err = ReportTypes.UnpackIntoMap(reportElems, report) require.NoError(t, err) - assert.Equal(t, int(reportElems["observationsTimestamp"].(uint32)), 242) - assert.Equal(t, reportElems["benchmarkPrice"].(*big.Int).Int64(), int64(243)) - assert.Equal(t, reportElems["validFromTimestamp"].(uint32), uint32(123)) - assert.Equal(t, reportElems["expiresAt"].(uint32), uint32(20)) - assert.Equal(t, reportElems["linkFee"].(*big.Int).Int64(), int64(456)) - assert.Equal(t, reportElems["nativeFee"].(*big.Int).Int64(), int64(457)) + assert.Equal(t, 242, int(reportElems["observationsTimestamp"].(uint32))) + assert.Equal(t, int64(243), reportElems["benchmarkPrice"].(*big.Int).Int64()) + assert.Equal(t, uint32(123), reportElems["validFromTimestamp"].(uint32)) + assert.Equal(t, uint32(20), reportElems["expiresAt"].(uint32)) + assert.Equal(t, int64(456), reportElems["linkFee"].(*big.Int).Int64()) + assert.Equal(t, int64(457), reportElems["nativeFee"].(*big.Int).Int64()) assert.Equal(t, types.Report{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7b, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xc9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xc8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf3}, report) max, err := r.MaxReportLength(ctx, 4) @@ -128,7 +128,7 @@ func Test_ReportCodec_ObservationTimestampFromReport(t *testing.T) { ts, err := r.ObservationTimestampFromReport(ctx, report) require.NoError(t, err) - assert.Equal(t, ts, uint32(123)) + assert.Equal(t, uint32(123), ts) }) t.Run("ObservationTimestampFromReport returns error when report is invalid", func(t *testing.T) { report := []byte{1, 2, 3} diff --git a/core/services/relay/evm/mercury/v3/data_source_test.go b/core/services/relay/evm/mercury/v3/data_source_test.go index 518fabb12c9..b097c63b5d1 100644 --- a/core/services/relay/evm/mercury/v3/data_source_test.go +++ b/core/services/relay/evm/mercury/v3/data_source_test.go @@ -376,9 +376,9 @@ func Test_Datasource(t *testing.T) { obs, err := ds.Observe(ctx, repts, false) assert.NoError(t, err) - assert.Nil(t, obs.LinkPrice.Err) + assert.NoError(t, obs.LinkPrice.Err) assert.Equal(t, obs.LinkPrice.Val, relaymercuryv3.MissingPrice) - assert.Nil(t, obs.NativePrice.Err) + assert.NoError(t, obs.NativePrice.Err) assert.Equal(t, obs.NativePrice.Val, relaymercuryv3.MissingPrice) assert.Equal(t, big.NewInt(122), obs.BenchmarkPrice.Val) }) @@ -388,9 +388,9 @@ func Test_Datasource(t *testing.T) { assert.NoError(t, err) assert.Equal(t, obs.LinkPrice.Val, relaymercuryv3.MissingPrice) - assert.Nil(t, obs.LinkPrice.Err) + assert.NoError(t, obs.LinkPrice.Err) assert.Equal(t, obs.NativePrice.Val, relaymercuryv3.MissingPrice) - assert.Nil(t, obs.NativePrice.Err) + assert.NoError(t, obs.NativePrice.Err) }) }) }) diff --git a/core/services/relay/evm/mercury/v3/reportcodec/report_codec_test.go b/core/services/relay/evm/mercury/v3/reportcodec/report_codec_test.go index 2cfb162841b..da6e51a838a 100644 --- a/core/services/relay/evm/mercury/v3/reportcodec/report_codec_test.go +++ b/core/services/relay/evm/mercury/v3/reportcodec/report_codec_test.go @@ -50,14 +50,14 @@ func Test_ReportCodec_BuildReport(t *testing.T) { err = ReportTypes.UnpackIntoMap(reportElems, report) require.NoError(t, err) - assert.Equal(t, int(reportElems["observationsTimestamp"].(uint32)), 242) - assert.Equal(t, reportElems["benchmarkPrice"].(*big.Int).Int64(), int64(243)) - assert.Equal(t, reportElems["bid"].(*big.Int).Int64(), int64(244)) - assert.Equal(t, reportElems["ask"].(*big.Int).Int64(), int64(245)) - assert.Equal(t, reportElems["validFromTimestamp"].(uint32), uint32(123)) - assert.Equal(t, reportElems["expiresAt"].(uint32), uint32(20)) - assert.Equal(t, reportElems["linkFee"].(*big.Int).Int64(), int64(456)) - assert.Equal(t, reportElems["nativeFee"].(*big.Int).Int64(), int64(457)) + assert.Equal(t, 242, int(reportElems["observationsTimestamp"].(uint32))) + assert.Equal(t, int64(243), reportElems["benchmarkPrice"].(*big.Int).Int64()) + assert.Equal(t, int64(244), reportElems["bid"].(*big.Int).Int64()) + assert.Equal(t, int64(245), reportElems["ask"].(*big.Int).Int64()) + assert.Equal(t, uint32(123), reportElems["validFromTimestamp"].(uint32)) + assert.Equal(t, uint32(20), reportElems["expiresAt"].(uint32)) + assert.Equal(t, int64(456), reportElems["linkFee"].(*big.Int).Int64()) + assert.Equal(t, int64(457), reportElems["nativeFee"].(*big.Int).Int64()) assert.Equal(t, types.Report{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7b, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xc9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xc8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf5}, report) max, err := r.MaxReportLength(ctx, 4) @@ -134,7 +134,7 @@ func Test_ReportCodec_ObservationTimestampFromReport(t *testing.T) { ts, err := r.ObservationTimestampFromReport(ctx, report) require.NoError(t, err) - assert.Equal(t, ts, uint32(123)) + assert.Equal(t, uint32(123), ts) }) t.Run("ObservationTimestampFromReport returns error when report is invalid", func(t *testing.T) { report := []byte{1, 2, 3} diff --git a/core/services/relay/evm/mercury/v4/data_source_test.go b/core/services/relay/evm/mercury/v4/data_source_test.go index 48aec5989a6..896c0a26950 100644 --- a/core/services/relay/evm/mercury/v4/data_source_test.go +++ b/core/services/relay/evm/mercury/v4/data_source_test.go @@ -308,9 +308,9 @@ func Test_Datasource(t *testing.T) { obs, err := ds.Observe(ctx, repts, false) assert.NoError(t, err) - assert.Nil(t, obs.LinkPrice.Err) + assert.NoError(t, obs.LinkPrice.Err) assert.Equal(t, obs.LinkPrice.Val, relaymercuryv4.MissingPrice) - assert.Nil(t, obs.NativePrice.Err) + assert.NoError(t, obs.NativePrice.Err) assert.Equal(t, obs.NativePrice.Val, relaymercuryv4.MissingPrice) assert.Equal(t, big.NewInt(122), obs.BenchmarkPrice.Val) }) @@ -320,9 +320,9 @@ func Test_Datasource(t *testing.T) { assert.NoError(t, err) assert.Equal(t, obs.LinkPrice.Val, relaymercuryv4.MissingPrice) - assert.Nil(t, obs.LinkPrice.Err) + assert.NoError(t, obs.LinkPrice.Err) assert.Equal(t, obs.NativePrice.Val, relaymercuryv4.MissingPrice) - assert.Nil(t, obs.NativePrice.Err) + assert.NoError(t, obs.NativePrice.Err) }) }) }) diff --git a/core/services/relay/evm/mercury/v4/reportcodec/report_codec_test.go b/core/services/relay/evm/mercury/v4/reportcodec/report_codec_test.go index 9813d422cc1..e3caead1fa8 100644 --- a/core/services/relay/evm/mercury/v4/reportcodec/report_codec_test.go +++ b/core/services/relay/evm/mercury/v4/reportcodec/report_codec_test.go @@ -48,13 +48,13 @@ func Test_ReportCodec_BuildReport(t *testing.T) { err = ReportTypes.UnpackIntoMap(reportElems, report) require.NoError(t, err) - assert.Equal(t, int(reportElems["observationsTimestamp"].(uint32)), 242) - assert.Equal(t, reportElems["benchmarkPrice"].(*big.Int).Int64(), int64(243)) - assert.Equal(t, reportElems["validFromTimestamp"].(uint32), uint32(123)) - assert.Equal(t, reportElems["expiresAt"].(uint32), uint32(20)) - assert.Equal(t, reportElems["linkFee"].(*big.Int).Int64(), int64(456)) - assert.Equal(t, reportElems["nativeFee"].(*big.Int).Int64(), int64(457)) - assert.Equal(t, reportElems["marketStatus"].(uint32), uint32(1)) + assert.Equal(t, 242, int(reportElems["observationsTimestamp"].(uint32))) + assert.Equal(t, int64(243), reportElems["benchmarkPrice"].(*big.Int).Int64()) + assert.Equal(t, uint32(123), reportElems["validFromTimestamp"].(uint32)) + assert.Equal(t, uint32(20), reportElems["expiresAt"].(uint32)) + assert.Equal(t, int64(456), reportElems["linkFee"].(*big.Int).Int64()) + assert.Equal(t, int64(457), reportElems["nativeFee"].(*big.Int).Int64()) + assert.Equal(t, uint32(1), reportElems["marketStatus"].(uint32)) assert.Equal(t, types.Report{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7b, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xc9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xc8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1}, report) max, err := r.MaxReportLength(ctx, 4) @@ -131,7 +131,7 @@ func Test_ReportCodec_ObservationTimestampFromReport(t *testing.T) { ts, err := r.ObservationTimestampFromReport(ctx, report) require.NoError(t, err) - assert.Equal(t, ts, uint32(123)) + assert.Equal(t, uint32(123), ts) }) t.Run("ObservationTimestampFromReport returns error when report is invalid", func(t *testing.T) { ctx := tests.Context(t) diff --git a/core/services/relay/evm/mercury/wsrpc/cache/cache_set_test.go b/core/services/relay/evm/mercury/wsrpc/cache/cache_set_test.go index f12dc8a9bc7..65624f4522d 100644 --- a/core/services/relay/evm/mercury/wsrpc/cache/cache_set_test.go +++ b/core/services/relay/evm/mercury/wsrpc/cache/cache_set_test.go @@ -24,22 +24,22 @@ func Test_CacheSet(t *testing.T) { var err error var f Fetcher t.Run("with caching disabled, returns nil, nil", func(t *testing.T) { - assert.Len(t, disabledCs.caches, 0) + assert.Empty(t, disabledCs.caches) f, err = disabledCs.Get(ctx, c) require.NoError(t, err) assert.Nil(t, f) - assert.Len(t, disabledCs.caches, 0) + assert.Empty(t, disabledCs.caches) }) t.Run("with virgin cacheset, makes new entry and returns it", func(t *testing.T) { - assert.Len(t, cs.caches, 0) + assert.Empty(t, cs.caches) f, err = cs.Get(ctx, c) require.NoError(t, err) - assert.IsType(t, f, &memCache{}) + assert.IsType(t, &memCache{}, f) assert.Len(t, cs.caches, 1) }) t.Run("with existing cache for value, returns that", func(t *testing.T) { @@ -49,7 +49,7 @@ func Test_CacheSet(t *testing.T) { f2, err = cs.Get(ctx, c) require.NoError(t, err) - assert.IsType(t, f, &memCache{}) + assert.IsType(t, &memCache{}, f) assert.Equal(t, f, f2) assert.Len(t, cs.caches, 1) }) diff --git a/core/services/relay/evm/mercury/wsrpc/cache/cache_test.go b/core/services/relay/evm/mercury/wsrpc/cache/cache_test.go index 6378577d8d5..45643fb75f6 100644 --- a/core/services/relay/evm/mercury/wsrpc/cache/cache_test.go +++ b/core/services/relay/evm/mercury/wsrpc/cache/cache_test.go @@ -186,7 +186,7 @@ func Test_Cache(t *testing.T) { t.Run("returns context deadline exceeded error if fetch takes too long", func(t *testing.T) { _, err := c.LatestReport(canceledCtx, req1) require.Error(t, err) - assert.True(t, errors.Is(err, context.Canceled)) + assert.ErrorIs(t, err, context.Canceled) assert.EqualError(t, err, "context canceled") }) t.Run("returns wrapped context deadline exceeded error if fetch has errored and is in the retry loop", func(t *testing.T) { @@ -194,7 +194,7 @@ func Test_Cache(t *testing.T) { _, err := c.LatestReport(canceledCtx, req1) require.Error(t, err) - assert.True(t, errors.Is(err, context.Canceled)) + assert.ErrorIs(t, err, context.Canceled) assert.EqualError(t, err, "some background fetch error\ncontext canceled") }) }) diff --git a/core/services/relay/evm/mercury/wsrpc/pool_test.go b/core/services/relay/evm/mercury/wsrpc/pool_test.go index bb5ceec0bb6..b7ea480f724 100644 --- a/core/services/relay/evm/mercury/wsrpc/pool_test.go +++ b/core/services/relay/evm/mercury/wsrpc/pool_test.go @@ -92,7 +92,7 @@ func Test_Pool(t *testing.T) { err := c.Close() require.NoError(t, err) - assert.Len(t, conn.checkouts, 0) + assert.Empty(t, conn.checkouts) require.IsType(t, nil, conn.Client) assert.Nil(t, conn.Client) assert.True(t, client.closed) @@ -120,13 +120,13 @@ func Test_Pool(t *testing.T) { c3 := mustCheckout(t, p, clientPrivKeys[0], serverPubKey, serverURLs[0]) assert.Len(t, p.connections, 1) assert.Len(t, p.connections[serverURLs[0]], 1) - assert.Len(t, p.connections[serverURLs[1]], 0) + assert.Empty(t, p.connections[serverURLs[1]]) // conn 2 c4 := mustCheckout(t, p, clientPrivKeys[1], serverPubKey, serverURLs[0]) assert.Len(t, p.connections, 1) assert.Len(t, p.connections[serverURLs[0]], 2) - assert.Len(t, p.connections[serverURLs[1]], 0) + assert.Empty(t, p.connections[serverURLs[1]]) // conn 3 c5 := mustCheckout(t, p, clientPrivKeys[0], serverPubKey, serverURLs[1]) @@ -168,7 +168,7 @@ func Test_Pool(t *testing.T) { assert.Len(t, p.connections[serverURLs[1]], 1) require.NoError(t, c3.Close()) - assert.Len(t, conn1.checkouts, 0) + assert.Empty(t, conn1.checkouts) assert.Nil(t, conn1.Client) assert.Len(t, p.connections, 2) assert.Len(t, p.connections[serverURLs[0]], 1) @@ -177,7 +177,7 @@ func Test_Pool(t *testing.T) { c7 := mustCheckout(t, p, clientPrivKeys[0], serverPubKey, serverURLs[0]) // Not the same one, since previously all checkouts were checked in, the original connection was deleted from the map and a new one created assert.NotSame(t, conn1, c7.(*clientCheckout).connection) - assert.Len(t, conn1.checkouts, 0) // actually, conn1 has already been removed from the map and will be garbage collected + assert.Empty(t, conn1.checkouts) // actually, conn1 has already been removed from the map and will be garbage collected conn4 := c7.(*clientCheckout).connection assert.Len(t, conn4.checkouts, 1) assert.NotNil(t, conn4.Client) @@ -192,12 +192,12 @@ func Test_Pool(t *testing.T) { require.NoError(t, c4.Close()) assert.Len(t, p.connections, 1) - assert.Len(t, p.connections[serverURLs[0]], 0) + assert.Empty(t, p.connections[serverURLs[0]]) assert.Len(t, p.connections[serverURLs[1]], 1) require.NoError(t, c5.Close()) require.NoError(t, c6.Close()) - assert.Len(t, p.connections, 0) + assert.Empty(t, p.connections) require.NoError(t, p.Close()) }) @@ -211,8 +211,8 @@ func Test_Pool(t *testing.T) { }) t.Run("Start", func(t *testing.T) { require.NoError(t, p.Start(ctx)) - assert.Nil(t, p.Ready()) - assert.Nil(t, p.HealthReport()["PoolTestLogger"]) + assert.NoError(t, p.Ready()) + assert.NoError(t, p.HealthReport()["PoolTestLogger"]) }) t.Run("Close force closes all connections", func(t *testing.T) { clientPrivKeys := []csakey.KeyV2{ diff --git a/core/services/relay/evm/ocr2keeper.go b/core/services/relay/evm/ocr2keeper.go index db96afee7d7..290416d56ca 100644 --- a/core/services/relay/evm/ocr2keeper.go +++ b/core/services/relay/evm/ocr2keeper.go @@ -33,7 +33,7 @@ import ( var ( _ OCR2KeeperRelayer = (*ocr2keeperRelayer)(nil) _ OCR2KeeperProvider = (*ocr2keeperProvider)(nil) - ErrInitializationFailure = fmt.Errorf("failed to initialize registry") + ErrInitializationFailure = errors.New("failed to initialize registry") ) // OCR2KeeperProviderOpts is the custom options to create a keeper provider diff --git a/core/services/relay/evm/read/batch.go b/core/services/relay/evm/read/batch.go index ce1c546ad73..47cede43d43 100644 --- a/core/services/relay/evm/read/batch.go +++ b/core/services/relay/evm/read/batch.go @@ -55,7 +55,7 @@ type Call struct { func (c BatchCall) String() string { callString := "" for _, call := range c { - callString += fmt.Sprintf("%s\n", call.String()) + callString += call.String() + "\n" } return callString } diff --git a/core/services/relay/evm/read/event.go b/core/services/relay/evm/read/event.go index d2b54e5bd64..52beb584f5f 100644 --- a/core/services/relay/evm/read/event.go +++ b/core/services/relay/evm/read/event.go @@ -392,7 +392,7 @@ func (b *EventBinding) decodeLogsIntoSequences(ctx context.Context, logs []logpo sequences[idx] = commontypes.Sequence{ Cursor: logpoller.FormatContractReaderCursor(logs[idx]), Head: commontypes.Head{ - Height: fmt.Sprint(logs[idx].BlockNumber), + Height: strconv.FormatInt(logs[idx].BlockNumber, 10), Hash: logs[idx].BlockHash.Bytes(), Timestamp: uint64(logs[idx].BlockTimestamp.Unix()), }, diff --git a/core/services/relay/evm/relayer_extender.go b/core/services/relay/evm/relayer_extender.go index 0d01494169f..d1909b2a6fc 100644 --- a/core/services/relay/evm/relayer_extender.go +++ b/core/services/relay/evm/relayer_extender.go @@ -67,7 +67,7 @@ func NewLegacyChains(ctx context.Context, opts legacyevm.ChainRelayOpts) (result KeyStore: opts.KeyStore, } - privOpts.Logger.Infow(fmt.Sprintf("Loading chain %s", cid), "evmChainID", cid) + privOpts.Logger.Infow("Loading chain "+cid, "evmChainID", cid) chain, err2 := legacyevm.NewTOMLChain(ctx, enabled[i], privOpts, clientsByChainID) if err2 != nil { err = multierr.Combine(err, fmt.Errorf("failed to create chain %s: %w", cid, err2)) diff --git a/core/services/relay/evm/relayer_extender_test.go b/core/services/relay/evm/relayer_extender_test.go index 3be2bbcb5e7..ab69dde90a1 100644 --- a/core/services/relay/evm/relayer_extender_test.go +++ b/core/services/relay/evm/relayer_extender_test.go @@ -42,7 +42,7 @@ func TestChainRelayExtenders(t *testing.T) { relayExtenders, err := evmrelay.NewLegacyChains(testutils.Context(t), opts) require.NoError(t, err) - require.Equal(t, len(relayExtenders), 2) + require.Len(t, relayExtenders, 2) relayExtendersInstances := relayExtenders for _, c := range relayExtendersInstances { require.NoError(t, c.Start(testutils.Context(t))) diff --git a/core/services/relay/evm/statuschecker/txm_status_checker.go b/core/services/relay/evm/statuschecker/txm_status_checker.go index f22e6d78b9f..386ccf5b023 100644 --- a/core/services/relay/evm/statuschecker/txm_status_checker.go +++ b/core/services/relay/evm/statuschecker/txm_status_checker.go @@ -2,6 +2,7 @@ package statuschecker import ( "context" + "errors" "fmt" "github.com/smartcontractkit/chainlink-common/pkg/types" @@ -46,7 +47,7 @@ func (tsc *TxmStatusChecker) CheckMessageStatus(ctx context.Context, msgID strin // Break the loop if the cap is reached if counter >= maxStatuses { - return allStatuses, counter - 1, fmt.Errorf("maximum number of statuses reached, possible infinite loop") + return allStatuses, counter - 1, errors.New("maximum number of statuses reached, possible infinite loop") } } diff --git a/core/services/relay/evm/types/codec_entry_test.go b/core/services/relay/evm/types/codec_entry_test.go index c71d5c0ad33..09d1e6a07f3 100644 --- a/core/services/relay/evm/types/codec_entry_test.go +++ b/core/services/relay/evm/types/codec_entry_test.go @@ -1,7 +1,6 @@ package types import ( - "errors" "math/big" "reflect" "testing" @@ -213,7 +212,7 @@ func TestCodecEntry(t *testing.T) { ct := entry.CheckedType() require.Equal(t, 2, ct.NumField()) args := entry.Args() - require.Equal(t, 2, len(args)) + require.Len(t, args, 2) f0 := ct.Field(0) assert.Equal(t, "F0", f0.Name) assert.Equal(t, "F0", args[0].Name) @@ -235,7 +234,7 @@ func TestCodecEntry(t *testing.T) { ct := entry.CheckedType() require.Equal(t, 2, ct.NumField()) args := entry.Args() - require.Equal(t, 2, len(args)) + require.Len(t, args, 2) f0 := ct.Field(0) assert.Equal(t, "F1", f0.Name) assert.Equal(t, reflect.TypeOf((*int64)(nil)), f0.Type) @@ -249,7 +248,7 @@ func TestCodecEntry(t *testing.T) { anyType, err := abi.NewType("int16[3]", "", []abi.ArgumentMarshaling{}) require.NoError(t, err) entry := NewCodecEntry(abi.Arguments{{Name: "Name", Type: anyType}, {Name: "Name", Type: anyType}}, nil, nil) - assert.True(t, errors.Is(entry.Init(), commontypes.ErrInvalidConfig)) + assert.ErrorIs(t, entry.Init(), commontypes.ErrInvalidConfig) }) t.Run("Indexed basic types leave their native and checked types as-is", func(t *testing.T) { @@ -298,7 +297,7 @@ func TestCodecEntry(t *testing.T) { {Name: "Name3", Type: anyType, Indexed: true}, {Name: "Name4", Type: anyType, Indexed: true}, }, nil, nil) - require.True(t, errors.Is(entry.Init(), commontypes.ErrInvalidConfig)) + require.ErrorIs(t, entry.Init(), commontypes.ErrInvalidConfig) }) // TODO: when the TODO on @@ -308,7 +307,7 @@ func TestCodecEntry(t *testing.T) { anyType, err := abi.NewType("int256[2]", "", []abi.ArgumentMarshaling{}) require.NoError(t, err) entry := NewCodecEntry(abi.Arguments{{Name: "Name", Type: anyType, Indexed: true}}, nil, nil) - assert.True(t, errors.Is(entry.Init(), commontypes.ErrInvalidConfig)) + assert.ErrorIs(t, entry.Init(), commontypes.ErrInvalidConfig) }) t.Run("Modifier returns provided modifier", func(t *testing.T) { diff --git a/core/services/relay/evm/types/int_types_test.go b/core/services/relay/evm/types/int_types_test.go index 6930287c869..e843dedb722 100644 --- a/core/services/relay/evm/types/int_types_test.go +++ b/core/services/relay/evm/types/int_types_test.go @@ -1,7 +1,6 @@ package types import ( - "errors" "fmt" "math/big" "reflect" @@ -48,7 +47,7 @@ func assertBigIntBounds(t *testing.T, tpe *ABIEncodingType, min, max *big.Int) { sbi = reflect.ValueOf(max).Convert(tpe.checked).Interface().(SizedBigInt) assert.NoError(t, sbi.Verify()) sbi = reflect.ValueOf(minMinusOne).Convert(tpe.checked).Interface().(SizedBigInt) - assert.True(t, errors.Is(types.ErrInvalidType, sbi.Verify())) + assert.ErrorIs(t, types.ErrInvalidType, sbi.Verify()) sbi = reflect.ValueOf(maxPlusOne).Convert(tpe.checked).Interface().(SizedBigInt) - assert.True(t, errors.Is(types.ErrInvalidType, sbi.Verify())) + assert.ErrorIs(t, types.ErrInvalidType, sbi.Verify()) } diff --git a/core/services/relay/evm/types/types.go b/core/services/relay/evm/types/types.go index 2b56aee6379..17bf496e8a1 100644 --- a/core/services/relay/evm/types/types.go +++ b/core/services/relay/evm/types/types.go @@ -313,7 +313,7 @@ func ChainReaderConfigFromBytes(bts []byte) (ChainReaderConfig, error) { var cfg ChainReaderConfig if err := decoder.Decode(&cfg); err != nil { - return cfg, fmt.Errorf("failed to unmarshal chain reader config err: %s", err) + return cfg, fmt.Errorf("failed to unmarshal chain reader config err: %w", err) } return cfg, nil diff --git a/core/services/relay/evm/types/types_test.go b/core/services/relay/evm/types/types_test.go index f77b4226e87..0ea56fe5d73 100644 --- a/core/services/relay/evm/types/types_test.go +++ b/core/services/relay/evm/types/types_test.go @@ -148,7 +148,7 @@ func Test_ChainReaderConfig(t *testing.T) { t.Run(tt.name, func(t *testing.T) { var config ChainReaderConfig config.Contracts = make(map[string]ChainContractReader) - require.Nil(t, json.Unmarshal([]byte(tt.jsonInput), &config)) + require.NoError(t, json.Unmarshal([]byte(tt.jsonInput), &config)) require.Equal(t, tt.expected, config) }) } diff --git a/core/services/relay/evm/write_target.go b/core/services/relay/evm/write_target.go index f14c13e5daa..b52ec4fb2bc 100644 --- a/core/services/relay/evm/write_target.go +++ b/core/services/relay/evm/write_target.go @@ -40,7 +40,7 @@ func NewWriteTarget(ctx context.Context, relayer *Relayer, chain legacyevm.Chain }, }) if err != nil { - return nil, fmt.Errorf("failed to marshal contract reader config %v", err) + return nil, fmt.Errorf("failed to marshal contract reader config %w", err) } cr, err := relayer.NewContractReader(ctx, contractReaderConfigEncoded) if err != nil { diff --git a/core/services/relay/evm/write_target_test.go b/core/services/relay/evm/write_target_test.go index c82c9ba81b9..58cf6ca72c6 100644 --- a/core/services/relay/evm/write_target_test.go +++ b/core/services/relay/evm/write_target_test.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/hex" "errors" - "fmt" "math/big" "testing" @@ -54,7 +53,7 @@ func newMockedEncodeTransmissionInfo() ([]byte, error) { var buffer bytes.Buffer gasLimitBytes := info.GasLimit.Bytes() if len(gasLimitBytes) > 80 { - return nil, fmt.Errorf("GasLimit too large") + return nil, errors.New("GasLimit too large") } paddedGasLimit := make([]byte, 80-len(gasLimitBytes)) buffer.Write(paddedGasLimit) diff --git a/core/services/s4/cached_orm_wrapper_test.go b/core/services/s4/cached_orm_wrapper_test.go index 5b94ce3b253..eadbc2196f2 100644 --- a/core/services/s4/cached_orm_wrapper_test.go +++ b/core/services/s4/cached_orm_wrapper_test.go @@ -2,7 +2,7 @@ package s4_test import ( "bytes" - "fmt" + "errors" "testing" "time" @@ -190,7 +190,7 @@ func TestGet(t *testing.T) { t.Run("NOK-Get_underlaying_ORM_returns_an_error", func(t *testing.T) { ctx := testutils.Context(t) underlayingORM := mocks.NewORM(t) - underlayingORM.On("Get", mock.Anything, address, slotID).Return(nil, fmt.Errorf("some_error")).Once() + underlayingORM.On("Get", mock.Anything, address, slotID).Return(nil, errors.New("some_error")).Once() orm := s4.NewCachedORMWrapper(underlayingORM, lggr) row, err := orm.Get(ctx, address, slotID) @@ -220,7 +220,7 @@ func TestDeletedExpired(t *testing.T) { ctx := testutils.Context(t) var expectedDeleted int64 underlayingORM := mocks.NewORM(t) - underlayingORM.On("DeleteExpired", mock.Anything, limit, now).Return(expectedDeleted, fmt.Errorf("some_error")).Once() + underlayingORM.On("DeleteExpired", mock.Anything, limit, now).Return(expectedDeleted, errors.New("some_error")).Once() orm := s4.NewCachedORMWrapper(underlayingORM, lggr) actualDeleted, err := orm.DeleteExpired(ctx, limit, now) @@ -254,7 +254,7 @@ func TestGetUnconfirmedRows(t *testing.T) { t.Run("NOK-GetUnconfirmedRows_underlaying_ORM_returns_an_error", func(t *testing.T) { ctx := testutils.Context(t) underlayingORM := mocks.NewORM(t) - underlayingORM.On("GetUnconfirmedRows", mock.Anything, limit).Return(nil, fmt.Errorf("some_error")).Once() + underlayingORM.On("GetUnconfirmedRows", mock.Anything, limit).Return(nil, errors.New("some_error")).Once() orm := s4.NewCachedORMWrapper(underlayingORM, lggr) actualRow, err := orm.GetUnconfirmedRows(ctx, limit) diff --git a/core/services/s4/storage_test.go b/core/services/s4/storage_test.go index 8deb23bb979..1141364082c 100644 --- a/core/services/s4/storage_test.go +++ b/core/services/s4/storage_test.go @@ -195,7 +195,7 @@ func TestStorage_PutAndGet(t *testing.T) { rec, metadata, err := storage.Get(testutils.Context(t), key) assert.NoError(t, err) - assert.Equal(t, false, metadata.Confirmed) + assert.False(t, metadata.Confirmed) assert.Equal(t, signature, metadata.Signature) assert.Equal(t, record.Expiration, rec.Expiration) assert.Equal(t, record.Payload, rec.Payload) diff --git a/core/services/signatures/ethdss/ethdss_test.go b/core/services/signatures/ethdss/ethdss_test.go index 4cc203ef400..b808d3d578e 100644 --- a/core/services/signatures/ethdss/ethdss_test.go +++ b/core/services/signatures/ethdss/ethdss_test.go @@ -55,7 +55,7 @@ func TestDSSNew(t *testing.T) { long: longterms[0], random: randoms[0], msg: msg, T: 4} dss, err := NewDSS(dssArgs) assert.NotNil(t, dss) - assert.Nil(t, err) + assert.NoError(t, err) dssArgs.secret = suite.Scalar().Zero() dss, err = NewDSS(dssArgs) assert.Nil(t, dss) @@ -66,12 +66,12 @@ func TestDSSPartialSigs(t *testing.T) { dss0 := getDSS(0) dss1 := getDSS(1) ps0, err := dss0.PartialSig() - assert.Nil(t, err) + assert.NoError(t, err) assert.NotNil(t, ps0) assert.Len(t, dss0.partials, 1) // second time should not affect list ps0, err = dss0.PartialSig() - assert.Nil(t, err) + assert.NoError(t, err) assert.NotNil(t, ps0) assert.Len(t, dss0.partials, 1) @@ -104,7 +104,7 @@ func TestDSSPartialSigs(t *testing.T) { goodV := ps0.Partial.V ps0.Partial.V = suite.Scalar().Zero() ps0.Signature, err = ethschnorr.Sign(dss0.secret, ps0.Hash()) - require.Nil(t, err) + require.NoError(t, err) err = dss1.ProcessPartialSig(ps0) assert.Error(t, err) assert.Contains(t, err.Error(), "not valid") @@ -113,7 +113,7 @@ func TestDSSPartialSigs(t *testing.T) { // fine err = dss1.ProcessPartialSig(ps0) - assert.Nil(t, err) + assert.NoError(t, err) // already received assert.Error(t, dss1.ProcessPartialSig(ps0)) @@ -128,8 +128,8 @@ func TestDSSPartialSigs(t *testing.T) { for i := 2; i < nbParticipants; i++ { dss := getDSS(i) ps, e := dss.PartialSig() - require.Nil(t, e) - require.Nil(t, dss1.ProcessPartialSig(ps)) + require.NoError(t, e) + require.NoError(t, dss1.ProcessPartialSig(ps)) } assert.True(t, dss1.EnoughPartialSig()) sig, err = dss1.Signature() @@ -153,7 +153,7 @@ func TestDSSSignature(t *testing.T) { for i := 0; i < nbParticipants; i++ { dsss[i] = getDSS(i) ps, err := dsss[i].PartialSig() - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, ps) pss[i] = ps } @@ -162,14 +162,14 @@ func TestDSSSignature(t *testing.T) { if i == j { continue } - require.Nil(t, dss.ProcessPartialSig(ps)) + require.NoError(t, dss.ProcessPartialSig(ps)) } } // issue and verify signature dss0 := dsss[0] sig, err := dss0.Signature() assert.NotNil(t, sig) - assert.Nil(t, err) + assert.NoError(t, err) assert.NoError(t, ethschnorr.Verify(longterms[0].Public(), dss0.msg, sig)) // Original contains this second check. Unclear why. assert.NoError(t, ethschnorr.Verify(longterms[0].Public(), dss0.msg, sig)) diff --git a/core/services/signatures/ethschnorr/ethschnorr.go b/core/services/signatures/ethschnorr/ethschnorr.go index e8c3e9b562e..63af14ff71b 100644 --- a/core/services/signatures/ethschnorr/ethschnorr.go +++ b/core/services/signatures/ethschnorr/ethschnorr.go @@ -18,6 +18,7 @@ package ethschnorr import ( "bytes" + "errors" "fmt" "math/big" @@ -67,19 +68,19 @@ func ChallengeHash(public kyber.Point, rAddress [20]byte, msg *big.Int) ( var err error h := secp256k1Suite.Hash() if _, herr := public.MarshalTo(h); herr != nil { - err = fmt.Errorf("failed to hash public key for signature: %s", herr) + err = fmt.Errorf("failed to hash public key for signature: %w", herr) } if err != nil && (msg.BitLen() > 256 || msg.Cmp(zero) == -1) { - err = fmt.Errorf("msg must be a uint256") + err = errors.New("msg must be a uint256") } if err == nil { if _, herr := h.Write(msg.Bytes()); herr != nil { - err = fmt.Errorf("failed to hash message for signature: %s", herr) + err = fmt.Errorf("failed to hash message for signature: %w", herr) } } if err == nil { if _, herr := h.Write(rAddress[:]); herr != nil { - err = fmt.Errorf("failed to hash r for signature: %s", herr) + err = fmt.Errorf("failed to hash r for signature: %w", herr) } } if err != nil { @@ -92,7 +93,7 @@ func ChallengeHash(public kyber.Point, rAddress [20]byte, msg *big.Int) ( // function Verify, or on-chain with SchnorrSECP256K1.sol. func Sign(private kyber.Scalar, msg *big.Int) (Signature, error) { if !secp256k1.IsSecp256k1Scalar(private) { - return nil, fmt.Errorf("private key is not a secp256k1 scalar") + return nil, errors.New("private key is not a secp256k1 scalar") } // create random secret and public commitment to it commitmentSecretKey := secp256k1Group.Scalar().Pick( @@ -117,16 +118,16 @@ func Sign(private kyber.Scalar, msg *big.Int) (Signature, error) { func Verify(public kyber.Point, msg *big.Int, s Signature) error { var err error if !ValidSignature(s) { - err = fmt.Errorf("s is not a valid signature") + err = errors.New("s is not a valid signature") } if err == nil && !secp256k1.IsSecp256k1Point(public) { - err = fmt.Errorf("public key is not a secp256k1 point") + err = errors.New("public key is not a secp256k1 point") } if err == nil && !secp256k1.ValidPublicKey(public) { - err = fmt.Errorf("`public` is not a valid public key") + err = errors.New("`public` is not a valid public key") } if err == nil && (msg.Cmp(zero) == -1 || msg.Cmp(maxUint256) == 1) { - err = fmt.Errorf("msg is not a uint256") + err = errors.New("msg is not a uint256") } var challenge kyber.Scalar var herr error @@ -148,7 +149,7 @@ func Verify(public kyber.Point, msg *big.Int, s Signature) error { maybeCommitmentPublicAddress := secp256k1.EthereumAddress(maybeCommitmentPublicKey) if !bytes.Equal(s.CommitmentPublicAddress[:], maybeCommitmentPublicAddress[:]) { - return fmt.Errorf("signature mismatch") + return errors.New("signature mismatch") } return nil } diff --git a/core/services/signatures/ethschnorr/ethschnorr_test.go b/core/services/signatures/ethschnorr/ethschnorr_test.go index 834d596bab7..ba770e764bf 100644 --- a/core/services/signatures/ethschnorr/ethschnorr_test.go +++ b/core/services/signatures/ethschnorr/ethschnorr_test.go @@ -27,7 +27,7 @@ var printTests = false func printTest(t *testing.T, msg *big.Int, private kyber.Scalar, public kyber.Point, signature Signature) { privateBytes, err := private.MarshalBinary() - require.Nil(t, err) + require.NoError(t, err) pX, pY := secp256k1.Coordinates(public) t.Logf(" ['%064x',\n '%064x',\n '%064x',\n '%064x',\n "+ "'%064x',\n '%040x'],\n", diff --git a/core/services/signatures/secp256k1/curve_test.go b/core/services/signatures/secp256k1/curve_test.go index e4802ea3d0e..325bae20d41 100644 --- a/core/services/signatures/secp256k1/curve_test.go +++ b/core/services/signatures/secp256k1/curve_test.go @@ -9,12 +9,12 @@ import ( var group = &Secp256k1{} func TestSecp256k1_String(t *testing.T) { - require.Equal(t, group.String(), "Secp256k1") + require.Equal(t, "Secp256k1", group.String()) } func TestSecp256k1_Constructors(t *testing.T) { - require.Equal(t, group.ScalarLen(), 32) + require.Equal(t, 32, group.ScalarLen()) require.Equal(t, ToInt(group.Scalar()), bigZero) - require.Equal(t, group.PointLen(), 33) - require.Equal(t, group.Point(), &secp256k1Point{fieldZero, fieldZero}) + require.Equal(t, 33, group.PointLen()) + require.Equal(t, &secp256k1Point{fieldZero, fieldZero}, group.Point()) } diff --git a/core/services/signatures/secp256k1/field_test.go b/core/services/signatures/secp256k1/field_test.go index 0914c6390df..012e7dcadd0 100644 --- a/core/services/signatures/secp256k1/field_test.go +++ b/core/services/signatures/secp256k1/field_test.go @@ -46,7 +46,7 @@ func TestField_SetIntAndEqual(t *testing.T) { } func TestField_String(t *testing.T) { - require.Equal(t, fieldZero.String(), "fieldElt{0}") + require.Equal(t, "fieldElt{0}", fieldZero.String()) } func TestField_Equal(t *testing.T) { @@ -74,7 +74,7 @@ func TestField_SmokeTestPick(t *testing.T) { f := newFieldZero() f.Pick(randomStream) observedFieldElt(t, f) - assert.True(t, f.int().Cmp(big.NewInt(1000000000)) == 1, + assert.Equal(t, f.int().Cmp(big.NewInt(1000000000)), 1, "should be greater than 1000000000, with very high probability") } @@ -131,12 +131,12 @@ func TestField_MaybeSquareRootInField(t *testing.T) { for i := 0; i < numFieldSamples; i++ { f.Pick(randomStream) observedFieldElt(t, f) - require.True(t, f.int().Cmp(q) == -1, "picked larger value than q: %s", f) - require.True(t, f.int().Cmp(big.NewInt(-1)) != -1, + require.Equal(t, f.int().Cmp(q), -1, "picked larger value than q: %s", f) + require.NotEqual(t, f.int().Cmp(big.NewInt(-1)), -1, "backing int must be non-negative") s := fieldSquare(f) g := maybeSqrtInField(s) - require.NotEqual(t, g, (*fieldElt)(nil)) + require.NotEqual(t, (*fieldElt)(nil), g) ng := newFieldZero().Neg(g) require.True(t, f.Equal(g) || f.Equal(ng), "squaring something and "+ "taking the square root should give ± the original: failed with %s", f) diff --git a/core/services/signatures/secp256k1/point.go b/core/services/signatures/secp256k1/point.go index 06a5f467baf..04bf3d5c7cc 100644 --- a/core/services/signatures/secp256k1/point.go +++ b/core/services/signatures/secp256k1/point.go @@ -16,6 +16,7 @@ package secp256k1 import ( "crypto/cipher" + "errors" "fmt" "io" "math/big" @@ -142,7 +143,7 @@ func (P *secp256k1Point) Data() ([]byte, error) { b := P.X.Bytes() dataLength := int(b[0]) if dataLength > P.EmbedLen() { - return nil, fmt.Errorf("point specifies too much data") + return nil, errors.New("point specifies too much data") } return b[1 : dataLength+1], nil } @@ -180,7 +181,7 @@ func (P *secp256k1Point) Neg(a kyber.Point) kyber.Point { func (P *secp256k1Point) Mul(s kyber.Scalar, a kyber.Point) kyber.Point { sBytes, err := s.(*secp256k1Scalar).MarshalBinary() if err != nil { - panic(fmt.Errorf("failure while marshaling multiplier: %s", + panic(fmt.Errorf("failure while marshaling multiplier: %w", err)) } var X, Y *big.Int @@ -201,19 +202,18 @@ func (P *secp256k1Point) Mul(s kyber.Scalar, a kyber.Point) kyber.Point { func (P *secp256k1Point) MarshalBinary() ([]byte, error) { maybeSqrt := maybeSqrtInField(rightHandSide(P.X)) if maybeSqrt == (*fieldElt)(nil) { - return nil, fmt.Errorf("x³+7 not a square") + return nil, errors.New("x³+7 not a square") } minusMaybeSqrt := newFieldZero().Neg(maybeSqrt) if !P.Y.Equal(maybeSqrt) && !P.Y.Equal(minusMaybeSqrt) { - return nil, fmt.Errorf( - "y ≠ ±maybeSqrt(x³+7), so not a point on the curve") + return nil, errors.New("y ≠ ±maybeSqrt(x³+7), so not a point on the curve") } rv := make([]byte, P.MarshalSize()) signByte := P.MarshalSize() - 1 // Last byte contains sign of Y. xordinate := P.X.Bytes() copyLen := copy(rv[:signByte], xordinate[:]) if copyLen != P.MarshalSize()-1 { - return []byte{}, fmt.Errorf("marshal of x ordinate too short") + return []byte{}, errors.New("marshal of x ordinate too short") } if P.Y.isEven() { rv[signByte] = 0 @@ -236,10 +236,10 @@ func (P *secp256k1Point) MarshalID() [8]byte { func (P *secp256k1Point) UnmarshalBinary(buf []byte) error { var err error if len(buf) != P.MarshalSize() { - err = fmt.Errorf("wrong length for marshaled point") + err = errors.New("wrong length for marshaled point") } if err == nil && !(buf[32] == 0 || buf[32] == 1) { - err = fmt.Errorf("bad sign byte (the last one)") + err = errors.New("bad sign byte (the last one)") } if err != nil { return err @@ -250,7 +250,7 @@ func (P *secp256k1Point) UnmarshalBinary(buf []byte) error { secp256k1RHS := rightHandSide(P.X) maybeY := maybeSqrtInField(secp256k1RHS) if maybeY == (*fieldElt)(nil) { - return fmt.Errorf("x ordinate does not correspond to a curve point") + return errors.New("x ordinate does not correspond to a curve point") } isEven := maybeY.isEven() P.Y.Set(maybeY) @@ -258,7 +258,7 @@ func (P *secp256k1Point) UnmarshalBinary(buf []byte) error { P.Y.Neg(P.Y) } else { if buf[32] != 0 && buf[32] != 1 { - return fmt.Errorf("parity byte must be 0 or 1") + return errors.New("parity byte must be 0 or 1") } } return nil diff --git a/core/services/signatures/secp256k1/point_test.go b/core/services/signatures/secp256k1/point_test.go index de67f5c3b9c..1171b8bbfea 100644 --- a/core/services/signatures/secp256k1/point_test.go +++ b/core/services/signatures/secp256k1/point_test.go @@ -20,8 +20,7 @@ var numPointSamples = 10 var randomStreamPoint = cryptotest.NewStream(&testing.T{}, 0) func TestPoint_String(t *testing.T) { - require.Equal(t, newPoint().String(), - "Secp256k1{X: fieldElt{0}, Y: fieldElt{0}}") + require.Equal(t, "Secp256k1{X: fieldElt{0}, Y: fieldElt{0}}", newPoint().String()) } func TestPoint_CloneAndEqual(t *testing.T) { @@ -62,7 +61,7 @@ func TestPoint_Embed(t *testing.T) { for i := 0; i < numPointSamples; i++ { data := make([]byte, p.EmbedLen()) _, err := rand.Read(data) - require.Nil(t, err) + require.NoError(t, err) p.Embed(data, randomStreamPoint) require.True(t, s256.IsOnCurve(p.X.int(), p.Y.int()), "should embed to a secp256k1 point") @@ -153,10 +152,10 @@ func TestPoint_Marshal(t *testing.T) { for i := 0; i < numPointSamples; i++ { p.Pick(randomStreamPoint) serialized, err := p.MarshalBinary() - require.Nil(t, err) + require.NoError(t, err) q := newPoint() err = q.UnmarshalBinary(serialized) - require.Nil(t, err) + require.NoError(t, err) require.True(t, p.Equal(q), "%v marshalled to %x, which "+ "unmarshalled to %v", p, serialized, q) } @@ -169,7 +168,7 @@ func TestPoint_Marshal(t *testing.T) { require.Error(t, err) require.Contains(t, err.Error(), "not a point on the curve") id := p.MarshalID() - require.Equal(t, string(id[:]), "sp256.po") + require.Equal(t, "sp256.po", string(id[:])) data := make([]byte, 34) err = p.UnmarshalBinary(data) require.Error(t, err) @@ -202,8 +201,7 @@ func TestPoint_EthereumAddress(t *testing.T) { private := newScalar(pInt) public := newPoint().Mul(private, nil) address := EthereumAddress(public) - assert.Equal(t, fmt.Sprintf("%x", address), - "c2d7cf95645d33006175b78989035c7c9061d3f9") + assert.Equal(t, "c2d7cf95645d33006175b78989035c7c9061d3f9", fmt.Sprintf("%x", address)) } func TestIsSecp256k1Point(t *testing.T) { diff --git a/core/services/signatures/secp256k1/public_key.go b/core/services/signatures/secp256k1/public_key.go index c39565984ae..3f1827fca87 100644 --- a/core/services/signatures/secp256k1/public_key.go +++ b/core/services/signatures/secp256k1/public_key.go @@ -56,7 +56,7 @@ func NewPublicKeyFromBytes(rawKey []byte) (PublicKey, error) { } var k PublicKey if c := copy(k[:], rawKey); c != CompressedPublicKeyLength { - panic(fmt.Errorf("failed to copy entire key to return value")) + panic(errors.New("failed to copy entire key to return value")) } return k, nil } diff --git a/core/services/signatures/secp256k1/public_key_test.go b/core/services/signatures/secp256k1/public_key_test.go index eabce44968f..c391d3c085a 100644 --- a/core/services/signatures/secp256k1/public_key_test.go +++ b/core/services/signatures/secp256k1/public_key_test.go @@ -16,8 +16,7 @@ func TestValueScanIdentityPointSet(t *testing.T) { var pk, nPk, nnPk PublicKey marshaledKey, err := p.MarshalBinary() require.NoError(t, err, "failed to marshal public key") - require.Equal(t, copy(pk[:], marshaledKey), - CompressedPublicKeyLength, "failed to copy marshaled key to pk") + require.Equal(t, CompressedPublicKeyLength, copy(pk[:], marshaledKey), "failed to copy marshaled key to pk") assert.NotEqual(t, pk, nPk, "equality test succeeds on different keys!") np, err := pk.Point() require.NoError(t, err, "failed to marshal public key") diff --git a/core/services/signatures/secp256k1/scalar.go b/core/services/signatures/secp256k1/scalar.go index d12826a8270..d1d63ddcd1c 100644 --- a/core/services/signatures/secp256k1/scalar.go +++ b/core/services/signatures/secp256k1/scalar.go @@ -15,6 +15,7 @@ package secp256k1 import ( "crypto/cipher" + "errors" "fmt" "io" "math/big" @@ -153,7 +154,7 @@ func (s *secp256k1Scalar) MarshalBinary() ([]byte, error) { // leftpad with zeros rv := append(make([]byte, s.MarshalSize()-len(b)), b...) if len(rv) != s.MarshalSize() { - return nil, fmt.Errorf("marshalled scalar to wrong length") + return nil, errors.New("marshalled scalar to wrong length") } return rv, nil } @@ -170,7 +171,7 @@ func (s *secp256k1Scalar) MarshalID() [8]byte { // returning error on failure. func (s *secp256k1Scalar) UnmarshalBinary(buf []byte) error { if len(buf) != s.MarshalSize() { - return fmt.Errorf("cannot unmarshal to scalar: wrong length") + return errors.New("cannot unmarshal to scalar: wrong length") } s.int().Mod(s.int().SetBytes(buf), GroupOrder) return nil @@ -181,7 +182,7 @@ func (s *secp256k1Scalar) UnmarshalBinary(buf []byte) error { func (s *secp256k1Scalar) MarshalTo(w io.Writer) (int, error) { buf, err := s.MarshalBinary() if err != nil { - return 0, fmt.Errorf("cannot marshal binary: %s", err) + return 0, fmt.Errorf("cannot marshal binary: %w", err) } return w.Write(buf) } diff --git a/core/services/signatures/secp256k1/scalar_test.go b/core/services/signatures/secp256k1/scalar_test.go index 63638934f88..409e3e473f3 100644 --- a/core/services/signatures/secp256k1/scalar_test.go +++ b/core/services/signatures/secp256k1/scalar_test.go @@ -60,7 +60,7 @@ func TestScalar_SmokeTestPick(t *testing.T) { for i := 0; i < numScalarSamples; i++ { f.Pick(randomStreamScalar) observedScalar(t, f) - require.True(t, ToInt(f).Cmp(big.NewInt(1000000000)) == 1, + require.Equal(t, ToInt(f).Cmp(big.NewInt(1000000000)), 1, "implausibly low value returned from Pick: %v", f) } } @@ -102,15 +102,15 @@ func TestScalar_Marshal(t *testing.T) { f.Pick(randomStreamScalar) observedScalar(t, f) data, err := f.MarshalBinary() - require.Nil(t, err) + require.NoError(t, err) err = g.UnmarshalBinary(data) - require.Nil(t, err) + require.NoError(t, err) require.True(t, g.Equal(f), "roundtrip through serialization should give same "+ "result back: failed with %s", f) } marshalID := f.(*secp256k1Scalar).MarshalID() - require.Equal(t, string(marshalID[:]), "sp256.sc") + require.Equal(t, "sp256.sc", string(marshalID[:])) data := make([]byte, 33) require.Contains(t, f.UnmarshalBinary(data).Error(), "wrong length") var buf bytes.Buffer @@ -150,7 +150,7 @@ func TestScalar_AllowVarTime(t *testing.T) { } func TestScalar_String(t *testing.T) { - require.Equal(t, newScalar(bigZero).String(), "scalar{0}") + require.Equal(t, "scalar{0}", newScalar(bigZero).String()) } func TestScalar_SetInt64(t *testing.T) { diff --git a/core/services/signatures/secp256k1/suite_test.go b/core/services/signatures/secp256k1/suite_test.go index 64dd2b0766f..f9c48999d1a 100644 --- a/core/services/signatures/secp256k1/suite_test.go +++ b/core/services/signatures/secp256k1/suite_test.go @@ -10,7 +10,6 @@ import ( func TestSuite(t *testing.T) { s := NewBlakeKeccackSecp256k1() emptyHashAsHex := hex.EncodeToString(s.Hash().Sum(nil)) - require.Equal(t, emptyHashAsHex, - "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470") + require.Equal(t, "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", emptyHashAsHex) _ = s.RandomStream() } diff --git a/core/services/standardcapabilities/standard_capabilities.go b/core/services/standardcapabilities/standard_capabilities.go index 76ca5fa1952..a76380c3ae1 100644 --- a/core/services/standardcapabilities/standard_capabilities.go +++ b/core/services/standardcapabilities/standard_capabilities.go @@ -73,12 +73,12 @@ func (s *standardCapabilities) Start(ctx context.Context) error { Env: nil, }) if err != nil { - return fmt.Errorf("error registering loop: %v", err) + return fmt.Errorf("error registering loop: %w", err) } s.capabilitiesLoop = loop.NewStandardCapabilitiesService(s.log, opts, cmdFn) if err = s.capabilitiesLoop.Start(ctx); err != nil { - return fmt.Errorf("error starting standard capabilities service: %v", err) + return fmt.Errorf("error starting standard capabilities service: %w", err) } s.wg.Add(1) diff --git a/core/services/streams/delegate.go b/core/services/streams/delegate.go index bf492d4bd15..eac67274c52 100644 --- a/core/services/streams/delegate.go +++ b/core/services/streams/delegate.go @@ -3,6 +3,7 @@ package streams import ( "context" "fmt" + "strconv" "strings" "github.com/google/uuid" @@ -47,7 +48,7 @@ func (d *Delegate) ServicesForSpec(ctx context.Context, jb job.Job) (services [] return nil, errors.New("streamID is required to be present for stream specs") } id := *jb.StreamID - lggr := d.lggr.Named(fmt.Sprintf("%d", id)).With("streamID", id) + lggr := d.lggr.Named(strconv.FormatUint(uint64(id), 10)).With("streamID", id) rrs := ocrcommon.NewResultRunSaver(d.runner, lggr, d.cfg.MaxSuccessfulRuns(), d.cfg.ResultWriteQueueDepth()) services = append(services, rrs, &StreamService{ diff --git a/core/services/streams/stream_registry_test.go b/core/services/streams/stream_registry_test.go index 738b68f5d4d..b9cb41f591e 100644 --- a/core/services/streams/stream_registry_test.go +++ b/core/services/streams/stream_registry_test.go @@ -52,7 +52,7 @@ func Test_Registry(t *testing.T) { sr := newRegistry(lggr, runner) t.Run("registers new stream", func(t *testing.T) { - assert.Len(t, sr.streams, 0) + assert.Empty(t, sr.streams) err := sr.Register(1, pipeline.Spec{ID: 32, DotDagSource: "source"}, nil) require.NoError(t, err) assert.Len(t, sr.streams, 1) diff --git a/core/services/synchronization/telemetry_ingress_batch_client.go b/core/services/synchronization/telemetry_ingress_batch_client.go index 8ca03d67ef6..55f080b0084 100644 --- a/core/services/synchronization/telemetry_ingress_batch_client.go +++ b/core/services/synchronization/telemetry_ingress_batch_client.go @@ -126,7 +126,7 @@ func (tc *telemetryIngressBatchClient) start(ctx context.Context) error { // Spawns a goroutine that will eventually connect conn, err := wsrpc.DialWithContext(ctx, tc.url.String(), wsrpc.WithTransportCreds(clientPrivKey, serverPubKey), wsrpc.WithLogger(tc.eng)) if err != nil { - return fmt.Errorf("could not start TelemIngressBatchClient, Dial returned error: %v", err) + return fmt.Errorf("could not start TelemIngressBatchClient, Dial returned error: %w", err) } tc.telemClient = telemPb.NewTelemClient(conn) tc.closeFn = func() error { conn.Close(); return nil } diff --git a/core/services/synchronization/telemetry_ingress_batch_worker_test.go b/core/services/synchronization/telemetry_ingress_batch_worker_test.go index 64166252a8f..61c2d45953b 100644 --- a/core/services/synchronization/telemetry_ingress_batch_worker_test.go +++ b/core/services/synchronization/telemetry_ingress_batch_worker_test.go @@ -43,13 +43,13 @@ func TestTelemetryIngressWorker_BuildTelemBatchReq(t *testing.T) { assert.Equal(t, string(synchronization.OCR), batchReq1.TelemetryType) assert.Len(t, batchReq1.Telemetry, maxTelemBatchSize) assert.Len(t, chTelemetry, 2) - assert.Greater(t, batchReq1.SentAt, int64(0)) + assert.Positive(t, batchReq1.SentAt) // Remainder of telemetry should be batched on next call batchReq2 := worker.BuildTelemBatchReq() assert.Equal(t, "0xa", batchReq2.ContractId) assert.Equal(t, string(synchronization.OCR), batchReq2.TelemetryType) assert.Len(t, batchReq2.Telemetry, 2) - assert.Len(t, chTelemetry, 0) - assert.Greater(t, batchReq2.SentAt, int64(0)) + assert.Empty(t, chTelemetry) + assert.Positive(t, batchReq2.SentAt) } diff --git a/core/services/synchronization/telemetry_ingress_client_test.go b/core/services/synchronization/telemetry_ingress_client_test.go index 407051ff19b..7d31540fab7 100644 --- a/core/services/synchronization/telemetry_ingress_client_test.go +++ b/core/services/synchronization/telemetry_ingress_client_test.go @@ -54,7 +54,7 @@ func TestTelemetryIngressClient_Send_HappyPath(t *testing.T) { assert.Equal(t, telemPayload.ContractID, telemReq.Address) assert.Equal(t, telemPayload.Telemetry, telemReq.Telemetry) assert.Equal(t, string(synchronization.OCR), telemReq.TelemetryType) - assert.Greater(t, telemReq.SentAt, int64(0)) + assert.Positive(t, telemReq.SentAt) }) // Send telemetry diff --git a/core/services/telemetry/manager_test.go b/core/services/telemetry/manager_test.go index df8e87018bc..eb93e630861 100644 --- a/core/services/telemetry/manager_test.go +++ b/core/services/telemetry/manager_test.go @@ -1,7 +1,6 @@ package telemetry import ( - "fmt" "math/big" "net/url" "reflect" @@ -157,12 +156,12 @@ func TestNewManager(t *testing.T) { require.Equal(t, uint(123), m.bufferSize) require.Equal(t, ks, m.ks) require.Equal(t, "TelemetryManager", m.Name()) - require.Equal(t, true, m.logging) + require.True(t, m.logging) require.Equal(t, uint(51), m.maxBatchSize) require.Equal(t, time.Millisecond*512, m.sendInterval) require.Equal(t, time.Second*7, m.sendTimeout) - require.Equal(t, true, m.uniConn) - require.Equal(t, true, m.useBatchSend) + require.True(t, m.uniConn) + require.True(t, m.useBatchSend) logs := logObs.TakeAll() for i, e := range endpoints { @@ -178,20 +177,20 @@ func TestNewManager(t *testing.T) { found = true } } - require.Equal(t, true, found, "cannot find log: %s", e.expectedError) + require.True(t, found, "cannot find log: %s", e.expectedError) } } require.Equal(t, "TelemetryManager", m.Name()) - require.Nil(t, m.Start(testutils.Context(t))) + require.NoError(t, m.Start(testutils.Context(t))) t.Cleanup(func() { require.NoError(t, m.Close()) }) testutils.WaitForLogMessageCount(t, logObs, "error connecting error while dialing dial tcp", 3) hr := m.HealthReport() - require.Equal(t, 4, len(hr)) + require.Len(t, hr, 4) } func TestCorrectEndpointRouting(t *testing.T) { @@ -263,8 +262,8 @@ func TestCorrectEndpointRouting(t *testing.T) { // Known networks and chainID for i, e := range testEndpoints { - telemType := fmt.Sprintf("TelemType_%s", e.chainID) - contractID := fmt.Sprintf("contractID_%s", e.chainID) + telemType := "TelemType_" + e.chainID + contractID := "contractID_" + e.chainID me := tm.GenMonitoringEndpoint( e.network, e.chainID, @@ -274,7 +273,7 @@ func TestCorrectEndpointRouting(t *testing.T) { me.SendLog([]byte(e.chainID)) require.Equal(t, 0, obsLogs.Len()) - require.Equal(t, i+1, len(clientSent)) + require.Len(t, clientSent, i+1) require.Equal(t, contractID, clientSent[i].ContractID) require.Equal(t, telemType, string(clientSent[i].TelemType)) require.Equal(t, []byte(e.chainID), clientSent[i].Telemetry) diff --git a/core/services/vrf/delegate_test.go b/core/services/vrf/delegate_test.go index 7ef3febd021..b4c86bc3682 100644 --- a/core/services/vrf/delegate_test.go +++ b/core/services/vrf/delegate_test.go @@ -223,7 +223,7 @@ func TestDelegate_ReorgAttackProtection(t *testing.T) { // Wait until the log is present waitForChannel(t, added, time.Second, "request not added to the queue") reqs := listener.ReqsConfirmedAt() - if assert.Equal(t, 1, len(reqs)) { + if assert.Len(t, reqs, 1) { // It should be confirmed at 10+6*(2^2) assert.Equal(t, uint64(34), reqs[0]) } @@ -321,7 +321,7 @@ func TestDelegate_ValidLog(t *testing.T) { waitForChannel(t, runComplete, 2*time.Second, "pipeline not complete") runs, err := vuni.prm.GetAllRuns(ctx) require.NoError(t, err) - require.Equal(t, i+1, len(runs)) + require.Len(t, runs, i+1) assert.False(t, runs[0].FatalErrors.HasError()) // Should have 4 tasks all completed assert.Len(t, runs[0].PipelineTaskRuns, 4) @@ -396,7 +396,7 @@ func TestDelegate_InvalidLog(t *testing.T) { // Should create a run that errors in the vrf task runs, err := vuni.prm.GetAllRuns(ctx) require.NoError(t, err) - require.Equal(t, len(runs), 1) + require.Len(t, runs, 1) for _, tr := range runs[0].PipelineTaskRuns { if tr.Type == pipeline.TaskTypeVRF { assert.Contains(t, tr.Error.String, "invalid key hash") @@ -412,7 +412,7 @@ func TestDelegate_InvalidLog(t *testing.T) { txes, err := txStore.GetAllTxes(testutils.Context(t)) require.NoError(t, err) - require.Len(t, txes, 0) + require.Empty(t, txes) } func TestFulfilledCheck(t *testing.T) { @@ -460,7 +460,7 @@ func TestFulfilledCheck(t *testing.T) { // Should consume the log with no run runs, err := vuni.prm.GetAllRuns(ctx) require.NoError(t, err) - require.Equal(t, len(runs), 0) + require.Empty(t, runs) } func Test_CheckFromAddressMaxGasPrices(t *testing.T) { diff --git a/core/services/vrf/solidity_cross_tests/vrf_coordinator_solidity_crosscheck_test.go b/core/services/vrf/solidity_cross_tests/vrf_coordinator_solidity_crosscheck_test.go index ad3d48ce78e..d214b608974 100644 --- a/core/services/vrf/solidity_cross_tests/vrf_coordinator_solidity_crosscheck_test.go +++ b/core/services/vrf/solidity_cross_tests/vrf_coordinator_solidity_crosscheck_test.go @@ -65,7 +65,7 @@ func TestRegisterProvingKey(t *testing.T) { for log.Next() { logCount++ assert.Equal(t, log.Event.KeyHash, keyHash, "VRFCoordinator logged a different keyHash than was registered") - assert.True(t, fee.Cmp(log.Event.Fee) == 0, "VRFCoordinator logged a different fee than was registered") + assert.Equal(t, fee.Cmp(log.Event.Fee), 0, "VRFCoordinator logged a different fee than was registered") } require.Equal(t, 1, logCount, "unexpected NewServiceAgreement log generated by key VRF key registration") serviceAgreement, err := coord.RootContract.ServiceAgreements(nil, keyHash) @@ -74,7 +74,7 @@ func TestRegisterProvingKey(t *testing.T) { "VRFCoordinator registered wrong provider, on service agreement!") assert.Equal(t, jobID, serviceAgreement.JobID, "VRFCoordinator registered wrong jobID, on service agreement!") - assert.True(t, fee.Cmp(serviceAgreement.Fee) == 0, + assert.Equal(t, fee.Cmp(serviceAgreement.Fee), 0, "VRFCoordinator registered wrong fee, on service agreement!") } @@ -164,7 +164,7 @@ func TestRandomnessRequestLog(t *testing.T) { nonce := big.NewInt(0) actualSeed, err := tc.ms() require.NoError(t, err, "failure while using VRFCoordinator to calculate actual VRF input seed") - assert.True(t, actualSeed.Cmp(log.Seed) == 0, + assert.Equal(t, actualSeed.Cmp(log.Seed), 0, "VRFCoordinator logged wrong actual input seed from randomness request") golangSeed := utils.MustHash(string(append(append(append( keyHash[:], @@ -174,7 +174,7 @@ func TestRandomnessRequestLog(t *testing.T) { assert.Equal(t, golangSeed, common.BigToHash((log.Seed)), "VRFCoordinator logged different actual input seed than expected by golang code!") assert.Equal(t, jobID, log.JobID, "VRFCoordinator logged different JobID from randomness request!") assert.Equal(t, tc.consumerAddress, log.Sender, "VRFCoordinator logged different requester address from randomness request!") - assert.True(t, fee.Cmp((*big.Int)(log.Fee)) == 0, "VRFCoordinator logged different fee from randomness request!") + assert.Equal(t, fee.Cmp((*big.Int)(log.Fee)), 0, "VRFCoordinator logged different fee from randomness request!") parsedLog, err := solidity_cross_tests.ParseRandomnessRequestLog(log.Raw.Raw) assert.NoError(t, err, "could not parse randomness request log generated by VRFCoordinator") assert.True(t, parsedLog.Equal(*log), "got a different randomness request log by parsing the raw data than reported by simulated backend") @@ -217,7 +217,7 @@ func TestFulfillRandomness(t *testing.T) { output, err := coordinator.ConsumerContract.RandomnessOutput(nil) require.NoError(t, err, "failed to get VRF output from consuming contract, "+ "after randomness request was fulfilled") - assert.True(t, proof.Output.Cmp(output) == 0, "VRF output from randomness "+ + assert.Equal(t, proof.Output.Cmp(output), 0, "VRF output from randomness "+ "request fulfillment was different than provided! Expected %d, got %d. "+ "This can happen if you update the VRFCoordinator wrapper without a "+ "corresponding update to the VRFConsumer", proof.Output, output) @@ -229,7 +229,7 @@ func TestFulfillRandomness(t *testing.T) { nil, coordinator.Neil.From) require.NoError(t, err, "failed to get neil's token balance, after he "+ "successfully fulfilled a randomness request") - assert.True(t, neilBalance.Cmp(fee) == 0, "neil's balance on VRFCoordinator "+ + assert.Equal(t, neilBalance.Cmp(fee), 0, "neil's balance on VRFCoordinator "+ "was not paid his fee, despite successful fulfillment of randomness request!") } @@ -246,12 +246,12 @@ func TestWithdraw(t *testing.T) { coordinator.Backend.Commit() peteBalance, err := coordinator.LinkContract.BalanceOf(nil, peteThePunter) require.NoError(t, err, "failed to get balance of payee on LINK contract, after payment") - assert.True(t, payment.Cmp(peteBalance) == 0, + assert.Equal(t, payment.Cmp(peteBalance), 0, "LINK balance is wrong, following payment") neilBalance, err := coordinator.RootContract.WithdrawableTokens( nil, coordinator.Neil.From) require.NoError(t, err, "failed to get neil's balance on VRFCoordinator") - assert.True(t, big.NewInt(0).Sub(fee, payment).Cmp(neilBalance) == 0, + assert.Equal(t, big.NewInt(0).Sub(fee, payment).Cmp(neilBalance), 0, "neil's VRFCoordinator balance is wrong, after he's made a withdrawal!") _, err = coordinator.RootContract.Withdraw(coordinator.Neil, peteThePunter, fee) assert.Error(t, err, "VRFcoordinator allowed overdraft") diff --git a/core/services/vrf/solidity_cross_tests/vrf_solidity_crosscheck_test.go b/core/services/vrf/solidity_cross_tests/vrf_solidity_crosscheck_test.go index d58ce1f7b6c..61f27793b2f 100644 --- a/core/services/vrf/solidity_cross_tests/vrf_solidity_crosscheck_test.go +++ b/core/services/vrf/solidity_cross_tests/vrf_solidity_crosscheck_test.go @@ -366,7 +366,7 @@ func TestVRF_MarshalProof(t *testing.T) { require.NoError(t, err, "failed to marshal VRF proof for on-chain verification") response, err := deployVRFTestHelper(t).RandomValueFromVRFProof(nil, mproof[:]) require.NoError(t, err, "failed on-chain to verify VRF proof / get its output") - require.True(t, response.Cmp(proof.Output) == 0, + require.Equal(t, response.Cmp(proof.Output), 0, "on-chain VRF output differs from off-chain!") corruptionTargetByte := r.Int63n(int64(len(mproof))) // Only the lower 160 bits of the word containing uWitness have any effect diff --git a/core/services/vrf/solidity_cross_tests/vrf_v08_solidity_crosscheck_test.go b/core/services/vrf/solidity_cross_tests/vrf_v08_solidity_crosscheck_test.go index 8b88ad73ea9..4dd2cbdeeb7 100644 --- a/core/services/vrf/solidity_cross_tests/vrf_v08_solidity_crosscheck_test.go +++ b/core/services/vrf/solidity_cross_tests/vrf_v08_solidity_crosscheck_test.go @@ -43,11 +43,11 @@ func TestVRFV08_InvalidPointCoordinates(t *testing.T) { _, err := verifier.IsOnCurve(nil, [2]*big.Int{big.NewInt(10), secp256k1.FieldSize}) require.Error(t, err) - assert.Equal(t, err.Error(), "execution reverted: invalid y-ordinate") + assert.Equal(t, "execution reverted: invalid y-ordinate", err.Error()) _, err = verifier.IsOnCurve(nil, [2]*big.Int{secp256k1.FieldSize, big.NewInt(10)}) require.Error(t, err) - assert.Equal(t, err.Error(), "execution reverted: invalid x-ordinate") + assert.Equal(t, "execution reverted: invalid x-ordinate", err.Error()) // Values inside should succeed _, err = verifier.IsOnCurve(nil, [2]*big.Int{big.NewInt(10), big.NewInt(0).Sub(secp256k1.FieldSize, big.NewInt(1))}) @@ -321,7 +321,7 @@ func TestVRFV08_MarshalProof(t *testing.T) { ZInv: solProof.ZInv, }, randomSeed) require.NoError(t, err, "failed on-chain to verify VRF proof / get its output") - require.True(t, response.Cmp(proof.Output) == 0, + require.Equal(t, response.Cmp(proof.Output), 0, "on-chain VRF output differs from off-chain!") } } diff --git a/core/services/vrf/v1/integration_test.go b/core/services/vrf/v1/integration_test.go index 6b416f5c5f8..2e8c25765de 100644 --- a/core/services/vrf/v1/integration_test.go +++ b/core/services/vrf/v1/integration_test.go @@ -90,8 +90,8 @@ func TestIntegration_VRF_JPV2(t *testing.T) { return len(runs) == 2 && runs[0].State == pipeline.RunStatusCompleted && runs[1].State == pipeline.RunStatusCompleted }, testutils.WaitTimeout(t), 1*time.Second) assert.Equal(t, pipeline.RunErrors([]null.String{{}}), runs[0].FatalErrors) - assert.Equal(t, 4, len(runs[0].PipelineTaskRuns)) - assert.Equal(t, 4, len(runs[1].PipelineTaskRuns)) + assert.Len(t, runs[0].PipelineTaskRuns, 4) + assert.Len(t, runs[1].PipelineTaskRuns, 4) assert.NotNil(t, 0, runs[0].Outputs.Val) assert.NotNil(t, 0, runs[1].Outputs.Val) @@ -210,7 +210,7 @@ func TestIntegration_VRF_WithBHS(t *testing.T) { return len(runs) == 1 && runs[0].State == pipeline.RunStatusCompleted }, 10*time.Second, 1*time.Second) assert.Equal(t, pipeline.RunErrors([]null.String{{}}), runs[0].FatalErrors) - assert.Equal(t, 4, len(runs[0].PipelineTaskRuns)) + assert.Len(t, runs[0].PipelineTaskRuns, 4) assert.NotNil(t, 0, runs[0].Outputs.Val) // stop jobs as to not cause a race condition in geth simulated backend diff --git a/core/services/vrf/v1/listener_v1.go b/core/services/vrf/v1/listener_v1.go index 74b522d4089..004636e0902 100644 --- a/core/services/vrf/v1/listener_v1.go +++ b/core/services/vrf/v1/listener_v1.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "math/big" + "strconv" "strings" "sync" "time" @@ -153,7 +154,7 @@ func (lsn *Listener) Start(ctx context.Context) error { go lsn.RunLogListener([]func(){unsubscribeLogs}, spec.MinIncomingConfirmations) go lsn.RunHeadListener(unsubscribeHeadBroadcaster) - lsn.MailMon.Monitor(lsn.ReqLogs, "VRFListener", "RequestLogs", fmt.Sprint(lsn.Job.ID)) + lsn.MailMon.Monitor(lsn.ReqLogs, "VRFListener", "RequestLogs", strconv.Itoa(int(lsn.Job.ID))) return nil }) } diff --git a/core/services/vrf/v1/listener_v1_test.go b/core/services/vrf/v1/listener_v1_test.go index c05358686df..96363464043 100644 --- a/core/services/vrf/v1/listener_v1_test.go +++ b/core/services/vrf/v1/listener_v1_test.go @@ -35,18 +35,18 @@ func TestConfirmedLogExtraction(t *testing.T) { // None are confirmed lsn.LatestHead = 0 logs := lsn.extractConfirmedLogs() - assert.Equal(t, 0, len(logs)) // None ready - assert.Equal(t, 3, len(lsn.Reqs)) // All pending + assert.Empty(t, logs) // None ready + assert.Len(t, lsn.Reqs, 3) // All pending lsn.LatestHead = 2 logs = lsn.extractConfirmedLogs() - assert.Equal(t, 2, len(logs)) // 1 and 2 should be confirmed - assert.Equal(t, 1, len(lsn.Reqs)) // 3 is still pending + assert.Len(t, logs, 2) // 1 and 2 should be confirmed + assert.Len(t, lsn.Reqs, 1) // 3 is still pending assert.Equal(t, uint64(3), lsn.Reqs[0].confirmedAtBlock) // Another block way in the future should clear it lsn.LatestHead = 10 logs = lsn.extractConfirmedLogs() - assert.Equal(t, 1, len(logs)) // remaining log - assert.Equal(t, 0, len(lsn.Reqs)) // all processed + assert.Len(t, logs, 1) // remaining log + assert.Empty(t, lsn.Reqs) // all processed } func TestResponsePruning(t *testing.T) { @@ -66,11 +66,11 @@ func TestResponsePruning(t *testing.T) { reqID: utils.PadByteToHash(0x01), }) lsn.pruneConfirmedRequestCounts() - assert.Equal(t, 2, len(lsn.ResponseCount)) + assert.Len(t, lsn.ResponseCount, 2) lsn.LatestHead = 10001 lsn.pruneConfirmedRequestCounts() - assert.Equal(t, 1, len(lsn.ResponseCount)) + assert.Len(t, lsn.ResponseCount, 1) lsn.LatestHead = 10002 lsn.pruneConfirmedRequestCounts() - assert.Equal(t, 0, len(lsn.ResponseCount)) + assert.Empty(t, lsn.ResponseCount) } diff --git a/core/services/vrf/v2/coordinator_v2x_interface.go b/core/services/vrf/v2/coordinator_v2x_interface.go index 35e8bcd4709..98c0a38aece 100644 --- a/core/services/vrf/v2/coordinator_v2x_interface.go +++ b/core/services/vrf/v2/coordinator_v2x_interface.go @@ -156,7 +156,7 @@ func (c *coordinatorV2) Version() vrfcommon.Version { func (c *coordinatorV2) RegisterProvingKey(opts *bind.TransactOpts, oracle *common.Address, publicProvingKey [2]*big.Int, maxGasPrice *uint64) (*types.Transaction, error) { if maxGasPrice != nil { - return nil, fmt.Errorf("max gas price not supported for registering proving key in v2") + return nil, errors.New("max gas price not supported for registering proving key in v2") } return c.coordinator.RegisterProvingKey(opts, *oracle, publicProvingKey) } diff --git a/core/services/vrf/v2/integration_helpers_test.go b/core/services/vrf/v2/integration_helpers_test.go index 1a46fc1e334..d30d45df31a 100644 --- a/core/services/vrf/v2/integration_helpers_test.go +++ b/core/services/vrf/v2/integration_helpers_test.go @@ -950,7 +950,7 @@ func testSingleConsumerForcedFulfillment( sub, err := uni.oldRootContract.GetSubscription(nil, subID) require.NoError(t, err, "failed to get subscription with id %d", subID) require.Equal(t, assets.Ether(5).ToInt(), sub.Balance()) - require.Equal(t, 1, len(sub.Consumers())) + require.Len(t, sub.Consumers(), 1) require.Equal(t, eoaConsumerAddr, sub.Consumers()[0]) require.Equal(t, uni.neil.From, sub.Owner()) @@ -1058,7 +1058,7 @@ func testSingleConsumerForcedFulfillment( require.Equal(t, subID.Uint64(), it.Event.SubId) require.Equal(t, eoaConsumerAddr.String(), it.Event.Sender.String()) } - require.Greater(t, i, 0) + require.Positive(t, i) t.Log("Done!") } @@ -1264,8 +1264,8 @@ func testSingleConsumerBigGasCallbackSandwich( { runs, err := app.PipelineORM().GetAllRuns(ctx) require.NoError(t, err) - assert.Equal(t, 0, len(runs)) - assert.Equal(t, 3, len(reqIDs)) + assert.Empty(t, runs) + assert.Len(t, reqIDs, 3) } // Wait for the 50_000 gas randomness request to be enqueued. @@ -1296,7 +1296,7 @@ func testSingleConsumerBigGasCallbackSandwich( { runs, err := app.PipelineORM().GetAllRuns(ctx) require.NoError(t, err) - assert.Equal(t, 1, len(runs)) + assert.Len(t, runs, 1) } // Make some randomness requests, each one block apart, this time without a low-gas request present in the callbackGasLimit slice. @@ -1738,8 +1738,8 @@ func testMaliciousConsumer( for it.Next() { fulfillments = append(fulfillments, it.Event()) } - require.Equal(t, 1, len(fulfillments)) - require.Equal(t, false, fulfillments[0].Success()) + require.Len(t, fulfillments, 1) + require.False(t, fulfillments[0].Success()) // It should not have succeeded in placing another request. it2, err2 := uni.rootContract.FilterRandomWordsRequested(nil, nil, nil, nil) @@ -1748,7 +1748,7 @@ func testMaliciousConsumer( for it2.Next() { requests = append(requests, it2.Event()) } - require.Equal(t, 1, len(requests)) + require.Len(t, requests, 1) } func testReplayOldRequestsOnStartUp( diff --git a/core/services/vrf/v2/integration_v2_reverted_txns_test.go b/core/services/vrf/v2/integration_v2_reverted_txns_test.go index 67716d440e3..87429fa34fe 100644 --- a/core/services/vrf/v2/integration_v2_reverted_txns_test.go +++ b/core/services/vrf/v2/integration_v2_reverted_txns_test.go @@ -99,7 +99,7 @@ func TestVRFV2Integration_ForceFulfillmentRevertedTxn_Retry(t *testing.T) { waitForForceFulfillment(t, th, req, th.subs[0], true, 2) receipts, err := getTxnReceiptDB(th.db, -1) - require.Nil(t, err) + require.NoError(t, err) require.Len(t, receipts, 2) require.Equal(t, uint64(0), receipts[0].EVMReceipt.Status) require.Equal(t, uint64(1), receipts[1].EVMReceipt.Status) @@ -121,7 +121,7 @@ func TestVRFV2Integration_CanceledSubForceFulfillmentRevertedTxn_Retry(t *testin waitForForceFulfillment(t, th, req, th.subs[0], true, 2) receipts, err := getTxnReceiptDB(th.db, -1) - require.Nil(t, err) + require.NoError(t, err) require.Len(t, receipts, 2) require.Equal(t, uint64(0), receipts[0].EVMReceipt.Status) require.Equal(t, uint64(1), receipts[1].EVMReceipt.Status) @@ -150,10 +150,10 @@ func TestUniqueReqById_NoPendingReceipts(t *testing.T) { require.Len(t, res, 2) for _, r := range res { if r.RequestID == "1" { - require.Equal(t, r.ForceFulfillmentAttempt, 2) + require.Equal(t, 2, r.ForceFulfillmentAttempt) } if r.RequestID == "2" { - require.Equal(t, r.ForceFulfillmentAttempt, 4) + require.Equal(t, 4, r.ForceFulfillmentAttempt) } } } @@ -181,7 +181,7 @@ func TestUniqueReqById_WithPendingReceipts(t *testing.T) { require.Len(t, res, 1) for _, r := range res { if r.RequestID == "1" { - require.Equal(t, r.ForceFulfillmentAttempt, 2) + require.Equal(t, 2, r.ForceFulfillmentAttempt) } } } @@ -250,7 +250,7 @@ func makeVRFReq(t *testing.T, th *revertTxnTH, sub *vrfSub) (req *vrfReq) { callbackGasLimit := uint32(600_000) _, err := th.eoaConsumer.RequestRandomWords(th.uni.neil, sub.subID, callbackGasLimit, uint16(confs), numWords, th.keyHash) - require.NoError(t, err, fmt.Sprintf("failed to request randomness from consumer: %v", err)) + require.NoError(t, err, "failed to request randomness from consumer: %v", err) th.uni.backend.Commit() // Generate VRF proof @@ -310,7 +310,7 @@ func fulfillVRFReq(t *testing.T, mine(t, req.requestID, big.NewInt(int64(sub.subID)), th.uni.backend, th.db, vrfcommon.V2, th.chainID) receipts, err := getTxnReceiptDB(th.db, etx.ID) - require.Nil(t, err) + require.NoError(t, err) require.Len(t, receipts, 1) require.Equal(t, uint64(0), receipts[0].EVMReceipt.Status) req.txID = etx.ID @@ -370,7 +370,7 @@ func fulfilBatchVRFReq(t *testing.T, mineBatch(t, requestIDInts, big.NewInt(int64(sub.subID)), th.uni.backend, th.db, vrfcommon.V2, chainID) receipts, err := getTxnReceiptDB(th.db, etx.ID) - require.Nil(t, err) + require.NoError(t, err) require.Len(t, receipts, 1) require.Equal(t, uint64(1), receipts[0].EVMReceipt.Status) } @@ -688,7 +688,7 @@ func setupSub(t *testing.T, th *revertTxnTH, subID uint64, balance uint64) { consumers := sub.Consumers() require.NoError(t, err, "failed to get subscription with id %d", subID) require.Equal(t, big.NewInt(int64(balance)), sub.Balance()) - require.Equal(t, 1, len(consumers)) + require.Len(t, consumers, 1) require.Equal(t, th.eoaConsumerAddr, consumers[0]) require.Equal(t, uni.neil.From, sub.Owner()) } diff --git a/core/services/vrf/v2/integration_v2_test.go b/core/services/vrf/v2/integration_v2_test.go index 6cbcc799e1b..ca72147c724 100644 --- a/core/services/vrf/v2/integration_v2_test.go +++ b/core/services/vrf/v2/integration_v2_test.go @@ -1126,8 +1126,8 @@ func testEoa( // Ensure there is only one log broadcast (our EOA request), and that // it hasn't been marked as consumed yet. - require.Equal(t, 1, len(broadcastsBeforeFinality)) - require.Equal(t, false, broadcastsBeforeFinality[0].Consumed) + require.Len(t, broadcastsBeforeFinality, 1) + require.False(t, broadcastsBeforeFinality[0].Consumed) // Create new blocks until the finality depth has elapsed. for i := 0; i < int(finalityDepth); i++ { @@ -1148,8 +1148,8 @@ func testEoa( // Ensure that there is still only one log broadcast (our EOA request), but that // it has been marked as "consumed," such that it won't be retried. - require.Equal(t, 1, len(broadcastsAfterFinality)) - require.Equal(t, true, broadcastsAfterFinality[0].Consumed) + require.Len(t, broadcastsAfterFinality, 1) + require.True(t, broadcastsAfterFinality[0].Consumed) t.Log("Done!") } @@ -2114,7 +2114,7 @@ func TestStartingCountsV1(t *testing.T) { var counts map[[32]byte]uint64 counts, err = listenerV1.GetStartingResponseCountsV1(testutils.Context(t)) require.NoError(t, err) - assert.Equal(t, 0, len(counts)) + assert.Empty(t, counts) err = ks.Unlock(ctx, testutils.Password) require.NoError(t, err) k, err := ks.Eth().Create(testutils.Context(t), testutils.SimulatedChainID) @@ -2267,7 +2267,7 @@ func TestStartingCountsV1(t *testing.T) { counts, err = listenerV1.GetStartingResponseCountsV1(testutils.Context(t)) require.NoError(t, err) - assert.Equal(t, 3, len(counts)) + assert.Len(t, counts, 3) assert.Equal(t, uint64(1), counts[evmutils.PadByteToHash(0x10)]) assert.Equal(t, uint64(2), counts[evmutils.PadByteToHash(0x11)]) assert.Equal(t, uint64(2), counts[evmutils.PadByteToHash(0x12)]) @@ -2275,7 +2275,7 @@ func TestStartingCountsV1(t *testing.T) { countsV2, err := listenerV2.GetStartingResponseCountsV2(testutils.Context(t)) require.NoError(t, err) t.Log(countsV2) - assert.Equal(t, 3, len(countsV2)) + assert.Len(t, countsV2, 3) assert.Equal(t, uint64(1), countsV2[big.NewInt(0x10).String()]) assert.Equal(t, uint64(2), countsV2[big.NewInt(0x11).String()]) assert.Equal(t, uint64(2), countsV2[big.NewInt(0x12).String()]) diff --git a/core/services/vrf/v2/listener_v2_helpers_test.go b/core/services/vrf/v2/listener_v2_helpers_test.go index 401a5bcc577..464b5a5655b 100644 --- a/core/services/vrf/v2/listener_v2_helpers_test.go +++ b/core/services/vrf/v2/listener_v2_helpers_test.go @@ -18,13 +18,13 @@ func TestListener_EstimateFeeJuels(t *testing.T) { weiPerUnitLink := big.NewInt(5898160000000000) actual, err := v2.EstimateFeeJuels(callbackGasLimit, maxGasPriceGwei, weiPerUnitLink) expected := big.NewInt(1780216203019246680) - require.True(t, actual.Cmp(expected) == 0, "expected:", expected.String(), "actual:", actual.String()) + require.Equal(t, actual.Cmp(expected), 0, "expected:", expected.String(), "actual:", actual.String()) require.NoError(t, err) weiPerUnitLink = big.NewInt(5898161234554321) actual, err = v2.EstimateFeeJuels(callbackGasLimit, maxGasPriceGwei, weiPerUnitLink) expected = big.NewInt(1780215830399116719) - require.True(t, actual.Cmp(expected) == 0, "expected:", expected.String(), "actual:", actual.String()) + require.Equal(t, actual.Cmp(expected), 0, "expected:", expected.String(), "actual:", actual.String()) require.NoError(t, err) actual, err = v2.EstimateFeeJuels(callbackGasLimit, maxGasPriceGwei, big.NewInt(0)) @@ -49,5 +49,5 @@ func Test_TxListDeduper(t *testing.T) { ChainID: big.NewInt(0), } txList := vrfcommon.DedupeTxList([]*txmgr.Tx{tx1, tx2, tx3}) - require.Equal(t, len(txList), 2) + require.Len(t, txList, 2) } diff --git a/core/services/vrf/v2/listener_v2_log_listener_test.go b/core/services/vrf/v2/listener_v2_log_listener_test.go index 06af4c83f19..483b45cf613 100644 --- a/core/services/vrf/v2/listener_v2_log_listener_test.go +++ b/core/services/vrf/v2/listener_v2_log_listener_test.go @@ -4,6 +4,7 @@ import ( "fmt" "math" "math/big" + "strconv" "strings" "testing" "time" @@ -127,7 +128,7 @@ func setupVRFLogPollerListenerTH(t *testing.T) *vrfLogPollerListenerTH { require.NoError(t, err) coordinatorV2, err := vrf_coordinator_v2.NewVRFCoordinatorV2(vrfLogEmitter.Address(), ec) - require.Nil(t, err) + require.NoError(t, err) coordinator := NewCoordinatorV2(coordinatorV2) chain := evmmocks.NewChain(t) @@ -157,13 +158,13 @@ func setupVRFLogPollerListenerTH(t *testing.T) *vrfLogPollerListenerTH { // listener.job.VRFSpec.CoordinatorAddress.Address(), }, }) - require.Nil(t, err) + require.NoError(t, err) require.NoError(t, lp.RegisterFilter(ctx, logpoller.Filter{ Name: "Integration test", EventSigs: []common.Hash{emitterABI.Events["Log1"].ID}, Addresses: []common.Address{emitterAddress1}, Retention: 0})) - require.Nil(t, err) + require.NoError(t, err) require.Len(t, lp.Filter(nil, nil, nil).Addresses, 2) require.Len(t, lp.Filter(nil, nil, nil).Topics, 1) require.Len(t, lp.Filter(nil, nil, nil).Topics[0], 3) @@ -228,10 +229,10 @@ func TestInitProcessedBlock_NoVRFReqs(t *testing.T) { // Should return logs from block 5 to 7 (inclusive) logs, err := th.LogPoller.Logs(testutils.Context(t), 4, 7, emitterABI.Events["Log1"].ID, th.EmitterAddress) require.NoError(t, err) - require.Equal(t, 3, len(logs)) + require.Len(t, logs, 3) lastProcessedBlock, err := th.Listener.initializeLastProcessedBlock(ctx) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(6), lastProcessedBlock) } @@ -314,7 +315,7 @@ func TestInitProcessedBlock_NoUnfulfilledVRFReqs(t *testing.T) { // initializeLastProcessedBlock must return the finalizedBlockNumber (8) instead of // VRF request block number (5), since all VRF requests are fulfilled lastProcessedBlock, err := th.Listener.initializeLastProcessedBlock(ctx) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(8), lastProcessedBlock) } @@ -366,7 +367,7 @@ func TestInitProcessedBlock_OneUnfulfilledVRFReq(t *testing.T) { // initializeLastProcessedBlock must return the unfulfilled VRF // request block number (5) instead of finalizedBlockNumber (8) lastProcessedBlock, err := th.Listener.initializeLastProcessedBlock(ctx) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(5), lastProcessedBlock) } @@ -426,7 +427,7 @@ func TestInitProcessedBlock_SomeUnfulfilledVRFReqs(t *testing.T) { // initializeLastProcessedBlock must return the earliest unfulfilled VRF request block // number instead of finalizedBlockNumber lastProcessedBlock, err := th.Listener.initializeLastProcessedBlock(ctx) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(6), lastProcessedBlock) } @@ -490,7 +491,7 @@ func TestInitProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { // initializeLastProcessedBlock must return the earliest unfulfilled VRF request block // number instead of finalizedBlockNumber lastProcessedBlock, err := th.Listener.initializeLastProcessedBlock(ctx) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(7), lastProcessedBlock) } @@ -556,7 +557,7 @@ func TestUpdateLastProcessedBlock_NoVRFReqs(t *testing.T) { // no VRF requests, after currLastProcessedBlock (block 6). The VRF requests // made above are before the currLastProcessedBlock (7) passed in below lastProcessedBlock, err := th.Listener.updateLastProcessedBlock(ctx, 7) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(8), lastProcessedBlock) } @@ -610,7 +611,7 @@ func TestUpdateLastProcessedBlock_NoUnfulfilledVRFReqs(t *testing.T) { // a VRF req at block (5) after currLastProcessedBlock (4) passed below, because // the VRF request is fulfilled lastProcessedBlock, err := th.Listener.updateLastProcessedBlock(ctx, 4) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(8), lastProcessedBlock) } @@ -660,7 +661,7 @@ func TestUpdateLastProcessedBlock_OneUnfulfilledVRFReq(t *testing.T) { // finalizedBlockNumber (8) after currLastProcessedBlock (4) passed below, // because the VRF request is unfulfilled lastProcessedBlock, err := th.Listener.updateLastProcessedBlock(ctx, 4) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(5), lastProcessedBlock) } @@ -716,7 +717,7 @@ func TestUpdateLastProcessedBlock_SomeUnfulfilledVRFReqs(t *testing.T) { // finalizedBlockNumber (16) after currLastProcessedBlock (4) passed below, // as block 6 contains the earliest unfulfilled VRF request lastProcessedBlock, err := th.Listener.updateLastProcessedBlock(ctx, 4) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(6), lastProcessedBlock) } @@ -777,7 +778,7 @@ func TestUpdateLastProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { // as block 7 contains the earliest unfulfilled VRF request. VRF request // in block 6 has been fulfilled in block 7. lastProcessedBlock, err := th.Listener.updateLastProcessedBlock(ctx, 4) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, int64(7), lastProcessedBlock) } @@ -812,7 +813,7 @@ func SetupGetUnfulfilledTH(t *testing.T) (*listenerV2, *ubig.Big) { require.NoError(t, err) b.Commit() coordinatorV2, err := vrf_coordinator_v2.NewVRFCoordinatorV2(vrfLogEmitter.Address(), b.Client()) - require.Nil(t, err) + require.NoError(t, err) coordinator := NewCoordinatorV2(coordinatorV2) listener := &listenerV2{ @@ -884,7 +885,7 @@ func TestGetUnfulfilled_NoUnfulfilledVRFReqs(t *testing.T) { EventSig: eventSig, Address: common.Address{}, TxHash: common.BigToHash(big.NewInt(int64(2 * i))), - Data: common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + fmt.Sprintf("%d", i) + "000000000000000000000000000000000000000000000000000000000000006a000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000002"), + Data: common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + strconv.Itoa(i) + "000000000000000000000000000000000000000000000000000000000000006a000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000002"), CreatedAt: time.Now(), }) if i%2 == 0 { @@ -896,7 +897,7 @@ func TestGetUnfulfilled_NoUnfulfilledVRFReqs(t *testing.T) { BlockTimestamp: time.Now(), Topics: [][]byte{ common.FromHex("0x7dffc5ae5ee4e2e4df1651cf6ad329a73cebdb728f37ea0187b9b17e036756e4"), - common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + fmt.Sprintf("%d", i)), + common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + strconv.Itoa(i)), }, EventSig: vrfEmitterABI.Events["RandomWordsFulfilled"].ID, Address: common.Address{}, @@ -942,7 +943,7 @@ func TestGetUnfulfilled_OneUnfulfilledVRFReq(t *testing.T) { EventSig: eventSig, Address: common.Address{}, TxHash: common.BigToHash(big.NewInt(int64(2 * i))), - Data: common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + fmt.Sprintf("%d", i) + "000000000000000000000000000000000000000000000000000000000000006a000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000002"), + Data: common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + strconv.Itoa(i) + "000000000000000000000000000000000000000000000000000000000000006a000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000002"), CreatedAt: time.Now(), }) } @@ -983,19 +984,19 @@ func TestGetUnfulfilled_SomeUnfulfilledVRFReq(t *testing.T) { EventSig: eventSig, Address: common.Address{}, TxHash: common.BigToHash(big.NewInt(int64(2 * i))), - Data: common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + fmt.Sprintf("%d", i) + "000000000000000000000000000000000000000000000000000000000000006a000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000002"), + Data: common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + strconv.Itoa(i) + "000000000000000000000000000000000000000000000000000000000000006a000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000002"), CreatedAt: time.Now(), }) } unfulfilled, _, fulfilled := listener.getUnfulfilled(logs, listener.l) require.Len(t, unfulfilled, 5) - require.Len(t, fulfilled, 0) + require.Empty(t, fulfilled) expected := map[int64]bool{0: true, 2: true, 4: true, 6: true, 8: true} for _, u := range unfulfilled { v, ok := expected[u.RequestID().Int64()] - require.Equal(t, ok, true) - require.Equal(t, v, true) + require.True(t, ok) + require.True(t, v) } require.Equal(t, len(expected), len(unfulfilled)) } @@ -1030,7 +1031,7 @@ func TestGetUnfulfilled_UnfulfilledNFulfilledVRFReqs(t *testing.T) { EventSig: eventSig, Address: common.Address{}, TxHash: common.BigToHash(big.NewInt(int64(2 * i))), - Data: common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + fmt.Sprintf("%d", i) + "000000000000000000000000000000000000000000000000000000000000006a000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000002"), + Data: common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + strconv.Itoa(i) + "000000000000000000000000000000000000000000000000000000000000006a000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000002"), CreatedAt: time.Now(), }) if i%2 == 0 && i < 6 { @@ -1042,7 +1043,7 @@ func TestGetUnfulfilled_UnfulfilledNFulfilledVRFReqs(t *testing.T) { BlockTimestamp: time.Now(), Topics: [][]byte{ common.FromHex("0x7dffc5ae5ee4e2e4df1651cf6ad329a73cebdb728f37ea0187b9b17e036756e4"), - common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + fmt.Sprintf("%d", i)), + common.FromHex("0x000000000000000000000000000000000000000000000000000000000000000" + strconv.Itoa(i)), }, EventSig: vrfEmitterABI.Events["RandomWordsFulfilled"].ID, Address: common.Address{}, @@ -1059,8 +1060,8 @@ func TestGetUnfulfilled_UnfulfilledNFulfilledVRFReqs(t *testing.T) { expected := map[int64]bool{6: true, 8: true} for _, u := range unfulfilled { v, ok := expected[u.RequestID().Int64()] - require.Equal(t, ok, true) - require.Equal(t, v, true) + require.True(t, ok) + require.True(t, v) } require.Equal(t, len(expected), len(unfulfilled)) } diff --git a/core/services/vrf/v2/reverted_txns.go b/core/services/vrf/v2/reverted_txns.go index 846ba347bc7..c93b037a887 100644 --- a/core/services/vrf/v2/reverted_txns.go +++ b/core/services/vrf/v2/reverted_txns.go @@ -496,7 +496,7 @@ func (lsn *listenerV2) filterSingleRevertedTxn(ctx context.Context, } _, rpcError := ethClient.CallContract(ctx, call, txnReceiptDB.EVMReceipt.BlockNumber) if rpcError == nil { - return nil, fmt.Errorf("error fetching revert reason %v: %v", txnReceiptDB.TxHash, err) + return nil, fmt.Errorf("error fetching revert reason %v: %w", txnReceiptDB.TxHash, err) } revertErr, err := evmclient.ExtractRPCError(rpcError) lsn.l.Infow("InsufficientBalRevertedTxn", @@ -505,7 +505,7 @@ func (lsn *listenerV2) filterSingleRevertedTxn(ctx context.Context, "ParsingErr", err, ) if err != nil { - return nil, fmt.Errorf("reverted_txn_reason_parse_err: %v", err) + return nil, fmt.Errorf("reverted_txn_reason_parse_err: %w", err) } revertErrDataStr := "" revertErrDataBytes := []byte{} @@ -535,7 +535,7 @@ func (lsn *listenerV2) filterSingleRevertedTxn(ctx context.Context, callData := txData[4:] // Remove first 4 bytes of function signature unpacked, err := coordinatorV2ABI.Methods["fulfillRandomWords"].Inputs.Unpack(callData) if err != nil { - return nil, fmt.Errorf("invalid_txn_data_for_tx_pack: %s, err %v", tx.Hash().String(), err) + return nil, fmt.Errorf("invalid_txn_data_for_tx_pack: %s, err %w", tx.Hash().String(), err) } proof := abi.ConvertType(unpacked[0], new(vrf_coordinator_v2.VRFProof)).(*vrf_coordinator_v2.VRFProof) reqCommitment := abi.ConvertType(unpacked[1], new(vrf_coordinator_v2.VRFCoordinatorV2RequestCommitment)).(*vrf_coordinator_v2.VRFCoordinatorV2RequestCommitment) @@ -564,7 +564,7 @@ func (lsn *listenerV2) filterBatchRevertedTxn(ctx context.Context, for _, proof := range *proofs { payload, err := evmutils.ABIEncode(`[{"type":"bytes32"},{"type":"uint256"}]`, keyHash, proof.Seed) if err != nil { - return nil, fmt.Errorf("ABI Encode Error: (err %v), (keyHash %v), (prood: %v)", err, keyHash, proof.Seed) + return nil, fmt.Errorf("ABI Encode Error: (err %w), (keyHash %v), (prood: %v)", err, keyHash, proof.Seed) } requestIDOfProof := common.BytesToHash(crypto.Keccak256(payload)) proofReqIDs = append(proofReqIDs, requestIDOfProof) diff --git a/core/services/vrf/vrfcommon/validate_test.go b/core/services/vrf/vrfcommon/validate_test.go index efb1f22216f..ceef5c297ba 100644 --- a/core/services/vrf/vrfcommon/validate_test.go +++ b/core/services/vrf/vrfcommon/validate_test.go @@ -191,7 +191,7 @@ decode_log->vrf->encode_tx->submit_tx `, assertion: func(t *testing.T, s job.Job, err error) { require.NoError(t, err) - assert.Equal(t, s.ExternalJobID.String(), "0eec7e1d-d0d2-476c-a1a8-72dfb6633f46") + assert.Equal(t, "0eec7e1d-d0d2-476c-a1a8-72dfb6633f46", s.ExternalJobID.String()) }, }, { diff --git a/core/services/webhook/external_initiator_manager_test.go b/core/services/webhook/external_initiator_manager_test.go index a2402b4114d..0426af3aaf0 100644 --- a/core/services/webhook/external_initiator_manager_test.go +++ b/core/services/webhook/external_initiator_manager_test.go @@ -42,13 +42,13 @@ func Test_ExternalInitiatorManager_Load(t *testing.T) { eiWebhookSpecs, jobID, err := eim.Load(ctx, webhookSpecNoEIs.ID) require.NoError(t, err) - assert.Len(t, eiWebhookSpecs, 0) + assert.Empty(t, eiWebhookSpecs) assert.Equal(t, jb3.ExternalJobID, jobID) eiWebhookSpecs, jobID, err = eim.Load(ctx, webhookSpecOneEI.ID) require.NoError(t, err) assert.Len(t, eiWebhookSpecs, 1) - assert.Equal(t, `{"ei": "foo", "name": "webhookSpecOneEI"}`, eiWebhookSpecs[0].Spec.Raw) + assert.JSONEq(t, `{"ei": "foo", "name": "webhookSpecOneEI"}`, eiWebhookSpecs[0].Spec.Raw) assert.Equal(t, eiFoo.ID, eiWebhookSpecs[0].ExternalInitiator.ID) assert.Equal(t, jb1.ExternalJobID, jobID) @@ -90,7 +90,7 @@ func Test_ExternalInitiatorManager_Notify(t *testing.T) { assert.Equal(t, jb.ExternalJobID.String(), gjson.GetBytes(b, "jobId").Str) assert.Equal(t, eiWithURL.Name, gjson.GetBytes(b, "type").Str) - assert.Equal(t, `{"ei":"foo","name":"webhookSpecTwoEIs"}`, gjson.GetBytes(b, "params").Raw) + assert.JSONEq(t, `{"ei":"foo","name":"webhookSpecTwoEIs"}`, gjson.GetBytes(b, "params").Raw) return r.Method == "POST" && r.URL.String() == eiWithURL.URL.String() && r.Header["Content-Type"][0] == "application/json" && r.Header["X-Chainlink-Ea-Accesskey"][0] == "token" && r.Header["X-Chainlink-Ea-Secret"][0] == "secret" })).Once().Return(&http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(""))}, nil) diff --git a/core/services/workflows/engine.go b/core/services/workflows/engine.go index d153e53bc07..404a677b0f2 100644 --- a/core/services/workflows/engine.go +++ b/core/services/workflows/engine.go @@ -510,7 +510,7 @@ func (e *Engine) stepUpdateLoop(ctx context.Context, executionID string, stepUpd return } // Executed synchronously to ensure we correctly schedule subsequent tasks. - e.logger.Debugw(fmt.Sprintf("received step update for execution %s", stepUpdate.ExecutionID), + e.logger.Debugw("received step update for execution "+stepUpdate.ExecutionID, platform.KeyWorkflowExecutionID, stepUpdate.ExecutionID, platform.KeyStepRef, stepUpdate.Ref) err := e.handleStepUpdate(ctx, stepUpdate, workflowCreatedAt) if err != nil { diff --git a/core/services/workflows/engine_test.go b/core/services/workflows/engine_test.go index 95ac74f0c76..6c81e098313 100644 --- a/core/services/workflows/engine_test.go +++ b/core/services/workflows/engine_test.go @@ -309,7 +309,7 @@ func TestEngineWithHardcodedWorkflow(t *testing.T) { state, err := eng.executionStates.Get(ctx, eid) require.NoError(t, err) - assert.Equal(t, state.Status, store.StatusCompleted) + assert.Equal(t, store.StatusCompleted, state.Status) } const ( @@ -490,9 +490,9 @@ func TestEngine_ErrorsTheWorkflowIfAStepErrors(t *testing.T) { state, err := eng.executionStates.Get(ctx, eid) require.NoError(t, err) - assert.Equal(t, state.Status, store.StatusErrored) + assert.Equal(t, store.StatusErrored, state.Status) // evm_median is the ref of our failing consensus step - assert.Equal(t, state.Steps["evm_median"].Status, store.StatusErrored) + assert.Equal(t, store.StatusErrored, state.Steps["evm_median"].Status) } func TestEngine_GracefulEarlyTermination(t *testing.T) { @@ -513,7 +513,7 @@ func TestEngine_GracefulEarlyTermination(t *testing.T) { state, err := eng.executionStates.Get(ctx, eid) require.NoError(t, err) - assert.Equal(t, state.Status, store.StatusCompletedEarlyExit) + assert.Equal(t, store.StatusCompletedEarlyExit, state.Status) assert.Nil(t, state.Steps["write_polygon-testnet-mumbai"]) } @@ -607,7 +607,7 @@ func TestEngine_MultiStepDependencies(t *testing.T) { state, err := eng.executionStates.Get(ctx, eid) require.NoError(t, err) - assert.Equal(t, state.Status, store.StatusCompleted) + assert.Equal(t, store.StatusCompleted, state.Status) // The inputs to the consensus step should // be the outputs of the two dependents. @@ -958,7 +958,7 @@ func TestEngine_PassthroughInterpolation(t *testing.T) { state, err := eng.executionStates.Get(ctx, eid) require.NoError(t, err) - assert.Equal(t, state.Status, store.StatusCompleted) + assert.Equal(t, store.StatusCompleted, state.Status) // There is passthrough interpolation between the consensus and target steps, // so the input of one should be the output of the other, exactly. @@ -1105,13 +1105,13 @@ func TestEngine_MergesWorkflowConfigAndCRConfig(t *testing.T) { state, err := eng.executionStates.Get(ctx, eid) require.NoError(t, err) - assert.Equal(t, state.Status, store.StatusCompleted) + assert.Equal(t, store.StatusCompleted, state.Status) // Assert that the config from the CR is merged with the default config from the registry. m, err := values.Unwrap(gotConfig) require.NoError(t, err) - assert.Equal(t, m.(map[string]any)["deltaStage"], "1s") - assert.Equal(t, m.(map[string]any)["schedule"], "allAtOnce") + assert.Equal(t, "1s", m.(map[string]any)["deltaStage"]) + assert.Equal(t, "allAtOnce", m.(map[string]any)["schedule"]) for _, k := range wantConfigKeys { assert.Contains(t, m.(map[string]any), k) @@ -1245,7 +1245,7 @@ func TestEngine_MergesWorkflowConfigAndCRConfig_CRConfigPrecedence(t *testing.T) state, err := eng.executionStates.Get(ctx, eid) require.NoError(t, err) - assert.Equal(t, state.Status, store.StatusCompleted) + assert.Equal(t, store.StatusCompleted, state.Status) // Assert that the config from the CR is merged with the default config from the registry. With // the CR config taking precedence. @@ -1299,7 +1299,7 @@ func TestEngine_HandlesNilConfigOnchain(t *testing.T) { state, err := eng.executionStates.Get(ctx, eid) require.NoError(t, err) - assert.Equal(t, state.Status, store.StatusCompleted) + assert.Equal(t, store.StatusCompleted, state.Status) m, err := values.Unwrap(gotConfig) require.NoError(t, err) @@ -1484,7 +1484,7 @@ func TestEngine_WithCustomComputeStep(t *testing.T) { state, err := eng.executionStates.Get(ctx, eid) require.NoError(t, err) - assert.Equal(t, state.Status, store.StatusCompleted) + assert.Equal(t, store.StatusCompleted, state.Status) res, ok := state.ResultForStep("compute") assert.True(t, ok) assert.True(t, res.Outputs.(*values.Map).Underlying["Value"].(*values.Bool).Underlying) diff --git a/core/services/workflows/monitoring_test.go b/core/services/workflows/monitoring_test.go index 5b7177e51dc..a43232c6986 100644 --- a/core/services/workflows/monitoring_test.go +++ b/core/services/workflows/monitoring_test.go @@ -16,5 +16,5 @@ func Test_InitMonitoringResources(t *testing.T) { func Test_WorkflowMetricsLabeler(t *testing.T) { testWorkflowsMetricLabeler := workflowsMetricLabeler{metrics.NewLabeler(), engineMetrics{}} testWorkflowsMetricLabeler2 := testWorkflowsMetricLabeler.with("foo", "baz") - require.EqualValues(t, testWorkflowsMetricLabeler2.Labels["foo"], "baz") + require.EqualValues(t, "baz", testWorkflowsMetricLabeler2.Labels["foo"]) } diff --git a/core/services/workflows/retry.go b/core/services/workflows/retry.go index e3f04353e7f..b7b4ac5346f 100644 --- a/core/services/workflows/retry.go +++ b/core/services/workflows/retry.go @@ -2,7 +2,7 @@ package workflows import ( "context" - "fmt" + "errors" "time" "github.com/smartcontractkit/chainlink/v2/core/logger" @@ -33,7 +33,7 @@ func retryable(ctx context.Context, lggr logger.Logger, retryMs int, maxRetries if maxRetries > 0 { if retries >= maxRetries { lggr.Errorf("%s", err) - return fmt.Errorf("max retries reached, aborting") + return errors.New("max retries reached, aborting") } } lggr.Errorf("%s, retrying in %.2fs", err, float64(retryMs)/1000) diff --git a/core/sessions/ldapauth/ldap_test.go b/core/sessions/ldapauth/ldap_test.go index ff3bc4096dc..928252fbc2b 100644 --- a/core/sessions/ldapauth/ldap_test.go +++ b/core/sessions/ldapauth/ldap_test.go @@ -377,15 +377,15 @@ func TestORM_ListUsers_Full(t *testing.T) { users, err := ldapAuthProvider.ListUsers(ctx) require.NoError(t, err) require.Equal(t, users[0].Email, user1.Email) - require.Equal(t, users[0].Role, sessions.UserRoleAdmin) + require.Equal(t, sessions.UserRoleAdmin, users[0].Role) require.Equal(t, users[1].Email, user3.Email) // User 2 inactive - require.Equal(t, users[1].Role, sessions.UserRoleEdit) + require.Equal(t, sessions.UserRoleEdit, users[1].Role) require.Equal(t, users[2].Email, user4.Email) - require.Equal(t, users[2].Role, sessions.UserRoleRun) + require.Equal(t, sessions.UserRoleRun, users[2].Role) require.Equal(t, users[3].Email, user6.Email) // User 5 inactive - require.Equal(t, users[3].Role, sessions.UserRoleView) - require.Equal(t, users[4].Email, cltest.APIEmailAdmin) // Text fixture user is local admin included as well - require.Equal(t, users[4].Role, sessions.UserRoleAdmin) + require.Equal(t, sessions.UserRoleView, users[3].Role) + require.Equal(t, cltest.APIEmailAdmin, users[4].Email) // Text fixture user is local admin included as well + require.Equal(t, sessions.UserRoleAdmin, users[4].Role) } func TestORM_CreateSession_UpstreamBind(t *testing.T) { diff --git a/core/sessions/localauth/orm_test.go b/core/sessions/localauth/orm_test.go index 1087af9499c..bed51ba9a30 100644 --- a/core/sessions/localauth/orm_test.go +++ b/core/sessions/localauth/orm_test.go @@ -208,7 +208,7 @@ func TestORM_WebAuthn(t *testing.T) { was, err := orm.GetUserWebAuthn(ctx, initial.Email) require.NoError(t, err) - assert.Len(t, was, 0) + assert.Empty(t, was) cred := webauthn.Credential{ ID: []byte("test-id"), diff --git a/core/sessions/webauthn.go b/core/sessions/webauthn.go index a1c01a446cd..cb362b0903d 100644 --- a/core/sessions/webauthn.go +++ b/core/sessions/webauthn.go @@ -62,7 +62,7 @@ func (store *WebAuthnSessionStore) BeginWebAuthnRegistration(user User, uwas []W return nil, err } - userRegistrationIndexKey := fmt.Sprintf("%s-registration", user.Email) + userRegistrationIndexKey := user.Email + "-registration" err = store.SaveWebauthnSession(userRegistrationIndexKey, sessionData) if err != nil { return nil, err @@ -81,7 +81,7 @@ func (store *WebAuthnSessionStore) FinishWebAuthnRegistration(user User, uwas [] return nil, err } - userRegistrationIndexKey := fmt.Sprintf("%s-registration", user.Email) + userRegistrationIndexKey := user.Email + "-registration" sessionData, err := store.GetWebauthnSession(userRegistrationIndexKey) if err != nil { return nil, err @@ -121,7 +121,7 @@ func BeginWebAuthnLogin(user User, uwas []WebAuthn, sr SessionRequest) (*protoco return nil, err } - userLoginIndexKey := fmt.Sprintf("%s-authentication", user.Email) + userLoginIndexKey := user.Email + "-authentication" err = sr.SessionStore.SaveWebauthnSession(userLoginIndexKey, sessionData) if err != nil { return nil, err @@ -146,7 +146,7 @@ func FinishWebAuthnLogin(user User, uwas []WebAuthn, sr SessionRequest) error { return err } - userLoginIndexKey := fmt.Sprintf("%s-authentication", user.Email) + userLoginIndexKey := user.Email + "-authentication" sessionData, err := sr.SessionStore.GetWebauthnSession(userLoginIndexKey) if err != nil { return err @@ -210,7 +210,7 @@ func (u *WebAuthnUser) LoadWebAuthnCredentials(uwas []WebAuthn) error { var credential webauthn.Credential err := v.PublicKeyData.Unmarshal(&credential) if err != nil { - return fmt.Errorf("error unmarshalling provided PublicKeyData: %s", err) + return fmt.Errorf("error unmarshalling provided PublicKeyData: %w", err) } u.WACredentials = append(u.WACredentials, credential) } diff --git a/core/static/static.go b/core/static/static.go index f840331bc99..72b9b99298b 100644 --- a/core/static/static.go +++ b/core/static/static.go @@ -44,7 +44,7 @@ func SetConsumerName(uri *url.URL, name string, id *uuid.UUID) { applicationName := fmt.Sprintf("Chainlink%s|%s", buildPrettyVersion(), name) if id != nil { - applicationName += fmt.Sprintf("|%s", id.String()) + applicationName += "|" + id.String() } if len(applicationName) > 63 { applicationName = applicationName[:63] diff --git a/core/store/migrate/migrate_test.go b/core/store/migrate/migrate_test.go index adbc0ca2f66..bfb6e8cb153 100644 --- a/core/store/migrate/migrate_test.go +++ b/core/store/migrate/migrate_test.go @@ -460,16 +460,16 @@ func TestDatabaseBackFillWithMigration202(t *testing.T) { assert.Len(t, results, 201) simulatedOrm := logpoller.NewORM(testutils.SimulatedChainID, db, logger.TestLogger(t)) - require.NoError(t, simulatedOrm.InsertBlock(ctx, testutils.Random32Byte(), 10, time.Now(), 0), err) - require.NoError(t, simulatedOrm.InsertBlock(ctx, testutils.Random32Byte(), 51, time.Now(), 0), err) - require.NoError(t, simulatedOrm.InsertBlock(ctx, testutils.Random32Byte(), 90, time.Now(), 0), err) - require.NoError(t, simulatedOrm.InsertBlock(ctx, testutils.Random32Byte(), 120, time.Now(), 23), err) + require.NoError(t, simulatedOrm.InsertBlock(ctx, testutils.Random32Byte(), 10, time.Now(), 0)) + require.NoError(t, simulatedOrm.InsertBlock(ctx, testutils.Random32Byte(), 51, time.Now(), 0)) + require.NoError(t, simulatedOrm.InsertBlock(ctx, testutils.Random32Byte(), 90, time.Now(), 0)) + require.NoError(t, simulatedOrm.InsertBlock(ctx, testutils.Random32Byte(), 120, time.Now(), 23)) baseOrm := logpoller.NewORM(big.NewInt(int64(84531)), db, logger.TestLogger(t)) - require.NoError(t, baseOrm.InsertBlock(ctx, testutils.Random32Byte(), 400, time.Now(), 0), err) + require.NoError(t, baseOrm.InsertBlock(ctx, testutils.Random32Byte(), 400, time.Now(), 0)) klaytnOrm := logpoller.NewORM(big.NewInt(int64(1001)), db, logger.TestLogger(t)) - require.NoError(t, klaytnOrm.InsertBlock(ctx, testutils.Random32Byte(), 100, time.Now(), 0), err) + require.NoError(t, klaytnOrm.InsertBlock(ctx, testutils.Random32Byte(), 100, time.Now(), 0)) _, err = p.UpTo(ctx, 202) require.NoError(t, err) diff --git a/core/store/migrate/migrations/0056_multichain.go b/core/store/migrate/migrations/0056_multichain.go index 39d7ec70b2b..35931a31142 100644 --- a/core/store/migrate/migrations/0056_multichain.go +++ b/core/store/migrate/migrations/0056_multichain.go @@ -3,7 +3,6 @@ package migrations import ( "context" "database/sql" - "fmt" "log" "math/big" "os" @@ -61,7 +60,7 @@ func Up56(ctx context.Context, tx *sql.Tx) error { } chainID, ok := new(big.Int).SetString(chainIDStr, 10) if !ok { - panic(fmt.Sprintf("ETH_CHAIN_ID was invalid, expected a number, got: %s", chainIDStr)) + panic("ETH_CHAIN_ID was invalid, expected a number, got: " + chainIDStr) } _, err := tx.ExecContext(ctx, "INSERT INTO evm_chains (id, created_at, updated_at) VALUES ($1, NOW(), NOW());", chainID.String()) return err diff --git a/core/store/models/common_test.go b/core/store/models/common_test.go index eca703d5f3a..70ebae483d6 100644 --- a/core/store/models/common_test.go +++ b/core/store/models/common_test.go @@ -79,8 +79,8 @@ func TestJSON_Merge(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - j1 := cltest.JSONFromString(t, test.original) - j2 := cltest.JSONFromString(t, test.input) + j1 := cltest.JSONFromString(t, "%s", test.original) + j2 := cltest.JSONFromString(t, "%s", test.input) merged, err := models.Merge(j1, j2) if test.wantError { diff --git a/core/store/models/errors_test.go b/core/store/models/errors_test.go index e752e0456c9..58a6238e121 100644 --- a/core/store/models/errors_test.go +++ b/core/store/models/errors_test.go @@ -15,7 +15,7 @@ func TestNewJSONAPIErrors(t *testing.T) { res := models.NewJSONAPIErrors() require.NotNil(t, res) require.NotNil(t, res.Errors) - require.Len(t, res.Errors, 0) + require.Empty(t, res.Errors) } func TestNewJSONAPIErrorsWith(t *testing.T) { diff --git a/core/utils/backoff_ticker_test.go b/core/utils/backoff_ticker_test.go index ee7c023ab20..c9de6e021d3 100644 --- a/core/utils/backoff_ticker_test.go +++ b/core/utils/backoff_ticker_test.go @@ -13,8 +13,8 @@ func TestBackoffTicker_Bounds(t *testing.T) { bt := NewBackoffTicker(1*time.Millisecond, 2*time.Second) min, max := bt.Bounds() - assert.Equal(t, min, 1*time.Millisecond) - assert.Equal(t, max, 2*time.Second) + assert.Equal(t, 1*time.Millisecond, min) + assert.Equal(t, 2*time.Second, max) } func TestBackoffTicker_StartTwice(t *testing.T) { diff --git a/core/utils/collection.go b/core/utils/collection.go index 3ab7a806a92..72ef397d3f3 100644 --- a/core/utils/collection.go +++ b/core/utils/collection.go @@ -1,13 +1,11 @@ package utils -import ( - "fmt" -) +import "github.com/pkg/errors" // BatchSplit splits an slices into an slices of slicess with a maximum length func BatchSplit[T any](list []T, max int) (out [][]T, err error) { if max == 0 { - return out, fmt.Errorf("max batch length cannot be 0") + return out, errors.New("max batch length cannot be 0") } // batch list into no more than max each diff --git a/core/utils/collection_test.go b/core/utils/collection_test.go index f956192d3a0..da835fed864 100644 --- a/core/utils/collection_test.go +++ b/core/utils/collection_test.go @@ -39,7 +39,7 @@ func TestBatchSplit(t *testing.T) { } assert.NoError(t, err) - assert.Equal(t, r.num, len(batch)) // check number of batches + assert.Len(t, batch, r.num) // check number of batches temp := []int{} for i := 0; i < len(batch); i++ { @@ -47,7 +47,7 @@ func TestBatchSplit(t *testing.T) { if i == len(batch)-1 { expectedLen = r.lastLen // expect last batch to be less than max } - assert.Equal(t, expectedLen, len(batch[i])) // check length of batch + assert.Len(t, batch[i], expectedLen) // check length of batch temp = append(temp, batch[i]...) } diff --git a/core/utils/config/validate.go b/core/utils/config/validate.go index 5c62a66ba14..fe776de44e1 100644 --- a/core/utils/config/validate.go +++ b/core/utils/config/validate.go @@ -27,7 +27,7 @@ type ErrOverride struct { } func (e ErrOverride) Error() string { - return fmt.Sprintf("%s: overrides (duplicate keys or list elements) are not allowed for multiple secrets files", e.Name) + return e.Name + ": overrides (duplicate keys or list elements) are not allowed for multiple secrets files" } type ErrDeprecated struct { diff --git a/core/utils/hash.go b/core/utils/hash.go index b0a32454e2f..d4afd081e1e 100644 --- a/core/utils/hash.go +++ b/core/utils/hash.go @@ -35,7 +35,7 @@ func (h *Hash) SetBytes(b []byte) { } // Hex converts a hash to a hex string. -func (h Hash) Hex() string { return fmt.Sprintf("0x%s", hex.EncodeToString(h[:])) } +func (h Hash) Hex() string { return "0x" + hex.EncodeToString(h[:]) } // String implements the stringer interface and is used also by the logger when // doing full logging into a file. diff --git a/core/utils/http/http_allowed_ips.go b/core/utils/http/http_allowed_ips.go index 2b77e89c7d4..a00e981fa81 100644 --- a/core/utils/http/http_allowed_ips.go +++ b/core/utils/http/http_allowed_ips.go @@ -27,7 +27,7 @@ func init() { } { _, block, err := net.ParseCIDR(cidr) if err != nil { - panic(fmt.Errorf("parse error on %q: %v", cidr, err)) + panic(fmt.Errorf("parse error on %q: %w", cidr, err)) } privateIPBlocks = append(privateIPBlocks, block) } diff --git a/core/utils/tomlutils/toml_test.go b/core/utils/tomlutils/toml_test.go index ece71b034a4..b640eee73eb 100644 --- a/core/utils/tomlutils/toml_test.go +++ b/core/utils/tomlutils/toml_test.go @@ -13,7 +13,7 @@ func TestUtils_TomlFloat32_Success_Decimal(t *testing.T) { err := tomlF32.UnmarshalText([]byte("0.23")) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, tomlF32, Float32(0.23)) } @@ -24,7 +24,7 @@ func TestUtils_TomlFloat32_Success_Integer(t *testing.T) { err := tomlF32.UnmarshalText([]byte("13")) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, tomlF32, Float32(13)) } @@ -35,7 +35,7 @@ func TestUtils_TomlFloat32_Failure(t *testing.T) { err := tomlF32.UnmarshalText([]byte("1s")) - assert.NotNil(t, err) + assert.Error(t, err) } func TestUtils_TomlFloat64_Success_Decimal(t *testing.T) { @@ -45,7 +45,7 @@ func TestUtils_TomlFloat64_Success_Decimal(t *testing.T) { err := tomlF64.UnmarshalText([]byte("2.82")) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, tomlF64, Float64(2.82)) } @@ -56,7 +56,7 @@ func TestUtils_TomlFloat64_Success_Integer(t *testing.T) { err := tomlF64.UnmarshalText([]byte("3")) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, tomlF64, Float64(3)) } @@ -67,5 +67,5 @@ func TestUtils_TomlFloat64_Failure(t *testing.T) { err := tomlF64.UnmarshalText([]byte("1s")) - assert.NotNil(t, err) + assert.Error(t, err) } diff --git a/core/utils/utils_test.go b/core/utils/utils_test.go index 587bd46efb9..6d7e7cfe9f5 100644 --- a/core/utils/utils_test.go +++ b/core/utils/utils_test.go @@ -41,7 +41,7 @@ func TestUtils_NewSecret(t *testing.T) { t.Parallel() secret := utils.NewSecret(test.numOfBytes) - assert.Equal(t, test.wantStrLen, len(secret)) + assert.Len(t, secret, test.wantStrLen) }) } } @@ -74,7 +74,7 @@ func TestUtils_DurationFromNow(t *testing.T) { future := time.Now().Add(time.Second) duration := utils.DurationFromNow(future) - assert.True(t, 0 < duration) + assert.Positive(t, duration) } func TestBoundedQueue(t *testing.T) { @@ -503,7 +503,7 @@ func TestErrorBuffer(t *testing.T) { buff.Append(err2) combined := buff.Flush() errs := utils.UnwrapError(combined) - assert.Equal(t, 2, len(errs)) + assert.Len(t, errs, 2) assert.Equal(t, err1.Error(), errs[0].Error()) assert.Equal(t, err2.Error(), errs[1].Error()) }) @@ -517,7 +517,7 @@ func TestErrorBuffer(t *testing.T) { buff.Append(err3) combined := buff.Flush() errs := utils.UnwrapError(combined) - assert.Equal(t, 2, len(errs)) + assert.Len(t, errs, 2) assert.Equal(t, err2.Error(), errs[0].Error()) assert.Equal(t, err3.Error(), errs[1].Error()) }) @@ -531,14 +531,14 @@ func TestErrorBuffer(t *testing.T) { combined := buff.Flush() errs := utils.UnwrapError(combined) - assert.Equal(t, 20, len(errs)) + assert.Len(t, errs, 20) assert.Equal(t, "err#20", errs[19].Error()) }) t.Run("UnwrapError returns the a single element err array if passed err is not a joinedError", func(t *testing.T) { t.Parallel() errs := utils.UnwrapError(err1) - assert.Equal(t, 1, len(errs)) + assert.Len(t, errs, 1) assert.Equal(t, err1.Error(), errs[0].Error()) }) @@ -547,6 +547,6 @@ func TestErrorBuffer(t *testing.T) { buff := utils.ErrorBuffer{} combined := buff.Flush() - require.Nil(t, combined) + require.NoError(t, combined) }) } diff --git a/core/web/api.go b/core/web/api.go index 51f7b855cd5..2a2a8baf15c 100644 --- a/core/web/api.go +++ b/core/web/api.go @@ -36,13 +36,13 @@ func ParsePaginatedRequest(sizeParam, pageParam string) (int, int, int, error) { if sizeParam != "" { if size, err = strconv.Atoi(sizeParam); err != nil || size < 1 { - return 0, 0, 0, fmt.Errorf("invalid size param, error: %+v", err) + return 0, 0, 0, fmt.Errorf("invalid size param, error: %+w", err) } } if pageParam != "" { if page, err = strconv.Atoi(pageParam); err != nil || page < 1 { - return 0, 0, 0, fmt.Errorf("invalid page param, error: %+v", err) + return 0, 0, 0, fmt.Errorf("invalid page param, error: %+w", err) } } @@ -70,7 +70,7 @@ func prevLink(url url.URL, size, page int) jsonapi.Link { func NewJSONAPIResponse(resource interface{}) ([]byte, error) { document, err := jsonapi.MarshalToStruct(resource, nil) if err != nil { - return nil, fmt.Errorf("failed to marshal resource to struct: %+v", err) + return nil, fmt.Errorf("failed to marshal resource to struct: %+w", err) } return json.Marshal(document) @@ -88,7 +88,7 @@ func NewPaginatedResponse(url url.URL, size, page, count int, resource interface func getPaginatedResponseDoc(url url.URL, size, page, count int, resource interface{}) (*jsonapi.Document, error) { document, err := jsonapi.MarshalToStruct(resource, nil) if err != nil { - return nil, fmt.Errorf("failed to marshal resource to struct: %+v", err) + return nil, fmt.Errorf("failed to marshal resource to struct: %+w", err) } document.Meta = make(jsonapi.Meta) @@ -126,7 +126,7 @@ func parsePaginatedResponseToDocument(input []byte, resource interface{}, docume // Unmarshal using the stdlib Unmarshal to extract the links part of the document err = json.Unmarshal(input, &document) if err != nil { - return fmt.Errorf("unable to unmarshal links: %+v", err) + return fmt.Errorf("unable to unmarshal links: %+w", err) } return nil } @@ -137,7 +137,7 @@ func ParseJSONAPIResponse(input []byte, resource interface{}) error { // as is api2go will discard the links err := jsonapi.Unmarshal(input, resource) if err != nil { - return fmt.Errorf("web: unable to unmarshal data of type %T, %+v", resource, err) + return fmt.Errorf("web: unable to unmarshal data of type %T, %+w", resource, err) } return nil diff --git a/core/web/api_test.go b/core/web/api_test.go index 1e414ccda56..d0346ec6ce5 100644 --- a/core/web/api_test.go +++ b/core/web/api_test.go @@ -154,10 +154,10 @@ func TestNewJSONAPIResponse(t *testing.T) { buffer, err := NewJSONAPIResponse(12981) assert.Error(t, err) - assert.Len(t, buffer, 0) + assert.Empty(t, buffer) r := DummyResource{ID: "782"} buffer, err = NewJSONAPIResponse(&r) assert.NoError(t, err) - assert.Equal(t, `{"data":{"type":"dummyResources","id":"782","attributes":{"ID":"782"}}}`, string(buffer)) + assert.JSONEq(t, `{"data":{"type":"dummyResources","id":"782","attributes":{"ID":"782"}}}`, string(buffer)) } diff --git a/core/web/aptos_keys_controller_test.go b/core/web/aptos_keys_controller_test.go index c5de75a5105..30ea49d9ded 100644 --- a/core/web/aptos_keys_controller_test.go +++ b/core/web/aptos_keys_controller_test.go @@ -1,7 +1,6 @@ package web_test import ( - "fmt" "net/http" "testing" @@ -83,13 +82,13 @@ func TestAptosKeysController_Delete_HappyPath(t *testing.T) { initialLength := len(keys) key, _ := keyStore.Aptos().Create(ctx) - response, cleanup := client.Delete(fmt.Sprintf("/v2/keys/aptos/%s", key.ID())) + response, cleanup := client.Delete("/v2/keys/aptos/" + key.ID()) t.Cleanup(cleanup) assert.Equal(t, http.StatusOK, response.StatusCode) assert.Error(t, utils.JustError(keyStore.Aptos().Get(key.ID()))) keys, _ = keyStore.Aptos().GetAll() - assert.Equal(t, initialLength, len(keys)) + assert.Len(t, keys, initialLength) } func setupAptosKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.Master) { diff --git a/core/web/bridge_types_controller.go b/core/web/bridge_types_controller.go index c787ca2fb54..b77176242b3 100644 --- a/core/web/bridge_types_controller.go +++ b/core/web/bridge_types_controller.go @@ -210,12 +210,12 @@ func (btc *BridgeTypesController) Destroy(c *gin.Context) { return } if err != nil { - jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("error searching for bridge: %+v", err)) + jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("error searching for bridge: %+w", err)) return } jobsUsingBridge, err := btc.App.JobORM().FindJobIDsWithBridge(ctx, name) if err != nil { - jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("error searching for associated v2 jobs: %+v", err)) + jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("error searching for associated v2 jobs: %+w", err)) return } if len(jobsUsingBridge) > 0 { @@ -223,7 +223,7 @@ func (btc *BridgeTypesController) Destroy(c *gin.Context) { return } if err = orm.DeleteBridgeType(ctx, &bt); err != nil { - jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("failed to delete bridge: %+v", err)) + jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("failed to delete bridge: %+w", err)) return } diff --git a/core/web/config_controller.go b/core/web/config_controller.go index 20b5819e1c0..d9f44d6d57d 100644 --- a/core/web/config_controller.go +++ b/core/web/config_controller.go @@ -27,7 +27,7 @@ func (cc *ConfigController) Show(c *gin.Context) { var err error userOnly, err = strconv.ParseBool(s) if err != nil { - jsonAPIError(c, http.StatusBadRequest, fmt.Errorf("invalid bool for userOnly: %v", err)) + jsonAPIError(c, http.StatusBadRequest, fmt.Errorf("invalid bool for userOnly: %w", err)) return } } diff --git a/core/web/cosmos_keys_controller_test.go b/core/web/cosmos_keys_controller_test.go index 1de64625dfa..c5377c3d3a9 100644 --- a/core/web/cosmos_keys_controller_test.go +++ b/core/web/cosmos_keys_controller_test.go @@ -1,7 +1,6 @@ package web_test import ( - "fmt" "net/http" "testing" @@ -84,13 +83,13 @@ func TestCosmosKeysController_Delete_HappyPath(t *testing.T) { initialLength := len(keys) key, _ := keyStore.Cosmos().Create(ctx) - response, cleanup := client.Delete(fmt.Sprintf("/v2/keys/cosmos/%s", key.ID())) + response, cleanup := client.Delete("/v2/keys/cosmos/" + key.ID()) t.Cleanup(cleanup) assert.Equal(t, http.StatusOK, response.StatusCode) assert.Error(t, utils.JustError(keyStore.Cosmos().Get(key.ID()))) keys, _ = keyStore.Cosmos().GetAll() - assert.Equal(t, initialLength, len(keys)) + assert.Len(t, keys, initialLength) } func setupCosmosKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.Master) { diff --git a/core/web/eth_keys_controller_test.go b/core/web/eth_keys_controller_test.go index 78982e2e304..ca40f9325db 100644 --- a/core/web/eth_keys_controller_test.go +++ b/core/web/eth_keys_controller_test.go @@ -208,7 +208,7 @@ func TestETHKeysController_Index_NoAccounts(t *testing.T) { assert.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Len(t, balances, 0) + assert.Empty(t, balances) } func TestETHKeysController_CreateSuccess(t *testing.T) { @@ -293,7 +293,7 @@ func TestETHKeysController_ChainSuccess_UpdateNonce(t *testing.T) { assert.Equal(t, cltest.FormatWithPrefixedChainID(cltest.FixtureChainID.String(), key.Address.String()), updatedKey.ID) assert.Equal(t, key.Address.String(), updatedKey.Address) assert.Equal(t, cltest.FixtureChainID.String(), updatedKey.EVMChainID.String()) - assert.Equal(t, false, updatedKey.Disabled) + assert.False(t, updatedKey.Disabled) } func TestETHKeysController_ChainSuccess_Disable(t *testing.T) { @@ -339,7 +339,7 @@ func TestETHKeysController_ChainSuccess_Disable(t *testing.T) { assert.Equal(t, cltest.FormatWithPrefixedChainID(updatedKey.EVMChainID.String(), key.Address.String()), updatedKey.ID) assert.Equal(t, key.Address.String(), updatedKey.Address) assert.Equal(t, cltest.FixtureChainID.String(), updatedKey.EVMChainID.String()) - assert.Equal(t, true, updatedKey.Disabled) + assert.True(t, updatedKey.Disabled) } func TestETHKeysController_ChainSuccess_Enable(t *testing.T) { @@ -384,7 +384,7 @@ func TestETHKeysController_ChainSuccess_Enable(t *testing.T) { assert.Equal(t, cltest.FormatWithPrefixedChainID(cltest.FixtureChainID.String(), key.Address.String()), updatedKey.ID) assert.Equal(t, key.Address.String(), updatedKey.Address) assert.Equal(t, cltest.FixtureChainID.String(), updatedKey.EVMChainID.String()) - assert.Equal(t, false, updatedKey.Disabled) + assert.False(t, updatedKey.Disabled) } func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { @@ -428,7 +428,7 @@ func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { txes, err := txStore.FindTxesByFromAddressAndState(testutils.Context(t), addr, "fatal_error") require.NoError(t, err) - require.Len(t, txes, 0) + require.Empty(t, txes) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -450,7 +450,7 @@ func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { assert.Equal(t, cltest.FormatWithPrefixedChainID(cltest.FixtureChainID.String(), key.Address.String()), updatedKey.ID) assert.Equal(t, key.Address.String(), updatedKey.Address) assert.Equal(t, cltest.FixtureChainID.String(), updatedKey.EVMChainID.String()) - assert.Equal(t, false, updatedKey.Disabled) + assert.False(t, updatedKey.Disabled) txes, err = txStore.FindTxesByFromAddressAndState(testutils.Context(t), addr, "fatal_error") require.NoError(t, err) @@ -685,7 +685,7 @@ func TestETHKeysController_DeleteSuccess(t *testing.T) { assert.Equal(t, cltest.FormatWithPrefixedChainID(cltest.FixtureChainID.String(), key0.Address.String()), deletedKey.ID) assert.Equal(t, key0.Address.String(), deletedKey.Address) assert.Equal(t, cltest.FixtureChainID.String(), deletedKey.EVMChainID.String()) - assert.Equal(t, false, deletedKey.Disabled) + assert.False(t, deletedKey.Disabled) resp, cleanup2 := client.Get("/v2/keys/evm") defer cleanup2() diff --git a/core/web/evm_transactions_controller_test.go b/core/web/evm_transactions_controller_test.go index 89b99eda1dd..e0c30598f49 100644 --- a/core/web/evm_transactions_controller_test.go +++ b/core/web/evm_transactions_controller_test.go @@ -45,7 +45,7 @@ func TestTransactionsController_Index_Success(t *testing.T) { _, count, err := txStore.TransactionsWithAttempts(ctx, 0, 100) require.NoError(t, err) - require.Equal(t, count, 3) + require.Equal(t, 3, count) size := 2 resp, cleanup := client.Get(fmt.Sprintf("/v2/transactions?size=%d", size)) diff --git a/core/web/evm_transfer_controller_test.go b/core/web/evm_transfer_controller_test.go index 55a55399405..7b6441bf049 100644 --- a/core/web/evm_transfer_controller_test.go +++ b/core/web/evm_transfer_controller_test.go @@ -4,12 +4,13 @@ import ( "bytes" "context" "encoding/json" - "fmt" "math/big" "net/http" "testing" "time" + "github.com/pkg/errors" + commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" @@ -69,7 +70,7 @@ func TestTransfersController_CreateSuccess_From(t *testing.T) { errors := cltest.ParseJSONAPIErrors(t, resp.Body) assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Len(t, errors.Errors, 0) + assert.Empty(t, errors.Errors) validateTxCount(t, app.GetDB(), 1) } @@ -111,7 +112,7 @@ func TestTransfersController_CreateSuccess_From_WEI(t *testing.T) { errors := cltest.ParseJSONAPIErrors(t, resp.Body) assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Len(t, errors.Errors, 0) + assert.Empty(t, errors.Errors) validateTxCount(t, app.GetDB(), 1) } @@ -158,7 +159,7 @@ func TestTransfersController_CreateSuccess_From_BalanceMonitorDisabled(t *testin errors := cltest.ParseJSONAPIErrors(t, resp.Body) assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Len(t, errors.Errors, 0) + assert.Empty(t, errors.Errors) validateTxCount(t, app.GetDB(), 1) } @@ -367,7 +368,7 @@ func TestTransfersController_FindTxAttempt(t *testing.T) { t.Run("failed to find tx", func(t *testing.T) { ctx := testutils.Context(t) find := func(_ context.Context, _ int64) (txmgr.Tx, error) { - return txmgr.Tx{}, fmt.Errorf("ERRORED") + return txmgr.Tx{}, errors.New("ERRORED") } _, err := web.FindTxAttempt(ctx, time.Second, tx, find) assert.ErrorContains(t, err, "failed to find transaction") diff --git a/core/web/external_initiators_controller_test.go b/core/web/external_initiators_controller_test.go index a79909c5864..b41a25b3658 100644 --- a/core/web/external_initiators_controller_test.go +++ b/core/web/external_initiators_controller_test.go @@ -3,8 +3,8 @@ package web_test import ( "bytes" "encoding/json" - "fmt" "net/http" + "strconv" "testing" "github.com/smartcontractkit/chainlink/v2/core/bridges" @@ -106,7 +106,7 @@ func TestExternalInitiatorsController_Index(t *testing.T) { assert.Empty(t, links["prev"].Href) assert.Len(t, eis, 1) - assert.Equal(t, fmt.Sprintf("%d", eiBar.ID), eis[0].ID) + assert.Equal(t, strconv.FormatInt(eiBar.ID, 10), eis[0].ID) assert.Equal(t, eiBar.Name, eis[0].Name) assert.Nil(t, eis[0].URL) assert.Equal(t, eiBar.AccessKey, eis[0].AccessKey) @@ -123,7 +123,7 @@ func TestExternalInitiatorsController_Index(t *testing.T) { assert.NotEmpty(t, links["prev"]) assert.Len(t, eis, 1) - assert.Equal(t, fmt.Sprintf("%d", eiFoo.ID), eis[0].ID) + assert.Equal(t, strconv.FormatInt(eiFoo.ID, 10), eis[0].ID) assert.Equal(t, eiFoo.Name, eis[0].Name) assert.Equal(t, eiFoo.URL.String(), eis[0].URL.String()) assert.Equal(t, eiFoo.AccessKey, eis[0].AccessKey) diff --git a/core/web/helpers.go b/core/web/helpers.go index e8900522eb9..6f723106f16 100644 --- a/core/web/helpers.go +++ b/core/web/helpers.go @@ -42,9 +42,9 @@ func paginatedResponse( } if err != nil { - jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("error getting paged %s: %+v", name, err)) + jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("error getting paged %s: %+w", name, err)) } else if buffer, err := NewPaginatedResponse(*c.Request.URL, size, page, count, resource); err != nil { - jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("failed to marshal document: %+v", err)) + jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("failed to marshal document: %+w", err)) } else { c.Data(http.StatusOK, MediaType, buffer) } @@ -64,7 +64,7 @@ func paginatedRequest(action func(*gin.Context, int, int, int)) func(*gin.Contex func jsonAPIResponseWithStatus(c *gin.Context, resource interface{}, name string, status int) { json, err := jsonapi.Marshal(resource) if err != nil { - jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("failed to marshal %s using jsonapi: %+v", name, err)) + jsonAPIError(c, http.StatusInternalServerError, fmt.Errorf("failed to marshal %s using jsonapi: %+w", name, err)) } else { c.Data(status, MediaType, json) } diff --git a/core/web/jobs_controller_test.go b/core/web/jobs_controller_test.go index f0c8f4b76e7..a77ec507f90 100644 --- a/core/web/jobs_controller_test.go +++ b/core/web/jobs_controller_test.go @@ -360,7 +360,7 @@ func TestJobController_Create_HappyPath(t *testing.T) { assert.NotNil(t, jb.PipelineSpec.DotDagSource) assert.Equal(t, types.EIP55Address("0x3cCad4715152693fE3BC4460591e3D3Fbd071b42"), jb.FluxMonitorSpec.ContractAddress) assert.Equal(t, time.Second, jb.FluxMonitorSpec.IdleTimerPeriod) - assert.Equal(t, false, jb.FluxMonitorSpec.IdleTimerDisabled) + assert.False(t, jb.FluxMonitorSpec.IdleTimerDisabled) assert.Equal(t, tomlutils.Float32(0.5), jb.FluxMonitorSpec.Threshold) assert.Equal(t, tomlutils.Float32(0), jb.FluxMonitorSpec.AbsoluteThreshold) }, @@ -570,7 +570,7 @@ func TestJobsController_Index_HappyPath(t *testing.T) { func TestJobsController_Show_HappyPath(t *testing.T) { _, client, ocrJobSpecFromFile, jobID, ereJobSpecFromFile, jobID2 := setupJobSpecsControllerTestsWithJobs(t) - response, cleanup := client.Get("/v2/jobs/" + fmt.Sprintf("%v", jobID)) + response, cleanup := client.Get("/v2/jobs/" + strconv.Itoa(int(jobID))) t.Cleanup(cleanup) cltest.AssertServerResponse(t, response, http.StatusOK) @@ -590,7 +590,7 @@ func TestJobsController_Show_HappyPath(t *testing.T) { runOCRJobSpecAssertions(t, ocrJobSpecFromFile, ocrJob) - response, cleanup = client.Get("/v2/jobs/" + fmt.Sprintf("%v", jobID2)) + response, cleanup = client.Get("/v2/jobs/" + strconv.Itoa(int(jobID2))) t.Cleanup(cleanup) cltest.AssertServerResponse(t, response, http.StatusOK) @@ -682,7 +682,7 @@ func TestJobsController_Update_HappyPath(t *testing.T) { body, _ := json.Marshal(web.UpdateJobRequest{ TOML: updatedSpec.Toml(), }) - response, cleanup := client.Put("/v2/jobs/"+fmt.Sprintf("%v", jb.ID), bytes.NewReader(body)) + response, cleanup := client.Put("/v2/jobs/"+strconv.Itoa(int(jb.ID)), bytes.NewReader(body)) t.Cleanup(cleanup) dbJb, err = app.JobORM().FindJob(ctx, jb.ID) diff --git a/core/web/keys_controller.go b/core/web/keys_controller.go index ca7ef5e134a..7b9360c893a 100644 --- a/core/web/keys_controller.go +++ b/core/web/keys_controller.go @@ -51,7 +51,7 @@ func NewKeysController[K keystore.Key, R jsonapi.EntityNamer](ks Keystore[K], lg var k K typ, err := keystore.GetFieldNameForKey(k) if err != nil { - panic(fmt.Errorf("unable to create keys controller: %v", err)) + panic(fmt.Errorf("unable to create keys controller: %w", err)) } return &keysController[K, R]{ ks: ks, diff --git a/core/web/lca_controller.go b/core/web/lca_controller.go index 0c3a065f2fd..3e310ae5a9b 100644 --- a/core/web/lca_controller.go +++ b/core/web/lca_controller.go @@ -2,7 +2,6 @@ package web import ( "errors" - "fmt" "net/http" "github.com/gin-gonic/gin" @@ -38,7 +37,7 @@ func (bdc *LCAController) FindLCA(c *gin.Context) { } if lca == nil { - jsonAPIError(c, http.StatusNotFound, fmt.Errorf("failed to find last common ancestor")) + jsonAPIError(c, http.StatusNotFound, errors.New("failed to find last common ancestor")) return } diff --git a/core/web/log_controller.go b/core/web/log_controller.go index 66bbe0d74c9..144220977fa 100644 --- a/core/web/log_controller.go +++ b/core/web/log_controller.go @@ -1,11 +1,11 @@ package web import ( - "fmt" "net/http" "strconv" "github.com/gin-gonic/gin" + "github.com/pkg/errors" "go.uber.org/zap/zapcore" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" @@ -57,7 +57,7 @@ func (cc *LogController) Patch(c *gin.Context) { // Validate request params if request.Level == "" && request.SqlEnabled == nil { - jsonAPIError(c, http.StatusBadRequest, fmt.Errorf("please check request params, no params configured")) + jsonAPIError(c, http.StatusBadRequest, errors.New("please check request params, no params configured")) return } diff --git a/core/web/loop_registry.go b/core/web/loop_registry.go index ffa80146449..58601972192 100644 --- a/core/web/loop_registry.go +++ b/core/web/loop_registry.go @@ -97,7 +97,7 @@ func (l *LoopRegistryServer) pluginMetricHandler(gc *gin.Context) { pluginURL := fmt.Sprintf("http://%s:%d/metrics", l.loopHostName, p.EnvCfg.PrometheusPort) res, err := l.client.Get(pluginURL) //nolint if err != nil { - msg := fmt.Sprintf("plugin metric handler failed to get plugin url %s", html.EscapeString(pluginURL)) + msg := "plugin metric handler failed to get plugin url " + html.EscapeString(pluginURL) l.logger.Errorw(msg, "err", err) gc.Data(http.StatusInternalServerError, "text/plain", []byte(fmt.Sprintf("%s: %s", msg, err))) return diff --git a/core/web/loop_registry_internal_test.go b/core/web/loop_registry_internal_test.go index d1235cd09b4..9b98c46a460 100644 --- a/core/web/loop_registry_internal_test.go +++ b/core/web/loop_registry_internal_test.go @@ -45,7 +45,7 @@ func TestLoopRegistryServer_CantWriteToResponse(t *testing.T) { rw := newResponseWriter() s.discoveryHandler(rw, &http.Request{}) - assert.Equal(t, rw.statusCode, http.StatusInternalServerError) + assert.Equal(t, http.StatusInternalServerError, rw.statusCode) assert.Equal(t, 1, o.FilterMessageSnippet("could not write to response").Len()) } @@ -62,6 +62,6 @@ func TestLoopRegistryServer_CantMarshal(t *testing.T) { rw := newResponseWriter() s.discoveryHandler(rw, &http.Request{}) - assert.Equal(t, rw.statusCode, http.StatusInternalServerError) + assert.Equal(t, http.StatusInternalServerError, rw.statusCode) assert.Equal(t, 1, o.FilterMessageSnippet("could not write to response").Len()) } diff --git a/core/web/ocr2_keys_controller_test.go b/core/web/ocr2_keys_controller_test.go index a8f480a1520..e3f0adfc196 100644 --- a/core/web/ocr2_keys_controller_test.go +++ b/core/web/ocr2_keys_controller_test.go @@ -94,7 +94,7 @@ func TestOCR2KeysController_Delete_HappyPath(t *testing.T) { assert.Error(t, utils.JustError(OCRKeyStore.Get(key.ID()))) keys, _ = OCRKeyStore.GetAll() - assert.Equal(t, initialLength, len(keys)) + assert.Len(t, keys, initialLength) } func setupOCR2KeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.OCR2) { diff --git a/core/web/ocr_keys_controller_test.go b/core/web/ocr_keys_controller_test.go index 82a0b9ebc2d..a5a5fd62ab4 100644 --- a/core/web/ocr_keys_controller_test.go +++ b/core/web/ocr_keys_controller_test.go @@ -82,7 +82,7 @@ func TestOCRKeysController_Delete_HappyPath(t *testing.T) { assert.Error(t, utils.JustError(OCRKeyStore.Get(key.ID()))) keys, _ = OCRKeyStore.GetAll() - assert.Equal(t, initialLength, len(keys)) + assert.Len(t, keys, initialLength) } func setupOCRKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.OCR) { diff --git a/core/web/p2p_keys_controller_test.go b/core/web/p2p_keys_controller_test.go index 63cea5f0ea7..af1ff49b957 100644 --- a/core/web/p2p_keys_controller_test.go +++ b/core/web/p2p_keys_controller_test.go @@ -1,7 +1,6 @@ package web_test import ( - "fmt" "net/http" "testing" @@ -99,13 +98,13 @@ func TestP2PKeysController_Delete_HappyPath(t *testing.T) { initialLength := len(keys) key, _ := keyStore.P2P().Create(ctx) - response, cleanup := client.Delete(fmt.Sprintf("/v2/keys/p2p/%s", key.ID())) + response, cleanup := client.Delete("/v2/keys/p2p/" + key.ID()) t.Cleanup(cleanup) assert.Equal(t, http.StatusOK, response.StatusCode) assert.Error(t, utils.JustError(keyStore.P2P().Get(key.PeerID()))) keys, _ = keyStore.P2P().GetAll() - assert.Equal(t, initialLength, len(keys)) + assert.Len(t, keys, initialLength) } func setupP2PKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.Master) { diff --git a/core/web/ping_controller_test.go b/core/web/ping_controller_test.go index b106161aed8..d5b278503bb 100644 --- a/core/web/ping_controller_test.go +++ b/core/web/ping_controller_test.go @@ -2,7 +2,6 @@ package web_test import ( "net/http" - "strings" "testing" "github.com/google/uuid" @@ -30,7 +29,7 @@ func TestPingController_Show_APICredentials(t *testing.T) { defer cleanup() cltest.AssertServerResponse(t, resp, http.StatusOK) body := string(cltest.ParseResponseBody(t, resp)) - require.Equal(t, `{"message":"pong"}`, strings.TrimSpace(body)) + require.JSONEq(t, `{"message":"pong"}`, body) } func TestPingController_Show_ExternalInitiatorCredentials(t *testing.T) { @@ -69,7 +68,7 @@ func TestPingController_Show_ExternalInitiatorCredentials(t *testing.T) { cltest.AssertServerResponse(t, resp, http.StatusOK) body := string(cltest.ParseResponseBody(t, resp)) - require.Equal(t, `{"message":"pong"}`, strings.TrimSpace(body)) + require.JSONEq(t, `{"message":"pong"}`, body) } func TestPingController_Show_NoCredentials(t *testing.T) { diff --git a/core/web/pipeline_runs_controller_test.go b/core/web/pipeline_runs_controller_test.go index 738d17de600..c1fe424b7f3 100644 --- a/core/web/pipeline_runs_controller_test.go +++ b/core/web/pipeline_runs_controller_test.go @@ -48,7 +48,7 @@ func TestPipelineRunsController_CreateWithBody_HappyPath(t *testing.T) { defer r.Body.Close() bs, err := io.ReadAll(r.Body) require.NoError(t, err) - require.Equal(t, `{"result":"12345"}`, string(bs)) + require.JSONEq(t, `{"result":"12345"}`, string(bs)) }) _, bridge := cltest.MustCreateBridge(t, app.GetDB(), cltest.BridgeOpts{URL: mockServer.URL}) @@ -108,7 +108,7 @@ func TestPipelineRunsController_CreateNoBody_HappyPath(t *testing.T) { defer r.Body.Close() bs, err := io.ReadAll(r.Body) require.NoError(t, err) - require.Equal(t, `{"result":"12345"}`, string(bs)) + require.JSONEq(t, `{"result":"12345"}`, string(bs)) }) _, submitBridge := cltest.MustCreateBridge(t, app.GetDB(), cltest.BridgeOpts{URL: mockServer.URL}) @@ -178,7 +178,7 @@ func TestPipelineRunsController_Index_GlobalHappyPath(t *testing.T) { func TestPipelineRunsController_Index_HappyPath(t *testing.T) { client, jobID, runIDs := setupPipelineRunsControllerTests(t) - response, cleanup := client.Get("/v2/jobs/" + fmt.Sprintf("%v", jobID) + "/runs") + response, cleanup := client.Get("/v2/jobs/" + strconv.Itoa(int(jobID)) + "/runs") defer cleanup() cltest.AssertServerResponse(t, response, http.StatusOK) @@ -201,7 +201,7 @@ func TestPipelineRunsController_Index_HappyPath(t *testing.T) { func TestPipelineRunsController_Index_Pagination(t *testing.T) { client, jobID, runIDs := setupPipelineRunsControllerTests(t) - response, cleanup := client.Get("/v2/jobs/" + fmt.Sprintf("%v", jobID) + "/runs?page=1&size=1") + response, cleanup := client.Get("/v2/jobs/" + strconv.Itoa(int(jobID)) + "/runs?page=1&size=1") defer cleanup() cltest.AssertServerResponse(t, response, http.StatusOK) @@ -223,7 +223,7 @@ func TestPipelineRunsController_Index_Pagination(t *testing.T) { func TestPipelineRunsController_Show_HappyPath(t *testing.T) { client, jobID, runIDs := setupPipelineRunsControllerTests(t) - response, cleanup := client.Get("/v2/jobs/" + fmt.Sprintf("%v", jobID) + "/runs/" + fmt.Sprintf("%v", runIDs[0])) + response, cleanup := client.Get("/v2/jobs/" + strconv.Itoa(int(jobID)) + "/runs/" + strconv.FormatInt(runIDs[0], 10)) defer cleanup() cltest.AssertServerResponse(t, response, http.StatusOK) diff --git a/core/web/presenters/csa_key.go b/core/web/presenters/csa_key.go index cdf5294d530..58cdb5a212a 100644 --- a/core/web/presenters/csa_key.go +++ b/core/web/presenters/csa_key.go @@ -1,8 +1,6 @@ package presenters import ( - "fmt" - "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/csakey" ) @@ -21,7 +19,7 @@ func (CSAKeyResource) GetName() string { func NewCSAKeyResource(key csakey.KeyV2) *CSAKeyResource { r := &CSAKeyResource{ JAID: NewJAID(key.ID()), - PubKey: fmt.Sprintf("csa_%s", key.PublicKeyString()), + PubKey: "csa_" + key.PublicKeyString(), Version: 1, } diff --git a/core/web/presenters/evm_forwarder_test.go b/core/web/presenters/evm_forwarder_test.go index 80eb6b190ef..b1efbbfe2ac 100644 --- a/core/web/presenters/evm_forwarder_test.go +++ b/core/web/presenters/evm_forwarder_test.go @@ -2,6 +2,7 @@ package presenters import ( "fmt" + "strconv" "strings" "testing" "time" @@ -32,7 +33,7 @@ func TestEVMForwarderResource(t *testing.T) { } r := NewEVMForwarderResource(fwd) - assert.Equal(t, fmt.Sprint(ID), r.ID) + assert.Equal(t, strconv.FormatInt(ID, 10), r.ID) assert.Equal(t, address, r.Address) assert.Equal(t, chainID, r.EVMChainID) assert.Equal(t, createdAt, r.CreatedAt) diff --git a/core/web/presenters/external_initiators.go b/core/web/presenters/external_initiators.go index 424b1512110..f6980491bac 100644 --- a/core/web/presenters/external_initiators.go +++ b/core/web/presenters/external_initiators.go @@ -1,7 +1,7 @@ package presenters import ( - "fmt" + "strconv" "time" "github.com/smartcontractkit/chainlink/v2/core/auth" @@ -66,7 +66,7 @@ type ExternalInitiatorResource struct { func NewExternalInitiatorResource(ei bridges.ExternalInitiator) ExternalInitiatorResource { return ExternalInitiatorResource{ - JAID: NewJAID(fmt.Sprintf("%d", ei.ID)), + JAID: NewJAID(strconv.FormatInt(ei.ID, 10)), Name: ei.Name, URL: ei.URL, AccessKey: ei.AccessKey, diff --git a/core/web/presenters/node_test.go b/core/web/presenters/node_test.go index d2db83009d9..601eaa797b9 100644 --- a/core/web/presenters/node_test.go +++ b/core/web/presenters/node_test.go @@ -17,8 +17,8 @@ func TestNodeResource(t *testing.T) { cfg := "cfg" testCases := []string{"solana", "cosmos", "starknet"} for _, tc := range testCases { - chainID := fmt.Sprintf("%s chain ID", tc) - nodeName := fmt.Sprintf("%s_node", tc) + chainID := tc + " chain ID" + nodeName := tc + "_node" nodeResource = NewNodeResource(types.NodeStatus{ ChainID: chainID, diff --git a/core/web/resolver/csa_keys.go b/core/web/resolver/csa_keys.go index 267592b4280..be4eb4ebb4c 100644 --- a/core/web/resolver/csa_keys.go +++ b/core/web/resolver/csa_keys.go @@ -1,8 +1,6 @@ package resolver import ( - "fmt" - "github.com/graph-gophers/graphql-go" "github.com/pkg/errors" @@ -26,7 +24,7 @@ func (r *CSAKeyResolver) ID() graphql.ID { // PubKey resolves the CSA Key public key string. func (r *CSAKeyResolver) PublicKey() string { - return fmt.Sprintf("csa_%s", r.key.PublicKeyString()) + return "csa_" + r.key.PublicKeyString() } // Version resolves the CSA Key version number. diff --git a/core/web/resolver/csa_keys_test.go b/core/web/resolver/csa_keys_test.go index 94513b53e45..4d5c72b8940 100644 --- a/core/web/resolver/csa_keys_test.go +++ b/core/web/resolver/csa_keys_test.go @@ -42,7 +42,7 @@ func Test_CSAKeysQuery(t *testing.T) { expectedKeys = append(expectedKeys, expectedKey{ ID: k.ID(), Version: k.Version, - PubKey: fmt.Sprintf("csa_%s", k.PublicKeyString()), + PubKey: "csa_" + k.PublicKeyString(), }) } diff --git a/core/web/resolver/eth_key_test.go b/core/web/resolver/eth_key_test.go index 9002f17fce6..2f28a96b9f1 100644 --- a/core/web/resolver/eth_key_test.go +++ b/core/web/resolver/eth_key_test.go @@ -71,8 +71,8 @@ func TestResolver_ETHKeys(t *testing.T) { }, } gError := errors.New("error") - keysError := fmt.Errorf("error getting unlocked keys: %v", gError) - statesError := fmt.Errorf("error getting key states: %v", gError) + keysError := fmt.Errorf("error getting unlocked keys: %w", gError) + statesError := fmt.Errorf("error getting key states: %w", gError) evmMockConfig := mockEvmConfig{linkAddr: "0x5431F5F973781809D18643b87B44921b11355d81", gasEstimatorMock: mocks2.NewGasEstimator(t)} evmMockConfig.gasEstimatorMock.On("PriceMaxKey", mock.Anything).Return(assets.NewWeiI(1)) diff --git a/core/web/resolver/mutation.go b/core/web/resolver/mutation.go index 92d30ca65af..991f7b77a94 100644 --- a/core/web/resolver/mutation.go +++ b/core/web/resolver/mutation.go @@ -678,7 +678,7 @@ func (r *Resolver) DeleteBridge(ctx context.Context, args struct { return nil, err } if len(jobsUsingBridge) > 0 { - return NewDeleteBridgePayload(nil, fmt.Errorf("bridge has jobs associated with it")), nil + return NewDeleteBridgePayload(nil, errors.New("bridge has jobs associated with it")), nil } if err = orm.DeleteBridgeType(ctx, &bt); err != nil { diff --git a/core/web/resolver/query.go b/core/web/resolver/query.go index ae33e5688bb..f659274907a 100644 --- a/core/web/resolver/query.go +++ b/core/web/resolver/query.go @@ -454,12 +454,12 @@ func (r *Resolver) ETHKeys(ctx context.Context) (*ETHKeysPayloadResolver, error) keys, err := ks.GetAll(ctx) if err != nil { - return nil, fmt.Errorf("error getting unlocked keys: %v", err) + return nil, fmt.Errorf("error getting unlocked keys: %w", err) } states, err := ks.GetStatesForKeys(ctx, keys) if err != nil { - return nil, fmt.Errorf("error getting key states: %v", err) + return nil, fmt.Errorf("error getting key states: %w", err) } var ethKeys []ETHKey diff --git a/core/web/router.go b/core/web/router.go index c57bf3c8095..d73bc5b7004 100644 --- a/core/web/router.go +++ b/core/web/router.go @@ -662,7 +662,7 @@ func prometheusHandler(token string, h http.Handler) gin.HandlerFunc { return } - bearer := fmt.Sprintf("Bearer %s", token) + bearer := "Bearer " + token if header != bearer { c.String(http.StatusUnauthorized, ginprom.ErrInvalidToken.Error()) diff --git a/core/web/schema/schema.go b/core/web/schema/schema.go index 74c2ae0fffe..4a13824cc02 100644 --- a/core/web/schema/schema.go +++ b/core/web/schema/schema.go @@ -5,7 +5,6 @@ package schema import ( "bytes" "embed" - "fmt" ) //go:embed *.graphql type/*.graphql @@ -27,7 +26,7 @@ func GetRootSchema() (string, error) { } for _, t := range types { - b, err = fs.ReadFile(fmt.Sprintf("type/%s", t.Name())) + b, err = fs.ReadFile("type/" + t.Name()) if err != nil { return "", err } diff --git a/core/web/sessions_controller.go b/core/web/sessions_controller.go index 87f59d4a213..1f3276b1b4b 100644 --- a/core/web/sessions_controller.go +++ b/core/web/sessions_controller.go @@ -35,7 +35,7 @@ func (sc *SessionsController) Create(c *gin.Context) { session := sessions.Default(c) var sr clsessions.SessionRequest if err := c.ShouldBindJSON(&sr); err != nil { - jsonAPIError(c, http.StatusBadRequest, fmt.Errorf("error binding json %v", err)) + jsonAPIError(c, http.StatusBadRequest, fmt.Errorf("error binding json %w", err)) return } diff --git a/core/web/sessions_controller_test.go b/core/web/sessions_controller_test.go index 049be4e2b69..b43f2c6803b 100644 --- a/core/web/sessions_controller_test.go +++ b/core/web/sessions_controller_test.go @@ -69,7 +69,7 @@ func TestSessionsController_Create(t *testing.T) { assert.NoError(t, err) assert.Contains(t, string(b), `"attributes":{"authenticated":true}`) } else { - require.True(t, resp.StatusCode >= 400, "Should not be able to create session") + require.GreaterOrEqual(t, resp.StatusCode, 400, "Should not be able to create session") // Ignore fixture session sessions, err := app.AuthenticationProvider().Sessions(ctx, 1, 2) assert.NoError(t, err) @@ -162,7 +162,7 @@ func TestSessionsController_Destroy(t *testing.T) { if test.success { assert.Equal(t, http.StatusOK, resp.StatusCode) } else { - assert.True(t, resp.StatusCode >= 400, "Should get an erroneous status code for deleting a nonexistent session id") + assert.GreaterOrEqual(t, resp.StatusCode, 400, "Should get an erroneous status code for deleting a nonexistent session id") } }) } diff --git a/core/web/solana_keys_controller_test.go b/core/web/solana_keys_controller_test.go index b71f8287d0f..5654b26456b 100644 --- a/core/web/solana_keys_controller_test.go +++ b/core/web/solana_keys_controller_test.go @@ -1,7 +1,6 @@ package web_test import ( - "fmt" "net/http" "testing" @@ -83,13 +82,13 @@ func TestSolanaKeysController_Delete_HappyPath(t *testing.T) { initialLength := len(keys) key, _ := keyStore.Solana().Create(ctx) - response, cleanup := client.Delete(fmt.Sprintf("/v2/keys/solana/%s", key.ID())) + response, cleanup := client.Delete("/v2/keys/solana/" + key.ID()) t.Cleanup(cleanup) assert.Equal(t, http.StatusOK, response.StatusCode) assert.Error(t, utils.JustError(keyStore.Solana().Get(key.ID()))) keys, _ = keyStore.Solana().GetAll() - assert.Equal(t, initialLength, len(keys)) + assert.Len(t, keys, initialLength) } func setupSolanaKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.Master) { diff --git a/core/web/starknet_keys_controller_test.go b/core/web/starknet_keys_controller_test.go index 05f611f2f22..cca1cfbd67a 100644 --- a/core/web/starknet_keys_controller_test.go +++ b/core/web/starknet_keys_controller_test.go @@ -1,7 +1,6 @@ package web_test import ( - "fmt" "net/http" "testing" @@ -83,13 +82,13 @@ func TestStarkNetKeysController_Delete_HappyPath(t *testing.T) { initialLength := len(keys) key, _ := keyStore.StarkNet().Create(ctx) - response, cleanup := client.Delete(fmt.Sprintf("/v2/keys/starknet/%s", key.ID())) + response, cleanup := client.Delete("/v2/keys/starknet/" + key.ID()) t.Cleanup(cleanup) assert.Equal(t, http.StatusOK, response.StatusCode) assert.Error(t, utils.JustError(keyStore.StarkNet().Get(key.ID()))) keys, _ = keyStore.StarkNet().GetAll() - assert.Equal(t, initialLength, len(keys)) + assert.Len(t, keys, initialLength) } func setupStarkNetKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.Master) { diff --git a/core/web/user_controller_test.go b/core/web/user_controller_test.go index f9d784a7456..d7d8ed97e33 100644 --- a/core/web/user_controller_test.go +++ b/core/web/user_controller_test.go @@ -240,14 +240,14 @@ func TestUserController_DeleteUser(t *testing.T) { err := app.AuthenticationProvider().CreateUser(ctx, &user) require.NoError(t, err) - resp, cleanup := client.Delete(fmt.Sprintf("/v2/users/%s", url.QueryEscape(user.Email))) + resp, cleanup := client.Delete("/v2/users/" + url.QueryEscape(user.Email)) t.Cleanup(cleanup) errors := cltest.ParseJSONAPIErrors(t, resp.Body) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Empty(t, errors.Errors) // second attempt would fail - resp, cleanup = client.Delete(fmt.Sprintf("/v2/users/%s", url.QueryEscape(user.Email))) + resp, cleanup = client.Delete("/v2/users/" + url.QueryEscape(user.Email)) t.Cleanup(cleanup) errors = cltest.ParseJSONAPIErrors(t, resp.Body) assert.Equal(t, http.StatusBadRequest, resp.StatusCode) diff --git a/internal/testdb/testdb.go b/internal/testdb/testdb.go index 1a52b1173e3..4f271d852a8 100644 --- a/internal/testdb/testdb.go +++ b/internal/testdb/testdb.go @@ -40,19 +40,19 @@ func CreateOrReplace(parsed url.URL, suffix string, withTemplate bool) (string, } defer db.Close() - _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", dbname)) + _, err = db.Exec("DROP DATABASE IF EXISTS " + dbname) if err != nil { - return "", fmt.Errorf("unable to drop postgres migrations test database: %v", err) + return "", fmt.Errorf("unable to drop postgres migrations test database: %w", err) } if withTemplate { _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s WITH TEMPLATE %s", dbname, PristineDBName)) } else { - _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", dbname)) + _, err = db.Exec("CREATE DATABASE " + dbname) } if err != nil { - return "", fmt.Errorf("unable to create postgres test database with name '%s': %v", dbname, err) + return "", fmt.Errorf("unable to create postgres test database with name '%s': %w", dbname, err) } - parsed.Path = fmt.Sprintf("/%s", dbname) + parsed.Path = "/" + dbname return parsed.String(), nil } @@ -73,9 +73,9 @@ func Drop(dbURL url.URL) error { } defer db.Close() - _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", dbname)) + _, err = db.Exec("DROP DATABASE IF EXISTS " + dbname) if err != nil { - return fmt.Errorf("unable to drop postgres migrations test database: %v", err) + return fmt.Errorf("unable to drop postgres migrations test database: %w", err) } return nil } diff --git a/plugins/cmd_test.go b/plugins/cmd_test.go index 8068977314a..1535bc0bba7 100644 --- a/plugins/cmd_test.go +++ b/plugins/cmd_test.go @@ -1,7 +1,7 @@ package plugins import ( - "fmt" + "errors" "strings" "testing" @@ -32,7 +32,7 @@ func TestNewCmdFactory_RegisterSuccess(t *testing.T) { func TestNewCmdFactory_RegisterFail(t *testing.T) { mockRegister := func(id string) (*RegisteredLoop, error) { - return nil, fmt.Errorf("registration failed") + return nil, errors.New("registration failed") } cmdConfig := CmdConfig{ diff --git a/plugins/loop_registry.go b/plugins/loop_registry.go index 82ef219566a..21fdae9a422 100644 --- a/plugins/loop_registry.go +++ b/plugins/loop_registry.go @@ -56,10 +56,10 @@ func (m *LoopRegistry) Register(id string) (*RegisteredLoop, error) { } ports, err := freeport.Take(1) if err != nil { - return nil, fmt.Errorf("failed to get free port: %v", err) + return nil, fmt.Errorf("failed to get free port: %w", err) } if len(ports) != 1 { - return nil, fmt.Errorf("failed to get free port: no ports returned") + return nil, errors.New("failed to get free port: no ports returned") } envCfg := loop.EnvConfig{PrometheusPort: ports[0]} diff --git a/plugins/loop_registry_test.go b/plugins/loop_registry_test.go index c7484b7aca9..1410a08fb56 100644 --- a/plugins/loop_registry_test.go +++ b/plugins/loop_registry_test.go @@ -16,7 +16,7 @@ func TestPluginPortManager(t *testing.T) { pFoo, err := m.Register("foo") require.NoError(t, err) require.Equal(t, "foo", pFoo.Name) - require.Greater(t, pFoo.EnvCfg.PrometheusPort, 0) + require.Positive(t, pFoo.EnvCfg.PrometheusPort) // test duplicate pNil, err := m.Register("foo") require.ErrorIs(t, err, ErrExists) @@ -75,7 +75,7 @@ func TestLoopRegistry_Register(t *testing.T) { // Test case 1: Register new loop registeredLoop, err := loopRegistry.Register("testID") - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, "testID", registeredLoop.Name) envCfg := registeredLoop.EnvCfg diff --git a/plugins/medianpoc/plugin.go b/plugins/medianpoc/plugin.go index e6ada1bec84..009b53c6c95 100644 --- a/plugins/medianpoc/plugin.go +++ b/plugins/medianpoc/plugin.go @@ -36,7 +36,7 @@ type PipelineNotFoundError struct { } func (e *PipelineNotFoundError) Error() string { - return fmt.Sprintf("no pipeline found for %s", e.Key) + return "no pipeline found for " + e.Key } func (p *Plugin) NewValidationService(ctx context.Context) (core.ValidationService, error) { @@ -171,7 +171,7 @@ type reportingPluginValidationService struct { func (r *reportingPluginValidationService) ValidateConfig(ctx context.Context, config map[string]interface{}) error { tt, ok := config["telemetryType"] if !ok { - return fmt.Errorf("expected telemtry type") + return errors.New("expected telemtry type") } telemetryType, ok := tt.(string) if !ok { diff --git a/tools/flakeytests/reporter.go b/tools/flakeytests/reporter.go index b7c7f66698f..52ab5642063 100644 --- a/tools/flakeytests/reporter.go +++ b/tools/flakeytests/reporter.go @@ -9,6 +9,7 @@ import ( "io" "net/http" "net/url" + "strconv" "time" ) @@ -70,7 +71,7 @@ type LokiReporter struct { func (l *LokiReporter) createRequest(report *Report) (pushRequest, error) { vs := [][]string{} now := l.now() - nows := fmt.Sprintf("%d", now.UnixNano()) + nows := strconv.FormatInt(now.UnixNano(), 10) for pkg, tests := range report.tests { for t := range tests { @@ -152,7 +153,7 @@ func (l *LokiReporter) makeRequest(ctx context.Context, pushReq pushRequest) err } req.Header.Add( "Authorization", - fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(l.auth))), + "Basic "+base64.StdEncoding.EncodeToString([]byte(l.auth)), ) req.Header.Add("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) diff --git a/tools/flakeytests/reporter_test.go b/tools/flakeytests/reporter_test.go index 15650fc7bd1..9f7ff427d70 100644 --- a/tools/flakeytests/reporter_test.go +++ b/tools/flakeytests/reporter_test.go @@ -1,7 +1,7 @@ package flakeytests import ( - "fmt" + "strconv" "testing" "time" @@ -11,7 +11,7 @@ import ( func TestMakeRequest_SingleTest(t *testing.T) { now := time.Now() - ts := fmt.Sprintf("%d", now.UnixNano()) + ts := strconv.FormatInt(now.UnixNano(), 10) r := &Report{ tests: map[string]map[string]int{ "core/assets": map[string]int{ @@ -23,7 +23,7 @@ func TestMakeRequest_SingleTest(t *testing.T) { pr, err := lr.createRequest(r) require.NoError(t, err) assert.Len(t, pr.Streams, 1) - assert.Equal(t, pr.Streams[0].Stream, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}) + assert.Equal(t, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}, pr.Streams[0].Stream) assert.ElementsMatch(t, pr.Streams[0].Values, [][]string{ {ts, `{"message_type":"flakey_test","commit_sha":"","repository":"","event_type":"","package":"core/assets","test_name":"TestLink","fq_test_name":"core/assets:TestLink"}`}, {ts, `{"message_type":"run_report","commit_sha":"","repository":"","event_type":"","num_package_panics":0,"num_flakes":1,"num_combined":1}`}, @@ -32,7 +32,7 @@ func TestMakeRequest_SingleTest(t *testing.T) { func TestMakeRequest_MultipleTests(t *testing.T) { now := time.Now() - ts := fmt.Sprintf("%d", now.UnixNano()) + ts := strconv.FormatInt(now.UnixNano(), 10) r := &Report{ tests: map[string]map[string]int{ "core/assets": map[string]int{ @@ -45,7 +45,7 @@ func TestMakeRequest_MultipleTests(t *testing.T) { pr, err := lr.createRequest(r) require.NoError(t, err) assert.Len(t, pr.Streams, 1) - assert.Equal(t, pr.Streams[0].Stream, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}) + assert.Equal(t, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}, pr.Streams[0].Stream) assert.ElementsMatch(t, pr.Streams[0].Values, [][]string{ {ts, `{"message_type":"flakey_test","commit_sha":"","repository":"","event_type":"","package":"core/assets","test_name":"TestLink","fq_test_name":"core/assets:TestLink"}`}, @@ -56,13 +56,13 @@ func TestMakeRequest_MultipleTests(t *testing.T) { func TestMakeRequest_NoTests(t *testing.T) { now := time.Now() - ts := fmt.Sprintf("%d", now.UnixNano()) + ts := strconv.FormatInt(now.UnixNano(), 10) r := NewReport() lr := &LokiReporter{auth: "bla", host: "bla", command: "go_core_tests", now: func() time.Time { return now }} pr, err := lr.createRequest(r) require.NoError(t, err) assert.Len(t, pr.Streams, 1) - assert.Equal(t, pr.Streams[0].Stream, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}) + assert.Equal(t, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}, pr.Streams[0].Stream) assert.ElementsMatch(t, pr.Streams[0].Values, [][]string{ {ts, `{"message_type":"run_report","commit_sha":"","repository":"","event_type":"","num_package_panics":0,"num_flakes":0,"num_combined":0}`}, }) @@ -70,13 +70,13 @@ func TestMakeRequest_NoTests(t *testing.T) { func TestMakeRequest_WithContext(t *testing.T) { now := time.Now() - ts := fmt.Sprintf("%d", now.UnixNano()) + ts := strconv.FormatInt(now.UnixNano(), 10) r := NewReport() lr := &LokiReporter{auth: "bla", host: "bla", command: "go_core_tests", now: func() time.Time { return now }, ctx: Context{CommitSHA: "42"}} pr, err := lr.createRequest(r) require.NoError(t, err) assert.Len(t, pr.Streams, 1) - assert.Equal(t, pr.Streams[0].Stream, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}) + assert.Equal(t, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}, pr.Streams[0].Stream) assert.ElementsMatch(t, pr.Streams[0].Values, [][]string{ {ts, `{"message_type":"run_report","commit_sha":"42","repository":"","event_type":"","num_package_panics":0,"num_flakes":0,"num_combined":0}`}, }) @@ -84,7 +84,7 @@ func TestMakeRequest_WithContext(t *testing.T) { func TestMakeRequest_Panics(t *testing.T) { now := time.Now() - ts := fmt.Sprintf("%d", now.UnixNano()) + ts := strconv.FormatInt(now.UnixNano(), 10) r := &Report{ tests: map[string]map[string]int{ "core/assets": map[string]int{ @@ -99,7 +99,7 @@ func TestMakeRequest_Panics(t *testing.T) { pr, err := lr.createRequest(r) require.NoError(t, err) assert.Len(t, pr.Streams, 1) - assert.Equal(t, pr.Streams[0].Stream, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}) + assert.Equal(t, map[string]string{"command": "go_core_tests", "app": "flakey-test-reporter"}, pr.Streams[0].Stream) assert.ElementsMatch(t, pr.Streams[0].Values, [][]string{ {ts, `{"message_type":"flakey_test","commit_sha":"","repository":"","event_type":"","package":"core/assets","test_name":"TestLink","fq_test_name":"core/assets:TestLink"}`}, diff --git a/tools/flakeytests/runner.go b/tools/flakeytests/runner.go index d4c6451a945..38731d9f1dd 100644 --- a/tools/flakeytests/runner.go +++ b/tools/flakeytests/runner.go @@ -6,7 +6,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "io" "log" "os" @@ -62,12 +61,12 @@ type testCommand struct { func (t *testCommand) test(pkg string, tests []string, w io.Writer) error { replacedPkg := strings.Replace(pkg, t.repo, "", -1) - cmd := exec.Command(t.command, fmt.Sprintf(".%s", replacedPkg)) //#nosec + cmd := exec.Command(t.command, "."+replacedPkg) //#nosec cmd.Env = os.Environ() if len(tests) > 0 { testFilter := strings.Join(tests, "|") - cmd.Env = append(cmd.Env, fmt.Sprintf("TEST_FLAGS=-run %s", testFilter)) + cmd.Env = append(cmd.Env, "TEST_FLAGS=-run "+testFilter) } cmd.Stdout = io.MultiWriter(os.Stdout, w) diff --git a/tools/flakeytests/runner_test.go b/tools/flakeytests/runner_test.go index 8f9433a427b..8fb195a3e76 100644 --- a/tools/flakeytests/runner_test.go +++ b/tools/flakeytests/runner_test.go @@ -49,7 +49,7 @@ func TestParser(t *testing.T) { ts := pr.tests assert.Len(t, ts, 1) assert.Len(t, ts["github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets"], 1) - assert.Equal(t, ts["github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets"]["TestLink"], 1) + assert.Equal(t, 1, ts["github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets"]["TestLink"]) } func TestParser_SkipsNonJSON(t *testing.T) { @@ -65,7 +65,7 @@ func TestParser_SkipsNonJSON(t *testing.T) { ts := pr.tests assert.Len(t, ts, 1) assert.Len(t, ts["github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets"], 1) - assert.Equal(t, ts["github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets"]["TestLink"], 1) + assert.Equal(t, 1, ts["github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets"]["TestLink"]) } func TestParser_PanicDueToLogging(t *testing.T) { @@ -80,7 +80,7 @@ func TestParser_PanicDueToLogging(t *testing.T) { ts := pr.tests assert.Len(t, ts, 1) assert.Len(t, ts["github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets"], 1) - assert.Equal(t, ts["github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets"]["TestAssets_LinkScanValue"], 1) + assert.Equal(t, 1, ts["github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets"]["TestAssets_LinkScanValue"]) } func TestParser_SuccessfulOutput(t *testing.T) { @@ -102,7 +102,7 @@ func TestParser_SuccessfulOutput(t *testing.T) { r := strings.NewReader(output) ts, err := parseOutput(r) require.NoError(t, err) - assert.Len(t, ts.tests, 0) + assert.Empty(t, ts.tests) } type testAdapter func(string, []string, io.Writer) error @@ -197,7 +197,7 @@ func TestRunner_AllFailures(t *testing.T) { err := r.Run(tests.Context(t)) require.NoError(t, err) - assert.Len(t, m.report.tests, 0) + assert.Empty(t, m.report.tests) } func TestRunner_RerunSuccessful(t *testing.T) {