diff --git a/chains/evm/gobindings/generation/abigen.go b/chains/evm/gobindings/generation/abigen.go index 19354a4edb..6d93a3138e 100644 --- a/chains/evm/gobindings/generation/abigen.go +++ b/chains/evm/gobindings/generation/abigen.go @@ -387,7 +387,7 @@ func writeAdditionalMethods(contractName string, logNames []string, abi abi.ABI, `, contractName, logName, contractName, logName) } - bs = append(bs, []byte(fmt.Sprintf(` + bs = append(bs, fmt.Appendf(nil, ` func (_%v *%v) ParseLog(log types.Log) (generated.AbigenLog, error) { switch log.Topics[0] { %v @@ -395,24 +395,24 @@ func (_%v *%v) ParseLog(log types.Log) (generated.AbigenLog, error) { return nil, fmt.Errorf("abigen wrapper received unknown log topic: %%v", log.Topics[0]) } } -`, contractName, contractName, logSwitchBody))...) +`, contractName, contractName, logSwitchBody)...) } // Write the Topic method for _, logName := range logNames { - bs = append(bs, []byte(fmt.Sprintf(` + bs = append(bs, fmt.Appendf(nil, ` func (%v%v) Topic() common.Hash { return common.HexToHash("%v") } -`, contractName, logName, abi.Events[logName].ID.Hex()))...) +`, contractName, logName, abi.Events[logName].ID.Hex())...) } // Write the Address method to the bottom of the file - bs = append(bs, []byte(fmt.Sprintf(` + bs = append(bs, fmt.Appendf(nil, ` func (_%v *%v) Address() common.Address { return _%v.address } -`, contractName, contractName, contractName))...) +`, contractName, contractName, contractName)...) return bs } diff --git a/commit/chainfee/observation.go b/commit/chainfee/observation.go index 23d889f267..8f0c0c4273 100644 --- a/commit/chainfee/observation.go +++ b/commit/chainfee/observation.go @@ -101,7 +101,7 @@ func feeUpdatesFromTimestampedBig( // packedFee = (dataAvFeeUSD << 112) | executionFeeUSD func fromPackedFee(packedFee *big.Int) ComponentsUSDPrices { ones112 := big.NewInt(0) - for i := 0; i < 112; i++ { + for i := range 112 { ones112 = ones112.SetBit(ones112, i, 1) } diff --git a/commit/chainfee/observation_async.go b/commit/chainfee/observation_async.go index 466470abf3..e3810125f6 100644 --- a/commit/chainfee/observation_async.go +++ b/commit/chainfee/observation_async.go @@ -14,6 +14,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/pkg/logutil" ccipreader "github.com/smartcontractkit/chainlink-ccip/pkg/reader" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) type observer interface { @@ -101,7 +102,7 @@ func (o *baseObserver) getSupportedChains( } supportedChainsSlice := supportedChains.ToSlice() - sort.Slice(supportedChainsSlice, func(i, j int) bool { return supportedChainsSlice[i] < supportedChainsSlice[j] }) + slices.Sort(supportedChainsSlice) return supportedChainsSlice, nil } diff --git a/commit/chainfee/observation_test.go b/commit/chainfee/observation_test.go index f2057bd636..54a9a30ffa 100644 --- a/commit/chainfee/observation_test.go +++ b/commit/chainfee/observation_test.go @@ -23,6 +23,7 @@ import ( reader2 "github.com/smartcontractkit/chainlink-ccip/mocks/internal_/reader" "github.com/smartcontractkit/chainlink-ccip/mocks/pkg/reader" "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) func Test_processor_Observation(t *testing.T) { @@ -134,7 +135,7 @@ func Test_processor_Observation(t *testing.T) { supportedSet.Remove(tc.dstChain) slicesWithoutDst := supportedSet.ToSlice() - sort.Slice(slicesWithoutDst, func(i, j int) bool { return slicesWithoutDst[i] < slicesWithoutDst[j] }) + slices.Sort(slicesWithoutDst) if len(slicesWithoutDst) == 0 { slicesWithoutDst = []ccipocr3.ChainSelector(nil) @@ -333,7 +334,7 @@ func Test_unique_chain_filter_in_Observation(t *testing.T) { supportedSet.Remove(tc.dstChain) slicesWithoutDst := supportedSet.ToSlice() - sort.Slice(slicesWithoutDst, func(i, j int) bool { return slicesWithoutDst[i] < slicesWithoutDst[j] }) + slices.Sort(slicesWithoutDst) ccipReader.EXPECT().GetChainsFeeComponents(ctx, slicesWithoutDst). Return(tc.chainFeeComponents).Maybe() diff --git a/commit/chainfee/outcome_test.go b/commit/chainfee/outcome_test.go index 0663642e77..8001d21c3c 100644 --- a/commit/chainfee/outcome_test.go +++ b/commit/chainfee/outcome_test.go @@ -133,7 +133,7 @@ var defaultChainConfig = reader.ChainConfig{ // sameObs returns n observations with the same observation but from different oracle ids func sameObs(n int, obs Observation) []plugincommon.AttributedObservation[Observation] { aos := make([]plugincommon.AttributedObservation[Observation], n) - for i := 0; i < n; i++ { + for i := range n { aos[i] = plugincommon.AttributedObservation[Observation]{OracleID: commontypes.OracleID(i), Observation: obs} } return aos diff --git a/commit/factory_test.go b/commit/factory_test.go index 1c2348d685..0d11fd4cb4 100644 --- a/commit/factory_test.go +++ b/commit/factory_test.go @@ -168,10 +168,7 @@ func Test_maxObservationLength(t *testing.T) { // Generate a string with a counter and fill the rest with 'x's func generateStringWithCounter(counter, length int) string { counterStr := fmt.Sprintf("%d", counter) - paddingLength := length - len(counterStr) - if paddingLength < 0 { - paddingLength = 0 - } + paddingLength := max(length-len(counterStr), 0) return counterStr + strings.Repeat("x", paddingLength) } diff --git a/commit/merkleroot/outcome_test.go b/commit/merkleroot/outcome_test.go index 8d19480ff5..5e045a0f98 100644 --- a/commit/merkleroot/outcome_test.go +++ b/commit/merkleroot/outcome_test.go @@ -20,6 +20,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/internal/plugintypes" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" "github.com/smartcontractkit/chainlink-ccip/pluginconfig" + "slices" ) var rmnRemoteCfg = testhelpers.CreateRMNRemoteCfg() @@ -401,7 +402,7 @@ func Test_Processor_Outcome(t *testing.T) { func(tc testCase) Observation { return tc.observations[0](tc) }, func(tc testCase) Observation { baseObs := tc.observations[0](tc) - baseObs.MerkleRoots = append(baseObs.MerkleRoots[:1], baseObs.MerkleRoots[2:]...) // skip chainB + baseObs.MerkleRoots = slices.Delete(baseObs.MerkleRoots, 1, 2) // skip chainB // report a different onRamp address for chainC this leads to no consensus for chainC merkle roots baseObs.MerkleRoots[1].OnRampAddress = []byte{0xd} @@ -699,7 +700,7 @@ func Test_buildMerkleRootsOutcome(t *testing.T) { } lggr := logger.Test(t) - for i := 0; i < rounds; i++ { + for range rounds { report1, err := buildMerkleRootsOutcome(Query{}, false, lggr, obs, Outcome{}, mockAddrCodec) require.NoError(t, err) report2, err := buildMerkleRootsOutcome(Query{}, false, lggr, obs, Outcome{}, mockAddrCodec) diff --git a/commit/merkleroot/rmn/controller_test.go b/commit/merkleroot/rmn/controller_test.go index 74fe5fdefd..965699bd22 100644 --- a/commit/merkleroot/rmn/controller_test.go +++ b/commit/merkleroot/rmn/controller_test.go @@ -30,6 +30,7 @@ import ( rmntypes "github.com/smartcontractkit/chainlink-ccip/commit/merkleroot/rmn/types" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "maps" ) var ( @@ -415,7 +416,7 @@ func TestClient_ComputeReportSignatures(t *testing.T) { const numNodes = 8 rmnNodes := make([]rmntypes.HomeNodeInfo, numNodes) - for i := 0; i < numNodes; i++ { + for i := range numNodes { rmnNodes[i] = rmntypes.HomeNodeInfo{ ID: rmntypes.NodeID(i + 1), PeerID: [32]byte{1, 2, 3}, @@ -733,7 +734,7 @@ func Test_controller_validateSignedObservationResponse(t *testing.T) { func Test_newRequestID(t *testing.T) { ids := map[uint64]struct{}{} - for i := 0; i < 1000; i++ { + for range 1000 { id := newRequestID(logger.Test(t)) _, ok := ids[id] assert.False(t, ok) @@ -913,11 +914,11 @@ func (ts *testSetup) nodesRespondToTheObservationRequests( laneUpdates := make([]*rmnpb.FixedDestLaneUpdate, 0) for _, laneUpdate := range allLaneUpdates { if requestedChains[nodeID].Contains(laneUpdate.LaneSource.SourceChainSelector) { - root := sha256.Sum256([]byte(fmt.Sprintf("%d[%d,%d]", + root := sha256.Sum256(fmt.Appendf(nil, "%d[%d,%d]", laneUpdate.LaneSource.SourceChainSelector, laneUpdate.ClosedInterval.MinMsgNr, laneUpdate.ClosedInterval.MaxMsgNr, - ))) + )) laneUpdates = append(laneUpdates, &rmnpb.FixedDestLaneUpdate{ LaneSource: laneUpdate.LaneSource, ClosedInterval: laneUpdate.ClosedInterval, @@ -1054,9 +1055,7 @@ func (m *mockPeerClient) getReceivedRequests() map[rmntypes.NodeID][]*rmnpb.Requ cp := make(map[rmntypes.NodeID][]*rmnpb.Request) m.mu.RLock() defer m.mu.RUnlock() - for k, v := range m.receivedRequests { - cp[k] = v - } + maps.Copy(cp, m.receivedRequests) return cp } diff --git a/commit/merkleroot/rmn/streamconfig.go b/commit/merkleroot/rmn/streamconfig.go index e6e50624ef..45b6015d94 100644 --- a/commit/merkleroot/rmn/streamconfig.go +++ b/commit/merkleroot/rmn/streamconfig.go @@ -100,7 +100,7 @@ func bytesLimit(roundInterval time.Duration) ragep2p.TokenBucketParams { // compute max observation request size and max report signatures request size func init() { fixedDestLaneUpdates := make([]*rmnpb.FixedDestLaneUpdate, 0, estimatedMaxNumberOfSourceChains) - for i := 0; i < estimatedMaxNumberOfSourceChains; i++ { + for range estimatedMaxNumberOfSourceChains { fixedDestLaneUpdates = append(fixedDestLaneUpdates, &rmnpb.FixedDestLaneUpdate{ LaneSource: &rmnpb.LaneSource{ SourceChainSelector: math.MaxUint64, diff --git a/commit/merkleroot/transmission_checks.go b/commit/merkleroot/transmission_checks.go index 73a9b46f5a..e454303c5b 100644 --- a/commit/merkleroot/transmission_checks.go +++ b/commit/merkleroot/transmission_checks.go @@ -10,6 +10,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/internal/libs/slicelib" "github.com/smartcontractkit/chainlink-ccip/pkg/reader" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) // ValidateMerkleRootsState validates the proposed merkle roots against the current on-chain state. @@ -38,7 +39,7 @@ func ValidateMerkleRootsState( } chainSlice := chainSet.ToSlice() - sort.Slice(chainSlice, func(i, j int) bool { return chainSlice[i] < chainSlice[j] }) + slices.Sort(chainSlice) offRampExpNextSeqNums, err := reader.NextSeqNum(ctx, chainSlice) if err != nil { diff --git a/commit/metrics/prom_test.go b/commit/metrics/prom_test.go index 7140d971ab..e913a51370 100644 --- a/commit/metrics/prom_test.go +++ b/commit/metrics/prom_test.go @@ -392,7 +392,7 @@ func Test_LatencyAndErrors(t *testing.T) { method := "observation" passCounter := 10 - for i := 0; i < passCounter; i++ { + for range passCounter { reporter.TrackProcessorLatency(processor, method, time.Second, nil) } l2 := internal.CounterFromHistogramByLabels(t, reporter.processorLatencyHistogram, chainID, processor, method) @@ -404,7 +404,7 @@ func Test_LatencyAndErrors(t *testing.T) { method := "outcome" errCounter := 5 - for i := 0; i < errCounter; i++ { + for range errCounter { reporter.TrackProcessorLatency(processor, method, time.Second, fmt.Errorf("error")) } errs := testutil.ToFloat64( diff --git a/commit/plugin_e2e_test.go b/commit/plugin_e2e_test.go index f524d82ad8..05286d7379 100644 --- a/commit/plugin_e2e_test.go +++ b/commit/plugin_e2e_test.go @@ -46,6 +46,7 @@ import ( reader2 "github.com/smartcontractkit/chainlink-ccip/pkg/reader" "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" "github.com/smartcontractkit/chainlink-ccip/pluginconfig" + "slices" ) const ( @@ -847,7 +848,7 @@ func setupNode(params SetupNodeParams) nodeSetup { for chainSel := range params.offRampNextSeqNum { sourceChains = append(sourceChains, chainSel) } - sort.Slice(sourceChains, func(i, j int) bool { return sourceChains[i] < sourceChains[j] }) + slices.Sort(sourceChains) offRampNextSeqNums := make(map[ccipocr3.ChainSelector]ccipocr3.SeqNum, 0) chainsWithNewMsgs := make([]ccipocr3.ChainSelector, 0) @@ -859,7 +860,7 @@ func setupNode(params SetupNodeParams) nodeSetup { newMsgs := make([]ccipocr3.Message, 0) numNewMsgs := (params.onRampLastSeqNum[sourceChain] - offRampNextSeqNum) + 1 for i := uint64(0); i < uint64(numNewMsgs); i++ { - messageID := sha256.Sum256([]byte(fmt.Sprintf("%d", uint64(offRampNextSeqNum)+i))) + messageID := sha256.Sum256(fmt.Appendf(nil, "%d", uint64(offRampNextSeqNum)+i)) newMsgs = append(newMsgs, ccipocr3.Message{ Header: ccipocr3.RampMessageHeader{ MessageID: messageID, diff --git a/commit/tokenprice/observation.go b/commit/tokenprice/observation.go index 344d5e0b2c..df753709bc 100644 --- a/commit/tokenprice/observation.go +++ b/commit/tokenprice/observation.go @@ -16,6 +16,7 @@ import ( pkgreader "github.com/smartcontractkit/chainlink-ccip/pkg/reader" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" "github.com/smartcontractkit/chainlink-ccip/pluginconfig" + "slices" ) func (p *processor) Observation( @@ -139,7 +140,7 @@ func (b *baseObserver) observeFeeQuoterTokenUpdates( tokensToQuery := maps.Keys(b.offChainCfg.TokenInfo) // sort tokens to query to ensure deterministic order - sort.Slice(tokensToQuery, func(i, j int) bool { return tokensToQuery[i] < tokensToQuery[j] }) + slices.Sort(tokensToQuery) lggr.Infow("observing fee quoter token updates") priceUpdates, err := b.tokenPriceReader.GetFeeQuoterTokenUpdates(ctx, tokensToQuery, b.destChain) if err != nil { diff --git a/execute/exectypes/commit_data.go b/execute/exectypes/commit_data.go index c39a548f96..a542df26da 100644 --- a/execute/exectypes/commit_data.go +++ b/execute/exectypes/commit_data.go @@ -4,6 +4,7 @@ import ( "time" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) // CommitData is the data that is committed to the chain. @@ -54,9 +55,9 @@ func (cd CommitData) CopyNoMsgData() CommitData { BlockNum: cd.BlockNum, MerkleRoot: cd.MerkleRoot, SequenceNumberRange: cd.SequenceNumberRange, - ExecutedMessages: append([]cciptypes.SeqNum{}, cd.ExecutedMessages...), + ExecutedMessages: slices.Clone(cd.ExecutedMessages), Messages: msgsWitoutData, - Hashes: append([]cciptypes.Bytes32{}, cd.Hashes...), - MessageTokenData: append([]MessageTokenData{}, cd.MessageTokenData...), + Hashes: slices.Clone(cd.Hashes), + MessageTokenData: slices.Clone(cd.MessageTokenData), } } diff --git a/execute/exectypes/outcome.go b/execute/exectypes/outcome.go index b5b080a02b..d952c290c1 100644 --- a/execute/exectypes/outcome.go +++ b/execute/exectypes/outcome.go @@ -4,6 +4,7 @@ import ( "sort" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) type PluginState string @@ -119,8 +120,8 @@ func NewSortedOutcome( pendingCommits []CommitData, report cciptypes.ExecutePluginReport, ) Outcome { - pendingCommitsCP := append([]CommitData{}, pendingCommits...) - reportCP := append([]cciptypes.ExecutePluginReportSingleChain{}, report.ChainReports...) + pendingCommitsCP := slices.Clone(pendingCommits) + reportCP := slices.Clone(report.ChainReports) sort.Slice( pendingCommitsCP, func(i, j int) bool { diff --git a/execute/exectypes/token.go b/execute/exectypes/token.go index 1ec268142d..5f2e4a09f8 100644 --- a/execute/exectypes/token.go +++ b/execute/exectypes/token.go @@ -138,7 +138,7 @@ func NotReadyToken() TokenData { // It intentionally skips the fields that are not relevant for the consensus process and are // not serialized when nodes gossiping func TokenDataHash(td TokenData) [32]byte { - return sha3.Sum256([]byte(fmt.Sprintf("%v_%v", td.Ready, td.Data))) + return sha3.Sum256(fmt.Appendf(nil, "%v_%v", td.Ready, td.Data)) } func (td TokenData) IsReady() bool { diff --git a/execute/exectypes/token_test.go b/execute/exectypes/token_test.go index f60d5b5aaf..c9be64d90f 100644 --- a/execute/exectypes/token_test.go +++ b/execute/exectypes/token_test.go @@ -150,7 +150,7 @@ func Test_MessageTokenData_Append(t *testing.T) { assert.False(t, msg.IsReady()) assert.Nil(t, msg.Error()) - for i := 0; i < 10; i++ { + for i := range 10 { assert.Nil(t, msg.TokenData[i].Data) msg = msg.Append(i, NewSuccessTokenData([]byte{byte(i)})) } diff --git a/execute/factory_test.go b/execute/factory_test.go index 03a1a336b3..8df8d116ad 100644 --- a/execute/factory_test.go +++ b/execute/factory_test.go @@ -80,7 +80,7 @@ func TestObservationSize(t *testing.T) { commitObs := make(exectypes.CommitObservations, estimatedMaxNumberOfSourceChains) bigSeqNum := ccipocr3.SeqNum(100000) - for i := 0; i < maxCommitReports; i++ { + for i := range maxCommitReports { idx := ccipocr3.ChainSelector(i % estimatedMaxNumberOfSourceChains) seqNum := bigSeqNum + ccipocr3.SeqNum(i) commitObs[idx] = append(commitObs[idx], exectypes.CommitData{ @@ -100,7 +100,7 @@ func TestObservationSize(t *testing.T) { } msgObs := make(exectypes.MessageObservations, estimatedMaxNumberOfSourceChains) - for i := 0; i < maxMessages; i++ { + for i := range maxMessages { idx := ccipocr3.ChainSelector(i % estimatedMaxNumberOfSourceChains % maxCommitReports) if nil == msgObs[idx] { msgObs[idx] = make(map[ccipocr3.SeqNum]ccipocr3.Message) @@ -130,7 +130,7 @@ func TestObservationSize(t *testing.T) { // This could be bigger, since each message could send multiple tokens. tokenDataObs := make(exectypes.TokenDataObservations, estimatedMaxNumberOfSourceChains) - for i := 0; i < maxMessages; i++ { + for i := range maxMessages { idx := ccipocr3.ChainSelector(i % estimatedMaxNumberOfSourceChains) if nil == tokenDataObs[idx] { tokenDataObs[idx] = make(map[ccipocr3.SeqNum]exectypes.MessageTokenData) @@ -151,7 +151,7 @@ func TestObservationSize(t *testing.T) { // separate sender for each message noncesObs := make(exectypes.NonceObservations, maxMessages) mockAddrCodec := internal.NewMockAddressCodecHex(t) - for i := 0; i < maxMessages; i++ { + for i := range maxMessages { idx := ccipocr3.ChainSelector(i % estimatedMaxNumberOfSourceChains) if nil == noncesObs[idx] { noncesObs[idx] = make(map[string]uint64) @@ -178,7 +178,7 @@ func TestObservationSize(t *testing.T) { //type ContractAddresses map[string]map[cciptypes.ChainSelector]cciptypes.UnknownAddress discoveryObs.Addresses[contract] = make(map[ccipocr3.ChainSelector]ccipocr3.UnknownAddress, estimatedMaxNumberOfSourceChains) - for i := 0; i < estimatedMaxNumberOfSourceChains; i++ { + for i := range estimatedMaxNumberOfSourceChains { discoveryObs.Addresses[contract][ccipocr3.ChainSelector(i)] = addr[:] } } diff --git a/execute/internal/cache/commit_root_cache_test.go b/execute/internal/cache/commit_root_cache_test.go index 56e6e97393..a5a3b8fd05 100644 --- a/execute/internal/cache/commit_root_cache_test.go +++ b/execute/internal/cache/commit_root_cache_test.go @@ -763,7 +763,7 @@ func TestCommitRootsCache_AdditionalEdgeCases(t *testing.T) { allReports := make(map[ccipocr3.ChainSelector][]exectypes.CommitData) allReports[selector] = make([]exectypes.CommitData, 0, 20) - for i := 0; i < 20; i++ { + for i := range 20 { root := ccipocr3.Bytes32{byte(i)} timestamp := now.Add(time.Duration(-100+i*5) * time.Minute) report := createCommitData(timestamp, selector, root) @@ -778,7 +778,7 @@ func TestCommitRootsCache_AdditionalEdgeCases(t *testing.T) { "Initial earliest should be first root") // Execute roots one by one from first to last - for i := 0; i < 20; i++ { + for i := range 20 { cache.MarkAsExecuted(selector, allReports[selector][i].MerkleRoot) // Create remaining reports diff --git a/execute/metrics/prom_test.go b/execute/metrics/prom_test.go index 13ccd053fe..0e80475a84 100644 --- a/execute/metrics/prom_test.go +++ b/execute/metrics/prom_test.go @@ -405,7 +405,7 @@ func Test_ExecLatency(t *testing.T) { t.Run("multiple latency outcomes", func(t *testing.T) { passCounter := 10 - for i := 0; i < passCounter; i++ { + for range passCounter { reporter.TrackLatency(exectypes.Filter, plugincommon.OutcomeMethod, time.Second, nil) } l2 := internal.CounterFromHistogramByLabels(t, reporter.latencyHistogram, chainID, "outcome", "Filter") @@ -414,7 +414,7 @@ func Test_ExecLatency(t *testing.T) { t.Run("multiple latency observation with errors", func(t *testing.T) { errCounter := 5 - for i := 0; i < errCounter; i++ { + for range errCounter { reporter.TrackLatency(exectypes.GetMessages, plugincommon.ObservationMethod, time.Second, fmt.Errorf("error")) } errs := testutil.ToFloat64( @@ -447,7 +447,7 @@ func Test_LatencyAndErrors(t *testing.T) { method := "observation" passCounter := 10 - for i := 0; i < passCounter; i++ { + for range passCounter { reporter.TrackProcessorLatency(processor, method, time.Second, nil) } l2 := internal.CounterFromHistogramByLabels(t, reporter.processorLatencyHistogram, chainID, processor, method) @@ -459,7 +459,7 @@ func Test_LatencyAndErrors(t *testing.T) { method := "outcome" errCounter := 5 - for i := 0; i < errCounter; i++ { + for range errCounter { reporter.TrackProcessorLatency(processor, method, time.Second, fmt.Errorf("error")) } errs := testutil.ToFloat64( diff --git a/execute/optimizers/type_optimizer.go b/execute/optimizers/type_optimizer.go index 59ce5b2a3c..98dbc22dda 100644 --- a/execute/optimizers/type_optimizer.go +++ b/execute/optimizers/type_optimizer.go @@ -12,6 +12,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/pkg/logutil" ocrtypecodec "github.com/smartcontractkit/chainlink-ccip/pkg/ocrtypecodec/v1" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) type ObservationOptimizer struct { @@ -76,9 +77,7 @@ func (op ObservationOptimizer) TruncateObservation(observation exectypes.Observa } chains := maps.Keys(obs.CommitReports) - sort.Slice(chains, func(i, j int) bool { - return chains[i] < chains[j] - }) + slices.Sort(chains) messageAndTokenDataEncodedSizes := exectypes.GetEncodedMsgAndTokenDataSizes(obs.Messages, obs.TokenData) // While the encoded obs is too large, continue filtering data. diff --git a/execute/plugin_e2e_test.go b/execute/plugin_e2e_test.go index 64daed978f..6719536d4c 100644 --- a/execute/plugin_e2e_test.go +++ b/execute/plugin_e2e_test.go @@ -86,7 +86,7 @@ func TestExceedSizeObservation(t *testing.T) { startSeqNr := cciptypes.SeqNum(100) messages := make([]inmem.MessagesWithMetadata, 0, maxMessages) - for i := 0; i < maxMessages; i++ { + for i := range maxMessages { messages = append(messages, makeMsgWithMetadata( startSeqNr+cciptypes.SeqNum(i), @@ -256,7 +256,7 @@ func TestPlugin_CommitReportTimestampOrdering(t *testing.T) { require.Len(t, outcome.CommitReports, 3) // Verify timestamps are in ascending order - for i := 0; i < len(outcome.CommitReports)-1; i++ { + for i := range len(outcome.CommitReports) - 1 { require.True(t, outcome.CommitReports[i].Timestamp.Before( outcome.CommitReports[i+1].Timestamp), "commit reports should be ordered by timestamp") diff --git a/execute/plugin_functions.go b/execute/plugin_functions.go index 1f47c474c5..279780b1ec 100644 --- a/execute/plugin_functions.go +++ b/execute/plugin_functions.go @@ -22,6 +22,7 @@ import ( ocrtypecodec "github.com/smartcontractkit/chainlink-ccip/pkg/ocrtypecodec/v1" "github.com/smartcontractkit/chainlink-ccip/pkg/reader" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) // validateCommitReportsReadingEligibility validates that all commit reports' source chains are supported by observer @@ -338,9 +339,7 @@ func combineReportsAndMessages( continue } - sort.Slice(executedMsgsInReportRange, func(i, j int) bool { - return executedMsgsInReportRange[i] < executedMsgsInReportRange[j] - }) + slices.Sort(executedMsgsInReportRange) report.ExecutedMessages = append(reports[i].ExecutedMessages, executedMsgsInReportRange...) pending = append(pending, report) } @@ -487,7 +486,7 @@ func computeCommitObservationsConsensus( } executedMessages = append(executedMessages, seqNum) } - sort.Slice(executedMessages, func(i, j int) bool { return executedMessages[i] < executedMessages[j] }) + slices.Sort(executedMessages) if _, ok := result[mr.SourceChain]; !ok { result[mr.SourceChain] = make([]exectypes.CommitData, 0) @@ -743,7 +742,7 @@ func computeNoncesConsensus( continue } - sort.Slice(nonces, func(i, j int) bool { return nonces[i] < nonces[j] }) + slices.Sort(nonces) consensusNonce := nonces[fChainDest] if _, ok := consensusNonces[pair.chain]; !ok { diff --git a/execute/plugin_test.go b/execute/plugin_test.go index 3678bf13af..409c539dd6 100644 --- a/execute/plugin_test.go +++ b/execute/plugin_test.go @@ -50,14 +50,14 @@ func genRandomChainReports(numReports, numMsgsPerReport int) []cciptypes.Execute // chain selectors and unique (random) sequence number ranges. // don't need to set anything else. chainReports := make([]cciptypes.ExecutePluginReportSingleChain, numReports) - for i := 0; i < numReports; i++ { + for i := range numReports { scc := cciptypes.ChainSelector(rand.RandomUint64()) chainReports[i] = cciptypes.ExecutePluginReportSingleChain{ SourceChainSelector: scc, Messages: make([]cciptypes.Message, 0, numMsgsPerReport), } start := rand.RandomUint32() - for j := 0; j < numMsgsPerReport; j++ { + for j := range numMsgsPerReport { chainReports[i].Messages = append(chainReports[i].Messages, cciptypes.Message{ Header: cciptypes.RampMessageHeader{ SequenceNumber: cciptypes.SeqNum(start + uint32(j)), @@ -99,12 +99,8 @@ func Test_getSeqNrRangesBySource(t *testing.T) { } expectedSetSlice := maps.Keys(expectedSet) actualSetSlice := seqNrRange.ToSlice() - sort.Slice(expectedSetSlice, func(i, j int) bool { - return expectedSetSlice[i] < expectedSetSlice[j] - }) - sort.Slice(actualSetSlice, func(i, j int) bool { - return actualSetSlice[i] < actualSetSlice[j] - }) + slices.Sort(expectedSetSlice) + slices.Sort(actualSetSlice) require.Equal(t, expectedSetSlice, actualSetSlice) } } @@ -1460,7 +1456,7 @@ func TestPlugin_ShouldAcceptAttestedReport_ShouldAccept(t *testing.T) { return e.Method == "ExecutedMessages" }) require.GreaterOrEqual(t, idx, 0) - mockReader.ExpectedCalls = append(mockReader.ExpectedCalls[:idx], mockReader.ExpectedCalls[idx+1:]...) + mockReader.ExpectedCalls = slices.Delete(mockReader.ExpectedCalls, idx, idx+1) mockReader.EXPECT(). ExecutedMessages( diff --git a/execute/plugin_tokendata_test.go b/execute/plugin_tokendata_test.go index edd2deea42..51198afec5 100644 --- a/execute/plugin_tokendata_test.go +++ b/execute/plugin_tokendata_test.go @@ -118,7 +118,7 @@ func Test_USDC_Transfer(t *testing.T) { }`) // Run 3 more rounds to get all attestations - for i := 0; i < 3; i++ { + for range 3 { outcome = runRoundAndGetOutcome(ctx, ocrTypeCodec, t, runner) } diff --git a/execute/report/data.go b/execute/report/data.go index 706919f079..ec5bfc082d 100644 --- a/execute/report/data.go +++ b/execute/report/data.go @@ -5,6 +5,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/execute/exectypes" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) // markNewMessagesExecuted compares an execute plugin report with the commit report metadata and marks the new messages @@ -13,13 +14,12 @@ func markNewMessagesExecuted( execReport cciptypes.ExecutePluginReportSingleChain, report exectypes.CommitData, ) exectypes.CommitData { // Mark new messages executed. - for i := 0; i < len(execReport.Messages); i++ { + for i := range execReport.Messages { report.ExecutedMessages = append(report.ExecutedMessages, execReport.Messages[i].Header.SequenceNumber) } - sort.Slice( - report.ExecutedMessages, - func(i, j int) bool { return report.ExecutedMessages[i] < report.ExecutedMessages[j] }) + slices.Sort( + report.ExecutedMessages) return report } diff --git a/execute/report/report.go b/execute/report/report.go index 1aebda2701..bea386a57d 100644 --- a/execute/report/report.go +++ b/execute/report/report.go @@ -30,7 +30,7 @@ func buildSingleChainReportHelper( if readyMessages == nil { readyMessages = make(map[int]struct{}) } - for i := 0; i < len(report.Messages); i++ { + for i := range report.Messages { readyMessages[i] = struct{}{} } } @@ -320,7 +320,7 @@ func CheckIfInflight(inflight IsInflight) Check { // checkMessages to get a set of which are ready to execute. func (b *execReportBuilder) checkMessages(ctx context.Context, report exectypes.CommitData) (map[int]struct{}, error) { readyMessages := make(map[int]struct{}) - for i := 0; i < len(report.Messages); i++ { + for i := range report.Messages { updatedReport, status, err := b.checkMessage(ctx, i, report) if err != nil { return nil, diff --git a/execute/report/report_test.go b/execute/report/report_test.go index d6e3d9b04a..7aad54f833 100644 --- a/execute/report/report_test.go +++ b/execute/report/report_test.go @@ -248,7 +248,7 @@ func makeTestCommitReport( } } var messages []cciptypes.Message - for i := 0; i < numMessages; i++ { + for i := range numMessages { var msg cciptypes.Message if zeroNonces { msg = makeMessage( @@ -270,7 +270,7 @@ func makeTestCommitReport( } var hashes []cciptypes.Bytes32 - for i := 0; i < len(messages); i++ { + for i := range messages { hash, err := hasher.Hash(context.Background(), messages[i]) if err != nil { panic(fmt.Sprintf("unable to hash message: %s", err)) @@ -279,12 +279,12 @@ func makeTestCommitReport( } messageTokenData := make([]exectypes.MessageTokenData, numMessages) - for i := 0; i < len(messages); i++ { + for i := range messages { messageTokenData[i] = exectypes.MessageTokenData{ TokenData: []exectypes.TokenData{ { Ready: true, - Data: []byte(fmt.Sprintf("data %d", i)), + Data: fmt.Appendf(nil, "data %d", i), }, }, } @@ -434,7 +434,7 @@ func Test_buildSingleChainReport_Errors(t *testing.T) { t.Parallel() msgs := make(map[int]struct{}) - for i := 0; i < len(tt.args.report.Messages); i++ { + for i := range tt.args.report.Messages { msgs[i] = struct{}{} } diff --git a/execute/test_utils.go b/execute/test_utils.go index 65781a856a..1edfb8ae53 100644 --- a/execute/test_utils.go +++ b/execute/test_utils.go @@ -106,7 +106,7 @@ func (it *IntTest) WithMessages( totalMessages := len(mapped) messagesPerReport := totalMessages / numReports - for i := 0; i < numReports; i++ { + for i := range numReports { startIndex := i * messagesPerReport endIndex := startIndex + messagesPerReport if i == numReports-1 { @@ -453,7 +453,7 @@ func setupHomeChainPoller( mock.Anything, mock.Anything, mock.Anything, - mock.MatchedBy(func(input map[string]interface{}) bool { + mock.MatchedBy(func(input map[string]any) bool { _, pageIndexExists := input["pageIndex"] _, pageSizeExists := input["pageSize"] return pageIndexExists && pageSizeExists diff --git a/execute/tokendata/http/http_test.go b/execute/tokendata/http/http_test.go index 53ef60c5c7..68b63a0141 100644 --- a/execute/tokendata/http/http_test.go +++ b/execute/tokendata/http/http_test.go @@ -194,7 +194,7 @@ func Test_HTTPClient_Cooldown(t *testing.T) { require.EqualError(t, err, tokendata.ErrUnknownResponse.Error()) // First rate-limit activates cooldown and other requests should return rate limit immediately - for i := 0; i < 10; i++ { + for range 10 { _, _, err = client.Get(tests.Context(t), cciptypes.Bytes32{1, 2, 3}.String()) require.EqualError(t, err, tokendata.ErrRateLimit.Error()) } @@ -334,7 +334,7 @@ func Test_HTTPClient_RateLimiting_Parallel(t *testing.T) { trigger := make(chan struct{}) errorChan := make(chan error, tc.requests) wg := sync.WaitGroup{} - for i := 0; i < int(tc.requests); i++ { + for range int(tc.requests) { wg.Add(1) go func() { defer wg.Done() diff --git a/execute/tokendata/observer/observer.go b/execute/tokendata/observer/observer.go index ece8af6929..d8f954419a 100644 --- a/execute/tokendata/observer/observer.go +++ b/execute/tokendata/observer/observer.go @@ -12,6 +12,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/pkg/contractreader" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" "github.com/smartcontractkit/chainlink-ccip/pluginconfig" + "slices" ) type TokenDataObserver interface { @@ -252,13 +253,7 @@ func (n *NoopTokenDataObserver) isError(selector cciptypes.ChainSelector, seq cc return false } - for _, idx := range tokenIdxs { - if idx == tokenIdx { - return true - } - } - - return false + return slices.Contains(tokenIdxs, tokenIdx) } func (n *NoopTokenDataObserver) IsTokenSupported(_ cciptypes.ChainSelector, _ cciptypes.RampTokenAmount) bool { diff --git a/execute/tokendata/observer/observer_background.go b/execute/tokendata/observer/observer_background.go index 901c6da362..3d2e81081b 100644 --- a/execute/tokendata/observer/observer_background.go +++ b/execute/tokendata/observer/observer_background.go @@ -12,6 +12,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/execute/exectypes" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) type backgroundObserver struct { @@ -145,7 +146,7 @@ func (o *backgroundObserver) startWorkers() { o.wg.Wait() o.lggr.Info("all workers stopped, new workers are starting...") - for i := 0; i < o.numWorkers; i++ { + for i := range o.numWorkers { o.wg.Add(1) workerID := i go o.worker(workerID) @@ -300,7 +301,7 @@ func (q *msgQueue) dequeue() (cciptypes.Message, bool) { "availableSince", time.Since(msg.availableAt), ) q.msgIDs.Remove(msg.msg.Header.MessageID) - q.msgs = append(q.msgs[:i], q.msgs[i+1:]...) + q.msgs = slices.Delete(q.msgs, i, i+1) return msg.msg, true } } diff --git a/execute/tokendata/observer/observer_background_test.go b/execute/tokendata/observer/observer_background_test.go index 7409789039..6c5c45c48e 100644 --- a/execute/tokendata/observer/observer_background_test.go +++ b/execute/tokendata/observer/observer_background_test.go @@ -150,7 +150,7 @@ func generateMsgObservations( errorMsgs := make(map[cciptypes.ChainSelector][]cciptypes.SeqNum) for chain, numMsgs := range numMsgsPerChain { msgObservations[chain] = make(map[cciptypes.SeqNum]cciptypes.Message, numMsgs) - for i := 0; i < numMsgs; i++ { + for i := range numMsgs { seqNum := cciptypes.SeqNum(i) msgIDStr := fmt.Sprintf("%d-%d", chain, i) msgID := cciptypes.Bytes32{} diff --git a/execute/tokendata/usdc/usdc_int_test.go b/execute/tokendata/usdc/usdc_int_test.go index 0ea40312a4..62f43d2712 100644 --- a/execute/tokendata/usdc/usdc_int_test.go +++ b/execute/tokendata/usdc/usdc_int_test.go @@ -56,7 +56,7 @@ type usdcMessage struct { // TODO actual tokenData bytes would be abi encoded, but we can't use abi in the repo so only // passing attestation as it is func (u *usdcMessage) tokenData() []byte { - var result map[string]interface{} + var result map[string]any err := json.Unmarshal([]byte(u.attestationResponse), &result) if err != nil { diff --git a/execute/tracked_test.go b/execute/tracked_test.go index 31e63b9425..7447813483 100644 --- a/execute/tracked_test.go +++ b/execute/tracked_test.go @@ -44,7 +44,7 @@ func Test_LatencyIsTracked(t *testing.T) { tracked := NewTrackedPlugin(origin, lggr, reporter, ocrtypecodec.DefaultExecCodec) count := 100 - for i := 0; i < count; i++ { + for range count { q, err := tracked.Query(ctx, ocr3types.OutcomeContext{}) require.Equal(t, query, q) require.NoError(t, err) @@ -87,7 +87,7 @@ func Test_ErrorIsTrackedWhenOriginReturns(t *testing.T) { tracked := NewTrackedPlugin(origin, lggr, reporter, ocrtypecodec.DefaultExecCodec) count := 100 - for i := 0; i < count; i++ { + for range count { _, err = tracked.Outcome( tests.Context(t), ocr3types.OutcomeContext{}, types.Query{}, []types.AttributedObservation{}, ) diff --git a/internal/libs/slicelib/bits.go b/internal/libs/slicelib/bits.go index ab4b0d7198..786a2df747 100644 --- a/internal/libs/slicelib/bits.go +++ b/internal/libs/slicelib/bits.go @@ -5,7 +5,7 @@ import "math/big" // BoolsToBitFlags transforms a list of boolean flags to a *big.Int encoded number. func BoolsToBitFlags(bools []bool) *big.Int { encodedFlags := big.NewInt(0) - for i := 0; i < len(bools); i++ { + for i := range bools { if bools[i] { encodedFlags.SetBit(encodedFlags, i, 1) } @@ -15,7 +15,7 @@ func BoolsToBitFlags(bools []bool) *big.Int { func BitFlagsToBools(encodedFlags *big.Int, size int) []bool { var bools []bool - for i := 0; i < size; i++ { + for i := range size { bools = append(bools, encodedFlags.Bit(i) == 1) } return bools diff --git a/internal/libs/slicelib/generic.go b/internal/libs/slicelib/generic.go index 3559ec9746..eb42bf2139 100644 --- a/internal/libs/slicelib/generic.go +++ b/internal/libs/slicelib/generic.go @@ -4,6 +4,7 @@ import ( "sort" mapset "github.com/deckarep/golang-set/v2" + "slices" ) // CountUnique counts the unique items of the provided slice. @@ -44,8 +45,6 @@ func Map[T any, T2 any](slice []T, mapper func(T) T2) []T2 { func ToSortedSlice[T ~int | ~int64 | ~uint64](set mapset.Set[T]) []T { elements := set.ToSlice() - sort.Slice(elements, func(i, j int) bool { - return elements[i] < elements[j] - }) + slices.Sort(elements) return elements } diff --git a/internal/mocks/inmem/ccipreader_inmem.go b/internal/mocks/inmem/ccipreader_inmem.go index c6220e01a2..078ad4e612 100644 --- a/internal/mocks/inmem/ccipreader_inmem.go +++ b/internal/mocks/inmem/ccipreader_inmem.go @@ -15,6 +15,7 @@ import ( cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" "github.com/smartcontractkit/chainlink-common/pkg/types" + "slices" ) type MessagesWithMetadata struct { @@ -109,7 +110,7 @@ func (r InMemoryCCIPReader) ExecutedMessages( } unqSeqNums := mapset.NewSet(seqNums...).ToSlice() - sort.Slice(unqSeqNums, func(i, j int) bool { return unqSeqNums[i] < unqSeqNums[j] }) + slices.Sort(unqSeqNums) ret[source] = unqSeqNums } return ret, nil diff --git a/internal/mocks/null_logger.go b/internal/mocks/null_logger.go index 255cf96982..491ca0937f 100644 --- a/internal/mocks/null_logger.go +++ b/internal/mocks/null_logger.go @@ -10,39 +10,39 @@ var NullLogger logger.Logger = &nullLogger{} type nullLogger struct{} -func (l *nullLogger) With(args ...interface{}) logger.Logger { return l } -func (l *nullLogger) Named(name string) logger.Logger { return l } -func (l *nullLogger) SetLogLevel(_ zapcore.Level) {} - -func (l *nullLogger) Trace(args ...interface{}) {} -func (l *nullLogger) Debug(args ...interface{}) {} -func (l *nullLogger) Info(args ...interface{}) {} -func (l *nullLogger) Warn(args ...interface{}) {} -func (l *nullLogger) Error(args ...interface{}) {} -func (l *nullLogger) Critical(args ...interface{}) {} -func (l *nullLogger) Panic(args ...interface{}) {} -func (l *nullLogger) Fatal(args ...interface{}) {} - -func (l *nullLogger) Tracef(format string, values ...interface{}) {} -func (l *nullLogger) Debugf(format string, values ...interface{}) {} -func (l *nullLogger) Infof(format string, values ...interface{}) {} -func (l *nullLogger) Warnf(format string, values ...interface{}) {} -func (l *nullLogger) Errorf(format string, values ...interface{}) {} -func (l *nullLogger) Criticalf(format string, values ...interface{}) {} -func (l *nullLogger) Panicf(format string, values ...interface{}) {} -func (l *nullLogger) Fatalf(format string, values ...interface{}) {} - -func (l *nullLogger) Tracew(msg string, keysAndValues ...interface{}) {} -func (l *nullLogger) Debugw(msg string, keysAndValues ...interface{}) {} -func (l *nullLogger) Infow(msg string, keysAndValues ...interface{}) {} -func (l *nullLogger) Warnw(msg string, keysAndValues ...interface{}) {} -func (l *nullLogger) Errorw(msg string, keysAndValues ...interface{}) {} -func (l *nullLogger) Criticalw(msg string, keysAndValues ...interface{}) {} -func (l *nullLogger) Panicw(msg string, keysAndValues ...interface{}) {} -func (l *nullLogger) Fatalw(msg string, keysAndValues ...interface{}) {} +func (l *nullLogger) With(args ...any) logger.Logger { return l } +func (l *nullLogger) Named(name string) logger.Logger { return l } +func (l *nullLogger) SetLogLevel(_ zapcore.Level) {} + +func (l *nullLogger) Trace(args ...any) {} +func (l *nullLogger) Debug(args ...any) {} +func (l *nullLogger) Info(args ...any) {} +func (l *nullLogger) Warn(args ...any) {} +func (l *nullLogger) Error(args ...any) {} +func (l *nullLogger) Critical(args ...any) {} +func (l *nullLogger) Panic(args ...any) {} +func (l *nullLogger) Fatal(args ...any) {} + +func (l *nullLogger) Tracef(format string, values ...any) {} +func (l *nullLogger) Debugf(format string, values ...any) {} +func (l *nullLogger) Infof(format string, values ...any) {} +func (l *nullLogger) Warnf(format string, values ...any) {} +func (l *nullLogger) Errorf(format string, values ...any) {} +func (l *nullLogger) Criticalf(format string, values ...any) {} +func (l *nullLogger) Panicf(format string, values ...any) {} +func (l *nullLogger) Fatalf(format string, values ...any) {} + +func (l *nullLogger) Tracew(msg string, keysAndValues ...any) {} +func (l *nullLogger) Debugw(msg string, keysAndValues ...any) {} +func (l *nullLogger) Infow(msg string, keysAndValues ...any) {} +func (l *nullLogger) Warnw(msg string, keysAndValues ...any) {} +func (l *nullLogger) Errorw(msg string, keysAndValues ...any) {} +func (l *nullLogger) Criticalw(msg string, keysAndValues ...any) {} +func (l *nullLogger) Panicw(msg string, keysAndValues ...any) {} +func (l *nullLogger) Fatalw(msg string, keysAndValues ...any) {} func (l *nullLogger) Sync() error { return nil } func (l *nullLogger) Helper(skip int) logger.Logger { return l } func (l *nullLogger) Name() string { return "nullLogger" } -func (l *nullLogger) Recover(panicErr interface{}) {} +func (l *nullLogger) Recover(panicErr any) {} diff --git a/internal/plugincommon/chain_support.go b/internal/plugincommon/chain_support.go index 1f31645f73..2ae2423ea2 100644 --- a/internal/plugincommon/chain_support.go +++ b/internal/plugincommon/chain_support.go @@ -14,6 +14,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/internal/libs/slicelib" "github.com/smartcontractkit/chainlink-ccip/internal/reader" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) // ChainSupport contains functions that enable an oracle to determine which chains are accessible by itself and @@ -72,7 +73,7 @@ func (c ccipChainSupport) KnownSourceChainsSlice() ([]cciptypes.ChainSelector, e } allChains := allChainsSet.ToSlice() - sort.Slice(allChains, func(i, j int) bool { return allChains[i] < allChains[j] }) + slices.Sort(allChains) sourceChains := slicelib.Filter(allChains, func(ch cciptypes.ChainSelector) bool { return ch != c.destChain }) diff --git a/internal/plugincommon/consensus/consensus.go b/internal/plugincommon/consensus/consensus.go index 8e29f4110f..ff4288a5c6 100644 --- a/internal/plugincommon/consensus/consensus.go +++ b/internal/plugincommon/consensus/consensus.go @@ -8,6 +8,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/logger" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) // GetConsensusMap takes a mapping from chains to a list of items, @@ -132,7 +133,7 @@ func GetOrderedConsensus[K comparable, T cmp.Ordered]( continue } - sort.Slice(items, func(i, j int) bool { return items[i] < items[j] }) + slices.Sort(items) result[key] = items[minThresh] } return result diff --git a/internal/plugincommon/consensus/consensus_test.go b/internal/plugincommon/consensus/consensus_test.go index 997528c5b4..e3f648fae5 100644 --- a/internal/plugincommon/consensus/consensus_test.go +++ b/internal/plugincommon/consensus/consensus_test.go @@ -237,7 +237,7 @@ func TestMakeConstantThreshold(t *testing.T) { f := 3 threshold := MakeConstantThreshold[cciptypes.ChainSelector](Threshold(f)) - for i := 0; i < 10; i++ { + for i := range 10 { thresh, ok := threshold.Get(cciptypes.ChainSelector(i)) assert.True(t, ok) assert.Equal(t, Threshold(f), thresh) @@ -247,7 +247,7 @@ func TestMakeConstantThreshold(t *testing.T) { f := 3.5 threshold := MakeConstantThreshold[float64](Threshold(f)) - for i := 0; i < 10; i++ { + for i := range 10 { thresh, ok := threshold.Get(float64(i)) assert.True(t, ok) assert.Equal(t, Threshold(f), thresh) diff --git a/internal/plugincommon/consensus/min_observation.go b/internal/plugincommon/consensus/min_observation.go index ae6aed8f29..d60788c4ca 100644 --- a/internal/plugincommon/consensus/min_observation.go +++ b/internal/plugincommon/consensus/min_observation.go @@ -35,7 +35,7 @@ type minObservation[T any] struct { func NewMinObservation[T any](minThreshold Threshold, idFunc func(T) [32]byte) MinObservation[T] { if idFunc == nil { idFunc = func(data T) [32]byte { - return sha3.Sum256([]byte(fmt.Sprintf("%v", data))) + return sha3.Sum256(fmt.Appendf(nil, "%v", data)) } } return &minObservation[T]{ diff --git a/internal/plugincommon/consensus/min_observation_test.go b/internal/plugincommon/consensus/min_observation_test.go index b488002852..42aa79c101 100644 --- a/internal/plugincommon/consensus/min_observation_test.go +++ b/internal/plugincommon/consensus/min_observation_test.go @@ -94,7 +94,7 @@ func Test_CommitReportValidator_ExecutePluginCommitData(t *testing.T) { // Initialize the minObservation idFunc := func(data exectypes.CommitData) [32]byte { - return sha3.Sum256([]byte(fmt.Sprintf("%v", data))) + return sha3.Sum256(fmt.Appendf(nil, "%v", data)) } validator := consensus.NewMinObservation[exectypes.CommitData](tt.min, idFunc) for _, report := range tt.reports { @@ -128,7 +128,7 @@ func Test_CommitReportValidator_Generics(t *testing.T) { // Initialize the minObservation idFunc := func(data Generic) [32]byte { - return sha3.Sum256([]byte(fmt.Sprintf("%v", data))) + return sha3.Sum256(fmt.Appendf(nil, "%v", data)) } validator := consensus.NewMinObservation[Generic](2, idFunc) diff --git a/internal/plugincommon/consensus/oracle_min_observation.go b/internal/plugincommon/consensus/oracle_min_observation.go index e6b1305904..97c667c3b0 100644 --- a/internal/plugincommon/consensus/oracle_min_observation.go +++ b/internal/plugincommon/consensus/oracle_min_observation.go @@ -38,7 +38,7 @@ type oracleMinObservation[T any] struct { func NewOracleMinObservation[T any](minThreshold Threshold, idFunc func(T) [32]byte) OracleMinObservation[T] { if idFunc == nil { idFunc = func(data T) [32]byte { - return sha3.Sum256([]byte(fmt.Sprintf("%v", data))) + return sha3.Sum256(fmt.Appendf(nil, "%v", data)) } } return &oracleMinObservation[T]{ diff --git a/internal/plugincommon/transmitters.go b/internal/plugincommon/transmitters.go index bdfa7227af..c52673d198 100644 --- a/internal/plugincommon/transmitters.go +++ b/internal/plugincommon/transmitters.go @@ -7,6 +7,7 @@ import ( "github.com/smartcontractkit/libocr/commontypes" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" + "slices" ) // GetTransmissionSchedule returns a TransmissionSchedule for the provided oracles. @@ -35,7 +36,7 @@ func GetTransmissionSchedule( } // transmissionSchedule must be deterministic - sort.Slice(transmitters, func(i, j int) bool { return transmitters[i] < transmitters[j] }) + slices.Sort(transmitters) transmissionDelays := make([]time.Duration, len(transmitters)) diff --git a/internal/reader/home_chain.go b/internal/reader/home_chain.go index 9eef7b2e4a..3b920dc994 100644 --- a/internal/reader/home_chain.go +++ b/internal/reader/home_chain.go @@ -135,7 +135,7 @@ func (r *homeChainPoller) fetchAndSetConfigs(ctx context.Context) error { ctx, r.ccipConfigBoundContract.ReadIdentifier(consts.MethodNameGetAllChainConfigs), primitives.Unconfirmed, - map[string]interface{}{ + map[string]any{ "pageIndex": pageIndex, "pageSize": defaultConfigPageSize, }, diff --git a/pkg/logutil/logutil_test.go b/pkg/logutil/logutil_test.go index a481428176..920d5ca34d 100644 --- a/pkg/logutil/logutil_test.go +++ b/pkg/logutil/logutil_test.go @@ -22,7 +22,7 @@ func TestLogWrapper(t *testing.T) { digest[0] = 1 digest[31] = 31 - expected := map[string]interface{}{ + expected := map[string]any{ donIDLoggerKey: donID, oracleIDLoggerKey: oracleID, pluginLoggerKey: "TestPlugin", @@ -54,7 +54,7 @@ func TestLogCopy(t *testing.T) { digest[0] = 1 digest[31] = 31 - expected := map[string]interface{}{ + expected := map[string]any{ donIDLoggerKey: donID, oracleIDLoggerKey: oracleID, pluginLoggerKey: "TestPlugin", diff --git a/pkg/ocrtypecodec/v1/translate.go b/pkg/ocrtypecodec/v1/translate.go index e5cd5d308a..e63488dc84 100644 --- a/pkg/ocrtypecodec/v1/translate.go +++ b/pkg/ocrtypecodec/v1/translate.go @@ -15,6 +15,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/pkg/ocrtypecodec/v1/ocrtypecodecpb" "github.com/smartcontractkit/chainlink-ccip/pkg/reader" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "maps" ) type protoTranslator struct{} @@ -852,9 +853,7 @@ func (t *protoTranslator) nonceObservationsToProto( for chainSel, nonceMap := range observations { addrToNonce := make(map[string]uint64, len(nonceMap)) - for addr, nonce := range nonceMap { - addrToNonce[addr] = nonce - } + maps.Copy(addrToNonce, nonceMap) nonceObservations[uint64(chainSel)] = &ocrtypecodecpb.StringAddrToNonce{Nonces: addrToNonce} } @@ -871,9 +870,7 @@ func (t *protoTranslator) nonceObservationsFromProto( for chainSel, nonceMap := range pbObservations { innerMap := make(map[string]uint64, len(nonceMap.Nonces)) - for addr, nonce := range nonceMap.Nonces { - innerMap[addr] = nonce - } + maps.Copy(innerMap, nonceMap.Nonces) nonces[cciptypes.ChainSelector(chainSel)] = innerMap } diff --git a/pkg/ocrtypecodec/v1/v1_test.go b/pkg/ocrtypecodec/v1/v1_test.go index 7686f34e3e..115876f673 100644 --- a/pkg/ocrtypecodec/v1/v1_test.go +++ b/pkg/ocrtypecodec/v1/v1_test.go @@ -45,10 +45,10 @@ func TestCommitQuery(t *testing.T) { t, gen.name, gen.commitQuery(), - func(b []byte) (interface{}, error) { return jsonCodec.DecodeQuery(b) }, - func(i interface{}) ([]byte, error) { return jsonCodec.EncodeQuery(i.(committypes.Query)) }, - func(b []byte) (interface{}, error) { return protoCodec.DecodeQuery(b) }, - func(i interface{}) ([]byte, error) { return protoCodec.EncodeQuery(i.(committypes.Query)) }, + func(b []byte) (any, error) { return jsonCodec.DecodeQuery(b) }, + func(i any) ([]byte, error) { return jsonCodec.EncodeQuery(i.(committypes.Query)) }, + func(b []byte) (any, error) { return protoCodec.DecodeQuery(b) }, + func(i any) ([]byte, error) { return protoCodec.EncodeQuery(i.(committypes.Query)) }, ) results = append(results, result) } @@ -65,10 +65,10 @@ func TestCommitObservation(t *testing.T) { t, gen.name, gen.commitObservation(), - func(b []byte) (interface{}, error) { return jsonCodec.DecodeObservation(b) }, - func(i interface{}) ([]byte, error) { return jsonCodec.EncodeObservation(i.(committypes.Observation)) }, - func(b []byte) (interface{}, error) { return protoCodec.DecodeObservation(b) }, - func(i interface{}) ([]byte, error) { return protoCodec.EncodeObservation(i.(committypes.Observation)) }, + func(b []byte) (any, error) { return jsonCodec.DecodeObservation(b) }, + func(i any) ([]byte, error) { return jsonCodec.EncodeObservation(i.(committypes.Observation)) }, + func(b []byte) (any, error) { return protoCodec.DecodeObservation(b) }, + func(i any) ([]byte, error) { return protoCodec.EncodeObservation(i.(committypes.Observation)) }, ) results = append(results, result) } @@ -85,10 +85,10 @@ func TestCommitOutcome(t *testing.T) { t, gen.name, gen.commitOutcome(), - func(b []byte) (interface{}, error) { return jsonCodec.DecodeOutcome(b) }, - func(i interface{}) ([]byte, error) { return jsonCodec.EncodeOutcome(i.(committypes.Outcome)) }, - func(b []byte) (interface{}, error) { return protoCodec.DecodeOutcome(b) }, - func(i interface{}) ([]byte, error) { return protoCodec.EncodeOutcome(i.(committypes.Outcome)) }, + func(b []byte) (any, error) { return jsonCodec.DecodeOutcome(b) }, + func(i any) ([]byte, error) { return jsonCodec.EncodeOutcome(i.(committypes.Outcome)) }, + func(b []byte) (any, error) { return protoCodec.DecodeOutcome(b) }, + func(i any) ([]byte, error) { return protoCodec.EncodeOutcome(i.(committypes.Outcome)) }, ) results = append(results, result) } @@ -105,10 +105,10 @@ func TestExecObservation(t *testing.T) { t, gen.name, gen.execObservation(), - func(b []byte) (interface{}, error) { return jsonCodec.DecodeObservation(b) }, - func(i interface{}) ([]byte, error) { return jsonCodec.EncodeObservation(i.(exectypes.Observation)) }, - func(b []byte) (interface{}, error) { return protoCodec.DecodeObservation(b) }, - func(i interface{}) ([]byte, error) { return protoCodec.EncodeObservation(i.(exectypes.Observation)) }, + func(b []byte) (any, error) { return jsonCodec.DecodeObservation(b) }, + func(i any) ([]byte, error) { return jsonCodec.EncodeObservation(i.(exectypes.Observation)) }, + func(b []byte) (any, error) { return protoCodec.DecodeObservation(b) }, + func(i any) ([]byte, error) { return protoCodec.EncodeObservation(i.(exectypes.Observation)) }, ) results = append(results, result) } @@ -125,10 +125,10 @@ func TestExecOutcome(t *testing.T) { t, gen.name, gen.execOutcome(), - func(b []byte) (interface{}, error) { return jsonCodec.DecodeOutcome(b) }, - func(i interface{}) ([]byte, error) { return jsonCodec.EncodeOutcome(i.(exectypes.Outcome)) }, - func(b []byte) (interface{}, error) { return protoCodec.DecodeOutcome(b) }, - func(i interface{}) ([]byte, error) { return protoCodec.EncodeOutcome(i.(exectypes.Outcome)) }, + func(b []byte) (any, error) { return jsonCodec.DecodeOutcome(b) }, + func(i any) ([]byte, error) { return jsonCodec.EncodeOutcome(i.(exectypes.Outcome)) }, + func(b []byte) (any, error) { return protoCodec.DecodeOutcome(b) }, + func(i any) ([]byte, error) { return protoCodec.EncodeOutcome(i.(exectypes.Outcome)) }, ) results = append(results, result) } @@ -140,11 +140,11 @@ func TestExecOutcome(t *testing.T) { func runBenchmark( t *testing.T, name string, - obj interface{}, - decodeJSONFunc func([]byte) (interface{}, error), - encodeJSONFunc func(interface{}) ([]byte, error), - decodeProtoFunc func([]byte) (interface{}, error), - encodeProtoFunc func(interface{}) ([]byte, error), + obj any, + decodeJSONFunc func([]byte) (any, error), + encodeJSONFunc func(any) ([]byte, error), + decodeProtoFunc func([]byte) (any, error), + encodeProtoFunc func(any) ([]byte, error), ) resultData { result := resultData{name: name} @@ -307,7 +307,7 @@ var ( func (d *dataGenerator) commitQuery() committypes.Query { sigs := make([]*serialization.EcdsaSignature, d.numRmnNodes) - for i := 0; i < d.numRmnNodes; i++ { + for i := range d.numRmnNodes { sigs[i] = &serialization.EcdsaSignature{ R: randomBytes(32), S: randomBytes(32), @@ -315,7 +315,7 @@ func (d *dataGenerator) commitQuery() committypes.Query { } laneUpdates := make([]*serialization.FixedDestLaneUpdate, d.numSourceChains) - for i := 0; i < d.numSourceChains; i++ { + for i := range d.numSourceChains { laneUpdates[i] = &serialization.FixedDestLaneUpdate{ LaneSource: &serialization.LaneSource{ SourceChainSelector: rand.Uint64(), @@ -352,7 +352,7 @@ func (d *dataGenerator) commitObservation() committypes.Observation { nativeTokenPrices := make(map[cciptypes.ChainSelector]cciptypes.BigInt, d.numSourceChains) chainFeeUpdates := make(map[cciptypes.ChainSelector]chainfee.Update, d.numSourceChains) - for i := 0; i < d.numSourceChains; i++ { + for range d.numSourceChains { fChain[cciptypes.ChainSelector(rand.Uint64())] = rand.Intn(256) feeComponents[cciptypes.ChainSelector(rand.Uint64())] = types.ChainFeeComponents{ @@ -374,7 +374,7 @@ func (d *dataGenerator) commitObservation() committypes.Observation { feedTokenPrices := make(map[cciptypes.UnknownEncodedAddress]cciptypes.BigInt, d.numPricedTokens) feeQuoterTokenUpdates := make(map[cciptypes.UnknownEncodedAddress]cciptypes.TimestampedBig, d.numPricedTokens) - for i := 0; i < d.numPricedTokens; i++ { + for range d.numPricedTokens { feedTokenPrices[cciptypes.UnknownEncodedAddress(genRandomString(40))] = randBigInt() feeQuoterTokenUpdates[cciptypes.UnknownEncodedAddress(genRandomString(40))] = cciptypes.TimestampedBig{ @@ -412,7 +412,7 @@ func (d *dataGenerator) commitObservation() committypes.Observation { func (d *dataGenerator) commitOutcome() committypes.Outcome { rmnReportSigs := make([]cciptypes.RMNECDSASignature, d.numRmnNodes) - for i := 0; i < d.numRmnNodes; i++ { + for i := range d.numRmnNodes { rmnReportSigs[i] = cciptypes.RMNECDSASignature{ R: randomBytes32(), S: randomBytes32(), @@ -420,12 +420,12 @@ func (d *dataGenerator) commitOutcome() committypes.Outcome { } tokenPrices := make(cciptypes.TokenPriceMap) - for i := 0; i < d.numPricedTokens; i++ { + for range d.numPricedTokens { tokenPrices[cciptypes.UnknownEncodedAddress(genRandomString(40))] = randBigInt() } gasPrices := make([]cciptypes.GasPriceChain, d.numSourceChains) - for i := 0; i < d.numSourceChains; i++ { + for i := range d.numSourceChains { gasPrices[i] = cciptypes.GasPriceChain{ ChainSel: cciptypes.ChainSelector(rand.Uint64()), GasPrice: randBigInt(), @@ -465,7 +465,7 @@ func (d *dataGenerator) execObservation() exectypes.Observation { msgHashObservations := make(map[cciptypes.ChainSelector]map[cciptypes.SeqNum]cciptypes.Bytes32) nonces := make(map[cciptypes.ChainSelector]map[string]uint64) msgObservations := make(map[cciptypes.ChainSelector]map[cciptypes.SeqNum]cciptypes.Message) - for i := 0; i < d.numSourceChains; i++ { + for range d.numSourceChains { chainSel := cciptypes.ChainSelector(rand.Uint64()) nonces[chainSel] = map[string]uint64{ genRandomString(5): rand.Uint64(), @@ -475,7 +475,7 @@ func (d *dataGenerator) execObservation() exectypes.Observation { msgHashObservations[chainSel] = make(map[cciptypes.SeqNum]cciptypes.Bytes32, d.numMessagesPerChain) msgObservations[chainSel] = make(map[cciptypes.SeqNum]cciptypes.Message, d.numMessagesPerChain) - for j := 0; j < d.numMessagesPerChain; j++ { + for range d.numMessagesPerChain { tokenDataObservations[chainSel][cciptypes.SeqNum(rand.Uint64())] = exectypes.MessageTokenData{ TokenData: []exectypes.TokenData{ { @@ -494,7 +494,7 @@ func (d *dataGenerator) execObservation() exectypes.Observation { } commitReports := make(map[cciptypes.ChainSelector][]exectypes.CommitData) - for i := 0; i < d.numSourceChains; i++ { + for range d.numSourceChains { commitReports[cciptypes.ChainSelector(rand.Uint64())] = []exectypes.CommitData{ { SourceChain: cciptypes.ChainSelector(rand.Uint64()), @@ -540,7 +540,7 @@ func (d *dataGenerator) execOutcome() exectypes.Outcome { commitReports := make([]exectypes.CommitData, d.numSourceChains) msgs := genMessages(d.numMessagesPerChain, d.numTokensPerMsg) - for i := 0; i < d.numSourceChains; i++ { + for i := range d.numSourceChains { commitReports[i] = exectypes.CommitData{ SourceChain: cciptypes.ChainSelector(rand.Uint64()), OnRampAddress: randomBytes(40), @@ -570,9 +570,9 @@ func (d *dataGenerator) execOutcome() exectypes.Outcome { } chainReports := make([]cciptypes.ExecutePluginReportSingleChain, d.numSourceChains) - for i := 0; i < d.numSourceChains; i++ { + for i := range d.numSourceChains { tokenData := make([][][]byte, 0) - for j := 0; j < d.numTokensPerMsg/4; j++ { + for range d.numTokensPerMsg / 4 { tokenData = append(tokenData, [][]byte{randomBytes(32), randomBytes(32), randomBytes(32), randomBytes(32)}) } @@ -599,15 +599,15 @@ func (d *dataGenerator) execOutcome() exectypes.Outcome { func genDiscoveryObservation(numSourceChains, numContractsPerChain int) dt.Observation { fChain := make(map[cciptypes.ChainSelector]int, numSourceChains) - for i := 0; i < numSourceChains; i++ { + for range numSourceChains { fChain[cciptypes.ChainSelector(rand.Uint64())] = rand.Intn(256) } contractAddresses := make(reader.ContractAddresses, numContractsPerChain) - for i := 0; i < numContractsPerChain; i++ { + for i := range numContractsPerChain { contractName := fmt.Sprintf("contract-%d", i) contractAddresses[contractName] = make(map[cciptypes.ChainSelector]cciptypes.UnknownAddress, numSourceChains) - for j := 0; j < numSourceChains; j++ { + for range numSourceChains { contractAddresses[contractName][cciptypes.ChainSelector(rand.Uint64())] = randomBytes(40) } } @@ -620,7 +620,7 @@ func genDiscoveryObservation(numSourceChains, numContractsPerChain int) dt.Obser func genMessages(numMsgs, numTokensPerMsg int) []cciptypes.Message { tokenAmounts := make([]cciptypes.RampTokenAmount, numTokensPerMsg) - for i := 0; i < numTokensPerMsg; i++ { + for i := range numTokensPerMsg { tokenAmounts[i] = cciptypes.RampTokenAmount{ SourcePoolAddress: randomBytes(40), DestTokenAddress: randomBytes(40), @@ -631,7 +631,7 @@ func genMessages(numMsgs, numTokensPerMsg int) []cciptypes.Message { } msgs := make([]cciptypes.Message, numMsgs) - for i := 0; i < numMsgs; i++ { + for i := range numMsgs { msgs[i] = cciptypes.Message{ Header: cciptypes.RampMessageHeader{ MessageID: randomBytes32(), @@ -658,7 +658,7 @@ func genMessages(numMsgs, numTokensPerMsg int) []cciptypes.Message { func genMerkleRootChain(n int) []cciptypes.MerkleRootChain { mrcs := make([]cciptypes.MerkleRootChain, n) - for i := 0; i < n; i++ { + for i := range n { mrcs[i] = cciptypes.MerkleRootChain{ ChainSel: cciptypes.ChainSelector(rand.Uint64()), OnRampAddress: randomBytes(40), @@ -671,7 +671,7 @@ func genMerkleRootChain(n int) []cciptypes.MerkleRootChain { func genRmnEnabledChains(n int) map[cciptypes.ChainSelector]bool { m := make(map[cciptypes.ChainSelector]bool) - for i := 0; i < n; i++ { + for range n { m[cciptypes.ChainSelector(rand.Uint64())] = rand.Int()%2 == 0 } return m @@ -679,7 +679,7 @@ func genRmnEnabledChains(n int) map[cciptypes.ChainSelector]bool { func genSeqNumChain(n int) []plugintypes.SeqNumChain { chains := make([]plugintypes.SeqNumChain, n) - for i := 0; i < n; i++ { + for i := range n { chains[i] = plugintypes.SeqNumChain{ ChainSel: cciptypes.ChainSelector(rand.Uint64()), SeqNum: cciptypes.SeqNum(rand.Uint64()), @@ -690,7 +690,7 @@ func genSeqNumChain(n int) []plugintypes.SeqNumChain { func genRmnRemoteConfig(numSigners int) cciptypes.RemoteConfig { rmnSigners := make([]cciptypes.RemoteSignerInfo, numSigners) - for i := 0; i < numSigners; i++ { + for i := range numSigners { rmnSigners[i] = cciptypes.RemoteSignerInfo{ OnchainPublicKey: randomBytes(20), NodeIndex: rand.Uint64(), @@ -713,7 +713,7 @@ func randBigInt() cciptypes.BigInt { func genChainRanges(n int) []plugintypes.ChainRange { ranges := make([]plugintypes.ChainRange, n) - for i := 0; i < n; i++ { + for i := range n { ranges[i] = plugintypes.ChainRange{ ChainSel: cciptypes.ChainSelector(rand.Uint64()), SeqNumRange: cciptypes.NewSeqNumRange( @@ -749,7 +749,7 @@ func randomBytes32() [32]byte { func genSeqNums(n int) []cciptypes.SeqNum { seqNums := make([]cciptypes.SeqNum, n) - for i := 0; i < n; i++ { + for i := range n { seqNums[i] = cciptypes.SeqNum(rand.Uint64()) } return seqNums @@ -757,7 +757,7 @@ func genSeqNums(n int) []cciptypes.SeqNum { func genBytes32Slice(n int) []cciptypes.Bytes32 { result := make([]cciptypes.Bytes32, n) - for i := 0; i < n; i++ { + for i := range n { result[i] = randomBytes32() } return result diff --git a/pkg/reader/ccip.go b/pkg/reader/ccip.go index 378901abae..97cdefdbe5 100644 --- a/pkg/reader/ccip.go +++ b/pkg/reader/ccip.go @@ -1084,7 +1084,7 @@ func (r *ccipChainReader) discoverOffRampContracts( // Iterate results in sourceChain selector order so that the router config is deterministic. keys := maps.Keys(sourceConfigs) - sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] }) + slices.Sort(keys) for _, sourceChain := range keys { cfg := sourceConfigs[sourceChain] resp = resp.Append(consts.ContractNameOnRamp, sourceChain, cfg.OnRamp) @@ -1842,7 +1842,7 @@ func (r *ccipChainReader) processOfframpResults( // Define processors for each expected result processors := []resultProcessor{ // CommitLatestOCRConfig - func(val interface{}) error { + func(val any) error { typed, ok := val.(*OCRConfigResponse) if !ok { return fmt.Errorf("invalid type for CommitLatestOCRConfig: %T", val) @@ -1851,7 +1851,7 @@ func (r *ccipChainReader) processOfframpResults( return nil }, // ExecLatestOCRConfig - func(val interface{}) error { + func(val any) error { typed, ok := val.(*OCRConfigResponse) if !ok { return fmt.Errorf("invalid type for ExecLatestOCRConfig: %T", val) @@ -1860,7 +1860,7 @@ func (r *ccipChainReader) processOfframpResults( return nil }, // StaticConfig - func(val interface{}) error { + func(val any) error { typed, ok := val.(*offRampStaticChainConfig) if !ok { return fmt.Errorf("invalid type for StaticConfig: %T", val) @@ -1869,7 +1869,7 @@ func (r *ccipChainReader) processOfframpResults( return nil }, // DynamicConfig - func(val interface{}) error { + func(val any) error { typed, ok := val.(*offRampDynamicChainConfig) if !ok { return fmt.Errorf("invalid type for DynamicConfig: %T", val) diff --git a/pkg/reader/ccip_test.go b/pkg/reader/ccip_test.go index ca9917ec0d..bce9a452ff 100644 --- a/pkg/reader/ccip_test.go +++ b/pkg/reader/ccip_test.go @@ -994,18 +994,18 @@ func TestCCIPChainReader_DiscoverContracts_GetOfframpStaticConfig_Errors(t *test // withReturnValueOverridden is a helper function to override the return value of a mocked out // ExtendedGetLatestValue call. -func withReturnValueOverridden(mapper func(returnVal interface{})) func(ctx context.Context, +func withReturnValueOverridden(mapper func(returnVal any)) func(ctx context.Context, contractName, methodName string, confidenceLevel primitives.ConfidenceLevel, params, - returnVal interface{}) { + returnVal any) { return func(ctx context.Context, contractName, methodName string, confidenceLevel primitives.ConfidenceLevel, params, - returnVal interface{}) { + returnVal any) { mapper(returnVal) } } @@ -1066,8 +1066,8 @@ func TestCCIPChainReader_getFeeQuoterTokenPriceUSD(t *testing.T) { ctx context.Context, readIdentifier string, confidenceLevel primitives.ConfidenceLevel, - params interface{}, - returnVal interface{}, + params any, + returnVal any, ) { givenTokenAddr := params.(map[string]any)["token"].([]byte) if bytes.Equal(tokenAddr, givenTokenAddr) { @@ -1210,9 +1210,9 @@ func TestCCIPChainReader_LinkPriceUSD(t *testing.T) { consts.ContractNameFeeQuoter, consts.MethodNameFeeQuoterGetTokenPrice, primitives.Unconfirmed, - map[string]interface{}{"token": tokenAddr}, + map[string]any{"token": tokenAddr}, mock.Anything, - ).Return(nil).Run(withReturnValueOverridden(func(returnVal interface{}) { + ).Return(nil).Run(withReturnValueOverridden(func(returnVal any) { price := returnVal.(*cciptypes.TimestampedUnixBig) price.Value = big.NewInt(145) })) @@ -1704,7 +1704,7 @@ func TestCCIPChainReader_GetWrappedNativeTokenPriceUSD(t *testing.T) { consts.ContractNameFeeQuoter, consts.MethodNameFeeQuoterGetTokenPrice, primitives.Unconfirmed, - map[string]interface{}{"token": wrappedNative1}, + map[string]any{"token": wrappedNative1}, mock.Anything, ).Run( func( @@ -1727,7 +1727,7 @@ func TestCCIPChainReader_GetWrappedNativeTokenPriceUSD(t *testing.T) { consts.ContractNameFeeQuoter, consts.MethodNameFeeQuoterGetTokenPrice, primitives.Unconfirmed, - map[string]interface{}{"token": wrappedNative2}, + map[string]any{"token": wrappedNative2}, mock.Anything, ).Run( func( @@ -1777,7 +1777,7 @@ func TestCCIPChainReader_GetWrappedNativeTokenPriceUSD(t *testing.T) { consts.ContractNameFeeQuoter, consts.MethodNameFeeQuoterGetTokenPrice, primitives.Unconfirmed, - map[string]interface{}{"token": wrappedNative2}, + map[string]any{"token": wrappedNative2}, mock.Anything, ).Run(func( ctx context.Context, @@ -1821,7 +1821,7 @@ func TestCCIPChainReader_GetWrappedNativeTokenPriceUSD(t *testing.T) { consts.ContractNameFeeQuoter, consts.MethodNameFeeQuoterGetTokenPrice, primitives.Unconfirmed, - map[string]interface{}{"token": wrappedNative1}, + map[string]any{"token": wrappedNative1}, mock.Anything, ).Return(fmt.Errorf("price fetch failed")) diff --git a/pkg/reader/config_poller.go b/pkg/reader/config_poller.go index 4261f207b4..0e023399a5 100644 --- a/pkg/reader/config_poller.go +++ b/pkg/reader/config_poller.go @@ -14,6 +14,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink-common/pkg/types" + "maps" ) // refreshAllKnownChains refreshes all known chains in background using batched requests where possible @@ -589,9 +590,7 @@ func (c *configPoller) GetOfframpSourceChainConfigs( } // Merge the new configs with existing cached results - for chain, config := range newCachedConfigs { - cachedSourceConfigs[chain] = config - } + maps.Copy(cachedSourceConfigs, newCachedConfigs) return cachedSourceConfigs, nil } @@ -770,7 +769,7 @@ func staticSourceChainConfigFromSourceChainConfig(sc SourceChainConfig) StaticSo } // resultProcessor defines a function type for processing individual results -type resultProcessor func(interface{}) error +type resultProcessor func(any) error // Ensure configCache implements ConfigPoller var _ ConfigPoller = (*configPoller)(nil) diff --git a/pkg/reader/config_poller_test.go b/pkg/reader/config_poller_test.go index d4bfe9909a..a06b4eed50 100644 --- a/pkg/reader/config_poller_test.go +++ b/pkg/reader/config_poller_test.go @@ -725,7 +725,7 @@ func TestConfigCache_ConcurrentAccess(t *testing.T) { // Run concurrent fetches on the filled cache const numGoroutines = 10 errCh := make(chan error, numGoroutines) - for i := 0; i < numGoroutines; i++ { + for range numGoroutines { go func() { _, err := cache.GetChainConfig(ctx, chainA) errCh <- err @@ -733,7 +733,7 @@ func TestConfigCache_ConcurrentAccess(t *testing.T) { } // Collect results - for i := 0; i < numGoroutines; i++ { + for range numGoroutines { err := <-errCh require.NoError(t, err) } diff --git a/pkg/reader/curses.go b/pkg/reader/curses.go index 2cf7dc2081..6860024ab8 100644 --- a/pkg/reader/curses.go +++ b/pkg/reader/curses.go @@ -4,6 +4,7 @@ import ( "sort" "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" + "slices" ) // CurseInfo contains cursing information that are fetched from the rmn remote contract. @@ -27,7 +28,7 @@ func (ci CurseInfo) NonCursedSourceChains(inputChains []ccipocr3.ChainSelector) sourceChains = append(sourceChains, ch) } } - sort.Slice(sourceChains, func(i, j int) bool { return sourceChains[i] < sourceChains[j] }) + slices.Sort(sourceChains) return sourceChains } diff --git a/pkg/reader/rmn_home_poller.go b/pkg/reader/rmn_home_poller.go index ad02e6d909..88dce6cba0 100644 --- a/pkg/reader/rmn_home_poller.go +++ b/pkg/reader/rmn_home_poller.go @@ -238,7 +238,7 @@ func (r *rmnHomePoller) fetchAndSetRmnHomeConfigs(ctx context.Context) error { ctx, r.rmnHomeBoundContract.ReadIdentifier(consts.MethodNameGetAllConfigs), primitives.Unconfirmed, - map[string]interface{}{}, + map[string]any{}, &activeAndCandidateConfigs, ) if err != nil { @@ -341,7 +341,7 @@ func convertOnChainConfigToRMNHomeChainConfig( for _, chain := range cfg.DynamicConfig.SourceChains { homeFMap[chain.ChainSelector] = int(chain.FObserve) - for j := 0; j < len(nodes); j++ { + for j := range nodes { isObserver, err := isNodeObserver(chain, j, len(nodes)) if err != nil { lggr.Warnw("failed to check if node is observer", "err", err) diff --git a/pkg/reader/rmn_home_test.go b/pkg/reader/rmn_home_test.go index 844e7710cc..c16d8637a8 100644 --- a/pkg/reader/rmn_home_test.go +++ b/pkg/reader/rmn_home_test.go @@ -108,7 +108,7 @@ func Test_CachingInstances(t *testing.T) { pollers := make([]*rmnHome, 1000) eg := new(errgroup.Group) - for i := 0; i < 1000; i++ { + for i := range 1000 { j := i eg.Go(func() error { pollers[j] = newRMNHomeCasted(ctx, t, lggr, chainSelector, address, chain1) @@ -120,7 +120,7 @@ func Test_CachingInstances(t *testing.T) { // 999 closed, but still one reference remains therefore bgPoller is running eg = new(errgroup.Group) - for i := 0; i < 999; i++ { + for i := range 999 { j := i eg.Go(func() error { requirePollerStarted(t, pollers[j]) diff --git a/pkg/reader/usdc_reader.go b/pkg/reader/usdc_reader.go index 922401c7a2..24615d186a 100644 --- a/pkg/reader/usdc_reader.go +++ b/pkg/reader/usdc_reader.go @@ -17,6 +17,7 @@ import ( "github.com/smartcontractkit/chainlink-ccip/pkg/contractreader" cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3" "github.com/smartcontractkit/chainlink-ccip/pluginconfig" + "maps" ) type USDCMessageReader interface { @@ -123,9 +124,7 @@ func AllAvailableDomains() map[uint64]uint32 { } destDomains := make(map[uint64]uint32) - for k, v := range CCTPDestDomains { - destDomains[k] = v - } + maps.Copy(destDomains, CCTPDestDomains) for i, chainID := range chainIDs { chainSelector, _ := sel.SelectorFromChainId(chainID) diff --git a/pkg/reader/usdc_reader_test.go b/pkg/reader/usdc_reader_test.go index f09f1de24f..0d88e76673 100644 --- a/pkg/reader/usdc_reader_test.go +++ b/pkg/reader/usdc_reader_test.go @@ -252,7 +252,7 @@ func Test_USDCMessageReader_MessagesByTokenID(t *testing.T) { func Test_MessageSentEvent_unpackID(t *testing.T) { nonEmptyEvent := eventID{} - for i := 0; i < 32; i++ { + for i := range 32 { nonEmptyEvent[i] = byte(i) } diff --git a/pkg/types/ccipocr3/chain_accessor.go b/pkg/types/ccipocr3/chain_accessor.go index fa2556e9d5..7d47b0b9e5 100644 --- a/pkg/types/ccipocr3/chain_accessor.go +++ b/pkg/types/ccipocr3/chain_accessor.go @@ -8,6 +8,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/types" "github.com/smartcontractkit/chainlink-common/pkg/types/query/primitives" + "slices" ) // AccessorMetadata contains metadata about the chain accessor. @@ -345,7 +346,7 @@ func (ci CurseInfo) NonCursedSourceChains(inputChains []ChainSelector) []ChainSe sourceChains = append(sourceChains, ch) } } - sort.Slice(sourceChains, func(i, j int) bool { return sourceChains[i] < sourceChains[j] }) + slices.Sort(sourceChains) return sourceChains } diff --git a/pkg/types/ccipocr3/common_types.go b/pkg/types/ccipocr3/common_types.go index 744582466f..9195e0a582 100644 --- a/pkg/types/ccipocr3/common_types.go +++ b/pkg/types/ccipocr3/common_types.go @@ -73,7 +73,7 @@ func (b Bytes) String() string { } func (b Bytes) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf(`"%s"`, b.String())), nil + return fmt.Appendf(nil, `"%s"`, b.String()), nil } func (b *Bytes) UnmarshalJSON(data []byte) error { @@ -129,7 +129,7 @@ func (b Bytes32) IsEmpty() bool { } func (b Bytes32) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf(`"%s"`, b.String())), nil + return fmt.Appendf(nil, `"%s"`, b.String()), nil } func (b *Bytes32) UnmarshalJSON(data []byte) error { @@ -176,7 +176,7 @@ func (b BigInt) MarshalJSON() ([]byte, error) { if b.Int == nil { return []byte("null"), nil } - return []byte(fmt.Sprintf(`"%s"`, b.String())), nil + return fmt.Appendf(nil, `"%s"`, b.String()), nil } func (b *BigInt) UnmarshalJSON(p []byte) error { diff --git a/pkg/types/ccipocr3/plugin_execute_types.go b/pkg/types/ccipocr3/plugin_execute_types.go index b55a3319bf..fc574bac82 100644 --- a/pkg/types/ccipocr3/plugin_execute_types.go +++ b/pkg/types/ccipocr3/plugin_execute_types.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + "slices" ) type ExecutePluginReport struct { @@ -34,7 +35,7 @@ func (e ExecutePluginReportSingleChain) CopyNoMsgData() ExecutePluginReportSingl SourceChainSelector: e.SourceChainSelector, Messages: msgsWithoutData, OffchainTokenData: e.OffchainTokenData, - Proofs: append([]Bytes32{}, e.Proofs...), + Proofs: slices.Clone(e.Proofs), ProofFlagBits: e.ProofFlagBits, } } diff --git a/pluginconfig/commit_test.go b/pluginconfig/commit_test.go index 5be278374f..07ad0ad840 100644 --- a/pluginconfig/commit_test.go +++ b/pluginconfig/commit_test.go @@ -561,7 +561,7 @@ func TestPreventRMNEnabledBeingChanged(t *testing.T) { typ := reflect.TypeOf(CommitOffchainConfig{}) numFields := typ.NumField() - for i := 0; i < numFields; i++ { + for i := range numFields { field := typ.Field(i) if field.Name == expectedField && field.Type.String() == expectedType && diff --git a/pluginconfig/token_test.go b/pluginconfig/token_test.go index b77a1e9ecc..94a6ef2f80 100644 --- a/pluginconfig/token_test.go +++ b/pluginconfig/token_test.go @@ -341,10 +341,10 @@ func Test_TokenDataObserver_Marshal(t *testing.T) { assert.ErrorContains(t, err, tt.errMsg) } else { assert.NoError(t, err) - var expected []map[string]interface{} + var expected []map[string]any err := json.Unmarshal([]byte(tt.wantJSON), &expected) require.NoError(t, err) - var actual []map[string]interface{} + var actual []map[string]any err = json.Unmarshal(actualJSON, &actual) require.NoError(t, err) assert.Equal(t, actual, expected)